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,694 @@
1
+ """Constants, parsing of user input and small widgets shared by the parts of the annotation GUI."""
2
+
3
+ import re
4
+ import tkinter as tk
5
+ from tkinter import messagebox, ttk
6
+ from typing import Callable
7
+
8
+ import numpy as np
9
+ from LipidCalculator import Adduct, CompoundDict
10
+ from LipidCalculator.compound_creation.formula_parser import parse_equation
11
+ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
12
+
13
+ try:
14
+ from LipidCalculator.gui.common import ADDUCTS
15
+ except ImportError: # LipidCalculator without GUI
16
+ ADDUCTS: list[str] = ['[M+H]+', '[M+NH4]+', '[M+Na]+', '[M+K]+', '[M-H]-', '[M+Cl]-', '[M+HCOO]-']
17
+
18
+ SQLITE_FILE_TYPES: list[tuple[str, str]] = [("SQLite Files", "*.sqlite *.db *.sql"), ("All files", "*.*")]
19
+
20
+ # (kind, measured feature id, reference) identifies a manual annotation, kind is one of the
21
+ # ManualAnnotationKind of FeatureManagerDB, the reference is the library feature id ("library"),
22
+ # the reference feature id (relations to another feature, see FEATURE_RELATIONS) or "name|adduct" ("manual")
23
+ AnnotationKey = tuple[str, int, str]
24
+ # relations between measured features: kind -> (label, role of the feature, role of the reference feature)
25
+ FEATURE_RELATIONS: dict[str, tuple[str, str, str]] = {
26
+ "in_source_fragment": ("in-source fragment", "Fragment", "Parent"),
27
+ "duplicate": ("duplicate", "Duplicate", "Original"),
28
+ "isotope": ("isotope peak", "Isotope peak", "Monoisotopic peak"),
29
+ "adduct": ("adduct", "Adduct", "Main adduct"),
30
+ }
31
+ FEATURE_RELATION_KINDS: tuple[str, ...] = tuple(FEATURE_RELATIONS)
32
+ ANNOTATION_KIND_LABELS: dict[str, str] = {
33
+ "library": "library match", "manual": "manual", **{kind: label for kind, (label, _, _) in FEATURE_RELATIONS.items()}
34
+ }
35
+
36
+ # colors of the two features compared by shift-click, used in the scatter plot and the overview
37
+ COMPARISON_COLORS: tuple[str, str] = ("C2", "C1")
38
+
39
+
40
+ def parse_masses(text: str) -> list[tuple[str, float]]:
41
+ """
42
+ Parse ";"-separated m/z values or formulas into (entry, mass) pairs.
43
+
44
+ Formulas are converted with LipidCalculator, a trailing "+" or "-" gives the mass of the ion
45
+ (e.g. "C5H15NO4P+" for the phosphocholine fragment).
46
+
47
+ Raises:
48
+ ValueError: if an entry is neither a number nor a valid formula, or its mass is not positive.
49
+ """
50
+ masses: list[tuple[str, float]] = []
51
+ for entry in text.split(';'):
52
+ if not (entry := entry.strip()):
53
+ continue
54
+ try:
55
+ mass = float(entry)
56
+ except ValueError:
57
+ try:
58
+ mass = CompoundDict(entry).mass
59
+ except Exception:
60
+ raise ValueError(f'"{entry}" is neither a number nor a valid formula.')
61
+ if mass <= 0:
62
+ raise ValueError(f'"{entry}" does not have a positive mass.')
63
+ masses.append((entry, mass))
64
+ return masses
65
+
66
+
67
+ def parse_mass_differences(text: str) -> list[tuple[str, Callable[[np.ndarray], np.ndarray]]]:
68
+ """
69
+ Parse ";"-separated mass differences into (entry, function) pairs. The function maps m/z values
70
+ of features to the m/z values of their expected partners.
71
+
72
+ An entry is a mass difference (number, formula or equation like "C[13] - C[12]" or "H2O + NH3", see
73
+ LipidCalculator's parse_equation) or an adduct exchange like "[M+H]+>[M+NH4]+" (the partner of an
74
+ [M+H]+ ion is the [M+NH4]+ ion of the same molecule, this also works for different charge states).
75
+
76
+ Raises:
77
+ ValueError: if an entry can't be parsed.
78
+ """
79
+ differences: list[tuple[str, Callable[[np.ndarray], np.ndarray]]] = []
80
+ for entry in text.split(';'):
81
+ if not (entry := entry.strip()):
82
+ continue
83
+ if '>' in entry:
84
+ try:
85
+ adduct_from, adduct_to = (Adduct(adduct.strip()) for adduct in entry.split('>'))
86
+ except Exception:
87
+ raise ValueError(f'"{entry}" is not a valid adduct exchange, use e.g. [M+H]+>[M+NH4]+.')
88
+ differences.append((entry, lambda mzs, a=adduct_from, b=adduct_to: np.array(
89
+ [b.mass_to_mz(a.mz_to_mass(mz)) for mz in mzs]
90
+ )))
91
+ else:
92
+ try:
93
+ mass = float(entry)
94
+ except ValueError:
95
+ try:
96
+ mass = parse_equation(entry).mass
97
+ except Exception:
98
+ raise ValueError(f'"{entry}" is neither a number, a formula nor an equation like C[13] - C[12].')
99
+ if mass == 0:
100
+ raise ValueError(f'"{entry}" has no mass difference.')
101
+ differences.append((entry, lambda mzs, d=mass: mzs + d))
102
+ return differences
103
+
104
+
105
+ def find_feature_pairs(
106
+ f_ids: np.ndarray,
107
+ rts: np.ndarray,
108
+ mzs: np.ndarray,
109
+ expected_partner_mz: Callable[[np.ndarray], np.ndarray],
110
+ max_dmz_ppm: float,
111
+ max_dmz_da: float,
112
+ rt_window: float
113
+ ) -> list[tuple[int, int]]:
114
+ """
115
+ Pairs (feature, partner) whose partner has the expected m/z (stricter of both tolerances) and a
116
+ retention time within rt_window of the feature.
117
+ """
118
+ expected: np.ndarray = expected_partner_mz(mzs)
119
+ tolerances: np.ndarray = np.minimum(max_dmz_da, max_dmz_ppm * 1e-6 * expected)
120
+ order: np.ndarray = np.argsort(mzs)
121
+ mzs_sorted: np.ndarray = mzs[order]
122
+ idcs_left = np.searchsorted(mzs_sorted, expected - tolerances, side='left')
123
+ idcs_right = np.searchsorted(mzs_sorted, expected + tolerances, side='right')
124
+
125
+ pairs: list[tuple[int, int]] = []
126
+ for i, (left, right) in enumerate(zip(idcs_left, idcs_right)):
127
+ for j in order[left:right]:
128
+ if j != i and abs(rts[j] - rts[i]) <= rt_window:
129
+ pairs.append((int(f_ids[i]), int(f_ids[j])))
130
+ return pairs
131
+
132
+
133
+ # inputs of the IPL builder when it was last closed or used (session only), shared by all dialogs that open it
134
+ ipl_builder_state: dict = {}
135
+ # variables of SingleIPLFrame in the order they are restored, the fields of the core are reset when it changes, so
136
+ # they come after it (_update_chain_state); older LipidCalculator versions don't have all of them
137
+ IPL_BUILDER_VARIABLES: tuple[str, ...] = ("core_class_var", "head_var", "head2_var", "core_var", "chains_var",
138
+ "split_var", "sort_var")
139
+ IPL_BUILDER_CORE_VARIABLES: tuple[str, ...] = ("core_chains_var", "core_db_var", "core_oh_var", "core_me_var")
140
+
141
+
142
+ def save_ipl_builder_state(frame):
143
+ """Remember the inputs and the selected adduct of the IPL builder."""
144
+ for name in (*IPL_BUILDER_VARIABLES, "rings_var", "isomer_var", *IPL_BUILDER_CORE_VARIABLES):
145
+ if hasattr(frame, name):
146
+ try:
147
+ ipl_builder_state[name] = getattr(frame, name).get()
148
+ except tk.TclError: # e.g. empty number field
149
+ pass
150
+ row = frame.table.selected_row()
151
+ ipl_builder_state["adduct"] = None if row is None else row["Adduct"]
152
+
153
+
154
+ def restore_ipl_builder_state(frame):
155
+ """Fill the IPL builder with the remembered inputs and select the remembered adduct once it is built."""
156
+ if not ipl_builder_state:
157
+ return
158
+
159
+ def restore(names):
160
+ for name in names:
161
+ if name in ipl_builder_state and hasattr(frame, name):
162
+ getattr(frame, name).set(ipl_builder_state[name])
163
+
164
+ restore(IPL_BUILDER_VARIABLES)
165
+ if hasattr(frame, "_set_core_class"): # cores of the remembered class in the list
166
+ frame.core_cb.configure(values=_cores_of_class(frame.core_class_var.get()))
167
+ frame._update_chain_state() # shows the fields of the core and resets them
168
+ if ipl_builder_state.get("rings_var") and hasattr(frame, "_update_isomers"): # tetraethers
169
+ restore(["rings_var"])
170
+ frame._update_isomers()
171
+ restore(["isomer_var"])
172
+ restore(IPL_BUILDER_CORE_VARIABLES)
173
+
174
+ def select_adduct(tries: int = 50):
175
+ """The structure is built shortly after the inputs change, then its table has rows."""
176
+ if not frame.winfo_exists():
177
+ return
178
+ tree = frame.table.tree
179
+ if not tree.get_children():
180
+ if tries:
181
+ frame.after(100, lambda: select_adduct(tries - 1))
182
+ return
183
+ for item in tree.get_children():
184
+ if tree.set(item, "Adduct") == ipl_builder_state.get("adduct"):
185
+ tree.selection_set(item)
186
+ tree.see(item)
187
+
188
+ frame.after(100, select_adduct)
189
+
190
+
191
+ def _cores_of_class(core_class: str) -> list[str]:
192
+ """Cores of a class in the IPL builder."""
193
+ from LipidCalculator.gui.ipl_gui import CORE_CLASSES
194
+ return CORE_CLASSES[core_class]
195
+
196
+
197
+ def open_ipl_builder(parent: tk.Misc, send_label: str, on_send: Callable[[object, dict, tk.Toplevel], None]):
198
+ """
199
+ Open the IPL builder of LipidCalculator in a window. Its button send_label calls on_send(frame, payload, window),
200
+ the payload holds the neutral formula and the adduct selected in the table of the builder (if any).
201
+ The inputs from the last time the builder was used (in this session) are restored.
202
+ """
203
+ try:
204
+ from LipidCalculator.gui.ipl_gui import SingleIPLFrame
205
+ except Exception as error:
206
+ messagebox.showerror("IPL builder", f"The IPL builder of LipidCalculator is not available:\n{error}",
207
+ parent=parent)
208
+ return
209
+ tk_window = tk.Toplevel(parent)
210
+ tk_window.title(f"IPL builder (select an adduct in the table, then \"{send_label}\")")
211
+ tk_window.geometry("1100x750")
212
+ frames: list = [] # the frame doesn't exist yet when the callback is defined
213
+
214
+ def send(payload):
215
+ save_ipl_builder_state(frames[0])
216
+ on_send(frames[0], payload, tk_window)
217
+
218
+ def close():
219
+ save_ipl_builder_state(frames[0])
220
+ tk_window.destroy()
221
+
222
+ frame = SingleIPLFrame(tk_window, send_targets={send_label: send})
223
+ frames.append(frame)
224
+ frame.pack(fill="both", expand=True)
225
+ restore_ipl_builder_state(frame)
226
+ tk_window.protocol("WM_DELETE_WINDOW", close)
227
+
228
+
229
+ # the batch window is hidden when closed and shown again, so its inputs and generated table are kept (session only)
230
+ _ipl_batch_window: tk.Toplevel | None = None
231
+
232
+
233
+ def batch_targets(frame, selected_only: bool) -> list:
234
+ """
235
+ m/z targets of the table of an IPL batch (BatchIPLFrame of LipidCalculator): one per row (the selected ones or
236
+ all) and adduct column.
237
+ """
238
+ from msIO.gui.annotation.matching import MzTarget
239
+ table = frame.table
240
+ columns: list[str] = list(table.columns)
241
+ adducts: list[str] = [column for column in columns if column in ADDUCTS or column.startswith("[")]
242
+ targets: list[MzTarget] = []
243
+ for values in table.rows(selected_only=selected_only):
244
+ row: dict = dict(zip(columns, values))
245
+ formula = re.sub(r"[+-]\d*$", "", row.get("Formula") or "") or None # rdkit formulas can carry a charge
246
+ for adduct in adducts:
247
+ try:
248
+ mz = float(row[adduct])
249
+ except (TypeError, ValueError):
250
+ continue
251
+ targets.append(MzTarget(name=row.get("Name") or "?", formula=formula, adduct=adduct, mz=mz,
252
+ smiles=row.get("SMILES") or None))
253
+ return targets
254
+
255
+
256
+ def open_ipl_batch(root: tk.Misc, on_use: Callable[[list], None]):
257
+ """
258
+ Open the batch generation of LipidCalculator (e.g. archaeols with ranges of chain lengths and double bonds). Its
259
+ button "Use for m/z filter" calls on_use(targets) with the targets of the selected rows (all rows if none is
260
+ selected), see batch_targets. The window keeps its inputs and table until the session ends.
261
+ """
262
+ global _ipl_batch_window
263
+ try:
264
+ from LipidCalculator.gui.ipl_gui import BatchIPLFrame
265
+ except Exception as error:
266
+ messagebox.showerror("IPL batch", f"The batch generation of LipidCalculator is not available:\n{error}",
267
+ parent=root)
268
+ return
269
+ if _ipl_batch_window is not None and _ipl_batch_window.winfo_exists():
270
+ _ipl_batch_window.on_use = on_use
271
+ _ipl_batch_window.deiconify()
272
+ _ipl_batch_window.lift()
273
+ return _ipl_batch_window
274
+
275
+ tk_window = tk.Toplevel(root)
276
+ tk_window.title("IPL batch (generate, select rows or none for all, then \"Use for m/z filter\")")
277
+ tk_window.geometry("1250x780")
278
+ tk_window.on_use = on_use
279
+ frame = BatchIPLFrame(tk_window)
280
+ tk_window.frame = frame
281
+ tk_buttons = ttk.Frame(tk_window, padding=(8, 0, 8, 8))
282
+ tk_buttons.pack(side="bottom", fill="x")
283
+ frame.pack(fill="both", expand=True)
284
+
285
+ def use():
286
+ selected: bool = bool(frame.table.tree.selection())
287
+ if not (targets := batch_targets(frame, selected_only=selected)):
288
+ messagebox.showerror("IPL batch", "Generate IPLs with at least one adduct first.", parent=tk_window)
289
+ return
290
+ tk_window.on_use(targets)
291
+
292
+ ttk.Button(tk_buttons, text="Close", command=tk_window.withdraw).pack(side="right")
293
+ ttk.Button(tk_buttons, text="Use for m/z filter", command=use).pack(side="right", padx=5)
294
+ ttk.Label(tk_buttons, foreground="gray",
295
+ text="m/z of each generated IPL and adduct ± precursor tolerance; features without library matches "
296
+ "are shown as dummy rows").pack(side="left")
297
+ tk_window.protocol("WM_DELETE_WINDOW", tk_window.withdraw)
298
+ _ipl_batch_window = tk_window
299
+ return tk_window
300
+
301
+
302
+ def focused_widget(widget: tk.Misc) -> tk.Misc | None:
303
+ """Widget with the keyboard focus in the application of widget, None if there is none (or tkinter can't resolve
304
+ it, e.g. the open list of a combobox)."""
305
+ try:
306
+ return widget.focus_get()
307
+ except KeyError:
308
+ return None
309
+
310
+
311
+ def canvas_has_focus(canvas: FigureCanvasTkAgg | None) -> bool:
312
+ return canvas is not None and focused_widget(canvas.get_tk_widget()) is canvas.get_tk_widget()
313
+
314
+
315
+ def create_canvas(fig, master: tk.Misc, focus_canvas: bool = False) -> FigureCanvasTkAgg:
316
+ """
317
+ Canvas of a figure that leaves the keyboard focus where it is. matplotlib focuses every new canvas, so redrawing
318
+ the overview (on every selected row) would take the focus from the table: arrow keys and Ctrl+C would stop
319
+ working there, as would the keys of the scatter plot. focus_canvas: give the new canvas the focus (e.g. it
320
+ replaces a canvas that had it).
321
+ """
322
+ # setting the focus back afterwards is not enough: on Windows, Tk applies focus changes later, so the canvas would
323
+ # still get it. matplotlib calls focus_set of the tk canvas in FigureCanvasTk.__init__, skip that call.
324
+ original_focus_set = tk.Canvas.focus_set
325
+ tk.Canvas.focus_set = lambda self: None
326
+ try:
327
+ canvas = FigureCanvasTkAgg(fig, master=master)
328
+ finally:
329
+ tk.Canvas.focus_set = original_focus_set
330
+ if focus_canvas:
331
+ canvas.get_tk_widget().focus_set()
332
+ _delay_resize(canvas)
333
+ return canvas
334
+
335
+
336
+ # a resized plot is redrawn once the size rests for this long (ms)
337
+ RESIZE_DELAY_MS: int = 150
338
+
339
+
340
+ def _delay_resize(canvas: FigureCanvasTkAgg):
341
+ """
342
+ matplotlib redraws the whole figure on every size change, which makes dragging a divider lag (one redraw per
343
+ pixel). Redraw once the size rests instead, until then the old image is shown.
344
+ """
345
+ tk_widget = canvas.get_tk_widget()
346
+ pending: dict = {"job": None, "event": None}
347
+
348
+ def resize_later(event):
349
+ pending["event"] = event
350
+ if pending["job"] is not None:
351
+ tk_widget.after_cancel(pending["job"])
352
+ pending["job"] = tk_widget.after(RESIZE_DELAY_MS, resize_now)
353
+
354
+ def resize_now():
355
+ pending["job"] = None
356
+ try:
357
+ canvas.resize(pending["event"])
358
+ except tk.TclError: # destroyed meanwhile
359
+ pass
360
+
361
+ # replaces the binding of matplotlib (FigureCanvasTk binds <Configure> to resize)
362
+ tk_widget.bind("<Configure>", resize_later)
363
+
364
+
365
+ class DividedArea(tk.PanedWindow):
366
+ """
367
+ Panes with movable dividers. While a divider is dragged only a line follows the mouse, the panes are resized once
368
+ it is released: resizing them live re-lays out the whole window (tables, plots) on every mouse move, which makes
369
+ dragging lag.
370
+ """
371
+
372
+ def __init__(self, master: tk.Misc, orient: str):
373
+ background: str = ttk.Style(master).lookup("TFrame", "background") or "SystemButtonFace"
374
+ super().__init__(master, orient=orient, opaqueresize=False, sashwidth=6, sashrelief="flat",
375
+ borderwidth=0, background=background)
376
+ self.horizontal: bool = orient == "horizontal"
377
+
378
+ def add_pane(self, widget: tk.Misc, grows: bool = True):
379
+ """Add a pane, grows: it gets a share of additional space when the area grows."""
380
+ self.add(widget, stretch="always" if grows else "never")
381
+
382
+ def set_grows(self, widget: tk.Misc, grows: bool):
383
+ self.paneconfigure(widget, stretch="always" if grows else "never")
384
+
385
+ def divider_position(self, index: int = 0) -> int:
386
+ """Position of a divider in pixels (x for horizontal, y for vertical areas)."""
387
+ x, y = self.sash_coord(index)
388
+ return x if self.horizontal else y
389
+
390
+ def set_divider_position(self, position: int, index: int = 0):
391
+ if self.horizontal:
392
+ self.sash_place(index, position, 0)
393
+ else:
394
+ self.sash_place(index, 0, position)
395
+
396
+
397
+ class Tooltip:
398
+ """Text shown in a small window while the mouse rests on a widget (after DELAY_MS)."""
399
+
400
+ DELAY_MS: int = 600
401
+ WRAP_LENGTH: int = 420
402
+
403
+ def __init__(self, widget: tk.Misc, text: str):
404
+ self.widget: tk.Misc = widget
405
+ self.text: str = text
406
+ self.job: str = None
407
+ self.window: tk.Toplevel = None
408
+ widget.bind("<Enter>", self._schedule, add="+")
409
+ for sequence in ("<Leave>", "<ButtonPress>", "<KeyPress>"):
410
+ widget.bind(sequence, self._hide, add="+")
411
+
412
+ def _schedule(self, event=None):
413
+ self._hide()
414
+ self.job = self.widget.after(self.DELAY_MS, self._show)
415
+
416
+ def _show(self):
417
+ self.job = None
418
+ if not self.text or not self.widget.winfo_viewable():
419
+ return
420
+ self.window = tk.Toplevel(self.widget)
421
+ self.window.wm_overrideredirect(True)
422
+ self.window.attributes("-topmost", True)
423
+ tk.Label(self.window, text=self.text, justify="left", wraplength=self.WRAP_LENGTH, background="#FFFFE0",
424
+ relief="solid", borderwidth=1, padx=6, pady=4).pack()
425
+ x = self.widget.winfo_rootx() + 12
426
+ y = self.widget.winfo_rooty() + self.widget.winfo_height() + 4
427
+ self.window.wm_geometry(f"+{x}+{y}")
428
+
429
+ def _hide(self, event=None):
430
+ if self.job is not None:
431
+ self.widget.after_cancel(self.job)
432
+ self.job = None
433
+ if self.window is not None:
434
+ self.window.destroy()
435
+ self.window = None
436
+
437
+
438
+ def add_tooltip(text: str, *widgets: tk.Misc) -> None:
439
+ """Show text while the mouse rests on any of the widgets (e.g. a label and its entry)."""
440
+ for widget in widgets:
441
+ Tooltip(widget, text)
442
+
443
+
444
+ def label_with_tooltip(master: tk.Misc, text: str, tooltip: str, *related_widgets: tk.Misc) -> ttk.Label:
445
+ """Label whose tooltip is also shown for the related widgets (e.g. its entry)."""
446
+ label = ttk.Label(master, text=text)
447
+ add_tooltip(tooltip, label, *related_widgets)
448
+ return label
449
+
450
+
451
+ def checkbutton_with_tooltip(master: tk.Misc, text: str, variable: tk.BooleanVar, command: Callable[[], None],
452
+ tooltip: str) -> ttk.Checkbutton:
453
+ checkbutton = ttk.Checkbutton(master, text=text, variable=variable, command=command)
454
+ add_tooltip(tooltip, checkbutton)
455
+ return checkbutton
456
+
457
+
458
+ SortKeys = list[tuple[str, bool]] # (column, descending), the first one is the primary key
459
+
460
+
461
+ def next_sort_keys(sort_keys: SortKeys, column: str, further_key: bool = False) -> SortKeys:
462
+ """
463
+ Sort keys after clicking a column header: ascending -> descending -> unsorted (default order). With further_key
464
+ (Ctrl+click), the column is added to the keys (or cycled through the same states) instead of replacing them.
465
+ """
466
+ position = next((i for i, (sorted_column, _) in enumerate(sort_keys) if sorted_column == column), None)
467
+ if not further_key or not sort_keys:
468
+ if position == 0: # primary key: reverse, then back to the default order
469
+ return [(column, True)] + sort_keys[1:] if not sort_keys[0][1] else []
470
+ return [(column, False)]
471
+ if position is None:
472
+ return sort_keys + [(column, False)]
473
+ if not sort_keys[position][1]:
474
+ return sort_keys[:position] + [(column, True)] + sort_keys[position + 1:]
475
+ return sort_keys[:position] + sort_keys[position + 1:]
476
+
477
+
478
+ def show_sort_keys(tree: ttk.Treeview, headings: dict[str, str], sort_keys: SortKeys):
479
+ """Arrows in the sorted column headers (numbered for several keys)."""
480
+ numbered: bool = len(sort_keys) > 1
481
+ arrows = {column: (" ▼" if descending else " ▲") + (str(i + 1) if numbered else "")
482
+ for i, (column, descending) in enumerate(sort_keys)}
483
+ for column, heading in headings.items():
484
+ tree.heading(column, text=heading + arrows.get(column, ""))
485
+
486
+
487
+ class TreeSorter:
488
+ """
489
+ Sorting of a ttk.Treeview by clicking its column headers, as in the results table: ascending -> descending ->
490
+ order of insertion, Ctrl+click adds a further sort key. Values are compared as numbers where possible (empty
491
+ values last), otherwise as text (case-insensitive). Call apply() after refilling the table.
492
+ """
493
+
494
+ def __init__(self, tree: ttk.Treeview, headings: dict[str, str]):
495
+ self.tree: ttk.Treeview = tree
496
+ self.headings: dict[str, str] = headings
497
+ self.keys: SortKeys = []
498
+ for column in headings:
499
+ tree.heading(column, command=lambda clicked=column: self.on_click(clicked))
500
+ tree.bind("<Control-ButtonRelease-1>", self._on_ctrl_release, add="+")
501
+
502
+ def _on_ctrl_release(self, event):
503
+ if self.tree.identify_region(event.x, event.y) != "heading":
504
+ return None
505
+ self.on_click(self.tree.column(self.tree.identify_column(event.x), "id"), further_key=True)
506
+ return "break"
507
+
508
+ def on_click(self, column: str, further_key: bool = False):
509
+ self.keys = next_sort_keys(self.keys, column, further_key)
510
+ show_sort_keys(self.tree, self.headings, self.keys)
511
+ self.apply()
512
+
513
+ @staticmethod
514
+ def _sort_value(text: str) -> tuple:
515
+ """Numbers before text, empty values last (in both directions, see apply)."""
516
+ try:
517
+ return 0, float(text), ""
518
+ except ValueError:
519
+ return 1, 0., text.lower()
520
+
521
+ def apply(self):
522
+ """Order the rows by the sort keys (stable, ties keep the order of insertion)."""
523
+ # order of insertion: the item ids (numbers given by the table, else Tk's I001, I002, ...)
524
+ items: list[str] = sorted(self.tree.get_children(), key=self._insertion_position)
525
+ # stable sorts from the last key to the first one give the sorting by several keys
526
+ for column, descending in reversed(self.keys):
527
+ filled = [item for item in items if str(self.tree.set(item, column)).strip()]
528
+ empty = [item for item in items if not str(self.tree.set(item, column)).strip()]
529
+ filled.sort(key=lambda item: self._sort_value(str(self.tree.set(item, column))), reverse=descending)
530
+ items = filled + empty
531
+ for position, item in enumerate(items):
532
+ self.tree.move(item, "", position)
533
+
534
+ @staticmethod
535
+ def _insertion_position(item: str) -> tuple:
536
+ return (0, int(item), "") if item.isdigit() else (1, 0, item)
537
+
538
+
539
+ def pack_canvas(canvas: FigureCanvasTkAgg):
540
+ """Fill the parent with the canvas, the figure is scaled to the available space."""
541
+ tk_widget = canvas.get_tk_widget()
542
+ # without this, the canvas requests the full figure size and pushes the dividers of the panes
543
+ tk_widget.config(width=1, height=1)
544
+ tk_widget.pack(fill=tk.BOTH, expand=True)
545
+
546
+
547
+ class CollapsibleSection(ttk.Frame):
548
+ """
549
+ Section with a header line that collapses / expands its body (click the header). Widgets go into body.
550
+
551
+ The body sits in a scrollable area: it asks for the size of its content and fills the space it gets, if it gets
552
+ less (small window or pane), scroll bars appear (mouse wheel: vertical, Shift+wheel: horizontal; not over
553
+ tables, lists and plots, which use the wheel themselves).
554
+
555
+ stretch: the section fills the remaining space of its (packed) parent while it is expanded.
556
+ on_toggle(expanded) is called after collapsing / expanding, e.g. to move the divider of a paned window.
557
+ """
558
+
559
+ # the size of the content is checked this often (ms), Tk has no event for a changed requested size
560
+ SIZE_CHECK_MS: int = 250
561
+
562
+ def __init__(self, master: tk.Misc, title: str, expanded: bool = True, stretch: bool = False,
563
+ on_toggle: Callable[[bool], None] = None, tooltip: str = None, **kwargs):
564
+ super().__init__(master, relief="groove", borderwidth=1, padding=(2, 1), **kwargs)
565
+ self.title: str = title
566
+ self.expanded: bool = expanded
567
+ self.stretch: bool = stretch
568
+ self.on_toggle: Callable[[bool], None] | None = on_toggle
569
+
570
+ self.tk_header = ttk.Label(self, cursor="hand2", font=("TkDefaultFont", 9, "bold"), padding=(4, 2))
571
+ self.tk_header.pack(fill="x")
572
+ self.tk_header.bind("<Button-1>", lambda event: self.toggle())
573
+ add_tooltip((tooltip + "\n\n" if tooltip else "") + "Click the header to collapse / expand the section.",
574
+ self.tk_header)
575
+
576
+ # body in a canvas, which scrolls it if it does not fit
577
+ self.tk_viewport = ttk.Frame(self)
578
+ self.tk_viewport.rowconfigure(0, weight=1)
579
+ self.tk_viewport.columnconfigure(0, weight=1)
580
+ background: str = ttk.Style(self).lookup("TFrame", "background") or "SystemButtonFace"
581
+ self.tk_canvas = tk.Canvas(self.tk_viewport, highlightthickness=0, borderwidth=0, background=background)
582
+ self.tk_canvas.grid(row=0, column=0, sticky="nsew")
583
+ self.tk_y_scroll = ttk.Scrollbar(self.tk_viewport, orient="vertical", command=self.tk_canvas.yview)
584
+ self.tk_x_scroll = ttk.Scrollbar(self.tk_viewport, orient="horizontal", command=self.tk_canvas.xview)
585
+ self.tk_canvas.configure(yscrollcommand=self.tk_y_scroll.set, xscrollcommand=self.tk_x_scroll.set)
586
+ self.body = ttk.Frame(self.tk_canvas, padding=(6, 2, 6, 4))
587
+ self._body_window = self.tk_canvas.create_window(0, 0, window=self.body, anchor="nw")
588
+ self._content_size: tuple[int, int] = None
589
+ self.tk_canvas.bind("<Configure>", lambda event: self._fit_body())
590
+ _bind_section_scrolling(self)
591
+ self.after(self.SIZE_CHECK_MS, self._check_content_size)
592
+
593
+ if expanded:
594
+ self.tk_viewport.pack(fill="both", expand=True)
595
+ self._update_header()
596
+
597
+ # ---- scrolling --------------------------------------------------------------------------------------------------
598
+ def _check_content_size(self):
599
+ """The content changed its size (e.g. widgets added): ask for the new size and fit the body again."""
600
+ try:
601
+ size = self.body.winfo_reqwidth(), self.body.winfo_reqheight()
602
+ if size != self._content_size:
603
+ self._content_size = size
604
+ # the section asks for the size of its content, as it would without scrolling
605
+ self.tk_canvas.configure(width=size[0], height=size[1])
606
+ self._fit_body()
607
+ self.after(self.SIZE_CHECK_MS, self._check_content_size)
608
+ except tk.TclError: # destroyed
609
+ pass
610
+
611
+ def _fit_body(self):
612
+ """Body as large as the visible area, but at least as large as its content; scroll bars for what is cut off."""
613
+ if self._content_size is None:
614
+ return
615
+ content_width, content_height = self._content_size
616
+ visible_width, visible_height = self.tk_canvas.winfo_width(), self.tk_canvas.winfo_height()
617
+ if visible_width <= 1: # not shown yet
618
+ return
619
+ width, height = max(visible_width, content_width), max(visible_height, content_height)
620
+ self.tk_canvas.itemconfigure(self._body_window, width=width, height=height)
621
+ self.tk_canvas.configure(scrollregion=(0, 0, width, height))
622
+ # showing a scroll bar makes the visible area smaller, which calls this again
623
+ for scrollbar, cut_off, sticky, position in (
624
+ (self.tk_y_scroll, content_height > visible_height, "ns", dict(row=0, column=1)),
625
+ (self.tk_x_scroll, content_width > visible_width, "ew", dict(row=1, column=0))):
626
+ if cut_off and not scrollbar.winfo_ismapped():
627
+ scrollbar.grid(sticky=sticky, **position)
628
+ elif not cut_off and scrollbar.winfo_ismapped():
629
+ scrollbar.grid_remove()
630
+
631
+ def scroll(self, units: int, horizontal: bool = False) -> bool:
632
+ """Scroll by units if the content is cut off in that direction, False if there is nothing to scroll."""
633
+ scrollbar = self.tk_x_scroll if horizontal else self.tk_y_scroll
634
+ if not scrollbar.winfo_ismapped():
635
+ return False
636
+ (self.tk_canvas.xview_scroll if horizontal else self.tk_canvas.yview_scroll)(units, "units")
637
+ return True
638
+
639
+ # ---- header -----------------------------------------------------------------------------------------------------
640
+ def _update_header(self):
641
+ self.tk_header.config(text=f"{'▼' if self.expanded else '▶'} {self.title}")
642
+
643
+ def set_title(self, title: str):
644
+ self.title = title
645
+ self._update_header()
646
+
647
+ def header_height(self) -> int:
648
+ """Height of the collapsed section in pixels."""
649
+ return self.tk_header.winfo_reqheight() + 6
650
+
651
+ def toggle(self):
652
+ self.set_expanded(not self.expanded)
653
+
654
+ def set_expanded(self, expanded: bool):
655
+ if expanded == self.expanded:
656
+ return
657
+ self.expanded = expanded
658
+ if expanded:
659
+ self.tk_viewport.pack(fill="both", expand=True)
660
+ else:
661
+ self.tk_viewport.pack_forget()
662
+ if self.stretch and self.winfo_manager() == "pack":
663
+ self.pack_configure(expand=expanded)
664
+ self._update_header()
665
+ if self.on_toggle is not None:
666
+ self.on_toggle(expanded)
667
+
668
+
669
+ # widgets that use the mouse wheel themselves (a tk.Canvas that is not the canvas of a section: matplotlib plot)
670
+ _OWN_WHEEL_SCROLLING = (ttk.Treeview, tk.Listbox, tk.Text, ttk.Combobox, ttk.Spinbox)
671
+
672
+
673
+ def _bind_section_scrolling(section: CollapsibleSection):
674
+ """Mouse wheel over a section scrolls it (if its content is cut off), bound once for the application."""
675
+ root: tk.Misc = section._root()
676
+ if getattr(root, "_section_wheel_bound", False):
677
+ return
678
+ root._section_wheel_bound = True
679
+
680
+ def on_wheel(event, horizontal: bool):
681
+ widget = event.widget
682
+ if not isinstance(widget, tk.Misc) or isinstance(widget, _OWN_WHEEL_SCROLLING):
683
+ return None
684
+ # the section around the widget under the mouse
685
+ while widget is not None and not isinstance(widget, CollapsibleSection):
686
+ if isinstance(widget, tk.Canvas) and not isinstance(widget.master.master, CollapsibleSection):
687
+ return None # a plot
688
+ widget = widget.master
689
+ if widget is not None:
690
+ widget.scroll(-1 if event.delta > 0 else 1, horizontal)
691
+ return None
692
+
693
+ root.bind_all("<MouseWheel>", lambda event: on_wheel(event, False), add="+")
694
+ root.bind_all("<Shift-MouseWheel>", lambda event: on_wheel(event, True), add="+")