lnaive_nb.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # lnaive_nb.py
  2. def naive_network_benchmarking_with_budget(network, path_list, bounces, C_budget, return_details=False):
  3. """
  4. 均等配分(L-Naive)版 NB。
  5. 既存の戻り値:
  6. correctness: bool
  7. cost: int
  8. best_path_fidelity: float | None
  9. return_details=True のとき追加で返す:
  10. alloc_by_path: dict[int,int] {path_id: バウンス総数}
  11. est_fid_by_path: dict[int,float] {path_id: 推定忠実度}
  12. 想定:
  13. - network.benchmark_path(path, bounces, sample_times) -> (p, used_cost)
  14. - 忠実度変換は既存と同じ: fidelity = p + (1 - p)/2
  15. """
  16. fidelity = {}
  17. cost = 0
  18. n_paths = len(path_list)
  19. if n_paths == 0:
  20. if return_details:
  21. return False, 0, None, {}, {}
  22. return False, 0, None
  23. per_sample_cost = sum(bounces) or 1
  24. per_path_budget = int(C_budget) // n_paths
  25. Ns = per_path_budget // per_sample_cost # 各パスのサンプル数
  26. if Ns <= 0:
  27. if return_details:
  28. return False, 0, None, {}, {}
  29. return False, 0, None
  30. # 各 hop に同じ Ns を配る(既存 naive と同じ割当表)
  31. sample_times = {h: int(Ns) for h in bounces}
  32. # 追加: 詳細記録用
  33. alloc_by_path = {int(p): 0 for p in path_list}
  34. est_fid_by_path = {}
  35. # 各パスを均等回数でベンチマーク
  36. for path in path_list:
  37. p, used = network.benchmark_path(path, bounces, sample_times)
  38. f = p + (1 - p) / 2.0 # 忠実度変換(既存式)
  39. fidelity[path] = f
  40. cost += int(used)
  41. # 追加: 詳細記録
  42. alloc_by_path[int(path)] = alloc_by_path.get(int(path), 0) + int(used)
  43. est_fid_by_path[int(path)] = float(f)
  44. if not fidelity:
  45. if return_details:
  46. return False, int(cost), None, alloc_by_path, est_fid_by_path
  47. return False, int(cost), None
  48. best_path = max(fidelity, key=fidelity.get)
  49. correctness = (best_path == getattr(network, "best_path", None))
  50. best_path_fidelity = fidelity[best_path]
  51. if return_details:
  52. return bool(correctness), int(cost), best_path_fidelity, alloc_by_path, est_fid_by_path
  53. return bool(correctness), int(cost), best_path_fidelity