Skip to content

Commit 9ee9be0

Browse files
committed
some junk. still not working.
1 parent 8e8d5fb commit 9ee9be0

File tree

585 files changed

+7999
-5793
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

585 files changed

+7999
-5793
lines changed

compare_goldenfiles.py

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Compare local golden files with those from the mflowcode/mfc repository.
4+
Prints the maximum difference for each test case.
5+
6+
Usage:
7+
python3 compare_goldenfiles.py [--limit N] [--test UUID]
8+
"""
9+
10+
import os
11+
import sys
12+
import argparse
13+
import numpy as np
14+
import urllib.request
15+
import urllib.error
16+
from pathlib import Path
17+
from concurrent.futures import ThreadPoolExecutor, as_completed
18+
19+
20+
def get_test_case_info(test_path):
21+
"""Extract test case information from case.py file."""
22+
case_py = test_path / "case.py"
23+
if not case_py.exists():
24+
return "Unknown"
25+
26+
try:
27+
with open(case_py, 'r') as f:
28+
lines = f.readlines()
29+
# Look for line 4 (index 3) which has the test case description
30+
# Format: # 1D -> Example -> hypo_2materials
31+
if len(lines) >= 4:
32+
line = lines[3].strip()
33+
if line.startswith('#'):
34+
desc = line[1:].strip() # Remove leading '#' and whitespace
35+
return desc
36+
except Exception:
37+
pass
38+
39+
return "Unknown"
40+
41+
42+
def fetch_repo_golden_file(test_uuid):
43+
"""Fetch a golden file from GitHub raw content."""
44+
url = f"https://raw.githubusercontent.com/mflowcode/mfc/master/tests/{test_uuid}/golden.txt"
45+
try:
46+
with urllib.request.urlopen(url, timeout=10) as response:
47+
return response.read().decode('utf-8')
48+
except urllib.error.HTTPError as e:
49+
if e.code == 404:
50+
return None
51+
return None
52+
except Exception:
53+
return None
54+
55+
56+
def parse_golden_data(text):
57+
"""Parse golden file text into numpy array, skipping non-numeric tokens."""
58+
values = text.split()
59+
floats = []
60+
for v in values:
61+
try:
62+
floats.append(float(v))
63+
except ValueError:
64+
# Skip non-numeric tokens (like file paths)
65+
continue
66+
return np.array(floats) if floats else np.array([])
67+
68+
69+
def compare_single_test(test_uuid, local_path, tolerance=1e-12):
70+
"""Compare a single test's golden file."""
71+
local_test_path = local_path / test_uuid
72+
local_golden_path = local_test_path / "golden.txt"
73+
74+
if not local_golden_path.exists():
75+
return test_uuid, "Unknown", "SKIP", "No local golden file"
76+
77+
# Get test case info
78+
case_info = get_test_case_info(local_test_path)
79+
80+
# Fetch repository version
81+
repo_content = fetch_repo_golden_file(test_uuid)
82+
if repo_content is None:
83+
return test_uuid, case_info, "SKIP", "Not found in repository"
84+
85+
try:
86+
# Load and compare data
87+
with open(local_golden_path, 'r') as f:
88+
local_content = f.read()
89+
90+
repo_data = parse_golden_data(repo_content)
91+
local_data = parse_golden_data(local_content)
92+
93+
if repo_data.size == 0 or local_data.size == 0:
94+
return test_uuid, case_info, "SKIP", "Empty or no numeric data"
95+
96+
if repo_data.shape != local_data.shape:
97+
return test_uuid, case_info, "DIFF", f"Shape mismatch. Repo: {repo_data.shape}, Local: {local_data.shape}"
98+
99+
# Compute differences
100+
diff = np.abs(repo_data - local_data)
101+
max_diff = np.max(diff)
102+
103+
if max_diff > tolerance:
104+
return test_uuid, case_info, "DIFF", f"Max difference = {max_diff:.10e}"
105+
else:
106+
return test_uuid, case_info, "OK", f"Max difference = {max_diff:.10e}"
107+
108+
except Exception as e:
109+
return test_uuid, case_info, "ERROR", str(e)
110+
111+
112+
def compare_golden_files(local_tests_dir, limit=None, specific_test=None, max_workers=10, show_ok=False):
113+
"""Compare local golden files with repository versions."""
114+
local_path = Path(local_tests_dir)
115+
116+
if not local_path.exists():
117+
print(f"Error: Local tests directory not found: {local_tests_dir}")
118+
return
119+
120+
# Get all local test directories
121+
if specific_test:
122+
test_dirs = [specific_test]
123+
else:
124+
test_dirs = sorted([d for d in os.listdir(local_path)
125+
if os.path.isdir(local_path / d)])
126+
if limit:
127+
test_dirs = test_dirs[:limit]
128+
129+
print(f"Comparing {len(test_dirs)} test(s)...")
130+
print("-" * 80)
131+
132+
differences_found = False
133+
ok_count = 0
134+
diff_count = 0
135+
skip_count = 0
136+
error_count = 0
137+
max_diff_overall = 0.0
138+
max_diff_test = None
139+
max_diff_case = None
140+
141+
results = []
142+
143+
# Use ThreadPoolExecutor for parallel fetching
144+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
145+
futures = {executor.submit(compare_single_test, test_uuid, local_path): test_uuid
146+
for test_uuid in test_dirs}
147+
148+
for future in as_completed(futures):
149+
test_uuid, case_info, status, message = future.result()
150+
results.append((test_uuid, case_info, status, message))
151+
152+
if status == "OK":
153+
ok_count += 1
154+
# Extract the max diff value
155+
try:
156+
diff_val = float(message.split('=')[1].strip())
157+
if diff_val > max_diff_overall:
158+
max_diff_overall = diff_val
159+
max_diff_test = test_uuid
160+
max_diff_case = case_info
161+
except:
162+
pass
163+
elif status == "DIFF":
164+
diff_count += 1
165+
differences_found = True
166+
# Extract the max diff value if present
167+
try:
168+
if 'Max difference' in message:
169+
diff_val = float(message.split('=')[1].strip())
170+
if diff_val > max_diff_overall:
171+
max_diff_overall = diff_val
172+
max_diff_test = test_uuid
173+
max_diff_case = case_info
174+
except:
175+
pass
176+
elif status == "SKIP":
177+
skip_count += 1
178+
elif status == "ERROR":
179+
error_count += 1
180+
differences_found = True
181+
182+
# Sort results by status and test UUID
183+
status_order = {"DIFF": 0, "ERROR": 1, "OK": 2, "SKIP": 3}
184+
results.sort(key=lambda x: (status_order[x[2]], x[0]))
185+
186+
# Print results
187+
for test_uuid, case_info, status, message in results:
188+
if status == "DIFF":
189+
print(f" [DIFF] {test_uuid}: {case_info}")
190+
print(f" {message}")
191+
elif status == "ERROR":
192+
print(f" [ERROR] {test_uuid}: {case_info}")
193+
print(f" {message}")
194+
elif status == "OK" and show_ok:
195+
print(f" [OK] {test_uuid}: {case_info}")
196+
print(f" {message}")
197+
# Skip printing SKIP status unless explicitly requested
198+
199+
print("-" * 80)
200+
print(f"\nSummary:")
201+
print(f" OK: {ok_count}")
202+
print(f" DIFF: {diff_count}")
203+
print(f" SKIP: {skip_count}")
204+
print(f" ERROR: {error_count}")
205+
206+
if max_diff_test:
207+
print(f"\nMaximum difference: {max_diff_overall:.10e}")
208+
print(f" Test: {max_diff_test}")
209+
print(f" Case: {max_diff_case}")
210+
211+
if not differences_found:
212+
print("\n✓ No significant differences found!")
213+
else:
214+
print(f"\n✗ Differences found in {diff_count} golden files")
215+
216+
217+
if __name__ == "__main__":
218+
parser = argparse.ArgumentParser(description='Compare MFC golden files with repository')
219+
parser.add_argument('--limit', type=int, help='Limit number of tests to compare')
220+
parser.add_argument('--test', type=str, help='Compare specific test UUID')
221+
parser.add_argument('--workers', type=int, default=10, help='Number of parallel workers (default: 10)')
222+
parser.add_argument('--show-ok', action='store_true', help='Show OK results in detail')
223+
224+
args = parser.parse_args()
225+
226+
script_dir = Path(__file__).parent.absolute()
227+
tests_dir = script_dir / "tests"
228+
compare_golden_files(tests_dir, limit=args.limit, specific_test=args.test,
229+
max_workers=args.workers, show_ok=args.show_ok)

0 commit comments

Comments
 (0)