-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
6715 lines (6249 loc) · 306 KB
/
Copy pathgui.py
File metadata and controls
6715 lines (6249 loc) · 306 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 -*-
"""
Microprobe Automated Measurement — GUI
Run: python gui.py
"""
import os
import platform
import re
import subprocess
import sys
import time
import threading
import traceback
import queue
import socket
import json
import numpy as np
import pandas as pd
import serial.tools.list_ports
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
VISION_IMPORT_ERRORS = []
try:
import cv2
except Exception as exc:
cv2 = None
VISION_IMPORT_ERRORS.append(f"opencv-python/cv2: {exc}")
try:
from PIL import Image, ImageTk
except Exception as exc:
Image = None
ImageTk = None
VISION_IMPORT_ERRORS.append(f"Pillow: {exc}")
from config import (
COM_PORTS,
BIOLOGIC_IP,
TEMP_SAFETY_ENABLED,
TEMP_SAFETY_ACTIVE_TARGET_C,
TEMP_SAFETY_MIN_VALID_C,
TEMP_SAFETY_MAX_DROP_C,
TEMP_SAFETY_POLL_S,
TEMP_SAFETY_SHUTDOWN_SETPOINT_C,
STAGE_SAFE_MOVE,
MFC_WRITE_ENABLED,
)
def _vision_unavailable(*_args, **_kwargs):
detail = "; ".join(VISION_IMPORT_ERRORS) or "vision dependencies were not loaded"
raise RuntimeError(
"Vision/OM tracking is unavailable on this runner. "
"Install the optional vision packages or run without camera features. "
f"Details: {detail}"
)
try:
from vision.electrode_mapper import (
annotate_detections,
compute_ecc_affine_registration,
detect_electrode_map,
detect_electrode_map_rgb,
detect_live_microscope_electrode_map_rgb,
detect_markup_electrode_map_rgb,
detect_reference_microscope_electrode_map_rgb,
filter_live_overlay_detections,
refine_circular_electrode_map_rgb,
scale_detection_table,
strip_red_markup_from_rgb,
transform_detection_table,
)
except Exception as exc:
VISION_IMPORT_ERRORS.append(f"vision.electrode_mapper: {exc}")
annotate_detections = _vision_unavailable
compute_ecc_affine_registration = _vision_unavailable
detect_electrode_map = _vision_unavailable
detect_electrode_map_rgb = _vision_unavailable
detect_live_microscope_electrode_map_rgb = _vision_unavailable
detect_markup_electrode_map_rgb = _vision_unavailable
detect_reference_microscope_electrode_map_rgb = _vision_unavailable
filter_live_overlay_detections = _vision_unavailable
refine_circular_electrode_map_rgb = _vision_unavailable
scale_detection_table = _vision_unavailable
strip_red_markup_from_rgb = _vision_unavailable
transform_detection_table = _vision_unavailable
try:
from vision.roi_verifier import verify_roi_revisit
except Exception as exc:
VISION_IMPORT_ERRORS.append(f"vision.roi_verifier: {exc}")
verify_roi_revisit = _vision_unavailable
try:
from vision_stage_mapper import (
SampleStageReference,
solve_sample_to_stage_affine_calibration,
sample_to_stage_xy,
)
except Exception as exc:
VISION_IMPORT_ERRORS.append(f"vision_stage_mapper: {exc}")
class SampleStageReference:
def __init__(self, *args, **kwargs):
_vision_unavailable(*args, **kwargs)
solve_sample_to_stage_affine_calibration = _vision_unavailable
sample_to_stage_xy = _vision_unavailable
VISION_AVAILABLE = (
cv2 is not None
and Image is not None
and ImageTk is not None
and not any(err.startswith("vision.") for err in VISION_IMPORT_ERRORS)
)
# ── 측정 관련 import (연결 실패해도 GUI는 뜨도록) ───────────────────────────
def _safe_import():
mods = {}
try:
from driver_biologic import BioLogicController
mods['biologic'] = BioLogicController
except Exception as e:
mods['biologic'] = None
print(f"[WARN] BioLogic import failed: {e}")
try:
from driver_motor import MDriveMotor
mods['motor'] = MDriveMotor
except Exception as e:
mods['motor'] = None
try:
from driver_temp import WatlowController
mods['temp'] = WatlowController
except Exception as e:
mods['temp'] = None
try:
from driver_mfc import AeraMFC
mods['mfc'] = AeraMFC
except Exception as e:
mods['mfc'] = None
try:
from measurement_sequence import rapid_eis_sequence, normal_eis_sequence
mods['sequence'] = rapid_eis_sequence
mods['rapid_sequence'] = rapid_eis_sequence
mods['normal_sequence'] = normal_eis_sequence
except Exception as e:
mods['sequence'] = None
mods['rapid_sequence'] = None
mods['normal_sequence'] = None
return mods
MODS = _safe_import()
# ── 색상 상수 ───────────────────────────────────────────────────────────────
CLR_BG = '#f5f5f5'
CLR_HEADER = '#2c3e50'
CLR_GREEN = '#27ae60'
CLR_RED = '#e74c3c'
CLR_ORANGE = '#e67e22'
CLR_BLUE = '#2980b9'
CLR_LGRAY = '#ecf0f1'
CLR_GOLD = '#f1c40f'
SKIP_TOKENS = {'', 'nan', 'none', 'non', 'skip', '-', 'na', 'n/a'}
GAS_SETTING_COLUMNS = {
'A': ('GasA_setting', 'GasA_sccm'),
'B': ('GasB_setting', 'GasB_sccm'),
}
MANUAL_QUICK_F_HIGH_HZ = 1e5
MANUAL_QUICK_F_LOW_HZ = 0.1
MANUAL_QUICK_CA_DT_S = 0.1
MANUAL_RECOMMENDATION_MAX_LF_HZ = 1.0
MONITOR_TIME_SERIES_MAX_POINTS = 5000
MONITOR_NYQUIST_MAX_POINTS = 1200
MONITOR_MAX_ABS_PLOT_VALUE = 1.0e15
MONITOR_QUEUE_BATCH_LIMIT = 120
MONITOR_REDRAW_INTERVAL_MS = 250
MONITOR_DROP_LIVE_QUEUE_ABOVE = 200
MANUAL_OCV_POLL_INTERVAL_MS = 1000
CONTACT_CONFIRM_DURATION_S = 10.0
CONTACT_CONFIRM_POLL_S = 1.0
def _parse_optional_float(value, default=None):
if value is None:
return default
if pd.isna(value):
return default
text = str(value).strip().lower()
if text in SKIP_TOKENS:
return default
return float(value)
def _parse_boolish(value, default=False):
if value is None:
return default
if pd.isna(value):
return default
text = str(value).strip().lower()
if text in SKIP_TOKENS:
return default
return text in {'1', 'true', 'yes', 'y', 'on'}
def _row_gas_setting(row, channel, default=None):
for column in GAS_SETTING_COLUMNS[channel]:
if column in row:
value = _parse_optional_float(row.get(column), default=None)
if value is not None:
return value
return default
def _label_number(value, *, digits=3, signed=False):
if value is None:
return 'NA'
try:
number = float(value)
except Exception:
return 'NA'
if abs(number) < (0.5 * (10 ** -int(digits))):
number = 0.0
text = f"{number:+.{digits}f}" if signed else f"{number:.{digits}f}"
if '.' in text:
text = text.rstrip('0').rstrip('.')
if text in {'-0', '+0'}:
text = '+0' if signed else '0'
return text.replace('.', 'p')
def _condition_label(
*,
prefix=None,
temperature=None,
gas_a=None,
gas_b=None,
electrode=None,
x_mm=None,
y_mm=None,
z_mm=None,
voltage=None,
):
parts = []
if prefix:
parts.append(str(prefix))
parts.extend([
f"T{_label_number(temperature, digits=1)}",
f"GA{_label_number(gas_a, digits=2)}",
f"GB{_label_number(gas_b, digits=2)}",
])
parts.append(f"E{int(electrode)}" if electrode is not None else "ENA")
parts.extend([
f"X{_label_number(x_mm, digits=3)}",
f"Y{_label_number(y_mm, digits=3)}",
f"Z{_label_number(z_mm, digits=3)}",
f"V{_label_number(voltage, digits=3, signed=True)}",
])
return '_'.join(parts)
def _safe_path_part(value, fallback='row'):
text = str(value or '').strip()
safe = ''.join(ch if ch.isalnum() or ch in '._+-' else '_' for ch in text)
safe = safe.strip('._-')
return safe or fallback
def _json_safe(value):
if hasattr(value, 'to_dict') and callable(value.to_dict):
return _json_safe(value.to_dict())
if isinstance(value, dict):
return {str(k): _json_safe(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [_json_safe(v) for v in value]
if isinstance(value, np.ndarray):
return _json_safe(value.tolist())
if isinstance(value, np.integer):
return int(value)
if isinstance(value, np.floating):
number = float(value)
return number if np.isfinite(number) else None
if isinstance(value, np.bool_):
return bool(value)
if isinstance(value, float):
return value if np.isfinite(value) else None
return value
def _detect_md_cc4xx_bridge():
"""Return True when the IMS USB bridge is present but not enumerated as a COM port."""
if platform.system() != 'Windows':
return False
try:
result = subprocess.run(
[
'powershell',
'-NoProfile',
'-Command',
"Get-PnpDevice | Where-Object { $_.InstanceId -like 'USB\\VID_10C4&PID_806F*' } | "
"Select-Object -ExpandProperty InstanceId",
],
capture_output=True,
text=True,
timeout=3,
check=False,
)
return 'USB\\VID_10C4&PID_806F' in (result.stdout or '')
except Exception:
return False
class MicroprobGUI(tk.Tk):
def __init__(self, *, enable_background_polls=True):
super().__init__()
self.title("Microprobe Automation")
self.geometry("1100x750")
self.configure(bg=CLR_BG)
self.resizable(True, True)
# Hardware objects
self.bl = None
self.motor = None
self.tc = None
self.mfc = None
# State
self.running = False
self.stop_flag = threading.Event()
self.log_queue = queue.Queue()
self.monitor_queue = queue.Queue()
self.condition_df = pd.DataFrame()
self._monitor_label = ''
self._monitor_step = 'Idle'
self._monitor_dc_points = []
self._monitor_eis_points = []
self._monitor_eis_overlay_points = []
self._monitor_dc_title = 'CA / CP Current Monitor'
self._monitor_eis_title = 'Impedance Monitor'
self._monitor_dc_axes = ('Time (s)', 'Current (A)')
self._monitor_eis_axes = ('Re(Z) (Ohm)', '-Im(Z) (Ohm)')
self._monitor_last_current = None
self._monitor_last_voltage = None
self._monitor_last_impedance = None
self._monitor_live_values = None
self._monitor_row_text = 'idle'
self._monitor_dc_series = None
self._monitor_eis_series = None
self._monitor_redraw_pending = False
self._monitor_last_redraw_s = 0.0
self._active_run_result_root = None
self._active_temperature_target_c = None
self._temp_safety_monitor_stop = None
self._temp_safety_last_pv_c = None
self._temp_safety_trip_payload = None
self._enable_background_polls = bool(enable_background_polls)
self._available_ports = []
self._serial_port_var = {
'motor': tk.StringVar(value=COM_PORTS['motor']),
'temp': tk.StringVar(value=COM_PORTS['temp']),
'mfc': tk.StringVar(value=COM_PORTS['mfc']),
}
self._biologic_channel_var = tk.StringVar(value='1')
self._biologic_channel_info = []
self._active_biologic_channel = 1
self._run_gas_mode_var = tk.StringVar(value='require_auto')
self._run_contact_fail_policy_var = tk.StringVar(value='stop')
self._run_confirm_preflight_var = tk.BooleanVar(value=True)
self._run_retract_tip_on_done_var = tk.BooleanVar(value=True)
self._run_retract_tip_mm_var = tk.StringVar(value='1.000')
self._tree_active_cell = (None, 0)
self._manual_target = {
'temp': tk.StringVar(value='600'),
'temp_ramp': tk.StringVar(value='5.0'),
'x': tk.StringVar(value='0.000'),
'y': tk.StringVar(value='0.000'),
'z': tk.StringVar(value='0.000'),
'gas_a': tk.StringVar(value='0'),
'gas_b': tk.StringVar(value='0'),
}
self._quick_eis = {
'label': tk.StringVar(value='manual_eis'),
'v_dc': tk.StringVar(value='0.300'),
'amp_mv': tk.StringVar(value='10'),
'n_pts': tk.StringVar(value='60'),
'peis_f_high': tk.StringVar(value=f'{MANUAL_QUICK_F_HIGH_HZ:.0f}'),
'peis_f_low': tk.StringVar(value=f'{MANUAL_QUICK_F_LOW_HZ:.1f}'),
'cycles': tk.StringVar(value='1'),
}
self._quick_rapid = {
'label': tk.StringVar(value='manual_rapid'),
'v_dc': tk.StringVar(value='0.300'),
'dv_mv': tk.StringVar(value='10'),
'hold_time': tk.StringVar(value='5'),
'post_hold_time': tk.StringVar(value='3'),
'ca_duration': tk.StringVar(value='20'),
'n_pts': tk.StringVar(value='60'),
'peis_f_high': tk.StringVar(value=f'{MANUAL_QUICK_F_HIGH_HZ:.0f}'),
'peis_f_low': tk.StringVar(value=f'{MANUAL_QUICK_F_LOW_HZ:.1f}'),
'cycles': tk.StringVar(value='1'),
}
self._contact_search = {
'start_offset': tk.StringVar(value='0.200'),
'step_mm': tk.StringVar(value='0.010'),
'max_drop_mm': tk.StringVar(value='0.400'),
'max_beyond_seed_mm': tk.StringVar(value='0.200'),
'ocv_threshold': tk.StringVar(value='0.100'),
'settle_s': tk.StringVar(value='1.00'),
'engage_mm': tk.StringVar(value='0.050'),
}
self._full_auto = {
'temperatures': tk.StringVar(value='600, 550, 500'),
'gas_pairs': tk.StringVar(value='10:30; 30:10'),
'voltages': tk.StringVar(value='0.0, 0.1, 0.2'),
'electrode_start': tk.StringVar(value='1'),
'electrode_end': tk.StringVar(value='8'),
'x1': tk.StringVar(value='0.000'),
'y1': tk.StringVar(value='0.000'),
'xn': tk.StringVar(value='7.000'),
'yn': tk.StringVar(value='0.000'),
'z1': tk.StringVar(value='0.000'),
'zn': tk.StringVar(value='0.000'),
'auto_contact_z': tk.StringVar(value='1'),
'contact_start_offset': tk.StringVar(value='0.200'),
'contact_step': tk.StringVar(value='0.010'),
'contact_max_drop': tk.StringVar(value='0.400'),
'contact_max_beyond_seed': tk.StringVar(value='0.200'),
'contact_ocv_threshold': tk.StringVar(value='0.100'),
'contact_settle': tk.StringVar(value='1.00'),
'contact_engage': tk.StringVar(value='0.050'),
'dv': tk.StringVar(value='0.03'),
'hold_time': tk.StringVar(value='60'),
'post_peis_hold_time': tk.StringVar(value='30'),
'peis_f_high': tk.StringVar(value='100000'),
'peis_f_low': tk.StringVar(value='0.1'),
'peis_n_pts': tk.StringVar(value='60'),
'ca_duration': tk.StringVar(value='200'),
'ca_dt': tk.StringVar(value='0.1'),
'temp_ramp_rate': tk.StringVar(value='5.0'),
'stable_time': tk.StringVar(value='120'),
'gas_stable_time': tk.StringVar(value='600'),
}
self._full_auto_use = {
'temperature': tk.BooleanVar(value=True),
'gas': tk.BooleanVar(value=True),
'tip': tk.BooleanVar(value=True),
}
self._full_auto_entries = {}
self._full_auto_summary = tk.StringVar(
value='Semi-auto generator ready'
)
self._adaptive_full_auto = {
'temperatures': tk.StringVar(value='600, 550, 500'),
'gas_pairs': tk.StringVar(value='10:30; 30:10'),
'voltages': tk.StringVar(value='0.0, 0.1, 0.2'),
'electrode_start': tk.StringVar(value='1'),
'electrode_end': tk.StringVar(value='8'),
'x1': tk.StringVar(value='0.000'),
'y1': tk.StringVar(value='0.000'),
'xn': tk.StringVar(value='7.000'),
'yn': tk.StringVar(value='0.000'),
'z1': tk.StringVar(value='0.000'),
'zn': tk.StringVar(value='0.000'),
'auto_contact_z': tk.StringVar(value='1'),
'contact_start_offset': tk.StringVar(value='0.200'),
'contact_step': tk.StringVar(value='0.010'),
'contact_max_drop': tk.StringVar(value='0.400'),
'contact_max_beyond_seed': tk.StringVar(value='0.200'),
'contact_ocv_threshold': tk.StringVar(value='0.100'),
'contact_settle': tk.StringVar(value='1.00'),
'contact_engage': tk.StringVar(value='0.050'),
'dv': tk.StringVar(value='0.03'),
'hold_time': tk.StringVar(value='60'),
'post_peis_hold_time': tk.StringVar(value='30'),
'peis_f_high': tk.StringVar(value='1000000'),
'peis_f_low': tk.StringVar(value='0.5'),
'peis_n_pts': tk.StringVar(value='60'),
'ca_duration': tk.StringVar(value='200'),
'ca_dt': tk.StringVar(value='0.1'),
'temp_ramp_rate': tk.StringVar(value='5.0'),
'stable_time': tk.StringVar(value='120'),
'gas_stable_time': tk.StringVar(value='600'),
'normal_eis_floor_hz': tk.StringVar(value='0.01'),
}
self._adaptive_full_auto_use = {
'temperature': tk.BooleanVar(value=True),
'gas': tk.BooleanVar(value=True),
'tip': tk.BooleanVar(value=True),
}
self._adaptive_full_auto_entries = {}
self._adaptive_full_auto_summary = tk.StringVar(
value='Full-auto adaptive planner ready'
)
self._manual_current = {
'temp': tk.StringVar(value='-'),
'x': tk.StringVar(value='-'),
'y': tk.StringVar(value='-'),
'z': tk.StringVar(value='-'),
'gas_a': tk.StringVar(value='-'),
'gas_b': tk.StringVar(value='-'),
'gas_a_sp': tk.StringVar(value='-'),
'gas_b_sp': tk.StringVar(value='-'),
}
self._manual_status_var = tk.StringVar(value='Manual control ready')
self._manual_ocv_var = tk.StringVar(value='OCV: -')
self._manual_recommendation_var = tk.StringVar(value='Recommendation: -')
self._monitor_recommendation_var = tk.StringVar(value='Recommendation: -')
self._manual_measurement_running = False
self._manual_measurement_stop_event = None
self._manual_gas_seq = 0
self._manual_gas_seq_lock = threading.Lock()
self._manual_ocv_poll_shutdown = False
self._manual_ocv_poll_inflight = False
self._adaptive_engine_factory = None
self._image_backend_var = tk.StringVar(value='dshow')
self._image_index_var = tk.StringVar(value='0')
self._image_detector_var = tk.StringVar(value='live')
self._image_expected_count_var = tk.StringVar(value='')
self._image_status_var = tk.StringVar(value='Camera idle')
self._image_detection_var = tk.StringVar(value='Electrodes: -')
self._image_hint_var = tk.StringVar(value='Hint: if the live overlay looks unreliable, use a pre-shot microscope image or attach the design image for assisted setup.')
self._image_design_path_var = tk.StringVar(value='')
self._image_design_status_var = tk.StringVar(value='Design: not loaded')
self._image_markup_path_var = tk.StringVar(value='')
self._image_markup_status_var = tk.StringVar(value='Markup: not loaded')
self._image_target_status_var = tk.StringVar(value='Target: not locked')
self._image_roi_verify_status_var = tk.StringVar(value='ROI verify: idle')
self._image_move_gate_status_var = tk.StringVar(value='Move gate: clear')
self._image_stage_anchor_status_var = tk.StringVar(value='Stage anchor: not set')
self._image_stage_affine_status_var = tk.StringVar(value='Stage calibration: not solved')
self._image_stage_swap_xy_var = tk.BooleanVar(value=False)
self._image_stage_invert_x_var = tk.BooleanVar(value=False)
self._image_stage_invert_y_var = tk.BooleanVar(value=False)
self._image_allow_stale_high_override_var = tk.BooleanVar(value=False)
self._image_monitor_cap = None
self._image_monitor_running = False
self._image_monitor_photo = None
self._image_monitor_frame_idx = 0
self._image_monitor_detect_every = 8
self._image_monitor_last_overlay_bgr = None
self._image_move_gate_label = None
self._image_move_target_button = None
self._image_override_weak_roi_button = None
self._image_design_map = None
self._image_markup_map = None
self._image_markup_reference_rgb = None
self._image_seed_map = None
self._image_seed_reference_rgb = None
self._image_monitor_last_frame_rgb = None
self._image_monitor_last_frame_time_s = None
self._image_tracking_map = None
self._image_selected_target = None
self._image_selected_design_target = None
self._image_stage_anchor = None
self._image_stage_calibration_refs = []
self._image_stage_affine_calibration = None
self._image_pending_roi_verification = None
self._image_pending_roi_seed_promotion = False
self._image_move_requires_review_after_weak_roi = False
self._image_allow_one_safe_move_after_weak_roi_override = False
self._image_last_roi_verify_result = None
self._image_render_shape = None
self._image_render_size = None
self._image_render_offset = (0, 0)
self._build_ui()
self._image_refresh_move_gate_status()
if self._enable_background_polls:
self._poll_log()
self._poll_monitor()
self._schedule_manual_ocv_poll()
self._refresh_port_choices()
def destroy(self):
self._manual_ocv_poll_shutdown = True
try:
self._image_monitor_stop()
finally:
super().destroy()
# ══════════════════════════════════════════════════════════════════════
# UI 구성
# ══════════════════════════════════════════════════════════════════════
def _build_ui(self):
# ── 상단 헤더 ────────────────────────────────────────────────────
hdr = tk.Frame(self, bg=CLR_HEADER, height=45)
hdr.pack(fill='x')
tk.Label(hdr, text="Microprobe Automated Measurement System",
bg=CLR_HEADER, fg='white',
font=('Segoe UI', 13, 'bold')).pack(side='left', padx=15, pady=10)
# ── 탭 ───────────────────────────────────────────────────────────
nb = ttk.Notebook(self)
nb.pack(fill='both', expand=True, padx=8, pady=8)
self.tab_hw = ttk.Frame(nb)
self.tab_cond = ttk.Frame(nb)
self.tab_full = ttk.Frame(nb)
self.tab_auto = ttk.Frame(nb)
self.tab_run = ttk.Frame(nb)
self.tab_image = ttk.Frame(nb)
self.tab_live = ttk.Frame(nb)
self.tab_manual = ttk.Frame(nb)
nb.add(self.tab_hw, text=' Hardware ')
nb.add(self.tab_cond, text=' CSV List ')
nb.add(self.tab_full, text=' Semi-auto ')
nb.add(self.tab_auto, text=' Full-auto ')
nb.add(self.tab_run, text=' Run / Monitor ')
nb.add(self.tab_image, text=' Image Monitor ')
nb.add(self.tab_live, text=' EIS Monitor ')
nb.add(self.tab_manual, text=' Manual Control ')
self._build_tab_hardware()
self._build_tab_conditions()
self._build_tab_full_auto()
self._build_tab_adaptive_full_auto()
self._build_tab_run()
self._build_tab_image()
self._build_tab_live()
self._build_tab_manual()
# ── Tab 1: Hardware ────────────────────────────────────────────────
def _build_tab_hardware(self):
f = self.tab_hw
pad = {'padx': 10, 'pady': 6}
self._hw_status = {}
self._hw_btn = {}
tk.Label(f, text="Hardware Connections",
font=('Segoe UI', 11, 'bold'), bg=CLR_BG).grid(
row=0, column=0, columnspan=5, sticky='w', **pad)
headers = ['Device', 'Interface', '', 'Status', '']
widths = [18, 22, 10, 18, 12]
for c, (h, w) in enumerate(zip(headers, widths)):
tk.Label(f, text=h, font=('Segoe UI', 9, 'bold'),
bg=CLR_LGRAY, width=w,
relief='flat', anchor='w').grid(row=1, column=c, sticky='ew', padx=4, pady=2)
# ── BioLogic row (with editable IP + Auto-detect) ──────────────
tk.Label(f, text='BioLogic SP-200', anchor='w', bg=CLR_BG,
font=('Segoe UI', 10)).grid(row=2, column=0, sticky='w', **pad)
ip_frame = tk.Frame(f, bg=CLR_BG)
ip_frame.grid(row=2, column=1, sticky='w', padx=10, pady=6)
tk.Label(ip_frame, text='IP:', bg=CLR_BG,
font=('Courier', 9), fg='#555').pack(side='left')
self._biologic_ip = tk.StringVar(value=BIOLOGIC_IP)
ip_entry = tk.Entry(ip_frame, textvariable=self._biologic_ip,
width=16, font=('Courier', 9))
ip_entry.pack(side='left', padx=2)
tk.Label(ip_frame, text='Ch:', bg=CLR_BG,
font=('Courier', 9), fg='#555').pack(side='left', padx=(8, 0))
channel_box = ttk.Combobox(
ip_frame,
textvariable=self._biologic_channel_var,
width=4,
values=['1'],
state='readonly',
)
channel_box.pack(side='left', padx=2)
channel_box.bind('<<ComboboxSelected>>', lambda _evt: self._selected_biologic_channel())
self._biologic_channel_box = channel_box
ttk.Button(f, text='Auto-detect',
command=self._autodetect_biologic).grid(row=2, column=2, padx=4, pady=6)
bl_status = tk.Label(f, text='● Not connected', fg=CLR_RED,
bg=CLR_BG, font=('Segoe UI', 10))
bl_status.grid(row=2, column=3, sticky='w', **pad)
self._hw_status['biologic'] = bl_status
bl_btn = ttk.Button(f, text='Connect',
command=lambda: self._toggle_connect('biologic'))
bl_btn.grid(row=2, column=4, **pad)
self._hw_btn['biologic'] = bl_btn
# ── Other devices ──────────────────────────────────────────────
other_devices = [
(3, 'IMS MDrive Motor', 'motor', 'COM9 9600 bps'),
(4, 'Watlow EZ-ZONE', 'temp', 'COM3 9600 bps Modbus'),
(5, 'Aera MFC (×2)', 'mfc', 'COM5 9600 bps'),
]
self._hw_port_box = {}
for r, name, key, iface in other_devices:
tk.Label(f, text=name, anchor='w', bg=CLR_BG,
font=('Segoe UI', 10)).grid(row=r, column=0, sticky='w', **pad)
port_frame = tk.Frame(f, bg=CLR_BG)
port_frame.grid(row=r, column=1, sticky='w', padx=10, pady=6)
box = ttk.Combobox(
port_frame,
textvariable=self._serial_port_var[key],
width=12,
state='readonly'
)
box.pack(side='left')
tk.Label(port_frame, text=iface, anchor='w', bg=CLR_BG,
font=('Courier', 9), fg='#555').pack(side='left', padx=(6, 0))
self._hw_port_box[key] = box
lbl = tk.Label(f, text='● Not connected', fg=CLR_RED,
bg=CLR_BG, font=('Segoe UI', 10))
lbl.grid(row=r, column=3, sticky='w', **pad)
self._hw_status[key] = lbl
btn = ttk.Button(f, text='Connect',
command=lambda k=key: self._toggle_connect(k))
btn.grid(row=r, column=4, **pad)
self._hw_btn[key] = btn
# Connect All / Disconnect All
btn_frame = tk.Frame(f, bg=CLR_BG)
btn_frame.grid(row=10, column=0, columnspan=5, pady=20, sticky='w', padx=10)
ttk.Button(btn_frame, text='Connect All',
command=self._connect_all).pack(side='left', padx=5)
ttk.Button(btn_frame, text='Disconnect All',
command=self._disconnect_all).pack(side='left', padx=5)
ttk.Button(btn_frame, text='Refresh COM Ports',
command=self._refresh_port_choices).pack(side='left', padx=5)
ttk.Button(btn_frame, text='Auto Detect Serial',
command=self._autodetect_serial_devices).pack(side='left', padx=5)
# Live readback
tk.Label(f, text="Live Readback",
font=('Segoe UI', 11, 'bold'), bg=CLR_BG).grid(
row=11, column=0, columnspan=5, sticky='w', padx=10, pady=(20,4))
rb_frame = tk.Frame(f, bg=CLR_LGRAY, relief='groove', bd=1)
rb_frame.grid(row=12, column=0, columnspan=5, sticky='ew', padx=10, pady=4)
self._rb_temp = self._readback_row(rb_frame, 0, 'Temperature (°C)')
self._rb_fa = self._readback_row(rb_frame, 1, 'Gas A output RFX (0-100)')
self._rb_fb = self._readback_row(rb_frame, 2, 'Gas B output RFX (0-100)')
self._rb_x = self._readback_row(rb_frame, 3, 'Motor X (mm)')
self._rb_y = self._readback_row(rb_frame, 4, 'Motor Y (mm)')
self._rb_z = self._readback_row(rb_frame, 5, 'Motor Z (mm)')
ttk.Button(f, text='Read now',
command=lambda: threading.Thread(
target=self._do_readback, daemon=True).start()
).grid(row=13, column=0, padx=10, pady=6, sticky='w')
self._port_status_var = tk.StringVar(value='Serial ports: not scanned yet')
tk.Label(f, textvariable=self._port_status_var, bg=CLR_BG,
fg='#555', anchor='w', font=('Segoe UI', 9)).grid(
row=14, column=0, columnspan=5, sticky='w', padx=10, pady=(0, 8))
def _readback_row(self, parent, row, label):
tk.Label(parent, text=label, bg=CLR_LGRAY, width=25,
anchor='w', font=('Segoe UI', 10)).grid(
row=row, column=0, padx=10, pady=4)
var = tk.StringVar(value='—')
tk.Label(parent, textvariable=var, bg=CLR_LGRAY, width=15,
anchor='w', font=('Courier', 10)).grid(
row=row, column=1, padx=10)
return var
# ── Tab 2: Conditions ──────────────────────────────────────────────
def _build_tab_conditions(self):
f = self.tab_cond
btn_row = tk.Frame(f, bg=CLR_BG)
btn_row.pack(fill='x', padx=8, pady=6)
ttk.Button(btn_row, text='Load CSV',
command=self._load_csv).pack(side='left', padx=4)
ttk.Button(btn_row, text='Save CSV',
command=self._save_csv).pack(side='left', padx=4)
ttk.Button(btn_row, text='Add row',
command=self._add_row).pack(side='left', padx=4)
ttk.Button(btn_row, text='Delete row',
command=self._del_row).pack(side='left', padx=4)
ttk.Button(btn_row, text='Copy',
command=self._copy_tree_selection).pack(side='left', padx=(14, 4))
ttk.Button(btn_row, text='Paste',
command=self._paste_tree_clipboard).pack(side='left', padx=4)
ttk.Button(btn_row, text='Load template',
command=self._load_template).pack(side='left', padx=4)
# Treeview table
cols = ['Label', 'Temperature_C', 'RampRate_C_per_min', 'GasA_setting', 'GasB_setting',
'X_mm', 'Y_mm', 'Z_mm',
'AutoContactZ', 'ContactStartOffset_mm', 'ContactStep_mm',
'ContactMaxDrop_mm', 'ContactMaxBeyondSeed_mm',
'ContactOCVThreshold_V', 'ContactSettle_s', 'ContactEngage_mm',
'V_dc', 'dV', 'HoldTime_s', 'PostPEIS_HoldTime_s',
'PEIS_fHigh', 'PEIS_fLow', 'PEIS_nPts',
'CA_duration_s', 'CA_dt',
'StableTime_s', 'GasStableTime_s', 'Skip']
self._tree_cols = cols
tree_frame = tk.Frame(f)
tree_frame.pack(fill='both', expand=True, padx=8, pady=4)
vsb = ttk.Scrollbar(tree_frame, orient='vertical')
hsb = ttk.Scrollbar(tree_frame, orient='horizontal')
self.tree = ttk.Treeview(tree_frame, columns=cols, show='headings',
yscrollcommand=vsb.set, xscrollcommand=hsb.set)
vsb.config(command=self.tree.yview)
hsb.config(command=self.tree.xview)
for c in cols:
w = 120 if c == 'Label' else 80
self.tree.heading(c, text=c)
self.tree.column(c, width=w, minwidth=50, anchor='center')
self.tree.grid(row=0, column=0, sticky='nsew')
vsb.grid(row=0, column=1, sticky='ns')
hsb.grid(row=1, column=0, sticky='ew')
tree_frame.rowconfigure(0, weight=1)
tree_frame.columnconfigure(0, weight=1)
self.tree.bind('<Button-1>', self._remember_tree_cell)
self.tree.bind('<Double-1>', self._edit_cell)
self.tree.bind('<Control-c>', self._copy_tree_selection)
self.tree.bind('<Control-C>', self._copy_tree_selection)
self.tree.bind('<Control-v>', self._paste_tree_clipboard)
self.tree.bind('<Control-V>', self._paste_tree_clipboard)
def _build_tab_full_auto(self):
f = self.tab_full
intro = tk.LabelFrame(f, text='Semi-auto Condition Generator',
bg=CLR_BG, padx=10, pady=10)
intro.pack(fill='x', padx=8, pady=(8, 6))
header = tk.Frame(intro, bg=CLR_BG)
header.pack(fill='x')
tk.Label(
header,
text=('Generate a condition table from temperature, gas, voltage, '
'and electrode ranges. Generated rows are sent to the '
'CSV List table for review before running.'),
bg=CLR_BG,
justify='left',
anchor='w',
font=('Segoe UI', 10),
).pack(side='left', fill='x', expand=True)
option_box = tk.LabelFrame(header, text='Disable Unused Hardware', bg=CLR_BG, padx=8, pady=6)
option_box.pack(side='right', padx=(12, 0))
ttk.Checkbutton(
option_box, text='Use temperature',
variable=self._full_auto_use['temperature'],
command=self._update_full_auto_field_states
).grid(row=0, column=0, sticky='w', padx=4)
ttk.Checkbutton(
option_box, text='Use gas',
variable=self._full_auto_use['gas'],
command=self._update_full_auto_field_states
).grid(row=1, column=0, sticky='w', padx=4)
ttk.Checkbutton(
option_box, text='Use tip position',
variable=self._full_auto_use['tip'],
command=self._update_full_auto_field_states
).grid(row=2, column=0, sticky='w', padx=4)
grid = tk.Frame(f, bg=CLR_BG)
grid.pack(fill='x', padx=8, pady=4)
grid.columnconfigure(1, weight=1)
grid.columnconfigure(3, weight=1)
fields = [
('Temperatures (C)', 'temperatures', 0, 0),
('Gas pairs A:B setting (0-100)', 'gas_pairs', 0, 2),
('Voltages (V)', 'voltages', 1, 0),
('Electrode 1 Z seed (mm)', 'z1', 1, 2),
('Electrode start', 'electrode_start', 2, 0),
('Electrode end', 'electrode_end', 2, 2),
('Electrode 1 X (mm)', 'x1', 3, 0),
('Electrode 1 Y (mm)', 'y1', 3, 2),
('Electrode N X (mm)', 'xn', 4, 0),
('Electrode N Y (mm)', 'yn', 4, 2),
('Electrode N Z seed (mm)', 'zn', 5, 0),
('AutoContactZ (0/1)', 'auto_contact_z', 5, 2),
('Contact start offset (mm)', 'contact_start_offset', 6, 0),
('Contact step (mm)', 'contact_step', 6, 2),
('Contact max drop (mm)', 'contact_max_drop', 7, 0),
('Contact max beyond seed (mm)', 'contact_max_beyond_seed', 7, 2),
('Contact OCV threshold (V)', 'contact_ocv_threshold', 8, 0),
('Contact settle (s)', 'contact_settle', 8, 2),
('Contact engage (mm)', 'contact_engage', 9, 0),
('dV (V)', 'dv', 10, 0),
('Pre-PEIS hold (s)', 'hold_time', 10, 2),
('Post-PEIS hold (s)', 'post_peis_hold_time', 11, 0),
('PEIS f high (Hz)', 'peis_f_high', 11, 2),
('PEIS f low (Hz)', 'peis_f_low', 12, 0),
('PEIS n pts', 'peis_n_pts', 12, 2),
('CA duration (s)', 'ca_duration', 13, 0),
('CA dt (s)', 'ca_dt', 13, 2),
('Temp ramp rate (C/min)', 'temp_ramp_rate', 14, 0),
('Temp stable time (s)', 'stable_time', 14, 2),
('Gas stable time (s)', 'gas_stable_time', 15, 0),
]
for label, key, row, col in fields:
tk.Label(
grid, text=label, bg=CLR_BG, anchor='w',
font=('Segoe UI', 10)
).grid(row=row, column=col, sticky='w', padx=(0, 8), pady=4)
entry = tk.Entry(
grid, textvariable=self._full_auto[key],
font=('Courier New', 10), width=28
)
entry.grid(row=row, column=col + 1, sticky='ew', padx=(0, 18), pady=4)
self._full_auto_entries[key] = entry
help_box = tk.LabelFrame(f, text='Input Format', bg=CLR_BG, padx=10, pady=10)
help_box.pack(fill='x', padx=8, pady=(4, 6))
help_lines = [
'Temperatures / Voltages: comma-separated, for example 600, 550, 500',
'Gas pairs: semicolon-separated raw DMFC setting pairs (0-100), for example 10:30; 30:10',
'Tip positions: XY are linearly interpolated from electrode 1 to electrode N',
'Z is a seed value. AutoContactZ=1 starts 0.2 mm above seed, steps toward contact, then engages by the configured amount.',
'Uncheck temperature / gas / tip position above to disable those inputs and generate None values for that hardware step.',
'During runs, gas is set before a temperature change; gas/temp stabilization waits overlap, and unchanged conditions skip their wait.',
'Post-PEIS CA uses one CA technique with two sequences: Vdc short hold, then Vdc+dV long CA.',
]
for line in help_lines:
tk.Label(help_box, text=line, bg=CLR_BG, anchor='w',
justify='left', font=('Segoe UI', 10)).pack(fill='x', pady=1)
btn_row = tk.Frame(f, bg=CLR_BG)
btn_row.pack(fill='x', padx=8, pady=(2, 6))
ttk.Button(
btn_row, text='Generate to CSV List',
command=self._generate_full_auto_conditions
).pack(side='left', padx=4)
ttk.Button(
btn_row, text='Append to CSV List',
command=lambda: self._generate_full_auto_conditions(append=True)
).pack(side='left', padx=4)
tk.Label(
f, textvariable=self._full_auto_summary, bg=CLR_LGRAY,
anchor='w', font=('Segoe UI', 10), relief='sunken'
).pack(fill='x', padx=8, pady=(0, 8))
self._update_full_auto_field_states()
def _build_tab_adaptive_full_auto(self):
f = self.tab_auto
intro = tk.LabelFrame(f, text='Full-auto Adaptive Planner',
bg=CLR_BG, padx=10, pady=10)
intro.pack(fill='x', padx=8, pady=(8, 6))
header = tk.Frame(intro, bg=CLR_BG)
header.pack(fill='x')
tk.Label(
header,
text=('Prepare the future fully automatic workflow that will use '
'optimized analysis results to choose the next measurement '
'parameters. For now, this planner generates the same base '
'CSV rows while keeping adaptive settings visible in the UI.'),
bg=CLR_BG,
justify='left',
anchor='w',
font=('Segoe UI', 10),
).pack(side='left', fill='x', expand=True)
option_box = tk.LabelFrame(header, text='Disable Unused Hardware', bg=CLR_BG, padx=8, pady=6)
option_box.pack(side='right', padx=(12, 0))
ttk.Checkbutton(
option_box, text='Use temperature',
variable=self._adaptive_full_auto_use['temperature'],
command=self._update_adaptive_full_auto_field_states
).grid(row=0, column=0, sticky='w', padx=4)
ttk.Checkbutton(
option_box, text='Use gas',
variable=self._adaptive_full_auto_use['gas'],
command=self._update_adaptive_full_auto_field_states
).grid(row=1, column=0, sticky='w', padx=4)
ttk.Checkbutton(
option_box, text='Use tip position',
variable=self._adaptive_full_auto_use['tip'],
command=self._update_adaptive_full_auto_field_states
).grid(row=2, column=0, sticky='w', padx=4)
grid = tk.Frame(f, bg=CLR_BG)
grid.pack(fill='x', padx=8, pady=4)
grid.columnconfigure(1, weight=1)
grid.columnconfigure(3, weight=1)
fields = [
('Temperatures (C)', 'temperatures', 0, 0),
('Gas pairs A:B setting (0-100)', 'gas_pairs', 0, 2),
('Voltages (V)', 'voltages', 1, 0),
('Electrode 1 Z seed (mm)', 'z1', 1, 2),
('Electrode start', 'electrode_start', 2, 0),
('Electrode end', 'electrode_end', 2, 2),
('Electrode 1 X (mm)', 'x1', 3, 0),
('Electrode 1 Y (mm)', 'y1', 3, 2),
('Electrode N X (mm)', 'xn', 4, 0),
('Electrode N Y (mm)', 'yn', 4, 2),
('Electrode N Z seed (mm)', 'zn', 5, 0),
('AutoContactZ (0/1)', 'auto_contact_z', 5, 2),
('Contact start offset (mm)', 'contact_start_offset', 6, 0),
('Contact step (mm)', 'contact_step', 6, 2),
('Contact max drop (mm)', 'contact_max_drop', 7, 0),
('Contact max beyond seed (mm)', 'contact_max_beyond_seed', 7, 2),
('Contact OCV threshold (V)', 'contact_ocv_threshold', 8, 0),