"""vdPauw_refactored.pyを同じフォルダーに置いて実行する。

    python test_vdPauw_refactored.py
    python -m unittest -v test_vdPauw_refactored

依存ライブラリ: numpy, scipy, matplotlib（unittestは標準ライブラリ）
Rは抵抗値そのものではなく、正の抵抗比 R_AB,CD / R_AD,BC。
試験範囲は、元の描画範囲0.01～100を超える1e-8～1e8。
"""

import unittest

import numpy as np

import vdPauw_refactored as vdp


R_VALUES = np.logspace(-8, 8, 161)
RESIDUAL_ATOL = 1e-9
SYMMETRY_RTOL = 1e-5  # 教材用の基準例。必要な精度に応じて変更する。


class TestVdpFactor(unittest.TestCase):
    def test_symmetric_case(self):
        """R=1では補正不要で、f=1となる。"""
        np.testing.assert_allclose(vdp.vdp_factor(1.0), 1.0, rtol=0, atol=1e-12)


    def test_equation_residual(self):
        """fからxを再構成し、全点でexp(-xR)+exp(-x)=1を確認する。"""
        f_values = vdp.calculate_factors(R_VALUES)
        assert f_values.shape == R_VALUES.shape
        assert np.isfinite(f_values).all()
        assert np.all((f_values > 0) & (f_values <= 1 + 1e-12))

        x_values = 2 * np.log(2) / ((R_VALUES + 1) * f_values)
        lhs = np.exp(-x_values * R_VALUES) + np.exp(-x_values)
        residuals = lhs - 1
        print("\nR           f              左辺              残差(左辺-1)")
        for i in (0, 40, 80, 120, 160):
            print(f"{R_VALUES[i]:.1e}  {f_values[i]:.10f}  "
                  f"{lhs[i]:.12f}  {residuals[i]:+.3e}")
        print(f"最大絶対残差: {np.max(np.abs(residuals)):.3e}")

        for r, residual in zip(R_VALUES, residuals):
            assert abs(residual) <= RESIDUAL_ATOL, (
                f"R={r:g}: residual={residual:.3e}, "
                f"許容値={RESIDUAL_ATOL:.1e}"
            )


    def test_reciprocal_symmetry(self):
        """2つの抵抗を交換しても補正因子は変わらない。"""
        forward = vdp.calculate_factors(R_VALUES)
        reciprocal = vdp.calculate_factors(1 / R_VALUES)
        print(f"最大対称性相対差: {np.max(np.abs(forward / reciprocal - 1)):.3e}")
        np.testing.assert_allclose(forward, reciprocal, rtol=SYMMETRY_RTOL,
                                   atol=1e-12)


if __name__ == "__main__":
    unittest.main(verbosity=2)
