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,916 @@
1
+ """
2
+ GUI for annotating measured features with matches from a spectral library.
3
+
4
+ Workflow:
5
+ 1. Select a measured database (FeatureManagerDB) and one or more library databases (Library).
6
+ The scatter plot (m/z vs RT) of the measurement is drawn right away, the MS2 spectra of the measurement and
7
+ the feature properties shown in the table (incl. I1 / I0 from the MS1 spectra) are loaded in the background.
8
+ 2. Set the matching parameters and click "Find Matches".
9
+ 3. Narrow down the results table with the filters (applied while typing, number fields take intervals like
10
+ 400-500; 512.3±0.01; the m/z can be set from a compound or an IPL batch of LipidCalculator), limit the rows per feature and add a dummy row per feature (only the feature
11
+ properties, also for features without matches). Clicking a
12
+ feature in the scatter plot selects its best match in the table. In the scatter plot, features with specific
13
+ MS2 fragments or neutral losses can be highlighted and pairs of features with
14
+ specific mass differences (e.g. adduct exchanges) can be connected.
15
+ 4. The overview panel shows the selected match (table row), a single feature (click in
16
+ the scatter plot or feature ID field) or two compared features (shift-click two
17
+ features or enter two IDs): MS2 spectra (peaks can be annotated by clicking them),
18
+ MS1 spectrum, intensities in the samples and the structure (see feature_overview).
19
+ 5. Collect annotations in a local list: library matches ("Add library match"),
20
+ compounds entered by hand or built with the LipidCalculator IPL builder ("Add manual
21
+ annotation") and relations to other features: in-source fragments, duplicates, isotope peaks and other
22
+ adducts ("Mark fragment / duplicate / isotope / adduct"), which can be hidden from the table.
23
+ "Manage annotations" opens a window to review new and existing annotations and to
24
+ write the changes to the measured database. "Export annotations as library" writes the annotated features to
25
+ a new database that can be loaded as library.
26
+
27
+ Each area of the window is a collapsible section in its own module (*_panel.py), AnnotationGUI holds the shared
28
+ state (databases, matches, annotations, compared features) and connects the sections.
29
+
30
+ Slow work (loading MS2 spectra, searching the library, building the overview figure) runs in worker
31
+ threads. Worker threads never touch tk widgets; they hand their results back to the
32
+ main thread with ``tk_root.after``.
33
+ """
34
+
35
+ import os
36
+ import threading
37
+ import tkinter as tk
38
+ from tkinter import filedialog, messagebox, ttk
39
+ from typing import Callable
40
+
41
+ import numpy as np
42
+ import pandas as pd
43
+
44
+ from msIO import __version__
45
+ from msIO.feature_managers.db import FeatureManagerDB, Library
46
+ from msIO.gui.annotation.annotations import AnnotationStore
47
+ from msIO.gui.annotation.common import ANNOTATION_KIND_LABELS, SQLITE_FILE_TYPES, AnnotationKey, DividedArea
48
+ from msIO.gui.annotation.database_panel import DatabasePanel
49
+ from msIO.gui.annotation.dialogs import (
50
+ AnnotationManagerWindow, FeatureRelationDialog, ManualAnnotationDialog, MzFromCompoundDialog
51
+ )
52
+ from msIO.gui.annotation.export import EXPORTED_KINDS, write_annotations_as_library
53
+ from msIO.gui.annotation.filter_panel import FilterError, FilterPanel
54
+ from msIO.gui.annotation.matching import (
55
+ MzTarget, annotation_table, build_feature_table, combine_rows, dummy_table, empty_matches_table,
56
+ limit_matches_per_feature, match_targets, matches_to_table
57
+ )
58
+ from msIO.gui.annotation.matching_panel import MatchingPanel
59
+ from msIO.gui.annotation.overview_panel import OverviewPanel
60
+ from msIO.gui.annotation.results_panel import ResultsPanel
61
+ from msIO.gui.annotation.scatter_panel import ScatterPanel
62
+ from msIO.gui.annotation.shortcuts import bind_shortcuts, show_shortcuts
63
+
64
+
65
+ class AnnotationGUI:
66
+ """
67
+ Main window for matching measured features against a library and annotating them.
68
+
69
+ Layout:
70
+ left: databases, matching parameters, filters, results table (with the annotation buttons)
71
+ right: overview above the scatter plot, separated by a movable divider
72
+ bottom: status bar
73
+ All sections can be collapsed by clicking their header.
74
+
75
+ Naming conventions:
76
+ tk_* tk widgets and tk variables
77
+ on_* callbacks of widgets and events
78
+ _*worker functions running in a worker thread
79
+ """
80
+
81
+ # height of the overview as fraction of the plot area, until the divider is moved
82
+ OVERVIEW_HEIGHT_FRACTION: float = 0.55
83
+
84
+ def __init__(self, root: tk.Misc):
85
+ """root: a window (Tk / Toplevel), which is then set up for this GUI, or a frame to embed the GUI in (e.g. a
86
+ tab of msIO.gui.main, which then has to call can_close before closing its window)."""
87
+ self.tk_root: tk.Misc = root
88
+ if isinstance(root, (tk.Tk, tk.Toplevel)):
89
+ self.tk_root.title(f"Annotation GUI (msIO {__version__})")
90
+ # 80 % of the screen, the plots need the space
91
+ width: int = int(self.tk_root.winfo_screenwidth() * 0.8)
92
+ height: int = int(self.tk_root.winfo_screenheight() * 0.8)
93
+ self.tk_root.geometry(f"{width}x{height}+10+10")
94
+ self.tk_root.protocol("WM_DELETE_WINDOW", self.on_close)
95
+ # tk variables are created with root as master: without it they belong to the first Tk instance of the process,
96
+ # which is not this window if e.g. an IPython console created one before, and the entries would stay empty
97
+
98
+ self.meas_db: FeatureManagerDB = None
99
+ # loaded libraries by file name (stored with library annotations, so it identifies the library)
100
+ self.lib_dbs: dict[str, Library] = {}
101
+ # incremented for every loaded measured database, so results of workers for an older database are dropped
102
+ self.meas_db_load_number: int = 0
103
+
104
+ # MS2 spectra and properties of the measured features (see matching.build_feature_table), loaded in a worker
105
+ self.ms2_spectra: dict = None
106
+ self.feature_table: pd.DataFrame = None
107
+ self.ms2_loading: bool = False
108
+ self.ms2_loading_error: str = None
109
+
110
+ # matching results: raw output of Library.find_matches (each match with the file name of its library under
111
+ # "library") and as table (the filtered one is in the results panel)
112
+ self.matches: dict[int, list[dict]] = {}
113
+ self.matches_table: pd.DataFrame = empty_matches_table(list(ResultsPanel.COLUMNS))
114
+ # matches with a dummy row per feature, built when needed: ((matches table, feature table), table)
115
+ # matches with dummy / annotation rows, built when needed: ((sources), table), see get_unfiltered_table
116
+ self._combined_table: tuple[tuple, pd.DataFrame] = None
117
+ # incremented on every change of the annotations, the annotation rows are rebuilt then
118
+ self.annotations_version: int = 0
119
+ # compounds of the m/z filter (e.g. an IPL batch) and the text they put into the m/z filter field, they are
120
+ # dropped when the field is changed
121
+ self.mz_targets: list[MzTarget] = []
122
+ self.mz_targets_text: str = ""
123
+
124
+ # manual annotations: changes are collected locally and only written to the measured database on request
125
+ self.annotations: AnnotationStore = AnnotationStore()
126
+ self.annotation_window: AnnotationManagerWindow = None
127
+
128
+ # (measured database, (feature ids, RTs in min, m/z)) of all measured features, see feature_positions
129
+ self._feature_positions: tuple = None
130
+
131
+ self.compared_f_ids: list[int] = [] # up to two features selected by shift-click
132
+ self.last_clicked_f_id: int = None # in the scatter plot
133
+
134
+ # position of the divider between overview and scatter plot while both are expanded
135
+ self.plot_divider_position: int = None
136
+ self.plot_sections_expanded: tuple[bool, bool] = (True, True) # (overview, scatter plot)
137
+
138
+ self._create_gui()
139
+
140
+ # ------------------------------------------------------------------------------------------------------------------
141
+ # GUI layout
142
+ # ------------------------------------------------------------------------------------------------------------------
143
+ def _create_gui(self):
144
+ # status bar is packed before the main area, so it keeps its space when the window shrinks
145
+ tk_status_bar = ttk.Frame(self.tk_root, relief="sunken")
146
+ tk_status_bar.pack(side="bottom", fill="x")
147
+ self.tk_status_field = ttk.Label(
148
+ tk_status_bar, text="Please load both databases to begin (F1: shortcuts).", anchor="w", padding=(5, 2)
149
+ )
150
+ self.tk_status_field.pack(side="left", fill="x", expand=True)
151
+ # only shown while the library is searched or indexed, see show_progress
152
+ self.tk_progress = ttk.Progressbar(tk_status_bar, mode="determinate", maximum=100, length=250)
153
+
154
+ self.tk_main_area = DividedArea(self.tk_root, orient="horizontal")
155
+ self.tk_main_area.pack(fill="both", expand=True, padx=10, pady=(10, 5))
156
+
157
+ # the results take the space left by the other sections (also when those are collapsed)
158
+ tk_results_pane = ttk.Frame(self.tk_main_area)
159
+ self.tk_main_area.add_pane(tk_results_pane)
160
+ self.database = DatabasePanel(tk_results_pane, self)
161
+ self.matching = MatchingPanel(tk_results_pane, self)
162
+ self.filters = FilterPanel(tk_results_pane, self)
163
+ self.results = ResultsPanel(tk_results_pane, self)
164
+ for section in (self.database, self.matching, self.filters):
165
+ section.pack(fill="x", pady=(0, 4))
166
+ self.results.pack(fill="both", expand=True)
167
+
168
+ self.tk_plot_area = DividedArea(self.tk_main_area, orient="vertical")
169
+ self.tk_main_area.add_pane(self.tk_plot_area)
170
+ self.overview = OverviewPanel(self.tk_plot_area, self)
171
+ self.scatter = ScatterPanel(self.tk_plot_area, self)
172
+ self.tk_plot_area.add_pane(self.overview)
173
+ self.tk_plot_area.add_pane(self.scatter)
174
+
175
+ # the panes would otherwise be sized by the requested size of their content, so place the dividers once the
176
+ # areas are shown (until then they have no size, e.g. in a hidden tab of the main window): results | plots at
177
+ # half the width, overview | scatter plot at OVERVIEW_HEIGHT_FRACTION
178
+ def set_initial_dividers():
179
+ width, height = self.tk_main_area.winfo_width(), self.tk_plot_area.winfo_height()
180
+ if width <= 1 or height <= 1:
181
+ self.tk_root.after(100, set_initial_dividers)
182
+ return
183
+ self.tk_main_area.set_divider_position(width // 2)
184
+ self.tk_plot_area.set_divider_position(int(height * self.OVERVIEW_HEIGHT_FRACTION))
185
+
186
+ self.tk_root.after(100, set_initial_dividers)
187
+ bind_shortcuts(self)
188
+ # help with the shortcuts in the top right corner, above the panes
189
+ tk_help_button = ttk.Button(self.tk_root, text="?", width=3, command=lambda: show_shortcuts(self))
190
+ tk_help_button.place(relx=1.0, x=-2, y=0, anchor="ne")
191
+
192
+ def on_toggle_plot_section(self):
193
+ """
194
+ Overview or scatter plot collapsed / expanded: a collapsed section only keeps its header, the other one gets
195
+ the space. Expanding both again restores the divider.
196
+ """
197
+ overview_expanded, scatter_expanded = self.overview.expanded, self.scatter.expanded
198
+ # the divider hasn't moved yet: if both were expanded before this toggle, remember where it was
199
+ if self.plot_sections_expanded == (True, True):
200
+ self.plot_divider_position = self.tk_plot_area.divider_position()
201
+ self.plot_sections_expanded = (overview_expanded, scatter_expanded)
202
+
203
+ # a collapsed section must not grow when the window is resized
204
+ self.tk_plot_area.set_grows(self.overview, overview_expanded)
205
+ self.tk_plot_area.set_grows(self.scatter, scatter_expanded)
206
+ self.tk_root.update_idletasks()
207
+ height: int = self.tk_plot_area.winfo_height()
208
+ if overview_expanded and scatter_expanded:
209
+ position = self.plot_divider_position or int(height * self.OVERVIEW_HEIGHT_FRACTION)
210
+ elif not overview_expanded:
211
+ position = self.overview.header_height()
212
+ else:
213
+ position = height - self.scatter.header_height()
214
+ self.tk_plot_area.set_divider_position(position)
215
+
216
+ # ------------------------------------------------------------------------------------------------------------------
217
+ # Status bar and threads
218
+ # ------------------------------------------------------------------------------------------------------------------
219
+ def set_status(self, text: str):
220
+ self.tk_status_field.config(text=text)
221
+
222
+ def call_in_main_thread(self, func: Callable[[], None]):
223
+ """Hand a function from a worker thread to the tk main loop."""
224
+ try:
225
+ self.tk_root.after(0, func)
226
+ except (tk.TclError, RuntimeError): # window was closed in the meantime
227
+ pass
228
+
229
+ def show_progress(self, text: str, indeterminate: bool = False):
230
+ """Show the progress bar in the status bar, indeterminate: moving bar for work without known progress."""
231
+ self.set_status(text)
232
+ self.tk_progress.config(value=0, mode="indeterminate" if indeterminate else "determinate")
233
+ self.tk_progress.pack(side="right", padx=5, before=self.tk_status_field)
234
+ if indeterminate:
235
+ self.tk_progress.start(20)
236
+
237
+ def update_progress(self, percent: float, text: str):
238
+ self.tk_progress.config(value=percent)
239
+ self.set_status(text)
240
+
241
+ def hide_progress(self):
242
+ self.tk_progress.stop()
243
+ self.tk_progress.pack_forget()
244
+
245
+ # ------------------------------------------------------------------------------------------------------------------
246
+ # Loading databases and closing
247
+ # ------------------------------------------------------------------------------------------------------------------
248
+ def on_browse_meas_db(self):
249
+ """Connect to a measured database, reset all results and start loading its MS2 spectra."""
250
+ if not self._confirm_discarding_unsaved_annotations():
251
+ return
252
+ path: str = filedialog.askopenfilename(filetypes=SQLITE_FILE_TYPES)
253
+ if not path:
254
+ return
255
+ try:
256
+ self.meas_db = FeatureManagerDB(path)
257
+ except Exception as error:
258
+ self.meas_db = None
259
+ messagebox.showerror("Error", f"Failed to load measured database:\n{error}")
260
+ return
261
+ self.database.tk_meas_path.set(path)
262
+ self.meas_db_load_number += 1
263
+
264
+ # clear data belonging to the previous database
265
+ self.ms2_spectra = None
266
+ self.feature_table = None
267
+ self.ms2_loading_error = None
268
+ self.ms2_loading = True
269
+ self.matches = {}
270
+ self.matches_table = empty_matches_table(self.results.columns)
271
+ self.results.clear()
272
+ self.annotations.reset(self.meas_db)
273
+ self.compared_f_ids = []
274
+ self.last_clicked_f_id = None
275
+ self.overview.clear()
276
+ self.overview.peak_annotations = {}
277
+ self.scatter.reset()
278
+ self._on_annotations_changed()
279
+
280
+ self.set_status(f"Measured database loaded, loading spectra ...: {path}")
281
+ threading.Thread(
282
+ target=self._ms2_spectra_worker,
283
+ args=(self.meas_db, self.meas_db_load_number),
284
+ daemon=True
285
+ ).start()
286
+
287
+ def _ms2_spectra_worker(self, meas_db: FeatureManagerDB, load_number: int):
288
+ """Worker thread: load all MS2 spectra of the measurement and the properties of the features."""
289
+ spectra, feature_table, errors = None, None, []
290
+ try:
291
+ spectra = meas_db.get_ms_spectra(meas_db.feature_ids, level=2)
292
+ except Exception as error:
293
+ errors.append(f"MS2 spectra: {error}")
294
+ try:
295
+ # the MS1 spectra are only needed for I1 / I0
296
+ feature_table = build_feature_table(meas_db, meas_db.get_ms_spectra(meas_db.feature_ids, level=1))
297
+ except Exception as error:
298
+ errors.append(f"feature properties: {type(error).__name__}: {error}")
299
+ error_text: str | None = "\n".join(errors) or None
300
+ self.call_in_main_thread(lambda: self._finish_ms2_loading(load_number, spectra, feature_table, error_text))
301
+
302
+ def _finish_ms2_loading(self, load_number: int, spectra: dict | None, feature_table: pd.DataFrame | None,
303
+ error_text: str | None):
304
+ """Main thread: store the loaded data, unless another database was loaded in the meantime."""
305
+ if load_number != self.meas_db_load_number:
306
+ return
307
+ self.ms2_loading = False
308
+ self.ms2_spectra = spectra
309
+ self.feature_table = feature_table
310
+ self.ms2_loading_error = None if spectra is not None else error_text
311
+
312
+ if error_text is not None:
313
+ self.set_status("Measured database loaded, but not all data could be loaded.")
314
+ messagebox.showerror("Loading error", f"Could not load:\n{error_text}")
315
+ else:
316
+ self.set_status("Measured database, spectra and feature properties loaded.")
317
+ if self.filters.tk_add_dummies.get():
318
+ self.apply_filters(show_empty_message=False)
319
+
320
+ def on_browse_lib_db(self):
321
+ """Replace the libraries by the selected ones."""
322
+ if paths := filedialog.askopenfilenames(filetypes=SQLITE_FILE_TYPES):
323
+ self.load_libraries(list(paths))
324
+
325
+ def on_add_lib_db(self):
326
+ """Add the selected libraries to the loaded ones."""
327
+ if paths := filedialog.askopenfilenames(filetypes=SQLITE_FILE_TYPES):
328
+ self.load_libraries([lib_db.path_file for lib_db in self.lib_dbs.values()] + list(paths))
329
+
330
+ def load_libraries(self, paths: list[str]):
331
+ """
332
+ Use the libraries at paths (libraries that are already loaded are kept). Library annotations are identified by
333
+ the file name of the library, so two libraries can't have the same file name.
334
+ """
335
+ loaded: dict[str, Library] = {os.path.normcase(os.path.abspath(lib_db.path_file)): lib_db
336
+ for lib_db in self.lib_dbs.values()}
337
+ lib_dbs: dict[str, Library] = {}
338
+ for path in dict.fromkeys(paths): # without duplicates, in order
339
+ name: str = os.path.basename(path)
340
+ if name in lib_dbs:
341
+ messagebox.showerror("Error", f"Two libraries are called {name}, please rename one of them.")
342
+ return
343
+ try:
344
+ lib_dbs[name] = loaded.get(os.path.normcase(os.path.abspath(path))) or Library(path)
345
+ except Exception as error:
346
+ messagebox.showerror("Error", f"Failed to load library database {path}:\n{error}")
347
+ return
348
+ changed: bool = list(lib_dbs.values()) != list(self.lib_dbs.values())
349
+ new: list[Library] = [lib_db for lib_db in lib_dbs.values() if lib_db not in self.lib_dbs.values()]
350
+ self.lib_dbs = lib_dbs
351
+ self.database.set_lib_paths([lib_db.path_file for lib_db in lib_dbs.values()])
352
+ if not changed:
353
+ return
354
+ self.set_status(f"{len(lib_dbs)} library database(s) loaded: {', '.join(lib_dbs)}")
355
+ self._clear_results_of_previous_library()
356
+ self._offer_missing_indexes(new)
357
+
358
+ def get_match_result(self, f_id_meas: int, library_name: str, f_id_lib: int) -> dict:
359
+ """Match of a measured feature with a library feature, as returned by Library.find_matches."""
360
+ return next(match for match in self.matches[f_id_meas]
361
+ if match['library'] == library_name and match['feature_id'] == f_id_lib)
362
+
363
+ def _clear_results_of_previous_library(self):
364
+ """Matches refer to the previous libraries, which may not be loaded anymore: search again."""
365
+ if self.meas_db is None:
366
+ return
367
+ self.matches = {}
368
+ self.matches_table = empty_matches_table(self.results.columns)
369
+ self.apply_filters(show_empty_message=False) # dummy rows stay
370
+ if self.overview.shown_key is not None and self.overview.shown_key[0] == "match":
371
+ self.overview.clear() # also drops a match overview that is still being built
372
+
373
+ def _offer_missing_indexes(self, dbs: list[FeatureManagerDB]):
374
+ """
375
+ Databases created before the indexes were added to the models load spectra much slower (full-scale library:
376
+ search 66 s instead of 14 s). Creating them changes the files, so ask first.
377
+ """
378
+ without_index: list[FeatureManagerDB] = []
379
+ for db in dbs:
380
+ try:
381
+ if db.get_missing_indexes():
382
+ without_index.append(db)
383
+ except Exception: # e.g. not an msIO database, the search will report it
384
+ pass
385
+ if not without_index:
386
+ return
387
+ sizes: str = ", ".join(f"{os.path.basename(db.path_file)} {os.path.getsize(db.path_file) / 1e9:.1f} GB"
388
+ for db in without_index)
389
+ if not messagebox.askyesno(
390
+ "Speed up the library",
391
+ f"{len(without_index)} library database(s) have no index for loading spectra, which makes the search "
392
+ f"several times slower.\n\n"
393
+ f"Add the index now? This is done once and changes the file: it takes a while for large libraries "
394
+ f"(about 20 s per 5 GB) and makes the file about 20 % larger (currently {sizes})."
395
+ ):
396
+ return
397
+ self.matching.set_searching(True)
398
+ self.show_progress("Creating the index of the library ...", indeterminate=True)
399
+
400
+ def worker():
401
+ try:
402
+ for db in without_index:
403
+ db.create_missing_indexes()
404
+ error_text = None
405
+ except Exception as error:
406
+ error_text = f"{type(error).__name__}: {error}"
407
+ self.call_in_main_thread(lambda: finish(error_text))
408
+
409
+ def finish(error_text: str | None):
410
+ self.matching.set_searching(False)
411
+ self.hide_progress()
412
+ if error_text is not None:
413
+ messagebox.showerror("Index", f"Could not create the index:\n{error_text}")
414
+ self.set_status("Library loaded without index.")
415
+ else:
416
+ self.set_status("Index of the library created.")
417
+
418
+ threading.Thread(target=worker, daemon=True).start()
419
+
420
+ def can_close(self) -> bool:
421
+ """Warn about annotation changes that were not written to the database, True if the window may be closed."""
422
+ return self._confirm_discarding_unsaved_annotations()
423
+
424
+ def on_close(self):
425
+ """Closing the main window: warn about annotation changes that were not written to the database."""
426
+ if self.can_close():
427
+ self.tk_root.winfo_toplevel().destroy()
428
+
429
+ # ------------------------------------------------------------------------------------------------------------------
430
+ # Matching
431
+ # ------------------------------------------------------------------------------------------------------------------
432
+ def on_click_find_matches(self):
433
+ """
434
+ Validate the matching parameters and search the library for all measured features in a worker thread
435
+ (progress in the status bar), the table is filled when the search is done.
436
+ """
437
+ if self.meas_db is None or not self.lib_dbs:
438
+ messagebox.showerror("Error", "Please select a measured database and at least one library.")
439
+ return
440
+ try:
441
+ parameters: dict = self.matching.get_search_parameters()
442
+ except ValueError as error:
443
+ messagebox.showerror("Invalid input", str(error))
444
+ return
445
+ # without spectra, all MS2 scores would be missing
446
+ if self.ms2_loading:
447
+ messagebox.showinfo("MS2 spectra", "MS2 spectra are still loading. Try again shortly.")
448
+ return
449
+ if self.feature_table is None:
450
+ messagebox.showerror("Error", "The properties of the measured features could not be loaded.")
451
+ return
452
+ if parameters['require_ms2'] and (self.ms2_loading_error or self.ms2_spectra is None):
453
+ messagebox.showerror("MS2 spectra", "MS2 spectra could not be loaded.")
454
+ return
455
+
456
+ self.matching.set_searching(True)
457
+ self.show_progress("Searching the library ...")
458
+ search_kwargs: dict = dict(
459
+ mzs=self.meas_db.mzs,
460
+ return_nhits_ms2=True,
461
+ # empty dict: scores are missing, but find_matches still returns the matches as dicts
462
+ ms2_spectra=self.ms2_spectra or {},
463
+ **parameters,
464
+ )
465
+ threading.Thread(
466
+ target=self._find_matches_worker,
467
+ args=(self.feature_table, dict(self.lib_dbs), search_kwargs, self.meas_db_load_number),
468
+ daemon=True
469
+ ).start()
470
+
471
+ def _find_matches_worker(self, feature_table: pd.DataFrame, lib_dbs: dict[str, Library], search_kwargs: dict,
472
+ load_number: int):
473
+ """Worker thread: search the libraries one after another and build the results table."""
474
+ last_percent: list[int] = [-1]
475
+
476
+ def report_progress(idx_library: int, n_done: int, n_total: int):
477
+ # only hand over changes of whole percents, the main thread doesn't need every feature
478
+ percent = int((idx_library + n_done / max(n_total, 1)) / len(lib_dbs) * 100)
479
+ if percent != last_percent[0]:
480
+ last_percent[0] = percent
481
+ text = f"Scoring MS2 matches (library {idx_library + 1} of {len(lib_dbs)}) ... {percent} %"
482
+ self.call_in_main_thread(lambda: self.update_progress(percent, text))
483
+
484
+ matches, table, error_text = None, None, None
485
+ try:
486
+ matches = {}
487
+ for idx_library, (library_name, lib_db) in enumerate(lib_dbs.items()):
488
+ found = lib_db.find_matches(**search_kwargs, progress_callback=lambda n_done, n_total, i=idx_library:
489
+ report_progress(i, n_done, n_total))
490
+ for f_id_meas, matches_of_feature in found.items():
491
+ for match in matches_of_feature:
492
+ match['library'] = library_name
493
+ matches.setdefault(f_id_meas, []).extend(matches_of_feature)
494
+ self.call_in_main_thread(lambda: self.update_progress(100, "Building the results table ..."))
495
+ table = matches_to_table(matches, feature_table, lib_dbs, search_kwargs['max_dmz_ppm'],
496
+ search_kwargs['max_dmz_da'], list(ResultsPanel.COLUMNS))
497
+ except Exception as error:
498
+ error_text = f"{type(error).__name__}: {error}"
499
+ self.call_in_main_thread(lambda: self._finish_find_matches(load_number, lib_dbs, matches, table, error_text))
500
+
501
+ def _finish_find_matches(self, load_number: int, lib_dbs: dict[str, Library], matches: dict | None,
502
+ table: pd.DataFrame | None, error_text: str | None):
503
+ """Main thread: show the results, unless another database was loaded during the search."""
504
+ self.matching.set_searching(False)
505
+ self.hide_progress()
506
+ if load_number != self.meas_db_load_number or lib_dbs != self.lib_dbs:
507
+ self.set_status("Search results dropped, a different database was loaded meanwhile.")
508
+ return
509
+ if error_text is not None:
510
+ messagebox.showerror("Error", f"Search failed:\n{error_text}")
511
+ self.set_status("Failed while looking for matches.")
512
+ return
513
+
514
+ self.matches, self.matches_table = matches, table
515
+ self.overview.shown_key = None # scores may have changed, selecting the match again replots it
516
+ self.apply_filters(show_empty_message=False)
517
+ count: int = len(self.matches_table)
518
+ self.set_status(f"Found {count} matches in {len(lib_dbs)} librar{'y' if len(lib_dbs) == 1 else 'ies'}.")
519
+ if count == 0:
520
+ messagebox.showinfo("Search complete", "No matches found.")
521
+
522
+ # ------------------------------------------------------------------------------------------------------------------
523
+ # Filters
524
+ # ------------------------------------------------------------------------------------------------------------------
525
+ def get_unfiltered_table(self) -> pd.DataFrame:
526
+ """
527
+ All rows of the results table: the matches and, if selected, a dummy row per measured feature and a row per
528
+ annotation of the measured database (stored or to add).
529
+ """
530
+ add_dummies: bool = self.filters.tk_add_dummies.get() and self.feature_table is not None
531
+ add_annotations: bool = self.filters.tk_add_annotations.get() and self.feature_table is not None
532
+ if not (add_dummies or add_annotations):
533
+ return self.matches_table
534
+ sources: tuple = (self.matches_table, self.feature_table, add_dummies,
535
+ self.annotations_version if add_annotations else None)
536
+ # the tables are compared by identity (a new search / database gives new ones), the flags by value
537
+ if self._combined_table is None or any(
538
+ (cached is not current) if isinstance(current, pd.DataFrame) else cached != current
539
+ for cached, current in zip(self._combined_table[0], sources)):
540
+ columns: list[str] = list(ResultsPanel.COLUMNS)
541
+ extra: list[pd.DataFrame] = []
542
+ if add_dummies:
543
+ extra.append(dummy_table(self.feature_table, columns))
544
+ if add_annotations:
545
+ extra.append(annotation_table(self.feature_table, self.annotations.kept(), columns,
546
+ ANNOTATION_KIND_LABELS))
547
+ self._combined_table = (sources, combine_rows(self.matches_table, *extra))
548
+ return self._combined_table[1]
549
+
550
+ def apply_filters(self, show_empty_message: bool = True, show_dialogs: bool = True):
551
+ """
552
+ Filter the results (matches and dummy rows) by all filter fields, limit the rows per feature and show the
553
+ result in the table.
554
+
555
+ Invalid filter values leave the table unchanged. They are reported in a dialog,
556
+ or in the status bar if show_dialogs is False (used while typing).
557
+ """
558
+ table: pd.DataFrame = self.get_unfiltered_table()
559
+ if table.empty:
560
+ self._show_filtered_matches(table.copy())
561
+ return
562
+ try:
563
+ mask = self.filters.compute_mask(table)
564
+ max_rows: int | None = self.filters.get_max_rows()
565
+ except FilterError as error:
566
+ # while typing, half-entered values are expected, so don't open a dialog for every key stroke
567
+ if show_dialogs:
568
+ messagebox.showerror(error.title, error.text)
569
+ else:
570
+ self.set_status(f"Filters not updated: {error.text}")
571
+ return
572
+
573
+ filtered: pd.DataFrame = table.loc[mask, :]
574
+ if max_rows is not None:
575
+ filtered = limit_matches_per_feature(filtered, max_rows)
576
+ if self.mz_targets and self.filters.tk_mz.get().strip() != self.mz_targets_text:
577
+ self.mz_targets, self.mz_targets_text = [], ""
578
+ if self.mz_targets:
579
+ filtered = filtered.assign(target=["; ".join(target.label for target in targets)
580
+ for targets in self.get_row_targets(filtered.mz_meas)])
581
+ self._show_filtered_matches(filtered)
582
+ n_shown: int = len(self.results.table)
583
+ if show_empty_message and n_shown == 0:
584
+ self.set_status("No rows meet the current filters.")
585
+ elif n_shown:
586
+ self.set_status(f"Showing {n_shown} of {len(table)} rows.")
587
+
588
+ def _show_filtered_matches(self, table: pd.DataFrame):
589
+ self.results.set_table(table)
590
+ self.scatter.mark_filtered_features()
591
+
592
+ def get_filtered_feature_ids(self) -> list[int]:
593
+ """Measured features of the shown rows, empty if the filters don't remove any row."""
594
+ if 0 < len(self.results.table) < len(self.get_unfiltered_table()):
595
+ return [int(f_id) for f_id in self.results.table.feature_id_meas.unique()]
596
+ return []
597
+
598
+ def get_row_targets(self, mzs) -> list[list[MzTarget]]:
599
+ """Targets of the m/z filter at each m/z (precursor tolerance), closest first."""
600
+ try:
601
+ max_dmz_ppm, max_dmz_da = self.matching.precursor_tolerances()
602
+ except tk.TclError:
603
+ return [[] for _ in mzs]
604
+ return match_targets(pd.to_numeric(pd.Series(mzs), errors='coerce').to_numpy(dtype=float), self.mz_targets,
605
+ max_dmz_ppm, max_dmz_da)
606
+
607
+ def set_mz_targets(self, targets: list[MzTarget]):
608
+ """
609
+ Filter the results to the m/z of the targets (each ± precursor tolerance, e.g. an IPL batch), show the dummy
610
+ rows (features without library matches) and name the fitting targets in the table.
611
+ """
612
+ try:
613
+ mzs = sorted({round(target.mz, 4) for target in targets})
614
+ text: str = "; ".join(f"{mz:.4f}±{self.matching.precursor_tolerance_da(mz):.4f}" for mz in mzs)
615
+ except tk.TclError:
616
+ messagebox.showerror("Invalid input", "Check the precursor tolerances.")
617
+ return
618
+ self.mz_targets, self.mz_targets_text = list(targets), text
619
+ self.filters.set_mz_text(text)
620
+ self.filters.tk_add_dummies.set(True)
621
+ self.apply_filters(show_empty_message=False)
622
+ n_features: int = len(set(self.results.table.feature_id_meas))
623
+ self.set_status(f"m/z filter of {len(targets)} targets ({len(mzs)} m/z values): {n_features} features "
624
+ f"(dummy rows show the features without library matches, see column Target).")
625
+
626
+ def set_mz_filter(self, mz: float):
627
+ """Filter the results to measured features at mz (± precursor tolerance)."""
628
+ try:
629
+ tolerance: float = self.matching.precursor_tolerance_da(mz)
630
+ except tk.TclError:
631
+ messagebox.showerror("Invalid input", "Check the precursor tolerances.")
632
+ return
633
+ self.filters.set_mz_text(f"{mz:.4f}±{tolerance:.4f}")
634
+ self.apply_filters()
635
+
636
+ def on_click_mz_from_compound(self):
637
+ if not self.require_meas_db():
638
+ return
639
+ MzFromCompoundDialog(self)
640
+
641
+ def on_click_remove_filters(self):
642
+ """Empty all filter fields and show all rows."""
643
+ self.filters.clear()
644
+ self.apply_filters(show_empty_message=False)
645
+ self.set_status(f"Showing all {len(self.results.table)} rows.")
646
+
647
+ # ------------------------------------------------------------------------------------------------------------------
648
+ # Manual annotations
649
+ # ------------------------------------------------------------------------------------------------------------------
650
+ def _confirm_discarding_unsaved_annotations(self) -> bool:
651
+ to_add, to_remove = self.annotations.unsaved_changes()
652
+ if not (to_add or to_remove):
653
+ return True
654
+ return messagebox.askyesno(
655
+ "Unsaved annotations",
656
+ f"{len(to_add)} annotation(s) to add and {len(to_remove)} to remove have not been written to the "
657
+ f"database. Discard these changes?"
658
+ )
659
+
660
+ def add_pending_annotation(self, key: AnnotationKey, info: dict) -> bool:
661
+ """
662
+ Add an annotation to the local list (not yet written to the database).
663
+
664
+ Returns False if the annotation is already in the database (it is kept, if it was marked for removal).
665
+ """
666
+ added: bool = self.annotations.add(key, info)
667
+ self._on_annotations_changed()
668
+ return added
669
+
670
+ def _get_current_feature(self) -> int | None:
671
+ """Feature to prefill annotation dialogs: selected in the table, else last clicked in the scatter plot."""
672
+ if (match := self.results.selected_match()) is not None:
673
+ return int(match.feature_id_meas)
674
+ if self.last_clicked_f_id is not None:
675
+ return self.last_clicked_f_id
676
+ return self.compared_f_ids[-1] if self.compared_f_ids else None
677
+
678
+ def on_click_add_library_match(self):
679
+ """Add the selected library match to the local list of annotations."""
680
+ if (match := self.results.selected_match()) is None or match.is_dummy or match.is_annotation:
681
+ messagebox.showerror("Error", "Please select a row with a library match first (not a dummy or "
682
+ "annotation row).")
683
+ return
684
+ f_id_meas, f_id_lib, library_name = int(match.feature_id_meas), int(match.feature_id_lib), match.library
685
+ match_result: dict = self.get_match_result(f_id_meas, library_name, f_id_lib)
686
+ key: AnnotationKey = AnnotationStore.library_key(f_id_meas, library_name, f_id_lib)
687
+ added: bool = self.add_pending_annotation(key, dict(
688
+ kind="library",
689
+ name=match_result.get('name'),
690
+ formula=match_result.get('formula'),
691
+ adduct=match_result.get('adduct'),
692
+ ms2_score=match_result.get('ms2_score'),
693
+ reference=f_id_lib,
694
+ library_name=library_name,
695
+ library=self.lib_dbs[library_name],
696
+ ))
697
+ if added:
698
+ self.set_status(f"Added library feature {f_id_lib} ({library_name}) for feature {f_id_meas} to the "
699
+ f"annotations. Use \"Manage annotations\" to write them to the database.")
700
+ else:
701
+ self.set_status(f"Library feature {f_id_lib} ({library_name}) is already annotated for feature "
702
+ f"{f_id_meas}.")
703
+
704
+ def on_click_add_manual_annotation(self):
705
+ if not self.require_meas_db():
706
+ return
707
+ # a target of the m/z filter at the selected row is the suggested compound
708
+ compound: MzTarget | None = None
709
+ if self.mz_targets and (match := self.results.selected_match()) is not None:
710
+ compound = next(iter(self.get_row_targets([match.mz_meas])[0]), None)
711
+ ManualAnnotationDialog(self, self._get_current_feature(), compound=compound)
712
+
713
+ def on_click_mark_relation(self, kind: str = "in_source_fragment"):
714
+ """
715
+ Open the dialog to mark a feature as in-source fragment, duplicate, isotope peak or adduct of another one,
716
+ prefilled with the compared features (the dialog orders them by m/z for fragments and isotope peaks).
717
+ """
718
+ if not self.require_meas_db():
719
+ return
720
+ if len(self.compared_f_ids) == 2:
721
+ f_id, f_id_reference = sorted(self.compared_f_ids, key=lambda f_id_: self.meas_db.mzs[f_id_])
722
+ else:
723
+ f_id, f_id_reference = self._get_current_feature(), None
724
+ return FeatureRelationDialog(self, f_id, f_id_reference, kind=kind)
725
+
726
+ def toggle_annotations(self, keys: list[AnnotationKey], keep: bool = None):
727
+ """Mark annotations to keep or discard (keep=None toggles each of them)."""
728
+ self.annotations.toggle(keys, keep)
729
+ self._on_annotations_changed()
730
+
731
+ def write_annotations_to_db(self, parent: tk.Misc = None):
732
+ """Add the new and remove the discarded annotations in the measured database (after confirmation)."""
733
+ to_add, to_remove = self.annotations.unsaved_changes()
734
+ if not (to_add or to_remove):
735
+ messagebox.showinfo("Annotations", "There are no changes to write.", parent=parent)
736
+ return
737
+ if not messagebox.askyesno(
738
+ "Write annotations",
739
+ f"Add {len(to_add)} and remove {len(to_remove)} annotation(s) in the measured database?",
740
+ parent=parent
741
+ ):
742
+ return
743
+
744
+ n_added, n_removed, errors = self.annotations.write(self.meas_db)
745
+ self._on_annotations_changed()
746
+ if self.scatter.tk_show_annotations.get():
747
+ self.scatter.redraw()
748
+ if errors:
749
+ messagebox.showerror("Annotation Error", "\n".join(errors), parent=parent)
750
+ self.set_status(f"Wrote annotations to the database: {n_added} added, {n_removed} removed.")
751
+
752
+ def _on_annotations_changed(self):
753
+ """Update everything that shows annotation states: table column, button text, manager window, scatter plot."""
754
+ self.annotations_version += 1
755
+ # the hidden features or the annotation rows changed
756
+ if self.filters.tk_hide_related.get() or self.filters.tk_add_annotations.get():
757
+ self.apply_filters(show_empty_message=False, show_dialogs=False)
758
+ self.results.refresh_annotation_column()
759
+ self.results.set_unsaved_annotation_count(sum(len(keys) for keys in self.annotations.unsaved_changes()))
760
+ if self.annotation_window is not None:
761
+ self.annotation_window.refresh()
762
+ self.scatter.mark_annotated_features()
763
+
764
+ def on_click_export_library(self):
765
+ """
766
+ Write the annotated features (library matches and manual annotations as listed in "Manage annotations", incl.
767
+ the unsaved changes) to a new database that can be loaded as library.
768
+ """
769
+ if not self.require_meas_db():
770
+ return
771
+ annotations: dict[AnnotationKey, dict] = self.annotations.kept()
772
+ if not (n_entries := sum(key[0] in EXPORTED_KINDS for key in annotations)):
773
+ messagebox.showinfo("Export", "There are no library matches or manual annotations to export.")
774
+ return
775
+ stem: str = os.path.splitext(os.path.basename(self.meas_db.path_file))[0]
776
+ path: str = filedialog.asksaveasfilename(
777
+ title="Export annotations as library", defaultextension=".sqlite", filetypes=SQLITE_FILE_TYPES,
778
+ initialfile=f"{stem}_annotations.sqlite"
779
+ )
780
+ if not path:
781
+ return
782
+ # the file is replaced, so it must not be one of the open databases
783
+ open_paths = {os.path.normcase(os.path.abspath(db.path_file)) for db in [self.meas_db, *self.lib_dbs.values()]}
784
+ if os.path.normcase(os.path.abspath(path)) in open_paths:
785
+ messagebox.showerror("Export", "Please choose a new file, this database is in use.")
786
+ return
787
+ source_name: str = os.path.splitext(os.path.basename(path))[0]
788
+ self.set_status(f"Exporting {n_entries} annotation(s) ...")
789
+ self.tk_root.update_idletasks()
790
+ try:
791
+ n_written: int = write_annotations_as_library(path, self.meas_db, annotations, self.lib_dbs, source_name)
792
+ except Exception as error:
793
+ messagebox.showerror("Export", f"Could not export the annotations:\n{type(error).__name__}: {error}")
794
+ self.set_status("Export failed.")
795
+ return
796
+ n_skipped: int = len(annotations) - n_written
797
+ self.set_status(f"Exported {n_written} annotation(s) as library to {path}"
798
+ + (f" ({n_skipped} in-source fragment annotation(s) left out)." if n_skipped else "."))
799
+
800
+ def on_click_manage_annotations(self):
801
+ if not self.require_meas_db():
802
+ return
803
+ if self.annotation_window is None:
804
+ self.annotation_window = AnnotationManagerWindow(self)
805
+ else:
806
+ self.annotation_window.lift()
807
+
808
+ # ------------------------------------------------------------------------------------------------------------------
809
+ # Selected and compared features
810
+ # ------------------------------------------------------------------------------------------------------------------
811
+ def get_rt_mz(self, f_id: int) -> tuple[float, float] | None:
812
+ """RT in minutes (as in FeatureManagerDB.plot_scatter) and m/z of a measured feature."""
813
+ rt = self.meas_db.retention_times_in_seconds.get(f_id)
814
+ mz = self.meas_db.mzs.get(f_id)
815
+ if rt is None or mz is None:
816
+ return None
817
+ return rt / 60, mz
818
+
819
+ def feature_positions(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
820
+ """(feature ids, RTs in min, m/z) of the measured features with both, cached for the measured database."""
821
+ if self._feature_positions is None or self._feature_positions[0] is not self.meas_db:
822
+ points = {f_id: p for f_id in self.meas_db.feature_ids if (p := self.get_rt_mz(f_id)) is not None}
823
+ f_ids = np.array(list(points), dtype=int)
824
+ rts, mzs = np.array(list(points.values()), dtype=float).reshape(-1, 2).T
825
+ self._feature_positions = (self.meas_db, (f_ids, rts, mzs))
826
+ return self._feature_positions[1]
827
+
828
+ def require_meas_db(self) -> bool:
829
+ """True if a measured database is loaded, otherwise ask to load one."""
830
+ if self.meas_db is None:
831
+ messagebox.showerror("Error", "Please load a measured database first.")
832
+ return False
833
+ return True
834
+
835
+ def on_match_selected(self, match: pd.Series, by_program: bool = False):
836
+ """
837
+ Row of the results table selected: mark its feature in the scatter plot (panned to it if it is outside the
838
+ view) and show the match (or feature).
839
+ """
840
+ if by_program: # selected by the program (scatter click, restored selection): keep the overview and the view
841
+ self.scatter.mark_selected_feature(int(match.feature_id_meas))
842
+ return
843
+ self.scatter.mark_selected_feature(int(match.feature_id_meas), show=True)
844
+ # e.g. selected again after sorting or filtering
845
+ if self._overview_key_of_row(match) != self.overview.shown_key:
846
+ self.clear_comparison()
847
+ self._show_row(match)
848
+
849
+ @staticmethod
850
+ def _overview_key_of_row(match: pd.Series) -> tuple:
851
+ """
852
+ Overview of a row of the results table (see OverviewPanel.shown_key): the match, the feature for dummy and
853
+ annotation rows.
854
+ """
855
+ if match.is_dummy or match.is_annotation:
856
+ return "feature", (int(match.feature_id_meas),), None
857
+ return "match", (int(match.feature_id_meas),), (match.library, int(match.feature_id_lib))
858
+
859
+ def _show_row(self, match: pd.Series):
860
+ mode, f_ids, lib_ref = self._overview_key_of_row(match)
861
+ self.overview.request(mode, list(f_ids), lib_ref)
862
+
863
+ def on_scatter_click(self, f_id: int, shift: bool = False):
864
+ """
865
+ Click: select the best match of the feature in the results table and show it, features without
866
+ matches (in the filtered table) are shown alone.
867
+ Shift-click: add the feature to the comparison (the oldest of two is replaced).
868
+ """
869
+ self.last_clicked_f_id = f_id
870
+ if shift:
871
+ self.add_feature_to_comparison(f_id)
872
+ return
873
+ self.clear_comparison()
874
+ # the overview is requested here, the selection event isn't generated if the row was already selected
875
+ if self.results.select_best_match(f_id, show_match=False):
876
+ self.scatter.mark_selected_feature(f_id)
877
+ self._show_row(self.results.selected_match())
878
+ else:
879
+ # the table has no row of the feature, the selected row would belong to another one
880
+ self.results.clear_selection()
881
+ self.show_feature(f_id)
882
+
883
+ def show_feature(self, f_id: int):
884
+ """Overview of a single measured feature (with or without matches)."""
885
+ self.scatter.mark_selected_feature(f_id)
886
+ self.overview.request("feature", [f_id])
887
+
888
+ def show_feature_ids(self, f_ids: list[int]):
889
+ """Feature ID field of the overview: one feature is selected (as by a click in the plot), two are compared."""
890
+ if len(f_ids) == 1:
891
+ # like a click on the feature in the plot, which is panned to it
892
+ self.on_scatter_click(f_ids[0])
893
+ if (point := self.get_rt_mz(f_ids[0])) is not None:
894
+ self.scatter.show_point(*point)
895
+ else:
896
+ self.compared_f_ids = list(f_ids)
897
+ self.scatter.mark_compared_features()
898
+ self.overview.request("comparison", list(f_ids))
899
+
900
+ def clear_comparison(self):
901
+ """The overview shows something else than the shift-clicked features: remove them and their squares."""
902
+ if self.compared_f_ids:
903
+ self.compared_f_ids = []
904
+ self.scatter.mark_compared_features()
905
+
906
+ def add_feature_to_comparison(self, f_id: int):
907
+ """Add a feature to the comparison: the first one is shown alone, two are compared."""
908
+ if f_id in self.compared_f_ids:
909
+ self.set_status(f"Feature {f_id} is already compared.")
910
+ return
911
+ self.compared_f_ids = (self.compared_f_ids + [f_id])[-2:]
912
+ self.scatter.mark_compared_features()
913
+ if len(self.compared_f_ids) < 2:
914
+ self.overview.request("feature", [f_id])
915
+ else:
916
+ self.overview.request("comparison", list(self.compared_f_ids))