Coverage for nilearn/image/tests/_testing.py: 0%

21 statements  

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

1"""Testing utilities for nilearn.image functions.""" 

2 

3import numpy as np 

4from numpy.testing import assert_array_equal 

5 

6 

7def match_headers_keys(source, target, except_keys): 

8 """Check if header fields of two Nifti images match, except for some keys. 

9 

10 Parameters 

11 ---------- 

12 source : Nifti1Image 

13 Source image to compare headers with. 

14 target : Nifti1Image 

15 Target image to compare headers from. 

16 except_keys : list of str 

17 List of keys that should from comparison. 

18 """ 

19 for key in source.header: 

20 if key in except_keys: 

21 assert (target.header[key] != source.header[key]).any() 

22 elif isinstance(target.header[key], np.ndarray): 

23 assert_array_equal( 

24 target.header[key], 

25 source.header[key], 

26 ) 

27 else: 

28 assert target.header[key] == source.header[key] 

29 

30 

31def pad_array(array, pad_sizes): 

32 """Pad an array with zeros. 

33 

34 Pads an array with zeros as specified in `pad_sizes`. 

35 

36 Parameters 

37 ---------- 

38 array : :class:`numpy.ndarray` 

39 Array to pad. 

40 

41 pad_sizes : :obj:`list` 

42 Padding quantity specified as 

43 *[x1minpad, x1maxpad, x2minpad,x2maxpad, x3minpad, ...]*. 

44 

45 Returns 

46 ------- 

47 :class:`numpy.ndarray` 

48 Padded array. 

49 

50 Raises 

51 ------ 

52 ValueError 

53 Inconsistent min/max padding quantities. 

54 

55 """ 

56 if len(pad_sizes) % 2 != 0: 

57 raise ValueError( 

58 "Please specify as many max paddings as min" 

59 f" paddings. You have specified {len(pad_sizes)} arguments" 

60 ) 

61 

62 all_paddings = np.zeros([array.ndim, 2], dtype=np.int64) 

63 all_paddings[: len(pad_sizes) // 2] = np.array(pad_sizes).reshape(-1, 2) 

64 

65 lower_paddings, upper_paddings = all_paddings.T 

66 new_shape = np.array(array.shape) + upper_paddings + lower_paddings 

67 

68 padded = np.zeros(new_shape, dtype=array.dtype) 

69 source_slices = [ 

70 slice(max(-lp, 0), min(s + up, s)) 

71 for lp, up, s in zip(lower_paddings, upper_paddings, array.shape) 

72 ] 

73 target_slices = [ 

74 slice(max(lp, 0), min(s - up, s)) 

75 for lp, up, s in zip(lower_paddings, upper_paddings, new_shape) 

76 ] 

77 

78 padded[tuple(target_slices)] = array[tuple(source_slices)].copy() 

79 return padded