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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Quantum Decision Core - Main integration module."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from typing import Dict, Any, Optional, List, Tuple
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class QuantumState:
|
| 12 |
+
"""Represents a quantum-encoded state."""
|
| 13 |
+
amplitudes: np.ndarray
|
| 14 |
+
probabilities: np.ndarray
|
| 15 |
+
entropy: float
|
| 16 |
+
n_qubits: int
|
| 17 |
+
|
| 18 |
+
@classmethod
|
| 19 |
+
def from_classical(cls, state_vector: np.ndarray, n_qubits: int) -> 'QuantumState':
|
| 20 |
+
"""Encode classical state into quantum amplitudes."""
|
| 21 |
+
# Normalize
|
| 22 |
+
amplitudes = state_vector / np.linalg.norm(state_vector)
|
| 23 |
+
probabilities = np.abs(amplitudes) ** 2
|
| 24 |
+
entropy = -np.sum(probabilities * np.log2(probabilities + 1e-10))
|
| 25 |
+
return cls(amplitudes, probabilities, entropy, n_qubits)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class QuantumDecisionCore:
|
| 29 |
+
"""
|
| 30 |
+
Main quantum decision core integrating QAOA, VQC, and uncertainty analysis.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, config: Any):
|
| 34 |
+
self.config = config
|
| 35 |
+
self.n_qubits = config.n_qubits
|
| 36 |
+
self.n_layers = config.n_layers
|
| 37 |
+
self.shots = config.shots
|
| 38 |
+
self.entropy_threshold = config.entropy_threshold
|
| 39 |
+
|
| 40 |
+
# Sub-modules
|
| 41 |
+
self.qaoa = None
|
| 42 |
+
self.vqc = None
|
| 43 |
+
self.uncertainty_analyzer = None
|
| 44 |
+
self.kernel_attention = None
|
| 45 |
+
|
| 46 |
+
# Metrics
|
| 47 |
+
self.metrics = {
|
| 48 |
+
'quantum_calls': 0,
|
| 49 |
+
'avg_optimization_time': 0.0,
|
| 50 |
+
'avg_entropy': 0.0,
|
| 51 |
+
'activation_count': 0
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
self._initialize_modules()
|
| 55 |
+
|
| 56 |
+
def _initialize_modules(self):
|
| 57 |
+
"""Initialize quantum sub-modules."""
|
| 58 |
+
try:
|
| 59 |
+
from .qaoa import QAOAOptimizer
|
| 60 |
+
from .vqc import VariationalQuantumCircuit
|
| 61 |
+
from .uncertainty import QuantumUncertaintyAnalyzer
|
| 62 |
+
from .kernels import QuantumKernelAttention
|
| 63 |
+
|
| 64 |
+
self.qaoa = QAOAOptimizer(self.config)
|
| 65 |
+
self.vqc = VariationalQuantumCircuit(self.config)
|
| 66 |
+
self.uncertainty_analyzer = QuantumUncertaintyAnalyzer(self.config)
|
| 67 |
+
self.kernel_attention = QuantumKernelAttention(self.config)
|
| 68 |
+
logger.info("Quantum modules initialized successfully")
|
| 69 |
+
except ImportError as e:
|
| 70 |
+
logger.warning(f"Quantum libraries not available: {e}")
|
| 71 |
+
|
| 72 |
+
def encode_state(self, classical_state: np.ndarray) -> QuantumState:
|
| 73 |
+
"""Encode classical state into quantum representation."""
|
| 74 |
+
# Pad or truncate to match qubit count
|
| 75 |
+
target_dim = 2 ** self.n_qubits
|
| 76 |
+
if len(classical_state) < target_dim:
|
| 77 |
+
padded = np.zeros(target_dim)
|
| 78 |
+
padded[:len(classical_state)] = classical_state
|
| 79 |
+
classical_state = padded
|
| 80 |
+
else:
|
| 81 |
+
classical_state = classical_state[:target_dim]
|
| 82 |
+
|
| 83 |
+
return QuantumState.from_classical(classical_state, self.n_qubits)
|
| 84 |
+
|
| 85 |
+
def optimize_path(self,
|
| 86 |
+
cost_matrix: np.ndarray,
|
| 87 |
+
constraints: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
| 88 |
+
"""Use QAOA to optimize path/cost function."""
|
| 89 |
+
if self.qaoa is None:
|
| 90 |
+
return self._classical_fallback(cost_matrix)
|
| 91 |
+
|
| 92 |
+
self.metrics['quantum_calls'] += 1
|
| 93 |
+
result = self.qaoa.optimize(cost_matrix, constraints)
|
| 94 |
+
self._update_metrics(result)
|
| 95 |
+
return result
|
| 96 |
+
|
| 97 |
+
def analyze_uncertainty(self, state: np.ndarray) -> Dict[str, float]:
|
| 98 |
+
"""Analyze uncertainty using VQC."""
|
| 99 |
+
if self.uncertainty_analyzer is None:
|
| 100 |
+
return self._classical_uncertainty(state)
|
| 101 |
+
|
| 102 |
+
result = self.uncertainty_analyzer.analyze(state)
|
| 103 |
+
self.metrics['avg_entropy'] = (
|
| 104 |
+
(self.metrics['avg_entropy'] * (self.metrics['quantum_calls'] - 1) + result['entropy']) /
|
| 105 |
+
self.metrics['quantum_calls']
|
| 106 |
+
)
|
| 107 |
+
return result
|
| 108 |
+
|
| 109 |
+
def compute_attention(self,
|
| 110 |
+
query: np.ndarray,
|
| 111 |
+
keys: np.ndarray) -> np.ndarray:
|
| 112 |
+
"""Compute quantum kernel attention."""
|
| 113 |
+
if self.kernel_attention is None:
|
| 114 |
+
return self._classical_attention(query, keys)
|
| 115 |
+
|
| 116 |
+
return self.kernel_attention.compute(query, keys)
|
| 117 |
+
|
| 118 |
+
def should_activate_quantum(self, world_state: Dict[str, Any]) -> bool:
|
| 119 |
+
"""Determine if quantum computation should be activated."""
|
| 120 |
+
entropy = world_state.get('entropy', 0.0)
|
| 121 |
+
uncertainty = world_state.get('uncertainty', 0.0)
|
| 122 |
+
obstacle_density = world_state.get('obstacle_density', 0.0)
|
| 123 |
+
|
| 124 |
+
# Activation logic based on complexity metrics
|
| 125 |
+
should_activate = (
|
| 126 |
+
entropy > self.config.activation_entropy or
|
| 127 |
+
uncertainty > 0.5 or
|
| 128 |
+
obstacle_density > 0.4
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
if should_activate:
|
| 132 |
+
self.metrics['activation_count'] += 1
|
| 133 |
+
|
| 134 |
+
return should_activate
|
| 135 |
+
|
| 136 |
+
def evaluate_trajectories(self,
|
| 137 |
+
trajectories: List[np.ndarray],
|
| 138 |
+
world_state: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 139 |
+
"""Evaluate multiple trajectories with quantum scoring."""
|
| 140 |
+
results = []
|
| 141 |
+
|
| 142 |
+
for traj in trajectories:
|
| 143 |
+
# Encode trajectory
|
| 144 |
+
q_state = self.encode_state(traj.flatten())
|
| 145 |
+
|
| 146 |
+
# Analyze uncertainty
|
| 147 |
+
uncertainty = self.analyze_uncertainty(traj.flatten())
|
| 148 |
+
|
| 149 |
+
# Compute quantum score
|
| 150 |
+
quantum_score = self._compute_quantum_score(q_state, uncertainty, world_state)
|
| 151 |
+
|
| 152 |
+
results.append({
|
| 153 |
+
'trajectory': traj,
|
| 154 |
+
'quantum_score': quantum_score,
|
| 155 |
+
'entropy': q_state.entropy,
|
| 156 |
+
'uncertainty': uncertainty,
|
| 157 |
+
'confidence': 1.0 - uncertainty.get('entropy', 0.0)
|
| 158 |
+
})
|
| 159 |
+
|
| 160 |
+
return sorted(results, key=lambda x: x['quantum_score'], reverse=True)
|
| 161 |
+
|
| 162 |
+
def _compute_quantum_score(self,
|
| 163 |
+
q_state: QuantumState,
|
| 164 |
+
uncertainty: Dict[str, float],
|
| 165 |
+
world_state: Dict[str, Any]) -> float:
|
| 166 |
+
"""Compute composite quantum score for decision making."""
|
| 167 |
+
# Components
|
| 168 |
+
coherence = 1.0 - q_state.entropy / self.n_qubits # Higher is better
|
| 169 |
+
confidence = 1.0 - uncertainty.get('entropy', 0.0)
|
| 170 |
+
|
| 171 |
+
# Weighted combination
|
| 172 |
+
score = (
|
| 173 |
+
0.4 * coherence +
|
| 174 |
+
0.3 * confidence +
|
| 175 |
+
0.2 * (1.0 - world_state.get('risk_score', 0.0)) +
|
| 176 |
+
0.1 * (1.0 - world_state.get('obstacle_density', 0.0))
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
return float(np.clip(score, 0.0, 1.0))
|
| 180 |
+
|
| 181 |
+
def _classical_fallback(self, cost_matrix: np.ndarray) -> Dict[str, Any]:
|
| 182 |
+
"""Classical fallback when quantum is unavailable."""
|
| 183 |
+
# Simple greedy optimization
|
| 184 |
+
n = cost_matrix.shape[0]
|
| 185 |
+
path = [0]
|
| 186 |
+
visited = {0}
|
| 187 |
+
|
| 188 |
+
while len(path) < n:
|
| 189 |
+
current = path[-1]
|
| 190 |
+
next_node = min(
|
| 191 |
+
(i for i in range(n) if i not in visited),
|
| 192 |
+
key=lambda i: cost_matrix[current, i]
|
| 193 |
+
)
|
| 194 |
+
path.append(next_node)
|
| 195 |
+
visited.add(next_node)
|
| 196 |
+
|
| 197 |
+
cost = sum(cost_matrix[path[i], path[i+1]] for i in range(n-1))
|
| 198 |
+
|
| 199 |
+
return {
|
| 200 |
+
'path': path,
|
| 201 |
+
'cost': float(cost),
|
| 202 |
+
'quantum_used': False,
|
| 203 |
+
'iterations': 1
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
def _classical_uncertainty(self, state: np.ndarray) -> Dict[str, float]:
|
| 207 |
+
"""Classical uncertainty estimation fallback."""
|
| 208 |
+
probs = np.abs(state) ** 2
|
| 209 |
+
probs = probs / (probs.sum() + 1e-10)
|
| 210 |
+
entropy = -np.sum(probs * np.log2(probs + 1e-10))
|
| 211 |
+
|
| 212 |
+
return {
|
| 213 |
+
'entropy': float(entropy),
|
| 214 |
+
'confidence': float(1.0 - entropy / np.log2(len(state))),
|
| 215 |
+
'risk_score': float(np.std(state)),
|
| 216 |
+
'quantum_used': False
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
def _classical_attention(self, query: np.ndarray, keys: np.ndarray) -> np.ndarray:
|
| 220 |
+
"""Classical dot-product attention fallback."""
|
| 221 |
+
scores = np.dot(keys, query)
|
| 222 |
+
scores = scores / np.sqrt(len(query))
|
| 223 |
+
exp_scores = np.exp(scores - np.max(scores))
|
| 224 |
+
attention = exp_scores / exp_scores.sum()
|
| 225 |
+
return attention
|
| 226 |
+
|
| 227 |
+
def _update_metrics(self, result: Dict[str, Any]):
|
| 228 |
+
"""Update internal metrics."""
|
| 229 |
+
if 'optimization_time' in result:
|
| 230 |
+
n = self.metrics['quantum_calls']
|
| 231 |
+
self.metrics['avg_optimization_time'] = (
|
| 232 |
+
(self.metrics['avg_optimization_time'] * (n - 1) + result['optimization_time']) / n
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
def get_metrics(self) -> Dict[str, float]:
|
| 236 |
+
"""Return quantum computation metrics."""
|
| 237 |
+
return self.metrics.copy()
|