Repository navigation
Expand file tree
/
Copy pathtgs_gui.py
More file actions
6881 lines (5709 loc) · 316 KB
/
Copy pathtgs_gui.py
File metadata and controls
6881 lines (5709 loc) · 316 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
#!/usr/bin/env python3
"""
PyTGS Graphical Interface with configuration editing and multi-scope support
"""
import sys
import os
import threading
import queue
import logging
import yaml
import shutil
import json
import numpy as np
import struct
from pathlib import Path
from datetime import datetime
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib
# Set backend before importing pyplot
try:
# Check if we're in a GUI environment
if sys.platform == 'win32':
# On Windows, try to use TkAgg but with warnings suppressed
pass # Keep default TkAgg for GUI
else:
matplotlib.use('Agg')
except:
pass
import matplotlib.pyplot as plt
matplotlib.rcParams['figure.max_open_warning'] = 0
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="matplotlib")
warnings.filterwarnings("ignore", category=UserWarning, module="pyvisa_py")
import ttkbootstrap as tb
import time
#import gpib_ctypes
# Check if we're using GPIB address
scope_addr = os.environ.get('SCOPE_ADDRESS', '')
if 'GPIB' not in scope_addr:
# Suppress the GPIB warning since we're not using GPIB
warnings.filterwarnings("ignore", category=UserWarning, module="gpib_ctypes")
# Import PyTGS modules
from src.analysis.signal_process import process_signal
from src.analysis.fft import fft
from src.analysis.lorentzian import lorentzian_fit
from src.core.path import Paths
# Suppress pyvisa_py logging at the source
os.environ['PYVISA_LOGGING'] = 'CRITICAL'
os.environ['PYVISA_PY_LOGGING'] = 'CRITICAL'
# Set up logging to suppress pyvisa_py completely
logging.getLogger('pyvisa').setLevel(logging.CRITICAL)
logging.getLogger('pyvisa_py').setLevel(logging.CRITICAL)
def get_resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
# Redirect logging to a queue for GUI display
log_queue = queue.Queue()
class QueueHandler(logging.Handler):
def __init__(self, queue):
super().__init__()
self.queue = queue
def emit(self, record):
# Only show INFO and above in GUI (no DEBUG)
if record.levelno >= logging.INFO:
self.queue.put(self.format(record))
class ToolTip:
"""Create tooltips for widgets with automatic positioning to stay on screen"""
def __init__(self, widget, text):
self.widget = widget
self.text = text
self.tip_window = None
widget.bind('<Enter>', self.enter)
widget.bind('<Leave>', self.leave)
def enter(self, event=None):
root = self.widget.winfo_toplevel()
# Get cursor position using the root window's method
# This should give coordinates relative to the root window's screen
cursor_x = root.winfo_pointerx()
cursor_y = root.winfo_pointery()
self.tip_window = tw = tk.Toplevel(root)
tw.wm_overrideredirect(True)
label = tk.Label(tw, text=self.text, justify=tk.LEFT,
background="#ffffe0", foreground="#000000",
relief=tk.SOLID, borderwidth=1,
font=("Arial", 9), wraplength=400)
label.pack()
tw.update_idletasks()
tip_width = tw.winfo_width()
tip_height = tw.winfo_height()
offset_x = 15
offset_y = 20
pos_x = cursor_x + offset_x
pos_y = cursor_y + offset_y
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
if pos_x + tip_width > screen_width:
pos_x = cursor_x - tip_width - offset_x
if pos_x < 0:
pos_x = 5
if pos_y + tip_height > screen_height:
pos_y = cursor_y - tip_height - offset_y
if pos_y < 0:
pos_y = 5
tw.wm_geometry(f"+{int(pos_x)}+{int(pos_y)}")
def leave(self, event=None):
if self.tip_window:
self.tip_window.destroy()
self.tip_window = None
class TGSApp:
VERSION = "1.0.1"
# Scope type constants
SCOPE_RIGOL = "Rigol"
SCOPE_LECROY = "LeCroy"
def __init__(self, root):
self.root = root
self.root.title("PyTGS v" + self.VERSION + " - Transient Grating Analyser")
self.root.geometry("1700x1000")
# Set theme to match system
self.setup_theme()
# Initialize basic attributes BEFORE loading config that might log
self.config = None
self.calibrated_spacing = None
# File storage - initialize early
self.pos_files = []
self.neg_files = []
self.calib_pos_file = ''
self.calib_neg_file = ''
self.baseline_pos_file = ''
self.baseline_neg_file = ''
self.file_to_fit_plot_data = {}
self.file_to_plot_path = {}
self.file_to_fit_params = {}
self.current_results_log_path = None
self.shutdown_flag = False
self.stop_batch = False
# Setup logging
self.setup_logging()
#Setup batch process file tracking
self.processed_files = set()
# Load fitting configuration
self.config = self.load_config()
# Scope settings initialisation
self.orig_scale = None
self.orig_offset = None
self.scope_connection_string = None
# Current scope type (default Rigol)
self.current_scope_type = self.SCOPE_RIGOL
# Build GUI
self.create_widgets()
self.setup_preference_saving()
self.root.bind('<Configure>', self.on_window_resize)
self.resize_timer = None
self.root.after(500, self.refresh_scope_addresses)
self.load_preferences()
self.continuous_acq_var.set(False)
# Bind closing event
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.running_job = None
# Show placeholder text in results table (now after treeview is created)
self.clear_results_table()
# Time tracking for batch processing
self.batch_start_time = None
self.first_run_duration = None
self.current_run_start_time = None
# Track scope connection state
self.scope_connected = False
# Test connection to oscilloscope at startup
self.test_scope_connection()
print(f"[INIT] PyTGS v{self.VERSION} starting...")
self.memory_monitor_active = True
self.start_memory_monitor()
def start_memory_monitor(self):
"""Start a background thread to monitor memory usage"""
def monitor_thread():
import time
while self.memory_monitor_active:
try:
mem = self.get_memory_usage()
if mem and mem['rss'] > 2000: # Warning if > 2GB
print(f"[WARNING] Memory usage high: {mem['rss']:.1f}MB")
self.log_message(f"Memory usage high: {mem['rss']:.1f}MB", logging.WARNING)
# Force garbage collection
gc.collect()
except:
pass
time.sleep(30) # Check every 30 seconds
thread = threading.Thread(target=monitor_thread, daemon=True)
thread.start()
def create_button(self, parent, text, command=None, state='normal', height=None, bg_color=None, fg_color=None):
"""Create a styled button with consistent hover effects"""
# Default padding - reduced height by setting smaller pady
padx_val = 12
pady_val = 3 if height == 'small' else 6
# Use custom colors if provided, otherwise use theme defaults
button_bg = bg_color if bg_color else self.button_color
button_fg = fg_color if fg_color else self.fg_color
# For red buttons, use a darker hover color
if bg_color == '#d32f2f':
hover_bg = '#b71c1c' # Darker red for hover
else:
hover_bg = self.accent_hover
btn = tk.Button(parent, text=text,
bg=button_bg, fg=button_fg,
activebackground=hover_bg,
activeforeground=button_fg,
relief=tk.FLAT, bd=0,
padx=padx_val, pady=pady_val,
font=("Arial", 9 if height == 'small' else 10, 'bold' if bg_color else 'normal'),
cursor="hand2",
state=state)
# Only set the command once
if command and state == 'normal':
btn.config(command=command)
# Add hover effects
def on_enter(e):
if state == 'normal':
btn.config(bg=hover_bg)
def on_leave(e):
if state == 'normal':
btn.config(bg=button_bg)
btn.bind("<Enter>", on_enter)
btn.bind("<Leave>", on_leave)
# Configure the button to expand and fill the available space
btn.config(highlightthickness=0)
return btn
def setup_theme(self):
"""Configure modern dark theme - remove all borders"""
# Colors
self.bg_color = '#1e1e1e'
self.panel_bg = '#2d2d2d'
self.fg_color = '#e0e0e0'
self.select_color = '#404040'
self.button_color = '#3c3c3c'
self.entry_bg = '#3c3c3c'
self.accent_hover = '#005a9e'
self.root.configure(background=self.bg_color)
style = ttk.Style()
# Remove borders from ttk widgets
style.configure("TFrame", borderwidth=0, relief="flat")
style.configure("TLabelframe", borderwidth=0, relief="flat")
style.configure("TLabelframe.Label", borderwidth=0, relief="flat")
style.configure("TPanedwindow", borderwidth=0, relief="flat")
style.configure("TPanedwindow.Sash", borderwidth=0)
# Treeview
style.configure("Treeview",
background=self.entry_bg,
foreground=self.fg_color,
fieldbackground=self.entry_bg)
style.configure("Treeview.Heading",
background=self.button_color,
foreground=self.fg_color)
style.map('Treeview',
background=[('selected', self.select_color)])
style.configure('Panel.TFrame', background=self.panel_bg)
def on_window_resize(self, event):
"""Maintain sash position proportion when window is resized (debounced)"""
# Debounce: wait for resize to finish before updating
if self.resize_timer:
self.root.after_cancel(self.resize_timer)
# Schedule the actual resize handling after a short delay
self.resize_timer = self.root.after(100, lambda: self._handle_resize(event))
def _handle_resize(self, event):
"""Actually handle the resize after debouncing"""
# Only update sash positions
if hasattr(self, 'paned_window') and event.widget == self.root:
total_width = self.root.winfo_width()
if total_width > 100:
# Maintain proportions: Left 35%, Middle 25%, Right 40%
try:
self.paned_window.sashpos(0, int(total_width * 0.30))
self.paned_window.sashpos(1, int(total_width * 0.60))
except:
pass
if hasattr(self, 'right_paned') and event.widget == self.root:
total_height = self.root.winfo_height()
if total_height > 100:
new_sash_pos = int(total_height * 0.4)
try:
self.right_paned.sashpos(0, new_sash_pos)
except:
pass
if hasattr(self, 'right_paned') and event.widget == self.root:
total_height = self.root.winfo_height()
if total_height > 100:
new_sash_pos = int(total_height * 0.4)
try:
self.right_paned.sashpos(0, new_sash_pos)
except:
pass
def set_initial_sash(self):
"""Set initial divider position for 3 panels"""
try:
total_width = self.root.winfo_width()
if total_width > 100:
self.paned_window.sashpos(0, int(total_width * 0.30)) # Left panel wider
self.paned_window.sashpos(1, int(total_width * 0.60)) # Middle + Left = 60% (so middle is 25%)
if hasattr(self, 'right_paned') and self.right_paned.winfo_exists():
total_height = self.root.winfo_height()
if total_height > 100:
self.right_paned.sashpos(0, int(total_height * 0.4))
except:
pass
def set_ui_state(self, state):
"""Simple UI state management - only disable run button during batch"""
self.current_ui_state = state
# Only disable the run button during batch processing to prevent re-run
if state == 'batch_processing':
if hasattr(self, 'run_button'):
self.run_button.config(state='disabled')
else:
if hasattr(self, 'run_button'):
self.run_button.config(state='normal')
def load_config(self):
"""Load config.yaml from the current directory or create default."""
# Add custom YAML constructor for numpy scalars
def construct_numpy_scalar(self, node):
import numpy as np
value = self.construct_scalar(node)
try:
# Try to convert to float first
return float(value)
except ValueError:
return value
# Add constructor for numpy array tag
def construct_numpy_array(self, node):
import numpy as np
value = self.construct_sequence(node)
# Convert numpy scalars to Python types
return [float(x) if hasattr(x, 'dtype') else x for x in value]
# Add the constructors to yaml
try:
from yaml import SafeLoader, add_constructor
add_constructor('tag:yaml.org,2002:python/object/apply:numpy._core.multiarray.scalar', construct_numpy_scalar)
add_constructor('tag:yaml.org,2002:python/object/apply:numpy.core.multiarray.scalar', construct_numpy_scalar)
add_constructor('tag:yaml.org,2002:python/object/apply:numpy.ndarray', construct_numpy_array)
except:
pass
# Check if running as executable
if getattr(sys, 'frozen', False):
# Running as compiled executable - look for config in the same directory as the exe
config_path = Path(os.path.dirname(sys.executable)) / "config.yaml"
else:
# Running as script
config_path = Path("config.yaml")
if config_path.exists():
try:
with open(config_path, 'r') as f:
config_data = yaml.safe_load(f)
# Clean any numpy types from the config recursively
config_data = self._clean_numpy_types(config_data)
return config_data
except Exception as e:
self.log_message(f"Error loading config, creating new one: {str(e)}", logging.WARNING)
# If config is corrupted, create backup and new default
if config_path.exists():
backup_path = config_path.with_suffix('.yaml.bak')
try:
shutil.copy(config_path, backup_path)
self.log_message(f"Backed up corrupted config to {backup_path}", logging.WARNING)
except:
pass
return self._create_default_config()
else:
return self._create_default_config()
def _clean_numpy_types(self, obj):
"""Recursively convert numpy types to Python native types"""
import numpy as np
if isinstance(obj, dict):
return {key: self._clean_numpy_types(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [self._clean_numpy_types(item) for item in obj]
elif isinstance(obj, tuple):
return tuple(self._clean_numpy_types(item) for item in obj)
elif isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
elif isinstance(obj, np.bool_):
return bool(obj)
else:
return obj
def _create_default_config(self):
"""Create default configuration dictionary"""
return {
"path": "example",
"study_names": None,
"idxs": None,
"signal_process": {
"heterodyne": "di-homodyne",
"null_point": 2,
"initial_samples": 50,
"baseline_correction": {"enabled": False, "pos": None, "neg": None}
},
"fft": {"signal_proportion": 1.0, "use_derivative": True, "analysis_type": "psd"},
"lorentzian": {
"signal_proportion": 1,
"frequency_bounds": [0.1, 0.9],
"dc_filter_range": [0, 50000],
"bimodal_fit": False,
"use_skewed_super_lorentzian": False
},
"tgs": {"grating_spacing": 3.5276, "signal_proportion": 1, "maxfev": 1000000},
"plot": {
"signal_process": True,
"fft_lorentzian": True,
"tgs": True,
"settings": {"num_points": None}
}
}
def save_config(self):
"""Save current config to config.yaml."""
# Clean numpy types before saving
cleaned_config = self._clean_numpy_types(self.config)
# Save to the appropriate location
if getattr(sys, 'frozen', False):
config_path = Path(os.path.dirname(sys.executable)) / "config.yaml"
else:
config_path = Path("config.yaml")
with open(config_path, 'w') as f:
yaml.dump(cleaned_config, f, sort_keys=False, default_flow_style=False)
self.log_message("Configuration saved to config.yaml")
def factory_reset_config(self, editor_window=None):
"""Reset configuration to factory defaults"""
# Confirm with user
if not messagebox.askyesno("Factory Reset",
"This will reset all settings to factory defaults.\n\n"
"Any unsaved changes will be lost.\n\n"
"Do you want to continue?"):
return
# Factory default configuration
default_config = {
"path": "example",
"study_names": None,
"idxs": None,
"signal_process": {
"heterodyne": "di-homodyne",
"null_point": 2,
"initial_samples": 50,
"baseline_correction": {"enabled": False, "pos": None, "neg": None}
},
"fft": {"signal_proportion": 1.0, "use_derivative": True, "analysis_type": "psd"},
"lorentzian": {
"signal_proportion": 1,
"frequency_bounds": [0.1, 0.9],
"dc_filter_range": [0, 50000],
"bimodal_fit": False,
"use_skewed_super_lorentzian": False
},
"tgs": {"grating_spacing": 3.5276, "signal_proportion": 1, "maxfev": 1000000},
"plot": {
"signal_process": True,
"fft_lorentzian": True,
"tgs": True,
"settings": {"num_points": None}
}
}
# Update config
self.config = default_config
# Update main GUI parameters
self.start_point_var.set(2)
self.two_saw_var.set(False)
self.baseline_var.set(False)
self.grating_edit.delete(0, tk.END)
self.grating_edit.insert(0, "3.5276")
# Save to default config.yaml
self.save_config()
self.log_message("Configuration reset to factory defaults")
if editor_window:
# Close and reopen editor to show defaults
editor_window.destroy()
self.open_config_editor()
else:
pass
def load_config_file(self, editor_window=None):
"""Load configuration from a user-selected YAML file"""
file_path = filedialog.askopenfilename(
filetypes=[
("YAML files", "*.yaml *.yml"),
("All files", "*.*")
],
title="Load Configuration File"
)
if not file_path:
return
try:
with open(file_path, 'r') as f:
loaded_config = yaml.safe_load(f)
# Update current config with loaded values
self.config.update(loaded_config)
# Update main GUI parameters from loaded config
self.start_point_var.set(self.config['signal_process']['null_point'])
self.two_saw_var.set(self.config['lorentzian']['bimodal_fit'])
self.baseline_var.set(self.config['signal_process']['baseline_correction']['enabled'])
# Update grating spacing
if 'tgs' in self.config and 'grating_spacing' in self.config['tgs']:
self.grating_edit.delete(0, tk.END)
self.grating_edit.insert(0, f"{self.config['tgs']['grating_spacing']:.6f}")
# Save to default config.yaml
self.save_config()
self.log_message(f"Configuration loaded from: {file_path}")
if editor_window:
# Close the existing editor and reopen with new config
editor_window.destroy()
self.open_config_editor()
else:
pass
except Exception as e:
self.log_message(f"Error loading configuration: {str(e)}", logging.ERROR)
if editor_window:
messagebox.showerror("Error", f"Failed to load configuration:\n{str(e)}")
def test_scope_connection(self):
"""Test connection to the oscilloscope at startup and log the result"""
# Don't test if we're shutting down
if hasattr(self, 'shutdown_flag') and self.shutdown_flag:
return
scope_address = self.scope_address_var.get().strip()
if not scope_address:
self.log_message("No oscilloscope address configured", logging.WARNING)
return
self.log_message(f"Testing connection to {self.current_scope_type} at {scope_address}...")
# Disable UI during test and show testing status
self.acq_status_var.set("Testing connection...")
def ping_thread():
# Check shutdown flag before proceeding
if hasattr(self, 'shutdown_flag') and self.shutdown_flag:
return
try:
import pyvisa
import time
# PyVISA automatically handles the underlying DLL loading (e.g., visa64.dll)
# Ensure NI-VISA Runtime is installed on the system.
rm = pyvisa.ResourceManager()
# Try to connect with a short timeout
scope = rm.open_resource(scope_address)
scope.timeout = 1000
scope.read_termination = '\n'
scope.write_termination = '\n'
# Try a simple command
try:
scope.write("*CLS")
except Exception as e:
# Cleanup on failure
try: scope.close()
except: pass
try: rm.close()
except: pass
if not (hasattr(self, 'shutdown_flag') and self.shutdown_flag):
self.root.after(0, lambda: self.log_message(f" Basic communication failed: {str(e)}"))
return
# Get instrument identification
idn = None
if not (hasattr(self, 'shutdown_flag') and self.shutdown_flag):
try:
idn = scope.query("*IDN?").strip()
except:
pass
# Cleanup
try: scope.close()
except: pass
try: rm.close()
except: pass
if idn and not (hasattr(self, 'shutdown_flag') and self.shutdown_flag):
idn_parts = idn.split(',')
model = idn_parts[1] if len(idn_parts) > 1 else "Unknown"
def handle_success():
if not (hasattr(self, 'shutdown_flag') and self.shutdown_flag):
self.log_message(f"Scope connected: {model}")
self.acq_status_var.set("Ready - Scope connected")
self.root.after(0, handle_success)
elif not idn and not (hasattr(self, 'shutdown_flag') and self.shutdown_flag):
def handle_error():
if not (hasattr(self, 'shutdown_flag') and self.shutdown_flag):
self.log_message("Scope connection failed: No response", logging.ERROR)
self.acq_status_var.set("Not ready - Scope NOT connected")
self.root.after(0, handle_error)
except Exception as e:
error_msg = str(e)
# Cleanup and log error
if not (hasattr(self, 'shutdown_flag') and self.shutdown_flag):
def handle_error():
self.log_message(f"Scope connection failed: {error_msg[:100]}", logging.ERROR)
self.acq_status_var.set("Not ready - Scope NOT connected")
self.root.after(0, handle_error)
# Start thread
thread = threading.Thread(target=ping_thread)
thread.daemon = True
thread.start()
def scan_available_resources(self):
"""Scan for available VISA resources and return a list of addresses"""
resources = []
try:
import pyvisa
# Try multiple backends
backends = ['@py', '@ivi', '']
for backend in backends:
try:
if backend:
rm = pyvisa.ResourceManager(backend)
else:
rm = pyvisa.ResourceManager()
# Get list of resources
available = rm.list_resources()
rm.close()
if available:
resources = list(available)
break
except Exception:
continue
except ImportError:
self.log_message("PyVISA not available for resource scanning", logging.WARNING)
except Exception as e:
self.log_message(f"Error scanning resources: {str(e)}", logging.WARNING)
return resources
def setup_logging(self):
"""Redirect logging to a queue for display in GUI."""
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
# Remove existing handlers
for handler in self.logger.handlers[:]:
self.logger.removeHandler(handler)
# Queue handler for GUI (INFO and above only)
self.queue_handler = QueueHandler(log_queue)
self.queue_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S'))
self.logger.addHandler(self.queue_handler)
# Suppress matplotlib debug messages
logging.getLogger('matplotlib').setLevel(logging.WARNING)
logging.getLogger('PIL').setLevel(logging.WARNING)
# Suppress pyvisa_py verbose logging - THIS IS KEY
logging.getLogger('pyvisa_py').setLevel(logging.CRITICAL) # Only show CRITICAL errors
logging.getLogger('pyvisa_py.protocols').setLevel(logging.ERROR)
logging.getLogger('pyvisa_py.tcpip').setLevel(logging.ERROR)
logging.getLogger('pyvisa').setLevel(logging.ERROR)
self.poll_log_queue()
def poll_log_queue(self):
"""Periodically update the log text widget."""
try:
while True:
msg = log_queue.get_nowait()
self.log_text.insert(tk.END, msg + '\n')
self.log_text.see(tk.END)
except queue.Empty:
pass
finally:
self.root.after(100, self.poll_log_queue)
def log_message(self, msg, level=logging.INFO):
"""Helper to log a message."""
self.logger.log(level, msg)
def create_widgets(self):
"""Create main layout - adjustable divider"""
# Main frame
main_frame = ttk.Frame(self.root)
main_frame.pack(fill='both', expand=True, padx=10, pady=10)
# Create a PanedWindow for left/right split
self.main_paned = ttk.PanedWindow(main_frame, orient='horizontal')
self.main_paned.pack(fill='both', expand=True)
# LEFT SIDE: Vertical paned window for acquisition + results summary
left_panel = ttk.Frame(self.main_paned)
self.left_paned = ttk.PanedWindow(left_panel, orient='vertical')
self.left_paned.pack(fill='both', expand=True)
# Acquisition panel (top-left) - let it use its natural height
acq_container = ttk.Frame(self.left_paned)
acq_inner = ttk.Frame(acq_container)
acq_inner.pack(fill='both', expand=True, padx=10, pady=5)
# Build acquisition section (ONCE)
self.build_acquisition_section(acq_inner)
# Force layout update and get the natural height
self.root.update_idletasks()
acq_natural_height = acq_container.winfo_reqheight()
# Add the acquisition container with weight 0 (won't expand)
self.left_paned.add(acq_container, weight=0)
# Results Summary panel (bottom-left) - takes all remaining space
results_summary_container = ttk.Frame(self.left_paned)
results_summary_inner = ttk.Frame(results_summary_container)
results_summary_inner.pack(fill='both', expand=True, padx=10, pady=5)
# Build results summary section (ONCE)
self.build_results_summary_section(results_summary_inner)
# Add the results container with weight 1 (expands to fill space)
self.left_paned.add(results_summary_container, weight=1)
self.main_paned.add(left_panel, weight=2) # Left side takes 20% width
# Middle panel for controls (existing)
middle_panel = ttk.Frame(self.main_paned)
middle_inner = ttk.Frame(middle_panel)
middle_inner.pack(fill='both', expand=True, padx=(10, 10), pady=5)
self.main_paned.add(middle_panel, weight=3) # 30% width
# Right panel for log output
right_panel = ttk.Frame(self.main_paned)
right_inner = ttk.Frame(right_panel)
right_inner.pack(fill='both', expand=True, padx=(10, 0), pady=5)
self.main_paned.add(right_panel, weight=5) # 50% width
# Store paned window references for sash positioning
self.paned_window = self.main_paned # For compatibility with resize handler
# Set initial sash positions after window is drawn
self.root.after(100, self.set_initial_sash)
# Build remaining sections (calibration, parameters, batch)
self.build_calibration_section(middle_inner)
self.build_parameters_section(middle_inner)
self.build_batch_section(middle_inner)
# Build right panel (log)
self.build_log_section(right_inner)
def add_tooltip(self, widget, text):
"""Add a tooltip to a widget"""
return ToolTip(widget, text)
def build_acquisition_section(self, parent):
"""Section 0: Oscilloscope Data Acquisition with multi-scope support"""
frame = ttk.LabelFrame(parent, text="Oscilloscope acquisition", padding=(15, 10))
frame.pack(fill='x', pady=(0, 15))
# Row 1: Scope type selector and address (full width)
row1 = ttk.Frame(frame, style='Panel.TFrame')
row1.pack(fill='x', pady=5)
# Scope type selector
lbl_scope_type = ttk.Label(row1, text="Scope type:", width=14, anchor='e')
lbl_scope_type.pack(side='left', padx=(0, 8))
self.scope_type_var = tk.StringVar(value=self.SCOPE_RIGOL)
self.scope_type_combo = ttk.Combobox(row1, textvariable=self.scope_type_var,
values=[self.SCOPE_RIGOL, self.SCOPE_LECROY],
state='readonly', width=10)
self.scope_type_combo.pack(side='left', padx=(0, 15))
self.scope_type_combo.bind('<<ComboboxSelected>>', self.on_scope_type_changed)
self.add_tooltip(self.scope_type_combo, "Select oscilloscope type (Rigol or LeCroy)")
lbl = ttk.Label(row1, text="Scope address:", width=14, anchor='e')
lbl.pack(side='left', padx=(0, 8))
# Set default addresses for both scope types
self.scope_address_var = tk.StringVar(value="TCPIP::169.254.228.210::INSTR")
self.scope_address_combo = ttk.Combobox(row1, textvariable=self.scope_address_var, width=35)
self.scope_address_combo.pack(side='left', fill='x', expand=True, padx=(0, 5))
# Row 2: Test and Refresh buttons (with scope type indicator)
btn_row = ttk.Frame(frame, style='Panel.TFrame')
btn_row.pack(fill='x', pady=5)
# Create a container frame to center the buttons
btn_container = ttk.Frame(btn_row)
btn_container.pack(anchor='center')
test_btn = self.create_button(btn_container, text="Test connection", command=self.test_scope_connection)
test_btn.pack(side='left', padx=(0, 10))
self.test_btn = test_btn # Store reference AFTER creation
refresh_btn = self.create_button(btn_container, text="Refresh", command=self.refresh_scope_addresses)
refresh_btn.pack(side='left', padx=(0, 10))
self.refresh_btn = refresh_btn # Store reference AFTER creation
self.debug_mode_var = tk.BooleanVar(value=False)
self.debug_mode_checkbox = ttk.Checkbutton(
btn_container, text="Debug mode", variable=self.debug_mode_var
)
self.debug_mode_checkbox.pack(side='left')
# Row 3: Study Name and Run Name (2 columns)
row3 = ttk.Frame(frame, style='Panel.TFrame')
row3.pack(fill='x', pady=5)
lbl = ttk.Label(row3, text="Study name:", width=14, anchor='e')
lbl.pack(side='left', padx=(0, 8))
self.study_name_var = tk.StringVar(value="Tungsten_Calibration")
self.study_entry = ttk.Entry(row3, textvariable=self.study_name_var, width=20)
self.study_entry.pack(side='left', padx=(0, 15))
lbl2 = ttk.Label(row3, text="Run name:", width=10, anchor='e')
lbl2.pack(side='left', padx=(0, 8))
self.run_name_var = tk.StringVar(value="spot1")
self.run_entry = ttk.Entry(row3, textvariable=self.run_name_var, width=20)
self.run_entry.pack(side='left', fill='x', expand=True)
# Row 4: Operator (shorter width) and Grating (shorter width)
row4 = ttk.Frame(frame, style='Panel.TFrame')
row4.pack(fill='x', pady=5)
lbl = ttk.Label(row4, text="Operator:", width=14, anchor='e')
lbl.pack(side='left', padx=(0, 8))
self.operator_var = tk.StringVar(value="Angus")
self.operator_entry = ttk.Entry(row4, textvariable=self.operator_var, width=10)
self.operator_entry.pack(side='left', padx=(0, 15))
lbl2 = ttk.Label(row4, text="Grating spacing Λ (µm):", width=18, anchor='e')
lbl2.pack(side='left', padx=(0, 8))
grating_options = ['1.6', '1.9', '2.2', '2.5', '2.8', '3.1', '3.4', '3.7',
'4.0', '4.2', '4.4', '4.6', '4.9', '5.2', '5.5', '5.8',
'6.4', '7.0', '7.6', '8.2', '8.8', '9.4']
self.acq_grating_var = tk.StringVar(value="6.4")
self.grating_combo = ttk.Combobox(row4, textvariable=self.acq_grating_var,
values=grating_options, width=8)
self.grating_combo.pack(side='left')
# Row 5: Number of traces (shorter width) and Trigger rate (shorter width)
row5 = ttk.Frame(frame, style='Panel.TFrame')
row5.pack(fill='x', pady=5)
lbl = ttk.Label(row5, text="Number of traces:", width=16, anchor='e')
lbl.pack(side='left', padx=(0, 8))
self.num_traces_var = tk.StringVar(value="8192")
self.traces_spin = ttk.Spinbox(row5, from_=1, to=10000, textvariable=self.num_traces_var, width=7)
self.traces_spin.pack(side='left', padx=(0, 15))
lbl2 = ttk.Label(row5, text="Trigger rate (kHz):", width=16, anchor='e')
lbl2.pack(side='left', padx=(0, 8))
self.trigger_rate_var = tk.StringVar(value="1")
self.trigger_spin = ttk.Spinbox(row5, from_=0.1, to=100, textvariable=self.trigger_rate_var, width=5, increment=0.1)
self.trigger_spin.pack(side='left')
# Row 6: Data directory
row6 = ttk.Frame(frame, style='Panel.TFrame')
row6.pack(fill='x', pady=5)
lbl = ttk.Label(row6, text="Data directory:", width=14, anchor='e')
lbl.pack(side='left', padx=(0, 8))
self.data_dir_var = tk.StringVar(value=r"C:\Users\short\Documents\Data")
self.data_dir_entry = ttk.Entry(row6, textvariable=self.data_dir_var, width=25)
self.data_dir_entry.pack(side='left', fill='x', expand=True, padx=(0, 5))
self.browse_button = self.create_button(row6, text="Browse...", command=self.browse_data_directory)
self.browse_button.pack(side='left')
# Separator
ttk.Separator(frame, orient='horizontal').pack(fill='x', pady=5)
# Row 7: Main action buttons (Acquire data and Acquire for calibration)
acq_row1 = ttk.Frame(frame, style='Panel.TFrame')
acq_row1.pack(fill='x', pady=5)
# Create a container frame to center the buttons
acq_container1 = ttk.Frame(acq_row1)
acq_container1.pack(anchor='center')
# Create RED "Acquire data" button with explicit styling
self.acquire_button = tk.Button(
acq_container1,
text="Acquire data",
command=self.acquire_rigol_data,
bg='#9B2C2C', # Muted brick red for dark theme
fg='white',
activebackground='#7A2323',
activeforeground='white',
relief=tk.RAISED, # Changed from FLAT to see if theme is forcing flat
bd=1,
padx=20,
pady=8,
font=("Arial", 10, 'bold'),
cursor="hand2",
highlightthickness=0,
highlightbackground='#d32f2f', # Force highlight color