test_reporting.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import numpy as np
  2. import pandas as pd
  3. from irae_risk import reporting
  4. from irae_risk.logistic import LogisticPolyRegression
  5. def _reporting_frames():
  6. df_data = pd.DataFrame(
  7. {
  8. "X": [-1.0, 0.0, 1.0, 2.0],
  9. "Y": [0, 0, 1, 1],
  10. "scale": ["plain"] * 4,
  11. "dataset": ["FULL"] * 4,
  12. }
  13. )
  14. df_fit = pd.DataFrame(
  15. {
  16. "scale": ["plain"],
  17. "dataset": ["FULL"],
  18. "theta": [np.array([-0.2, 0.8])],
  19. "cov": [np.eye(2) * 0.01],
  20. }
  21. )
  22. return df_data, df_fit
  23. def test_reporting_builders_read_theta_column():
  24. df_data, df_fit = _reporting_frames()
  25. model = LogisticPolyRegression(degree=1)
  26. df_fit_index = df_fit.set_index(["scale", "dataset"])
  27. points, fits = reporting.build_plot_data_basic(
  28. df_data,
  29. df_fit_index,
  30. model,
  31. n_grid=5,
  32. )
  33. _, _, intervals = reporting.build_plot_data(
  34. df_data,
  35. df_fit_index,
  36. alpha=0.05,
  37. lg=model,
  38. n_grid=5,
  39. )
  40. assert len(points) == len(df_data)
  41. assert len(fits) == 5
  42. assert set(intervals["method"]) == {"normal", "delta"}
  43. def test_full_ci_builder_accepts_bootstrap_theta_results():
  44. df_data, df_fit = _reporting_frames()
  45. model = LogisticPolyRegression(degree=1)
  46. df_fit_index = df_fit.set_index(["scale", "dataset"])
  47. bootstrap_theta = {
  48. ("plain", "FULL", "parametric_boots"): np.array(
  49. [[-0.3, 0.7], [-0.2, 0.8], [-0.1, 0.9]]
  50. )
  51. }
  52. _, _, intervals = reporting.build_plot_data_full_ci(
  53. df_data,
  54. df_fit_index,
  55. model,
  56. alpha=0.05,
  57. boots_theta_results=bootstrap_theta,
  58. n_grid=5,
  59. analytic_methods=(),
  60. bootstrap_methods=("parametric_boots",),
  61. )
  62. assert set(intervals["method"]) == {"parametric_boots"}
  63. assert set(intervals["ci_source"]) == {"bootstrap"}
  64. def test_bootstrap_loader_calls_theta_api(tmp_path):
  65. df_data, _ = _reporting_frames()
  66. class ThetaSampler:
  67. def get_normal_theta(self, x, y, m):
  68. assert len(x) == len(y) == 4
  69. return np.full((m, 2), 1.5)
  70. result = reporting.load_or_build_bootstrap_theta(
  71. df_data,
  72. ThetaSampler(),
  73. tmp_path,
  74. n_boots=3,
  75. methods=("normal",),
  76. )
  77. samples = result[("plain", "FULL", "normal")]
  78. assert samples.shape == (3, 2)
  79. assert np.all(samples == 1.5)
  80. assert (tmp_path / "boots_theta_results.pkl").is_file()