Repository navigation
Expand file tree
/
Copy pathLabSpectrumManager.pyw
More file actions
5410 lines (4862 loc) · 253 KB
/
Copy pathLabSpectrumManager.pyw
File metadata and controls
5410 lines (4862 loc) · 253 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
# ---- Version and update check (Help > Check for updates...) -----------------------------------------------------------
__version__ = "1.0.0"
GITHUB_REPO = "milanone/LabSpectrumManager"
PROGRAM_FILE = "LabSpectrumManager.pyw"
def parse_version(tag):
"""'v1.2.3' -> (1, 2, 3); anything that is not a number after the dots (a suffix such as '-rc1') is ignored."""
nums = re.findall(r"\d+", str(tag).strip().lstrip("vV").split("-")[0])
return tuple(int(n) for n in nums) or (0,)
def _github_get(url, timeout=10):
"""GET with a generic client name (no personal data goes out); returns the response bytes."""
import urllib.request
req = urllib.request.Request(url, headers={"User-Agent": "LabSpectrumManager-update-check",
"Accept": "application/vnd.github+json"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.read()
def fetch_latest_release(repo=GITHUB_REPO, timeout=10):
"""Latest published version of the repository: {'tag', 'notes', 'url'}, or None when nothing is published.
Uses the latest GitHub release; with no release yet it falls back to the newest tag. Network errors propagate."""
import json as _json
import urllib.error
try:
d = _json.loads(_github_get(f"https://api.github.com/repos/{repo}/releases/latest", timeout))
return {"tag": d["tag_name"], "notes": d.get("body") or "", "url": d.get("html_url") or f"https://github.com/{repo}"}
except urllib.error.HTTPError as e:
if e.code != 404:
raise
tags = _json.loads(_github_get(f"https://api.github.com/repos/{repo}/tags", timeout))
if not tags:
return None
best = max(tags, key=lambda t: parse_version(t["name"]))
return {"tag": best["name"], "notes": "", "url": f"https://github.com/{repo}/releases/tag/{best['name']}"}
def download_release(tag, folder, repo=GITHUB_REPO, timeout=30):
"""Download the program file of a tag into `folder` as LabSpectrumManager_<tag>.pyw. The running program is never
touched, and an existing file is never overwritten (a counter is added). The text must compile and contain the
program class, otherwise nothing is written. Returns the path."""
data = _github_get(f"https://raw.githubusercontent.com/{repo}/{tag}/{PROGRAM_FILE}", timeout)
text = data.decode("utf-8")
compile(text, PROGRAM_FILE, "exec")
if "class LabSpectrumManager" not in text:
raise ValueError("the downloaded file is not the program")
base = os.path.join(folder, f"LabSpectrumManager_{tag}")
path, n = base + ".pyw", 1
while os.path.exists(path):
n += 1
path = f"{base}_{n}.pyw"
with open(path, "wb") as f:
f.write(data)
return path
# ---- 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 ToolTip:
"""Small yellow help box shown after the pointer rests on a widget for `delay` ms; hidden on leave or click."""
def __init__(self, widget, text, delay=500, wraplength=340):
self.widget, self.text, self.delay, self.wraplength = widget, text, delay, wraplength
self._after, self._tip = None, None
widget.bind('<Enter>', self._schedule, add='+')
widget.bind('<Leave>', self._hide, add='+')
widget.bind('<ButtonPress>', self._hide, add='+')
def _schedule(self, _event=None):
self._hide()
self._after = self.widget.after(self.delay, self._show)
def _show(self):
self._after = None
if self._tip is not None or not self.text:
return
x = self.widget.winfo_rootx() + 12
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 4
self._tip = tk.Toplevel(self.widget)
self._tip.wm_overrideredirect(True)
self._tip.wm_geometry(f"+{x}+{y}")
tk.Label(self._tip, text=self.text, justify=tk.LEFT, bg='#ffffe0', relief=tk.SOLID, borderwidth=1,
font=('Arial', 8), wraplength=self.wraplength).pack()
def _hide(self, _event=None):
if self._after is not None:
self.widget.after_cancel(self._after)
self._after = None
if self._tip is not None:
self._tip.destroy()
self._tip = None
# Help texts of the simulator fields (key -> text); the keys are those of the field table in open_simulator()
SIM_MODES = ("Lipid vesicles", "Solid spheres (latex)")
SIM_TIPS = {
'mode': "Lipid vesicles: a thin lipid shell in water (the concentration is in mg/mL of lipid). Solid spheres: "
"homogeneous particles such as a polystyrene latex size standard (the concentration is in % w/v of solids). "
"The fields of the other type are greyed out.",
'nsph': "Refractive index of the solid particles at 589 nm (polystyrene 1.592). The dispersion with wavelength is "
"that of polystyrene, which is only an approximation for other materials.",
'rho': "Density of the solid particles, g/mL (polystyrene latex 1.055). With the % w/v it gives the number of "
"particles.",
'c': "Concentration of the stock suspension: lipid vesicles, mg/mL (= g/L) of the total lipid, cholesterol and "
"PEG-lipid included; solid spheres, % w/v of solids (4% w/v = 40 mg/mL).",
'dil': "Dilution of the stock in the cuvette: 40 means 1 part of stock in 40 parts in total. 1 = measured undiluted.",
'loss': "Percentage of the material lost during the preparation (extrusion, filtration, adsorption). It lowers the "
"concentration in the cuvette and so the predicted amplitude.",
'path': "Optical path of the cuvette in cm. The predicted absorbance is proportional to it.",
'd': "Median outer diameter of the particle population, nm. 'Fit size' finds the value that agrees best with the "
"measurement.",
'sg': "Width σ of the log-normal size distribution: the spread of ln(diameter), about the relative standard "
"deviation of the size (0.2 = 20%). It is related to the DLS polydispersity index by PDI ≈ σ² "
"(σ 0.2 ≈ PDI 0.04, σ 0.3 ≈ PDI 0.09). A wider population smooths the oscillations of large particles.",
'n': "Number of concentric bilayers of each vesicle. Extruded vesicles (11 passes) are unilamellar (1). The "
"amplitude is roughly proportional to the number of lamellae at a given lipid concentration.",
'acc': "Collection half-angle of the instrument: the light scattered forward inside this cone still reaches the "
"detector, so it does not count as absorbance. It is not in the instrument specifications and is a "
"property of the geometry; 10° is compatible with the samples measured so far but is not determined by "
"them. It matters for particles larger than about 150 nm (it lowers their apparent P) and not for "
"small ones.",
't': "Thickness of the lipid (POPC) bilayer, nm, used as the scattering shell. In the simulator cholesterol "
"thickens it (+0.4 nm per 10 mol%).",
'dn': "Refractive index excess of the lipid shell over water (0.155 for egg lecithin, from the literature). Together with the "
"thickness it sets the absolute amplitude, which goes roughly as (thickness × index excess)²: this is the "
"main uncertainty of the absolute scale (a factor 2-3).",
'rep': "Repeat distance of a multilamellar vesicle, nm: bilayer plus the water gap between two lamellae. Used only "
"for more than one lamella.",
'mw': "Molar mass of POPC, g/mol (760.08). With the other components it gives the mean molar mass of the mixture, "
"i.e. the number of lipid molecules in the cuvette.",
'area': "Area per POPC molecule in the bilayer, nm² (0.65). With the lipid concentration it gives the number of "
"lipids per vesicle, so the number of vesicles. Cholesterol reduces it (below).",
'k': "Amplitude factor multiplied by the theoretical spectrum. k = 1 is the pure prediction from the lipid "
"concentration. The value that would make theory and measurement agree is shown under the plot: it absorbs "
"the errors of the lipid amount (loss, concentration), of the shell (thickness × index) and of the number "
"of lamellae. 'Fit size + amplitude' sets it. A k near 1 means that the absolute scale agrees.",
'off': "Constant added to the theory (baseline or cuvette mismatch). 0 for a perfect blank.",
'chol': "Cholesterol, mol% of all the lipid molecules. Condenses the bilayer: smaller area per molecule and a "
"thicker bilayer (assumed -9% area and +0.4 nm per 10 mol%).",
'peg': "PEG-lipid (for example DSPE-PEG2000), mol% of all the lipid molecules. Its polymer corona adds a thin "
"film of PEG to the shell, which scatters a little.",
'pegmw': "Molar mass of the PEG chain, g/mol (2000). It gives the volume of polymer per chain.",
'peglmw': "Molar mass of the whole PEG-lipid, g/mol (2805.5 for DSPE-mPEG2000), used for the mean molar mass.",
'pegl': "Number of leaflets that carry PEG: 2 when the PEG-lipid was mixed in before the film was made, 1 if it is "
"only on the outer leaflet, 0 to ignore the PEG film.",
'lo': "Shortest wavelength of the window used for the comparison, nm. Below about 350-400 nm lipids and other "
"components may absorb, which the scattering model does not include.",
'hi': "Longest wavelength of the window used for the comparison, nm.",
}
SIM_BUTTON_TIPS = {
'fit': "Finds the diameter with the least rms residual, keeping every other field as typed, k included.",
'fitk': "Finds the diameter and, for each diameter, the amplitude factor k that minimises the rms residual. The "
"shape of the spectrum fixes the size; k then says how far the absolute scale is from the prediction.",
'update': "Redraws with the current values (the plot also updates by itself after each edit).",
}
def fit_power_law(x, y, P=None, m=0.0, p_lo=1.0, p_hi=None, under=None):
"""Least-squares fit of y = VS*(x/1000)^-P - m*x with NO offset (plain, unconstrained).
P=None optimises the exponent above p_lo (grid scan, VS and the slope are linear so they are solved exactly at
each P). There is no upper limit by default: the scan starts at p_lo..5 and, when the best exponent is at its upper
edge, goes on in steps of 5 until the optimum is inside (a safety stop at 200, far beyond any physical exponent);
a number as p_hi restores a limit. m=None fits the slope too, a number keeps it fixed. Returns (VS, P, m, rms).
under=(xc, yc) forces the trace to stay at or below the points yc at xc (also outside the fitted window): with no
offset to lower, VS gives way (for a fixed slope VS = min(least-squares VS, min over the points of the value that
touches the first one); a free slope is solved with SLSQP). Points of yc at or below zero are left out of the
constraint (a trace with VS >= 0 cannot go under them; they would force VS = 0). The returned P (3 decimals), slope
(8 decimals) and VS (6 significant digits, rounded down) are the rounded values and the constraint holds for them."""
x = np.asarray(x, float)
y = np.asarray(y, float)
if under is not None:
xc, yc = np.asarray(under[0], float), np.asarray(under[1], float)
keep = yc > 0 # a trace with VS >= 0 cannot go under a point at or below zero: leave those out
xc, yc = xc[keep], yc[keep]
def solve(p):
t = (x / 1000.0) ** -p
if m is None:
c, *_ = np.linalg.lstsq(np.column_stack([t, -x]), y, rcond=None)
vs, mm = float(c[0]), float(c[1])
else:
vs, mm = float((t @ (y + m * x)) / (t @ t)), float(m)
return vs, mm, float(np.sqrt(np.mean((y - (vs * t - mm * x)) ** 2)))
def solve_under(p, mm_fixed):
"""Constrained VS (and slope when mm_fixed is None) at the exponent p."""
t, tc = (x / 1000.0) ** -p, (xc / 1000.0) ** -p
if mm_fixed is not None:
vs = float((t @ (y + mm_fixed * x)) / (t @ t))
vs = max(min(vs, float(np.min((yc + mm_fixed * xc) / tc)) if yc.size else vs), 0.0)
return vs, float(mm_fixed), float(np.sqrt(np.mean((y - (vs * t - mm_fixed * x)) ** 2)))
try:
from scipy.optimize import minimize
except ImportError:
return solve_under(p, 0.0)
A, Ac = np.column_stack([t, -x]), np.column_stack([tc, -xc])
sc = np.maximum(np.abs(A).max(axis=0), 1e-300)
As, Acs = A / sc, Ac / sc
q0, *_ = np.linalg.lstsq(As, y, rcond=None)
res = minimize(lambda q: float((As @ q - y) @ (As @ q - y)), q0, jac=lambda q: 2.0 * As.T @ (As @ q - y),
method='SLSQP', bounds=[(0.0, None), (None, None)],
constraints=[{'type': 'ineq', 'fun': lambda q: yc - Acs @ q, 'jac': lambda q: -Acs}],
options={'maxiter': 200, 'ftol': 1e-14})
vs, mm = (res.x / sc) if np.all(np.isfinite(res.x)) else (0.0, 0.0)
return float(vs), float(mm), float(np.sqrt(np.mean((y - (vs * t - mm * x)) ** 2)))
def finish_under(p, mm):
"""Round P and the slope, then recompute VS under the constraint and round it down."""
p = round(float(p), 3)
mm = round(float(mm), 8)
vs, _, r = solve_under(p, mm)
vs = float(f"{vs * (1.0 - 2e-6):.6g}")
t = (x / 1000.0) ** -p
return vs, p, mm, float(np.sqrt(np.mean((y - (vs * t - mm * x)) ** 2)))
if P is not None:
if under is not None:
return finish_under(P, m if m is not None else solve_under(float(P), None)[1])
vs, mm, r = solve(float(P))
return vs, float(P), mm, r
hi = 5.0 if p_hi is None else float(p_hi)
step = 0.025 if under is None else 0.05
score = (lambda p: solve(p)[2]) if under is None else (lambda p: solve_under(p, m)[2])
while True:
grid = np.linspace(p_lo, hi, int(round((hi - p_lo) / step)) + 1)
best = min(grid, key=score)
if p_hi is not None or best < hi - 1e-9 or hi >= 200.0:
break
hi += 5.0 # the optimum is at the edge of the range: keep going
fine = np.linspace(max(p_lo, best - step), best + step if p_hi is None else min(hi, best + step), 101)
best = min(fine, key=score)
if under is not None:
return finish_under(best, solve_under(best, m)[1])
vs, mm, r = solve(best)
return vs, float(best), mm, r
# ---- Mie theory for a vesicle (thin lipid shell in water): the theoretical P(d) curve of the scattering panel ----
# Bohren & Huffman ch. 8 coefficients for a coated sphere; the core has the index of the medium. scipy.special is
# imported only here, so the rest of the program does not need it.
def _water_index(lam):
return 1.3245 + 3.0e3 / np.asarray(lam, float) ** 2 # Cauchy fit: 1.333 at 589 nm, 1.343 at 400 nm
def _mie_coefs(lam, d, t, dn):
from scipy.special import spherical_jn, spherical_yn
def ric(n, z):
j, yy = spherical_jn(n, z), spherical_yn(n, z)
jp, yp = spherical_jn(n, z, derivative=True), spherical_yn(n, z, derivative=True)
return z * j, j + z * jp, -z * yy, -(yy + z * yp)
lam = np.asarray(lam, float)
nm = _water_index(lam)
k = 2 * np.pi * nm / lam
b = d / 2.0
a = max(b - t, 1e-6)
m2 = (nm + dn) / nm
x, y = k * a, k * b
nmax = int(np.ceil(y.max() + 4 * y.max() ** (1 / 3) + 2))
an, bn = [], []
for n in range(1, nmax + 1):
p1x, d1x, _, _ = ric(n, x)
p2x, d2x, c2x, dc2x = ric(n, m2 * x)
py, dpy, cy, dcy = ric(n, y)
p2y, d2y, c2y, dc2y = ric(n, m2 * y)
xi, dxi = py - 1j * cy, dpy - 1j * dcy
An = (m2 * p2x * d1x - d2x * p1x) / (m2 * c2x * d1x - dc2x * p1x)
Bn = (m2 * p1x * d2x - p2x * d1x) / (m2 * dc2x * p1x - d1x * c2x)
an.append((py * (d2y - An * dc2y) - m2 * dpy * (p2y - An * c2y)) /
(xi * (d2y - An * dc2y) - m2 * dxi * (p2y - An * c2y)))
bn.append((m2 * py * (d2y - Bn * dc2y) - dpy * (p2y - Bn * c2y)) /
(m2 * xi * (d2y - Bn * dc2y) - dxi * (p2y - Bn * c2y)))
return np.array(an), np.array(bn), k
def vesicle_turbidity(lam, d, t=4.5, dn=0.155, acc_deg=10.0):
"""Cross-section (nm^2) of one vesicle (outer diameter d nm, shell t nm, index excess dn) as a spectrophotometer
sees it: total scattering minus the light scattered inside the collection half-angle acc_deg, which still reaches
the detector (0 = true extinction)."""
an, bn, k = _mie_coefs(lam, d, t, dn)
N = an.shape[0]
n = np.arange(1, N + 1)[:, None]
csca = 2 * np.pi / k ** 2 * np.sum((2 * n + 1) * (abs(an) ** 2 + abs(bn) ** 2), axis=0)
if acc_deg <= 0:
return csca
th = np.linspace(0, np.radians(acc_deg), 200)
mu = np.cos(th)
pi_prev, pi_cur = np.zeros_like(mu), np.ones_like(mu)
S1 = np.zeros((len(th), len(k)), complex)
S2 = np.zeros_like(S1)
for i in range(1, N + 1):
if i > 1:
pi_prev, pi_cur = pi_cur, ((2 * i - 1) / (i - 1)) * mu * pi_cur - (i / (i - 1)) * pi_prev
tau = i * mu * pi_cur - (i + 1) * pi_prev
w = (2 * i + 1) / (i * (i + 1))
S1 += w * (np.outer(pi_cur, an[i - 1]) + np.outer(tau, bn[i - 1]))
S2 += w * (np.outer(tau, an[i - 1]) + np.outer(pi_cur, bn[i - 1]))
dC = (abs(S1) ** 2 + abs(S2) ** 2) / (2 * k ** 2)
trapz = getattr(np, 'trapezoid', None) or np.trapz # renamed in numpy 2
return csca - 2 * np.pi * trapz(dC * np.sin(th)[:, None], th, axis=0)
def vesicle_population(lam, d_med, sigma, t=4.5, dn=0.155, acc_deg=10.0, nbin=11):
"""Number-weighted mean cross-section of a log-normal population (median d_med nm, shape sigma)."""
if sigma <= 0:
return vesicle_turbidity(lam, d_med, t, dn, acc_deg)
z = np.linspace(-2.5, 2.5, nbin)
w = np.exp(-z ** 2 / 2)
w /= w.sum()
return sum(wi * vesicle_turbidity(lam, d_med * np.exp(sigma * zi), min(t, d_med * np.exp(sigma * zi) / 2 - 1),
dn, acc_deg) for zi, wi in zip(z, w))
def vesicle_P_curve(diameters, lam, sigma=0.2, t=4.5, dn=0.155, acc_deg=10.0):
"""Exponent P of the pure power law VS*(lam/1000)^-P (no offset, no slope) fitted on the theoretical spectrum of
vesicles of each median diameter, over the wavelengths lam: the same fit that the panel makes on a measurement."""
return np.array([fit_power_law(lam, vesicle_population(lam, d, sigma, t, dn, acc_deg), m=0.0)[1]
for d in diameters])
def vesicle_amplitude(lam, d, sigma, n=1, c_mg_ml=10.0, path_cm=1.0, t_bil=4.5, dn=0.155, rep=7.0, acc_deg=10.0,
mw=760.08, area=0.65, nbin=11):
"""Absorbance (as the spectrophotometer reads it) of a suspension of n-lamellar vesicles at the wavelengths lam,
from the lipid concentration alone: vesicles per nm^3 = lipid molecules per nm^3 / lipids per vesicle, times the
cross-section of one vesicle, times the path. Defaults: POPC (760.08 g/mol, 0.65 nm^2 per lipid), bilayer
4.5 nm, index excess 0.155 (egg lecithin, Khlebtsov et al. 2001). A multilamellar vesicle is one shell of thickness n*rep-(rep-t_bil) (rep = bilayer +
water repeat distance) whose index excess is averaged over the water gaps: dn*n*t_bil/thickness; its lipids are
the sum over the n concentric bilayers. c_mg_ml is the lipid concentration IN THE CUVETTE (mg/mL = g/L)."""
T = n * rep - (rep - t_bil)
dne = dn * n * t_bil / T
if sigma > 0:
z = np.linspace(-2.5, 2.5, nbin)
w = np.exp(-z ** 2 / 2)
w /= w.sum()
diam = d * np.exp(sigma * z)
else:
w, diam = np.array([1.0]), np.array([float(d)])
lipids = sum(wi * sum(4 * np.pi * ((di / 2 - k * rep) ** 2 + (di / 2 - k * rep - t_bil) ** 2) / area
for k in range(n) if di / 2 - k * rep - t_bil > 0) for wi, di in zip(w, diam))
rho = c_mg_ml / mw * 6.022e23 / 1e24 # lipid molecules per nm^3
C = vesicle_population(lam, d, sigma, T, dne, acc_deg, nbin)
return path_cm * 1e7 / np.log(10) * rho / lipids * C
def _ps_dispersion(lam):
"""Wavelength dependence of the refractive index of polystyrene (Cauchy form, approximate coefficients, not verified
against a reference): n(lam) = 1.5718 + 0.0084/lam^2 with lam in um. Only differences are used."""
return 0.0084 / (np.asarray(lam, float) / 1000.0) ** 2
def solid_sphere_amplitude(lam, d, sigma, c_pct_wv=1.0, path_cm=1.0, n589=1.592, density=1.055, acc_deg=10.0,
nbin=11):
"""Absorbance (as the spectrophotometer reads it) of a suspension of solid spheres in water at the wavelengths lam,
for example a polystyrene latex size standard: particles per cm^3 = mass concentration / (density x mean volume),
times the cross-section of one sphere (Mie theory, same collection half-angle as the vesicles), times the path.
d is the median diameter (nm) of a log-normal population of width sigma (about the CV of the size). c_pct_wv is the
solids concentration IN THE CUVETTE in % w/v (g per 100 mL). The index of the particles is n589 at 589 nm with the
dispersion of polystyrene (a different material gets the same dispersion shape: a simplification)."""
lam = np.asarray(lam, float)
dn = n589 + (_ps_dispersion(lam) - _ps_dispersion(589.0)) - _water_index(lam) # index excess, per wavelength
if sigma > 0:
z = np.linspace(-2.5, 2.5, nbin)
w = np.exp(-z ** 2 / 2)
w /= w.sum()
diam = d * np.exp(sigma * z)
else:
w, diam = np.array([1.0]), np.array([float(d)])
volume = float(np.sum(w * np.pi / 6 * diam ** 3)) * 1e-21 # cm^3, number-weighted mean
n_per_cm3 = (c_pct_wv / 100.0) / density / volume
C = vesicle_population(lam, d, sigma, d / 2, dn, acc_deg, nbin) # nm^2 (a 1 nm water core is kept)
return n_per_cm3 * C * 1e-14 * path_cm / np.log(10)
def lipid_mixture(chol_pct=0.0, peg_pct=0.0, mw_popc=760.08, area_popc=0.65, t_popc=4.5, dn_popc=0.155,
mw_chol=386.65, mw_pegl=2805.5, peg_mw=2000.0, peg_leaflets=2):
"""Effective lipid, area and shell parameters of a POPC / cholesterol / PEG-lipid bilayer (mol%), for
vesicle_amplitude(): mean molar mass, mean area per molecule, bilayer thickness and shell index excess.
Assumptions (order-of-magnitude, not fitted): cholesterol condenses the bilayer, -9% of the area per molecule and
+0.4 nm of thickness per 10 mol%; the bilayer index excess is not changed by cholesterol; the PEG chains (volume from
the PEG mass at 1.2 g/cm^3, index excess 0.127 over water) are a thin film of polymer whose scattering adds to the
shell, peg_leaflets leaflets of it (2 when the PEG-lipid was mixed in before the film was made). A corona a few nm
thick is far thinner than the wavelength, so only its total polarisability matters, not its position or profile."""
xc, xp = chol_pct / 100.0, peg_pct / 100.0
if xc < 0 or xp < 0 or xc + xp > 1:
raise ValueError("the mole fractions must be >= 0 and add up to at most 100%")
mw = (1 - xc - xp) * mw_popc + xc * mw_chol + xp * mw_pegl
area = area_popc * (1 - 0.9 * xc)
t = t_popc + 4.0 * xc
film = (peg_mw / 1.2 / 6.022e23 * 1e21) * xp / area # nm of pure PEG per leaflet
dn = dn_popc + peg_leaflets * film * 0.127 / t
return {'mw': mw, 'area': area, 't': t, 'dn': dn, 'peg_film': film}
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, .vspd, .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.help_menu = tk.Menu(self.menu_bar, tearoff=0)
self.help_menu.add_command(label="Check for updates...", command=self.check_for_updates)
self.menu_bar.add_cascade(label="Help", menu=self.help_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)
# Operation buttons on two columns, like the rows above. A grid with uniform columns
# (not one pack row per pair) keeps every button the same width, including the last
# one when the count is odd, which stays on the left half instead of stretching.
btn_frame_ops = tk.Frame(self.f_right_inner, bg='#f0f4f7')
btn_frame_ops.pack(fill=tk.X, padx=10, pady=(2, 0))
btn_frame_ops.columnconfigure((0, 1), weight=1, uniform='ops')
operazioni = [
("Scattering Correction", self.apri_correzione_scattering, '#dce8f5'),
("Normalize Selected", self.apri_normalizzazione, '#f3e5f5'),
("Baseline (FTIR)", self.apri_baseline, '#d7ccc8'),
("Adaptive Baseline", self.apri_baseline_adattiva, '#c8e6c9'),
("Smooth Selected", self.apri_smoothing, '#ffe0b2'),
("Deconvolution", self.apri_deconvoluzione, '#b3e5fc'),
("Trim", self.apri_trim, '#cfd8dc'),
("Derivative", self.apri_derivata, '#d1c4e9'),
("Shift / Scale", self.apri_shift_scale, '#f8bbd0'),
("Spectrum Simulator", self.open_simulator, '#e1f5fe'),
]
for i, (testo, comando, colore) in enumerate(operazioni):
tk.Button(btn_frame_ops, text=testo, command=comando, bg=colore,
font=('Arial', 9)).grid(row=i // 2, column=i % 2, sticky='ew',
padx=2, pady=(2, 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, '{:.6g}')
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}')
# Offset fixed at 0: Auto then fits the pure power law VS*(λ/1000)^-P (with the slope fixed or free) by plain
# least squares. For non-absorbing particles (liposomes) the exponent is then the true slope of the turbidity
# and can be compared with the theoretical P(d) curve; a free offset absorbs part of the curvature.
self._sc_OFF_lock = tk.BooleanVar(value=False)
off_lock_row = tk.Frame(ctrl, bg=bg)
off_lock_row.pack(fill=tk.X, pady=(0, 3))
tk.Label(off_lock_row, text='', width=9, bg=bg).pack(side=tk.LEFT) # alignment
tk.Checkbutton(off_lock_row, text='fix offset = 0', variable=self._sc_OFF_lock, bg=bg,
font=('Consolas', 8),
command=lambda: self._sc_OFF_lock.get() and self._linked_set(self._sc_OFF, 0.0)
).pack(side=tk.LEFT, padx=(10, 0))
# With the offset fixed at 0 the fit is plain least squares; this flag forces the trace under the data anyway
self._sc_UNDER = tk.BooleanVar(value=False)
self._sc_under_cb = tk.Checkbutton(off_lock_row, text='keep under data', variable=self._sc_UNDER, bg=bg,
font=('Consolas', 8), state=tk.DISABLED)
self._sc_under_cb.pack(side=tk.LEFT, padx=(6, 0))
self._sc_OFF_lock.trace_add('write', lambda *_: self._sc_under_cb.config(
state=tk.NORMAL if self._sc_OFF_lock.get() else tk.DISABLED))
# 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 _sc_set_VS(self, value):
"""Set VS (6 significant digits, not decimals: with a large P it is tiny). The slider range and step follow the
value (a power of 10 above twice the value), so that the slider stays usable; the box is free anyway."""
value = float(f"{value:.6g}")
st = self._sc_VS
if value > st['hi'] or (0 < value < 0.05 * st['hi']):
hi = 10.0 ** np.ceil(np.log10(max(2.0 * value, 1e-15)))
self._linked_set_range(st, 0.0, hi, hi / 1000.0)
self._linked_set(st, value)
def _sc_set_P(self, value):
"""Set the exponent P; the slider range grows when the fitted value is above it (P has no upper limit)."""
if value > self._sc_P['hi']:
self._linked_set_range(self._sc_P, self._sc_P['lo'], float(np.ceil(value * 1.2)), 0.01)
self._linked_set(self._sc_P, value)
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: