-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUltrafastSpectroscopyAnalyzer.py
More file actions
2236 lines (1786 loc) · 85.2 KB
/
UltrafastSpectroscopyAnalyzer.py
File metadata and controls
2236 lines (1786 loc) · 85.2 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
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 12 16:25:52 2025
@author: Alejandro
"""
# =============================================================================
# IMPORTS
# =============================================================================
import os
import sys
import time
import numpy as np
import pandas as pd
from scipy.optimize import least_squares
from scipy.interpolate import RegularGridInterpolator, interp1d
import matplotlib.pyplot as plt
from matplotlib import cm, gridspec
from matplotlib.figure import Figure
from matplotlib.colors import BoundaryNorm
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from mpl_toolkits.axes_grid1 import make_axes_locatable
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QDialog, QTabWidget,
QVBoxLayout, QHBoxLayout, QGridLayout, QFormLayout,
QPushButton, QLabel, QLineEdit, QFileDialog, QMessageBox,
QProgressBar, QTableWidget, QTableWidgetItem, QHeaderView,
QComboBox, QDoubleSpinBox, QSpinBox, QSlider, QDial,
QFrame, QGroupBox, QRadioButton, QCheckBox, QSpacerItem, QSizePolicy,QInputDialog
)
from PyQt5.QtGui import QFont, QPalette, QColor, QDesktopServices, QIcon
from PyQt5.QtCore import Qt, QTimer, QUrl, QSize,QEvent
import fit
from core_analysis import fit_t0, load_data, eV_a_nm
from GlobalFitClassGui import GlobalFitPanel
from maps_from_timescans import AppWindow as XFELWindow
STYLESHEET = """
QMainWindow, QWidget {
background-color: #e6e8ed;
color: #222222;
font-family: "Segoe UI", Arial, sans-serif;
font-size: 13px;
}
QLineEdit, QComboBox, QListWidget, QTextEdit, QTableWidget {
background-color: #FFFFFF;
border: 1px solid #C0C0C0;
border-radius: 3px;
padding: 4px;
color: #000000;
}
QComboBox::down-arrow {
image: none;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 5px solid #666666;
width: 0px;
height: 0px;
margin-top: 2px;
}
QComboBox:hover {
border: 1px solid #0078D7;
}
QComboBox::drop-down {
subcontrol-origin: padding;
subcontrol-position: top right;
width: 25px;
border-left: 1px solid #E5E5E5;
background-color: #FAFAFA;
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
QComboBox QAbstractItemView {
border: 1px solid #C0C0C0;
background-color: #FFFFFF;
selection-background-color: #E5F1FB;
selection-color: #000000;
outline: none;
}
QComboBox QAbstractItemView::item {
padding: 8px 10px;
min-height: 25px;
}
QPushButton {
background-color: #E1E1E1;
border: 1px solid #ADADAD;
border-radius: 3px;
padding: 6px 12px;
color: #222222;
}
QPushButton:hover {
background-color: #D4D4D4;
border: 1px solid #0078D7;
}
QPushButton:pressed {
background-color: #C8C8C8;
}
QPushButton#MenuCard {
background-color: #FFFFFF;
color: #2B2B2B;
border: 1px solid #D2D2D2;
border-radius: 6px;
font-size: 15px;
font-weight: bold;
}
QPushButton#MenuCard:hover {
background-color: #F8FBFF;
border: 1px solid #0078D7;
color: #005A9E;
}
QPushButton#MenuCard:pressed {
background-color: #E5F1FB;
border: 1px solid #005499;
}
QPushButton#BtnGreen {
background-color: #6CB66C;
color: white;
border: 1px solid #549A54;
border-radius: 3px;
font-weight: bold;
padding: 8px;
}
QPushButton#BtnGreen:hover {
background-color: #5CA55C;
border: 1px solid #468446;
}
QPushButton#BtnGreen:pressed {
background-color: #4A8C4A;
}
QTabWidget::pane {
border: 1px solid #C0C0C0;
background: #F0F2F5;
top: -1px;
}
QTabBar::tab {
background: #E1E1E1;
border: 1px solid #C0C0C0;
padding: 6px 15px;
margin-right: 2px;
border-top-left-radius: 2px;
border-top-right-radius: 2px;
}
QTabBar::tab:selected {
background: #F0F2F5;
border-bottom-color: #F0F2F5;
font-weight: bold;
}
QTabBar::tab:hover:!selected {
background: #ECECEC;
}
QLabel#MainTitle {
font-size: 24px;
font-weight: bold;
color: #333333;
}
QCheckBox {
spacing: 5px;
}
QCheckBox::indicator {
width: 14px;
height: 14px;
border: 1px solid #ADADAD;
background: #FFFFFF;
border-radius: 2px;
}
QCheckBox::indicator:checked {
background: #6CB66C;
border: 1px solid #549A54;
}
"""
class MainApp(QMainWindow):
"""
Main Window (DASHBOARD)
Serves as the central hub for the Ultrafast Spectroscopy Analyzer suite.
Provides a graphical menu to launch different specialized analysis tools
(FLUPS, TAS, Global Fit, and 2D Mapper).
"""
def __init__(self):
"""Initializes the main dashboard window, sets dimensions, and applies styling."""
super().__init__()
self.setWindowTitle("Ultrafast Spectroscopy Analyzer")
self.setMinimumSize(800, 400)
# Note: Ensure STYLESHEET is defined in your broader scope or imported
# self.setStyleSheet(STYLESHEET)
self.github_url = "https://github.com/AlejandroSerranoCapote/Ultrafast-Spectroscopy-Analyzer"
self.initUI()
def initUI(self):
"""Sets up the UI elements, layouts, headers, buttons, and footer."""
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
main_layout.setContentsMargins(50, 40, 50, 30)
main_layout.setSpacing(1)
# --- 1. Header ---
title = QLabel("SELECT ANALYSIS MODE")
title.setObjectName("MainTitle")
title.setAlignment(Qt.AlignCenter)
subtitle = QLabel("Ultrafast Spectroscopy Processing Tools")
subtitle.setAlignment(Qt.AlignCenter)
main_layout.addWidget(title)
main_layout.addWidget(subtitle)
# --- 2. Buttons Grid ---
grid = QGridLayout()
grid.setSpacing(20)
txt_flups = "FLUPS ANALYZER"
txt_tas = "TAS ANALYZER"
txt_fit = "GLOBAL FIT"
txt_xfel = "2D MAPPER"
# Create buttons
self.btn_flups = self.create_card(txt_flups)
self.btn_tas = self.create_card(txt_tas)
self.btn_fit = self.create_card(txt_fit)
self.btn_xfel = self.create_card(txt_xfel)
# Connect buttons to their respective launcher methods
self.btn_flups.clicked.connect(self.launch_flups)
self.btn_tas.clicked.connect(self.launch_tas)
self.btn_fit.clicked.connect(self.launch_global)
self.btn_xfel.clicked.connect(self.launch_xfel)
# Add buttons to grid
grid.addWidget(self.btn_flups, 0, 0)
grid.addWidget(self.btn_tas, 0, 1)
grid.addWidget(self.btn_fit, 1, 0)
grid.addWidget(self.btn_xfel, 1, 1)
main_layout.addLayout(grid)
main_layout.addSpacing(20)
# --- 3. Footer ---
footer_layout = QVBoxLayout()
footer_layout.setSpacing(10)
self.btn_github = QPushButton("View Source Code on GitHub")
self.btn_github.setCursor(Qt.PointingHandCursor)
self.btn_github.clicked.connect(self.open_github)
h_center = QHBoxLayout()
h_center.addStretch()
h_center.addWidget(self.btn_github)
h_center.addStretch()
footer_layout.addLayout(h_center)
description = QLabel(
"Welcome! This free and open-source software allows you to analyze "
"ultrafast spectroscopy data directly from experiments such as "
"<b>FLUPS</b> (Fluorescence Upconversion Spectroscopy) "
", <b>TAS</b> (Transient Absorption Spectroscopy) "
"and <b>XTAS</b> (X-Ray Transient Absorption Spectroscopy).<br><br>"
"For any questions or feedback, please contact:<br>"
"<b>alejandro.serrano1610@gmail.com</b>"
)
description.setWordWrap(True)
description.setAlignment(Qt.AlignCenter)
footer_layout.addWidget(description)
main_layout.addLayout(footer_layout)
def create_card(self, text):
"""
Creates a stylized, large push button to act as a dashboard card.
Args:
text (str): The label text to display on the button.
Returns:
QPushButton: The configured button widget.
"""
btn = QPushButton(text)
btn.setCursor(Qt.PointingHandCursor)
btn.setMinimumHeight(80)
# Used for targeting in CSS/QSS styling
btn.setObjectName("MenuCard")
return btn
def open_github(self):
"""Opens the repository URL in the user's default web browser."""
if hasattr(self, 'github_url'):
QDesktopServices.openUrl(QUrl(self.github_url))
def open_tool(self, tool_window):
"""
Hides the main menu, opens the selected tool, and ensures the menu
reappears when the child tool window is closed.
Args:
tool_window (QMainWindow or QWidget): The specific tool instance to open.
"""
self.current_tool = tool_window
# Store the original close event of the tool window
original_close = tool_window.closeEvent
def on_close_tool(event):
# Show the main menu again when the tool closes
self.show()
# Execute the tool's standard close event
original_close(event)
# Override the tool's close event with our custom wrapper
tool_window.closeEvent = on_close_tool
tool_window.show()
self.hide()
def launch_xfel(self):
"""Instantiates and launches the XFEL 2D Mapper tool."""
window = XFELWindow()
self.open_tool(window)
def launch_flups(self):
"""Instantiates and launches the FLUPS Analyzer tool."""
window = FLUPSAnalyzer()
self.open_tool(window)
def launch_tas(self):
"""Instantiates and launches the TAS Analyzer tool."""
window = TASAnalyzer()
self.open_tool(window)
def launch_global(self):
"""Instantiates and launches the Global Fit tool."""
window = GlobalFitPanel()
self.open_tool(window)
class FLUPSAnalyzer(QMainWindow):
"""
Main application window for FLUPS (Fluorescence Upconversion Spectroscopy) analysis.
Provides an interactive GUI to load data, visualize 2D maps, fit time-zero (t0)
dispersion curves, and explore kinetics/spectra dynamically.
"""
def __init__(self):
"""Initializes the FLUPS Analyzer UI, layouts, and state variables."""
super().__init__()
self.setWindowTitle("FLUPS Analyzer")
screen = QApplication.primaryScreen()
screen_geom = screen.availableGeometry() # Usable size (excluding taskbar)
w_target = int(screen_geom.width() * 0.85)
h_target = int(screen_geom.height() * 0.90)
x_pos = (screen_geom.width() - w_target) // 2 + screen_geom.left()
y_pos = screen_geom.top() + 35
self.setGeometry(x_pos, y_pos, w_target, h_target)
self.setMinimumSize(1000, 700)
# --- State variables ---
self.WL = None
self.TD = None
self.data = None
self.file_path = None
self.data_corrected = None
self.result_fit = None
self.use_discrete_levels = True # Change to False for a continuous map
self.bg_cache = None
self.cid_draw = None
self._is_drawing = False
# --- UI Widgets ---
self.btn_load = QPushButton("Load CSV")
self.btn_load.setObjectName("BtnGreen")
self.btn_load.clicked.connect(self.load_file)
self.btn_plot = QPushButton("Show Map")
self.btn_plot.clicked.connect(self.plot_map)
self.btn_plot.setEnabled(False)
self.btn_remove_fringe = QPushButton("Remove Pump Fringe")
self.btn_remove_fringe.clicked.connect(self.remove_pump_fringe)
self.btn_remove_fringe.setEnabled(True)
self.label_status = QLabel("No file loaded")
self.btn_select = QPushButton("Select t₀ points")
self.btn_select.clicked.connect(self.enable_point_selection)
self.btn_select.setEnabled(False)
self.btn_fit = QPushButton("Fit t₀")
self.btn_fit.clicked.connect(self.fit_t0_points)
self.btn_fit.setEnabled(False)
self.btn_show_corr = QPushButton("Show Corrected Map")
self.btn_show_corr.clicked.connect(self.toggle_corrected_map)
self.btn_show_corr.setEnabled(False)
self.showing_corrected = False
self.btn_global_fit = QPushButton("Global Fit")
self.btn_global_fit.clicked.connect(self.open_global_fit)
self.btn_global_fit.setObjectName("BtnGreen")
self._last_move_time = 0.0
self._move_min_interval = 1.0 / 25.0
self.figure = Figure(figsize=(12, 8))
self.gs = gridspec.GridSpec(2, 2, height_ratios=[3, 1], width_ratios=[1, 1], hspace=0.25, wspace=0.35)
self.ax_map = self.figure.add_subplot(self.gs[0, :])
self.ax_time_small = self.figure.add_subplot(self.gs[1, 0])
self.ax_spec_small = self.figure.add_subplot(self.gs[1, 1])
self.canvas = FigureCanvas(self.figure)
self.cid_draw = self.canvas.mpl_connect('draw_event', self.on_draw)
self.cid_move = self.canvas.mpl_connect("motion_notify_event", self.on_move_map)
self.clicked_points = []
self.cid_click = None
self.pcm = None
self.cbar = None
self.marker_map = None
self.vline_map = None
self.hline_map = None
self.fit_line_artist = None
self._init_small_plots()
# --- Main window layout ---
layout = QVBoxLayout()
# Top Layout (Buttons)
top_layout = QHBoxLayout()
top_layout.addWidget(self.btn_load)
top_layout.addWidget(self.label_status)
top_layout.addWidget(self.btn_plot)
top_layout.addWidget(self.btn_select)
top_layout.addWidget(self.btn_fit)
top_layout.addWidget(self.btn_show_corr)
top_layout.addWidget(self.btn_remove_fringe)
top_layout.addWidget(self.btn_global_fit)
layout.addLayout(top_layout)
# Add Canvas
layout.addWidget(self.canvas)
# ===================================================================
# BOTTOM BLOCK: CENTERED CONTROLS
# ===================================================================
# Layout holding all controls (TAS will inject here)
self.bottom_controls_layout = QHBoxLayout()
self.bottom_controls_layout.setSpacing(25)
# 1. --- Delay ---
delay_layout = QVBoxLayout()
delay_layout.setSpacing(5)
delay_layout.addWidget(QLabel("Delay min (ps):"))
self.xmin_edit = QLineEdit("-1")
self.xmin_edit.setFixedWidth(50)
delay_layout.addWidget(self.xmin_edit)
delay_layout.addWidget(QLabel("Delay max (ps):"))
self.xmax_edit = QLineEdit("3")
self.xmax_edit.setFixedWidth(50)
delay_layout.addWidget(self.xmax_edit)
self.btn_apply_xlim = QPushButton("Apply X limits")
self.btn_apply_xlim.setFixedWidth(120)
self.btn_apply_xlim.clicked.connect(self.apply_x_limits)
delay_layout.addWidget(self.btn_apply_xlim)
delay_layout.addStretch() # Push upwards
# 2. --- Wavelength ---
wl_layout = QVBoxLayout()
wl_layout.setSpacing(5)
# wl min
wl_min_layout = QHBoxLayout()
wl_min_label = QLabel("λ min:")
self.lbl_min_value = QLabel("400")
self.lbl_min_value.setCursor(Qt.PointingHandCursor)
self.lbl_min_value.setToolTip("Click to enter exact value")
self.lbl_min_value.installEventFilter(self) # Make the window listen to this label's events
self.slider_min = QSlider(Qt.Horizontal)
self.slider_min.setMinimumWidth(200)
self.slider_min.setMinimum(400)
self.slider_min.setMaximum(800)
self.slider_min.setValue(500)
self.slider_min.valueChanged.connect(self.update_wl_range)
wl_min_layout.addWidget(wl_min_label)
wl_min_layout.addWidget(self.slider_min)
wl_min_layout.addWidget(self.lbl_min_value)
wl_layout.addLayout(wl_min_layout)
# wlmax
wl_max_layout = QHBoxLayout()
wl_max_label = QLabel("λ max:")
self.lbl_max_value = QLabel("800")
self.lbl_max_value.setCursor(Qt.PointingHandCursor)
self.lbl_max_value.setToolTip("Click to enter exact value")
self.lbl_max_value.installEventFilter(self) # Make the window listen to this label's events
self.slider_max = QSlider(Qt.Horizontal)
self.slider_max.setMinimumWidth(200)
self.slider_max.setMinimum(400)
self.slider_max.setMaximum(800)
self.slider_max.setValue(700)
self.slider_max.valueChanged.connect(self.update_wl_range)
wl_max_layout.addWidget(wl_max_label)
wl_max_layout.addWidget(self.slider_max)
wl_max_layout.addWidget(self.lbl_max_value)
wl_layout.addLayout(wl_max_layout)
wl_layout.addStretch() # Push upwards
# 3. --- Dial Levels ---
dial_layout = QVBoxLayout()
self.n_levels = 30
self.dial_levels = QDial()
self.dial_levels.setRange(2, 100)
self.dial_levels.setValue(self.n_levels)
self.dial_levels.setNotchesVisible(True)
self.dial_levels.setWrapping(False)
self.dial_levels.setFixedSize(80, 80)
self.dial_levels.valueChanged.connect(self.update_n_levels)
self.lbl_dial = QLabel(f"{self.n_levels}")
self.lbl_dial.setAlignment(Qt.AlignCenter)
dial_layout.addWidget(self.dial_levels, alignment=Qt.AlignCenter)
dial_layout.addWidget(self.lbl_dial, alignment=Qt.AlignCenter)
dial_layout.addStretch()
# 4. --- Combo Box (t0 Model) ---
combo_layout = QVBoxLayout()
lbl_model = QLabel("Chirp model fit ( t<sub>0</sub> ):")
self.combo_model = QComboBox()
self.combo_model.addItems(["Polynomial", "Non linear"])
self.combo_model.setCurrentIndex(1)
combo_layout.addWidget(lbl_model)
combo_layout.addWidget(self.combo_model)
combo_layout.addStretch()
# 5. --- Y-Axis Scale ---
scale_layout = QVBoxLayout()
scale_layout.setSpacing(5)
scale_layout.addWidget(QLabel("Y-Axis Scale:"))
self.combo_scale = QComboBox()
self.combo_scale.addItems(["SymLog", "Linear"])
self.combo_scale.setCurrentIndex(0) # SymLog by default
scale_layout.addWidget(self.combo_scale)
self.lbl_linthresh = QLabel("Linthresh (ps):")
self.spin_linthresh = QDoubleSpinBox()
self.spin_linthresh.setDecimals(2)
self.spin_linthresh.setRange(0.01, 1000.0) # Wide range to play with
self.spin_linthresh.setValue(1.0) # Default value
self.spin_linthresh.setSingleStep(0.5)
scale_layout.addWidget(self.lbl_linthresh)
scale_layout.addWidget(self.spin_linthresh)
scale_layout.addStretch()
# Connect to the function that updates the plot instantly
self.combo_scale.currentIndexChanged.connect(self.apply_y_scale)
self.spin_linthresh.valueChanged.connect(self.apply_y_scale)
# --- Pack everything into the controls layout ---
self.bottom_controls_layout.addLayout(delay_layout)
self.bottom_controls_layout.addLayout(wl_layout)
self.bottom_controls_layout.addLayout(dial_layout)
# Insert the new control here:
self.bottom_controls_layout.addLayout(scale_layout)
self.bottom_controls_layout.addLayout(combo_layout)
center_bottom_layout = QHBoxLayout()
center_bottom_layout.addStretch() # Left stretch
center_bottom_layout.addLayout(self.bottom_controls_layout)
center_bottom_layout.addStretch() # Right stretch
layout.addLayout(center_bottom_layout)
self.bottom_controls_layout.setSpacing(60)
self.bottom_controls_layout.setContentsMargins(60, 10, 60, 0)
layout.addLayout(self.bottom_controls_layout)
# Set central widget
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
# --- Color styling for main axes and colorbars ---
self.ax_map.tick_params(colors="black")
self.ax_map.xaxis.label.set_color("black")
self.ax_map.yaxis.label.set_color("black")
self.ax_map.title.set_color("black")
for spine in self.ax_map.spines.values():
spine.set_color("black")
if self.cbar is not None:
self.cbar.ax.yaxis.set_tick_params(color="black", labelcolor="black")
self.cbar.ax.yaxis.label.set_color("black")
for spine in self.cbar.ax.spines.values():
spine.set_color("black")
for ax in [self.ax_time_small, self.ax_spec_small]:
ax.tick_params(colors="black")
ax.xaxis.label.set_color("black")
ax.yaxis.label.set_color("black")
ax.title.set_color("black")
def on_draw(self, event):
"""
Captures the background for Blitting with anti-recursion protection.
Args:
event: The matplotlib draw event.
"""
if event is not None and event.canvas != self.canvas:
return
if self._is_drawing:
return
self._is_drawing = True
try:
self.bg_cache = self.canvas.copy_from_bbox(self.figure.bbox)
self.draw_animated_artists()
finally:
self._is_drawing = False
def apply_y_scale(self):
"""Applies the selected Y-axis scale and updates the plot instantly."""
is_symlog = self.combo_scale.currentText() == "SymLog"
self.lbl_linthresh.setVisible(is_symlog)
self.spin_linthresh.setVisible(is_symlog)
# If the map doesn't exist yet, do nothing
if not hasattr(self, 'ax_map') or self.data is None:
return
# Apply scale
if is_symlog:
# Reads the exact value from the spinbox to set where the logarithmic part begins
self.ax_map.set_yscale("symlog", linthresh=self.spin_linthresh.value())
self.ax_map.set_ylabel("Delay (ps) - SymLog")
else:
self.ax_map.set_yscale("linear")
self.ax_map.set_ylabel("Delay (ps) - Linear")
# Redraw only what is necessary
self.canvas.draw_idle()
def draw_animated_artists(self):
"""Draws only the animated (moving) elements over the cached background."""
# Map Lines
if self.vline_map: self.ax_map.draw_artist(self.vline_map)
if self.hline_map: self.ax_map.draw_artist(self.hline_map)
if self.marker_map: self.ax_map.draw_artist(self.marker_map)
# Small Plot Lines
if self.cut_time_small: self.ax_time_small.draw_artist(self.cut_time_small)
if self.vline_time_small: self.ax_time_small.draw_artist(self.vline_time_small)
if self.cut_spec_small: self.ax_spec_small.draw_artist(self.cut_spec_small)
def eventFilter(self, obj, event):
"""
Intercepts specific events from monitored widgets.
Args:
obj: The QObject receiving the event.
event: The QEvent object.
Returns:
bool: True if event was handled, False otherwise.
"""
if event.type() == QEvent.MouseButtonPress and event.button() == Qt.LeftButton:
if obj == self.lbl_min_value:
self.prompt_exact_wl_min()
return True # Indicate that the event has already been processed
elif obj == self.lbl_max_value:
self.prompt_exact_wl_max()
return True
# Let the rest of the events process normally
return super().eventFilter(obj, event)
def prompt_exact_wl_min(self):
"""Opens a dialog to precisely set the minimum λ value."""
if getattr(self, "WL", None) is None:
return # Prevents errors if no data is loaded
try:
current_val = float(self.lbl_min_value.text().replace(" nm", ""))
except ValueError:
current_val = float(np.min(self.WL))
val, ok = QInputDialog.getDouble(
self, "Exact Min Wavelength", "Enter wavelength (nm):",
value=current_val, decimals=2, min=np.min(self.WL), max=np.max(self.WL)
)
if ok:
idx = int(np.argmin(np.abs(self.WL - val)))
self.slider_min.setValue(idx)
def prompt_exact_wl_max(self):
"""Opens a dialog to precisely set the maximum λ value."""
if getattr(self, "WL", None) is None:
return
try:
current_val = float(self.lbl_max_value.text().replace(" nm", ""))
except ValueError:
current_val = float(np.max(self.WL))
val, ok = QInputDialog.getDouble(
self, "Exact Max Wavelength", "Enter wavelength (nm):",
value=current_val, decimals=2, min=np.min(self.WL), max=np.max(self.WL)
)
if ok:
idx = int(np.argmin(np.abs(self.WL - val)))
self.slider_max.setValue(idx)
def open_global_fit(self):
"""Opens the Global Fit panel dialog."""
dlg = GlobalFitPanel(self)
dlg.exec_()
def _init_small_plots(self):
"""Initializes the empty state and labels of the subplots."""
self.ax_time_small.set_xlabel("Delay (ps)")
self.ax_time_small.set_ylabel("ΔA")
self.ax_time_small.set_title("Kinetics (cursor)")
self.ax_time_small.set_xlim(-1, 3)
self.cut_time_small, = self.ax_time_small.plot([], [], '-', lw=1.5)
self.vline_time_small = self.ax_time_small.axvline(
x=0, color='k', ls='--', lw=1, visible=False, zorder=5
)
self.ax_spec_small.set_xlabel("Wavelength (nm)")
self.ax_spec_small.set_ylabel("ΔA")
self.ax_spec_small.set_title("Spectra (cursor)")
self.cut_spec_small, = self.ax_spec_small.plot([], [], '-', lw=1.5)
def apply_x_limits(self):
"""Applies the X-axis (Delay) limits entered by the user."""
try:
x_min = float(self.xmin_edit.text())
x_max = float(self.xmax_edit.text())
if x_min >= x_max:
raise ValueError("x_min debe ser menor que x_max")
self.ax_time_small.set_xlim(x_min, x_max)
self.canvas.draw_idle()
except ValueError:
QMessageBox.warning(self, "Error", "Introduce valores numéricos válidos para los límites de Delay.")
def remove_pump_fringe(self):
"""Removes the pump fringe directly from the current data."""
if self.data is None:
QMessageBox.warning(self, "No data", "Load data first.")
return
sWl, ok1 = QInputDialog.getDouble(
self, "Pump wavelength", "Pump wavelength (nm):", min=0.0
)
if not ok1:
return
wisWL, ok2 = QInputDialog.getDouble(
self, "Width of scattering", "Width of pump scattering (nm):", min=0.0
)
if not ok2:
return
if getattr(self, "showing_corrected", False) and self.data_corrected is not None:
data_target = self.data_corrected
else:
data_target = self.data
# Fringe indices
posl1 = np.argmin(np.abs(self.WL - (sWl - wisWL / 2)))
posl2 = np.argmin(np.abs(self.WL - (sWl + wisWL / 2)))
# Modify data directly
data_target[posl1:posl2, :] = 1e-10
# Refresh map to see the effect
if getattr(self, "showing_corrected", False):
self.toggle_corrected_map() # re-show corrected map
else:
self.plot_map() # re-show original map
QMessageBox.information(
self, "Pump fringe removed",
f"Fringe at {sWl} ± {wisWL/2} nm has been set to near-zero."
)
def load_file(self):
"""Loads the data file, cleans it, and automatically normalizes ΔA."""
# Select CSV or data.txt
file_path, _ = QFileDialog.getOpenFileName(
self, "Select CSV or Data File", "",
"CSV Files (*.csv);;Data Files (*.txt *.dat)"
)
if not file_path:
return
try:
# Load data
if file_path.endswith(".csv"):
data, wl, td = load_data(auto_path=file_path)
else:
wl_path, _ = QFileDialog.getOpenFileName(self, "Select Wavelength File", "", "Text Files (*.txt)")
td_path, _ = QFileDialog.getOpenFileName(self, "Select Delay File", "", "Text Files (*.txt)")
if not wl_path or not td_path:
QMessageBox.warning(self, "Files missing", "You must select both WL and TD files.")
return
data, wl, td = load_data(data_path=file_path, wl_path=wl_path, td_path=td_path)
# --- REMOVE DUPLICATES AND SORT (FLUPS) ---
wl, idx_wl = np.unique(wl, return_index=True)
td, idx_td = np.unique(td, return_index=True)
# Crop the data matrix to match the clean indices
data = data[idx_wl, :][:, idx_td]
# --- Normalization ---
# =============================================================================
# NORMALIZATION DATA IN FLUPS
# =============================================================================
max_val = np.nanmax(np.abs(data))
if max_val != 0:
data = data / max_val
self.WL, self.TD, self.data = wl, td, data
self.file_path = file_path
# Save the CSV path and base directory
self.csv_path = file_path
self.base_dir = os.path.dirname(file_path)
self.label_status.setText(f"Loaded : {os.path.basename(file_path)}")
self.btn_plot.setEnabled(True)
self.btn_select.setEnabled(True)
self.btn_fit.setEnabled(True)
# Update sliders
nwl = len(wl)
self.slider_min.blockSignals(True)
self.slider_max.blockSignals(True)
self.slider_min.setMinimum(0)
self.slider_min.setMaximum(nwl - 1)
self.slider_max.setMinimum(0)
self.slider_max.setMaximum(nwl - 1)
self.slider_min.setValue(0)
self.slider_max.setValue(nwl - 1)
self.slider_min.blockSignals(False)
self.slider_max.blockSignals(False)
self.update_wl_range()
except Exception as e:
QMessageBox.critical(self, "Error loading file", str(e))
def apply_wl_range(self):
"""Applies the current slider values to the console printout."""
min_val = self.slider_min.value()
max_val = self.slider_max.value()
print(f"Aplicando λ min={min_val}, λ max={max_val}")
def _plot_discrete_map(self, ax, WL, TD, data, n_levels=5, cmap='jet', shading='auto', vmin=None, vmax=None):
"""
Draws a contourf-style map using a discrete pcolormesh.
Args:
ax: The matplotlib axis object.
WL: Wavelength array.
TD: Time Delay array.
data: The 2D data matrix.
n_levels: Number of discrete color levels.
cmap: The colormap string.
shading: Shading style for pcolormesh.
vmin: Minimum value for the color scale.
vmax: Maximum value for the color scale.
Returns:
QuadMesh: The created pcolormesh object.
"""
if vmin is None:
vmin = np.nanmin(data)
if vmax is None:
vmax = np.nanmax(data)
levels = np.linspace(vmin, vmax, n_levels)
norm = BoundaryNorm(levels, ncolors=plt.get_cmap(cmap).N, clip=True)
pcm = ax.pcolormesh(WL, TD, data.T, shading=shading, cmap=cmap, norm=norm)
return pcm
def update_n_levels(self, value):
"""Updates the number of levels for the discrete map and redraws it, respecting the visible range."""
self.n_levels = value
self.lbl_dial.setText(f"{value} levels") # update text
if self.data is None:
return
# Determine which data and WL to use (respecting current visible range)
if hasattr(self, "WL_visible") and self.WL_visible is not None:
WL_used = self.WL_visible
if getattr(self, "showing_corrected", False):
# if we are showing the corrected map
wl_min = self.WL_visible[0]
wl_max = self.WL_visible[-1]
wl_min_idx = np.argmin(np.abs(self.WL - wl_min))
wl_max_idx = np.argmin(np.abs(self.WL - wl_max)) + 1
data_used = self.data_corrected[wl_min_idx:wl_max_idx, :]
else:
data_used = self.data_visible
else:
WL_used = self.WL
data_used = self.data_corrected if getattr(self, "showing_corrected", False) else self.data
# Redraw map directly (without resetting)
self.ax_map.clear()
if self.cbar:
try: self.cbar.remove()
except: pass
self.cbar = None
self.pcm = self._plot_discrete_map(
self.ax_map,
WL_used,
self.TD,
data_used,
n_levels=self.n_levels,
shading="auto",
vmin=-1,
vmax=1
)
self.ax_map.set_xlabel("Wavelength (nm)")
self.ax_map.set_ylabel("Delay (ps)")
self.ax_map.set_title("ΔA Map")
self.apply_y_scale()