Spaces:
Sleeping
Sleeping
File size: 13,158 Bytes
6413ecc |
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 |
"""
Evaluation metrics for the quantum finance feasibility framework.
Metrics defined per plan.md:
1. Expert Alignment: Agreement with literature/expert consensus
2. Hallucination Rate: Factual accuracy of agent outputs
3. Computational Efficiency: Agent rounds and time per evaluation
"""
import re
import time
from dataclasses import dataclass, field
from typing import Optional
from datetime import datetime
@dataclass
class EvaluationMetrics:
"""Container for evaluation metrics of a single run."""
idea: str
start_time: datetime = field(default_factory=datetime.now)
end_time: Optional[datetime] = None
# Computational efficiency metrics
total_agent_rounds: int = 0
total_tokens_used: int = 0
wall_clock_time_seconds: float = 0.0
# Quality metrics (to be assessed manually or via comparison)
expert_alignment_score: Optional[float] = None # 0-1 scale
hallucination_count: int = 0
factual_claims_count: int = 0
# Output scores from agents
quantum_feasibility_score: Optional[float] = None
hardware_readiness_score: Optional[float] = None
classical_competitiveness_score: Optional[float] = None
business_viability_score: Optional[float] = None
overall_score: Optional[float] = None
def complete(self):
"""Mark evaluation as complete and calculate duration."""
self.end_time = datetime.now()
self.wall_clock_time_seconds = (self.end_time - self.start_time).total_seconds()
@property
def hallucination_rate(self) -> Optional[float]:
"""Calculate hallucination rate as fraction of factual claims."""
if self.factual_claims_count == 0:
return None
return self.hallucination_count / self.factual_claims_count
def to_dict(self) -> dict:
"""Convert to dictionary for serialization."""
return {
'idea': self.idea,
'start_time': self.start_time.isoformat(),
'end_time': self.end_time.isoformat() if self.end_time else None,
'total_agent_rounds': self.total_agent_rounds,
'total_tokens_used': self.total_tokens_used,
'wall_clock_time_seconds': self.wall_clock_time_seconds,
'expert_alignment_score': self.expert_alignment_score,
'hallucination_rate': self.hallucination_rate,
'quantum_feasibility_score': self.quantum_feasibility_score,
'hardware_readiness_score': self.hardware_readiness_score,
'classical_competitiveness_score': self.classical_competitiveness_score,
'business_viability_score': self.business_viability_score,
'overall_score': self.overall_score
}
class MetricsCollector:
"""Collect and aggregate metrics across multiple evaluations."""
def __init__(self):
self.evaluations: list[EvaluationMetrics] = []
def start_evaluation(self, idea: str) -> EvaluationMetrics:
"""Start tracking a new evaluation."""
metrics = EvaluationMetrics(idea=idea)
self.evaluations.append(metrics)
return metrics
def get_summary_statistics(self) -> dict:
"""Calculate summary statistics across all evaluations."""
if not self.evaluations:
return {'error': 'No evaluations recorded'}
completed = [e for e in self.evaluations if e.end_time is not None]
if not completed:
return {'error': 'No completed evaluations'}
times = [e.wall_clock_time_seconds for e in completed]
rounds = [e.total_agent_rounds for e in completed]
alignment_scores = [e.expert_alignment_score for e in completed
if e.expert_alignment_score is not None]
overall_scores = [e.overall_score for e in completed
if e.overall_score is not None]
import numpy as np
return {
'total_evaluations': len(completed),
'timing': {
'mean_seconds': np.mean(times),
'std_seconds': np.std(times),
'min_seconds': np.min(times),
'max_seconds': np.max(times)
},
'agent_rounds': {
'mean': np.mean(rounds),
'std': np.std(rounds),
'min': np.min(rounds),
'max': np.max(rounds)
},
'expert_alignment': {
'mean': np.mean(alignment_scores) if alignment_scores else None,
'n_rated': len(alignment_scores)
},
'overall_scores': {
'mean': np.mean(overall_scores) if overall_scores else None,
'std': np.std(overall_scores) if overall_scores else None
}
}
# Ground truth for validation against literature consensus
LITERATURE_CONSENSUS = {
'portfolio_optimization_qaoa': {
'quantum_advantage_near_term': False,
'feasible_on_nisq': True, # Can run, but no advantage
'bottleneck': 'noise_and_classical_competition',
'recommended_approach': 'hybrid',
'references': [
'Egger et al. (2020) - Quantum Computing for Finance',
'Herman et al. (2022) - Portfolio Optimization Survey'
]
},
'option_pricing_amplitude_estimation': {
'quantum_advantage_near_term': False,
'feasible_on_nisq': False, # Requires error correction
'bottleneck': 'circuit_depth_and_error_correction',
'recommended_approach': 'classical_monte_carlo',
'references': [
'Stamatopoulos et al. (2020) - Option Pricing using QC',
'Chakrabarti et al. (2021) - Threshold for Quantum Speedup'
]
},
'fraud_detection_quantum_ml': {
'quantum_advantage_near_term': False,
'feasible_on_nisq': True, # Can run, limited scale
'bottleneck': 'data_loading_and_classical_ml_strength',
'recommended_approach': 'classical_ml',
'references': [
'Schuld & Petruccione (2021) - ML with Quantum Computers',
'Tang (2019) - Quantum-inspired classical algorithms'
]
},
'risk_analysis_quantum_monte_carlo': {
'quantum_advantage_near_term': False,
'feasible_on_nisq': False,
'bottleneck': 'quadratic_speedup_insufficient_with_noise',
'recommended_approach': 'gpu_accelerated_classical',
'references': [
'Woerner & Egger (2019) - Quantum Risk Analysis',
'Miyamoto & Shiohara (2022) - Bermudan Option Pricing'
]
},
'credit_scoring_vqc': {
'quantum_advantage_near_term': False,
'feasible_on_nisq': True,
'bottleneck': 'barren_plateaus_and_expressibility',
'recommended_approach': 'classical_ensemble_methods',
'references': [
'McClean et al. (2018) - Barren Plateaus',
'Cerezo et al. (2021) - Variational Quantum Algorithms'
]
}
}
def calculate_expert_alignment(
agent_output: dict,
use_case_key: str
) -> dict:
"""
Calculate alignment between agent output and literature consensus.
Args:
agent_output: Structured output from the agent crew
use_case_key: Key into LITERATURE_CONSENSUS dict
Returns:
Alignment analysis with score
"""
if use_case_key not in LITERATURE_CONSENSUS:
return {
'error': f'Unknown use case: {use_case_key}',
'available_cases': list(LITERATURE_CONSENSUS.keys())
}
consensus = LITERATURE_CONSENSUS[use_case_key]
alignment_checks = []
# Check quantum advantage assessment
if 'quantum_advantage' in agent_output:
agent_says_advantage = agent_output.get('quantum_advantage', False)
consensus_advantage = consensus['quantum_advantage_near_term']
alignment_checks.append({
'criterion': 'quantum_advantage_assessment',
'agent': agent_says_advantage,
'consensus': consensus_advantage,
'aligned': agent_says_advantage == consensus_advantage
})
# Check feasibility assessment
if 'feasible_on_nisq' in agent_output:
agent_feasible = agent_output.get('feasible_on_nisq', False)
consensus_feasible = consensus['feasible_on_nisq']
alignment_checks.append({
'criterion': 'nisq_feasibility',
'agent': agent_feasible,
'consensus': consensus_feasible,
'aligned': agent_feasible == consensus_feasible
})
# Calculate alignment score
if alignment_checks:
aligned_count = sum(1 for c in alignment_checks if c['aligned'])
alignment_score = aligned_count / len(alignment_checks)
else:
alignment_score = None
return {
'use_case': use_case_key,
'alignment_checks': alignment_checks,
'alignment_score': alignment_score,
'consensus_references': consensus['references']
}
def extract_scores_from_text(text: str) -> dict:
"""
Extract numerical scores from agent output text.
Looks for patterns like:
- "score: 0.7"
- "feasibility score (0-1): 0.65"
- "Rating: 7/10"
"""
scores = {}
# Pattern: "X score: 0.Y" or "X score (0-1): 0.Y"
score_pattern = r'(\w+(?:\s+\w+)?)\s+score\s*(?:\([^)]+\))?\s*[:=]\s*([\d.]+)'
for match in re.finditer(score_pattern, text, re.IGNORECASE):
label = match.group(1).lower().replace(' ', '_')
value = float(match.group(2))
if 0 <= value <= 1:
scores[f'{label}_score'] = value
elif 0 <= value <= 10:
scores[f'{label}_score'] = value / 10
# Pattern: "Rating: X/10"
rating_pattern = r'rating\s*[:=]\s*([\d.]+)\s*/\s*10'
for match in re.finditer(rating_pattern, text, re.IGNORECASE):
value = float(match.group(1))
scores['rating'] = value / 10
return scores
class HallucinationChecker:
"""
Check agent outputs for potential hallucinations.
Compares claims against known facts about quantum computing
and finance applications.
"""
# Known facts for validation
KNOWN_FACTS = {
# Hardware facts (2024-2026)
'ibm_qubit_count': (433, 1121), # Range: Osprey to Condor
'ionq_qubit_count': (32, 36),
'google_qubit_count': (72, 100),
# Algorithm facts
'grover_speedup': 'quadratic', # sqrt(N)
'shor_speedup': 'exponential',
'qaoa_proven_advantage': False,
'vqe_proven_advantage': False,
# Finance facts
'hft_latency_requirement_us': 1, # microseconds
'typical_portfolio_size': (10, 10000),
}
HALLUCINATION_PATTERNS = [
# Claims of proven quantum advantage for NISQ
r'proven\s+quantum\s+advantage\s+(?:for|in|on)\s+(?:NISQ|near-term)',
r'demonstrat(?:ed|es)\s+quantum\s+supremacy\s+(?:for|in)\s+finance',
# Unrealistic hardware claims
r'(?:current|available)\s+(?:quantum\s+)?computers?\s+(?:with|have)\s+(?:\d{4,}|\d+,\d{3,})\s+qubits',
# Impossible speedup claims
r'exponential\s+speedup\s+(?:for|in|using)\s+(?:QAOA|VQE)',
]
def check_output(self, text: str) -> dict:
"""
Check text for potential hallucinations.
Args:
text: Agent output text to check
Returns:
Dictionary with hallucination analysis
"""
findings = []
# Check against hallucination patterns
for pattern in self.HALLUCINATION_PATTERNS:
matches = re.findall(pattern, text, re.IGNORECASE)
if matches:
findings.append({
'type': 'suspicious_claim',
'pattern': pattern,
'matches': matches
})
# Check qubit count claims
qubit_claims = re.findall(r'(\d+)\s*qubits?', text, re.IGNORECASE)
for claim in qubit_claims:
count = int(claim)
if count > 2000: # No current hardware has this many
findings.append({
'type': 'unrealistic_qubit_count',
'claimed': count,
'realistic_max': 1121
})
return {
'potential_hallucinations': len(findings),
'findings': findings,
'text_length': len(text)
}
if __name__ == "__main__":
# Demo metrics collection
collector = MetricsCollector()
# Simulate an evaluation
metrics = collector.start_evaluation(
"Quantum portfolio optimization using QAOA"
)
metrics.total_agent_rounds = 5
metrics.quantum_feasibility_score = 0.6
metrics.hardware_readiness_score = 0.4
metrics.classical_competitiveness_score = 0.8
metrics.business_viability_score = 0.5
metrics.overall_score = 0.3
metrics.expert_alignment_score = 0.85
import time
time.sleep(0.1) # Simulate some work
metrics.complete()
print("Evaluation Metrics Demo")
print("=" * 50)
print(metrics.to_dict())
print("\nSummary Statistics:")
print(collector.get_summary_statistics())
|