Coverage for nilearn/decoding/tests/test_tv.py: 0%

21 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-16 12:32 +0200

1import numpy as np 

2import pytest 

3 

4from nilearn.decoding._objective_functions import gradient_id, squared_loss 

5from nilearn.decoding.space_net_solvers import ( 

6 _tvl1_objective, 

7 _tvl1_objective_from_gradient, 

8 tvl1_solver, 

9) 

10 

11 

12@pytest.mark.parametrize("alpha", [0.0, 1e-1, 1e-3]) 

13@pytest.mark.parametrize("l1_ratio", [0.0, 0.5, 1.0]) 

14def test_tvl1_from_gradient(rng, alpha, l1_ratio, size=5, n_samples=10): 

15 shape = [size] * 3 

16 n_voxels = np.prod(shape) 

17 X = rng.standard_normal((n_samples, n_voxels)) 

18 y = rng.standard_normal(n_samples) 

19 w = rng.standard_normal(shape) 

20 mask = np.ones_like(w).astype(bool) 

21 

22 gradid = gradient_id(w, l1_ratio=l1_ratio) 

23 

24 assert _tvl1_objective( 

25 X, y, w.copy().ravel(), alpha, l1_ratio, mask 

26 ) == squared_loss( 

27 X, y, w.copy().ravel(), compute_grad=False 

28 ) + alpha * _tvl1_objective_from_gradient(gradid) 

29 

30 

31def test_tvl1_objective_raises_value_error_if_invalid_loss(): 

32 with pytest.raises(ValueError, match="mse' or 'logistic"): 

33 _tvl1_objective(None, None, None, None, None, None, loss="invalidloss") 

34 

35 

36def test_tvl1_solver_raises_value_error_if_invalid_loss(): 

37 with pytest.raises(ValueError, match="mse' or 'logistic"): 

38 tvl1_solver( 

39 np.array([[1]]), None, None, None, None, loss="invalidloss" 

40 )