Repository navigation
Expand file tree
/
Copy pathLabSpectrumManager.pyw
More file actions
4617 lines (4138 loc) · 207 KB
/
Copy pathLabSpectrumManager.pyw
File metadata and controls
4617 lines (4138 loc) · 207 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import matplotlib.pyplot as plt
import os
import sys
import struct
import re
import datetime
import pickle
import traceback
import tkinter as tk
from tkinter import filedialog, scrolledtext, messagebox, Listbox, ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import pandas as pd
try:
from tkinterdnd2 import DND_FILES, TkinterDnD
HAS_DND = True
except ImportError:
HAS_DND = False
# ---- PlotStyleKit bootstrap: the same text in every program (PlotStyleKit/README.md, 'Using it from a program') ----
import json
import os
PSK_MIN_API = 2
PSK_CONFIG = os.path.join(os.path.expanduser('~'), '.plotstylekit.json')
def _psk_config():
try:
with open(PSK_CONFIG, encoding='utf-8') as f:
return json.load(f)
except Exception:
return {}
def _psk_save(**changes):
cfg = _psk_config()
cfg.update(changes)
try:
with open(PSK_CONFIG, 'w', encoding='utf-8') as f:
json.dump(cfg, f)
except OSError:
pass
def _psk_try(folder, min_api):
"""(module, problem): problem is None when plotstylekit.py in `folder` loads and is recent enough."""
import importlib.util as ilu
path = os.path.join(folder, 'plotstylekit.py')
if not os.path.isfile(path):
return None, f"plotstylekit.py is not in {folder}"
try:
spec = ilu.spec_from_file_location('plotstylekit', path)
mod = ilu.module_from_spec(spec)
spec.loader.exec_module(mod)
except Exception as e:
return None, f"plotstylekit.py in {folder} cannot be loaded: {e}"
if getattr(mod, 'API', 0) < min_api:
return None, (f"PlotStyleKit in {folder} is too old for this program (API {getattr(mod, 'API', '?')}, "
f"it needs {min_api}): update it")
return mod, None
def _load_plotstylekit(min_api=PSK_MIN_API):
"""(module, problem): the first usable PlotStyleKit, or None and a sentence saying what was wrong."""
here = os.path.dirname(os.path.abspath(__file__))
folders = [here, os.environ.get('PLOTSTYLEKIT'), _psk_config().get('path'), os.path.join(here, '..', 'PlotStyleKit'),
os.path.expanduser(os.path.join('~', 'progetti', 'PlotStyleKit'))]
problem = "PlotStyleKit was not found (next to the program, PLOTSTYLEKIT, a folder you chose, ../PlotStyleKit)"
for folder in filter(None, folders):
if os.path.isfile(os.path.join(folder, 'plotstylekit.py')):
mod, why = _psk_try(folder, min_api)
if mod is not None:
return mod, None
problem = why
return None, problem
def _ask_plotstylekit_folder(parent, problem, min_api=PSK_MIN_API):
"""The warning that asks for the folder of PlotStyleKit. Returns the module, or None if the user cancels
(remembered: the program is not asked again) or closes the folder dialog (asked again next time)."""
from tkinter import filedialog, messagebox
while True:
if not messagebox.askokcancel(
"PlotStyleKit", problem + ".\n\nOK: choose the folder that contains plotstylekit.py.\n"
"Cancel: use the program without it (plain matplotlib look, no Edit Figure). You will not be asked "
"again; File > PlotStyleKit... lets you change your mind.", parent=parent):
_psk_save(declined=True)
return None
folder = filedialog.askdirectory(parent=parent, title="Folder of PlotStyleKit (contains plotstylekit.py)")
if not folder:
return None
mod, why = _psk_try(folder, min_api)
if mod is not None:
_psk_save(path=folder, declined=False)
return mod
problem = why
psk, PSK_PROBLEM = _load_plotstylekit()
if psk is not None:
try:
psk.setup()
except Exception as e:
psk, PSK_PROBLEM = None, f"PlotStyleKit failed to start: {e}"
# ---- end of the PlotStyleKit bootstrap ----
# Scattering model subtracted from a UV-Vis spectrum (wavelength in nm); the one place where it is written as text.
SCATTER_FORM = "A_corr(λ) = A(λ) − [ VS·(λ/1000)^(−P) − m·λ + Offset ]"
def scatter_equation(VS, P, M, OFF):
"""The fitted scattering term as text, with the optimised parameters in place of the symbols
(signs folded into the operators, so negative values do not read '+ -0.02')."""
def term(v, tail):
return f" {'−' if v < 0 else '+'} {abs(v):.6g}{tail}"
return (f"Scatter(λ) = {VS:.6g}·(λ/1000)^(−{P:.4g})"
+ term(-M, "·λ") + term(OFF, "") + " (λ in nm)")
class LabSpectrumManager:
def __init__(self, root):
self.root = root
self.root.title("Lab Spectrum Manager (UV-Vis + FTIR + Fluorescence)")
# Dimensione iniziale commisurata allo schermo (non un fisso 1500x900, che su
# schermi piccoli o con scaling elevato sporge sotto la taskbar): al più il
# 90% della larghezza e l'80% dell'altezza disponibili (l'80%, non l'85%, per
# lasciare margine alla barra delle applicazioni), finestra centrata.
screen_w = self.root.winfo_screenwidth()
screen_h = self.root.winfo_screenheight()
win_w = min(1500, int(screen_w * 0.90))
win_h = min(900, int(screen_h * 0.80))
pos_x = (screen_w - win_w) // 2
pos_y = (screen_h - win_h) // 2
self.root.geometry(f"{win_w}x{win_h}+{pos_x}+{pos_y}")
# A Tk button does not take the keyboard focus when clicked (Windows), so a value typed in an entry and not
# confirmed with Enter was never committed: its <FocusOut> did not fire before the button's command ran
# (Trim, Fit range, baseline anchors, ... used the old value). Focusing the button on press fixes every panel.
self.root.bind_class('Button', '<ButtonPress-1>', lambda e: e.widget.focus_set(), add='+')
if psk is None and not _psk_config().get('declined'):
self.root.after(400, lambda: self._offer_plotstylekit(PSK_PROBLEM))
self.spectra = {}
self._hidden_spectra = set() # nomi nascosti dal grafico (restano in lista/tabella)
self._dirty = False # True se ci sono risultati calcolati non ancora esportati
self.v_line = None
self.v_text = None
self.current_dir = os.getcwd()
self._cursor_data = [] # cache (name, x_array, y_array) per il cursore
self._cursor_box_pos = None # (ax_x, ax_y, ha, va) se trascinato manualmente; None = posizione "best" automatica
self._cursor_drag = False # True mentre l'utente trascina il riquadro X/Y
# Stato pannello scattering
self._sc_name = None
self._sc_x = None
self._sc_y = None
self._sc_lines = {}
self._sc_vline_lo = None
self._sc_vline_hi = None
self._sc_drag = None # 'lo' | 'hi' | None
self._sc_cids = [] # canvas connection IDs
self._sc_lim_cids = [] # callback id per xlim/ylim_changed
self._sc_user_zoomed = False # True se l'utente ha zoomato/pannato
self._sc_setting_lim = False # guard: stiamo impostando noi i limiti
# Stato pannello scaled subtraction
self._sub_name_a = None
self._sub_name_b = None
self._sub_index_a = None # pandas Index di A (usato per il DataFrame risultato)
self._sub_x = None # asse x di A come numpy array (per il grafico)
self._sub_y_a = None
self._sub_y_b = None
self._sub_lines = {}
# Stato pannello normalize
self._norm_names = []
self._norm_lines = {}
# Stato pannello baseline FTIR
self._bl_name = None
self._bl_x = None
self._bl_y = None
self._bl_lines = {}
self._bl_va = None # linea ancora 1 (trascinabile)
self._bl_vb = None # linea ancora 2 (trascinabile)
self._bl_drag = None # 'a' | 'b' | None
self._bl_cids = []
self._bl_syncing = False
# Stato pannello baseline adattiva
self._ab_name = None
self._ab_x = None
self._ab_y = None
self._ab_lines = {}
# Stato pannello smoothing
self._sm_name = None
self._sm_x = None
self._sm_y = None
self._sm_lines = {}
# Stato pannello derivata (Savitzky-Golay, 1a/2a)
self._dv_name = None
self._dv_x = None
self._dv_y = None
self._dv_lines = {}
# Stato pannello shift/scale (traslazione verticale e fattore moltiplicativo)
self._ss_names = []
self._ss_lines = {}
self._ss_ref_y = [] # valori Y degli spettri di riferimento (per i limiti dell'asse)
# Stato pannello deconvoluzione (lorentziane)
self._dc_name = None
self._dc_x = None
self._dc_y = None
self._dc_peaks = [] # lista di dict {'x0','A','w'}
self._dc_offset = 0.0
self._dc_fitted = False
self._dc_cids = []
self._dc_range = None # [lo, hi] intervallo di fit
self._dc_va = None # linea intervallo sinistra
self._dc_vb = None # linea intervallo destra
self._dc_drag = None # 'a' | 'b' | None
self._dc_drag_moved = False # distingue un click fermo (→ aggiungi picco) da un drag reale
# Stato pannello trim (ritaglio di una porzione di spettro)
self._tr_name = None
self._tr_x = None
self._tr_y = None
self._tr_lines = {}
self._tr_vline_lo = None
self._tr_vline_hi = None
self._tr_drag = None # 'lo' | 'hi' | None
self._tr_cids = [] # canvas connection IDs
if HAS_DND:
self.root.drop_target_register(DND_FILES)
self.root.dnd_bind('<<Drop>>', self.handle_drop)
# --- MENU ---
self.menu_bar = tk.Menu(root)
self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
self.file_menu.add_command(label="Open Files (.dsp, .dsw, .sp, .spc, .csv)", command=self.carica_da_dialog)
self.file_menu.add_separator()
self.file_menu.add_command(label="Open Session...", command=self.apri_sessione)
self.file_menu.add_command(label="Save Session...", command=self.salva_sessione)
self.file_menu.add_separator()
self.file_menu.add_command(label="Export CSV", command=self.esporta_csv)
self.file_menu.add_command(label="Save Figure (pickle)", command=self.salva_figura_pickle)
self.file_menu.add_command(label="Edit Figure...", command=self.apri_editor_figura)
self.file_menu.add_command(label="PlotStyleKit...", command=self.plotstylekit_dialog)
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit", command=self.on_exit)
self.menu_bar.add_cascade(label="File", menu=self.file_menu)
self.root.config(menu=self.menu_bar)
self.root.protocol("WM_DELETE_WINDOW", self.on_exit)
self.paned = tk.PanedWindow(root, orient=tk.HORIZONTAL, sashrelief=tk.RAISED, sashwidth=4)
self.paned.pack(fill=tk.BOTH, expand=True)
# 1. SINISTRA: DATA TABLE — Treeview invece di testo tab-separated: colonne
# ridimensionabili trascinando i separatori (nativo di Treeview) e intestazione
# sempre larga quanto la colonna (non può andare a capo su più righe, limite del
# widget: il nome viene troncato solo se l'utente restringe la colonna sotto la
# larghezza calcolata dal testo dell'intestazione).
self.f_data = tk.Frame(self.paned, bg='#ffffff')
tk.Label(self.f_data, text="DATA TABLE", font=('Arial', 10, 'bold'), bg='#ffffff').pack(pady=5)
data_table_frame = tk.Frame(self.f_data, bg='#ffffff')
data_table_frame.pack(padx=2, pady=2, fill=tk.BOTH, expand=True)
data_vsb = tk.Scrollbar(data_table_frame, orient=tk.VERTICAL)
data_hsb = tk.Scrollbar(data_table_frame, orient=tk.HORIZONTAL)
self.data_table = ttk.Treeview(data_table_frame, show='headings',
yscrollcommand=data_vsb.set, xscrollcommand=data_hsb.set)
data_vsb.config(command=self.data_table.yview)
data_hsb.config(command=self.data_table.xview)
data_vsb.pack(side=tk.RIGHT, fill=tk.Y)
data_hsb.pack(side=tk.BOTTOM, fill=tk.X)
self.data_table.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Select + copy: Treeview non ha un "seleziona tutto e incolla" nativo come
# il vecchio widget di testo, quindi lo ricreiamo con Ctrl+A / Ctrl+C (righe
# selezionate, header incluso, tab-separated) e un menu contestuale per scoprirli.
self.data_table.bind('<Control-c>', self._copia_tabella_dati)
self.data_table.bind('<Control-C>', self._copia_tabella_dati)
self.data_table.bind('<Control-a>', self._seleziona_tutto_tabella)
self.data_table.bind('<Control-A>', self._seleziona_tutto_tabella)
self.data_table.bind('<Button-3>', self._tabella_tasto_destro)
self.paned.add(self.f_data, width=400)
# 2. CENTRO: Grafico
self.f_plot = tk.Frame(self.paned)
self.fig, self.ax = plt.subplots(figsize=(6, 6))
# Il margine superiore di default di matplotlib (12% dell'altezza) è pensato
# per un titolo del grafico che qui non è mai impostato: ridotto per non
# lasciare una fascia vuota sopra il grafico. Impostato una sola volta sulla
# figura condivisa: resta valido per tutti i pannelli (ax.clear() non lo tocca).
self.fig.subplots_adjust(top=0.96)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.f_plot)
self.toolbar = NavigationToolbar2Tk(self.canvas, self.f_plot, pack_toolbar=False)
self.toolbar.pack(side=tk.TOP, fill=tk.X)
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.canvas.mpl_connect('axes_leave_event', self.on_mouse_leave)
self.canvas.mpl_connect('button_press_event', self._cursor_drag_start)
self.canvas.mpl_connect('button_release_event', self._cursor_drag_stop)
# Incolla dati x,y dalla clipboard: clic sul grafico per il focus, poi Ctrl+V
plot_widget = self.canvas.get_tk_widget()
plot_widget.bind('<Button-1>', lambda e: plot_widget.focus_set(), add='+')
plot_widget.bind('<Control-v>', self._incolla_clipboard)
plot_widget.bind('<Control-V>', self._incolla_clipboard)
# add='+' è essenziale: senza, questa bind sostituirebbe quella interna di
# FigureCanvasTk su <Button-3> (che genera il button_press_event di matplotlib),
# e il tasto destro smetterebbe di funzionare in deconvoluzione (e ovunque)
# tranne che con un doppio click, l'unico ancora instradato correttamente
plot_widget.bind('<Button-3>', self._menu_grafico, add='+')
self.paned.add(self.f_plot, width=700)
# 3. DESTRA: Gestione File
self.f_right = tk.Frame(self.paned, bg='#f0f4f7')
# Contenuto scorrevole verticalmente (canvas + scrollbar): alcuni pannelli
# operativi (Deconvolution soprattutto) hanno più controlli di quanti ne
# entrino in altezza, e allargare la finestra non è sempre possibile.
right_canvas = tk.Canvas(self.f_right, bg='#f0f4f7', highlightthickness=0)
right_scroll = tk.Scrollbar(self.f_right, orient=tk.VERTICAL, command=right_canvas.yview)
right_canvas.configure(yscrollcommand=right_scroll.set)
right_scroll.pack(side=tk.RIGHT, fill=tk.Y)
right_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.f_right_inner = tk.Frame(right_canvas, bg='#f0f4f7')
right_canvas_window = right_canvas.create_window((0, 0), window=self.f_right_inner, anchor='nw')
self.f_right_inner.bind('<Configure>',
lambda e: right_canvas.configure(scrollregion=right_canvas.bbox("all")))
right_canvas.bind('<Configure>',
lambda e: right_canvas.itemconfig(right_canvas_window, width=e.width))
tk.Label(self.f_right_inner, text="LOADED SPECTRA", font=('Arial', 10, 'bold'), bg='#f0f4f7').pack(pady=5)
self.file_listbox = Listbox(self.f_right_inner, selectmode=tk.MULTIPLE, height=8, font=('Arial', 9))
self.file_listbox.pack(padx=10, pady=5, fill=tk.X)
self.file_listbox.bind('<Button-3>', self._listbox_tasto_destro)
self.file_listbox.bind('<<ListboxSelect>>', lambda e: self._evidenzia_selezionati())
btn_frame = tk.Frame(self.f_right_inner, bg='#f0f4f7')
btn_frame.pack(fill=tk.X, padx=10)
tk.Button(btn_frame, text="Remove Selected", command=self.remove_selected).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
tk.Button(btn_frame, text="Clear All", command=self.clear_all).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
btn_frame_vis = tk.Frame(self.f_right_inner, bg='#f0f4f7')
btn_frame_vis.pack(fill=tk.X, padx=10, pady=(2, 0))
tk.Button(btn_frame_vis, text="Hide Selected", command=self.hide_selected).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
tk.Button(btn_frame_vis, text="Show Selected", command=self.show_selected).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
btn_frame2 = tk.Frame(self.f_right_inner, bg='#f0f4f7')
btn_frame2.pack(fill=tk.X, padx=10, pady=(2, 0))
tk.Button(btn_frame2, text="Average Selected", command=self.media_selezionati,
bg='#e8f5e9', font=('Arial', 9)).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
tk.Button(btn_frame2, text="Scaled Subtraction", command=self.apri_sottrazione_scalata,
bg='#fff3e0', font=('Arial', 9)).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
tk.Button(self.f_right_inner, text="Scattering Correction",
command=self.apri_correzione_scattering,
bg='#dce8f5', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(4, 0))
tk.Button(self.f_right_inner, text="Normalize Selected",
command=self.apri_normalizzazione,
bg='#f3e5f5', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(4, 0))
tk.Button(self.f_right_inner, text="Baseline (FTIR)",
command=self.apri_baseline,
bg='#d7ccc8', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(4, 0))
tk.Button(self.f_right_inner, text="Adaptive Baseline",
command=self.apri_baseline_adattiva,
bg='#c8e6c9', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(4, 0))
tk.Button(self.f_right_inner, text="Smooth Selected",
command=self.apri_smoothing,
bg='#ffe0b2', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(4, 0))
tk.Button(self.f_right_inner, text="Deconvolution",
command=self.apri_deconvoluzione,
bg='#b3e5fc', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(4, 0))
tk.Button(self.f_right_inner, text="Trim",
command=self.apri_trim,
bg='#cfd8dc', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(4, 0))
tk.Button(self.f_right_inner, text="Derivative",
command=self.apri_derivata,
bg='#d1c4e9', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(4, 0))
tk.Button(self.f_right_inner, text="Shift / Scale",
command=self.apri_shift_scale,
bg='#f8bbd0', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(4, 0))
# --- PANNELLO METADATA (visibile per default) ---
self.f_metadata = tk.Frame(self.f_right_inner, bg='#f0f4f7')
self.f_metadata.pack(fill=tk.BOTH, expand=True)
tk.Label(self.f_metadata, text="METADATA", font=('Arial', 10, 'bold'), bg='#f0f4f7').pack(pady=(15, 5))
self.param_box = scrolledtext.ScrolledText(self.f_metadata, width=45, height=15, font=('Consolas', 9), bg='#f0f4f7', bd=0)
self.param_box.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)
# --- PANNELLO SCATTERING (nascosto per default) ---
self.f_scattering = tk.Frame(self.f_right_inner, bg='#f0f4f7')
# non packed — appare solo quando attivato
self._costruisci_pannello_scattering()
# --- PANNELLO SCALED SUBTRACTION (nascosto per default) ---
self.f_subtraction = tk.Frame(self.f_right_inner, bg='#f0f4f7')
# non packed — appare solo quando attivato
self._costruisci_pannello_sottrazione()
# --- PANNELLO NORMALIZE (nascosto per default) ---
self.f_normalize = tk.Frame(self.f_right_inner, bg='#f0f4f7')
# non packed — appare solo quando attivato
self._costruisci_pannello_normalizzazione()
# --- PANNELLO BASELINE FTIR (nascosto per default) ---
self.f_baseline = tk.Frame(self.f_right_inner, bg='#f0f4f7')
# non packed — appare solo quando attivato
self._costruisci_pannello_baseline()
# --- PANNELLO BASELINE ADATTIVA (nascosto per default) ---
self.f_adaptive = tk.Frame(self.f_right_inner, bg='#f0f4f7')
# non packed — appare solo quando attivato
self._costruisci_pannello_adattivo()
# --- PANNELLO SMOOTHING (nascosto per default) ---
self.f_smooth = tk.Frame(self.f_right_inner, bg='#f0f4f7')
# non packed — appare solo quando attivato
self._costruisci_pannello_smoothing()
# --- PANNELLO DECONVOLUZIONE (nascosto per default) ---
self.f_deconv = tk.Frame(self.f_right_inner, bg='#f0f4f7')
# non packed — appare solo quando attivato
self._costruisci_pannello_deconv()
# --- PANNELLO TRIM (nascosto per default) ---
self.f_trim = tk.Frame(self.f_right_inner, bg='#f0f4f7')
# non packed — appare solo quando attivato
self._costruisci_pannello_trim()
# --- PANNELLO DERIVATA (nascosto per default) ---
self.f_derivative = tk.Frame(self.f_right_inner, bg='#f0f4f7')
# non packed — appare solo quando attivato
self._costruisci_pannello_derivata()
# --- PANNELLO SHIFT / SCALE (nascosto per default) ---
self.f_shiftscale = tk.Frame(self.f_right_inner, bg='#f0f4f7')
# non packed — appare solo quando attivato
self._costruisci_pannello_shift_scale()
self.paned.add(self.f_right, width=400)
if len(sys.argv) > 1:
for i in range(1, len(sys.argv)):
self.processa_file(sys.argv[i])
self.aggiorna_vista()
# --- PANNELLO SCATTERING: costruzione widget (una sola volta) ---
def _costruisci_pannello_scattering(self):
bg = '#f0f4f7'
tk.Label(self.f_scattering, text="SCATTERING CORRECTION",
font=('Arial', 10, 'bold'), bg=bg).pack(pady=(15, 2))
self._sc_label_nome = tk.Label(self.f_scattering, text="", font=('Consolas', 9, 'italic'), bg=bg)
self._sc_label_nome.pack()
ctrl = tk.Frame(self.f_scattering, bg=bg)
ctrl.pack(fill=tk.X, padx=10, pady=6)
# Tre parametri, ciascuno slider fine + casella editabile (valori a piacimento)
self._sc_VS = self._make_linked_row(ctrl, 'VS', 0.0, 1.0, 0.001, '{:.4f}')
self._sc_M = self._make_linked_row(ctrl, 'Slope (m)', -0.001, 0.001, 0.000002, '{:.6f}')
self._sc_M_lock = tk.BooleanVar(value=True)
m_lock_row = tk.Frame(ctrl, bg=bg)
m_lock_row.pack(fill=tk.X, pady=(0, 3))
tk.Label(m_lock_row, text='', width=9, bg=bg).pack(side=tk.LEFT) # allineamento
tk.Checkbutton(m_lock_row, text='fix slope', variable=self._sc_M_lock, bg=bg,
font=('Consolas', 8)).pack(side=tk.LEFT, padx=(10, 0))
self._sc_OFF = self._make_linked_row(ctrl, 'Offset', -1.5, 1.5, 0.001, '{:.3f}')
# Esponente P: slider continuo + casella, con preset 1/2/3/4 e blocco "fix P"
self._sc_P = self._make_linked_row(ctrl, 'P', 1.0, 5.0, 0.01, '{:.2f}')
self._linked_set(self._sc_P, 2.0)
preset = tk.Frame(ctrl, bg=bg)
preset.pack(fill=tk.X, pady=(0, 3))
tk.Label(preset, text='', width=9, bg=bg).pack(side=tk.LEFT) # allineamento
for p_val in (1, 2, 3, 4):
tk.Button(preset, text=str(p_val), width=2, font=('Consolas', 8),
command=lambda v=p_val: self._linked_set(self._sc_P, float(v))).pack(side=tk.LEFT, padx=2)
self._sc_P_lock = tk.BooleanVar(value=False)
tk.Checkbutton(preset, text='fix P', variable=self._sc_P_lock, bg=bg,
font=('Consolas', 8)).pack(side=tk.LEFT, padx=(10, 0))
# The equation: the form (what is subtracted) and the same with the current parameters
tk.Label(self.f_scattering, text=SCATTER_FORM, font=('Consolas', 8), bg=bg,
wraplength=360, justify=tk.LEFT).pack(padx=10, pady=(6, 0), anchor='w')
self._sc_eq_label = tk.Label(self.f_scattering, text="", font=('Consolas', 8), bg=bg, fg='#1f3b57',
wraplength=360, justify=tk.LEFT)
self._sc_eq_label.pack(padx=10, pady=(2, 0), anchor='w')
self._sc_fit_label = tk.Label(self.f_scattering, text="", font=('Consolas', 8), bg=bg, fg='#555555',
wraplength=360, justify=tk.LEFT)
self._sc_fit_label.pack(padx=10, anchor='w')
tk.Button(self.f_scattering, text="Copy equation", command=self._sc_copia_equazione,
font=('Arial', 8)).pack(padx=10, pady=(2, 0), anchor='w')
# Range label + pulsante Auto
self._sc_range_label = tk.Label(self.f_scattering, text="Fit range: —",
font=('Consolas', 8), bg='#f0f4f7', fg='#555555')
self._sc_range_label.pack(pady=(6, 0))
tk.Button(self.f_scattering, text="Auto (fit window)",
command=self._sc_auto, bg='#fff9c4', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(2, 0))
# Pulsanti Apply / Cancel
btn_sc = tk.Frame(self.f_scattering, bg=bg)
btn_sc.pack(fill=tk.X, padx=10, pady=10)
tk.Button(btn_sc, text="Apply", command=self._sc_applica,
bg='#2ecc71', fg='white', font=('Arial', 9, 'bold')).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
tk.Button(btn_sc, text="Cancel", command=self._sc_annulla).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
# --- SCATTERING: riga parametro con slider fine + casella editabile ---
def _make_linked_row(self, parent, label, lo, hi, res, fmt):
"""Crea una riga slider+Entry sincronizzati. La casella accetta valori
a piacimento (anche oltre il range dello slider); lo slider resta clampato.
Restituisce un dict di stato con chiavi 'value','slider','entry','lo','hi','fmt'."""
bg = '#f0f4f7'
st = {'syncing': False, 'lo': lo, 'hi': hi, 'fmt': fmt,
'value': tk.DoubleVar(value=0.0),
'slider': tk.DoubleVar(value=0.0),
'entry': tk.StringVar(value=fmt.format(0.0))}
row = tk.Frame(parent, bg=bg)
row.pack(fill=tk.X, pady=3)
tk.Label(row, text=label, width=9, anchor='w', bg=bg, font=('Consolas', 9)).pack(side=tk.LEFT)
sc = tk.Scale(row, variable=st['slider'], from_=lo, to=hi, resolution=res,
orient=tk.HORIZONTAL, length=185, bg=bg, font=('Consolas', 8),
showvalue=False,
command=lambda v, s=st: self._linked_from_slider(s, v))
sc.pack(side=tk.LEFT)
st['scale'] = sc
e = tk.Entry(row, textvariable=st['entry'], width=8, font=('Consolas', 9))
e.pack(side=tk.LEFT, padx=4)
e.bind('<Return>', lambda ev, s=st: self._linked_from_entry(s))
e.bind('<FocusOut>', lambda ev, s=st: self._linked_from_entry(s))
st['value'].trace_add('write', self._sc_aggiorna_preview)
return st
def _linked_set_range(self, st, lo, hi, res):
"""Ridimensiona il range dello slider (la casella resta comunque libera)."""
st['lo'], st['hi'] = lo, hi
st['scale'].config(from_=lo, to=hi, resolution=res)
def _linked_set(self, st, value, origine=None):
"""Imposta il parametro allineando valore reale, slider (clampato) e casella."""
st['syncing'] = True
if origine != 'entry':
st['entry'].set(st['fmt'].format(value))
if origine != 'slider':
st['slider'].set(min(max(value, st['lo']), st['hi']))
st['value'].set(value) # trace → preview
st['syncing'] = False
def _linked_from_slider(self, st, val):
if st['syncing']:
return
self._linked_set(st, float(val), origine='slider')
def _linked_from_entry(self, st):
if st['syncing']:
return
try:
v = float(st['entry'].get().replace(',', '.'))
except ValueError:
return
self._linked_set(st, v, origine='entry')
# --- SCATTERING: apertura pannello ---
def apri_correzione_scattering(self):
sel = self._selezione_effettiva()
if len(sel) != 1:
messagebox.showwarning("Scattering Correction", "Seleziona esattamente uno spettro dalla lista.")
return
name = self.file_listbox.get(sel[0])
if self.spectra[name]['info']['Type'] == 'FTIR':
messagebox.showwarning("Scattering Correction", "La correzione scattering non è applicabile a spettri FTIR.")
return
self._sc_name = name
self._sc_x = self.spectra[name]['df'].index.to_numpy(dtype=float)
self._sc_y = self.spectra[name]['df'][name].to_numpy(dtype=float)
# Range dei parametri commisurati all'ampiezza Y (e X per la pendenza):
# offset e VS ~ ampiezza dello spettro; slope ~ ampiezza/estensione X
span = float(self._sc_y.max() - self._sc_y.min())
if span <= 0:
span = max(abs(float(self._sc_y.max())), 0.1)
x_absmax = max(abs(float(self._sc_x.min())), abs(float(self._sc_x.max())), 1.0)
m_hi = span / x_absmax
# VS è il valore a 1000; la correzione all'estremo di bassa λ è
# VS·(λmin/1000)^-2. Scaliamo VS così che tale correzione arrivi a ~2·ampiezza,
# tenendo conto dell'amplificazione (altrimenti il range risulta troppo ampio).
lam_min = float(self._sc_x.min())
# (stima automatica, non piu' usata per lo slider: ora il fondoscala di VS e' fisso a 1)
vs_hi = 1.0
self._linked_set_range(self._sc_VS, 0.0, vs_hi, 0.001)
self._linked_set_range(self._sc_M, -m_hi, m_hi, 2 * m_hi / 1000.0)
self._linked_set_range(self._sc_OFF, -span, span, 2 * span / 1000.0)
# Reset slider ai valori di default
self._linked_set(self._sc_VS, 0.0)
self._linked_set(self._sc_M, 0.0)
self._sc_M_lock.set(True)
self._linked_set(self._sc_OFF, 0.0)
self._linked_set(self._sc_P, 2.0)
self._sc_label_nome.config(text=name)
# Prepara grafico principale con le tre linee di anteprima
self.ax.clear()
self.v_line = self.v_text = None
tipo = self.spectra[name]['info']['Type']
self.ax.set_xlabel("Raman shift (cm⁻¹)" if tipo == 'Raman' else "Wavelength (nm)")
self.ax.set_ylabel("Intensity (A.U.)" if tipo in ('Fluorescence', 'Raman') else "Absorbance")
self.ax.grid(True, linestyle=':', alpha=0.6)
self._sc_lines['orig'], = self.ax.plot(self._sc_x, self._sc_y,
color='steelblue', alpha=0.5, lw=1.5, label=f'{name} (orig)')
self._sc_lines['corr'], = self.ax.plot(self._sc_x, np.zeros_like(self._sc_y),
color='orange', lw=1.2, ls='--', label='Scattering')
self._sc_lines['res'], = self.ax.plot(self._sc_x, self._sc_y.copy(),
color='green', lw=2, label=f'{name}_corr')
self.ax.legend(fontsize=8)
# Linee verticali trascinabili per la finestra di fit: di default coprono
# l'intero spettro (l'auto-fit vincolato è ormai robusto su tutta la banda)
x_lo = self._sc_x.min()
x_hi = self._sc_x.max()
self._sc_vline_lo = self.ax.axvline(x=x_lo, color='purple', ls='--', lw=1.5, alpha=0.8)
self._sc_vline_hi = self.ax.axvline(x=x_hi, color='purple', ls='--', lw=1.5, alpha=0.8)
self._sc_drag = None
self._sc_cids = [
self.canvas.mpl_connect('button_press_event', self._sc_drag_start),
self.canvas.mpl_connect('motion_notify_event', self._sc_drag_move),
self.canvas.mpl_connect('button_release_event', self._sc_drag_stop),
]
self._sc_aggiorna_range_label()
self._sc_fit_label.config(text="")
self._sc_aggiorna_preview()
self.canvas.draw()
# Rileva zoom/pan dell'utente per non sovrascriverlo durante la preview.
# Connesso dopo il primo draw così l'autoscale iniziale non conta come zoom.
self._sc_user_zoomed = False
self._sc_lim_cids = [
self.ax.callbacks.connect('xlim_changed', self._sc_on_lim_changed),
self.ax.callbacks.connect('ylim_changed', self._sc_on_lim_changed),
]
# Mostra pannello scattering, nascondi metadata
self.f_metadata.pack_forget()
self.f_scattering.pack(fill=tk.BOTH, expand=True)
def _sc_on_lim_changed(self, ax=None):
# Ignora i cambi di limiti che impostiamo noi (guard); gli altri = zoom utente
if not self._sc_setting_lim:
self._sc_user_zoomed = True
# --- SCATTERING: aggiornamento preview live ---
def _sc_aggiorna_preview(self, *_):
if self._sc_x is None or 'corr' not in self._sc_lines:
return
VS, P, M, OFF = (self._sc_VS['value'].get(), self._sc_P['value'].get(),
self._sc_M['value'].get(), self._sc_OFF['value'].get())
correction = VS * (self._sc_x / 1000.0) ** -P - M * self._sc_x + OFF
y_corr = self._sc_y - correction
self._sc_eq_label.config(text=scatter_equation(VS, P, M, OFF))
self._sc_lines['corr'].set_ydata(correction)
self._sc_lines['res'].set_ydata(y_corr)
# Autoscale solo finché l'utente non ha zoomato: così lo zoom viene preservato
if not self._sc_user_zoomed:
y_all = np.concatenate([self._sc_y, y_corr, correction])
margin = (y_all.max() - y_all.min()) * 0.05 or 0.05
self._sc_setting_lim = True
self.ax.set_ylim(y_all.min() - margin, y_all.max() + margin)
self._sc_setting_lim = False
self.canvas.draw_idle()
# --- SCATTERING: fit automatico sulla finestra definita dalle linee ---
def _sc_auto(self):
if self._sc_x is None or self._sc_vline_lo is None:
return
P0 = float(self._sc_P['value'].get())
lock_P = self._sc_P_lock.get()
M0_fixed = float(self._sc_M['value'].get())
lock_M = self._sc_M_lock.get()
x, y = self._sc_x, self._sc_y
x_lo = self._sc_vline_lo.get_xdata()[0]
x_hi = self._sc_vline_hi.get_xdata()[0]
x_lo, x_hi = min(x_lo, x_hi), max(x_lo, x_hi)
mask = (x >= x_lo) & (x <= x_hi)
if mask.sum() < 3:
messagebox.showwarning("Auto fit", "La finestra selezionata contiene meno di 3 punti.")
return
x_ref, y_ref = x[mask], y[mask]
# Fit lineare iniziale a P fisso: VS*(x/1000)^-P - M*x + OFF = y (sulla finestra)
A_ref = np.column_stack([
(x_ref / 1000.0) ** -P0,
-x_ref,
np.ones_like(x_ref),
])
if lock_M:
coeffs, _, _, _ = np.linalg.lstsq(A_ref[:, [0, 2]], y_ref + M0_fixed * x_ref, rcond=None)
VS0, M0, OFF0 = float(max(coeffs[0], 0.0)), M0_fixed, float(coeffs[1])
else:
coeffs, _, _, _ = np.linalg.lstsq(A_ref, y_ref, rcond=None)
VS0, M0, OFF0 = float(max(coeffs[0], 0.0)), float(coeffs[1]), float(coeffs[2])
# Punto di partenza ammissibile: abbassa l'offset finché la traccia è sotto lo spettro
corr_full = VS0 * (x / 1000.0) ** -P0 - M0 * x + OFF0
over = float(np.max(corr_full - y))
if over > 0:
OFF0 -= over
VS_fit, M_fit, OFF_fit, P_fit = VS0, M0, OFF0, P0
step = max(1, len(x) // 800) # decima i vincoli (la traccia è liscia)
xc, yc = x[::step], y[::step]
# Scale per condizionare l'ottimizzazione (VS, M, x su ordini diversi)
s = np.maximum(np.abs(A_ref).max(axis=0), 1e-12)
# Rifinitura vincolata (traccia ≤ spettro in ogni punto). Richiede scipy;
# senza scipy resta la soluzione ammissibile con solo l'offset abbassato.
# Se lo slope è fissato, il suo bound collassa a un punto (M0*s[1]) e SLSQP
# lo tiene bloccato pur restando nella stessa formulazione del fit libero
m_bound = (M0 * s[1], M0 * s[1]) if lock_M else (None, None)
try:
from scipy.optimize import minimize
if lock_P:
# P fisso → modello lineare nei parametri: usa il jacobiano analitico
Ac = np.column_stack([(xc / 1000.0) ** -P0, -xc, np.ones_like(xc)])
Ars, Acs = A_ref / s, Ac / s
cons = [{'type': 'ineq',
'fun': lambda q: yc - Acs @ q,
'jac': lambda q: -Acs}]
res = minimize(lambda q: float((Ars @ q - y_ref) @ (Ars @ q - y_ref)),
np.array([VS0, M0, OFF0]) * s,
jac=lambda q: 2.0 * Ars.T @ (Ars @ q - y_ref),
method='SLSQP',
bounds=[(0.0, None), m_bound, (None, None)],
constraints=cons, options={'maxiter': 500, 'ftol': 1e-12})
if np.all(np.isfinite(res.x)):
VS_fit, M_fit, OFF_fit = (res.x / s)
else:
# P libero → modello non lineare: ottimizza anche l'esponente in [1, 5]
def corr(q, xx):
vs, m, off, pp = q[0] / s[0], q[1] / s[1], q[2] / s[2], q[3]
return vs * (xx / 1000.0) ** -pp - m * xx + off
cons = [{'type': 'ineq', 'fun': lambda q: yc - corr(q, xc)}]
q0 = np.array([VS0 * s[0], M0 * s[1], OFF0 * s[2], P0])
res = minimize(lambda q: float((corr(q, x_ref) - y_ref) @ (corr(q, x_ref) - y_ref)),
q0, method='SLSQP',
bounds=[(0.0, None), m_bound, (None, None), (1.0, 5.0)],
constraints=cons, options={'maxiter': 800, 'ftol': 1e-12})
if np.all(np.isfinite(res.x)):
VS_fit = res.x[0] / s[0]
M_fit = res.x[1] / s[1]
OFF_fit = res.x[2] / s[2]
P_fit = float(res.x[3])
except ImportError:
pass
VS_fit = float(max(VS_fit, 0.0))
# Garanzia finale su TUTTI i punti (il vincolo SLSQP era su griglia decimata)
corr_full = VS_fit * (x / 1000.0) ** -P_fit - M_fit * x + OFF_fit
over = float(np.max(corr_full - y))
if over > 0:
OFF_fit -= over
# Usa i valori reali del fit (VS ≥ 0); se eccedono il range dello slider
# la casella li mostra comunque e lo slider resta agganciato al massimo
self._linked_set(self._sc_VS, round(VS_fit, 6))
self._linked_set(self._sc_OFF, round(float(OFF_fit), 6))
if not lock_M:
self._linked_set(self._sc_M, round(float(M_fit), 8))
if not lock_P:
self._linked_set(self._sc_P, round(P_fit, 3))
# how well the trace follows the spectrum in the window (the trace stays at or below it by construction)
corr_win = VS_fit * (x_ref / 1000.0) ** -P_fit - M_fit * x_ref + OFF_fit
rmse = float(np.sqrt(np.mean((y_ref - corr_win) ** 2)))
self._sc_fit_label.config(
text=f"Auto fit {x_lo:.1f}–{x_hi:.1f} nm, {len(x_ref)} points, rms residual {rmse:.3g}; "
f"P {'fixed' if lock_P else 'optimised'}, slope {'fixed' if lock_M else 'optimised'}")
def _sc_copia_equazione(self):
"""Copy the form and the current parameters to the clipboard, ready to paste into a report."""
VS, P, M, OFF = (self._sc_VS['value'].get(), self._sc_P['value'].get(),
self._sc_M['value'].get(), self._sc_OFF['value'].get())
text = (f"{SCATTER_FORM}\n{scatter_equation(VS, P, M, OFF)}\n"
f"VS = {VS:.6g}, P = {P:.4g}, m = {M:.6g}, Offset = {OFF:.6g}")
self.root.clipboard_clear()
self.root.clipboard_append(text)
self.root.update()
# --- SCATTERING: drag delle linee verticali ---
def _sc_aggiorna_range_label(self):
if self._sc_vline_lo is None:
return
lo = self._sc_vline_lo.get_xdata()[0]
hi = self._sc_vline_hi.get_xdata()[0]
lo, hi = min(lo, hi), max(lo, hi)
self._sc_range_label.config(text=f"Fit range: {lo:.1f} – {hi:.1f}")
def _sc_drag_start(self, event):
if event.inaxes != self.ax or event.button != 1:
return
for key, line in [('lo', self._sc_vline_lo), ('hi', self._sc_vline_hi)]:
x_disp = self.ax.transData.transform((line.get_xdata()[0], 0))[0]
if abs(event.x - x_disp) < 8:
self._sc_drag = key
return
def _sc_drag_move(self, event):
if self._sc_drag is None or event.inaxes != self.ax or event.xdata is None:
return
xv = event.xdata
lo = self._sc_vline_lo.get_xdata()[0]
hi = self._sc_vline_hi.get_xdata()[0]
if self._sc_drag == 'lo':
xv = min(xv, hi - 1)
self._sc_vline_lo.set_xdata([xv, xv])
else:
xv = max(xv, lo + 1)
self._sc_vline_hi.set_xdata([xv, xv])
self._sc_aggiorna_range_label()
self.canvas.draw_idle()
def _sc_drag_stop(self, event):
self._sc_drag = None
# --- SCATTERING: applica e torna alla vista normale ---
def _sc_applica(self):
VS, P, M, OFF = (self._sc_VS['value'].get(), self._sc_P['value'].get(),
self._sc_M['value'].get(), self._sc_OFF['value'].get())
correction = VS * (self._sc_x / 1000.0) ** -P - M * self._sc_x + OFF
y_corr = self._sc_y - correction
new_name = f"{self._sc_name}_corr"
new_info = dict(self.spectra[self._sc_name]['info'])
new_info['Sample'] = new_name
new_info['Derived from'] = self._sc_name
new_info['Scatter VS'] = f"{VS:.4f}"
new_info['Scatter P'] = str(P)
new_info['Scatter Slope'] = f"{M:.6f}"
new_info['Scatter Offset'] = f"{OFF:.3f}"
new_info['Scatter equation'] = scatter_equation(VS, P, M, OFF) # full precision, unlike the keys above
self.spectra[new_name] = {
'df': pd.DataFrame({'x': self._sc_x, new_name: y_corr}).set_index('x'),
'info': new_info,
}
self._dirty = True
self._sc_chiudi_pannello()
self.aggiorna_vista()
# --- SCATTERING: annulla senza modifiche ---
def _sc_annulla(self):
self._sc_chiudi_pannello()
self.aggiorna_vista()
# --- SCATTERING: chiude il pannello e ripristina metadata ---
def _sc_chiudi_pannello(self):
for cid in self._sc_cids:
self.canvas.mpl_disconnect(cid)
self._sc_cids = []
for cid in self._sc_lim_cids:
self.ax.callbacks.disconnect(cid)
self._sc_lim_cids = []
self._sc_user_zoomed = False
self._sc_drag = None
self._sc_vline_lo = None
self._sc_vline_hi = None
self._sc_name = None
self._sc_x = None
self._sc_y = None
self._sc_lines = {}
self.f_scattering.pack_forget()
self.f_metadata.pack(fill=tk.BOTH, expand=True)
# --- PANNELLO SCALED SUBTRACTION: costruzione widget ---
def _costruisci_pannello_sottrazione(self):
bg = '#f0f4f7'
tk.Label(self.f_subtraction, text="SCALED SUBTRACTION",
font=('Arial', 10, 'bold'), bg=bg).pack(pady=(15, 2))
# Etichetta con i nomi degli spettri coinvolti
self._sub_label_ab = tk.Label(self.f_subtraction, text="", font=('Consolas', 9, 'italic'),
bg=bg, wraplength=360, justify='left')
self._sub_label_ab.pack(padx=10)
ctrl = tk.Frame(self.f_subtraction, bg=bg)
ctrl.pack(fill=tk.X, padx=10, pady=8)
row = tk.Frame(ctrl, bg=bg)
row.pack(fill=tk.X, pady=4)
tk.Label(row, text='k', width=5, anchor='w', bg=bg, font=('Consolas', 10, 'bold')).pack(side=tk.LEFT)
self._var_k = tk.DoubleVar(value=1.0)
tk.Scale(row, variable=self._var_k, from_=-5.0, to=5.0, resolution=0.001,
orient=tk.HORIZONTAL, length=270, bg=bg,
font=('Consolas', 8), showvalue=True).pack(side=tk.LEFT)
# Spettro di riferimento
ref_row = tk.Frame(ctrl, bg=bg)
ref_row.pack(fill=tk.X, pady=4)
tk.Label(ref_row, text='Ref', width=5, anchor='w', bg=bg, font=('Consolas', 10)).pack(side=tk.LEFT)
self._sub_ref_var = tk.StringVar(value='— none —')
self._sub_ref_menu = tk.OptionMenu(ref_row, self._sub_ref_var, '— none —')
self._sub_ref_menu.config(font=('Consolas', 8), width=28)
self._sub_ref_menu.pack(side=tk.LEFT, fill=tk.X, expand=True)
self._sub_ref_var.trace_add('write', self._sub_aggiorna_riferimento)
# Formula display
self._sub_formula = tk.Label(self.f_subtraction, text="Result = A − 1.000 × B",
font=('Consolas', 9), bg=bg, fg='#555555')
self._sub_formula.pack()
self._var_k.trace_add('write', self._sub_aggiorna_preview)
# Pulsante Swap
tk.Button(self.f_subtraction, text="Swap A ↔ B", command=self._sub_scambia_ab,
bg='#e8eaf6', font=('Arial', 9)).pack(fill=tk.X, padx=10, pady=(0, 4))
# Pulsanti Apply / Cancel
btn_sub = tk.Frame(self.f_subtraction, bg=bg)
btn_sub.pack(fill=tk.X, padx=10, pady=10)
tk.Button(btn_sub, text="Apply", command=self._sub_applica,
bg='#2ecc71', fg='white', font=('Arial', 9, 'bold')).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
tk.Button(btn_sub, text="Cancel", command=self._sub_annulla).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
# --- SCALED SUBTRACTION: apertura pannello ---
def apri_sottrazione_scalata(self):
sel = self.file_listbox.curselection()
if len(sel) != 2:
messagebox.showwarning("Scaled Subtraction", "Seleziona esattamente 2 spettri (A e B, in quest'ordine).")
return
name_a = self.file_listbox.get(sel[0])
name_b = self.file_listbox.get(sel[1])
types = {self.spectra[name_a]['info']['Type'], self.spectra[name_b]['info']['Type']}
if len(types) > 1:
messagebox.showwarning("Scaled Subtraction", f"Gli spettri hanno tipi diversi: {', '.join(types)}.")
return
self._sub_name_a = name_a
self._sub_name_b = name_b
# Asse x di A; B allineato per indice (stessa x garantita dall'utente)
df_a = self.spectra[name_a]['df']
df_b = self.spectra[name_b]['df']
self._sub_index_a = df_a.index
self._sub_x = df_a.index.to_numpy(dtype=float)
self._sub_y_a = df_a[name_a].to_numpy(dtype=float)
self._sub_y_b = df_b[name_b].reindex(df_a.index).to_numpy(dtype=float)
self._var_k.set(1.0)
self._sub_label_ab.config(text=f"A: {name_a}\nB: {name_b}")
# Aggiorna opzioni menu riferimento
opts = ['— none —'] + [n for n in self.spectra if n not in (name_a, name_b)]
m = self._sub_ref_menu['menu']
m.delete(0, 'end')
for opt in opts:
m.add_command(label=opt, command=lambda v=opt: self._sub_ref_var.set(v))
self._sub_ref_var.set('— none —')
# Prepara grafico
self.ax.clear()
self.v_line = self.v_text = None
tipo = self.spectra[name_a]['info']['Type']
if tipo == 'FTIR':
self.ax.set_xlabel("Wavenumber (cm⁻¹)")
self.ax.set_ylabel(self._ftir_ylabel([self._sub_name_a, self._sub_name_b]))
elif tipo == 'Raman':
self.ax.set_xlabel("Raman shift (cm⁻¹)")
self.ax.set_ylabel("Intensity (A.U.)")
elif tipo == 'Fluorescence':
self.ax.set_xlabel("Wavelength (nm)")
self.ax.set_ylabel("Intensity (A.U.)")
else:
self.ax.set_xlabel("Wavelength (nm)")
self.ax.set_ylabel("Absorbance")
self.ax.grid(True, linestyle=':', alpha=0.6)
self._sub_lines['ref'], = self.ax.plot([], [], color='gray', lw=1.2,
ls=':', visible=False, label='_nolegend_')
self._sub_lines['a'], = self.ax.plot(self._sub_x, self._sub_y_a,
color='steelblue', alpha=0.6, lw=1.5, label=f'{name_a} (A)')
self._sub_lines['b'], = self.ax.plot(self._sub_x, self._sub_y_b,
color='tomato', alpha=0.3, lw=1.2, ls='--', label=f'{name_b} (B)')
self._sub_lines['kb'], = self.ax.plot(self._sub_x, self._sub_y_b,
color='tomato', alpha=0.8, lw=1.5, label='k×B')
self._sub_lines['res'], = self.ax.plot(self._sub_x, self._sub_y_a - self._sub_y_b,
color='green', lw=2, label='A − k×B')
self.ax.legend(fontsize=8)
if tipo == 'FTIR':
self.ax.invert_xaxis()
self.canvas.draw()