-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_full_analysis.py
More file actions
executable file
·509 lines (411 loc) · 19.3 KB
/
run_full_analysis.py
File metadata and controls
executable file
·509 lines (411 loc) · 19.3 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
#!/usr/bin/env python3
"""
Master script to run complete analysis pipeline on auction data.
This script:
1. Scans auction data directory for solutions
2. Filters out empty solutions
3. Generates detailed analysis JSON files
4. Runs verification checks
5. Produces summary reports
6. Saves results to timestamped output directory
"""
import json
import os
import sys
import subprocess
from pathlib import Path
from datetime import datetime
from collections import defaultdict
def print_header(title, width=100):
"""Print a nice header."""
print("\n" + "=" * width)
print(f"{title:^{width}}")
print("=" * width)
def print_section(title, width=100):
"""Print a section divider."""
print(f"\n{title}")
print("-" * width)
def check_solutions(auction_dir):
"""Check which auction files have solutions."""
print_header("STEP 1: SCANNING FOR SOLUTIONS")
solution_files = sorted(auction_dir.glob("*_solutions.json"))
stats = {
'total': len(solution_files),
'with_solutions': 0,
'empty': 0,
'errors': 0,
'auction_ids': [],
'empty_auction_ids': []
}
print(f"Scanning {stats['total']} solution files...")
for solution_file in solution_files:
# Skip enhanced solutions
if 'enhanced' in solution_file.name:
continue
auction_id = solution_file.stem.replace('_solutions', '')
try:
with open(solution_file) as f:
data = json.load(f)
solutions = data.get('solutions', [])
if solutions and len(solutions) > 0:
stats['with_solutions'] += 1
stats['auction_ids'].append(auction_id)
else:
stats['empty'] += 1
stats['empty_auction_ids'].append(auction_id)
except Exception as e:
stats['errors'] += 1
print(f" ✗ Error reading {solution_file.name}: {e}")
print_section("SOLUTION SCAN RESULTS")
print(f"Total solution files: {stats['total']:>6}")
print(f"With solutions: {stats['with_solutions']:>6} ({stats['with_solutions']/max(stats['total'],1)*100:.1f}%)")
print(f"Empty (no solutions): {stats['empty']:>6} ({stats['empty']/max(stats['total'],1)*100:.1f}%)")
print(f"Errors reading file: {stats['errors']:>6}")
return stats
def cleanup_empty_auctions(auction_dir, empty_auction_ids):
"""Remove auction files that don't have solutions."""
print_header("STEP 2: CLEANING UP EMPTY AUCTION FILES")
if not empty_auction_ids:
print("✓ No empty auction files to clean up")
return 0
print(f"Found {len(empty_auction_ids)} auctions without solutions")
print("These files will be removed to save space...")
# File patterns to remove for each auction
file_patterns = [
'_auction.json',
'_competition.json',
'_liquidity.json',
'_solutions.json',
'_enhanced_solutions.json',
'_solution_verification.json',
'_analysis.json'
]
removed_count = 0
total_size = 0
for auction_id in empty_auction_ids:
for pattern in file_patterns:
file_path = auction_dir / f"{auction_id}{pattern}"
if file_path.exists():
try:
size = file_path.stat().st_size
file_path.unlink()
removed_count += 1
total_size += size
except Exception as e:
print(f" ✗ Error removing {file_path.name}: {e}")
# Convert size to human readable
if total_size < 1024:
size_str = f"{total_size} bytes"
elif total_size < 1024 * 1024:
size_str = f"{total_size / 1024:.1f} KB"
else:
size_str = f"{total_size / (1024 * 1024):.1f} MB"
print_section("CLEANUP RESULTS")
print(f"Files removed: {removed_count:>6}")
print(f"Space freed: {size_str:>12}")
print(f"Auctions cleaned: {len(empty_auction_ids):>6}")
return removed_count
def check_required_files(auction_dir, auction_ids):
"""Check which auctions have all required files for analysis."""
print_header("STEP 3: CHECKING REQUIRED FILES")
required_suffixes = ['_auction.json', '_competition.json', '_liquidity.json', '_solutions.json']
valid_auctions = []
missing_files = defaultdict(list)
for auction_id in auction_ids:
has_all = True
for suffix in required_suffixes:
file_path = auction_dir / f"{auction_id}{suffix}"
if not file_path.exists():
has_all = False
missing_files[auction_id].append(suffix)
if has_all:
valid_auctions.append(auction_id)
print(f"\nAuctions with solutions: {len(auction_ids)}")
print(f"Auctions with all files: {len(valid_auctions)}")
print(f"Auctions missing files: {len(auction_ids) - len(valid_auctions)}")
if missing_files:
print_section("MISSING FILES")
for auction_id, missing in sorted(missing_files.items())[:10]:
print(f" Auction {auction_id}: missing {', '.join(missing)}")
if len(missing_files) > 10:
print(f" ... and {len(missing_files) - 10} more")
return valid_auctions
def generate_analysis(auction_dir, auction_ids):
"""Generate detailed analysis JSON files."""
print_header("STEP 4: GENERATING DETAILED ANALYSIS")
print(f"Generating analysis for {len(auction_ids)} auctions...")
print("This may take a moment...\n")
try:
# Run the detailed comparison script (from the parent directory)
script_dir = Path(__file__).parent
result = subprocess.run(
['python3', str(script_dir / 'compare_solutions_detailed.py')],
capture_output=True,
text=True,
timeout=300 # 5 minute timeout
)
if result.returncode != 0:
print(f"✗ Error running analysis script:")
print(result.stderr)
return False
# Count generated files
analysis_files = list(auction_dir.glob("*_analysis.json"))
print(f"✓ Generated {len(analysis_files)} analysis files")
return True
except subprocess.TimeoutExpired:
print("✗ Analysis timed out after 5 minutes")
return False
except Exception as e:
print(f"✗ Error running analysis: {e}")
return False
def run_verification(auction_dir):
"""Run solution verification checks."""
print_header("STEP 5: RUNNING VERIFICATION CHECKS")
print("Checking solution accuracy via on-chain verification...\n")
try:
script_dir = Path(__file__).parent
result = subprocess.run(
['python3', str(script_dir / 'check_verification.py')],
capture_output=True,
text=True,
timeout=300
)
# Print the output
print(result.stdout)
if result.returncode != 0:
print(f"\n✗ Verification had issues:")
print(result.stderr)
return False
return True
except subprocess.TimeoutExpired:
print("✗ Verification timed out after 5 minutes")
return False
except Exception as e:
print(f"✗ Error running verification: {e}")
return False
def generate_summary_report(auction_dir):
"""Generate summary statistics from analysis files."""
print_header("STEP 6: GENERATING SUMMARY REPORT")
analysis_files = list(auction_dir.glob("*_analysis.json"))
if not analysis_files:
print("✗ No analysis files found")
return None
stats = {
'total_auctions': len(analysis_files),
'valid_solutions': 0,
'competitive': 0,
'beat_winner': 0,
'total_surplus': 0,
'pool_types': defaultdict(int),
'pool_versions': defaultdict(int),
'pool_addresses': defaultdict(lambda: {'count': 0, 'wins': 0, 'type': '', 'version': '', 'fee': ''}),
'wins': [],
'losses': []
}
for analysis_file in analysis_files:
try:
with open(analysis_file) as f:
data = json.load(f)
auction_id = data['auction_id']
is_win = data.get('beat_winner', False)
# Load verification file to get pool versions
verification_file = auction_dir / f"{auction_id}_solution_verification.json"
pool_version_map = {}
if verification_file.exists():
try:
with open(verification_file) as vf:
verif_data = json.load(vf)
for solution in verif_data:
for swap in solution.get('swaps', []):
pool_id = swap.get('pool_id')
pool_version = swap.get('pool_version', 'Unknown')
if pool_id:
pool_version_map[pool_id] = pool_version
except:
pass
if data.get('valid'):
stats['valid_solutions'] += 1
if data.get('competitive'):
stats['competitive'] += 1
if is_win:
stats['beat_winner'] += 1
stats['wins'].append({
'auction_id': auction_id,
'pool_type': list(data['pool_stats'].keys())[0] if data['pool_stats'] else 'unknown'
})
else:
stats['losses'].append({
'auction_id': auction_id,
'pool_type': list(data['pool_stats'].keys())[0] if data['pool_stats'] else 'unknown'
})
# Pool statistics
for pool_type, count in data.get('pool_stats', {}).items():
stats['pool_types'][pool_type] += count
# Extract pool information from interactions
for interaction in data.get('interactions', []):
pool_id = interaction.get('pool_id', '')
pool_address = interaction.get('pool_address', '')
pool_kind = interaction.get('pool_kind', '')
pool_fee = interaction.get('pool_fee', '')
pool_version = pool_version_map.get(pool_id, 'Unknown')
if pool_address:
stats['pool_addresses'][pool_address]['count'] += 1
if is_win:
stats['pool_addresses'][pool_address]['wins'] += 1
stats['pool_addresses'][pool_address]['type'] = pool_kind
stats['pool_addresses'][pool_address]['version'] = pool_version
stats['pool_addresses'][pool_address]['fee'] = pool_fee
# Track pool versions
if pool_version != 'Unknown':
stats['pool_versions'][pool_version] += 1
# Calculate surplus
for trade in data.get('trades', []):
stats['total_surplus'] += trade.get('surplus_vs_min_pct', 0)
except Exception as e:
print(f" ✗ Error reading {analysis_file.name}: {e}")
# Calculate averages
avg_surplus = stats['total_surplus'] / max(stats['total_auctions'], 1)
# Print summary
print_section("PERFORMANCE SUMMARY")
print(f"Total Auctions Analyzed: {stats['total_auctions']:>6}")
print(f"Valid Solutions: {stats['valid_solutions']:>6} ({stats['valid_solutions']/max(stats['total_auctions'],1)*100:.1f}%)")
print(f"Beat Winner: {stats['beat_winner']:>6} ({stats['beat_winner']/max(stats['total_auctions'],1)*100:.1f}%)")
print(f"Average Surplus: {avg_surplus:>6.2f}%")
print_section("POOL VERSIONS")
total_versions = sum(stats['pool_versions'].values())
for version, count in sorted(stats['pool_versions'].items(), key=lambda x: -x[1]):
pct = count / max(total_versions, 1) * 100
print(f" {version:<20} {count:>4} ({pct:>5.1f}%)")
print_section("POOL TYPES")
total_pool_usages = sum(stats['pool_types'].values())
for pool_type, count in sorted(stats['pool_types'].items(), key=lambda x: -x[1]):
pct = count / max(total_pool_usages, 1) * 100
print(f" {pool_type:<20} {count:>4} ({pct:>5.1f}%)")
print_section("SPECIFIC POOLS USED")
for pool_address, info in sorted(stats['pool_addresses'].items(), key=lambda x: -x[1]['count']):
win_rate = (info['wins'] / info['count'] * 100) if info['count'] > 0 else 0
print(f" {pool_address}")
print(f" Version: {info['version']:<5} Type: {info['type']:<20} Fee: {info['fee']}")
print(f" Uses: {info['count']:>3} Wins: {info['wins']:>3} Win Rate: {win_rate:>5.1f}%")
print_section("WINS")
if stats['wins']:
for win in stats['wins'][:10]:
print(f" ✓ Auction {win['auction_id']} ({win['pool_type']})")
if len(stats['wins']) > 10:
print(f" ... and {len(stats['wins']) - 10} more")
else:
print(" No wins in this dataset")
return stats
def save_report(stats, output_dir):
"""Save analysis report to JSON file."""
print_header("STEP 7: SAVING REPORT")
# Create output directory with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
report_dir = output_dir / f"analysis_report_{timestamp}"
report_dir.mkdir(parents=True, exist_ok=True)
# Save stats
report_file = report_dir / "summary_report.json"
with open(report_file, 'w') as f:
json.dump(stats, f, indent=2, default=str)
print(f"✓ Report saved to: {report_file}")
# Create markdown report
md_file = report_dir / "ANALYSIS_REPORT.md"
with open(md_file, 'w') as f:
f.write(f"# Solution Analysis Report\n\n")
f.write(f"**Generated**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
f.write(f"## Summary\n\n")
f.write(f"- Total Auctions: {stats['total_auctions']}\n")
f.write(f"- Valid Solutions: {stats['valid_solutions']} ({stats['valid_solutions']/max(stats['total_auctions'],1)*100:.1f}%)\n")
f.write(f"- Win Rate: {stats['beat_winner']} / {stats['total_auctions']} ({stats['beat_winner']/max(stats['total_auctions'],1)*100:.1f}%)\n")
f.write(f"- Average Surplus: {stats['total_surplus']/max(stats['total_auctions'],1):.2f}%\n\n")
f.write(f"## Pool Versions\n\n")
total_versions = sum(stats['pool_versions'].values())
for version, count in sorted(stats['pool_versions'].items(), key=lambda x: -x[1]):
pct = count / max(total_versions, 1) * 100
f.write(f"- {version}: {count} ({pct:.1f}%)\n")
f.write(f"\n## Pool Types\n\n")
total_pool_usages = sum(stats['pool_types'].values())
for pool_type, count in sorted(stats['pool_types'].items(), key=lambda x: -x[1]):
pct = count / max(total_pool_usages, 1) * 100
f.write(f"- {pool_type}: {count} ({pct:.1f}%)\n")
f.write(f"\n## Specific Pools Used\n\n")
for pool_address, info in sorted(stats['pool_addresses'].items(), key=lambda x: -x[1]['count']):
win_rate = (info['wins'] / info['count'] * 100) if info['count'] > 0 else 0
f.write(f"### Pool: `{pool_address}`\n\n")
f.write(f"- **Version**: {info['version']}\n")
f.write(f"- **Type**: {info['type']}\n")
f.write(f"- **Fee**: {info['fee']}\n")
f.write(f"- **Total Uses**: {info['count']}\n")
f.write(f"- **Wins**: {info['wins']} ({win_rate:.1f}% win rate)\n\n")
f.write(f"\n## Wins ({len(stats['wins'])})\n\n")
for win in stats['wins']:
f.write(f"- Auction {win['auction_id']} ({win['pool_type']})\n")
f.write(f"\n## Losses ({len(stats['losses'])})\n\n")
for loss in stats['losses']:
f.write(f"- Auction {loss['auction_id']} ({loss['pool_type']})\n")
print(f"✓ Markdown report saved to: {md_file}")
return report_dir
def main():
"""Main execution function."""
print_header("BALANCER SOLVER - COMPLETE ANALYSIS PIPELINE", 100)
print(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# Configuration
auction_dir = Path(os.environ.get("AUCTION_DIR", "/tmp/auction-data/arbitrum"))
output_dir = Path("analysis_reports")
output_dir.mkdir(exist_ok=True)
if not auction_dir.exists():
print(f"\n✗ Error: Auction directory not found: {auction_dir}")
print("Please make sure auction data exists or set AUCTION_DIR env var")
return 1
# Step 1: Scan for solutions
solution_stats = check_solutions(auction_dir)
# Step 2: Clean up empty auction files (always run, even if no solutions)
cleanup_empty_auctions(auction_dir, solution_stats['empty_auction_ids'])
if solution_stats['with_solutions'] == 0:
print("\n✗ No solutions found in auction data!")
print("But empty files were cleaned up. ✓")
return 0 # Exit successfully after cleanup
# Step 3: Check required files
valid_auctions = check_required_files(auction_dir, solution_stats['auction_ids'])
if not valid_auctions:
print("\n✗ No auctions have all required files!")
print("Each auction needs: _auction.json, _competition.json, _liquidity.json, _solutions.json")
return 1
print(f"\n✓ Found {len(valid_auctions)} auctions ready for analysis")
# Step 4: Generate analysis
if not generate_analysis(auction_dir, valid_auctions):
print("\n✗ Failed to generate analysis")
return 1
# Step 5: Run verification (optional, can fail without stopping)
print("\n" + "=" * 100)
run_verification(auction_dir)
# Step 6: Generate summary
stats = generate_summary_report(auction_dir)
if not stats:
print("\n✗ Failed to generate summary report")
return 1
# Step 7: Save report
report_dir = save_report(stats, output_dir)
# Final summary
print_header("ANALYSIS COMPLETE", 100)
print(f"Finished: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"\n✓ Analyzed {stats['total_auctions']} auctions")
print(f"✓ Win rate: {stats['beat_winner']}/{stats['total_auctions']} ({stats['beat_winner']/max(stats['total_auctions'],1)*100:.1f}%)")
print(f"✓ Reports saved to: {report_dir}")
print("\n💡 Next steps:")
print(f" 1. View summary: python3 view_analysis.py summary")
print(f" 2. View details: python3 view_analysis.py list")
print(f" 3. Check pools: python3 view_analysis.py pools")
print(f" 4. Read report: cat {report_dir / 'ANALYSIS_REPORT.md'}")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\n\n✗ Analysis interrupted by user")
sys.exit(1)
except Exception as e:
print(f"\n\n✗ Unexpected error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)