-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_op_cog.py
More file actions
2048 lines (1786 loc) · 95.1 KB
/
test_op_cog.py
File metadata and controls
2048 lines (1786 loc) · 95.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import argparse
from copy import deepcopy
from execution_cache import ExecutionCache
import Levenshtein
import json
import pexpect
import difflib
from epics import caput_many, camonitor
from datetime import datetime
import sys
import re, time
from pprint import pprint
from scipy.stats import linregress
import numpy as np
from codebleu import calc_codebleu
import tomllib
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
sys.path.append(parent_dir)
from src.hal_beam_com.model_manager import ModelManager
from utils import strip_comments, calculate_mape, print_log_comparison
from base_test_framework import BaseTestFramework
from src.hal_beam_com.cogs.op_cog import invoke
from src.hal_beam_com.utils import get_data_field, CogType
from src.hal_beam_com.pv_config import get_pv_config
class ExecutionCancellationError(Exception):
"""Raised when snippet execution must be canceled due to timeout or hang."""
class ExecutionFailedError(Exception):
"""Raised when an error was detected in the execution of a code snippet."""
def __init__(self, message="Execution failed"):
self.message = message
super().__init__(self.message)
def is_temp_match(gt_temp_logs, pred_temp_logs,
mae_threshold=5.0, final_temp_threshold=5.0):
"""
Compare temperature progressions using MAE and final temperature accuracy.
Args:
gt_temp_logs: Ground truth temperature logs [(timestamp, temp), ...]
pred_temp_logs: Predicted temperature logs
mae_threshold: Maximum acceptable MAE in °C for score=0 (default: 5.0°C)
final_temp_threshold: Maximum final temperature difference in °C for score=0 (default: 5.0°C)
Returns:
(binary_match, continuous_score, details)
"""
if len(gt_temp_logs) == 0 and len(pred_temp_logs) == 0:
# Both empty - perfect match
return True, 1.0, {"reason": "both empty", "score": 1.0}
if len(gt_temp_logs) == 0 or len(pred_temp_logs) == 0:
# One empty, one not - no match
return False, 0.0, {"reason": "one empty", "score": 0.0}
# Extract just the temperature values (ignoring timestamps)
gt_temps = np.array([temp for _, temp in gt_temp_logs])
pred_temps = np.array([temp for _, temp in pred_temp_logs])
# Pad the shorter sequence with its last value
max_len = max(len(gt_temps), len(pred_temps))
if len(gt_temps) < max_len:
gt_temps = np.pad(gt_temps, (0, max_len - len(gt_temps)), 'edge')
elif len(pred_temps) < max_len:
pred_temps = np.pad(pred_temps, (0, max_len - len(pred_temps)), 'edge')
# Calculate Mean Absolute Error
mae = np.mean(np.abs(gt_temps - pred_temps))
# Calculate final temperature difference
final_temp_diff = abs(float(gt_temps[-1]) - float(pred_temps[-1]))
# Calculate continuous scores using exponential decay
# MAE score: exponential decay with characteristic scale of 15°C
mae_score = np.exp(-mae / 15.0)
# Final temp score: exponential decay with characteristic scale of 15°C
final_temp_score = np.exp(-final_temp_diff / 15.0)
# Weighted average for overall score (70% MAE, 30% final temp)
continuous_score = 0.7 * mae_score + 0.3 * final_temp_score
# Binary match decision (both conditions must be satisfied)
binary_match = (mae <= mae_threshold and
final_temp_diff <= final_temp_threshold)
# Print diagnostic information if mismatch
if not binary_match:
print(f"Temperature progression mismatch:")
print(f" MAE: {mae:.2f}°C (score: {mae_score:.3f})")
print(f" Final temp diff: {final_temp_diff:.2f}°C (score: {final_temp_score:.3f})")
print(f" Overall score: {continuous_score:.3f}")
if len(gt_temps) <= 10: # Only print if not too many values
print(f" GT temps: {gt_temps}")
print(f" Pred temps: {pred_temps}")
details = {
"mae": mae,
"final_temp_diff": final_temp_diff,
"mae_score": mae_score,
"final_temp_score": final_temp_score,
"score": continuous_score
}
return binary_match, continuous_score, details
class OpAgentTestFramework(BaseTestFramework):
# Define IPython prompt pattern as a class constant
IPYTHON_PROMPT = r'In\s*\[[0-9]+\]:\s*'
# ANSI-tolerant error detection regexes and helper to build expect patterns
ERROR_TRACEBACK_RE = re.compile(r'(?m)^\s*(?:\x1b\[[0-9;]*m)*Traceback \(most recent call last\):')
ERROR_HEADER_RE = re.compile(r'(?m)^\s*(?:\x1b\[[0-9;]*m)*An exception has occurred, use .+ to see the full traceback\.')
ERROR_LINE_RE = re.compile(r'(?m)^\s*(?:\x1b\[[0-9;]*m)*(?!except\b)[A-Za-z_]\w*(?:Error|Exception|Interrupt|Exit)(?::|$)')
def _error_expect_patterns(self):
return [self.IPYTHON_PROMPT, self.ERROR_TRACEBACK_RE, self.ERROR_HEADER_RE, self.ERROR_LINE_RE]
def __init__(self, dataset_path, results_path, *,
scientist_file=None,
base_model='mistral',
system_prompt_path=None,
num_runs=1, debug=False,
use_gt_cache=True, use_cache=True,
complex_only=False, simple_only=False,
beamline='11BM'):
super().__init__(dataset_path, results_path,
system_prompt_path=system_prompt_path,
base_model=base_model, num_runs=num_runs)
self.log_file = None
self.monitor_logs = []
self._current_test_start_time: float | None = None # wall-clock (sec) when we begin logging
self.interactive_shell = None
self.debug = debug
self.use_gt_cache = use_gt_cache
self.use_cache = use_cache
self.complex_only = complex_only
self.simple_only = simple_only
self._idx = 0 # running counter for entries
self.beamline = beamline
# ── load scientists' answers if provided ────────────────────────────
self.scientist_map = {}
if scientist_file:
with open(scientist_file, 'rb') as f:
self.scientist_map = tomllib.load(f) # {command: {'code': …}}
print(f"Loaded {len(self.scientist_map)} beamline scientist answers "
f"from {scientist_file}")
# CATEGORY 1: Functions to mock (log but remove from execution)
# Dictionary mapping function names to regex patterns
self.functions_to_mock = {
# capture the call **plus** any trailing whitespace so no stray
# space/indent is left behind after removal
"sam.align": r"sam\.align\s*\([^)]*\)\s*;?\s*"
# Add more functions here that should be logged but not executed
}
# CATEGORY 2: Functions to log with parameters (log but keep in code)
# Dictionary mapping function names to regex patterns and parameter extraction config
self.functions_to_log = {
"sam.setOrigin": {
"pattern": r"sam\.setOrigin\(\s*(\[[^\]]*\])\s*(?:,\s*(\[[^\]]*\]))?\s*\)",
"param_format": lambda matches: f"{matches[0]}, {matches[1] if len(matches) > 1 and matches[1] else 'None'}",
"compare_params": False
},
"wsam": { # NEW ─ log but keep in code
"pattern": r"wsam\s*\(\s*\)", # match `wsam()` with any spacing
"param_format": lambda matches: "", # no parameters to record
"compare_params": False # value is ignored during comparison
},
"sam.pos": {
"pattern": r"sam.pos\s*\(\s*\)",
"param_format": lambda matches: "",
"compare_params": False
}
}
# Validate that complex_only and simple_only are not both True
if self.complex_only and self.simple_only:
raise ValueError("Cannot specify both complex_only and simple_only")
# Set up logging to file
self.console_log_path = os.path.join(os.path.dirname(self.results_path), 'console_output.log')
self.console_log_file = open(self.console_log_path, 'w', encoding='utf-8', buffering=1) # Line buffered
# Create a custom stdout that writes to both console and file
self.original_stdout = sys.stdout
sys.stdout = self
# Initialize the execution cache
if self.use_gt_cache or self.use_cache or self.debug:
cache_file_path = os.path.join(os.path.dirname(os.path.sep.join(results_path.split(os.path.sep)[:-3])), 'execution_cache.json')
self.execution_cache = ExecutionCache(cache_file_path)
else:
self.execution_cache = None
# Log the start of the test run
print(f"Test run started at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Results will be saved to: {self.results_path}")
print(f"Console output is being logged to: {self.console_log_path}")
_, self.pvs_defaults = get_pv_config(self.beamline)
# --- CodeBLEU-related column names ---------------------------------
_cb_keys = list(calc_codebleu(["print('x')"], ["print('x')"], lang="python").keys())
_cb_keys = ["average_CodeBLEU" if k == "codebleu" else k for k in _cb_keys]
_cb_keys += ["comb_7_CodeBLEU"]
self.fieldnames = ([
'command', 'expected_codes', 'generated_code', 'exact_match', 'inference_time',
'pv_match_rate', 'pv_mismatch_rate', 'exact_pv_match',
'timing_match', 'temp_match', 'full_match',
'timing_score', 'temp_score', 'full_score',
'temperature_involved',
'pv_value_matches', 'pv_total_pairs', 'num_gt_pv_events', 'num_pred_pv_events',
'timing_r2', 'timing_slope', 'timing_mape', 'timing_duration_ratio',
'timing_details', 'temp_details',
'codebleu_scores', 'levenshtein_distances', 'normalized_levenshtein_distances',
'best_normalized_levenshtein_distance', 'is_complex',
'gt_pv_logs', 'pred_pv_logs', 'ignore_pvs', 'aligned_gt_logs', 'aligned_pred_logs',
'ground_truth_snippet', 'gt_temp_logs', 'pred_temp_logs'
]
+ _cb_keys
+ ['best_codebleu_score', 'best_levenshtein_distance', 'average_levenshtein_distance'])
# Single dictionary to track all metrics by complexity
self.metrics = {
'simple': {'results': [], 'execution_times': [], 'count': 0, 'full_matches': 0,
'exact_code_match_count': 0,
'pv_exact_match_count': 0, 'pv_exact_mismatch_count': 0, 'pv_match_rates': [],
'pv_mismatch_rates': [],
'timing_match_count': 0, 'timing_mismatch_count': 0,
'timing_scores': [], 'temp_scores': [], 'full_scores': [],
'temp_match_count': 0, 'temp_mismatch_count': 0,
'full_match_count': 0, 'full_mismatch_count': 0},
'complex': {'results': [], 'execution_times': [], 'count': 0, 'full_matches': 0,
'exact_code_match_count': 0,
'pv_exact_match_count': 0, 'pv_exact_mismatch_count': 0, 'pv_match_rates': [],
'pv_mismatch_rates': [],
'timing_match_count': 0, 'timing_mismatch_count': 0,
'timing_scores': [], 'temp_scores': [], 'full_scores': [],
'temp_match_count': 0, 'temp_mismatch_count': 0,
'full_match_count': 0, 'full_mismatch_count': 0}
}
if not self.debug and not scientist_file:
# Preload the model and do a warm-up request
model = ModelManager.get_model(self.base_model)
# We should not use model cache for testing, because we're not using an actual model
if not self.use_cache:
print("Performing warm-up request...")
warmup_data = [{
'beamline': self.beamline,
'text_input': 'print hello',
'include_context_functions': True,
'only_text_input': 1,
'operator_cog_history': "",
'operator_cog_db_history': "",
'user_id': "test",
}]
invoke(warmup_data, base_model=self.base_model, finetuned=False, system_prompt_path=self.system_prompt_path)
print("Warm-up complete")
self.start_ipython_env()
self.setup_monitoring()
def _log_entries_match(self, gt, pred):
gt_pv, _, gt_val = gt
pr_pv, _, pr_val = pred
if gt_pv != pr_pv:
return False
if gt_pv in self.functions_to_log and \
self.functions_to_log[gt_pv].get("compare_params") is False:
return True
try:
return abs(float(gt_val) - float(pr_val)) < 1e-3
except (ValueError, TypeError):
return str(gt_val) == str(pr_val)
# ------------------------------------------------------------------
# PV‑name comparison that is used for sequence alignment _only_
# (value equality is checked later, after the alignment is fixed)
# ------------------------------------------------------------------
def _canonical_pv(self, pv: str) -> str:
"""Returns a canonical identifier for the PV (aliases can be added here if desired)."""
return pv
def _pv_equal(self, pv_a: str, pv_b: str) -> bool:
return self._canonical_pv(pv_a) == self._canonical_pv(pv_b)
# ------------------------------------------------------------------
# Linear-regression helper: R² + slope + duration + MAPE
# ------------------------------------------------------------------
def _timing_match(
self,
gt_ts, pr_ts,
r2_thresh=0.90,
slope_lo=0.8, slope_hi=1.2,
dur_tol=0.25, # 25% tolerance on total duration
mape_tol=1 # 100% tolerance on intervals
):
"""
Compare two sequences of timestamps.
Returns (match: bool, score: float, details: dict)
"""
n = len(gt_ts)
# Different number of timestamps -> immediate failure
if n != len(pr_ts):
return False, 0.0, {"reason": "length mismatch", "score": 0.0}
# One (or zero) timestamp: no timing regression can be computed,
# therefore consider the timing a match. This avoids false negatives
# when only a single intercepted call is logged (e.g., sam.align).
if n < 2:
return True, 1.0, {"score": 1.0}
gt = np.asarray(gt_ts) - gt_ts[0] # shift timestamps so first is zero
pr = np.asarray(pr_ts) - pr_ts[0]
res = linregress(gt, pr)
r2 = res.rvalue ** 2
slope = res.slope
# Calculate continuous score components
r2_score = r2
# Slope score: perfect=1.0 at slope=1, decreases as slope deviates
slope_score = 1.0 - min(abs(slope - 1.0), 1.0)
# Duration score
dur_gt, dur_pr = gt[-1], pr[-1]
if dur_gt == 0:
duration_score = 0.0
else:
duration_diff = abs(dur_pr - dur_gt) / dur_gt
duration_score = max(0, 1.0 - duration_diff / dur_tol)
# MAPE score on intervals
gt_intervals = np.diff(gt)
pr_intervals = np.diff(pr)
mape = calculate_mape(gt_intervals, pr_intervals)
mape_score = max(0, 1.0 - mape / mape_tol)
# Combined timing score (weighted average)
timing_score = (0.4 * r2_score + 0.2 * slope_score +
0.2 * duration_score + 0.2 * mape_score)
# Binary match decision (keep existing logic)
binary_match = (r2 >= r2_thresh and
slope_lo <= slope <= slope_hi and
(dur_gt == 0 or abs(dur_pr - dur_gt) / dur_gt <= dur_tol) and
mape <= mape_tol)
details = {
"r2": r2,
"slope": slope,
"mape": mape,
"duration_ratio": dur_pr / (dur_gt or 1),
"score": timing_score,
"r2_score": r2_score,
"slope_score": slope_score,
"duration_score": duration_score,
"mape_score": mape_score
}
return binary_match, timing_score, details
def _compute_pv_match_metrics(self, gt_logs, pr_logs):
n = len(gt_logs)
if n == 0:
# When no PV changes (or caught functions) have been observed, then exact match should've triggered,
# otherwise the codes can't be correct/equivalent if no PVs changes were tracked.
# All the examples should either be exactly matchable, or produce PV changes that are tracked.
return 0.0, 1.0, False, 0, [], []
# Lists with only the canonical PV names
gt_tokens = [self._canonical_pv(pv) for pv, _, _ in gt_logs]
pr_tokens = [self._canonical_pv(pv) for pv, _, _ in pr_logs]
# Alignment using difflib.SequenceMatcher (favors earlier matches)
sm = difflib.SequenceMatcher(None, gt_tokens, pr_tokens, autojunk=False)
aligned_gt, aligned_pr = [], []
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == "equal": # Identical PVs
for k in range(i2 - i1):
aligned_gt.append(gt_logs[i1 + k])
aligned_pr.append(pr_logs[j1 + k])
elif tag == "delete": # Only in GT
for k in range(i1, i2):
aligned_gt.append(gt_logs[k])
aligned_pr.append(None)
elif tag == "insert": # Only in Pred
for k in range(j1, j2):
aligned_gt.append(None)
aligned_pr.append(pr_logs[k])
else: # 'replace' → differences
span = max(i2 - i1, j2 - j1)
for off in range(span):
aligned_gt.append(gt_logs[i1 + off] if i1 + off < i2 else None)
aligned_pr.append(pr_logs[j1 + off] if j1 + off < j2 else None)
# Comparing values for aligned pairs
value_matches = sum(
1
for g, p in zip(aligned_gt, aligned_pr)
if g is not None and p is not None and self._log_entries_match(g, p)
)
total_pairs = len(aligned_gt) # this is equal to the number of rows in the comparison table
mismatches = total_pairs - value_matches
mismatch_rate = mismatches / total_pairs if total_pairs else 0.0
rate = value_matches / total_pairs if total_pairs else 1.0
exact = value_matches == n and value_matches == len(pr_logs)
return rate, mismatch_rate, exact, value_matches, aligned_gt, aligned_pr
def start_ipython_env(self):
print("Setting up command...")
repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
example_services = os.path.join(repo_root, "external", "example-services")
profile_collection = os.path.join(repo_root, "external", "profile_collection")
cmd = (
f'source $(conda info --base)/etc/profile.d/conda.sh && '
f'conda activate 2024-3.0-py311-tiled && '
f'source {example_services}/environment.sh && '
f'cd {profile_collection} && '
'./.ci/apply-autosettings.sh &&'
'ipython --profile-dir=. --no-term-title --simple-prompt'
)
print("Starting bash...")
self.interactive_shell = pexpect.spawn('/bin/bash', encoding='utf-8', timeout=30)
# Create log file in the same directory as results
log_path = os.path.join(os.path.dirname(self.results_path), 'pexpect.log')
self.log_file = open(log_path, 'a', encoding='utf-8', buffering=1) # Line buffered
self.interactive_shell.logfile = self.log_file #sys.stdout
print("Running IPython...")
self.interactive_shell.sendline(cmd)
# Wait for IPython prompt
self.interactive_shell.expect('In \\[[0-9]+\\]: ', timeout=300)
print("Sending drop-in command...")
self.interactive_shell.sendline('%run -i ./.ci/linkam-drop-in.py')
return self.interactive_shell
def _monitor_callback(self, pvname=None, value=None,
char_value=None, timestamp=None, **kwargs):
"""
EPICS monitor callback. Ignore PV changes that occurred before the
current snippet’s start-time, so previous test activity does not leak
into the present logs.
"""
# Use the EPICS timestamp if provided, otherwise the local clock
ts = float(timestamp) if timestamp is not None else time.time()
# Accept only events that happen during/after the active test window
if (self._current_test_start_time is None) or (ts >= self._current_test_start_time):
self.monitor_logs.append((pvname, ts, value))
def setup_monitoring(self):
self.monitor_logs = []
for pv in self.pvs_defaults:
camonitor(pv, callback=self._monitor_callback)
# Give monitors time to establish fully
time.sleep(1)
def reset_pvs(self):
pvs = list(self.pvs_defaults.keys())
values = list(self.pvs_defaults.values())
# 1st try – blocking put (wait until all PVs report success)
results = caput_many(
pvs, values,
wait="all",
connection_timeout=5,
put_timeout=60,
)
# Collect PVs that did NOT complete (caput_many returns -1)
failed_pvs = [pv for pv, r in zip(pvs, results) if r == -1]
if failed_pvs:
print(f"Warning: {len(failed_pvs)} PV resets timed-out – "
"retrying with instant motor-teleport.")
# ---------- classify failures ---------------------------------
motor_pvs = [pv for pv in failed_pvs if pv.endswith("Mtr")]
other_pvs = [pv for pv in failed_pvs if pv not in motor_pvs]
# ---------- instant reset for motors --------------------------
if motor_pvs:
motor_vals = [self.pvs_defaults[pv] for pv in motor_pvs]
set_fields = [pv + ".SET" for pv in motor_pvs]
val_fields = [pv + ".VAL" for pv in motor_pvs]
# 1) enter SET-mode
caput_many(set_fields, [1]*len(set_fields),
wait="all", connection_timeout=5, put_timeout=60)
# 2) override VAL (teleport)
caput_many(val_fields, motor_vals, wait=False)
# 3) leave SET-mode
caput_many(set_fields, [0]*len(set_fields), wait=False)
# ---------- non-motor PVs: simple fire-and-forget --------------
if other_pvs:
other_vals = [self.pvs_defaults[pv] for pv in other_pvs]
caput_many(other_pvs, other_vals, wait=False)
# short pause to allow network traffic to settle
time.sleep(2)
def initialize_environment(self):
"""Initialize the testing environment with required objects and settings."""
print("Waiting for initial prompt...")
patterns = self._error_expect_patterns()
try:
index = self.interactive_shell.expect(patterns, timeout=60)
print(f"Got initial prompt with index {index}")
# print("Buffer after prompt:", repr(self.interactive_shell.before))
# print("After buffer:", repr(self.interactive_shell.after))
except pexpect.TIMEOUT:
print("Timed out waiting for initial prompt")
# print("Final buffer state:", repr(self.interactive_shell.before))
# print("Final after buffer:", repr(self.interactive_shell.after))
raise
print("Initializing sample...")
self.interactive_shell.sendline("sam = Sample('test')")
print("Waiting for prompt after sample init...")
try:
index = self.interactive_shell.expect(patterns, timeout=30)
print(f"Got sample init prompt with index {index}")
print("Buffer after sample init:", repr(self.interactive_shell.before))
print("After buffer:", repr(self.interactive_shell.after))
print("Sample initialized")
except pexpect.TIMEOUT:
print("Timed out waiting for sample init prompt")
print("Final buffer state:", repr(self.interactive_shell.before))
print("Final after buffer:", repr(self.interactive_shell.after))
raise
def pre_process_code(self, code_string):
"""Process code to handle function calls that need special treatment."""
# Process functions that should be mocked out
for func, pattern in self.functions_to_mock.items():
matches = re.findall(pattern, code_string)
if matches:
for _ in matches:
# Log a dummy PV event for the mocked function call
self.monitor_logs.append((func, time.time(), 0))
code_string = re.sub(pattern, "", code_string)
# Process functions that should be logged with parameters but still executed
for func, config in self.functions_to_log.items():
pattern = config["pattern"]
param_formatter = config["param_format"]
matches = re.findall(pattern, code_string)
for match in matches:
# Use the custom formatting function to format parameters for logging
param_value = param_formatter(match if isinstance(match, tuple) else (match,))
# Log the function call with its parameters
self.monitor_logs.append((func, time.time(), param_value))
return code_string
def execute_snippet_in_mock_env(self, code_string, is_gt=False, is_complex=False):
# Check if we have cached results for this code snippet
# Previously we had that debug mode would re-run GT here, but I don't think that makes sense.
if self.use_cache or (is_gt and self.use_gt_cache) and self.execution_cache:
cached_logs = self.execution_cache.get(code_string)
# Previously our error regex was too inclusive, leading try except code throw a false positive.
# Therefore, if the code contains 'error' (case-insensitive), bypass any cached result
# and force re-execution to refresh potentially corrupted cache entries.
if cached_logs is not None and re.search(r'error', code_string, re.IGNORECASE):
print("[CACHE] Bypassing cache because code contains 'error' (case-insensitive); will re-execute and refresh cache.")
cached_logs = None
# Validate cache quality - don't use suspiciously small logs for complex code
if cached_logs is not None and is_gt:
# For ground truth execution, check if we have enough logs
# Complex code with loops should generate multiple PV changes
if len(cached_logs) < 3:
print(f"Warning: Cached ground truth logs only have {len(cached_logs)} entries")
if is_complex:
print("This is a complex example but has few PV changes in cache. Executing instead.")
cached_logs = None
if cached_logs is not None:
print(f"Using cached execution logs ({len(cached_logs)} entries)")
return cached_logs
# If not in cache or cache disabled, execute the code
print("Executing code snippet (not in cache)")
self.reset_pvs()
self.monitor_logs = [] # Reset logs before execution
# Mark the beginning of the logging window – anything earlier will be ignored
self._current_test_start_time = time.time()
try:
# Pre-process the code to remove (and log) mocked function calls
code_string = self.pre_process_code(code_string)
self.initialize_environment()
# Send the command
print(f"Sending command: {code_string}")
# Use %cpaste magic instead of sendline
self.interactive_shell.sendline("%cpaste -q") # -q for quiet mode
self.interactive_shell.sendline(code_string)
self.interactive_shell.sendline("--") # End of paste marker
# self.interactive_shell.sendline('') # End current block
# TODO: Perhaps only for complex control flows ending on for loops?
self.interactive_shell.sendline('') # Additional newline to confirm termination
# Look for either the next prompt or an error
patterns = self._error_expect_patterns()
while True:
try:
index = self.interactive_shell.expect(patterns, timeout=300)
if index == 0: # Got prompt
break
elif index in [1, 2, 3]: # Got error
# Start with what we have now (header/traceback/type)
error_message = self.interactive_shell.before + self.interactive_shell.after
# Try to collect the rest of the error block (exception line and "See ..." line) until the next prompt
try:
post_error_patterns = [
self.ERROR_LINE_RE,
re.compile(r'(?m)^\s*(?:\x1b\[[0-9;]*m)*See .+ for the full traceback\.'),
re.compile(self.IPYTHON_PROMPT),
]
while True:
try:
idx2 = self.interactive_shell.expect(post_error_patterns, timeout=2)
error_message += self.interactive_shell.before + self.interactive_shell.after
if idx2 == 2: # Prompt reached
break
except pexpect.TIMEOUT:
# No more output to collect
break
except Exception:
# If anything goes wrong while collecting, fall back to what we already captured
pass
# Format the error message for better readability
formatted_error = "\n" + "*"*80 + "\n"
formatted_error += "** ERROR DETECTED:\n"
formatted_error += "** " + "-"*76 + "\n"
for line in error_message.strip().split('\n'):
formatted_error += f"** {line}\n"
formatted_error += "*"*80
print(formatted_error)
# Capture logs before raising the exception
logs_snapshot = deepcopy(self.monitor_logs)
# Cache policy: do not cache an empty GT log, but tell the user.
if is_gt and len(logs_snapshot) == 0:
print("[INFO] Ground-truth snippet produced no PV logs – nothing cached.")
elif (self.use_cache or self.debug) and self.execution_cache:
self.execution_cache.put(code_string, logs_snapshot)
# Raise exception but include the logs we captured
error = ExecutionFailedError(error_message.strip())
error.logs = logs_snapshot
raise error
except pexpect.TIMEOUT:
print("Timeout in pattern match loop")
print("Current buffer:", repr(self.interactive_shell.before))
print("Current after buffer:", repr(self.interactive_shell.after))
# Capture logs before raising the exception
logs_snapshot = deepcopy(self.monitor_logs)
# Cache policy: do not cache an empty GT log, but tell the user.
if is_gt and len(logs_snapshot) == 0:
print("[INFO] Ground-truth snippet produced no PV logs – nothing cached.")
elif (self.use_cache or self.debug) and self.execution_cache:
self.execution_cache.put(code_string, logs_snapshot)
raise pexpect.TIMEOUT("Timeout in pattern match loop")
logs_snapshot = deepcopy(self.monitor_logs)
# Cache policy: do not cache an empty GT log, but tell the user.
if is_gt and len(logs_snapshot) == 0:
print("[INFO] Ground-truth snippet produced no PV logs – nothing cached.")
elif (self.use_cache or self.debug) and self.execution_cache:
self.execution_cache.put(code_string, logs_snapshot)
return logs_snapshot
except pexpect.TIMEOUT:
print("Execution timed out, sending Ctrl-C (twice) to shell.")
self.interactive_shell.sendintr() # Ctrl+C
time.sleep(1)
self.interactive_shell.sendintr()
time.sleep(1)
print("Sending RE.abort() to clean up.")
self.interactive_shell.sendline("RE.abort()")
time.sleep(1)
# Capture logs before raising the exception
logs_snapshot = deepcopy(self.monitor_logs)
# Cache the execution logs even though there was a timeout
if self.use_cache and self.execution_cache:
self.execution_cache.put(code_string, logs_snapshot)
# Create a cancellation error but include the logs we captured
error = ExecutionCancellationError("Snippet timed out, canceled by operator")
error.logs = logs_snapshot
raise error
except Exception as e:
# Create a nicely formatted error box
error_box = "\n" + "*"*80 + "\n"
error_box += "** EXECUTION ERROR\n"
error_box += "** " + "-"*76 + "\n"
# Add exception type and message
error_box += f"** Type: {type(e).__name__}\n"
# Only show detailed message if it's not already shown above
if isinstance(e, ExecutionFailedError):
error_box += f"** Details: See error output above\n"
else:
error_box += f"** Details: {str(e)}\n"
# Only show buffer contents for non-ExecutionFailedError exceptions
# since ExecutionFailedError already shows the full output
if self.interactive_shell.before.strip():
error_box += "** " + "-"*76 + "\n"
error_box += "** Last buffer content:\n"
error_box += "** " + "-"*76 + "\n"
for line in self.interactive_shell.before.strip().split('\n'):
error_box += f"** {line}\n"
if self.interactive_shell.after.strip():
error_box += "** " + "-"*76 + "\n"
error_box += "** After buffer content:\n"
error_box += "** " + "-"*76 + "\n"
for line in self.interactive_shell.after.strip().split('\n'):
error_box += f"** {line}\n"
error_box += "*"*80
print(error_box)
# For non-timeout, non-execution errors, we don't have logs to return
if not hasattr(e, 'logs'):
# Capture logs before re-raising the exception
logs_snapshot = deepcopy(self.monitor_logs)
# Cache policy: do not cache an empty GT log, but tell the user.
if is_gt and len(logs_snapshot) == 0:
print("[INFO] Ground-truth snippet produced no PV logs – nothing cached.")
elif self.use_cache and self.execution_cache:
self.execution_cache.put(code_string, logs_snapshot)
# Add logs to the exception
e.logs = logs_snapshot
raise
def test_entry(self, entry):
self._idx += 1 # will be 1-based
# Determine complexity type
is_complex = entry.get('is_complex', False)
complexity_type = 'complex' if is_complex else 'simple'
# Skip based on complexity filter settings
if hasattr(self, 'complex_only') and self.complex_only and not is_complex:
print(f"Skipping simple example (complex_only={self.complex_only}).")
return False
if hasattr(self, 'simple_only') and self.simple_only and is_complex:
print(f"Skipping complex example (simple_only={self.simple_only}).")
return False
command = entry['command']
expected_codes = entry['expected_code']
# Get list of PVs to ignore during comparison
ignore_pvs = set(entry.get('ignore_pvs', []))
data = [{
'beamline': self.beamline,
'text_input': command,
'include_context_functions': True,
'only_text_input': 1,
'operator_cog_history': "",
'operator_cog_db_history': "",
'user_id': "test",
}]
# Execute both ground truth and predicted code
ground_truth_snippet = expected_codes[0] # Use first expected code
start_time = time.time()
# --- 1) scientist-provided answer? ------------------------------------
using_scientist_answer = command in self.scientist_map
if using_scientist_answer:
generated_code = self.scientist_map[command]['code']
print(f"Using scientist answer for command: {command}")
elif self.scientist_map:
raise ValueError("Human code does not cover all code cases it is assigned to:", command)
# --- 2) debug mode -----------------------------------------------------
elif self.debug:
self.system_prompt = "debug"
generated_code = ground_truth_snippet
# --- 3) normal LLM invocation with retry logic for empty responses ----
else:
max_retries = 5
retry_count = 0
generated_code = ""
while retry_count < max_retries:
cog_result = invoke(data, base_model=self.base_model,
finetuned=False,
system_prompt_path=self.system_prompt_path)
generated_code = cog_result[0][f'{CogType.OP.value}_cog_output']
# Check if the response is empty or contains only whitespace
if generated_code and generated_code.strip():
break # Got a valid response, exit retry loop
# Exponential backoff
time.sleep(min(int(5 ** retry_count), 60))
retry_count += 1
if retry_count < max_retries:
print(f"Warning: Model returned empty response. Retrying... (attempt {retry_count + 1}/{max_retries})")
else:
print(f"Error: Model returned empty response after {max_retries} attempts.")
# Keep the empty string if all retries failed
end_time = time.time()
inference_time = end_time - start_time
self.execution_times.append(inference_time)
print(f"{inference_time=}")
# --------------------------------------------------------------
# Pre-compute code-string similarity metrics before simulation
# --------------------------------------------------------------
generated_code_clean = strip_comments(generated_code)
expected_codes_clean = [strip_comments(code) for code in expected_codes]
exact_match = any(
generated_code_clean.strip() == exp.strip()
for exp in expected_codes_clean
)
if self.debug:
exact_match = False
codebleu_scores = []
for exp in expected_codes_clean:
# 2.1 old (= average) weighting -----------------------------
_avg = calc_codebleu([exp], [generated_code_clean],
lang="python",
weights=(0.25, 0.25, 0.25, 0.25),
tokenizer=None)
# 2.2 new (= comb-7) weighting ------------------------------
_c7 = calc_codebleu([exp], [generated_code_clean],
lang="python",
weights=(0.10, 0.10, 0.40, 0.40),
tokenizer=None)
# 2.3 merge into a single dict ------------------------------
comb = _avg.copy() # keeps n-gram, syntax, …
comb["average_CodeBLEU"] = comb.pop("codebleu")
comb["comb_7_CodeBLEU"] = _c7["codebleu"]
codebleu_scores.append(comb)
levenshtein_distances = [
Levenshtein.distance(generated_code_clean, exp)
for exp in expected_codes_clean
]
normalized_levenshtein_distances = [
d / max(len(generated_code_clean), len(exp))
for d, exp in zip(levenshtein_distances, expected_codes_clean)
]
best_codebleu_output = max(codebleu_scores,
key=lambda x: x["comb_7_CodeBLEU"])
best_levenshtein_distance = min(levenshtein_distances)
best_normalized_levenshtein_distance = min(normalized_levenshtein_distances)
# ------------------------------------------------------------------
# Default values for execution-comparison metrics; may be overwritten
# in the non-exact-match branch.
# ------------------------------------------------------------------
pv_match_rate = 1.0
pv_mismatch_rate = 0.0
exact_pv_match = True
# --------------------------------------------------------------
# If the generated code is an exact match, skip the simulator
# --------------------------------------------------------------
if exact_match and not self.debug:
# One-line summary in case of exact match
print(f"[{self._idx}] EXACT MATCH │ Command: {command} │ Predicted: {generated_code.strip()}")
pv_match_rate = 1.0
pv_mismatch_rate = 0.0
exact_pv_match = True
timing_match = True
timing_score = 1.0
temp_match = True # no temp PVs involved
temp_score = 1.0
full_match = True
full_score = 1.0
# For exact matches, we still need to store empty PV logs
gt_pv_logs = []
pred_pv_logs = []
aligned_gt_logs = []
aligned_pred_logs = []
# New: dummy temp logs for CSV
gt_temp_logs = []
pred_temp_logs = []
# Additional metrics for CSV
temperature_involved = False
pv_value_matches = 0
pv_total_pairs = 0
num_gt_pv_events = 0
num_pred_pv_events = 0
timing_r2 = None
timing_slope = None
timing_mape = None
timing_duration_ratio = None
timing_details = {}
temp_details = {}
# ----------------------------------------------------------
# UPDATE METRICS for this exact-match entry
# ----------------------------------------------------------
self.metrics[complexity_type]['exact_code_match_count'] += 1
self.metrics[complexity_type]['pv_exact_match_count'] += 1
self.metrics[complexity_type]['pv_match_rates'].append(1.0)
self.metrics[complexity_type]['pv_mismatch_rates'].append(0.0)
self.metrics[complexity_type]['timing_match_count'] += 1
self.metrics[complexity_type]['timing_scores'].append(1.0)
self.metrics[complexity_type]['temp_scores'].append(1.0)
self.metrics[complexity_type]['full_scores'].append(1.0)
self.metrics[complexity_type]['full_match_count'] += 1
# (temperature counters stay unchanged – no temp PVs)
if self.system_prompt is None and not self.debug and not using_scientist_answer:
self.system_prompt = get_data_field(cog_result, CogType.OP, "system_prompt")
self._record_result(
complexity_type = complexity_type,
command = command,
expected_codes = expected_codes,
generated_code = generated_code,
exact_match = exact_match,
inference_time = inference_time,
pv_match_rate = pv_match_rate,
pv_mismatch_rate = pv_mismatch_rate,
exact_pv_match = exact_pv_match,
timing_match = timing_match,
temp_match = temp_match,
timing_score = timing_score,
temp_score = temp_score,
full_score = full_score,
temperature_involved = temperature_involved,