|
| 1 | +import numpy as np |
| 2 | +from gen_surv.piecewise import piecewise_hazard_function, piecewise_survival_function |
| 3 | + |
| 4 | + |
| 5 | +def test_piecewise_hazard_function_scalar_and_array(): |
| 6 | + breakpoints = [1.0, 2.0] |
| 7 | + hazard_rates = [0.5, 1.0, 1.5] |
| 8 | + # Scalar values |
| 9 | + assert piecewise_hazard_function(0.5, breakpoints, hazard_rates) == 0.5 |
| 10 | + assert piecewise_hazard_function(1.5, breakpoints, hazard_rates) == 1.0 |
| 11 | + assert piecewise_hazard_function(3.0, breakpoints, hazard_rates) == 1.5 |
| 12 | + # Array values |
| 13 | + arr = np.array([0.5, 1.5, 3.0]) |
| 14 | + np.testing.assert_allclose( |
| 15 | + piecewise_hazard_function(arr, breakpoints, hazard_rates), |
| 16 | + np.array([0.5, 1.0, 1.5]), |
| 17 | + ) |
| 18 | + |
| 19 | + |
| 20 | +def test_piecewise_hazard_function_negative_time(): |
| 21 | + """Hazard should be zero for negative times.""" |
| 22 | + breakpoints = [1.0, 2.0] |
| 23 | + hazard_rates = [0.5, 1.0, 1.5] |
| 24 | + assert piecewise_hazard_function(-1.0, breakpoints, hazard_rates) == 0 |
| 25 | + np.testing.assert_array_equal( |
| 26 | + piecewise_hazard_function(np.array([-0.5, -2.0]), breakpoints, hazard_rates), |
| 27 | + np.array([0.0, 0.0]), |
| 28 | + ) |
| 29 | + |
| 30 | + |
| 31 | +def test_piecewise_survival_function(): |
| 32 | + breakpoints = [1.0, 2.0] |
| 33 | + hazard_rates = [0.5, 1.0, 1.5] |
| 34 | + # Known survival probabilities |
| 35 | + expected = np.exp(-np.array([0.0, 0.25, 1.0, 3.0])) |
| 36 | + times = np.array([0.0, 0.5, 1.5, 3.0]) |
| 37 | + np.testing.assert_allclose( |
| 38 | + piecewise_survival_function(times, breakpoints, hazard_rates), |
| 39 | + expected, |
| 40 | + ) |
| 41 | + |
| 42 | + |
| 43 | +def test_piecewise_survival_function_scalar_and_negative(): |
| 44 | + breakpoints = [1.0, 2.0] |
| 45 | + hazard_rates = [0.5, 1.0, 1.5] |
| 46 | + # Scalar output should be a float |
| 47 | + val = piecewise_survival_function(1.5, breakpoints, hazard_rates) |
| 48 | + assert isinstance(val, float) |
| 49 | + assert np.isclose(val, np.exp(-1.0)) |
| 50 | + # Negative times return survival of 1 |
| 51 | + assert piecewise_survival_function(-2.0, breakpoints, hazard_rates) == 1 |
0 commit comments