Coverage for topology/learned_topology.py: 100%

163 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Learned/probabilistic topology overlay for Aether Quant V2-17.5. 

2 

3Adds a data-driven, probabilistic layer on top of - never in place of - the 

4deterministic topology in market_topology.py: cluster probabilities, 

5confidence/uncertainty, a stress score, and small bounded 3D offsets. Pure 

6Python, no numpy/sklearn at runtime (matches market_topology.py, regime/, 

7liquidity/): the model is trained offline (see train_topology.py) and loaded 

8as a plain JSON dict; this module never touches a file and never raises, 

9degrading node-by-node - and, in the worst case, entirely - to the 

10deterministic baseline when the model is missing, malformed, or not 

11confident enough. 

12 

13"Non-deterministic" here means probabilistic scoring, not randomized 

14behavior: every function is a deterministic function of its inputs (no RNG). 

15Trading actions never read the new fields this module adds - 

16analyzer/market_analyzer.py continues to consume only topology_risk/state, 

17exactly as produced by the unchanged deterministic layer. 

18 

19Prototype offsets (development/Problems.md #56) have an intentionally 

20asymmetric contract: x/y are absolute scene units, clamped straight to 

21max_offset_xy, because x/y's scale never changes between 

22market_topology.py's 2D and 3D (V4-W3) embedding modes. z is normalized 

23to [-1, 1] and multiplied by max_offset_z before clamping, because z is 

24the one axis whose scene scale *does* change between modes (a 0..1 

25volatility encoding in 2D, a 0..100 spatial axis in 3D) - a raw offset 

26tuned for one scale would be meaningless, or effectively zero, on the 

27other. 

28""" 

29 

30from __future__ import annotations 

31 

32import math 

33from typing import Any 

34 

35FEATURE_KEYS = ("volatility", "momentum", "correlation_strength", "liquidity_score", "regime_risk_score") 

36TOPOLOGY_SOURCES = ("deterministic", "learned", "hybrid", "fallback") 

37 

38DEFAULT_TEMPERATURE = 0.35 

39DEFAULT_TOP_N_NEIGHBORS = 3 

40DEFAULT_MIN_CONFIDENCE_FOR_LEARNED = 0.2 

41DEFAULT_MAX_OFFSET_XY = 6.0 

42DEFAULT_MAX_OFFSET_Z = 0.1 

43 

44_FALLBACK_NODE_FIELDS = { 

45 "topology_source": "fallback", 

46 "cluster_probs": {}, 

47 "topology_confidence": 0.0, 

48 "topology_uncertainty": 1.0, 

49 "stress_score": 0.0, 

50 "neighbor_shift_score": 0.0, 

51 "topology_disagreement": 0.0, 

52 "learned_neighbors": [], 

53} 

54 

55 

56def _clamp(value: float, low: float, high: float) -> float: 

57 return max(low, min(high, value)) 

58 

59 

60def _normalize(vector: dict[str, Any], feature_stats: dict[str, Any]) -> dict[str, Any]: 

61 normalized = {} 

62 for key in FEATURE_KEYS: 

63 value = float(vector.get(key, 0.0) or 0.0) 

64 key_stats = feature_stats.get(key) or {} 

65 mean = float(key_stats.get("mean", 0.0) or 0.0) 

66 std = float(key_stats.get("std", 0.0) or 0.0) or 1.0 

67 normalized[key] = (value - mean) / std 

68 return normalized 

69 

70 

71def _euclidean_distance(a: dict[str, Any], b: dict[str, Any]) -> float: 

72 return math.sqrt(sum((value - float(b.get(key, 0.0) or 0.0)) ** 2 for key, value in a.items())) 

73 

74 

75def _softmax_neg_distances(distances: dict[str, Any], temperature: float) -> dict[str, Any]: 

76 if not distances: 

77 return {} 

78 temperature = max(float(temperature), 1e-6) 

79 scaled = {key: -value / temperature for key, value in distances.items()} 

80 peak = max(scaled.values()) 

81 exponentials = {key: math.exp(value - peak) for key, value in scaled.items()} 

82 total = sum(exponentials.values()) or 1.0 

83 return {key: value / total for key, value in exponentials.items()} 

84 

85 

86def _normalized_entropy(probabilities: dict[str, Any]) -> float: 

87 count = len(probabilities) 

88 if count <= 1: 

89 return 0.0 

90 entropy = -sum(p * math.log(p) for p in probabilities.values() if p > 0.0) 

91 return _clamp(entropy / math.log(count), 0.0, 1.0) 

92 

93 

94def _jaccard_distance(a: set[Any], b: set[Any]) -> float: 

95 union = a | b 

96 if not union: 

97 return 0.0 

98 return 1.0 - (len(a & b) / len(union)) 

99 

100 

101def _apply_offset(base: float, offset: float, confidence: float, max_shift: float) -> float: 

102 return base + _clamp(offset * confidence, -max_shift, max_shift) 

103 

104 

105def liquidity_score_from_decision(liquidity: dict[str, Any]) -> float: 

106 """Maps a liquidity.market_liquidity.LiquidityDecision-shaped dict (or 

107 any dict carrying participation_rate/estimated_slippage) into a single 

108 0..1 liquidity_score feature - higher is more liquid. Shared by 

109 train_topology.py (offline training) and main.py (runtime) so both 

110 sides compute this feature identically.""" 

111 liquidity = liquidity or {} 

112 participation_rate = float(liquidity.get("participation_rate", 0.0) or 0.0) 

113 slippage = float(liquidity.get("estimated_slippage", 0.0) or 0.0) 

114 return _clamp(1.0 - min(1.0, participation_rate * 10.0 + slippage * 5.0), 0.0, 1.0) 

115 

116 

117def _neighbor_probabilities(symbol: str, normalized_by_symbol: dict[str, Any], temperature: float) -> dict[str, Any]: 

118 own = normalized_by_symbol.get(symbol) 

119 if own is None: 

120 return {} 

121 distances = { 

122 other: _euclidean_distance(own, vector) for other, vector in normalized_by_symbol.items() if other != symbol 

123 } 

124 return _softmax_neg_distances(distances, temperature) 

125 

126 

127def _score_node( 

128 node: dict[str, Any], 

129 normalized_by_symbol: dict[str, Any], 

130 prototypes: list[Any], 

131 distance_scale: float, 

132 cluster_dominant_regime_label: str, 

133 cluster_peers: set[Any], 

134 previous_neighbors: set[Any], 

135 *, 

136 temperature: float, 

137 top_n_neighbors: int, 

138 min_confidence_for_learned: float, 

139 max_offset_xy: float, 

140 max_offset_z: float, 

141) -> dict[str, Any]: 

142 """Pure per-node scoring against a trained prototype set. Raises on 

143 malformed inputs - callers catch and fall back per-node.""" 

144 symbol = node["symbol"] 

145 own_normalized = normalized_by_symbol[symbol] 

146 

147 distances = { 

148 str(prototype.get("label")): _euclidean_distance(own_normalized, prototype.get("centroid") or {}) 

149 for prototype in prototypes 

150 } 

151 cluster_probs = _softmax_neg_distances(distances, temperature) 

152 confidence = max(cluster_probs.values()) if cluster_probs else 0.0 

153 uncertainty = _normalized_entropy(cluster_probs) 

154 stress = _clamp(min(distances.values()) / distance_scale, 0.0, 1.0) if distances else 0.0 

155 

156 nearest_label = max(cluster_probs, key=lambda key: cluster_probs[key]) if cluster_probs else None 

157 nearest_prototype = next((p for p in prototypes if str(p.get("label")) == nearest_label), {}) 

158 

159 neighbor_probs = _neighbor_probabilities(symbol, normalized_by_symbol, temperature) 

160 learned_neighbors = sorted(neighbor_probs, key=lambda other: (-neighbor_probs[other], other))[:top_n_neighbors] 

161 neighbor_shift = _jaccard_distance(set(learned_neighbors), previous_neighbors) 

162 

163 nearest_regime = nearest_prototype.get("dominant_regime_label", "unknown") 

164 regime_mismatch = 1.0 if nearest_regime != cluster_dominant_regime_label else 0.0 

165 peer_overlap_distance = _jaccard_distance(set(learned_neighbors), cluster_peers) 

166 disagreement = 0.5 * regime_mismatch + 0.5 * peer_overlap_distance 

167 

168 node = dict(node) 

169 if confidence >= min_confidence_for_learned: 

170 node["topology_source"] = "learned" 

171 offset = nearest_prototype.get("offset") or {} 

172 node["x"] = _apply_offset(float(node.get("x", 0.0)), float(offset.get("x", 0.0)), confidence, max_offset_xy) 

173 node["y"] = _apply_offset(float(node.get("y", 0.0)), float(offset.get("y", 0.0)), confidence, max_offset_xy) 

174 # z is normalized to [-1, 1] by train_topology.py (module 

175 # docstring above), unlike x/y's already-absolute scene units - 

176 # scale it into scene units by max_offset_z before the same 

177 # confidence-weighted clamp x/y already go through. 

178 node["z"] = _apply_offset( 

179 float(node.get("z", 0.0)), float(offset.get("z", 0.0)) * max_offset_z, confidence, max_offset_z 

180 ) 

181 else: 

182 node["topology_source"] = "fallback" 

183 

184 node.update( 

185 cluster_probs=cluster_probs, 

186 topology_confidence=confidence, 

187 topology_uncertainty=uncertainty, 

188 stress_score=stress, 

189 neighbor_shift_score=neighbor_shift, 

190 topology_disagreement=disagreement, 

191 learned_neighbors=learned_neighbors, 

192 ) 

193 return node, learned_neighbors 

194 

195 

196def learned_sizing_inputs( 

197 vector: dict[str, Any], 

198 model: dict[str, Any] | None, 

199 feature_schema: dict[str, Any] | None, 

200 *, 

201 cluster_regime_label: str | None = None, 

202 peer_distance: float = 0.5, 

203 temperature: float = DEFAULT_TEMPERATURE, 

204 min_confidence_for_learned: float = DEFAULT_MIN_CONFIDENCE_FOR_LEARNED, 

205) -> dict[str, Any]: 

206 """The three numbers `risk.position_sizing.topology_sizing_multiplier` reads, for ONE node from its feature vector 

207 alone: the same prototype distances, softmax confidence and regime-mismatch term `_score_node` computes. The peer 

208 term (`_jaccard_distance` of the learned neighbours vs the deterministic cluster peers) needs the whole bar's 

209 topology, so offline callers pass it as `peer_distance` (a bracket, 0.0..1.0). `cluster_regime_label` is the 

210 deterministic cluster's dominant regime; None means "no mismatch information" (term 0). Never raises: a missing or 

211 malformed model gives the fallback no-op.""" 

212 fallback = {"topology_source": "fallback", "topology_confidence": 0.0, "topology_disagreement": 0.0} 

213 try: 

214 prototypes = (model or {}).get("prototypes") or [] 

215 feature_stats = (feature_schema or {}).get("feature_stats") or {} 

216 if not prototypes or not feature_stats: 

217 return fallback 

218 own = _normalize(vector, feature_stats) 

219 distances = {str(p.get("label")): _euclidean_distance(own, p.get("centroid") or {}) for p in prototypes} 

220 probabilities = _softmax_neg_distances(distances, temperature) 

221 confidence = max(probabilities.values()) 

222 if confidence < min_confidence_for_learned: 

223 return fallback | {"topology_confidence": confidence} 

224 nearest = max(probabilities, key=lambda key: probabilities[key]) 

225 nearest_regime = next( 

226 (p.get("dominant_regime_label", "unknown") for p in prototypes if str(p.get("label")) == nearest), "unknown" 

227 ) 

228 mismatch = 1.0 if cluster_regime_label is not None and nearest_regime != cluster_regime_label else 0.0 

229 disagreement = 0.5 * mismatch + 0.5 * _clamp(float(peer_distance), 0.0, 1.0) 

230 return {"topology_source": "learned", "topology_confidence": confidence, "topology_disagreement": disagreement} 

231 except Exception: 

232 return fallback 

233 

234 

235def apply_learned_topology( 

236 deterministic_topology: dict[str, Any], 

237 symbol_features: dict[str, dict] | None = None, 

238 previous_neighbors_by_symbol: dict[str, list[str]] | None = None, 

239 model: dict[str, Any] | None = None, 

240 feature_schema: dict[str, Any] | None = None, 

241 *, 

242 temperature: float = DEFAULT_TEMPERATURE, 

243 top_n_neighbors: int = DEFAULT_TOP_N_NEIGHBORS, 

244 min_confidence_for_learned: float = DEFAULT_MIN_CONFIDENCE_FOR_LEARNED, 

245 max_offset_xy: float = DEFAULT_MAX_OFFSET_XY, 

246 max_offset_z: float = DEFAULT_MAX_OFFSET_Z, 

247) -> dict[str, Any]: 

248 """Overlay learned cluster probabilities/uncertainty/offsets on top of a 

249 deterministic MarketTopology.to_dict()-shaped payload. 

250 

251 Never raises. Falls back to the deterministic node unchanged (position 

252 untouched, diagnostic fields zeroed) whenever the model is missing, a 

253 symbol has no current-bar features, or the model's confidence for that 

254 symbol is below `min_confidence_for_learned`. 

255 """ 

256 symbol_features = symbol_features or {} 

257 previous_neighbors_by_symbol = previous_neighbors_by_symbol or {} 

258 reasons = list(deterministic_topology.get("reasons") or []) 

259 

260 deterministic_nodes = deterministic_topology.get("nodes") or [] 

261 clusters = deterministic_topology.get("clusters") or [] 

262 cluster_regime_by_id = {cluster.get("cluster_id"): cluster.get("dominant_regime_label", "unknown") for cluster in clusters} 

263 cluster_members_by_id = {cluster.get("cluster_id"): set(cluster.get("members") or []) for cluster in clusters} 

264 

265 feature_stats = (feature_schema or {}).get("feature_stats") or {} 

266 prototypes = (model or {}).get("prototypes") or [] 

267 distance_scale = float((model or {}).get("distance_scale") or 0.0) or 1.0 

268 model_version_id = (model or {}).get("version_id") 

269 # development/Problems.md #56: detection hook for the prototypes[].offset 

270 # format, distinct from model_version_id (a pipeline run identity, not a 

271 # schema version). None for any model trained before this field existed. 

272 model_offset_schema = (model or {}).get("offset_schema") 

273 

274 model_loaded = bool(model) and bool(feature_schema) and bool(prototypes) and bool(feature_stats) 

275 if not model_loaded: 

276 reasons.append("learned_topology_model_missing") 

277 

278 normalized_by_symbol: dict[str, dict] = {} 

279 if model_loaded: 

280 for symbol, vector in symbol_features.items(): 

281 try: 

282 normalized_by_symbol[symbol] = _normalize(vector, feature_stats) 

283 except Exception: 

284 continue 

285 

286 learned_neighbors_by_symbol: dict[str, list[str]] = {} 

287 nodes_out = [] 

288 

289 for node in deterministic_nodes: 

290 symbol = node.get("symbol") 

291 cluster_id = node.get("cluster_id") 

292 cluster_dominant_regime_label = cluster_regime_by_id.get(cluster_id, node.get("regime_label", "unknown")) 

293 cluster_peers = cluster_members_by_id.get(cluster_id, set()) - {symbol} 

294 

295 node = dict(node) 

296 node["cluster_dominant_regime_label"] = cluster_dominant_regime_label 

297 

298 if not model_loaded or symbol not in normalized_by_symbol: 

299 node.update(_FALLBACK_NODE_FIELDS) 

300 nodes_out.append(node) 

301 continue 

302 

303 try: 

304 previous_neighbors = set(previous_neighbors_by_symbol.get(symbol, [])) 

305 scored_node, learned_neighbors = _score_node( 

306 node, 

307 normalized_by_symbol, 

308 prototypes, 

309 distance_scale, 

310 cluster_dominant_regime_label, 

311 cluster_peers, 

312 previous_neighbors, 

313 temperature=temperature, 

314 top_n_neighbors=top_n_neighbors, 

315 min_confidence_for_learned=min_confidence_for_learned, 

316 max_offset_xy=max_offset_xy, 

317 max_offset_z=max_offset_z, 

318 ) 

319 learned_neighbors_by_symbol[symbol] = learned_neighbors 

320 nodes_out.append(scored_node) 

321 except Exception: 

322 node.update(_FALLBACK_NODE_FIELDS) 

323 nodes_out.append(node) 

324 

325 node_sources = {node.get("topology_source") for node in nodes_out} 

326 if not nodes_out or not model_loaded or node_sources == {"fallback"}: 

327 topology_source = "fallback" 

328 elif node_sources == {"learned"}: 

329 topology_source = "learned" 

330 else: 

331 topology_source = "hybrid" 

332 

333 result = dict(deterministic_topology) 

334 result["nodes"] = nodes_out 

335 result["reasons"] = reasons 

336 result["topology_source"] = topology_source 

337 result["model_loaded"] = model_loaded 

338 result["model_version_id"] = model_version_id 

339 result["model_offset_schema"] = model_offset_schema 

340 result["learned_neighbors_by_symbol"] = learned_neighbors_by_symbol 

341 return result