import numpy as np import pandas as pd from scipy.special import gammaln from models import curves, survival SOLVER_TOLERANCE = 1e-6 def test_fractional_weibull_reproduces_the_classic_one(): t = np.linspace(0, 300, 61) for k, lam in ((0.9, 476.0), (2.4, 233.6), (1.3, 60.0)): found, want = curves.fractional(t, k, 1.0, 1.0, lam), curves.weibull(t, k, lam) np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE) def _series(z: np.ndarray, rho: float, m: float, l: float, terms: int = 200) -> np.ndarray: # noqa: E741 j = np.arange(terms - 1) log_c = np.concatenate([[0.0], np.cumsum(gammaln(rho * (m * j + l) + 1) - gammaln(rho * (m * j + l + 1) + 1))]) # fmt: skip return (np.exp(log_c)[None, :] * z[:, None] ** np.arange(terms)[None, :]).sum(axis=1) def test_fractional_weibull_solver_matches_the_series(): t = np.linspace(0, 72, 289) for k, a, b, lam in ((1.0, 0.5, 0.7, 80.0), (0.8, 0.9, 0.4, 150.0), (1.3, 0.3, 0.9, 60.0)): s = k + a - 2 z = -np.exp(gammaln(k + 1) - gammaln(k + a - 1)) * (t / lam) ** (k + a + b - 2) assert np.abs(z).max() < 2 found, want = curves.fractional(t, k, a, b, lam), _series(z, b, s / b + 1, s / b) np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE) def test_survival_censors_deaths_after_follow_up_or_horizon(): index = pd.Series(["2020-01-01"] * 4) death = pd.Series(["2020-03-05", "2020-05-15", "2020-08-01", None]) result = survival.outcomes(index, death, "2020-06-01", cap_months=3) assert list(result.itertuples(index=False, name=None)) == [ (2, True), (3, False), (3, False), (3, False), ] uncapped = survival.outcomes(index, death, "2020-06-01", cap_months=0) assert list(uncapped.itertuples(index=False, name=None)) == [ (2, True), (4, True), (4, False), (4, False), ]