id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
1,700
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_labels_to_matrix
class TestModule_labels_to_matrix(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_labels_to_matrix_example(self): fi = ants.image_read(ants.get_ants_data("r16")).resample_image((60, 60), 1, 0) mask = ants.get_mask(fi) labs = ants.kmeans_segmentation(fi, 3)["segmentation"] labmat = ants.labels_to_matrix(labs, mask)
class TestModule_labels_to_matrix(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_labels_to_matrix_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
12
2
10
8
6
0
10
8
6
1
2
0
3
1,701
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_label_stats
class TestModule_label_stats(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_label_stats_example(self): image = ants.image_read(ants.get_ants_data("r16"), 2) image = ants.resample_image(image, (64, 64), 1, 0) segs1 = ants.kmeans_segmentation(image, 3) stats = ants.label_stats(image, segs1["segmentation"])
class TestModule_label_stats(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_label_stats_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
12
2
10
7
6
0
10
7
6
1
2
0
3
1,702
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_label_overlap_measures
class TestModule_label_overlap_measures(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_label_overlap_measures(self): r16 = ants.image_read( ants.get_ants_data('r16') ) r64 = ants.image_read( ants.get_ants_data('r64') ) s16 = ants.kmeans_segmentation( r16, 3 )['segmentation'] s64 = ants.kmeans_segmentation( r64, 3 )['segmentation'] stats = ants.label_overlap_measures(s16, s64)
class TestModule_label_overlap_measures(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_label_overlap_measures(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
13
2
11
9
7
0
11
9
7
1
2
0
3
1,703
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_label_image_centroids
class TestModule_label_image_centroids(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_label_image_centroids(self): image = ants.from_numpy( np.asarray([[[0, 2], [1, 3]], [[4, 6], [5, 7]]]).astype("float32") ) labels = ants.label_image_centroids(image) self.assertEqual(len(labels['labels']), 7) # Test non-sequential labels image = ants.from_numpy( np.asarray([[[0, 2], [2, 2]], [[2, 0], [5, 0]]]).astype("float32") ) labels = ants.label_image_centroids(image) self.assertTrue(len(labels['labels']) == 2) self.assertTrue(labels['labels'][1] == 5) self.assertTrue(np.allclose(labels['vertices'][0], [0.5 , 0.5 , 0.25], atol=1e-5)) # With convex = False, the centroid position should change labels = ants.label_image_centroids(image, convex=False) self.assertTrue(np.allclose(labels['vertices'][0], [1.0, 1.0, 0.0], atol=1e-5)) # single point unchanged self.assertTrue(np.allclose(labels['vertices'][1], [0.0, 1.0, 1.0], atol=1e-5))
class TestModule_label_image_centroids(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_label_image_centroids(self): pass
4
0
8
1
7
1
1
0.14
1
0
0
0
3
0
3
75
28
4
21
6
17
3
17
6
13
1
2
0
3
1,704
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_label_clusters
class TestModule_label_clusters(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_label_clusters_example(self): image = ants.image_read(ants.get_ants_data("r16")) timageFully = ants.label_clusters(image, 10, 128, 150, True) timageFace = ants.label_clusters(image, 10, 128, 150, False)
class TestModule_label_clusters(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_label_clusters_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
11
2
9
7
5
0
9
7
5
1
2
0
3
1,705
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_image_to_cluster_images
class TestModule_image_to_cluster_images(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data("r16")) img3d = ants.image_read(ants.get_ants_data("mni")).resample_image((2, 2, 2)) self.imgs = [img2d, img3d] def tearDown(self): pass def test_image_to_cluster_images_example(self): image = ants.image_read(ants.get_ants_data("r16")) image = ants.threshold_image(image, 1, 1e15) image_cluster_list = ants.image_to_cluster_images(image)
class TestModule_image_to_cluster_images(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_image_to_cluster_images_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
1
3
75
13
2
11
9
7
0
11
9
7
1
2
0
3
1,706
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_image_similarity
class TestModule_image_similarity(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data("r16")) img3d = ants.image_read(ants.get_ants_data("mni")).resample_image((2, 2, 2)) self.imgs = [img2d, img3d] def tearDown(self): pass def test_image_similarity_example(self): x = ants.image_read(ants.get_ants_data("r16")) y = ants.image_read(ants.get_ants_data("r30")) metric = ants.image_similarity(x, y, metric_type="MeanSquares") self.assertTrue(metric > 0)
class TestModule_image_similarity(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_image_similarity_example(self): pass
4
0
4
0
4
0
1
0
1
0
0
0
3
1
3
75
14
2
12
10
8
0
12
10
8
1
2
0
3
1,707
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_scalar_rgb_vector
class TestModule_scalar_rgb_vector(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test1(self): import ants import numpy as np # this fails because ConvertScalarImageToRGB is not wrapped img = ants.image_read(ants.get_data("r16"), pixeltype="unsigned char") # img_rgb = img.scalar_to_rgb() # img_vec = img_rgb.rgb_to_vector() # rgb_arr = img_rgb.numpy() # vec_arr = img_vec.numpy() print(np.allclose(img.numpy(), img.numpy())) def test2(self): import ants import numpy as np rgb_img = ants.from_numpy( np.random.randint(0, 255, (20, 20, 3)).astype("uint8"), is_rgb=True ) vec_img = rgb_img.rgb_to_vector() print(ants.allclose(rgb_img, vec_img)) vec_img = ants.from_numpy( np.random.randint(0, 255, (20, 20, 3)).astype("uint8"), has_components=True ) rgb_img = vec_img.vector_to_rgb() print(ants.allclose(rgb_img, vec_img))
class TestModule_scalar_rgb_vector(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test1(self): pass def test2(self): pass
5
0
8
1
6
1
1
0.22
1
0
0
0
4
0
4
76
35
7
23
12
14
5
19
12
10
1
2
0
4
1,708
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_iMath
class TestModule_iMath(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) #img3d = ants.image_read(ants.get_ants_data('mni')).resample_image((2,2,2)) self.imgs = [img2d] def tearDown(self): pass def test_iMath_example(self): img = ants.image_read(ants.get_ants_data('r16')) img2 = ants.iMath(img, 'Canny', 1, 5, 12) def test_iMath_options(self): for img in self.imgs: # Grayscale dilation img_gd = ants.iMath(img, 'GD', 3) self.assertTrue(ants.image_physical_space_consistency(img_gd, img)) self.assertTrue(not ants.allclose(img_gd, img)) # Grayscale erosion img_tx = ants.iMath(img, 'GE', 3) self.assertTrue(ants.image_physical_space_consistency(img_tx, img)) self.assertFalse(ants.allclose(img_tx, img)) # Morphological dilation img_tx = ants.iMath(img, 'MD', 3) self.assertTrue(ants.image_physical_space_consistency(img_tx, img)) self.assertFalse(ants.allclose(img_tx, img)) # Morphological erosion img_tx = ants.iMath(img, 'ME', 3) self.assertTrue(ants.image_physical_space_consistency(img_tx, img)) self.assertFalse(ants.allclose(img_tx, img)) # Morphological closing img_tx = ants.iMath(img, 'MC', 3) self.assertTrue(ants.image_physical_space_consistency(img_tx, img)) self.assertTrue(not ants.allclose(img_tx, img)) # Morphological opening img_tx = ants.iMath(img, 'MO', 3) self.assertTrue(ants.image_physical_space_consistency(img_tx, img)) self.assertTrue(not ants.allclose(img_tx, img)) # Pad image - ERRORS #img_tx = ants.iMath(img, 'PadImage', 2) # PeronaMalik - ERRORS #img_tx = ants.iMath(img, 'PeronaMalik', 10, 0.5) # Maurer Distance img_tx = ants.iMath(img, 'MaurerDistance') self.assertTrue(ants.image_physical_space_consistency(img_tx, img)) self.assertTrue(not ants.allclose(img_tx, img)) # Danielsson Distance Map #img_tx = ants.iMath(img, 'DistanceMap') #self.assertTrue(ants.image_physical_space_consistency(img_tx, img)) #self.assertTrue(not ants.allclose(img_tx, img)) # Image gradient img_tx = ants.iMath(img, 'Grad', 1) self.assertTrue(ants.image_physical_space_consistency(img_tx, img)) self.assertTrue(not ants.allclose(img_tx, img)) # Laplacian img_tx = ants.iMath(img, 'Laplacian', 1, 1) self.assertTrue(ants.image_physical_space_consistency(img_tx, img)) self.assertTrue(not ants.allclose(img_tx, img))
class TestModule_iMath(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_iMath_example(self): pass def test_iMath_options(self): pass
5
0
17
3
9
5
1
0.47
1
0
0
0
4
1
4
76
71
15
38
12
33
18
38
12
33
2
2
1
5
1,709
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_get_mask
class TestModule_get_mask(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data("r16")) img3d = ants.image_read(ants.get_ants_data("mni")).resample_image((2, 2, 2)) self.imgs = [img2d, img3d] def tearDown(self): pass def test_get_mask_example(self): image = ants.image_read(ants.get_ants_data("r16")) mask = ants.get_mask(image)
class TestModule_get_mask(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get_mask_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
1
3
75
12
2
10
9
6
0
10
9
6
1
2
0
3
1,710
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_get_centroids
class TestModule_get_centroids(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data("r16")) img3d = ants.image_read(ants.get_ants_data("mni")).resample_image((2, 2, 2)) self.imgs = [img2d, img3d] def tearDown(self): pass def test_get_centroids_example(self): image = ants.image_read(ants.get_ants_data("r16")) image = ants.threshold_image(image, 90, 120) image = ants.label_clusters(image, 10) cents = ants.get_centroids(image)
class TestModule_get_centroids(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get_centroids_example(self): pass
4
0
4
0
4
0
1
0
1
0
0
0
3
1
3
75
14
2
12
9
8
0
12
9
8
1
2
0
3
1,711
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_get_ants_data
class TestModule_get_ants_data(unittest.TestCase): def test_get_ants_data(self): for dataname in ants.get_ants_data(None): if dataname.endswith("nii.gz"): img = ants.image_read(dataname) # def test_get_ants_data_files(self): # datanames = ants.get_ants_data(None) # self.assertTrue(isinstance(datanames, list)) # self.assertTrue(len(datanames) > 0) def test_get_ants_data2(self): for dataname in ants.get_data(None): if dataname.endswith("nii.gz"): img = ants.image_read(dataname)
class TestModule_get_ants_data(unittest.TestCase): def test_get_ants_data(self): pass def test_get_ants_data2(self): pass
3
0
4
0
4
0
3
0.44
1
0
0
0
2
0
2
74
15
2
9
7
6
4
9
7
6
3
2
2
6
1,712
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_fit_bspline_object_to_scattered_data
class TestModule_fit_bspline_object_to_scattered_data(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_fit_bspline_object_to_scattered_data_1d_curve_example(self): x = np.linspace(-4, 4, num=100) + np.random.uniform(-0.1, 0.1, 100) u = np.linspace(0, 1.0, num=len(x)) scattered_data = np.expand_dims(u, axis=-1) parametric_data = np.expand_dims(u, axis=-1) spacing = 1/(len(x)-1) * 1.0 bspline_curve = ants.fit_bspline_object_to_scattered_data( scattered_data, parametric_data, parametric_domain_origin=[0.0], parametric_domain_spacing=[spacing], parametric_domain_size=[len(x)], is_parametric_dimension_closed=None, number_of_fitting_levels=5, mesh_size=1) def test_fit_bspline_object_to_scattered_data_2d_curve_example(self): x = np.linspace(-4, 4, num=100) y = np.exp(-np.multiply(x, x)) + np.random.uniform(-0.1, 0.1, len(x)) u = np.linspace(0, 1.0, num=len(x)) scattered_data = np.column_stack((x, y)) parametric_data = np.expand_dims(u, axis=-1) spacing = 1/(len(x)-1) * 1.0 bspline_curve = ants.fit_bspline_object_to_scattered_data( scattered_data, parametric_data, parametric_domain_origin=[0.0], parametric_domain_spacing=[spacing], parametric_domain_size=[len(x)], is_parametric_dimension_closed=None, number_of_fitting_levels=5, mesh_size=1) def test_fit_bspline_object_to_scattered_data_3d_curve_example(self): x = np.linspace(-4, 4, num=100) y = np.exp(-np.multiply(x, x)) + np.random.uniform(-0.1, 0.1, len(x)) z = np.exp(-np.multiply(x, y)) + np.random.uniform(-0.1, 0.1, len(x)) u = np.linspace(0, 1.0, num=len(x)) scattered_data = np.column_stack((x, y)) parametric_data = np.expand_dims(u, axis=-1) spacing = 1/(len(x)-1) * 1.0 bspline_curve = ants.fit_bspline_object_to_scattered_data( scattered_data, parametric_data, parametric_domain_origin=[0.0], parametric_domain_spacing=[spacing], parametric_domain_size=[len(x)], is_parametric_dimension_closed=None, number_of_fitting_levels=5, mesh_size=1) def test_fit_bspline_object_to_scattered_data_2d_scalar_field_example(self): number_of_random_points = 10000 img = ants.image_read( ants.get_ants_data("r16")) img_array = img.numpy() row_indices = np.random.choice(range(2, img_array.shape[0]), number_of_random_points) col_indices = np.random.choice(range(2, img_array.shape[1]), number_of_random_points) scattered_data = np.zeros((number_of_random_points, 1)) parametric_data = np.zeros((number_of_random_points, 2)) for i in range(number_of_random_points): scattered_data[i,0] = img_array[row_indices[i], col_indices[i]] parametric_data[i,0] = row_indices[i] parametric_data[i,1] = col_indices[i] bspline_img = ants.fit_bspline_object_to_scattered_data( scattered_data, parametric_data, parametric_domain_origin=[0.0, 0.0], parametric_domain_spacing=[1.0, 1.0], parametric_domain_size = img.shape, number_of_fitting_levels=7, mesh_size=1) def test_fit_bspline_object_to_scattered_data_3d_scalar_field_example(self): number_of_random_points = 10000 img = ants.image_read( ants.get_ants_data("mni")) img_array = img.numpy() row_indices = np.random.choice(range(2, img_array.shape[0]), number_of_random_points) col_indices = np.random.choice(range(2, img_array.shape[1]), number_of_random_points) dep_indices = np.random.choice(range(2, img_array.shape[2]), number_of_random_points) scattered_data = np.zeros((number_of_random_points, 1)) parametric_data = np.zeros((number_of_random_points, 3)) for i in range(number_of_random_points): scattered_data[i,0] = img_array[row_indices[i], col_indices[i], dep_indices[i]] parametric_data[i,0] = row_indices[i] parametric_data[i,1] = col_indices[i] parametric_data[i,2] = dep_indices[i] bspline_img = ants.fit_bspline_object_to_scattered_data( scattered_data, parametric_data, parametric_domain_origin=[0.0, 0.0, 0.0], parametric_domain_spacing=[1.0, 1.0, 1.0], parametric_domain_size = img.shape, number_of_fitting_levels=5, mesh_size=1) def test_fit_bspline_object_to_scattered_data_2d_displacement_field_example(self): img = ants.image_read( ants.get_ants_data("r16")) # smooth a single vector in the middle of the image scattered_data = np.reshape(np.asarray((10.0, 10.0)), (1, 2)) parametric_data = np.reshape(np.asarray( (scattered_data[0, 0]/img.shape[0], scattered_data[0, 1]/img.shape[1])), (1, 2)) bspline_field = ants.fit_bspline_object_to_scattered_data( scattered_data, parametric_data, parametric_domain_origin=[0.0, 0.0], parametric_domain_spacing=[1.0, 1.0], parametric_domain_size = img.shape, number_of_fitting_levels=7, mesh_size=1) def test_fit_bspline_object_to_scattered_data_3d_displacement_field_example(self): img = ants.image_read( ants.get_ants_data("mni")) # smooth a single vector in the middle of the image scattered_data = np.reshape(np.asarray((10.0, 10.0, 10.0)), (1, 3)) parametric_data = np.reshape(np.asarray( (scattered_data[0, 0]/img.shape[0], scattered_data[0, 1]/img.shape[1], scattered_data[0, 2]/img.shape[2])), (1, 3)) bspline_field = ants.fit_bspline_object_to_scattered_data( scattered_data, parametric_data, parametric_domain_origin=[0.0, 0.0, 0.0], parametric_domain_spacing=[1.0, 1.0, 1.0], parametric_domain_size = img.shape, number_of_fitting_levels=5, mesh_size=1)
class TestModule_fit_bspline_object_to_scattered_data(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_fit_bspline_object_to_scattered_data_1d_curve_example(self): pass def test_fit_bspline_object_to_scattered_data_2d_curve_example(self): pass def test_fit_bspline_object_to_scattered_data_3d_curve_example(self): pass def test_fit_bspline_object_to_scattered_data_2d_scalar_field_example(self): pass def test_fit_bspline_object_to_scattered_data_3d_scalar_field_example(self): pass def test_fit_bspline_object_to_scattered_data_2d_displacement_field_example(self): pass def test_fit_bspline_object_to_scattered_data_3d_displacement_field_example(self): pass
10
0
12
0
11
0
1
0.02
1
1
0
0
9
0
9
81
113
8
103
58
93
2
67
58
57
2
2
1
11
1,713
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_denoise_image
class TestModule_denoise_image(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data("r16")) img3d = ants.image_read(ants.get_ants_data("mni")).resample_image((2, 2, 2)) self.imgs = [img2d, img3d] def tearDown(self): pass def test_denoise_image_example(self): image = ants.image_read(ants.get_ants_data("r16")) # add fairly large salt and pepper noise imagenoise = image + np.random.randn(*image.shape).astype("float32") * 5 imagedenoise = ants.denoise_image(imagenoise, image > image.mean())
class TestModule_denoise_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_denoise_image_example(self): pass
4
0
4
0
3
0
1
0.09
1
0
0
0
3
1
3
75
14
2
11
10
7
1
11
10
7
1
2
0
3
1,714
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_crop_image
class TestModule_crop_image(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data("r16")) img3d = ants.image_read(ants.get_ants_data("mni")).resample_image((2, 2, 2)) self.imgs = [img2d, img3d] def tearDown(self): pass def test_crop_image_example(self): fi = ants.image_read(ants.get_ants_data("r16")) cropped = ants.crop_image(fi) cropped = ants.crop_image(fi, fi, 100) # image not float type cropped = ants.crop_image(fi.clone("unsigned int")) # label image not float cropped = ants.crop_image(fi, fi.clone("unsigned int"), 100) # channel image fi = ants.image_read( ants.get_ants_data('r16') ) cropped = ants.crop_image(fi) fi2 = ants.merge_channels([fi,fi]) cropped2 = ants.crop_image(fi2) self.assertEqual(cropped.shape, cropped2.shape) def test_crop_indices_example(self): fi = ants.image_read(ants.get_ants_data("r16")) cropped = ants.crop_indices(fi, (10, 10), (100, 100)) cropped = ants.smooth_image(cropped, 5) decropped = ants.decrop_image(cropped, fi) # image not float cropped = ants.crop_indices(fi.clone("unsigned int"), (10, 10), (100, 100)) # image dim not equal to indices with self.assertRaises(Exception): cropped = ants.crop_indices(fi, (10, 10, 10), (100, 100)) cropped = ants.crop_indices(fi, (10, 10), (100, 100, 100)) # vector images fi = ants.image_read( ants.get_ants_data("r16")) cropped = ants.crop_indices( fi, (10,10), (100,100) ) fi2 = ants.merge_channels([fi,fi]) cropped2 = ants.crop_indices( fi, (10,10), (100,100) ) self.assertEqual(cropped.shape, cropped2.shape) def test_decrop_image_example(self): fi = ants.image_read(ants.get_ants_data("r16")) mask = ants.get_mask(fi) cropped = ants.crop_image(fi, mask, 1) cropped = ants.smooth_image(cropped, 1) decropped = ants.decrop_image(cropped, fi) # image not float cropped = ants.crop_image(fi.clone("unsigned int"), mask, 1) # full image not float cropped = ants.crop_image(fi, mask.clone("unsigned int"), 1)
class TestModule_crop_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_crop_image_example(self): pass def test_crop_indices_example(self): pass def test_decrop_image_example(self): pass
6
0
11
2
8
2
1
0.2
1
1
0
0
5
1
5
77
61
13
40
22
34
8
40
22
34
1
2
1
5
1,715
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_channels
class TestModule_channels(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data("r16")) img3d = ants.image_read(ants.get_ants_data("mni")) self.imgs = [img2d, img3d] arr2d = np.random.randn(69, 70, 4).astype("float32") arr3d = np.random.randn(69, 70, 71, 4).astype("float32") self.comparrs = [arr2d, arr3d] def tearDown(self): pass def test_merge_channels(self): for img in self.imgs: imglist = [img.clone(), img.clone()] merged_img = ants.merge_channels(imglist) self.assertEqual(merged_img.shape, img.shape) self.assertEqual(merged_img.components, len(imglist)) nptest.assert_allclose(merged_img.numpy()[..., 0], imglist[0].numpy()) imglist = [img.clone(), img.clone(), img.clone(), img.clone()] merged_img = ants.merge_channels(imglist) self.assertEqual(merged_img.shape, img.shape) self.assertEqual(merged_img.components, len(imglist)) nptest.assert_allclose(merged_img.numpy()[..., 0], imglist[-1].numpy()) for comparr in self.comparrs: imglist = [ ants.from_numpy(comparr[..., i].copy()) for i in range(comparr.shape[-1]) ] merged_img = ants.merge_channels(imglist) for i in range(comparr.shape[-1]): nptest.assert_allclose(merged_img.numpy()[..., i], comparr[..., i])
class TestModule_channels(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_merge_channels(self): pass
4
0
11
1
10
0
2
0
1
1
0
0
3
2
3
75
36
6
30
14
26
0
27
14
23
4
2
2
6
1,716
ANTsX/ANTsPy
ants/core/ants_metric.py
ants.core.ants_metric.ANTsImageToImageMetric
class ANTsImageToImageMetric(object): """ ANTsImageToImageMetric class """ def __init__(self, metric): self._metric = metric self._is_initialized = False self.fixed_image = None self.fixed_mask = None self.moving_image = None self.moving_mask = None # ------------------------------------------ # PROPERTIES @property def precision(self): return self._metric.precision @property def dimension(self): return self._metric.dimension @property def metrictype(self): return self._metric.metrictype.replace('ImageToImageMetricv4','') @property def is_vector(self): return self._metric.isVector == 1 @property def pointer(self): return self._metric.pointer # ------------------------------------------ # METHODS def set_fixed_image(self, image): """ Set Fixed ANTsImage for metric """ if not ants.is_image(image): raise ValueError('image must be ANTsImage type') if image.dimension != self.dimension: raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension)) self._metric.setFixedImage(image.pointer, False) self.fixed_image = image def set_fixed_mask(self, image): """ Set Fixed ANTsImage Mask for metric """ if not ants.is_image(image): raise ValueError('image must be ANTsImage type') if image.dimension != self.dimension: raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension)) self._metric.setFixedImage(image.pointer, True) self.fixed_mask = image def set_moving_image(self, image): """ Set Moving ANTsImage for metric """ if not ants.is_image(image): raise ValueError('image must be ANTsImage type') if image.dimension != self.dimension: raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension)) self._metric.setMovingImage(image.pointer, False) self.moving_image = image def set_moving_mask(self, image): """ Set Fixed ANTsImage Mask for metric """ if not ants.is_image(image): raise ValueError('image must be ANTsImage type') if image.dimension != self.dimension: raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension)) self._metric.setMovingImage(image.pointer, True) self.moving_mask = image def set_sampling(self, strategy='regular', percentage=1.): if (self.fixed_image is None) or (self.moving_image is None): raise ValueError('must set fixed_image and moving_image before setting sampling') self._metric.setSampling(strategy, percentage) def initialize(self): if (self.fixed_image is None) or (self.moving_image is None): raise ValueError('must set fixed_image and moving_image before initializing') self._metric.initialize() self._is_initialized = True def get_value(self): if not self._is_initialized: self.initialize() return self._metric.getValue() def __call__(self, fixed, moving, fixed_mask=None, moving_mask=None, sampling_strategy='regular', sampling_percentage=1.): self.set_fixed_image(fixed) self.set_moving_image(moving) if fixed_mask is not None: self.set_fixed_mask(fixed_mask) if moving_mask is not None: self.set_moving_mask(moving_mask) if (sampling_strategy is not None) or (sampling_percentage is not None): self.set_sampling(sampling_strategy, sampling_percentage) self.initialize() return self.get_value() def __repr__(self): s = "ANTsImageToImageMetric\n" +\ '\t {:<10} : {}\n'.format('Dimension', self.dimension)+\ '\t {:<10} : {}\n'.format('Precision', self.precision)+\ '\t {:<10} : {}\n'.format('MetricType', self.metrictype)+\ '\t {:<10} : {}\n'.format('IsVector', self.is_vector) return s
class ANTsImageToImageMetric(object): ''' ANTsImageToImageMetric class ''' def __init__(self, metric): pass @property def precision(self): pass @property def dimension(self): pass @property def metrictype(self): pass @property def is_vector(self): pass @property def pointer(self): pass def set_fixed_image(self, image): ''' Set Fixed ANTsImage for metric ''' pass def set_fixed_mask(self, image): ''' Set Fixed ANTsImage Mask for metric ''' pass def set_moving_image(self, image): ''' Set Moving ANTsImage for metric ''' pass def set_moving_mask(self, image): ''' Set Fixed ANTsImage Mask for metric ''' pass def set_sampling(self, strategy='regular', percentage=1.): pass def initialize(self): pass def get_value(self): pass def __call__(self, fixed, moving, fixed_mask=None, moving_mask=None, sampling_strategy='regular', sampling_percentage=1.): pass def __repr__(self): pass
21
5
7
1
5
1
2
0.23
1
1
0
0
15
6
15
15
131
30
82
28
61
19
73
23
57
4
1
1
29
1,717
ANTsX/ANTsPy
tests/test_segmentation.py
test_segmentation.TestModule_random
class TestModule_random(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_fuzzy_cmeans(self): image = ants.image_read(ants.get_ants_data('r16')) mask = ants.get_mask(image) fuzzy = ants.fuzzy_spatial_cmeans_segmentation(image, mask, number_of_clusters=3) def test_functional_lung(self): image = ants.image_read(ants.get_data("mni")).resample_image((4,4,4)) mask = image.get_mask() seg = ants.functional_lung_segmentation(image, mask, verbose=True, number_of_iterations=1, number_of_clusters=2, number_of_atropos_iterations=1) def test_anti_alias(self): img = ants.image_read(ants.get_data('r16')) mask = ants.get_mask(img) mask_aa = ants.anti_alias(mask)
class TestModule_random(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_fuzzy_cmeans(self): pass def test_functional_lung(self): pass def test_anti_alias(self): pass
6
0
4
0
4
0
1
0
1
0
0
0
5
0
5
77
24
4
20
15
14
0
17
15
11
1
2
0
5
1,718
ANTsX/ANTsPy
tests/test_segmentation.py
test_segmentation.TestModule_prior_based_segmentation
class TestModule_prior_based_segmentation(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): fi = ants.image_read(ants.get_ants_data('r16')) seg = ants.kmeans_segmentation(fi,3) mask = ants.threshold_image(seg['segmentation'], 1, 1e15) priorseg = ants.prior_based_segmentation(fi, seg['probabilityimages'], mask, 0.25, 0.1, 3)
class TestModule_prior_based_segmentation(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
13
3
10
8
6
0
10
8
6
1
2
0
3
1,719
ANTsX/ANTsPy
tests/test_segmentation.py
test_segmentation.TestModule_kmeans
class TestModule_kmeans(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): fi = ants.image_read(ants.get_ants_data('r16')) fi = ants.n3_bias_field_correction(fi, 2) seg = ants.kmeans_segmentation(fi, 3)
class TestModule_kmeans(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
12
3
9
6
5
0
9
6
5
1
2
0
3
1,720
ANTsX/ANTsPy
tests/test_segmentation.py
test_segmentation.TestModule_kelly_kapowski
class TestModule_kelly_kapowski(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): img = ants.image_read( ants.get_ants_data('r16') ,2) img = ants.resample_image(img, (64,64),1,0) mask = ants.get_mask( img ) segs = ants.kmeans_segmentation( img, k=3, kmask = mask) thick = ants.kelly_kapowski(s=segs['segmentation'], g=segs['probabilityimages'][1], w=segs['probabilityimages'][2], its=45, r=0.5, m=1)
class TestModule_kelly_kapowski(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
4
0
4
0
1
0
1
0
0
0
3
0
3
75
16
3
13
8
9
0
11
8
7
1
2
0
3
1,721
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_get_neighborhood
class TestModule_get_neighborhood(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data("r16")) img3d = ants.image_read(ants.get_ants_data("mni")).resample_image((2, 2, 2)) self.imgs = [img2d, img3d] def tearDown(self): pass def test_get_neighborhood_in_mask_example(self): img = ants.image_read(ants.get_ants_data("r16")) mask = ants.get_mask(img) mat = ants.get_neighborhood_in_mask(img, mask, radius=(2, 2)) # image not ANTsImage with self.assertRaises(Exception): ants.get_neighborhood_in_mask(2, mask, radius=(2, 2)) # mask not ANTsImage with self.assertRaises(Exception): ants.get_neighborhood_in_mask(img, 2, radius=(2, 2)) # radius not right length with self.assertRaises(Exception): ants.get_neighborhood_in_mask(img, 2, radius=(2, 2, 2, 2)) # radius is just a float/int mat = ants.get_neighborhood_in_mask(img, mask, radius=2) # boundary condition == 'image' mat = ants.get_neighborhood_in_mask( img, mask, radius=(2, 2), boundary_condition="image" ) # boundary condition == 'mean' mat = ants.get_neighborhood_in_mask( img, mask, radius=(2, 2), boundary_condition="mean" ) # spatial info mat = ants.get_neighborhood_in_mask(img, mask, radius=(2, 2), spatial_info=True) # get_gradient mat = ants.get_neighborhood_in_mask(img, mask, radius=(2, 2), get_gradient=True) def test_get_neighborhood_at_voxel_example(self): img = ants.image_read(ants.get_ants_data("r16")) center = (2, 2) radius = (3, 3) retval = ants.get_neighborhood_at_voxel(img, center, radius) # image not ANTsImage with self.assertRaises(Exception): ants.get_neighborhood_at_voxel(2, center, radius) # wrong center length with self.assertRaises(Exception): ants.get_neighborhood_at_voxel(img, (2, 2, 2, 2, 2), radius) # wrong radius length with self.assertRaises(Exception): ants.get_neighborhood_at_voxel(img, center, (2, 2, 2, 2))
class TestModule_get_neighborhood(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get_neighborhood_in_mask_example(self): pass def test_get_neighborhood_at_voxel_example(self): pass
5
0
13
2
9
3
1
0.3
1
1
0
0
4
1
4
76
57
9
37
15
32
11
33
15
28
1
2
1
4
1,722
ANTsX/ANTsPy
tests/test_segmentation.py
test_segmentation.TestModule_joint_label_fusion
class TestModule_joint_label_fusion(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): ref = ants.image_read( ants.get_ants_data('r16')) ref = ants.resample_image(ref, (50,50),1,0) ref = ants.iMath(ref,'Normalize') mi = ants.image_read( ants.get_ants_data('r27')) mi2 = ants.image_read( ants.get_ants_data('r30')) mi3 = ants.image_read( ants.get_ants_data('r62')) mi4 = ants.image_read( ants.get_ants_data('r64')) mi5 = ants.image_read( ants.get_ants_data('r85')) refmask = ants.get_mask(ref) refmask = ants.iMath(refmask,'ME',2) # just to speed things up ilist = [mi,mi2,mi3,mi4,mi5] seglist = [None]*len(ilist) for i in range(len(ilist)): ilist[i] = ants.iMath(ilist[i],'Normalize') mytx = ants.registration(fixed=ref , moving=ilist[i] , type_of_transform = ('Affine') ) mywarpedimage = ants.apply_transforms(fixed=ref,moving=ilist[i], transformlist=mytx['fwdtransforms']) ilist[i] = mywarpedimage seg = ants.threshold_image(ilist[i],'Otsu', 3) seglist[i] = ( seg ) + ants.threshold_image( seg, 1, 3 ).morphology( operation='dilate', radius=3 ) r = 2 pp = ants.joint_label_fusion(ref, refmask, ilist, r_search=2, label_list=seglist, rad=[r]*ref.dimension ) pp = ants.joint_label_fusion(ref,refmask,ilist, r_search=2, rad=2 ) def test_max_lab_plus_one(self): ref = ants.image_read( ants.get_ants_data('r16')) ref = ants.resample_image(ref, (50,50),1,0) ref = ants.iMath(ref,'Normalize') mi = ants.image_read( ants.get_ants_data('r27')) mi2 = ants.image_read( ants.get_ants_data('r30')) mi3 = ants.image_read( ants.get_ants_data('r62')) mi4 = ants.image_read( ants.get_ants_data('r64')) mi5 = ants.image_read( ants.get_ants_data('r85')) refmask = ants.get_mask(ref) refmask = ants.iMath(refmask,'ME',2) # just to speed things up ilist = [mi,mi2,mi3,mi4,mi5] seglist = [None]*len(ilist) for i in range(len(ilist)): ilist[i] = ants.iMath(ilist[i],'Normalize') mytx = ants.registration(fixed=ref , moving=ilist[i] , type_of_transform = ('Affine') ) mywarpedimage = ants.apply_transforms(fixed=ref,moving=ilist[i], transformlist=mytx['fwdtransforms']) ilist[i] = mywarpedimage seg = ants.threshold_image(ilist[i],'Otsu', 3) seglist[i] = ( seg ) + ants.threshold_image( seg, 1, 3 ).morphology( operation='dilate', radius=3 ) r = 2 pp = ants.joint_label_fusion(ref, refmask, ilist, r_search=2, label_list=seglist, rad=[r]*ref.dimension, max_lab_plus_one=True ) pp = ants.joint_label_fusion(ref,refmask,ilist, r_search=2, rad=2, max_lab_plus_one=True)
class TestModule_joint_label_fusion(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass def test_max_lab_plus_one(self): pass
5
0
15
1
14
1
2
0.03
1
1
0
0
4
0
4
76
64
6
58
35
53
2
51
35
46
2
2
1
6
1,723
ANTsX/ANTsPy
tests/test_core_ants_image_indexing.py
test_core_ants_image_indexing.TestClass_AntsImageIndexing
class TestClass_AntsImageIndexing(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_pixeltype_2d(self): img = ants.image_read(ants.get_data('r16')) for ptype in ['unsigned char', 'unsigned int', 'float', 'double']: img = img.clone(ptype) self.assertEqual(img.pixeltype, ptype) img2 = img[:10,:10] self.assertEqual(img2.pixeltype, ptype) def test_pixeltype_3d(self): img = ants.image_read(ants.get_data('mni')) for ptype in ['unsigned char', 'unsigned int', 'float', 'double']: img = img.clone(ptype) self.assertEqual(img.pixeltype, ptype) img2 = img[:10,:10,:10] self.assertEqual(img2.pixeltype, ptype) img3 = img[:10,:10,10] self.assertEqual(img3.pixeltype, ptype) def test_2d(self): img = ants.image_read(ants.get_data('r16')) img2 = img[:10,:10] self.assertEqual(img2.dimension, 2) img2 = img[:5,:5] self.assertEqual(img2.dimension, 2) img2 = img[1:20,1:10] self.assertEqual(img2.dimension, 2) img2 = img[:5,:5] self.assertEqual(img2.dimension, 2) img2 = img[:5,4:5] self.assertEqual(img2.dimension, 2) img2 = img[5:5,5:5] # down to 1d arr = img[10,:] self.assertTrue(isinstance(arr, np.ndarray)) # single value arr = img[10,10] def test_2d_image_index(self): img = ants.image_read(ants.get_data('r16')) idx = img > 200 # acts like a mask img2 = img[idx] def test_3d(self): img = ants.image_read(ants.get_data('mni')) img2 = img[:10,:10,:10] self.assertEqual(img2.dimension, 3) img2 = img[:5,:5,:5] self.assertEqual(img2.dimension, 3) img2 = img[1:20,1:10,1:15] self.assertEqual(img2.dimension, 3) img2 = img[:5,:5,:5] self.assertEqual(img2.dimension, 3) # down to 2d img2 = img[10,:,:] self.assertEqual(img2.dimension, 2) img2 = img[:,10,:] self.assertEqual(img2.dimension, 2) img2 = img[:,:,10] self.assertEqual(img2.dimension, 2) img2 = img[10,:20,:20] self.assertEqual(img2.dimension, 2) img2 = img[:20,10,:] self.assertEqual(img2.dimension, 2) img2 = img[2:20,3:30,10] self.assertEqual(img2.dimension, 2) # down to 1d arr = img[10,:,10] self.assertTrue(isinstance(arr, np.ndarray)) arr = img[10,:,5] self.assertTrue(isinstance(arr, np.ndarray)) # single value arr = img[10,10,10] def test_double_indexing(self): img = ants.image_read(ants.get_data('mni')) img2 = img[20:,:,:] self.assertEqual(img2.shape, (162,218,182)) img3 = img[0,:,:] self.assertEqual(img3.shape, (218,182)) def test_reverse_error(self): img = ants.image_read(ants.get_data('mni')) with self.assertRaises(Exception): img2 = img[20:10,:,:] def test_2d_vector(self): img = ants.image_read(ants.get_data('r16')) img2 = img[:10,:10] img_v = ants.merge_channels([img]) img_v2 = img_v[:10,:10] self.assertTrue(ants.allclose(img2, ants.split_channels(img_v2)[0])) def test_2d_vector_multi(self): img = ants.image_read(ants.get_data('r16')) img2 = img[:10,:10] img_v = ants.merge_channels([img,img,img]) img_v2 = img_v[:10,:10] self.assertTrue(ants.allclose(img2, ants.split_channels(img_v2)[0])) self.assertTrue(ants.allclose(img2, ants.split_channels(img_v2)[1])) self.assertTrue(ants.allclose(img2, ants.split_channels(img_v2)[2])) def test_setting_3d(self): img = ants.image_read(ants.get_data('mni')) img2d = img[100,:,:] # setting a sub-image with an image img2 = img + 10 img2[100,:,:] = img2d self.assertFalse(ants.allclose(img, img2)) self.assertTrue(ants.allclose(img2d, img2[100,:,:])) # setting a sub-image with an array img2 = img + 10 img2[100,:,:] = img2d.numpy() self.assertFalse(ants.allclose(img, img2)) self.assertTrue(ants.allclose(img2d, img2[100,:,:])) def test_setting_2d(self): img = ants.image_read(ants.get_data('r16')) img2d = img[100,:] # setting a sub-image with an image img2 = img + 10 img2[100,:] = img2d self.assertFalse(ants.allclose(img, img2)) self.assertTrue(np.allclose(img2d, img2[100,:])) def test_setting_2d_sub_image(self): img = ants.image_read(ants.get_data('r16')) img2d = img[10:30,10:30] # setting a sub-image with an image img2 = img + 10 img2[10:30,10:30] = img2d self.assertFalse(ants.allclose(img, img2)) self.assertTrue(ants.allclose(img2d, img2[10:30,10:30])) # setting a sub-image with an array img2 = img + 10 img2[10:30,10:30] = img2d.numpy() self.assertFalse(ants.allclose(img, img2)) self.assertTrue(ants.allclose(img2d, img2[10:30,10:30])) def test_setting_correctness(self): img = ants.image_read(ants.get_data('r16')) * 0 self.assertEqual(img.sum(), 0) img2 = img[10:30,10:30] img2 = img2 + 10 self.assertEqual(img2.mean(), 10) img[:20,:20] = img2 self.assertEqual(img.sum(), img2.sum()) self.assertEqual(img.numpy()[:20,:20].sum(), img2.sum()) self.assertNotEqual(img.numpy()[10:30,10:30].sum(), img2.sum()) def test_slicing_3d(self): img = ants.image_read(ants.get_data('mni')) img2 = img[:10,:10,:10] img3 = img[10:20,10:20,10:20] self.assertTrue(ants.allclose(img2, img3)) img_np = img.numpy() self.assertTrue(np.allclose(img2.numpy(), img_np[:10,:10,:10])) self.assertTrue(np.allclose(img[20].numpy(), img_np[20])) self.assertTrue(np.allclose(img[:,20:40].numpy(), img_np[:,20:40])) self.assertTrue(np.allclose(img[:,:,20:-2].numpy(), img_np[:,:,20:-2])) self.assertTrue(np.allclose(img[0:-1,].numpy(), img_np[0:-1,])) self.assertTrue(np.allclose(img[100,10:100,0:-1].numpy(), img_np[100,10:100,0:-1])) self.assertTrue(np.allclose(img[:,10:,30:].numpy(), img_np[:,10:,30:])) # if the slice returns 1D, it should be a numpy array already self.assertTrue(np.allclose(img[100:-1,30,40], img_np[100:-1,30,40])) def test_slicing_2d(self): img = ants.image_read(ants.get_data('r16')) img2 = img[:10,:10] img_np = img.numpy() self.assertTrue(np.allclose(img2.numpy(), img_np[:10,:10])) self.assertTrue(np.allclose(img[:,20:40].numpy(), img_np[:,20:40])) self.assertTrue(np.allclose(img[0:-1,].numpy(), img_np[0:-1,])) self.assertTrue(np.allclose(img[50:,10:-3].numpy(), img_np[50:,10:-3])) # if the slice returns 1D, it should be a numpy array already self.assertTrue(np.allclose(img[20], img_np[20])) self.assertTrue(np.allclose(img[100:-1,30], img_np[100:-1,30]))
class TestClass_AntsImageIndexing(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_pixeltype_2d(self): pass def test_pixeltype_3d(self): pass def test_2d(self): pass def test_2d_image_index(self): pass def test_3d(self): pass def test_double_indexing(self): pass def test_reverse_error(self): pass def test_2d_vector(self): pass def test_2d_vector_multi(self): pass def test_setting_3d(self): pass def test_setting_2d(self): pass def test_setting_2d_sub_image(self): pass def test_setting_correctness(self): pass def test_slicing_3d(self): pass def test_slicing_2d(self): pass
18
0
12
2
9
1
1
0.08
1
1
0
0
17
0
17
89
220
52
155
65
137
13
155
65
137
2
2
1
19
1,724
ANTsX/ANTsPy
tests/test_core_ants_image.py
test_core_ants_image.TestClass_ANTsImage
class TestClass_ANTsImage(unittest.TestCase): """ Test ants.ANTsImage class """ def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) img3d = ants.image_read(ants.get_ants_data('mni')) self.imgs = [img2d, img3d] self.pixeltypes = ['unsigned char', 'unsigned int', 'float', 'double'] self.numpy_pixeltypes = ['uint8', 'uint32', 'float32', 'float64'] def tearDown(self): pass def test_get_spacing(self): #self.setUp() for img in self.imgs: spacing = img.spacing self.assertTrue(isinstance(spacing, tuple)) self.assertEqual(len(img.spacing), img.dimension) def test_set_spacing(self): #self.setUp() for img in self.imgs: # set spacing from list new_spacing_list = [6.9]*img.dimension img.set_spacing(new_spacing_list) self.assertEqual(img.spacing, tuple(new_spacing_list)) # set spacing from tuple new_spacing_tuple = tuple(new_spacing_list) img.set_spacing(new_spacing_tuple) self.assertEqual(img.spacing, new_spacing_tuple) # test exceptions with self.assertRaises(Exception): new_spacing = img.clone() img.set_spacing(new_spacing) with self.assertRaises(Exception): new_spacing = [6.9]*(img.dimension+1) img.set_spacing(new_spacing) def test_get_origin(self): #self.setUp() for img in self.imgs: origin = img.origin self.assertTrue(isinstance(origin, tuple)) self.assertEqual(len(img.origin), img.dimension) def test_set_origin(self): for img in self.imgs: # set spacing from list new_origin_list = [6.9]*img.dimension img.set_origin(new_origin_list) self.assertEqual(img.origin, tuple(new_origin_list)) # set spacing from tuple new_origin_tuple = tuple(new_origin_list) img.set_origin(new_origin_tuple) self.assertEqual(img.origin, new_origin_tuple) # test exceptions with self.assertRaises(Exception): new_origin = img.clone() img.set_origin(new_origin) with self.assertRaises(Exception): new_origin = [6.9]*(img.dimension+1) img.set_origin(new_origin) def test_get_direction(self): #self.setUp() for img in self.imgs: direction = img.direction self.assertTrue(isinstance(direction,np.ndarray)) self.assertTrue(img.direction.shape, (img.dimension,img.dimension)) def test_set_direction(self): #self.setUp() for img in self.imgs: new_direction = np.eye(img.dimension)*3 img.set_direction(new_direction) nptest.assert_allclose(img.direction, new_direction) # set from list img.set_direction(new_direction.tolist()) # test exceptions with self.assertRaises(Exception): new_direction = img.clone() img.set_direction(new_direction) with self.assertRaises(Exception): new_direction = np.eye(img.dimension+2)*3 img.set_direction(new_direction) def test_view(self): #self.setUp() for img in self.imgs: myview = img.view() self.assertTrue(isinstance(myview, np.ndarray)) self.assertEqual(myview.shape, img.shape) # test that changes to view are direct changes to the image myview *= 3. nptest.assert_allclose(myview, img.numpy()) def test_numpy(self): #self.setUp() for img in self.imgs: mynumpy = img.numpy() self.assertTrue(isinstance(mynumpy, np.ndarray)) self.assertEqual(mynumpy.shape, img.shape) # test that changes to view are NOT direct changes to the image mynumpy *= 3. nptest.assert_allclose(mynumpy, img.numpy()*3.) def test_clone(self): #self.setUp() for img in self.imgs: orig_ptype = img.pixeltype for ptype in [*self.pixeltypes, *self.numpy_pixeltypes]: imgclone = img.clone(ptype) self.assertIn(ptype, [imgclone.dtype, imgclone.pixeltype]) self.assertEqual(img.pixeltype, orig_ptype) # test physical space consistency self.assertTrue(ants.image_physical_space_consistency(img, imgclone)) if ptype == orig_ptype: # test that they dont share image pointer view1 = img.view() view1 *= 6.9 nptest.assert_allclose(view1, imgclone.numpy()*6.9) def test_new_image_like(self): #self.setUp() for img in self.imgs: myarray = img.numpy() myarray *= 6.9 imgnew = img.new_image_like(myarray) # test physical space consistency self.assertTrue(ants.image_physical_space_consistency(img, imgnew)) # test data nptest.assert_allclose(myarray, imgnew.numpy()) nptest.assert_allclose(myarray, img.numpy()*6.9) # test exceptions with self.assertRaises(Exception): # not ndarray new_data = img.clone() img.new_image_like(new_data) with self.assertRaises(Exception): # wrong shape new_data = np.random.randn(69,12,21).astype('float32') img.new_image_like(new_data) with self.assertRaises(Exception): # wrong shape with components vecimg = ants.from_numpy(np.random.randn(69,12,3).astype('float32'), has_components=True) new_data = np.random.randn(69,12,4).astype('float32') vecimg.new_image_like(new_data) def test_from_numpy_like(self): img = ants.image_read(ants.get_data('mni')) arr = img.numpy() arr *= 2 img2 = ants.from_numpy_like(arr, img) self.assertTrue(ants.image_physical_space_consistency(img, img2)) self.assertEqual(img2.mean() / img.mean(), 2) def test_to_file(self): #self.setUp() for img in self.imgs: filename = mktemp(suffix='.nii.gz') img.to_file(filename) # test that file now exists self.assertTrue(os.path.exists(filename)) img2 = ants.image_read(filename) # test physical space and data self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img.numpy(), img2.numpy()) try: os.remove(filename) except: pass def test_apply(self): #self.setUp() for img in self.imgs: img2 = img.apply(lambda x: x*6.9) self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()*6.9) def test_numpy_ops(self): for img in self.imgs: median = img.median() std = img.std() argmin = img.argmin() argmax = img.argmax() flat = img.flatten() nonzero = img.nonzero() unique = img.unique() def test__add__(self): #self.setUp() for img in self.imgs: # op on constant img2 = img + 6.9 self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()+6.9) # op on another image img2 = img + img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()+img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img + img2 def test__radd__(self): #self.setUp() for img in self.imgs: # op on constant img2 = img.__radd__(6.9) self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy() + 6.9) # op on another image img2 = img + img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()+img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img + img2 def test__sub__(self): #self.setUp() for img in self.imgs: # op on constant img2 = img - 6.9 self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()-6.9) # op on another image img2 = img - img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()-img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img - img2 def test__rsub__(self): #self.setUp() for img in self.imgs: # op on constant img2 = img.__rsub__(6.9) self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), 6.9 - img.numpy()) # op on another image img2 = img - img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()-img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img - img2 def test__mul__(self): #self.setUp() for img in self.imgs: # op on constant img2 = img * 6.9 self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()*6.9) # op on another image img2 = img * img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()*img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img * img2 def test__rmul__(self): #self.setUp() for img in self.imgs: # op on constant img2 = img.__rmul__(6.9) self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), 6.9*img.numpy()) # op on another image img2 = img * img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()*img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img * img2 def test__div__(self): #self.setUp() for img in self.imgs: img = img + 10 # op on constant img2 = img / 6.9 self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()/6.9) # op on another image img2 = img / img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()/img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img / img2 def test__pow__(self): #self.setUp() for img in self.imgs: img = img + 10 # op on constant img2 = img ** 6.9 self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()**6.9) # op on another image img2 = img ** img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()**img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img ** img2 def test__gt__(self): #self.setUp() for img in self.imgs: img2 = img > 6.9 self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), (img.numpy()>6.9).astype('int')) # op on another image img2 = img > img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()>img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img > img2 def test__ge__(self): #self.setUp() for img in self.imgs: img2 = img >= 6.9 self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), (img.numpy()>=6.9).astype('int')) # op on another image img2 = img >= img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()>=img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img >= img2 def test__lt__(self): #self.setUp() for img in self.imgs: img2 = img < 6.9 self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), (img.numpy()<6.9).astype('int')) # op on another image img2 = img < img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()<img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img < img2 def test__le__(self): #self.setUp() for img in self.imgs: img2 = img <= 6.9 self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), (img.numpy()<=6.9).astype('int')) # op on another image img2 = img <= img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()<=img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img <= img2 def test__eq__(self): #self.setUp() for img in self.imgs: img2 = (img == 6.9) self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), (img.numpy()==6.9).astype('int')) # op on another image img2 = img == img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()==img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img == img2 def test__ne__(self): #self.setUp() for img in self.imgs: img2 = (img != 6.9) self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), (img.numpy()!=6.9).astype('int')) # op on another image img2 = img != img.clone() self.assertTrue(ants.image_physical_space_consistency(img, img2)) nptest.assert_allclose(img2.numpy(), img.numpy()!=img.numpy()) with self.assertRaises(Exception): # different physical space img2 = img.clone() img2.set_spacing([2.31]*img.dimension) img3 = img != img2 def test__getitem__(self): for img in self.imgs: if img.dimension == 2: img2 = img[6:9,6:9] nptest.assert_allclose(img2.numpy(), img.numpy()[6:9,6:9]) elif img.dimension == 3: img2 = img[6:9,6:9,6:9] nptest.assert_allclose(img2.numpy(), img.numpy()[6:9,6:9,6:9]) # get from another image img2 = img.clone() xx = img[img2] with self.assertRaises(Exception): # different physical space img2.set_direction(img.direction*2) xx = img[img2] def test__setitem__(self): for img in self.imgs: if img.dimension == 2: img[6:9,6:9] = 6.9 self.assertTrue(img.numpy()[6:9,6:9].mean(), 6.9) elif img.dimension == 3: img[6:9,6:9,6:9] = 6.9 self.assertTrue(img.numpy()[6:9,6:9,6:9].mean(), 6.9) # set from another image img2 = img.clone() img3 = img.clone() img[img2] = 0 with self.assertRaises(Exception): # different physical space img2.set_direction(img3.direction*2) img3[img2] = 0 def test__repr__(self): for img in self.imgs: s = img.__repr__() def test__iter__(self): # Attempts to use __iter__ on an ANTsImage should raise a TypeError img = self.imgs[0] with self.assertRaises(TypeError): for _ in img: pass
class TestClass_ANTsImage(unittest.TestCase): ''' Test ants.ANTsImage class ''' def setUp(self): pass def tearDown(self): pass def test_get_spacing(self): pass def test_set_spacing(self): pass def test_get_origin(self): pass def test_set_origin(self): pass def test_get_direction(self): pass def test_set_direction(self): pass def test_view(self): pass def test_numpy(self): pass def test_clone(self): pass def test_new_image_like(self): pass def test_from_numpy_like(self): pass def test_to_file(self): pass def test_apply(self): pass def test_numpy_ops(self): pass def test__add__(self): pass def test__radd__(self): pass def test__sub__(self): pass def test__rsub__(self): pass def test__mul__(self): pass def test__rmul__(self): pass def test__div__(self): pass def test__pow__(self): pass def test__gt__(self): pass def test__ge__(self): pass def test__lt__(self): pass def test__le__(self): pass def test__eq__(self): pass def test__ne__(self): pass def test__getitem__(self): pass def test__setitem__(self): pass def test__repr__(self): pass def test__iter__(self): pass
35
1
14
1
10
3
2
0.26
1
3
0
0
34
3
34
106
512
77
346
138
311
89
344
138
309
4
2
3
72
1,725
ANTsX/ANTsPy
ants/core/ants_image.py
ants.core.ants_image.ANTsImage
class ANTsImage(object): def __init__(self, pointer): """ Initialize an ANTsImage. Creating an ANTsImage requires a pointer to an underlying ITK image that is stored via a nanobind class wrapping a AntsImage struct. Arguments --------- pointer : nb::class nanobind class wrapping the struct holding the pointer to the underlying ITK image object """ self.pointer = pointer self.channels_first = False self._array = None @property def _libsuffix(self): return str(type(self.pointer)).split('AntsImage')[-1].split("'")[0] @property def shape(self): return tuple(get_lib_fn('getShape')(self.pointer)) @property def physical_shape(self): return tuple([round(sh*sp,3) for sh,sp in zip(self.shape, self.spacing)]) @property def is_rgb(self): return 'RGB' in self._libsuffix @property def has_components(self): suffix = self._libsuffix return suffix.startswith('V') or suffix.startswith('RGB') @property def components(self): if not self.has_components: return 1 return get_lib_fn('getComponents')(self.pointer) @property def pixeltype(self): ptype = self._libsuffix[:-1] if self.has_components: if self.is_rgb: ptype = ptype[3:] else: ptype = ptype[1:] ptype_map = {'UC': 'unsigned char', 'UI': 'unsigned int', 'F': 'float', 'D': 'double'} return ptype_map[ptype] @property def dtype(self): return _itk_to_npy_map[self.pixeltype] @property def dimension(self): return int(self._libsuffix[-1]) @property def spacing(self): """ Get image spacing Returns ------- tuple """ return tuple(get_lib_fn('getSpacing')(self.pointer)) def set_spacing(self, new_spacing): """ Set image spacing Arguments --------- new_spacing : tuple or list updated spacing for the image. should have one value for each dimension Returns ------- None """ if not isinstance(new_spacing, (tuple, list)): raise ValueError('arg must be tuple or list') if len(new_spacing) != self.dimension: raise ValueError('must give a spacing value for each dimension (%i)' % self.dimension) get_lib_fn('setSpacing')(self.pointer, new_spacing) @property def origin(self): """ Get image origin Returns ------- tuple """ return tuple(get_lib_fn('getOrigin')(self.pointer)) def set_origin(self, new_origin): """ Set image origin Arguments --------- new_origin : tuple or list updated origin for the image. should have one value for each dimension Returns ------- None """ if not isinstance(new_origin, (tuple, list)): raise ValueError('arg must be tuple or list') if len(new_origin) != self.dimension: raise ValueError('must give a origin value for each dimension (%i)' % self.dimension) get_lib_fn('setOrigin')(self.pointer, new_origin) @property def direction(self): """ Get image direction Returns ------- tuple """ return np.array(get_lib_fn('getDirection')(self.pointer)).reshape(self.dimension,self.dimension) def set_direction(self, new_direction): """ Set image direction Arguments --------- new_direction : numpy.ndarray or tuple or list updated direction for the image. should have one value for each dimension Returns ------- None """ if isinstance(new_direction, (tuple,list)): new_direction = np.asarray(new_direction) if not isinstance(new_direction, np.ndarray): raise ValueError('arg must be np.ndarray or tuple or list') if len(new_direction) != self.dimension: raise ValueError('must give a origin value for each dimension (%i)' % self.dimension) get_lib_fn('setDirection')(self.pointer, new_direction) @property def orientation(self): if self.dimension == 3: return self.get_orientation() else: return None def view(self, single_components=False): """ Geet a numpy array providing direct, shared access to the image data. IMPORTANT: If you alter the view, then the underlying image data will also be altered. Arguments --------- single_components : boolean (default is False) if True, keep the extra component dimension in returned array even if image only has one component (i.e. self.has_components == False) Returns ------- ndarray """ if self.is_rgb: img = self.rgb_to_vector() else: img = self dtype = img.dtype shape = img.shape[::-1] if img.has_components or (single_components == True): shape = list(shape) + [img.components] memview = get_lib_fn('toNumpy')(img.pointer) return np.asarray(memview).view(dtype = dtype).reshape(shape).view(np.ndarray).T def numpy(self, single_components=False): """ Get a numpy array copy representing the underlying image data. Altering this ndarray will have NO effect on the underlying image data. Arguments --------- single_components : boolean (default is False) if True, keep the extra component dimension in returned array even if image only has one component (i.e. self.has_components == False) Returns ------- ndarray """ array = np.array(self.view(single_components=single_components), copy=True, dtype=self.dtype) if self.has_components or (single_components == True): if not self.channels_first: array = np.rollaxis(array, 0, self.dimension+1) return array def astype(self, dtype): """ Cast & clone an ANTsImage to a given numpy datatype. Map: uint8 : unsigned char uint32 : unsigned int float32 : float float64 : double """ if dtype not in _supported_dtypes: raise ValueError('Datatype %s not supported. Supported types are %s' % (dtype, _supported_dtypes)) pixeltype = _npy_to_itk_map[dtype] return self.clone(pixeltype) def to_file(self, filename): """ Write the ANTsImage to file Args ---- filename : string filepath to which the image will be written """ filename = os.path.expanduser(filename) get_lib_fn('toFile')(self.pointer, filename) to_filename = to_file def apply(self, fn): """ Apply an arbitrary function to ANTsImage. Args ---- fn : python function or lambda function to apply to ENTIRE image at once Returns ------- ANTsImage image with function applied to it """ this_array = self.numpy() new_array = fn(this_array) return self.new_image_like(new_array) ## NUMPY FUNCTIONS ## def abs(self, axis=None): """ Return absolute value of image """ return np.abs(self.numpy()) def mean(self, axis=None): """ Return mean along specified axis """ return self.numpy().mean(axis=axis) def median(self, axis=None): """ Return median along specified axis """ return np.median(self.numpy(), axis=axis) def std(self, axis=None): """ Return std along specified axis """ return self.numpy().std(axis=axis) def sum(self, axis=None, keepdims=False): """ Return sum along specified axis """ return self.numpy().sum(axis=axis, keepdims=keepdims) def min(self, axis=None): """ Return min along specified axis """ return self.numpy().min(axis=axis) def max(self, axis=None): """ Return max along specified axis """ return self.numpy().max(axis=axis) def range(self, axis=None): """ Return range tuple along specified axis """ return (self.min(axis=axis), self.max(axis=axis)) def argmin(self, axis=None): """ Return argmin along specified axis """ return self.numpy().argmin(axis=axis) def argmax(self, axis=None): """ Return argmax along specified axis """ return self.numpy().argmax(axis=axis) def argrange(self, axis=None): """ Return argrange along specified axis """ amin = self.argmin(axis=axis) amax = self.argmax(axis=axis) if axis is None: return (amin, amax) else: return np.stack([amin, amax]).T def flatten(self): """ Flatten image data """ return self.numpy().flatten() def nonzero(self): """ Return non-zero indices of image """ return self.numpy().nonzero() def unique(self, sort=False): """ Return unique set of values in image """ unique_vals = np.unique(self.numpy()) if sort: unique_vals = np.sort(unique_vals) return unique_vals ## OVERLOADED OPERATORS ## def __add__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array + other return self.new_image_like(new_array) __radd__ = __add__ def __sub__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array - other return self.new_image_like(new_array) def __rsub__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = other - this_array return self.new_image_like(new_array) def __mul__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array * other return self.new_image_like(new_array) __rmul__ = __mul__ def __truediv__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array / other return self.new_image_like(new_array) def __pow__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array ** other return self.new_image_like(new_array) def __gt__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array > other return self.new_image_like(new_array.astype('uint8')) def __ge__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array >= other return self.new_image_like(new_array.astype('uint8')) def __lt__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array < other return self.new_image_like(new_array.astype('uint8')) def __le__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array <= other return self.new_image_like(new_array.astype('uint8')) def __eq__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array == other return self.new_image_like(new_array.astype('uint8')) def __ne__(self, other): this_array = self.numpy() if is_image(other): if not ants.image_physical_space_consistency(self, other): raise ValueError('images do not occupy same physical space') other = other.numpy() new_array = this_array != other return self.new_image_like(new_array.astype('uint8')) def __getitem__(self, idx): if self.has_components: return ants.merge_channels([ img[idx] for img in ants.split_channels(self) ]) if isinstance(idx, ANTsImage): if not ants.image_physical_space_consistency(self, idx): raise ValueError('images do not occupy same physical space') return self.numpy().__getitem__(idx.numpy().astype('bool')) # convert idx to tuple if it is not, eg im[10] or im[10:20] if not isinstance(idx, tuple): idx = (idx,) ndim = len(self.shape) if len(idx) > ndim: raise ValueError('Too many indices for image') if len(idx) < ndim: # If not all dimensions are indexed, assume the rest are full slices # eg im[10] -> im[10, :, :] idx = idx + (slice(None),) * (ndim - len(idx)) sizes = list(self.shape) starts = [0] * ndim stops = list(self.shape) for i in range(ndim): ti = idx[i] if isinstance(ti, slice): if ti.start: starts[i] = ti.start if ti.stop: if ti.stop < 0: stops[i] = self.shape[i] + ti.stop else: stops[i] = ti.stop sizes[i] = stops[i] - starts[i] if stops[i] < starts[i]: raise ValueError('Reverse indexing is not supported.') elif isinstance(ti, int): starts[i] = ti sizes[i] = 0 if sizes[i] == 0: ndim -= 1 if ndim < 2: return self.numpy().__getitem__(idx) libfn = get_lib_fn('getItem%i' % ndim) new_ptr = libfn(self.pointer, starts, sizes) new_image = from_pointer(new_ptr) return new_image def __setitem__(self, idx, value): arr = self.view() if is_image(value): value = value.numpy() if is_image(idx): if not ants.image_physical_space_consistency(self, idx): raise ValueError('images do not occupy same physical space') arr.__setitem__(idx.numpy().astype('bool'), value) else: arr.__setitem__(idx, value) def __iter__(self): # Do not allow iteration on ANTsImage. Builtin iteration, eg sum(), will generally be much slower # than using numpy methods. We need to explicitly disallow it to prevent breaking object state. raise TypeError("ANTsImage is not iterable. See docs for available functions, or use numpy.") def __repr__(self): if self.dimension == 3: s = 'ANTsImage ({})\n'.format(self.orientation) else: s = 'ANTsImage\n' s = s +\ '\t {:<10} : {} ({})\n'.format('Pixel Type', self.pixeltype, self.dtype)+\ '\t {:<10} : {}{}\n'.format('Components', self.components, ' (RGB)' if 'RGB' in self._libsuffix else '')+\ '\t {:<10} : {}\n'.format('Dimensions', self.shape)+\ '\t {:<10} : {}\n'.format('Spacing', tuple([round(s,4) for s in self.spacing]))+\ '\t {:<10} : {}\n'.format('Origin', tuple([round(o,4) for o in self.origin]))+\ '\t {:<10} : {}\n'.format('Direction', np.round(self.direction.flatten(),4)) return s def __getstate__(self): """ import ants import pickle import numpy as np from copy import deepcopy img = ants.image_read( ants.get_ants_data("r16")) img_pickled = pickle.dumps(img) img2 = pickle.loads(img_pickled) img3 = deepcopy(img) img += 10 print(img.mean(), img3.mean()) """ return self.numpy(), self.origin, self.spacing, self.direction, self.has_components, self.is_rgb def __setstate__(self, state): data, origin, spacing, direction, has_components, is_rgb = state image = ants.from_numpy(np.copy(data), origin=origin, spacing=spacing, direction=direction, has_components=has_components, is_rgb=is_rgb) self.__dict__ = image.__dict__
class ANTsImage(object): def __init__(self, pointer): ''' Initialize an ANTsImage. Creating an ANTsImage requires a pointer to an underlying ITK image that is stored via a nanobind class wrapping a AntsImage struct. Arguments --------- pointer : nb::class nanobind class wrapping the struct holding the pointer to the underlying ITK image object ''' pass @property def _libsuffix(self): pass @property def shape(self): pass @property def physical_shape(self): pass @property def is_rgb(self): pass @property def has_components(self): pass @property def components(self): pass @property def pixeltype(self): pass @property def dtype(self): pass @property def dimension(self): pass @property def spacing(self): ''' Get image spacing Returns ------- tuple ''' pass def set_spacing(self, new_spacing): ''' Set image spacing Arguments --------- new_spacing : tuple or list updated spacing for the image. should have one value for each dimension Returns ------- None ''' pass @property def origin(self): ''' Get image origin Returns ------- tuple ''' pass def set_origin(self, new_origin): ''' Set image origin Arguments --------- new_origin : tuple or list updated origin for the image. should have one value for each dimension Returns ------- None ''' pass @property def direction(self): ''' Get image direction Returns ------- tuple ''' pass def set_direction(self, new_direction): ''' Set image direction Arguments --------- new_direction : numpy.ndarray or tuple or list updated direction for the image. should have one value for each dimension Returns ------- None ''' pass @property def orientation(self): pass def view(self, single_components=False): ''' Geet a numpy array providing direct, shared access to the image data. IMPORTANT: If you alter the view, then the underlying image data will also be altered. Arguments --------- single_components : boolean (default is False) if True, keep the extra component dimension in returned array even if image only has one component (i.e. self.has_components == False) Returns ------- ndarray ''' pass def numpy(self, single_components=False): ''' Get a numpy array copy representing the underlying image data. Altering this ndarray will have NO effect on the underlying image data. Arguments --------- single_components : boolean (default is False) if True, keep the extra component dimension in returned array even if image only has one component (i.e. self.has_components == False) Returns ------- ndarray ''' pass def astype(self, dtype): ''' Cast & clone an ANTsImage to a given numpy datatype. Map: uint8 : unsigned char uint32 : unsigned int float32 : float float64 : double ''' pass def to_file(self, filename): ''' Write the ANTsImage to file Args ---- filename : string filepath to which the image will be written ''' pass def apply(self, fn): ''' Apply an arbitrary function to ANTsImage. Args ---- fn : python function or lambda function to apply to ENTIRE image at once Returns ------- ANTsImage image with function applied to it ''' pass def abs(self, axis=None): ''' Return absolute value of image ''' pass def mean(self, axis=None): ''' Return mean along specified axis ''' pass def median(self, axis=None): ''' Return median along specified axis ''' pass def std(self, axis=None): ''' Return std along specified axis ''' pass def sum(self, axis=None, keepdims=False): ''' Return sum along specified axis ''' pass def min(self, axis=None): ''' Return min along specified axis ''' pass def max(self, axis=None): ''' Return max along specified axis ''' pass def range(self, axis=None): ''' Return range tuple along specified axis ''' pass def argmin(self, axis=None): ''' Return argmin along specified axis ''' pass def argmax(self, axis=None): ''' Return argmax along specified axis ''' pass def argrange(self, axis=None): ''' Return argrange along specified axis ''' pass def flatten(self): ''' Flatten image data ''' pass def nonzero(self): ''' Return non-zero indices of image ''' pass def unique(self, sort=False): ''' Return unique set of values in image ''' pass def __add__(self, other): pass def __sub__(self, other): pass def __rsub__(self, other): pass def __mul__(self, other): pass def __truediv__(self, other): pass def __pow__(self, other): pass def __gt__(self, other): pass def __ge__(self, other): pass def __lt__(self, other): pass def __le__(self, other): pass def __eq__(self, other): pass def __ne__(self, other): pass def __getitem__(self, idx): pass def __setitem__(self, idx, value): pass def __iter__(self): pass def __repr__(self): pass def __getstate__(self): ''' import ants import pickle import numpy as np from copy import deepcopy img = ants.image_read( ants.get_ants_data("r16")) img_pickled = pickle.dumps(img) img2 = pickle.loads(img_pickled) img3 = deepcopy(img) img += 10 print(img.mean(), img3.mean()) ''' pass def __setstate__(self, state): pass
68
27
9
1
6
3
2
0.45
1
10
0
0
54
4
54
54
571
109
318
126
250
144
286
113
231
16
1
4
116
1,726
ANTsX/ANTsPy
ants/contrib/sklearn_interface/sklearn_registration.py
ants.contrib.sklearn_interface.sklearn_registration.RigidRegistration
class RigidRegistration(object): """ Rigid Registration as a Scikit-Learn compatible transform class Example ------- >>> import ants >>> import ants.extra as extrants >>> fi = ants.image_read(ants.get_data('r16')) >>> mi = ants.image_read(ants.get_data('r64')) >>> regtx = extrants.RigidRegistration() >>> regtx.fit(fi, mi) >>> mi_r = regtx.transform(mi) >>> ants.plot(fi, mi_r.iMath_Canny(1, 2, 4).iMath('MD',1)) """ def __init__(self, fixed_image=None): self.type_of_transform = 'Rigid' self.fixed_image = fixed_image def fit(self, moving_image, fixed_image=None): if fixed_image is None: if self.fixed_image is None: raise ValueError('must give fixed_image in fit() or set it in __init__') fixed_image = self.fixed_image fit_result = interface.registration(fixed_image, moving_image, type_of_transform=self.type_of_transform, initial_transform=None, outprefix='', mask=None, grad_step=0.2, flow_sigma=3, total_sigma=0, aff_metric='mattes', aff_sampling=32, syn_metric='mattes', syn_sampling=32, reg_iterations=(40,20,0), verbose=False) self._fit_result = fit_result self.fwdtransforms_ = fit_result['fwdtransforms'] self.invtransforms_ = fit_result['invtransforms'] self.warpedmovout_ = fit_result['warpedmovout'] self.warpedfiout_ = fit_result['warpedfixout'] def transform(self, moving_image, fixed_image=None): result = apply_transforms(fixed=fixed_image, moving=moving_image, transformlist=self.fwdtransforms) return result def inverse_transform(self, moving_image, fixed_image=None): result = apply_transforms(fixed=fixed_image, moving=moving_image, transformlist=self.invtransforms) return result
class RigidRegistration(object): ''' Rigid Registration as a Scikit-Learn compatible transform class Example ------- >>> import ants >>> import ants.extra as extrants >>> fi = ants.image_read(ants.get_data('r16')) >>> mi = ants.image_read(ants.get_data('r64')) >>> regtx = extrants.RigidRegistration() >>> regtx.fit(fi, mi) >>> mi_r = regtx.transform(mi) >>> ants.plot(fi, mi_r.iMath_Canny(1, 2, 4).iMath('MD',1)) ''' def __init__(self, fixed_image=None): pass def fit(self, moving_image, fixed_image=None): pass def transform(self, moving_image, fixed_image=None): pass def inverse_transform(self, moving_image, fixed_image=None): pass
5
1
9
0
9
0
2
0.35
1
1
0
0
4
7
4
4
55
5
37
15
32
13
21
15
16
3
1
2
6
1,727
ANTsX/ANTsPy
ants/contrib/sklearn_interface/sklearn_registration.py
ants.contrib.sklearn_interface.sklearn_registration.Registration
class Registration(object): """ How would it work: # Co-registration within-visit reg = Registration('Rigid', fixed_image=t1_template, save_dir=save_dir, save_suffix='_coreg') for img in other_imgs: reg.fit(img) for img in [flair_img, t2_img]: reg = Registration('Rigid', fixed_image=t1_template, save_dir=save_dir, save_suffix='_coreg') reg.fit(img) # Co-registration across-visit reg = Registration('Rigid', fixed_image=t1) reg.fit(moving=t1_followup) # now align all followups with first visit for img in [flair_follwup, t2_followup]: img_reg = reg.transform(img) # conversly, align all first visits with followups for img in [flair, t2]: img_reg = reg.inverse_transform(img) """ def __init__(self, type_of_transform, fixed_image): """ Properties: type_of_transform fixed_image (template) save_dir (where to save outputs) save_suffix (what to append to saved outputs) save_prefix (what to preppend to saved outputs) """ self.type_of_transform = type_of_transform self.fixed_image = fixed_image def fit(self, X, y=None): """ X : ANTsImage | string | list of ANTsImage types | list of strings images to register to fixed image y : string | list of strings labels for images """ moving_images = X if isinstance(X, (list,tuple)) else [X] moving_labels = y if y is not None else [i for i in range(len(moving_images))] fixed_image = self.fixed_image self.fwdtransforms_ = {} self.invtransforms_ = {} self.warpedmovout_ = {} self.warpedfixout_ = {} for moving_image, moving_label in zip(moving_images, moving_labels): fit_result = interface.registration(fixed_image, moving_image, type_of_transform=self.type_of_transform, initial_transform=None, outprefix='', mask=None, grad_step=0.2, flow_sigma=3, total_sigma=0, aff_metric='mattes', aff_sampling=32, syn_metric='mattes', syn_sampling=32, reg_iterations=(40,20,0), verbose=False) self.fwdtransforms_[moving_label] = fit_result['fwdtransforms'] self.invtransforms_[moving_label] = fit_result['invtransforms'] self.warpedmovout_[moving_label] = fit_result['warpedmovout'] self.warpedfixout_[moving_label] = fit_result['warpedfixout'] return self def transform(self, X, y=None): pass
class Registration(object): ''' How would it work: # Co-registration within-visit reg = Registration('Rigid', fixed_image=t1_template, save_dir=save_dir, save_suffix='_coreg') for img in other_imgs: reg.fit(img) for img in [flair_img, t2_img]: reg = Registration('Rigid', fixed_image=t1_template, save_dir=save_dir, save_suffix='_coreg') reg.fit(img) # Co-registration across-visit reg = Registration('Rigid', fixed_image=t1) reg.fit(moving=t1_followup) # now align all followups with first visit for img in [flair_follwup, t2_followup]: img_reg = reg.transform(img) # conversly, align all first visits with followups for img in [flair, t2]: img_reg = reg.inverse_transform(img) ''' def __init__(self, type_of_transform, fixed_image): ''' Properties: type_of_transform fixed_image (template) save_dir (where to save outputs) save_suffix (what to append to saved outputs) save_prefix (what to preppend to saved outputs) ''' pass def fit(self, X, y=None): ''' X : ANTsImage | string | list of ANTsImage types | list of strings images to register to fixed image y : string | list of strings labels for images ''' pass def transform(self, X, y=None): pass
4
3
18
2
11
5
2
1
1
4
0
0
3
6
3
3
83
13
35
15
31
35
21
15
17
4
1
1
6
1,728
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.TranslateImage
class TranslateImage(object): """ Translate an image in physical space. This function calls highly optimized ITK/C++ code. """ def __init__(self, translation, reference=None, interp='linear'): """ Initialize a TranslateImage transform Arguments --------- translation : list, tuple, or numpy.ndarray absolute pixel transformation in each axis reference : ANTsImage (optional) image which provides the reference physical space in which to perform the transform interp : string type of interpolation to use options: linear, nearest Example ------- >>> import ants >>> translater = ants.contrib.TranslateImage((10,10), interp='linear') """ if interp not in {'linear', 'nearest'}: raise ValueError('interp must be one of {linear, nearest}') self.translation = list(translation) self.reference = reference self.interp = interp def transform(self, X, y=None): """ Example ------- >>> import ants >>> translater = ants.contrib.TranslateImage((40,0)) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = translater.transform(img2d) >>> ants.plot(img2d, img2d_r) >>> translater = ants.contrib.TranslateImage((40,0,0)) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = translater.transform(img3d) >>> ants.plot(img3d, img3d_r, axis=2) """ if X.pixeltype != 'float': raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float') if len(self.translation) != X.dimension: raise ValueError('must give a translation value for each image dimension') if self.reference is None: reference = X else: reference = self.reference insuffix = X._libsuffix cast_fn = utils.get_lib_fn('translateAntsImage%s_%s' % (insuffix, self.interp)) casted_ptr = cast_fn(X.pointer, reference.pointer, self.translation) return iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr)
class TranslateImage(object): ''' Translate an image in physical space. This function calls highly optimized ITK/C++ code. ''' def __init__(self, translation, reference=None, interp='linear'): ''' Initialize a TranslateImage transform Arguments --------- translation : list, tuple, or numpy.ndarray absolute pixel transformation in each axis reference : ANTsImage (optional) image which provides the reference physical space in which to perform the transform interp : string type of interpolation to use options: linear, nearest Example ------- >>> import ants >>> translater = ants.contrib.TranslateImage((10,10), interp='linear') ''' pass def transform(self, X, y=None): ''' Example ------- >>> import ants >>> translater = ants.contrib.TranslateImage((40,0)) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = translater.transform(img2d) >>> ants.plot(img2d, img2d_r) >>> translater = ants.contrib.TranslateImage((40,0,0)) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = translater.transform(img3d) >>> ants.plot(img3d, img3d_r, axis=2) ''' pass
3
3
29
4
10
15
3
1.62
1
3
1
0
2
3
2
2
64
9
21
10
18
34
19
10
16
4
1
1
6
1,729
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.SigmoidIntensity
class SigmoidIntensity(object): """ Transform an image using a sigmoid function """ def __init__(self, min_val, max_val, alpha, beta): """ Initialize a SigmoidIntensity transform Arguments --------- min_val : float minimum value max_val : float maximum value alpha : float alpha value for sigmoid beta : flaot beta value for sigmoid Example ------- >>> import ants >>> sigscaler = ants.contrib.SigmoidIntensity(0,1,1,1) """ self.min_val = min_val self.max_val = max_val self.alpha = alpha self.beta = beta def transform(self, X, y=None): """ Transform an image by applying a sigmoid function. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> sigscaler = ants.contrib.SigmoidIntensity(0,1,1,1) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = sigscaler.transform(img2d) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = sigscaler.transform(img3d) """ if X.pixeltype != 'float': raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float') insuffix = X._libsuffix cast_fn = utils.get_lib_fn('sigmoidAntsImage%s' % (insuffix)) casted_ptr = cast_fn(X.pointer, self.min_val, self.max_val, self.alpha, self.beta) return iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr)
class SigmoidIntensity(object): ''' Transform an image using a sigmoid function ''' def __init__(self, min_val, max_val, alpha, beta): ''' Initialize a SigmoidIntensity transform Arguments --------- min_val : float minimum value max_val : float maximum value alpha : float alpha value for sigmoid beta : flaot beta value for sigmoid Example ------- >>> import ants >>> sigscaler = ants.contrib.SigmoidIntensity(0,1,1,1) ''' pass def transform(self, X, y=None): ''' Transform an image by applying a sigmoid function. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> sigscaler = ants.contrib.SigmoidIntensity(0,1,1,1) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = sigscaler.transform(img2d) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = sigscaler.transform(img3d) ''' pass
3
3
28
5
7
17
2
2.64
1
2
1
0
2
4
2
2
61
10
14
10
11
37
13
10
10
2
1
1
3
1,730
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.ShiftScaleIntensity
class ShiftScaleIntensity(object): """ Shift and scale the intensity of an ANTsImage """ def __init__(self, shift, scale): """ Initialize a ShiftScaleIntensity transform Arguments --------- shift : float shift all of the intensity values by the given amount through addition. For example, if the minimum image value is 0.0 and the shift is 10.0, then the new minimum value (before scaling) will be 10.0 scale : float scale all the intensity values by the given amount through multiplication. For example, if the min/max image values are 10/20 and the scale is 2.0, then then new min/max values will be 20/40 Example ------- >>> import ants >>> shiftscaler = ants.contrib.ShiftScaleIntensity(shift=10, scale=2) """ self.shift = shift self.scale = scale def transform(self, X, y=None): """ Transform an image by shifting and scaling its intensity values. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> shiftscaler = ants.contrib.ShiftScaleIntensity(10,2.) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = shiftscaler.transform(img2d) >>> print(img2d.min(), ',', img2d.max(), ' -> ', img2d_r.min(), ',', img2d_r.max()) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = shiftscaler.transform(img3d) >>> print(img3d.min(), ',' , img3d.max(), ',', ' -> ', img3d_r.min(), ',' , img3d_r.max()) """ if X.pixeltype != 'float': raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float') insuffix = X._libsuffix cast_fn = utils.get_lib_fn('shiftScaleAntsImage%s' % (insuffix)) casted_ptr = cast_fn(X.pointer, self.scale, self.shift) return iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr)
class ShiftScaleIntensity(object): ''' Shift and scale the intensity of an ANTsImage ''' def __init__(self, shift, scale): ''' Initialize a ShiftScaleIntensity transform Arguments --------- shift : float shift all of the intensity values by the given amount through addition. For example, if the minimum image value is 0.0 and the shift is 10.0, then the new minimum value (before scaling) will be 10.0 scale : float scale all the intensity values by the given amount through multiplication. For example, if the min/max image values are 10/20 and the scale is 2.0, then then new min/max values will be 20/40 Example ------- >>> import ants >>> shiftscaler = ants.contrib.ShiftScaleIntensity(shift=10, scale=2) ''' pass def transform(self, X, y=None): ''' Transform an image by shifting and scaling its intensity values. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> shiftscaler = ants.contrib.ShiftScaleIntensity(10,2.) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = shiftscaler.transform(img2d) >>> print(img2d.min(), ',', img2d.max(), ' -> ', img2d_r.min(), ',', img2d_r.max()) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = shiftscaler.transform(img3d) >>> print(img3d.min(), ',' , img3d.max(), ',', ' -> ', img3d_r.min(), ',' , img3d_r.max()) ''' pass
3
3
27
4
6
18
2
3.25
1
2
1
0
2
2
2
2
59
8
12
8
9
39
11
8
8
2
1
1
3
1,731
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.ScaleImage
class ScaleImage(object): """ Scale an image in physical space. This function calls highly optimized ITK/C++ code. """ def __init__(self, scale, reference=None, interp='linear'): """ Initialize a TranslateImage transform Arguments --------- scale : list, tuple, or numpy.ndarray relative scaling along each axis reference : ANTsImage (optional) image which provides the reference physical space in which to perform the transform interp : string type of interpolation to use options: linear, nearest Example ------- >>> import ants >>> translater = ants.contrib.TranslateImage((10,10), interp='linear') """ if interp not in {'linear', 'nearest'}: raise ValueError('interp must be one of {linear, nearest}') self.scale = list(scale) self.reference = reference self.interp = interp def transform(self, X, y=None): """ Example ------- >>> import ants >>> scaler = ants.contrib.ScaleImage((1.2,1.2)) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = scaler.transform(img2d) >>> ants.plot(img2d, img2d_r) >>> scaler = ants.contrib.ScaleImage((1.2,1.2,1.2)) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = scaler.transform(img3d) >>> ants.plot(img3d, img3d_r) """ if X.pixeltype != 'float': raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float') if len(self.scale) != X.dimension: raise ValueError('must give a scale value for each image dimension') if self.reference is None: reference = X else: reference = self.reference insuffix = X._libsuffix cast_fn = utils.get_lib_fn('scaleAntsImage%s_%s' % (insuffix, self.interp)) casted_ptr = cast_fn(X.pointer, reference.pointer, self.scale) return iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr)
class ScaleImage(object): ''' Scale an image in physical space. This function calls highly optimized ITK/C++ code. ''' def __init__(self, scale, reference=None, interp='linear'): ''' Initialize a TranslateImage transform Arguments --------- scale : list, tuple, or numpy.ndarray relative scaling along each axis reference : ANTsImage (optional) image which provides the reference physical space in which to perform the transform interp : string type of interpolation to use options: linear, nearest Example ------- >>> import ants >>> translater = ants.contrib.TranslateImage((10,10), interp='linear') ''' pass def transform(self, X, y=None): ''' Example ------- >>> import ants >>> scaler = ants.contrib.ScaleImage((1.2,1.2)) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = scaler.transform(img2d) >>> ants.plot(img2d, img2d_r) >>> scaler = ants.contrib.ScaleImage((1.2,1.2,1.2)) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = scaler.transform(img3d) >>> ants.plot(img3d, img3d_r) ''' pass
3
3
29
4
10
15
3
1.62
1
3
1
0
2
3
2
2
64
9
21
10
18
34
19
10
16
4
1
1
6
1,732
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.RescaleIntensity
class RescaleIntensity(object): """ Rescale the pixeltype of an ANTsImage linearly to be between a given minimum and maximum value. This code uses the C++ ITK library directly, so it is fast. NOTE: this offered a ~5x speedup over using built-in arithmetic operations in ANTs. It is also more-or-less the same in speed as an equivalent numpy+scikit-learn solution. Timing vs Built-in Operations ----------------------------- >>> import ants >>> import time >>> rescaler = ants.contrib.RescaleIntensity(0,1) >>> img = ants.image_read(ants.get_data('mni')) >>> s = time.time() >>> for i in range(100): ... img_float = rescaler.transform(img) >>> e = time.time() >>> print(e - s) # 2.8s >>> s = time.time() >>> for i in range(100): ... maxval = img.max() ... img_float = (img - maxval) / (maxval - img.min()) >>> e = time.time() >>> print(e - s) # 13.9s Timing vs Numpy+Scikit-Learn ---------------------------- >>> import ants >>> import numpy as np >>> from sklearn.preprocessing import MinMaxScaler >>> import time >>> img = ants.image_read(ants.get_data('mni')) >>> arr = img.numpy().reshape(1,-1) >>> rescaler = ants.contrib.RescaleIntensity(-1,1) >>> rescaler2 = MinMaxScaler((-1,1)).fit(arr) >>> s = time.time() >>> for i in range(100): ... img_scaled = rescaler.transform(img) >>> e = time.time() >>> print(e - s) # 2.8s >>> s = time.time() >>> for i in range(100): ... arr_scaled = rescaler2.transform(arr) >>> e = time.time() >>> print(e - s) # 3s """ def __init__(self, min_val, max_val): """ Initialize a RescaleIntensity transform. Arguments --------- min_val : float minimum value to which image(s) will be rescaled max_val : float maximum value to which image(s) will be rescaled Example ------- >>> import ants >>> rescaler = ants.contrib.RescaleIntensity(0,1) """ self.min_val = min_val self.max_val = max_val def transform(self, X, y=None): """ Transform an image by linearly rescaling its intensity to be between a minimum and maximum value Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> rescaler = ants.contrib.RescaleIntensity(0,1) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = rescaler.transform(img2d) >>> print(img2d.min(), ',', img2d.max(), ' -> ', img2d_r.min(), ',', img2d_r.max()) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = rescaler.transform(img3d) >>> print(img3d.min(), ',' , img3d.max(), ' -> ', img3d_r.min(), ',' , img3d_r.max()) """ if X.pixeltype != 'float': raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float') insuffix = X._libsuffix cast_fn = utils.get_lib_fn('rescaleAntsImage%s' % (insuffix)) casted_ptr = cast_fn(X.pointer, self.min_val, self.max_val) return iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr)
class RescaleIntensity(object): ''' Rescale the pixeltype of an ANTsImage linearly to be between a given minimum and maximum value. This code uses the C++ ITK library directly, so it is fast. NOTE: this offered a ~5x speedup over using built-in arithmetic operations in ANTs. It is also more-or-less the same in speed as an equivalent numpy+scikit-learn solution. Timing vs Built-in Operations ----------------------------- >>> import ants >>> import time >>> rescaler = ants.contrib.RescaleIntensity(0,1) >>> img = ants.image_read(ants.get_data('mni')) >>> s = time.time() >>> for i in range(100): ... img_float = rescaler.transform(img) >>> e = time.time() >>> print(e - s) # 2.8s >>> s = time.time() >>> for i in range(100): ... maxval = img.max() ... img_float = (img - maxval) / (maxval - img.min()) >>> e = time.time() >>> print(e - s) # 13.9s Timing vs Numpy+Scikit-Learn ---------------------------- >>> import ants >>> import numpy as np >>> from sklearn.preprocessing import MinMaxScaler >>> import time >>> img = ants.image_read(ants.get_data('mni')) >>> arr = img.numpy().reshape(1,-1) >>> rescaler = ants.contrib.RescaleIntensity(-1,1) >>> rescaler2 = MinMaxScaler((-1,1)).fit(arr) >>> s = time.time() >>> for i in range(100): ... img_scaled = rescaler.transform(img) >>> e = time.time() >>> print(e - s) # 2.8s >>> s = time.time() >>> for i in range(100): ... arr_scaled = rescaler2.transform(arr) >>> e = time.time() >>> print(e - s) # 3s ''' def __init__(self, min_val, max_val): ''' Initialize a RescaleIntensity transform. Arguments --------- min_val : float minimum value to which image(s) will be rescaled max_val : float maximum value to which image(s) will be rescaled Example ------- >>> import ants >>> rescaler = ants.contrib.RescaleIntensity(0,1) ''' pass def transform(self, X, y=None): ''' Transform an image by linearly rescaling its intensity to be between a minimum and maximum value Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> rescaler = ants.contrib.RescaleIntensity(0,1) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = rescaler.transform(img2d) >>> print(img2d.min(), ',', img2d.max(), ' -> ', img2d_r.min(), ',', img2d_r.max()) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = rescaler.transform(img3d) >>> print(img3d.min(), ',' , img3d.max(), ' -> ', img3d_r.min(), ',' , img3d_r.max()) ''' pass
3
3
26
4
6
17
2
6.5
1
2
1
0
2
2
2
2
102
12
12
8
9
78
11
8
8
2
1
1
3
1,733
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.NormalizeIntensity
class NormalizeIntensity(object): """ Normalize the intensity values of an ANTsImage to have zero mean and unit variance NOTE: this transform is more-or-less the same in speed as an equivalent numpy+scikit-learn solution. Timing vs Numpy+Scikit-Learn ---------------------------- >>> import ants >>> import numpy as np >>> from sklearn.preprocessing import StandardScaler >>> import time >>> img = ants.image_read(ants.get_data('mni')) >>> arr = img.numpy().reshape(1,-1) >>> normalizer = ants.contrib.NormalizeIntensity() >>> normalizer2 = StandardScaler() >>> s = time.time() >>> for i in range(100): ... img_scaled = normalizer.transform(img) >>> e = time.time() >>> print(e - s) # 3.3s >>> s = time.time() >>> for i in range(100): ... arr_scaled = normalizer2.fit_transform(arr) >>> e = time.time() >>> print(e - s) # 3.5s """ def __init__(self): """ Initialize a NormalizeIntensity transform """ pass def transform(self, X, y=None): """ Transform an image by normalizing its intensity values to have zero mean and unit variance. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> normalizer = ants.contrib.NormalizeIntensity() >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = normalizer.transform(img2d) >>> print(img2d.mean(), ',', img2d.std(), ' -> ', img2d_r.mean(), ',', img2d_r.std()) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = normalizer.transform(img3d) >>> print(img3d.mean(), ',' , img3d.std(), ',', ' -> ', img3d_r.mean(), ',' , img3d_r.std()) """ if X.pixeltype != 'float': raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float') insuffix = X._libsuffix cast_fn = utils.get_lib_fn('normalizeAntsImage%s' % (insuffix)) casted_ptr = cast_fn(X.pointer) return iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr)
class NormalizeIntensity(object): ''' Normalize the intensity values of an ANTsImage to have zero mean and unit variance NOTE: this transform is more-or-less the same in speed as an equivalent numpy+scikit-learn solution. Timing vs Numpy+Scikit-Learn ---------------------------- >>> import ants >>> import numpy as np >>> from sklearn.preprocessing import StandardScaler >>> import time >>> img = ants.image_read(ants.get_data('mni')) >>> arr = img.numpy().reshape(1,-1) >>> normalizer = ants.contrib.NormalizeIntensity() >>> normalizer2 = StandardScaler() >>> s = time.time() >>> for i in range(100): ... img_scaled = normalizer.transform(img) >>> e = time.time() >>> print(e - s) # 3.3s >>> s = time.time() >>> for i in range(100): ... arr_scaled = normalizer2.fit_transform(arr) >>> e = time.time() >>> print(e - s) # 3.5s ''' def __init__(self): ''' Initialize a NormalizeIntensity transform ''' pass def transform(self, X, y=None): ''' Transform an image by normalizing its intensity values to have zero mean and unit variance. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> normalizer = ants.contrib.NormalizeIntensity() >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = normalizer.transform(img2d) >>> print(img2d.mean(), ',', img2d.std(), ' -> ', img2d_r.mean(), ',', img2d_r.std()) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_r = normalizer.transform(img3d) >>> print(img3d.mean(), ',' , img3d.std(), ',', ' -> ', img3d_r.mean(), ',' , img3d_r.std()) ''' pass
3
3
19
2
5
12
2
4.45
1
2
1
0
2
0
2
2
67
7
11
6
8
49
10
6
7
2
1
1
3
1,734
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.MultiResolutionImage
class MultiResolutionImage(object): """ Generate a set of images at multiple resolutions from an original image """ def __init__(self, levels=4, keep_shape=False): self.levels = levels self.keep_shape = keep_shape def transform(self, X, y=None): """ Generate a set of multi-resolution ANTsImage types Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform Example ------- >>> import ants >>> multires = ants.contrib.MultiResolutionImage(levels=4) >>> img = ants.image_read(ants.get_data('r16')) >>> imgs = multires.transform(img) """ insuffix = X._libsuffix multires_fn = utils.get_lib_fn('multiResolutionAntsImage%s' % (insuffix)) casted_ptrs = multires_fn(X.pointer, self.levels) imgs = [] for casted_ptr in casted_ptrs: img = iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr) if self.keep_shape: img = img.resample_image_to_target(X) imgs.append(img) return imgs
class MultiResolutionImage(object): ''' Generate a set of images at multiple resolutions from an original image ''' def __init__(self, levels=4, keep_shape=False): pass def transform(self, X, y=None): ''' Generate a set of multi-resolution ANTsImage types Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform Example ------- >>> import ants >>> multires = ants.contrib.MultiResolutionImage(levels=4) >>> img = ants.image_read(ants.get_data('r16')) >>> imgs = multires.transform(img) ''' pass
3
2
18
3
8
8
2
1.13
1
1
1
0
2
2
2
2
40
6
16
11
13
18
15
11
12
3
1
2
4
1,735
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.LocallyBlurIntensity
class LocallyBlurIntensity(object): """ Blur an ANTsImage locally using a gradient anisotropic diffusion filter, thereby preserving the sharpeness of edges as best as possible. """ def __init__(self, conductance=1, iters=5): self.conductance = conductance self.iters = iters def transform(self, X, y=None): """ Locally blur an image by applying a gradient anisotropic diffusion filter. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> blur = ants.contrib.LocallyBlurIntensity(1,5) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_b = blur.transform(img2d) >>> ants.plot(img2d) >>> ants.plot(img2d_b) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_b = blur.transform(img3d) >>> ants.plot(img3d) >>> ants.plot(img3d_b) """ #if X.pixeltype != 'float': # raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float') insuffix = X._libsuffix cast_fn = utils.get_lib_fn('locallyBlurAntsImage%s' % (insuffix)) casted_ptr = cast_fn(X.pointer, self.iters, self.conductance) return iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr)
class LocallyBlurIntensity(object): ''' Blur an ANTsImage locally using a gradient anisotropic diffusion filter, thereby preserving the sharpeness of edges as best as possible. ''' def __init__(self, conductance=1, iters=5): pass def transform(self, X, y=None): ''' Locally blur an image by applying a gradient anisotropic diffusion filter. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> blur = ants.contrib.LocallyBlurIntensity(1,5) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_b = blur.transform(img2d) >>> ants.plot(img2d) >>> ants.plot(img2d_b) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_b = blur.transform(img3d) >>> ants.plot(img3d) >>> ants.plot(img3d_b) ''' pass
3
2
18
2
5
12
1
2.8
1
1
1
0
2
2
2
2
42
4
10
8
7
28
9
8
6
1
1
0
2
1,736
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.FlipImage
class FlipImage(object): """ Transform an image by flipping two axes. """ def __init__(self, axis1, axis2): """ Initialize a SigmoidIntensity transform Arguments --------- axis1 : int axis to flip axis2 : int other axis to flip Example ------- >>> import ants >>> flipper = ants.contrib.FlipImage(0,1) """ self.axis1 = axis1 self.axis2 = axis2 def transform(self, X, y=None): """ Transform an image by applying a sigmoid function. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> flipper = ants.contrib.FlipImage(0,1) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = flipper.transform(img2d) >>> ants.plot(img2d) >>> ants.plot(img2d_r) >>> flipper2 = ants.contrib.FlipImage(1,0) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = flipper2.transform(img2d) >>> ants.plot(img2d) >>> ants.plot(img2d_r) """ if X.pixeltype != 'float': raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float') insuffix = X._libsuffix cast_fn = utils.get_lib_fn('flipAntsImage%s' % (insuffix)) casted_ptr = cast_fn(X.pointer, self.axis1, self.axis2) return iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr, origin=X.origin)
class FlipImage(object): ''' Transform an image by flipping two axes. ''' def __init__(self, axis1, axis2): ''' Initialize a SigmoidIntensity transform Arguments --------- axis1 : int axis to flip axis2 : int other axis to flip Example ------- >>> import ants >>> flipper = ants.contrib.FlipImage(0,1) ''' pass def transform(self, X, y=None): ''' Transform an image by applying a sigmoid function. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> flipper = ants.contrib.FlipImage(0,1) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = flipper.transform(img2d) >>> ants.plot(img2d) >>> ants.plot(img2d_r) >>> flipper2 = ants.contrib.FlipImage(1,0) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_r = flipper2.transform(img2d) >>> ants.plot(img2d) >>> ants.plot(img2d_r) ''' pass
3
3
27
4
6
18
2
2.92
1
2
1
0
2
2
2
2
59
8
13
8
10
38
11
8
8
2
1
1
3
1,737
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.CastIntensity
class CastIntensity(object): """ Cast the pixeltype of an ANTsImage to a given type. This code uses the C++ ITK library directly, so it is fast. NOTE: This offers a ~2.5x speedup over using img.clone(pixeltype): Timings vs Cloning ------------------ >>> import ants >>> import time >>> caster = ants.contrib.CastIntensity('float') >>> img = ants.image_read(ants.get_data('mni')).clone('unsigned int') >>> s = time.time() >>> for i in range(1000): ... img_float = caster.transform(img) >>> e = time.time() >>> print(e - s) # 9.6s >>> s = time.time() >>> for i in range(1000): ... img_float = img.clone('float') >>> e = time.time() >>> print(e - s) # 25.3s """ def __init__(self, pixeltype): """ Initialize a CastIntensity transform Arguments --------- pixeltype : string pixeltype to which images will be casted Example ------- >>> import ants >>> caster = ants.contrib.CastIntensity('float') """ self.pixeltype = pixeltype def transform(self, X, y=None): """ Transform an image by casting its type Arguments --------- X : ANTsImage image to cast y : ANTsImage (optional) another image to cast. Example ------- >>> import ants >>> caster = ants.contrib.CastIntensity('float') >>> img2d = ants.image_read(ants.get_data('r16')).clone('unsigned int') >>> img2d_float = caster.transform(img2d) >>> print(img2d.pixeltype, '- ', img2d_float.pixeltype) >>> img3d = ants.image_read(ants.get_data('mni')).clone('unsigned int') >>> img3d_float = caster.transform(img3d) >>> print(img3d.pixeltype, ' - ' , img3d_float.pixeltype) """ insuffix = X._libsuffix outsuffix = '%s%i' % (utils.short_ptype(self.pixeltype), X.dimension) cast_fn = utils.get_lib_fn('castAntsImage%s%s' % (insuffix, outsuffix)) casted_ptr = cast_fn(X.pointer) return iio.ANTsImage(pixeltype=self.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr)
class CastIntensity(object): ''' Cast the pixeltype of an ANTsImage to a given type. This code uses the C++ ITK library directly, so it is fast. NOTE: This offers a ~2.5x speedup over using img.clone(pixeltype): Timings vs Cloning ------------------ >>> import ants >>> import time >>> caster = ants.contrib.CastIntensity('float') >>> img = ants.image_read(ants.get_data('mni')).clone('unsigned int') >>> s = time.time() >>> for i in range(1000): ... img_float = caster.transform(img) >>> e = time.time() >>> print(e - s) # 9.6s >>> s = time.time() >>> for i in range(1000): ... img_float = img.clone('float') >>> e = time.time() >>> print(e - s) # 25.3s ''' def __init__(self, pixeltype): ''' Initialize a CastIntensity transform Arguments --------- pixeltype : string pixeltype to which images will be casted Example ------- >>> import ants >>> caster = ants.contrib.CastIntensity('float') ''' pass def transform(self, X, y=None): ''' Transform an image by casting its type Arguments --------- X : ANTsImage image to cast y : ANTsImage (optional) another image to cast. Example ------- >>> import ants >>> caster = ants.contrib.CastIntensity('float') >>> img2d = ants.image_read(ants.get_data('r16')).clone('unsigned int') >>> img2d_float = caster.transform(img2d) >>> print(img2d.pixeltype, '- ', img2d_float.pixeltype) >>> img3d = ants.image_read(ants.get_data('mni')).clone('unsigned int') >>> img3d_float = caster.transform(img3d) >>> print(img3d.pixeltype, ' - ' , img3d_float.pixeltype) ''' pass
3
3
22
3
5
15
1
5.1
1
1
1
0
2
1
2
2
69
8
10
8
7
51
9
8
6
1
1
0
2
1,738
ANTsX/ANTsPy
tests/test_core_ants_image.py
test_core_ants_image.TestModule_ants_image
class TestModule_ants_image(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')).clone('float') img3d = ants.image_read(ants.get_ants_data('mni')).clone('float') self.imgs = [img2d, img3d] self.pixeltypes = ['unsigned char', 'unsigned int', 'float', 'double'] def tearDown(self): pass def test_copy_image_info(self): for img in self.imgs: img2 = img.clone() img2.set_spacing([6.9]*img.dimension) img2.set_origin([6.9]*img.dimension) self.assertTrue(not ants.image_physical_space_consistency(img,img2)) img3 = ants.copy_image_info(reference=img, target=img2) self.assertTrue(ants.image_physical_space_consistency(img,img3)) def test_get_spacing(self): for img in self.imgs: spacing = ants.get_spacing(img) self.assertTrue(isinstance(spacing, tuple)) self.assertEqual(len(ants.get_spacing(img)), img.dimension) def test_set_spacing(self): for img in self.imgs: # set spacing from list new_spacing_list = [6.9]*img.dimension ants.set_spacing(img, new_spacing_list) self.assertEqual(img.spacing, tuple(new_spacing_list)) # set spacing from tuple new_spacing_tuple = tuple(new_spacing_list) ants.set_spacing(img, new_spacing_tuple) self.assertEqual(ants.get_spacing(img), new_spacing_tuple) def test_get_origin(self): for img in self.imgs: origin = ants.get_origin(img) self.assertTrue(isinstance(origin, tuple)) self.assertEqual(len(ants.get_origin(img)), img.dimension) def test_set_origin(self): for img in self.imgs: # set spacing from list new_origin_list = [6.9]*img.dimension ants.set_origin(img, new_origin_list) self.assertEqual(img.origin, tuple(new_origin_list)) # set spacing from tuple new_origin_tuple = tuple(new_origin_list) ants.set_origin(img, new_origin_tuple) self.assertEqual(ants.get_origin(img), new_origin_tuple) def test_get_direction(self): for img in self.imgs: direction = ants.get_direction(img) self.assertTrue(isinstance(direction,np.ndarray)) self.assertTrue(ants.get_direction(img).shape, (img.dimension,img.dimension)) def test_set_direction(self): for img in self.imgs: new_direction = np.eye(img.dimension)*3 ants.set_direction(img, new_direction) nptest.assert_allclose(ants.get_direction(img), new_direction) def test_image_physical_spacing_consistency(self): for img in self.imgs: self.assertTrue(ants.image_physical_space_consistency(img,img)) self.assertTrue(ants.image_physical_space_consistency(img,img,datatype=True)) clonetype = 'float' if img.pixeltype != 'float' else 'unsigned int' img2 = img.clone(clonetype) self.assertTrue(ants.image_physical_space_consistency(img,img2)) self.assertTrue(not ants.image_physical_space_consistency(img,img2,datatype=True)) # test incorrectness # # bad spacing img2 = img.clone() img2.set_spacing([6.96]*img.dimension) self.assertTrue(not ants.image_physical_space_consistency(img,img2)) # bad origin img2 = img.clone() img2.set_origin([6.96]*img.dimension) self.assertTrue(not ants.image_physical_space_consistency(img,img2)) # bad direction img2 = img.clone() img2.set_direction(img.direction*2) self.assertTrue(not ants.image_physical_space_consistency(img,img2)) # bad dimension ndim = img.dimension img2 = ants.from_numpy(np.random.randn(*tuple([69]*(ndim+1))).astype('float32')) self.assertTrue(not ants.image_physical_space_consistency(img,img2)) # only one image with self.assertRaises(Exception): ants.image_physical_space_consistency(img) # not an ANTsImage with self.assertRaises(Exception): ants.image_physical_space_consistency(img, 12) # false because of components vecimg = ants.from_numpy(np.random.randn(69,70,3), has_components=True) vecimg2 = ants.from_numpy(np.random.randn(69,70,4), has_components=True) self.assertTrue(not ants.image_physical_space_consistency(vecimg, vecimg2, datatype=True)) def test_image_type_cast(self): # test with list of images imgs2 = ants.image_type_cast(self.imgs) for img in imgs2: self.assertTrue(img.pixeltype, 'float') # not a list or tuple with self.assertRaises(Exception): ants.image_type_cast(self.imgs[0]) # cast from unsigned int imgs = [i.clone() for i in self.imgs] imgs[0] = imgs[0].clone('unsigned int') imgs2 = ants.image_type_cast(imgs) def test_allclose(self): for img in self.imgs: img2 = img.clone() self.assertTrue(ants.allclose(img,img2)) self.assertTrue(ants.allclose(img*6.9, img2*6.9)) self.assertTrue(not ants.allclose(img, img2*6.9)) def test_pickle(self): import ants import pickle img = ants.image_read( ants.get_ants_data("mni")) img_pickled = pickle.dumps(img) img2 = pickle.loads(img_pickled) self.assertTrue(ants.allclose(img, img2)) self.assertTrue(ants.image_physical_space_consistency(img, img2)) img = ants.image_read( ants.get_ants_data("r16")) img_pickled = pickle.dumps(img) img2 = pickle.loads(img_pickled) self.assertTrue(ants.allclose(img, img2)) self.assertTrue(ants.image_physical_space_consistency(img, img2))
class TestModule_ants_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_copy_image_info(self): pass def test_get_spacing(self): pass def test_set_spacing(self): pass def test_get_origin(self): pass def test_set_origin(self): pass def test_get_direction(self): pass def test_set_direction(self): pass def test_image_physical_spacing_consistency(self): pass def test_image_type_cast(self): pass def test_allclose(self): pass def test_pickle(self): pass
14
0
10
1
8
1
2
0.14
1
2
0
0
13
2
13
85
150
28
107
51
91
15
107
51
91
3
2
2
24
1,739
ANTsX/ANTsPy
ants/contrib/sampling/transforms.py
ants.contrib.sampling.transforms.BlurIntensity
class BlurIntensity(object): """ Transform for blurring the intensity of an ANTsImage using a Gaussian Filter """ def __init__(self, sigma, width): """ Initialize a BlurIntensity transform Arguments --------- sigma : float variance of gaussian kernel intensity increasing this value increasing the amount of blur width : int width of gaussian kernel shape increasing this value increase the number of neighboring voxels which are used for blurring Example ------- >>> import ants >>> blur = ants.contrib.BlurIntensity(2,3) """ self.sigma = sigma self.width = width def transform(self, X, y=None): """ Blur an image by applying a gaussian filter. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> blur = ants.contrib.BlurIntensity(2,3) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_b = blur.transform(img2d) >>> ants.plot(img2d) >>> ants.plot(img2d_b) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_b = blur.transform(img3d) >>> ants.plot(img3d) >>> ants.plot(img3d_b) """ if X.pixeltype != 'float': raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float') insuffix = X._libsuffix cast_fn = utils.get_lib_fn('blurAntsImage%s' % (insuffix)) casted_ptr = cast_fn(X.pointer, self.sigma, self.width) return iio.ANTsImage(pixeltype=X.pixeltype, dimension=X.dimension, components=X.components, pointer=casted_ptr, origin=X.origin)
class BlurIntensity(object): ''' Transform for blurring the intensity of an ANTsImage using a Gaussian Filter ''' def __init__(self, sigma, width): ''' Initialize a BlurIntensity transform Arguments --------- sigma : float variance of gaussian kernel intensity increasing this value increasing the amount of blur width : int width of gaussian kernel shape increasing this value increase the number of neighboring voxels which are used for blurring Example ------- >>> import ants >>> blur = ants.contrib.BlurIntensity(2,3) ''' pass def transform(self, X, y=None): ''' Blur an image by applying a gaussian filter. Arguments --------- X : ANTsImage image to transform y : ANTsImage (optional) another image to transform. Example ------- >>> import ants >>> blur = ants.contrib.BlurIntensity(2,3) >>> img2d = ants.image_read(ants.get_data('r16')) >>> img2d_b = blur.transform(img2d) >>> ants.plot(img2d) >>> ants.plot(img2d_b) >>> img3d = ants.image_read(ants.get_data('mni')) >>> img3d_b = blur.transform(img3d) >>> ants.plot(img3d) >>> ants.plot(img3d_b) ''' pass
3
3
29
4
6
19
2
3.23
1
2
1
0
2
2
2
2
63
8
13
8
10
42
11
8
8
2
1
1
3
1,740
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
ants.contrib.sampling.affine3d.Translate3D
class Translate3D(object): """ Create an ANTs Affine Transform with a specified translation. """ def __init__(self, translation, reference=None, lazy=False): """ Initialize a Translate3D object Arguments --------- translation : list or tuple translation values for each axis, in degrees. Negative values can be used for translation in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(translation, (list, tuple))) or (len(translation) != 3): raise ValueError( "translation argument must be list/tuple with three values!" ) self.translation = translation self.lazy = lazy self.reference = reference self.tx = tio.ANTsTransform( precision="float", dimension=3, transform_type="AffineTransform" ) if self.reference is not None: self.tx.set_fixed_parameters(self.reference.get_center_of_mass()) def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.Translate3D(translation=(10,0,0)) >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Translate3D(translation=(-10,0,0)) # other direction >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Translate3D(translation=(0,10,0)) >>> img2_y = tx.transform(img) # y axis stays same >>> tx = ants.contrib.Translate3D(translation=(0,0,10)) >>> img2_z = tx.transform(img) # z axis stays same >>> tx = ants.contrib.Translate3D(translation=(10,10,10)) >>> img2 = tx.transform(img) """ # unpack translation_x, translation_y, translation_z = self.translation translation_matrix = np.array( [ [1, 0, 0, translation_x], [0, 1, 0, translation_y], [0, 0, 1, translation_z], ] ) self.tx.set_parameters(translation_matrix) if self.lazy or X is None: return self.tx else: if y is None: return self.tx.apply_to_image(X, reference=self.reference) else: return ( self.tx.apply_to_image(X, reference=self.reference), self.tx.apply_to_image(y, reference=self.reference), )
class Translate3D(object): ''' Create an ANTs Affine Transform with a specified translation. ''' def __init__(self, translation, reference=None, lazy=False): ''' Initialize a Translate3D object Arguments --------- translation : list or tuple translation values for each axis, in degrees. Negative values can be used for translation in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.Translate3D(translation=(10,0,0)) >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Translate3D(translation=(-10,0,0)) # other direction >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Translate3D(translation=(0,10,0)) >>> img2_y = tx.transform(img) # y axis stays same >>> tx = ants.contrib.Translate3D(translation=(0,0,10)) >>> img2_z = tx.transform(img) # z axis stays same >>> tx = ants.contrib.Translate3D(translation=(10,10,10)) >>> img2 = tx.transform(img) ''' pass
3
3
44
5
17
22
3
1.38
1
4
1
0
2
4
2
2
93
12
34
9
31
47
19
9
16
3
1
2
6
1,741
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
ants.contrib.sampling.affine3d.Shear3D
class Shear3D(object): """ Create an ANTs Affine Transform with a specified shear. """ def __init__(self, shear, reference=None, lazy=False): """ Initialize a Shear3D object Arguments --------- shear : list or tuple shear values for each axis, in degrees. Negative values can be used for shear in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(shear, (list, tuple))) or (len(shear) != 3): raise ValueError("shear argument must be list/tuple with three values!") self.shear = shear self.lazy = lazy self.reference = reference self.tx = tio.ANTsTransform( precision="float", dimension=3, transform_type="AffineTransform" ) if self.reference is not None: self.tx.set_fixed_parameters(self.reference.get_center_of_mass()) def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given shear parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.Shear3D(shear=(10,0,0)) >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear3D(shear=(-10,0,0)) # other direction >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear3D(shear=(0,10,0)) >>> img2_y = tx.transform(img) # y axis stays same >>> tx = ants.contrib.Shear3D(shear=(0,0,10)) >>> img2_z = tx.transform(img) # z axis stays same >>> tx = ants.contrib.Shear3D(shear=(10,10,10)) >>> img2 = tx.transform(img) """ # convert to radians and unpack shear = [math.pi / 180 * s for s in self.shear] shear_x, shear_y, shear_z = shear shear_matrix = np.array( [ [1, shear_x, shear_x, 0], [shear_y, 1, shear_y, 0], [shear_z, shear_z, 1, 0], ] ) self.tx.set_parameters(shear_matrix) if self.lazy or X is None: return self.tx else: if y is None: return self.tx.apply_to_image(X, reference=self.reference) else: return ( self.tx.apply_to_image(X, reference=self.reference), self.tx.apply_to_image(y, reference=self.reference), )
class Shear3D(object): ''' Create an ANTs Affine Transform with a specified shear. ''' def __init__(self, shear, reference=None, lazy=False): ''' Initialize a Shear3D object Arguments --------- shear : list or tuple shear values for each axis, in degrees. Negative values can be used for shear in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with the given shear parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.Shear3D(shear=(10,0,0)) >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear3D(shear=(-10,0,0)) # other direction >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear3D(shear=(0,10,0)) >>> img2_y = tx.transform(img) # y axis stays same >>> tx = ants.contrib.Shear3D(shear=(0,0,10)) >>> img2_z = tx.transform(img) # z axis stays same >>> tx = ants.contrib.Shear3D(shear=(10,10,10)) >>> img2 = tx.transform(img) ''' pass
3
3
43
5
16
22
3
1.42
1
4
1
0
2
4
2
2
92
12
33
10
30
47
20
10
17
3
1
2
6
1,742
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
ants.contrib.sampling.affine3d.Rotate3D
class Rotate3D(object): """ Create an ANTs Affine Transform with a specified level of rotation. """ def __init__(self, rotation, reference=None, lazy=False): """ Initialize a Rotate3D object Arguments --------- rotation : list or tuple rotation values for each axis, in degrees. Negative values can be used for rotation in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(rotation, (list, tuple))) or (len(rotation) != 3): raise ValueError("rotation argument must be list/tuple with three values!") self.rotation = rotation self.lazy = lazy self.reference = reference self.tx = tio.ANTsTransform( precision="float", dimension=3, transform_type="AffineTransform" ) if self.reference is not None: self.tx.set_fixed_parameters(self.reference.get_center_of_mass()) def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given rotation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.Rotate3D(rotation=(10,-5,12)) >>> img2 = tx.transform(img) """ # unpack zoom range rotation_x, rotation_y, rotation_z = self.rotation # Rotation about X axis theta_x = math.pi / 180 * rotation_x rotate_matrix_x = np.array( [ [1, 0, 0, 0], [0, math.cos(theta_x), -math.sin(theta_x), 0], [0, math.sin(theta_x), math.cos(theta_x), 0], [0, 0, 0, 1], ] ) # Rotation about Y axis theta_y = math.pi / 180 * rotation_y rotate_matrix_y = np.array( [ [math.cos(theta_y), 0, math.sin(theta_y), 0], [0, 1, 0, 0], [-math.sin(theta_y), 0, math.cos(theta_y), 0], [0, 0, 0, 1], ] ) # Rotation about Z axis theta_z = math.pi / 180 * rotation_z rotate_matrix_z = np.array( [ [math.cos(theta_z), -math.sin(theta_z), 0, 0], [math.sin(theta_z), math.cos(theta_z), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) rotate_matrix = rotate_matrix_x.dot(rotate_matrix_y).dot(rotate_matrix_z)[:3, :] self.tx.set_parameters(rotate_matrix) if self.lazy or X is None: return self.tx else: if y is None: return self.tx.apply_to_image(X, reference=self.reference) else: return ( self.tx.apply_to_image(X, reference=self.reference), self.tx.apply_to_image(y, reference=self.reference), )
class Rotate3D(object): ''' Create an ANTs Affine Transform with a specified level of rotation. ''' def __init__(self, rotation, reference=None, lazy=False): ''' Initialize a Rotate3D object Arguments --------- rotation : list or tuple rotation values for each axis, in degrees. Negative values can be used for rotation in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with the given rotation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.Rotate3D(rotation=(10,-5,12)) >>> img2 = tx.transform(img) ''' pass
3
3
52
7
26
20
3
0.81
1
4
1
0
2
4
2
2
111
15
53
15
50
43
25
15
22
3
1
2
6
1,743
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
ants.contrib.sampling.affine3d.RandomZoom3D
class RandomZoom3D(object): """ Apply a Zoom3D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. """ def __init__(self, zoom_range, reference=None, lazy=False): """ Initialize a RandomZoom3D object Arguments --------- zoom_range : list or tuple Lower and Upper bounds on zoom parameter. e.g. zoom_range = (0.7,0.9) will result in a random draw of the zoom parameters between 0.7 and 0.9 reference : ANTsImage (optional but recommended) image providing the reference space for the transform this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(zoom_range, (list, tuple))) or (len(zoom_range) != 2): raise ValueError("zoom_range argument must be list/tuple with two values!") self.zoom_range = zoom_range self.reference = reference self.lazy = lazy def transform(self, X=None, y=None): """ Transform an image using an Affine transform with zoom parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomZoom3D(zoom_range=(0.8,0.9)) >>> img2 = tx.transform(img) """ # random draw in zoom range zoom_x = np.exp( random.gauss(np.log(self.zoom_range[0]), np.log(self.zoom_range[1])) ) zoom_y = np.exp( random.gauss(np.log(self.zoom_range[0]), np.log(self.zoom_range[1])) ) zoom_z = np.exp( random.gauss(np.log(self.zoom_range[0]), np.log(self.zoom_range[1])) ) self.params = (zoom_x, zoom_y, zoom_z) tx = Zoom3D((zoom_x, zoom_y, zoom_z), reference=self.reference, lazy=self.lazy) return tx.transform(X, y)
class RandomZoom3D(object): ''' Apply a Zoom3D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. ''' def __init__(self, zoom_range, reference=None, lazy=False): ''' Initialize a RandomZoom3D object Arguments --------- zoom_range : list or tuple Lower and Upper bounds on zoom parameter. e.g. zoom_range = (0.7,0.9) will result in a random draw of the zoom parameters between 0.7 and 0.9 reference : ANTsImage (optional but recommended) image providing the reference space for the transform this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with zoom parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomZoom3D(zoom_range=(0.8,0.9)) >>> img2 = tx.transform(img) ''' pass
3
3
33
5
10
19
2
2.15
1
4
1
0
2
4
2
2
75
12
20
11
17
43
14
11
11
2
1
1
3
1,744
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
ants.contrib.sampling.affine3d.RandomTranslate3D
class RandomTranslate3D(object): """ Apply a Translate3D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. """ def __init__(self, translation_range, reference=None, lazy=False): """ Initialize a RandomTranslate3D object Arguments --------- translation_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. translation_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(translation_range, (list, tuple))) or ( len(translation_range) != 2 ): raise ValueError("shear_range argument must be list/tuple with two values!") self.translation_range = translation_range self.reference = reference self.lazy = lazy def transform(self, X=None, y=None): """ Transform an image using an Affine transform with translation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomShear3D(translation_range=(-10,10)) >>> img2 = tx.transform(img) """ # random draw in translation range translation_x = random.gauss( self.translation_range[0], self.translation_range[1] ) translation_y = random.gauss( self.translation_range[0], self.translation_range[1] ) translation_z = random.gauss( self.translation_range[0], self.translation_range[1] ) self.params = (translation_x, translation_y, translation_z) tx = Translate3D( (translation_x, translation_y, translation_z), reference=self.reference, lazy=self.lazy, ) return tx.transform(X, y)
class RandomTranslate3D(object): ''' Apply a Translate3D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. ''' def __init__(self, translation_range, reference=None, lazy=False): ''' Initialize a RandomTranslate3D object Arguments --------- translation_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. translation_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with translation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomShear3D(translation_range=(-10,10)) >>> img2 = tx.transform(img) ''' pass
3
3
36
5
13
19
2
1.65
1
4
1
0
2
4
2
2
81
12
26
11
23
43
14
11
11
2
1
1
3
1,745
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
ants.contrib.sampling.affine3d.RandomShear3D
class RandomShear3D(object): """ Apply a Shear3D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. """ def __init__(self, shear_range, reference=None, lazy=False): """ Initialize a RandomShear3D object Arguments --------- shear_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. shear_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(shear_range, (list, tuple))) or (len(shear_range) != 2): raise ValueError("shear_range argument must be list/tuple with two values!") self.shear_range = shear_range self.reference = reference self.lazy = lazy def transform(self, X=None, y=None): """ Transform an image using an Affine transform with shear parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomShear3D(shear_range=(-10,10)) >>> img2 = tx.transform(img) """ # random draw in shear range shear_x = random.gauss(self.shear_range[0], self.shear_range[1]) shear_y = random.gauss(self.shear_range[0], self.shear_range[1]) shear_z = random.gauss(self.shear_range[0], self.shear_range[1]) self.params = (shear_x, shear_y, shear_z) tx = Shear3D( (shear_x, shear_y, shear_z), reference=self.reference, lazy=self.lazy ) return tx.transform(X, y)
class RandomShear3D(object): ''' Apply a Shear3D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. ''' def __init__(self, shear_range, reference=None, lazy=False): ''' Initialize a RandomShear3D object Arguments --------- shear_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. shear_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with shear parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomShear3D(shear_range=(-10,10)) >>> img2 = tx.transform(img) ''' pass
3
3
31
5
8
19
2
2.69
1
4
1
0
2
4
2
2
71
12
16
11
13
43
14
11
11
2
1
1
3
1,746
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
ants.contrib.sampling.affine3d.RandomRotate3D
class RandomRotate3D(object): """ Apply a Rotate3D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. """ def __init__(self, rotation_range, reference=None, lazy=False): """ Initialize a RandomRotate3D object Arguments --------- rotation_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. rotation_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(rotation_range, (list, tuple))) or ( len(rotation_range) != 2 ): raise ValueError( "rotation_range argument must be list/tuple with two values!" ) self.rotation_range = rotation_range self.reference = reference self.lazy = lazy def transform(self, X=None, y=None): """ Transform an image using an Affine transform with rotation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomRotate3D(rotation_range=(-10,10)) >>> img2 = tx.transform(img) """ # random draw in rotation range rotation_x = random.gauss(self.rotation_range[0], self.rotation_range[1]) rotation_y = random.gauss(self.rotation_range[0], self.rotation_range[1]) rotation_z = random.gauss(self.rotation_range[0], self.rotation_range[1]) self.params = (rotation_x, rotation_y, rotation_z) tx = Rotate3D( (rotation_x, rotation_y, rotation_z), reference=self.reference, lazy=self.lazy, ) return tx.transform(X, y)
class RandomRotate3D(object): ''' Apply a Rotate3D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. ''' def __init__(self, rotation_range, reference=None, lazy=False): ''' Initialize a RandomRotate3D object Arguments --------- rotation_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. rotation_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with rotation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomRotate3D(rotation_range=(-10,10)) >>> img2 = tx.transform(img) ''' pass
3
3
34
5
11
19
2
1.95
1
4
1
0
2
4
2
2
77
12
22
11
19
43
14
11
11
2
1
1
3
1,747
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
ants.contrib.sampling.affine3d.Affine3D
class Affine3D(object): """ Create a specified ANTs Affine Transform """ def __init__(self, transformation, reference=None, lazy=False): """ Initialize a Affine object Arguments --------- transformation : array affine transformation array (3x4) reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(transformation, np.ndarray) or transformation.shape != (3,4)): raise ValueError( "transformation argument must be 3x4 Numpy array!" ) self.transformation = transformation self.lazy = lazy self.reference = reference self.tx = tio.ANTsTransform( precision="float", dimension=3, transform_type="AffineTransform" ) if self.reference is not None: self.tx.set_fixed_parameters(self.reference.get_center_of_mass()) def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.Affine3D(transformation=np.array([[1, 0, 0, dx], [0, 1, 0, dy],[0, 0, 1, dz]]) >>> img2_x = tx.transform(img)# image translated by (dx, dy, dz) """ # unpack transformation_matrix = self.transformation self.tx.set_parameters(transformation_matrix) if self.lazy or X is None: return self.tx else: if y is None: return self.tx.apply_to_image(X, reference=self.reference) else: return ( self.tx.apply_to_image(X, reference=self.reference), self.tx.apply_to_image(y, reference=self.reference), )
class Affine3D(object): ''' Create a specified ANTs Affine Transform ''' def __init__(self, transformation, reference=None, lazy=False): ''' Initialize a Affine object Arguments --------- transformation : array affine transformation array (3x4) reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.Affine3D(transformation=np.array([[1, 0, 0, dx], [0, 1, 0, dy],[0, 0, 1, dz]]) >>> img2_x = tx.transform(img)# image translated by (dx, dy, dz) ''' pass
3
3
36
6
13
17
3
1.37
1
2
1
0
2
4
2
2
78
14
27
8
24
37
18
8
15
3
1
2
6
1,748
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
ants.contrib.sampling.affine2d.Zoom2D
class Zoom2D(object): """ Create an ANTs Affine Transform with a specified level of zoom. Any value greater than 1 implies a "zoom-out" and anything less than 1 implies a "zoom-in". """ def __init__(self, zoom, reference=None, lazy=False): """ Initialize a Zoom2D object Arguments --------- zoom_range : list or tuple Lower and Upper bounds on zoom parameter. e.g. zoom_range = (0.7,0.9) will result in a random draw of the zoom parameters between 0.7 and 0.9 reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(zoom, (list, tuple))) or (len(zoom) != 2): raise ValueError("zoom_range argument must be list/tuple with two values!") self.zoom = zoom self.lazy = lazy self.reference = reference self.tx = tio.ANTsTransform( precision="float", dimension=2, transform_type="AffineTransform" ) if self.reference is not None: self.tx.set_fixed_parameters(self.reference.get_center_of_mass()) def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given zoom parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Zoom2D(zoom=(0.8,0.8,0.8)) >>> img2 = tx.transform(img) """ # unpack zoom range zoom_x, zoom_y = self.zoom self.params = (zoom_x, zoom_y) zoom_matrix = np.array([[zoom_x, 0, 0], [0, zoom_y, 0]]) self.tx.set_parameters(zoom_matrix) if self.lazy or X is None: return self.tx else: if y is None: return self.tx.apply_to_image(X, reference=self.reference) else: return ( self.tx.apply_to_image(X, reference=self.reference), self.tx.apply_to_image(y, reference=self.reference), )
class Zoom2D(object): ''' Create an ANTs Affine Transform with a specified level of zoom. Any value greater than 1 implies a "zoom-out" and anything less than 1 implies a "zoom-in". ''' def __init__(self, zoom, reference=None, lazy=False): ''' Initialize a Zoom2D object Arguments --------- zoom_range : list or tuple Lower and Upper bounds on zoom parameter. e.g. zoom_range = (0.7,0.9) will result in a random draw of the zoom parameters between 0.7 and 0.9 reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with the given zoom parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Zoom2D(zoom=(0.8,0.8,0.8)) >>> img2 = tx.transform(img) ''' pass
3
3
36
5
13
18
3
1.52
1
4
1
0
2
5
2
2
80
12
27
10
24
41
20
10
17
3
1
2
6
1,749
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
ants.contrib.sampling.affine2d.Translate2D
class Translate2D(object): """ Create an ANTs Affine Transform with a specified translation. """ def __init__(self, translation, reference=None, lazy=False): """ Initialize a Translate2D object Arguments --------- translation : list or tuple translation values for each axis, in degrees. Negative values can be used for translation in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(translation, (list, tuple))) or (len(translation) != 2): raise ValueError("translation argument must be list/tuple with two values!") self.translation = translation self.lazy = lazy self.reference = reference self.tx = tio.ANTsTransform( precision="float", dimension=2, transform_type="AffineTransform" ) if self.reference is not None: self.tx.set_fixed_parameters(self.reference.get_center_of_mass()) def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Translate2D(translation=(10,0)) >>> img2_x = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(-10,0)) # other direction >>> img2_x = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(0,10)) >>> img2_z = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(10,10)) >>> img2 = tx.transform(img) """ # convert to radians and unpack translation_x, translation_y = self.translation translation_matrix = np.array([[1, 0, translation_x], [0, 1, translation_y]]) self.tx.set_parameters(translation_matrix) if self.lazy or X is None: return self.tx else: if y is None: return self.tx.apply_to_image(X, reference=self.reference) else: return ( self.tx.apply_to_image(X, reference=self.reference), self.tx.apply_to_image(y, reference=self.reference), )
class Translate2D(object): ''' Create an ANTs Affine Transform with a specified translation. ''' def __init__(self, translation, reference=None, lazy=False): ''' Initialize a Translate2D object Arguments --------- translation : list or tuple translation values for each axis, in degrees. Negative values can be used for translation in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Translate2D(translation=(10,0)) >>> img2_x = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(-10,0)) # other direction >>> img2_x = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(0,10)) >>> img2_z = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(10,10)) >>> img2 = tx.transform(img) ''' pass
3
3
39
5
13
21
3
1.73
1
4
1
0
2
4
2
2
83
12
26
9
23
45
19
9
16
3
1
2
6
1,750
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
ants.contrib.sampling.affine2d.Shear2D
class Shear2D(object): """ Create an ANTs Affine Transform with a specified shear. """ def __init__(self, shear, reference=None, lazy=False): """ Initialize a Shear2D object Arguments --------- shear : list or tuple shear values for each axis, in degrees. Negative values can be used for shear in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(shear, (list, tuple))) or (len(shear) != 2): raise ValueError("shear argument must be list/tuple with two values!") self.shear = shear self.lazy = lazy self.reference = reference self.tx = tio.ANTsTransform( precision="float", dimension=2, transform_type="AffineTransform" ) if self.reference is not None: self.tx.set_fixed_parameters(self.reference.get_center_of_mass()) def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given shear parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Shear2D(shear=(10,0,0)) >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear2D(shear=(-10,0,0)) # other direction >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear2D(shear=(0,10,0)) >>> img2_y = tx.transform(img) # y axis stays same >>> tx = ants.contrib.Shear2D(shear=(0,0,10)) >>> img2_z = tx.transform(img) # z axis stays same >>> tx = ants.contrib.Shear2D(shear=(10,10,10)) >>> img2 = tx.transform(img) """ # convert to radians and unpack shear = [math.pi / 180 * s for s in self.shear] shear_x, shear_y = shear shear_matrix = np.array([[1, shear_x, 0], [shear_y, 1, 0]]) self.tx.set_parameters(shear_matrix) if self.lazy or X is None: return self.tx else: if y is None: return self.tx.apply_to_image(X, reference=self.reference) else: return ( self.tx.apply_to_image(X, reference=self.reference), self.tx.apply_to_image(y, reference=self.reference), )
class Shear2D(object): ''' Create an ANTs Affine Transform with a specified shear. ''' def __init__(self, shear, reference=None, lazy=False): ''' Initialize a Shear2D object Arguments --------- shear : list or tuple shear values for each axis, in degrees. Negative values can be used for shear in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with the given shear parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Shear2D(shear=(10,0,0)) >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear2D(shear=(-10,0,0)) # other direction >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear2D(shear=(0,10,0)) >>> img2_y = tx.transform(img) # y axis stays same >>> tx = ants.contrib.Shear2D(shear=(0,0,10)) >>> img2_z = tx.transform(img) # z axis stays same >>> tx = ants.contrib.Shear2D(shear=(10,10,10)) >>> img2 = tx.transform(img) ''' pass
3
3
40
5
13
22
3
1.74
1
4
1
0
2
4
2
2
86
12
27
10
24
47
20
10
17
3
1
2
6
1,751
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
ants.contrib.sampling.affine2d.Rotate2D
class Rotate2D(object): """ Create an ANTs Affine Transform with a specified level of rotation. """ def __init__(self, rotation, reference=None, lazy=False): """ Initialize a Rotate2D object Arguments --------- rotation : scalar rotation value in degrees. Negative values can be used for rotation in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ self.rotation = rotation self.lazy = lazy self.reference = reference self.tx = tio.ANTsTransform( precision="float", dimension=2, transform_type="AffineTransform" ) if self.reference is not None: self.tx.set_fixed_parameters(self.reference.get_center_of_mass()) def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given rotation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Rotate2D(rotation=(10,-5,12)) >>> img2 = tx.transform(img) """ # unpack zoom range rotation = self.rotation # Rotation about X axis theta = math.pi / 180 * rotation rotation_matrix = np.array( [[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0]] ) self.tx.set_parameters(rotation_matrix) if self.lazy or X is None: return self.tx else: if y is None: return self.tx.apply_to_image(X, reference=self.reference) else: return ( self.tx.apply_to_image(X, reference=self.reference), self.tx.apply_to_image(y, reference=self.reference), )
class Rotate2D(object): ''' Create an ANTs Affine Transform with a specified level of rotation. ''' def __init__(self, rotation, reference=None, lazy=False): ''' Initialize a Rotate2D object Arguments --------- rotation : scalar rotation value in degrees. Negative values can be used for rotation in the other direction reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with the given rotation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Rotate2D(rotation=(10,-5,12)) >>> img2 = tx.transform(img) ''' pass
3
3
37
5
13
19
3
1.52
1
1
1
0
2
4
2
2
80
12
27
10
24
41
18
10
15
3
1
2
5
1,752
ANTsX/ANTsPy
tests/test_bugs.py
test_bugs.Test_bugs
class Test_bugs(unittest.TestCase): """ Test ants.ANTsImage class """ def setUp(self): pass def tearDown(self): pass def test_resample_returns_NaNs(self): """ Test that resampling an image doesnt cause the resampled image to have NaNs - previously caused by resampling an image of type DOUBLE """ img2d = ants.image_read(ants.get_ants_data('r16')) img2dr = ants.resample_image(img2d, (2,2), 0, 0) self.assertTrue(np.sum(np.isnan(img2dr.numpy())) == 0) img3d = ants.image_read(ants.get_ants_data('mni')) img3dr = ants.resample_image(img3d, (2,2,2), 0, 0) self.assertTrue(np.sum(np.isnan(img3dr.numpy())) == 0) def test_compose_multi_type_transforms(self): image = ants.image_read(ants.get_ants_data("r16")) linear_transform = ants.create_ants_transform(transform_type= "AffineTransform", precision='float', dimension=image.dimension) displacement_field = ants.simulate_displacement_field(image, field_type="bspline", number_of_random_points=1000, sd_noise=10.0, enforce_stationary_boundary=True, number_of_fitting_levels=4, mesh_size=1, sd_smoothing=4.0) displacement_field_xfrm = ants.transform_from_displacement_field(displacement_field) xfrm = ants.compose_ants_transforms([linear_transform, displacement_field_xfrm]) xfrm = ants.compose_ants_transforms([linear_transform, linear_transform]) xfrm = ants.compose_ants_transforms([displacement_field_xfrm, linear_transform]) def test_bspline_image_with_2d_weights(self): # see https://github.com/ANTsX/ANTsPy/issues/655 import ants import numpy as np output_size = (256, 256) bspline_epsilon = 1e-4 number_of_fitting_levels = 4 image = ants.image_read(ants.get_ants_data("r16")) image = ants.resample_image(image, (100, 100), use_voxels=True) indices = np.meshgrid(list(range(image.shape[0])), list(range(image.shape[1]))) indices_array = np.stack((indices[1].flatten(), indices[0].flatten()), axis=0) image_parametric_values = indices_array.transpose() weight_array = np.ones(image.shape) parametric_values = image_parametric_values scattered_data = np.atleast_2d(image.numpy().flatten()).transpose() weight_values = np.atleast_2d(weight_array.flatten()).transpose() min_parametric_values = np.min(parametric_values, axis=0) max_parametric_values = np.max(parametric_values, axis=0) spacing = np.zeros((2,)) for d in range(2): spacing[d] = (max_parametric_values[d] - min_parametric_values[d]) / (output_size[d] - 1) + bspline_epsilon bspline_image = ants.fit_bspline_object_to_scattered_data(scattered_data, parametric_values, parametric_domain_origin=min_parametric_values - bspline_epsilon, parametric_domain_spacing=spacing, parametric_domain_size=output_size, data_weights=weight_values, number_of_fitting_levels=number_of_fitting_levels, mesh_size=1) def test_scalar_rgb_missing(self): import ants img = ants.image_read(ants.get_data('r16')) with self.assertRaises(Exception): img_color = ants.scalar_to_rgb(img, cmap='jet') def test_bspline_zeros(self): import ants import numpy as np x = np.linspace(-4, 4, num=100) + np.random.uniform(-0.1, 0.1, 100) u = np.linspace(0, 1.0, num=len(x)) scattered_data = np.expand_dims(u, axis=-1) parametric_data = np.expand_dims(u, axis=-1) spacing = 1/(len(x)-1) * 1.0 bspline_curve = ants.fit_bspline_object_to_scattered_data( scattered_data, parametric_data, parametric_domain_origin=[0.0], parametric_domain_spacing=[spacing], parametric_domain_size=[len(x)], is_parametric_dimension_closed=None, number_of_fitting_levels=5, mesh_size=1) # Erroneously returns all zeros. self.assertNotEqual(bspline_curve.sum(), 0) def test_from_numpy_different_dtypes(self): all_dtypes = ('bool', 'int8', 'int16', 'int32', 'int64', 'uint16', 'uint64', 'float16') arr = np.random.randn(100,100) for dtype in all_dtypes: arr2 = arr.astype(dtype) img = ants.from_numpy(arr2) self.assertTrue(ants.is_image(img))
class Test_bugs(unittest.TestCase): ''' Test ants.ANTsImage class ''' def setUp(self): pass def tearDown(self): pass def test_resample_returns_NaNs(self): ''' Test that resampling an image doesnt cause the resampled image to have NaNs - previously caused by resampling an image of type DOUBLE ''' pass def test_compose_multi_type_transforms(self): pass def test_bspline_image_with_2d_weights(self): pass def test_scalar_rgb_missing(self): pass def test_bspline_zeros(self): pass def test_from_numpy_different_dtypes(self): pass
9
2
14
2
11
1
1
0.11
1
3
0
0
8
0
8
80
121
24
87
52
73
10
63
52
49
2
2
1
10
1,753
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
ants.contrib.sampling.affine3d.Zoom3D
class Zoom3D(object): """ Create an ANTs Affine Transform with a specified level of zoom. Any value greater than 1 implies a "zoom-out" and anything less than 1 implies a "zoom-in". """ def __init__(self, zoom, reference=None, lazy=False): """ Initialize a Zoom3D object Arguments --------- zoom_range : list or tuple Lower and Upper bounds on zoom parameter. e.g. zoom_range = (0.7,0.9) will result in a random draw of the zoom parameters between 0.7 and 0.9 reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(zoom, (list, tuple))) or (len(zoom) != 3): raise ValueError( "zoom_range argument must be list/tuple with three values!" ) self.zoom = zoom self.lazy = lazy self.reference = reference self.tx = tio.ANTsTransform( precision="float", dimension=3, transform_type="AffineTransform" ) if self.reference is not None: self.tx.set_fixed_parameters(self.reference.get_center_of_mass()) def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given zoom parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.Zoom3D(zoom=(0.8,0.8,0.8)) >>> img2 = tx.transform(img) """ # unpack zoom range zoom_x, zoom_y, zoom_z = self.zoom self.params = (zoom_x, zoom_y, zoom_z) zoom_matrix = np.array( [[zoom_x, 0, 0, 0], [0, zoom_y, 0, 0], [0, 0, zoom_z, 0]] ) self.tx.set_parameters(zoom_matrix) if self.lazy or X is None: return self.tx else: if y is None: return self.tx.apply_to_image(X, reference=self.reference) else: return ( self.tx.apply_to_image(X, reference=self.reference), self.tx.apply_to_image(y, reference=self.reference), )
class Zoom3D(object): ''' Create an ANTs Affine Transform with a specified level of zoom. Any value greater than 1 implies a "zoom-out" and anything less than 1 implies a "zoom-in". ''' def __init__(self, zoom, reference=None, lazy=False): ''' Initialize a Zoom3D object Arguments --------- zoom_range : list or tuple Lower and Upper bounds on zoom parameter. e.g. zoom_range = (0.7,0.9) will result in a random draw of the zoom parameters between 0.7 and 0.9 reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with the given zoom parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.Zoom3D(zoom=(0.8,0.8,0.8)) >>> img2 = tx.transform(img) ''' pass
3
3
38
5
15
18
3
1.32
1
4
1
0
2
5
2
2
84
12
31
10
28
41
20
10
17
3
1
2
6
1,754
ANTsX/ANTsPy
tests/test_segmentation.py
test_segmentation.TestModule_atropos
class TestModule_atropos(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): # test ANTsPy/ANTsR example img = ants.image_read(ants.get_ants_data('r16')) img = ants.resample_image(img, (64,64), 1, 0) mask = ants.get_mask(img) ants.atropos( a = img, m = '[0.2,1x1]', c = '[2,0]', i = 'kmeans[3]', x = mask ) def test_multiple_inputs(self): img = ants.image_read( ants.get_ants_data("r16")) img = ants.resample_image( img, (64,64), 1, 0 ) mask = ants.get_mask(img) segs1 = ants.atropos( a = img, m = '[0.2,1x1]', c = '[2,0]', i = 'kmeans[3]', x = mask ) # Use probabilities from k-means seg as priors segs2 = ants.atropos( a = img, m = '[0.2,1x1]', c = '[2,0]', i = segs1['probabilityimages'], x = mask ) # multiple inputs feats = [img, ants.iMath(img,"Laplacian"), ants.iMath(img,"Grad") ] segs3 = ants.atropos( a = feats, m = '[0.2,1x1]', c = '[2,0]', i = segs1['probabilityimages'], x = mask )
class TestModule_atropos(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass def test_multiple_inputs(self): pass
5
0
6
1
5
1
1
0.14
1
0
0
0
4
0
4
76
30
6
21
13
16
3
18
13
13
1
2
0
4
1,755
ANTsX/ANTsPy
ants/core/ants_transform.py
ants.core.ants_transform.ANTsTransform
class ANTsTransform(object): def __init__(self, precision='float', dimension=3, transform_type='AffineTransform', pointer=None): """ NOTE: This class should never be initialized directly by the user. Initialize an ANTsTransform object. Arguments --------- pixeltype : string dimension : integer transform_type : stirng pointer : py::capsule (optional) """ self.precision = precision self.dimension = dimension self.transform_type = transform_type self.type = transform_type if pointer is None: libfn = get_lib_fn('newAntsTransform%s%i' % (short_ptype(precision), dimension)) pointer = libfn(precision, dimension, transform_type) self.pointer = pointer # suffix to append to all c++ library function calls self._libsuffix = '%s%i' % (short_ptype(self.precision), self.dimension) @property def parameters(self): """ Get parameters of transform """ libfn = get_lib_fn('getTransformParameters') return np.asarray(libfn(self.pointer), order='F')#.reshape((self.dimension, self.dimension+1), order='F') def set_parameters(self, parameters): """ Set parameters of transform """ if not isinstance(parameters, np.ndarray): parameters = np.asarray(parameters) # if in two dimensions, flatten with fortran ordering if parameters.ndim > 1: parameters = parameters.flatten(order='F') libfn = get_lib_fn('setTransformParameters') libfn(self.pointer, parameters.tolist()) @property def fixed_parameters(self): """ Get parameters of transform """ libfn = get_lib_fn('getTransformFixedParameters') return np.asarray(libfn(self.pointer)) def set_fixed_parameters(self, parameters): """ Set parameters of transform """ if not isinstance(parameters, np.ndarray): parameters = np.asarray(parameters) libfn = get_lib_fn('setTransformFixedParameters') libfn(self.pointer, parameters.tolist()) def invert(self): """ Invert the transform """ libfn = get_lib_fn('inverseTransform') inv_tx_ptr = libfn(self.pointer) new_tx = ANTsTransform(precision=self.precision, dimension=self.dimension, transform_type=self.transform_type, pointer=inv_tx_ptr) return new_tx def apply(self, data, data_type='point', reference=None, **kwargs): """ Apply transform to data """ if data_type == 'point': return self.apply_to_point(data) elif data_type == 'vector': return self.apply_to_vector(data) elif data_type == 'image': return self.apply_to_image(data, reference, **kwargs) def apply_to_point(self, point): """ Apply transform to a point Arguments --------- point : list/tuple point to which the transform will be applied Returns ------- list : transformed point Example ------- >>> import ants >>> tx = ants.new_ants_transform() >>> params = tx.parameters >>> tx.set_parameters(params*2) >>> pt2 = tx.apply_to_point((1,2,3)) # should be (2,4,6) """ libfn = get_lib_fn('transformPoint') return tuple(libfn(self.pointer, point)) def apply_to_vector(self, vector): """ Apply transform to a vector Arguments --------- vector : list/tuple vector to which the transform will be applied Returns ------- list : transformed vector """ if isinstance(vector, np.ndarray): vector = vector.tolist() libfn = get_lib_fn('transformVector') return np.asarray(libfn(self.pointer, vector)) def apply_to_image(self, image, reference=None, interpolation='linear'): """ Apply transform to an image Arguments --------- image : ANTsImage image to which the transform will be applied reference : ANTsImage target space for transforming image interpolation : string type of interpolation to use. Options are: linear nearestneighbor multilabel gaussian bspline cosinewindowedsinc welchwindowedsinc hammingwindoweddinc lanczoswindowedsinc genericlabel Returns ------- list : transformed vector """ if reference is None: reference = image.clone() interpolation = interpolation.lower() tform_fn = get_lib_fn('transformImage') reference = reference.clone(image.pixeltype) img_ptr = tform_fn(self.pointer, image.pointer, reference.pointer, interpolation) return ants.from_pointer(img_ptr) def __repr__(self): s = "ANTsTransform\n" +\ '\t {:<10} : {}\n'.format('Type', self.type)+\ '\t {:<10} : {}\n'.format('Dimension', self.dimension)+\ '\t {:<10} : {}\n'.format('Precision', self.precision) return s
class ANTsTransform(object): def __init__(self, precision='float', dimension=3, transform_type='AffineTransform', pointer=None): ''' NOTE: This class should never be initialized directly by the user. Initialize an ANTsTransform object. Arguments --------- pixeltype : string dimension : integer transform_type : stirng pointer : py::capsule (optional) ''' pass @property def parameters(self): ''' Get parameters of transform ''' pass def set_parameters(self, parameters): ''' Set parameters of transform ''' pass @property def fixed_parameters(self): ''' Get parameters of transform ''' pass def set_fixed_parameters(self, parameters): ''' Set parameters of transform ''' pass def invert(self): ''' Invert the transform ''' pass def apply(self, data, data_type='point', reference=None, **kwargs): ''' Apply transform to data ''' pass def apply_to_point(self, point): ''' Apply transform to a point Arguments --------- point : list/tuple point to which the transform will be applied Returns ------- list : transformed point Example ------- >>> import ants >>> tx = ants.new_ants_transform() >>> params = tx.parameters >>> tx.set_parameters(params*2) >>> pt2 = tx.apply_to_point((1,2,3)) # should be (2,4,6) ''' pass def apply_to_vector(self, vector): ''' Apply transform to a vector Arguments --------- vector : list/tuple vector to which the transform will be applied Returns ------- list : transformed vector ''' pass def apply_to_image(self, image, reference=None, interpolation='linear'): ''' Apply transform to an image Arguments --------- image : ANTsImage image to which the transform will be applied reference : ANTsImage target space for transforming image interpolation : string type of interpolation to use. Options are: linear nearestneighbor multilabel gaussian bspline cosinewindowedsinc welchwindowedsinc hammingwindoweddinc lanczoswindowedsinc genericlabel Returns ------- list : transformed vector ''' pass def __repr__(self): pass
14
10
15
3
6
7
2
1.09
1
1
0
0
11
6
11
11
176
39
66
33
52
72
58
31
46
4
1
1
20
1,756
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_resample_image
class TestModule_resample_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_resample_image_example(self): fi = ants.image_read(ants.get_ants_data("r16")) finn = ants.resample_image(fi, (50, 60), True, 0) filin = ants.resample_image(fi, (1.5, 1.5), False, 1) def test_resample_channels(self): img = ants.image_read( ants.get_ants_data("r16")) img = ants.merge_channels([img, img]) outimg = ants.resample_image(img, (128,128), True) self.assertEqual(outimg.shape, (128, 128)) self.assertEqual(outimg.components, 2) def test_resample_image_to_target_example(self): fi = ants.image_read(ants.get_ants_data("r16")) fi2mm = ants.resample_image(fi, (2, 2), use_voxels=0, interp_type=1) resampled = ants.resample_image_to_target(fi2mm, fi, verbose=True) self.assertTrue(ants.image_physical_space_consistency(fi, resampled, 0.0001, datatype=True))
class TestModule_resample_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_resample_image_example(self): pass def test_resample_channels(self): pass def test_resample_image_to_target_example(self): pass
6
0
4
0
4
0
1
0
1
0
0
0
5
0
5
77
24
4
20
14
14
0
20
14
14
1
2
0
5
1,757
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
ants.contrib.sampling.affine2d.RandomTranslate2D
class RandomTranslate2D(object): """ Apply a Translate2D transform to an image, but with the parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. """ def __init__(self, translation_range, reference=None, lazy=False): """ Initialize a RandomTranslate2D object Arguments --------- translation_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. translation_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(translation_range, (list, tuple))) or ( len(translation_range) != 2 ): raise ValueError("shear_range argument must be list/tuple with two values!") self.translation_range = translation_range self.reference = reference self.lazy = lazy def transform(self, X=None, y=None): """ Transform an image using an Affine transform with translation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomShear2D(translation_range=(-10,10)) >>> img2 = tx.transform(img) """ # random draw in translation range translation_x = random.gauss( self.translation_range[0], self.translation_range[1] ) translation_y = random.gauss( self.translation_range[0], self.translation_range[1] ) self.params = (translation_x, translation_y) tx = Translate2D( (translation_x, translation_y), reference=self.reference, lazy=self.lazy ) return tx.transform(X, y)
class RandomTranslate2D(object): ''' Apply a Translate2D transform to an image, but with the parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. ''' def __init__(self, translation_range, reference=None, lazy=False): ''' Initialize a RandomTranslate2D object Arguments --------- translation_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. translation_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with translation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomShear2D(translation_range=(-10,10)) >>> img2 = tx.transform(img) ''' pass
3
3
34
5
10
19
2
2.05
1
4
1
0
2
4
2
2
76
12
21
10
18
43
13
10
10
2
1
1
3
1,758
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
ants.contrib.sampling.affine2d.RandomZoom2D
class RandomZoom2D(object): """ Apply a Zoom2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. """ def __init__(self, zoom_range, reference=None, lazy=False): """ Initialize a RandomZoom2D object Arguments --------- zoom_range : list or tuple Lower and Upper bounds on zoom parameter. e.g. zoom_range = (0.7,0.9) will result in a random draw of the zoom parameters between 0.7 and 0.9 reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(zoom_range, (list, tuple))) or (len(zoom_range) != 2): raise ValueError("zoom_range argument must be list/tuple with two values!") self.zoom_range = zoom_range self.reference = reference self.lazy = lazy def transform(self, X=None, y=None): """ Transform an image using an Affine transform with zoom parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomZoom2D(zoom_range=(0.8,0.9)) >>> img2 = tx.transform(img) """ # random draw in zoom range zoom_x = np.exp( random.gauss(np.log(self.zoom_range[0]), np.log(self.zoom_range[1])) ) zoom_y = np.exp( random.gauss(np.log(self.zoom_range[0]), np.log(self.zoom_range[1])) ) self.params = (zoom_x, zoom_y) tx = Zoom2D((zoom_x, zoom_y), reference=self.reference, lazy=self.lazy) return tx.transform(X, y)
class RandomZoom2D(object): ''' Apply a Zoom2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. ''' def __init__(self, zoom_range, reference=None, lazy=False): ''' Initialize a RandomZoom2D object Arguments --------- zoom_range : list or tuple Lower and Upper bounds on zoom parameter. e.g. zoom_range = (0.7,0.9) will result in a random draw of the zoom parameters between 0.7 and 0.9 reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with zoom parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomZoom2D(zoom_range=(0.8,0.9)) >>> img2 = tx.transform(img) ''' pass
3
3
32
5
8
19
2
2.53
1
4
1
0
2
4
2
2
72
12
17
10
14
43
13
10
10
2
1
1
3
1,759
ANTsX/ANTsPy
tests/test_core_ants_transform.py
test_core_ants_transform.TestClass_ANTsTransform
class TestClass_ANTsTransform(unittest.TestCase): """ Test ants.ANTsImage class """ def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) img3d = ants.image_read(ants.get_ants_data('mni')) tx2d = ants.create_ants_transform(precision='float', dimension=2) tx3d = ants.create_ants_transform(precision='float', dimension=3) self.imgs = [img2d, img3d] self.txs = [tx2d, tx3d] self.pixeltypes = ['unsigned char', 'unsigned int', 'float'] def tearDown(self): pass def test__repr__(self): for tx in self.txs: r = tx.__repr__() def test_get_precision(self): for tx in self.txs: precision = tx.precision self.assertEqual(precision, 'float') def test_get_dimension(self): tx2d = ants.create_ants_transform(precision='float', dimension=2) self.assertEqual(tx2d.dimension, 2) tx3d = ants.create_ants_transform(precision='float', dimension=3) self.assertEqual(tx3d.dimension, 3) def test_get_type(self): for tx in self.txs: ttype = tx.type self.assertEqual(ttype, 'AffineTransform') def test_get_pointer(self): for tx in self.txs: ptr = tx.pointer def test_get_parameters(self): for tx in self.txs: params = tx.parameters def test_get_fixed_parameters(self): for tx in self.txs: fixed_params = tx.fixed_parameters def test_invert(self): for tx in self.txs: txinvert = tx.invert() def test_apply(self): tx = ants.new_ants_transform() params = tx.parameters tx.set_parameters(params*2) pt2 = tx.apply(data=(1,2,3), data_type='point') tx = ants.new_ants_transform() params = tx.parameters tx.set_parameters(params*2) pt2 = tx.apply(data=(1,2,3), data_type='vector') img = ants.image_read(ants.get_ants_data("r16")).clone('float') tx = ants.new_ants_transform(dimension=2) tx.set_parameters((0.9,0,0,1.1,10,11)) img2 = tx.apply(data=img, reference=img, data_type='image') def test_apply_to_point(self): tx = ants.new_ants_transform() params = tx.parameters tx.set_parameters(params*2) pt2 = tx.apply_to_point((1,2,3)) # should be (2,4,6) def test_apply_to_vector(self): tx = ants.new_ants_transform() params = tx.parameters tx.set_parameters(params*2) pt2 = tx.apply_to_vector((1,2,3)) # should be (2,4,6) def test_apply_to_image(self): for ptype in self.pixeltypes: img = ants.image_read(ants.get_ants_data("r16")).clone(ptype) tx = ants.new_ants_transform(dimension=2) tx.set_parameters((0.9,0,0,1.1,10,11)) img2 = tx.apply_to_image(img, img)
class TestClass_ANTsTransform(unittest.TestCase): ''' Test ants.ANTsImage class ''' def setUp(self): pass def tearDown(self): pass def test__repr__(self): pass def test_get_precision(self): pass def test_get_dimension(self): pass def test_get_type(self): pass def test_get_pointer(self): pass def test_get_parameters(self): pass def test_get_fixed_parameters(self): pass def test_invert(self): pass def test_apply(self): pass def test_apply_to_point(self): pass def test_apply_to_vector(self): pass def test_apply_to_image(self): pass
15
1
5
0
5
0
2
0.07
1
0
0
0
14
3
14
86
88
17
68
53
53
5
68
53
53
2
2
1
22
1,760
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_symmetrize_image
class TestModule_symmetrize_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): image = ants.image_read(ants.get_ants_data("r16")) simage = ants.symmetrize_image(image)
class TestModule_symmetrize_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
2
0
2
0
1
0
1
0
0
0
3
0
3
75
10
2
8
6
4
0
8
6
4
1
2
0
3
1,761
ANTsX/ANTsPy
tests/test_core_ants_metric.py
test_core_ants_metric.TestClass_ANTsImageToImageMetric
class TestClass_ANTsImageToImageMetric(unittest.TestCase): """ Test ants.ANTsImage class """ def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) img3d = ants.image_read(ants.get_ants_data('mni')) metric2d = ants.new_ants_metric(precision='float', dimension=2) metric3d = ants.new_ants_metric(precision='float', dimension=3) self.imgs = [img2d, img3d] self.metrics = [metric2d, metric3d] def tearDown(self): pass def test__repr__(self): for metric in self.metrics: r = metric.__repr__() def test_precision(self): for metric in self.metrics: precison = metric.precision def dimension(self): for metric in self.metrics: dimension = metric.dimension def metrictype(self): for metric in self.metrics: mtype = metric.metrictype def is_vector(self): for metric in self.metrics: isvec = metric.is_vector def pointer(self): for metric in self.metrics: ptr = metric.pointer def test_set_fixed_image(self): # def set_fixed_image(self, image): for img, metric in zip(self.imgs,self.metrics): metric.set_fixed_image(img) def test_set_fixed_mask(self): # def set_fixed_image(self, image): for img, metric in zip(self.imgs,self.metrics): mask = img > img.mean() metric.set_fixed_mask(img) def test_set_moving_image(self): # def set_fixed_image(self, image): for img, metric in zip(self.imgs,self.metrics): metric.set_moving_image(img) def test_set_moving_mask(self): # def set_fixed_image(self, image): for img, metric in zip(self.imgs,self.metrics): mask = img > img.mean() metric.set_moving_mask(img) def test_set_sampling(self): for img, metric in zip(self.imgs,self.metrics): with self.assertRaises(Exception): # set sampling without moving+fixed images metric.set_sampling() img2 = img.clone() metric.set_fixed_image(img) metric.set_moving_image(img2) metric.set_sampling() def test_initialize(self): for img, metric in zip(self.imgs,self.metrics): with self.assertRaises(Exception): # initialize without moving+fixed images metric.initialize() img2 = img.clone() metric.set_fixed_image(img) metric.set_moving_image(img2) metric.set_sampling() metric.initialize() def test_get_value(self): for img, metric in zip(self.imgs,self.metrics): with self.assertRaises(Exception): # initialize without moving+fixed images metric.get_value() img2 = img.clone() metric.set_fixed_image(img) metric.set_moving_image(img2) metric.set_sampling() metric.get_value() def test__call__(self): for img, metric in zip(self.imgs,self.metrics): img2 = img.clone() * 1.1 imgmask = img > img.mean() imgmask2 = img2 > img2.mean() val = metric(img,img2) # val = metric(img,img2, fixed_mask=imgmask, moving_mask=imgmask2) val = metric(img,img2, sampling_percentage=0.8)
class TestClass_ANTsImageToImageMetric(unittest.TestCase): ''' Test ants.ANTsImage class ''' def setUp(self): pass def tearDown(self): pass def test__repr__(self): pass def test_precision(self): pass def dimension(self): pass def metrictype(self): pass def is_vector(self): pass def pointer(self): pass def test_set_fixed_image(self): pass def test_set_fixed_mask(self): pass def test_set_moving_image(self): pass def test_set_moving_mask(self): pass def test_set_sampling(self): pass def test_initialize(self): pass def test_get_value(self): pass def test__call__(self): pass
17
1
6
0
5
1
2
0.15
1
2
0
0
16
2
16
88
108
22
75
52
58
11
75
52
58
2
2
2
30
1,762
ANTsX/ANTsPy
tests/test_core_ants_image_io.py
test_core_ants_image_io.TestModule_ants_image_io
class TestModule_ants_image_io(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')).clone('float') img3d = ants.image_read(ants.get_ants_data('mni')).clone('float') arr2d = np.random.randn(69,70).astype('float32') arr3d = np.random.randn(69,70,71).astype('float32') vecimg2d = ants.from_numpy(np.random.randn(69,70,4), has_components=True) vecimg3d = ants.from_numpy(np.random.randn(69,70,71,2), has_components=True) self.imgs = [img2d, img3d] self.arrs = [arr2d, arr3d] self.vecimgs = [vecimg2d, vecimg3d] self.pixeltypes = ['unsigned char', 'unsigned int', 'float'] def tearDown(self): pass def test_from_numpy(self): self.setUp() # no physical space info for arr in self.arrs: img = ants.from_numpy(arr) self.assertTrue(img.dimension, arr.ndim) self.assertTrue(img.shape, arr.shape) self.assertTrue(img.dtype, arr.dtype.name) nptest.assert_allclose(img.numpy(), arr) new_origin = tuple([6.9]*arr.ndim) new_spacing = tuple([3.6]*arr.ndim) new_direction = np.eye(arr.ndim)*9.6 img2 = ants.from_numpy(arr, origin=new_origin, spacing=new_spacing, direction=new_direction) self.assertEqual(img2.origin, new_origin) self.assertEqual(img2.spacing, new_spacing) nptest.assert_allclose(img2.direction, new_direction) # test with components arr2d_components = np.random.randn(69,70,4).astype('float32') img = ants.from_numpy(arr2d_components, has_components=True) self.assertEqual(img.components, arr2d_components.shape[-1]) nptest.assert_allclose(arr2d_components, img.numpy()) def test_make_image(self): self.setUp() for arr in self.arrs: voxval = 6. img = ants.make_image(arr.shape, voxval=voxval) self.assertTrue(img.dimension, arr.ndim) self.assertTrue(img.shape, arr.shape) nptest.assert_allclose(img.mean(), voxval) new_origin = tuple([6.9]*arr.ndim) new_spacing = tuple([3.6]*arr.ndim) new_direction = np.eye(arr.ndim)*9.6 img2 = ants.make_image(arr.shape, voxval=voxval, origin=new_origin, spacing=new_spacing, direction=new_direction) self.assertTrue(img2.dimension, arr.ndim) self.assertTrue(img2.shape, arr.shape) nptest.assert_allclose(img2.mean(), voxval) self.assertEqual(img2.origin, new_origin) self.assertEqual(img2.spacing, new_spacing) nptest.assert_allclose(img2.direction, new_direction) for ptype in self.pixeltypes: img = ants.make_image(arr.shape, voxval=1., pixeltype=ptype) self.assertEqual(img.pixeltype, ptype) # test with components img = ants.make_image((69,70,4), has_components=True) self.assertEqual(img.components, 4) self.assertEqual(img.dimension, 2) nptest.assert_allclose(img.mean(), 0.) img = ants.make_image((69,70,71,4), has_components=True) self.assertEqual(img.components, 4) self.assertEqual(img.dimension, 3) nptest.assert_allclose(img.mean(), 0.) # set from image for img in self.imgs: mask = ants.image_clone( img > img.mean(), pixeltype = 'float' ) arr = img[mask] img2 = ants.make_image(mask, voxval=arr) nptest.assert_allclose(img2.numpy(), (img*mask).numpy()) self.assertTrue(ants.image_physical_space_consistency(img2,mask)) # set with arr.ndim > 1 img2 = ants.make_image(mask, voxval=np.expand_dims(arr,-1)) nptest.assert_allclose(img2.numpy(), (img*mask).numpy()) self.assertTrue(ants.image_physical_space_consistency(img2,mask)) #with self.assertRaises(Exception): # # wrong number of non-zero voxels # img3 = ants.make_image(img, voxval=arr) def test_matrix_to_images(self): # def matrix_to_images(data_matrix, mask): for img in self.imgs: imgmask = ants.image_clone( img > img.mean(), pixeltype = 'float' ) data = img[imgmask] dataflat = data.reshape(1,-1) mat = np.vstack([dataflat,dataflat]).astype('float32') imglist = ants.matrix_to_images(mat, imgmask) nptest.assert_allclose((img*imgmask).numpy(), imglist[0].numpy()) nptest.assert_allclose((img*imgmask).numpy(), imglist[1].numpy()) self.assertTrue(ants.image_physical_space_consistency(img,imglist[0])) self.assertTrue(ants.image_physical_space_consistency(img,imglist[1])) # go back to matrix mat2 = ants.images_to_matrix(imglist, imgmask) nptest.assert_allclose(mat, mat2) # test with matrix.ndim > 2 img = img.clone() img.set_direction(img.direction*2) imgmask = ants.image_clone( img > img.mean(), pixeltype = 'float' ) arr = (img*imgmask).numpy() arr = arr[arr>=0.5] arr2 = arr.copy() mat = np.stack([arr,arr2]) imglist = ants.matrix_to_images(mat, imgmask) for im in imglist: self.assertTrue(ants.allclose(im, imgmask*img)) self.assertTrue(ants.image_physical_space_consistency(im, imgmask)) # test for wrong number of voxels #with self.assertRaises(Exception): # arr = (img*imgmask).numpy() # arr = arr[arr>0.5] # arr2 = arr.copy() # mat = np.stack([arr,arr2]) # imglist = ants.matrix_to_images(mat, img) def test_images_to_matrix(self): # def images_to_matrix(image_list, mask=None, sigma=None, epsilon=0): for img in self.imgs: mask = ants.image_clone( img > img.mean(), pixeltype = 'float' ) imglist = [img.clone(),img.clone(),img.clone()] imgmat = ants.images_to_matrix(imglist, mask=mask) self.assertTrue(imgmat.shape[0] == len(imglist)) self.assertTrue(imgmat.shape[1] == (mask>0).sum()) self.assertTrue(np.allclose(img[mask], imgmat[0,:])) # go back to images imglist2 = ants.matrix_to_images(imgmat, mask) for i1,i2 in zip(imglist,imglist2): self.assertTrue(ants.image_physical_space_consistency(i1,i2)) nptest.assert_allclose(i1.numpy()*mask.numpy(),i2.numpy()) if img.dimension == 2: # with sigma mask = ants.image_clone( img > img.mean(), pixeltype = 'float' ) imglist = [img.clone(),img.clone(),img.clone()] imgmat = ants.images_to_matrix(imglist, mask=mask, sigma=2.) # with no mask imgmat = ants.images_to_matrix(imglist) # Mask not binary mask = ants.image_clone( img / img.mean(), pixeltype = 'float' ) imgmat = ants.images_to_matrix(imglist, mask=mask, epsilon=1) # with mask of different shape s = [65]*img.dimension mask2 = ants.from_numpy(np.random.randn(*s), spacing=[4.0, 4.0]) mask2 = mask2 > mask2.mean() imgmat = ants.images_to_matrix(imglist, mask=mask2) self.assertTrue(imgmat.shape[0] == len(imglist)) self.assertTrue(imgmat.shape[1] == (mask2>0).sum()) def timeseries_to_matrix(self): img = ants.make_image( (10,10,10,5 ) ) mat = ants.timeseries_to_matrix( img ) img = ants.make_image( (10,10,10,5 ) ) mask = ants.ndimage_to_list( img )[0] * 0 mask[ 4:8, 4:8, 4:8 ] = 1 mat = ants.timeseries_to_matrix( img, mask = mask ) img2 = ants.matrix_to_timeseries( img, mat, mask) def test_image_header_info(self): # def image_header_info(filename): for img in self.imgs: img.set_spacing([6.9]*img.dimension) img.set_origin([3.6]*img.dimension) tmpfile = mktemp(suffix='.nii.gz') ants.image_write(img, tmpfile) info = ants.image_header_info(tmpfile) self.assertEqual(info['dimensions'], img.shape) nptest.assert_allclose(info['direction'], img.direction) self.assertEqual(info['nComponents'], img.components) self.assertEqual(info['nDimensions'], img.dimension) self.assertEqual(info['origin'], img.origin) self.assertEqual(info['pixeltype'], img.pixeltype) self.assertEqual(info['pixelclass'], 'vector' if img.has_components else 'scalar') self.assertEqual(info['spacing'], img.spacing) try: os.remove(tmpfile) except: pass # test on vector image img = ants.from_numpy(np.random.randn(69,60,4).astype('float32'), has_components=True) tmpfile = mktemp(suffix='.nii.gz') ants.image_write(img, tmpfile) info = ants.image_header_info(tmpfile) self.assertEqual(info['dimensions'], img.shape) nptest.assert_allclose(info['direction'], img.direction) self.assertEqual(info['nComponents'], img.components) self.assertEqual(info['nDimensions'], img.dimension) self.assertEqual(info['origin'], img.origin) self.assertEqual(info['pixeltype'], img.pixeltype) self.assertEqual(info['pixelclass'], 'vector' if img.has_components else 'scalar') self.assertEqual(info['spacing'], img.spacing) img = ants.from_numpy(np.random.randn(69,60,70,2).astype('float32'), has_components=True) tmpfile = mktemp(suffix='.nii.gz') ants.image_write(img, tmpfile) info = ants.image_header_info(tmpfile) self.assertEqual(info['dimensions'], img.shape) nptest.assert_allclose(info['direction'], img.direction) self.assertEqual(info['nComponents'], img.components) self.assertEqual(info['nDimensions'], img.dimension) self.assertEqual(info['origin'], img.origin) self.assertEqual(info['pixeltype'], img.pixeltype) self.assertEqual(info['pixelclass'], 'vector' if img.has_components else 'scalar') self.assertEqual(info['spacing'], img.spacing) # non-existant file with self.assertRaises(Exception): tmpfile = mktemp(suffix='.nii.gz') ants.image_header_info(tmpfile) def test_image_clone(self): for img in self.imgs: img = ants.image_clone(img, 'unsigned char') orig_ptype = img.pixeltype for ptype in self.pixeltypes: imgcloned = ants.image_clone(img, ptype) self.assertTrue(ants.image_physical_space_consistency(img,imgcloned)) nptest.assert_allclose(img.numpy(), imgcloned.numpy()) self.assertEqual(imgcloned.pixeltype, ptype) self.assertEqual(img.pixeltype, orig_ptype) for img in self.vecimgs: img = img.clone('unsigned char') orig_ptype = img.pixeltype for ptype in self.pixeltypes: imgcloned = ants.image_clone(img, ptype) self.assertTrue(ants.image_physical_space_consistency(img,imgcloned)) self.assertEqual(imgcloned.components, img.components) nptest.assert_allclose(img.numpy(), imgcloned.numpy()) self.assertEqual(imgcloned.pixeltype, ptype) self.assertEqual(img.pixeltype, orig_ptype) def test_image_read_write(self): # def image_read(filename, dimension=None, pixeltype='float'): # def image_write(image, filename): # test scalar images for img in self.imgs: img = (img - img.min()) / (img.max() - img.min()) img = img * 255. img = img.clone('unsigned char') for ptype in self.pixeltypes: img = img.clone(ptype) tmpfile = mktemp(suffix='.nii.gz') ants.image_write(img, tmpfile) img2 = ants.image_read(tmpfile) self.assertTrue(ants.image_physical_space_consistency(img,img2)) self.assertEqual(img2.components, img.components) nptest.assert_allclose(img.numpy(), img2.numpy()) # unsupported ptype with self.assertRaises(Exception): ants.image_read(tmpfile, pixeltype='not-suppoted-ptype') # test vector images for img in self.vecimgs: img = (img - img.min()) / (img.max() - img.min()) img = img * 255. img = img.clone('unsigned char') for ptype in self.pixeltypes: img = img.clone(ptype) tmpfile = mktemp(suffix='.nii.gz') ants.image_write(img, tmpfile) img2 = ants.image_read(tmpfile) self.assertTrue(ants.image_physical_space_consistency(img,img2)) self.assertEqual(img2.components, img.components) nptest.assert_allclose(img.numpy(), img2.numpy()) # test saving/loading as npy for img in self.imgs: tmpfile = mktemp(suffix='.npy') ants.image_write(img, tmpfile) img2 = ants.image_read(tmpfile) self.assertTrue(ants.image_physical_space_consistency(img,img2)) self.assertEqual(img2.components, img.components) nptest.assert_allclose(img.numpy(), img2.numpy()) # with no json header arr = img.numpy() tmpfile = mktemp(suffix='.npy') np.save(tmpfile, arr) img2 = ants.image_read(tmpfile) nptest.assert_allclose(img.numpy(), img2.numpy()) # non-existant file with self.assertRaises(ValueError): tmpfile = mktemp(suffix='.nii.gz') ants.image_read(tmpfile) # Test empty file with self.assertRaises(RuntimeError): tmpfile = mktemp(suffix='.nii.gz') open(tmpfile, 'a').close() ants.image_read(tmpfile) def test_image_from_numpy_shape(self): arr = np.random.randn(1,9,1).astype('float32') img = ants.from_numpy(arr) self.assertEqual(img.shape, arr.shape) nptest.assert_allclose(img.numpy(), arr) arr = np.random.randn(2,3,4).astype('float32') img = ants.from_numpy(arr) self.assertEqual(img.shape, arr.shape) nptest.assert_allclose(img.numpy(), arr) # Test special case where shape is (1,N), was getting transposed arr = np.random.randn(1,9).astype('float32') img = ants.from_numpy(arr) self.assertEqual(img.shape, arr.shape) nptest.assert_allclose(img.numpy(), arr) arr = np.random.randn(9,1).astype('float32') img = ants.from_numpy(arr) self.assertEqual(img.shape, arr.shape) nptest.assert_allclose(img.numpy(), arr)
class TestModule_ants_image_io(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_from_numpy(self): pass def test_make_image(self): pass def test_matrix_to_images(self): pass def test_images_to_matrix(self): pass def timeseries_to_matrix(self): pass def test_image_header_info(self): pass def test_image_clone(self): pass def test_image_read_write(self): pass def test_image_from_numpy_shape(self): pass
12
0
29
4
23
2
3
0.14
1
5
0
0
11
4
11
83
352
58
257
74
245
37
257
74
245
6
2
2
34
1,763
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
ants.contrib.sampling.affine2d.RandomShear2D
class RandomShear2D(object): """ Apply a Shear2D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. """ def __init__(self, shear_range, reference=None, lazy=False): """ Initialize a RandomShear2D object Arguments --------- shear_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. shear_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(shear_range, (list, tuple))) or (len(shear_range) != 2): raise ValueError("shear_range argument must be list/tuple with two values!") self.shear_range = shear_range self.reference = reference self.lazy = lazy def transform(self, X=None, y=None): """ Transform an image using an Affine transform with shear parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomShear2D(shear_range=(-10,10)) >>> img2 = tx.transform(img) """ # random draw in shear range shear_x = random.gauss(self.shear_range[0], self.shear_range[1]) shear_y = random.gauss(self.shear_range[0], self.shear_range[1]) self.params = (shear_x, shear_y) tx = Shear2D((shear_x, shear_y), reference=self.reference, lazy=self.lazy) return tx.transform(X, y)
class RandomShear2D(object): ''' Apply a Shear2D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. ''' def __init__(self, shear_range, reference=None, lazy=False): ''' Initialize a RandomShear2D object Arguments --------- shear_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. shear_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with shear parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomShear2D(shear_range=(-10,10)) >>> img2 = tx.transform(img) ''' pass
3
3
30
5
6
19
2
3.31
1
4
1
0
2
4
2
2
68
12
13
10
10
43
13
10
10
2
1
1
3
1,764
ANTsX/ANTsPy
tests/test_core_ants_transform.py
test_core_ants_transform.TestModule_ants_transform
class TestModule_ants_transform(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) img3d = ants.image_read(ants.get_ants_data('mni')) tx2d = ants.create_ants_transform(precision='float', dimension=2) tx3d = ants.create_ants_transform(precision='float', dimension=3) self.imgs = [img2d, img3d] self.txs = [tx2d, tx3d] self.pixeltypes = ['unsigned char', 'unsigned int', 'float'] def tearDown(self): pass def test_get_ants_transform_parameters(self): for tx in self.txs: params = ants.get_ants_transform_parameters(tx) def test_set_ants_transform_parameters(self): for tx in self.txs: ants.set_ants_transform_parameters(tx, tx.parameters**2) def test_get_ants_transform_fixed_parameters(self): for tx in self.txs: params = ants.get_ants_transform_fixed_parameters(tx) def test_set_ants_transform_fixed_parameters(self): for tx in self.txs: ants.set_ants_transform_fixed_parameters(tx, tx.fixed_parameters**2) def test_apply_ants_transform(self): tx = ants.new_ants_transform() params = tx.parameters tx.set_parameters(params*2) pt2 = ants.apply_ants_transform(tx, data=(1,2,3), data_type='point') tx = ants.new_ants_transform() params = tx.parameters tx.set_parameters(params*2) pt2 = ants.apply_ants_transform(tx, data=(1,2,3), data_type='vector') img = ants.image_read(ants.get_ants_data("r16")).clone('float') tx = ants.new_ants_transform(dimension=2) tx.set_parameters((0.9,0,0,1.1,10,11)) img2 = ants.apply_ants_transform(tx, data=img, reference=img, data_type='image') def test_apply_ants_transform_to_point(self): tx = ants.new_ants_transform() params = tx.parameters tx.set_parameters(params*2) pt2 = ants.apply_ants_transform_to_point(tx, (1,2,3)) # should be (2,4,6) def test_apply_ants_transform_to_vector(self): tx = ants.new_ants_transform() params = tx.parameters tx.set_parameters(params*2) pt2 = ants.apply_ants_transform_to_vector(tx, (1,2,3)) # should be (2,4,6) def test_apply_ants_transform_to_image(self): img = ants.image_read(ants.get_ants_data("r16")).clone('float') tx = ants.new_ants_transform(dimension=2) tx.set_parameters((0.9,0,0,1.1,10,11)) img2 = ants.apply_ants_transform_to_image(tx, img, img) def test_apply_ants_transform_to_image_displacement_field(self): img = ants.image_read(ants.get_ants_data("r27")).clone('float') img2 = ants.image_read(ants.get_ants_data("r16")).clone('float') reg = ants.registration(fixed=img, moving=img2, type_of_transform="SyN") tra = ants.transform_from_displacement_field(ants.image_read(reg['fwdtransforms'][0])) deformed = tra.apply_to_image(img2, reference=img) deformed_aat = ants.apply_transforms(img, img2, reg['fwdtransforms'][0], singleprecision=True) nptest.assert_allclose(deformed.numpy(), deformed_aat.numpy(), atol=1e-6) def test_invert_ants_transform(self): img = ants.image_read(ants.get_ants_data("r16")).clone('float') tx = ants.new_ants_transform(dimension=2) tx.set_parameters((0.9,0,0,1.1,10,11)) img_transformed = tx.apply_to_image(img, img) inv_tx = ants.invert_ants_transform(tx) img_orig = inv_tx.apply_to_image(img_transformed, img_transformed) def test_compose_ants_transforms(self): img = ants.image_read(ants.get_ants_data("r16")).clone('float') tx = ants.new_ants_transform(dimension=2) tx.set_parameters((0.9,0,0,1.1,10,11)) inv_tx = tx.invert() single_tx = ants.compose_ants_transforms([tx, inv_tx]) img_orig = single_tx.apply_to_image(img, img) # different precisions tx1 = ants.new_ants_transform(dimension=2, precision='float') tx2 = ants.new_ants_transform(dimension=2, precision='double') with self.assertRaises(Exception): single_tx = ants.compose_ants_transforms([tx1,tx2]) # different dimensions tx1 = ants.new_ants_transform(dimension=2, precision='float') tx2 = ants.new_ants_transform(dimension=3, precision='float') with self.assertRaises(Exception): single_tx = ants.compose_ants_transforms([tx1,tx2]) def test_transform_index_to_physical_point(self): img = ants.make_image((10,10),np.random.randn(100)) pt = ants.transform_index_to_physical_point(img, (2,2)) # image not ANTsImage with self.assertRaises(Exception): ants.transform_index_to_physical_point(2, (2,2)) # index not tuple/list with self.assertRaises(Exception): ants.transform_index_to_physical_point(img,img) # index not same size as dimension with self.assertRaises(Exception): ants.transform_index_to_physical_point(img,[2]*(img.dimension+1)) def test_transform_physical_point_to_index(self): img = ants.make_image((10,10),np.random.randn(100)) idx = ants.transform_physical_point_to_index(img, (2,2)) img.set_spacing((2,2)) idx2 = ants.transform_physical_point_to_index(img, (4,4)) # image not ANTsImage with self.assertRaises(Exception): ants.transform_physical_point_to_index(2, (2,2)) # index not tuple/list with self.assertRaises(Exception): ants.transform_physical_point_to_index(img,img) # index not same size as dimension with self.assertRaises(Exception): ants.transform_physical_point_to_index(img,[2]*(img.dimension+1))
class TestModule_ants_transform(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get_ants_transform_parameters(self): pass def test_set_ants_transform_parameters(self): pass def test_get_ants_transform_fixed_parameters(self): pass def test_set_ants_transform_fixed_parameters(self): pass def test_apply_ants_transform(self): pass def test_apply_ants_transform_to_point(self): pass def test_apply_ants_transform_to_vector(self): pass def test_apply_ants_transform_to_image(self): pass def test_apply_ants_transform_to_image_displacement_field(self): pass def test_invert_ants_transform(self): pass def test_compose_ants_transforms(self): pass def test_transform_index_to_physical_point(self): pass def test_transform_physical_point_to_index(self): pass
16
0
8
0
7
1
1
0.1
1
1
0
0
15
3
15
87
133
24
101
66
85
10
101
66
85
2
2
1
19
1,765
ANTsX/ANTsPy
tests/test_core_ants_transform_io.py
test_core_ants_transform_io.TestModule_ants_transform_io
class TestModule_ants_transform_io(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) img3d = ants.image_read(ants.get_ants_data('mni')) tx2d = ants.create_ants_transform(precision='float', dimension=2) tx3d = ants.create_ants_transform(precision='float', dimension=3) self.imgs = [img2d, img3d] self.txs = [tx2d, tx3d] self.pixeltypes = ['unsigned char', 'unsigned int', 'float'] self.matrix_offset_types = ['AffineTransform', 'CenteredAffineTransform', 'Euler2DTransform', 'Euler3DTransform', 'Rigid2DTransform', 'QuaternionRigidTransform', 'Similarity2DTransform', 'CenteredSimilarity2DTransform', 'Similarity3DTransform', 'CenteredRigid2DTransform', 'CenteredEuler3DTransform', 'Rigid3DTransform'] def tearDown(self): pass def test_new_ants_transform(self): tx = ants.new_ants_transform() params = tx.parameters*2 # initialize w/ params tx = ants.new_ants_transform(parameters=params) def test_create_ants_transform(self): for mtype in self.matrix_offset_types: for ptype in {'float', 'double'}: for ndim in {2, 3}: ants.create_ants_transform(transform_type=mtype, precision=ptype, dimension=ndim) # supported types tx = ants.create_ants_transform(supported_types=True) # input params translation = (3,4,5) tx = ants.create_ants_transform( transform_type='Euler3DTransform', translation=translation ) #translation = np.array([3,4,5]) tx = ants.create_ants_transform( transform_type='Euler3DTransform', translation=translation ) # invalid dimension with self.assertRaises(Exception): ants.create_ants_transform(dimension=5) # unsupported type with self.assertRaises(Exception): ants.create_ants_transform(transform_type='unsupported-type') # bad param arg with self.assertRaises(Exception): ants.create_ants_transform( transform_type='Euler3DTransform', translation=ants.image_read(ants.get_ants_data('r16')) ) # bad precision with self.assertRaises(Exception): ants.create_ants_transform(precision='unsigned int') def test_read_write_transform(self): for tx in self.txs: filename = mktemp(suffix='.mat') ants.write_transform(tx, filename) tx2 = ants.read_transform(filename, precision='float') # file doesnt exist with self.assertRaises(Exception): ants.read_transform('blah-blah.mat') def test_from_displacement_components(self): vec_np = np.ndarray((2,2,3), dtype=np.float32) vec = ants.from_numpy(vec_np, origin=(0,0), spacing=(1,1), has_components=True) # should get ValueError here because the 2D vector field has 3 components with self.assertRaises(ValueError): ants.transform_from_displacement_field(vec) vec_np = np.ndarray((2,2,2,3), dtype=np.float32) vec = ants.from_numpy(vec_np, origin=(0,0,0), spacing=(1,1,1), has_components=True) # should work here because the 3D vector field has 3 components tx = ants.transform_from_displacement_field(vec) def test_from_displacement(self): fi = ants.image_read(ants.get_ants_data('r16') ) mi = ants.image_read(ants.get_ants_data('r64') ) fi = ants.resample_image(fi,(60,60),1,0) mi = ants.resample_image(mi,(60,60),1,0) # speed up mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = ('SyN') ) # read transform, which calls transform_from_displacement_field atx = ants.read_transform( mytx['fwdtransforms'][0] ) def test_to_displacement(self): fi = ants.image_read(ants.get_ants_data('r16') ) mi = ants.image_read(ants.get_ants_data('r64') ) fi = ants.resample_image(fi,(60,60),1,0) mi = ants.resample_image(mi,(60,60),1,0) # speed up mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = ('SyN') ) vec = ants.image_read( mytx['fwdtransforms'][0] ) atx = ants.transform_from_displacement_field( vec ) field = ants.transform_to_displacement_field( atx, fi ) def test_catch_error(self): with self.assertRaises(Exception): ants.write_transform(123, 'test.mat')
class TestModule_ants_transform_io(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_new_ants_transform(self): pass def test_create_ants_transform(self): pass def test_read_write_transform(self): pass def test_from_displacement_components(self): pass def test_from_displacement_components(self): pass def test_to_displacement(self): pass def test_catch_error(self): pass
10
0
11
1
9
2
1
0.18
1
2
0
0
9
4
9
81
110
20
78
41
68
14
67
41
57
4
2
3
13
1,766
ANTsX/ANTsPy
tests/test_learn.py
test_learn.TestModule_decomposition
class TestModule_decomposition(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_sparse_decom2_example(self): mat = np.random.randn(20, 100) mat2 = np.random.randn(20, 90) mydecom = ants.sparse_decom2(inmatrix = (mat,mat2), sparseness=(0.1,0.3), nvecs=3, its=3, perms=10) def test_initialize_eigenanatomy_example(self): mat = np.random.randn(4,100).astype('float32') init = ants.initialize_eigenanatomy(mat) img = ants.image_read(ants.get_ants_data('r16')) segs = ants.kmeans_segmentation(img, 3) init = ants.initialize_eigenanatomy(segs['segmentation']) def test_eig_seg_example(self): mylist = [ants.image_read(ants.get_ants_data('r16')), ants.image_read(ants.get_ants_data('r27')), ants.image_read(ants.get_ants_data('r85'))] myseg = ants.eig_seg(ants.get_mask(mylist[0]), mylist) mylist = [ants.image_read(ants.get_ants_data('r16')), ants.image_read(ants.get_ants_data('r27')), ants.image_read(ants.get_ants_data('r85'))] myseg = ants.eig_seg(ants.get_mask(mylist[0]), mylist, cthresh=2) mylist = [ants.image_read(ants.get_ants_data('r16')), ants.image_read(ants.get_ants_data('r27')), ants.image_read(ants.get_ants_data('r85'))] myseg = ants.eig_seg(ants.get_mask(mylist[0]), mylist, apply_segmentation_to_images=True)
class TestModule_decomposition(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_sparse_decom2_example(self): pass def test_initialize_eigenanatomy_example(self): pass def test_eig_seg_example(self): pass
6
0
6
1
6
0
1
0
1
0
0
0
5
0
5
77
39
9
30
15
24
0
22
15
16
1
2
0
5
1,767
ANTsX/ANTsPy
tests/test_ops.py
test_ops.Test_iMath
class Test_iMath(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_functions(self): image = ants.image_read(ants.get_data('r16')) ants.iMath_canny(image, sigma=2, lower=0, upper=1) ants.iMath_fill_holes(image, hole_type=2) ants.iMath_GC(image, radius=1) ants.iMath_GD(image, radius=1) ants.iMath_GE(image, radius=1) ants.iMath_GO(image, radius=1) ants.iMath_get_largest_component(image, min_size=50) ants.iMath_grad(image, sigma=0.5, normalize=False) ants.iMath_histogram_equalization(image, alpha=0.5, beta=0.5) ants.iMath_laplacian(image, sigma=0.5, normalize=False) ants.iMath_MC(image, radius=1, value=1, shape=1, parametric=False, lines=3, thickness=1, include_center=False) ants.iMath_MD(image, radius=1, value=1, shape=1, parametric=False, lines=3, thickness=1, include_center=False) ants.iMath_ME(image, radius=1, value=1, shape=1, parametric=False, lines=3, thickness=1, include_center=False) ants.iMath_MO(image, radius=1, value=1, shape=1, parametric=False, lines=3, thickness=1, include_center=False) ants.iMath_maurer_distance(image, foreground=1) ants.iMath_normalize(image) ants.iMath_pad(image, padding=2) ants.iMath_perona_malik(image, conductance=0.25, n_iterations=1) ants.iMath_sharpen(image) ants.iMath_truncate_intensity(image, lower_q=0.05, upper_q=0.95, n_bins=64)
class Test_iMath(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_functions(self): pass
4
0
9
0
9
0
1
0
1
0
0
0
3
0
3
75
31
4
27
5
23
0
27
5
23
1
2
0
3
1,768
ANTsX/ANTsPy
tests/test_ops.py
test_ops.Test_slice_image
class Test_slice_image(unittest.TestCase): """ Test ants.ANTsImage class """ def setUp(self): pass def tearDown(self): pass def test_slice_image_2d(self): """ Test that resampling an image doesnt cause the resampled image to have NaNs - previously caused by resampling an image of type DOUBLE """ img = ants.image_read(ants.get_ants_data('r16')) img2 = ants.slice_image(img, 0, 100) self.assertTrue(isinstance(img2, np.ndarray)) img2 = ants.slice_image(img, 1, 100) self.assertTrue(isinstance(img2, np.ndarray)) with self.assertRaises(Exception): img2 = ants.slice_image(img, 2, 100) with self.assertRaises(Exception): img2 = ants.slice_image(img, -3, 100) with self.assertRaises(Exception): img2 = ants.slice_image(img, 4, 100) img2 = ants.slice_image(img, -1, 100) img3 = ants.slice_image(img, 1, 100) self.assertTrue(np.allclose(img2, img3)) def test_slice_image_2d_vector(self): img0 = ants.image_read(ants.get_ants_data('r16')) img = ants.merge_channels([img0,img0,img0]) img2 = ants.slice_image(img, 0, 100) self.assertTrue(isinstance(img2, np.ndarray)) img2 = ants.slice_image(img, 1, 100) self.assertTrue(isinstance(img2, np.ndarray)) with self.assertRaises(Exception): img2 = ants.slice_image(img, 2, 100) with self.assertRaises(Exception): img2 = ants.slice_image(img, -3, 100) with self.assertRaises(Exception): img2 = ants.slice_image(img, 4, 100) img2 = ants.slice_image(img, -1, 100) img3 = ants.slice_image(img, 1, 100) self.assertTrue(np.allclose(img2, img3)) def test_slice_image_3d(self): """ Test that resampling an image doesnt cause the resampled image to have NaNs - previously caused by resampling an image of type DOUBLE """ img = ants.image_read(ants.get_ants_data('mni')) img2 = ants.slice_image(img, 0, 100) self.assertEqual(img2.dimension, 2) img2 = ants.slice_image(img, 1, 100) self.assertEqual(img2.dimension, 2) img2 = ants.slice_image(img, 2, 100) self.assertEqual(img2.dimension, 2) img2 = ants.slice_image(img.clone('unsigned int'), 2, 100) self.assertEqual(img2.dimension, 2) with self.assertRaises(Exception): img2 = ants.slice_image(img, 3, 100) with self.assertRaises(Exception): img2 = ants.slice_image(img, 2, 100, collapse_strategy=23) img2 = ants.slice_image(img, -1, 100) img3 = ants.slice_image(img, 2, 100) self.assertTrue(ants.allclose(img2, img3)) def test_slice_image_3d_vector(self): """ Test that resampling an image doesnt cause the resampled image to have NaNs - previously caused by resampling an image of type DOUBLE """ img0 = ants.image_read(ants.get_ants_data('mni')) img = ants.merge_channels([img0,img0,img0]) img2 = ants.slice_image(img, 0, 100) self.assertEqual(img2.dimension, 2) img2 = ants.slice_image(img, 1, 100) self.assertEqual(img2.dimension, 2) img2 = ants.slice_image(img, 2, 100) self.assertEqual(img2.dimension, 2) img2 = ants.slice_image(img.clone('unsigned int'), 2, 100) self.assertEqual(img2.dimension, 2) with self.assertRaises(Exception): img2 = ants.slice_image(img, 3, 100) with self.assertRaises(Exception): img2 = ants.slice_image(img, 2, 100, collapse_strategy=23) img2 = ants.slice_image(img, -1, 100) img3 = ants.slice_image(img, 2, 100) self.assertTrue(ants.allclose(img2, img3))
class Test_slice_image(unittest.TestCase): ''' Test ants.ANTsImage class ''' def setUp(self): pass def tearDown(self): pass def test_slice_image_2d(self): ''' Test that resampling an image doesnt cause the resampled image to have NaNs - previously caused by resampling an image of type DOUBLE ''' pass def test_slice_image_2d_vector(self): pass def test_slice_image_3d(self): ''' Test that resampling an image doesnt cause the resampled image to have NaNs - previously caused by resampling an image of type DOUBLE ''' pass def test_slice_image_3d_vector(self): ''' Test that resampling an image doesnt cause the resampled image to have NaNs - previously caused by resampling an image of type DOUBLE ''' pass
7
4
19
4
12
3
1
0.25
1
1
0
0
6
0
6
78
120
31
71
21
64
18
71
21
64
1
2
1
6
1,769
ANTsX/ANTsPy
tests/test_plotting.py
test_plotting.TestModule_plot
class TestModule_plot(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) img3d = ants.image_read(ants.get_ants_data('mni')) self.imgs = [img2d, img3d] def tearDown(self): pass def test_plot_example(self): filename = mktemp(suffix='.png') for img in self.imgs: ants.plot(img) ants.plot(img, overlay=img*2) ants.plot(img, overlay=img*2) ants.plot(img, filename=filename) def test_extra_plot(self): img = ants.image_read(ants.get_ants_data('r16')) ants.plot(img, overlay=img*2, domain_image_map=ants.image_read(ants.get_data('r64'))) img = ants.image_read(ants.get_ants_data('r16')) ants.plot(img, crop=True) img = ants.image_read(ants.get_ants_data('mni')) ants.plot(img, overlay=img*2, domain_image_map=ants.image_read(ants.get_data('mni')).resample_image((4,4,4))) img = ants.image_read(ants.get_ants_data('mni')) ants.plot(img, overlay=img*2, reorient=True, crop=True) def test_random(self): img = ants.image_read(ants.get_ants_data('r16')) img3 = ants.image_read(ants.get_data('r64')) img2 = ants.image_read(ants.get_ants_data('mni')) imgv = ants.merge_channels([img2]) ants.plot(img2, axis='x', scale=True, ncol=1) ants.plot(img2, axis='y', scale=(0.05, 0.95)) ants.plot(img2, axis='z', slices=[10,20,30], title='Test', cbar=True, cbar_vertical=True) ants.plot(img2, cbar=True, cbar_vertical=False) ants.plot(img, black_bg=False, title='Test', cbar=True) imgx = img2.clone() imgx.set_spacing((10,1,1)) ants.plot(imgx) ants.plot(ants.get_ants_data('r16'), overlay=ants.get_data('r64'), blend=True) with self.assertRaises(Exception): ants.plot(ants.get_ants_data('r16'), overlay=123) with self.assertRaises(Exception): ants.plot(ants.get_ants_data('r16'), overlay=ants.merge_channels([img,img])) ants.plot(ants.from_numpy(np.zeros((100,100)))) ants.plot(img.clone('unsigned int')) ants.plot(img, domain_image_map=img3) with self.assertRaises(Exception): ants.plot(123)
class TestModule_plot(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_plot_example(self): pass def test_extra_plot(self): pass def test_random(self): pass
6
0
11
1
9
0
1
0
1
1
0
0
5
1
5
77
59
11
48
17
42
0
46
17
40
2
2
1
6
1,770
ANTsX/ANTsPy
tests/test_plotting.py
test_plotting.TestModule_plot_grid
class TestModule_plot_grid(unittest.TestCase): def setUp(self): mni1 = ants.image_read(ants.get_data('mni')) mni2 = mni1.smooth_image(1.) mni3 = mni1.smooth_image(2.) mni4 = mni1.smooth_image(3.) self.images3d = np.asarray([[mni1, mni2], [mni3, mni4]]) self.images2d = np.asarray([[mni1.slice_image(2,100), mni2.slice_image(2,100)], [mni3.slice_image(2,100), mni4.slice_image(2,100)]]) def tearDown(self): pass def test_plot_example(self): ants.plot_grid(self.images3d, slices=100) # should take middle slices if none are given ants.plot_grid(self.images3d) # should work with 2d images ants.plot_grid(self.images2d) def test_examples(self): mni1 = ants.image_read(ants.get_data('mni')) mni2 = mni1.smooth_image(1.) mni3 = mni1.smooth_image(2.) mni4 = mni1.smooth_image(3.) images = np.asarray([[mni1, mni2], [mni3, mni4]]) slices = np.asarray([[100, 100], [100, 100]]) ants.plot_grid(images=images, slices=slices, title='2x2 Grid') images2d = np.asarray([[mni1.slice_image(2,100), mni2.slice_image(2,100)], [mni3.slice_image(2,100), mni4.slice_image(2,100)]]) ants.plot_grid(images=images2d, title='2x2 Grid Pre-Sliced') ants.plot_grid(images.reshape(1,4), slices.reshape(1,4), title='1x4 Grid') ants.plot_grid(images.reshape(4,1), slices.reshape(4,1), title='4x1 Grid') # Padding between rows and/or columns ants.plot_grid(images, slices, cpad=0.02, title='Col Padding') ants.plot_grid(images, slices, rpad=0.02, title='Row Padding') ants.plot_grid(images, slices, rpad=0.02, cpad=0.02, title='Row and Col Padding') # Adding plain row and/or column labels ants.plot_grid(images, slices, title='Adding Row Labels', rlabels=['Row #1', 'Row #2']) ants.plot_grid(images, slices, title='Adding Col Labels', clabels=['Col #1', 'Col #2']) ants.plot_grid(images, slices, title='Row and Col Labels', rlabels=['Row 1', 'Row 2'], clabels=['Col 1', 'Col 2']) # Making a publication-quality image images = np.asarray([[mni1, mni2, mni2], [mni3, mni4, mni4]]) slices = np.asarray([[100, 100, 100], [100, 100, 100]]) axes = np.asarray([[0, 1, 2], [0, 1, 2]]) ants.plot_grid(images, slices, axes, title='Publication Figures with ANTsPy', tfontsize=20, title_dy=0.03, title_dx=-0.04, rlabels=['Row 1', 'Row 2'], clabels=['Col 1', 'Col 2', 'Col 3'], rfontsize=16, cfontsize=16)
class TestModule_plot_grid(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_plot_example(self): pass def test_examples(self): pass
5
0
14
1
12
2
1
0.14
1
0
0
0
4
2
4
76
61
7
49
19
44
7
36
19
31
1
2
0
4
1,771
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
ants.contrib.sampling.affine2d.RandomRotate2D
class RandomRotate2D(object): """ Apply a Rotated2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. """ def __init__(self, rotation_range, reference=None, lazy=False): """ Initialize a RandomRotate2D object Arguments --------- rotation_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. rotation_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image """ if (not isinstance(rotation_range, (list, tuple))) or ( len(rotation_range) != 2 ): raise ValueError( "rotation_range argument must be list/tuple with two values!" ) self.rotation_range = rotation_range self.reference = reference self.lazy = lazy def transform(self, X=None, y=None): """ Transform an image using an Affine transform with rotation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomRotate2D(rotation_range=(-10,10)) >>> img2 = tx.transform(img) """ # random draw in rotation range rotation = random.gauss(self.rotation_range[0], self.rotation_range[1]) self.params = rotation tx = Rotate2D(rotation, reference=self.reference, lazy=self.lazy) return tx.transform(X, y)
class RandomRotate2D(object): ''' Apply a Rotated2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. ''' def __init__(self, rotation_range, reference=None, lazy=False): ''' Initialize a RandomRotate2D object Arguments --------- rotation_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. rotation_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommended) image providing the reference space for the transform. this will also set the transform fixed parameters. lazy : boolean (default = False) if True, calling the `transform` method only returns the randomly generated transform and does not actually transform the image ''' pass def transform(self, X=None, y=None): ''' Transform an image using an Affine transform with rotation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomRotate2D(rotation_range=(-10,10)) >>> img2 = tx.transform(img) ''' pass
3
3
31
5
8
19
2
2.69
1
4
1
0
2
4
2
2
71
12
16
9
13
43
12
9
9
2
1
1
3
1,772
ANTsX/ANTsPy
tests/test_plotting.py
test_plotting.TestModule_plot_ortho
class TestModule_plot_ortho(unittest.TestCase): def setUp(self): img3d = ants.image_read(ants.get_ants_data('mni')) self.imgs = [img3d] def tearDown(self): pass def test_plot_example(self): filename = mktemp(suffix='.png') for img in self.imgs: ants.plot_ortho(img) ants.plot_ortho(img, filename=filename) def test_plot_extra(self): img = ants.image_read(ants.get_ants_data('mni')) ants.plot_ortho(img, overlay=img*2, domain_image_map=ants.image_read(ants.get_data('mni'))) img = ants.image_read(ants.get_ants_data('mni')) ants.plot_ortho(img, overlay=img*2, reorient=True, crop=True) def test_random_params(self): img = ants.image_read(ants.get_ants_data('mni')).resample_image((4,4,4)) img2 = ants.image_read(ants.get_data('r16')) ants.plot_ortho(ants.get_data('mni'), overlay=ants.get_data('mni')) with self.assertRaises(Exception): ants.plot_ortho(123) with self.assertRaises(Exception): ants.plot_ortho(img2) with self.assertRaises(Exception): ants.plot_ortho(img, overlay=img2) imgx = img.clone() imgx.set_spacing((3,3,3)) ants.plot_ortho(img,overlay=imgx) ants.plot_ortho(img.clone('unsigned int'),overlay=img, blend=True) imgx = img.clone() imgx.set_spacing((10,1,1)) ants.plot_ortho(imgx) ants.plot_ortho(img, flat=True, title='Test', text='This is a test') ants.plot_ortho(img, title='Test', text='This is a test', cbar=True) with self.assertRaises(Exception): ants.plot_ortho(img, domain_image_map=123) with self.assertRaises(Exception): ants.plot_orto(ants.merge_channels([img,img]))
class TestModule_plot_ortho(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_plot_example(self): pass def test_plot_extra(self): pass def test_random_params(self): pass
6
0
9
1
8
0
1
0
1
1
0
0
5
1
5
77
51
11
40
14
34
0
39
14
33
2
2
1
6
1,773
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_reorient_image
class TestModule_reorient_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_reorient_image(self): mni = ants.image_read(ants.get_data('mni')) mni2 = mni.reorient_image2() def test_get_center_of_mass(self): fi = ants.image_read(ants.get_ants_data("r16")) com = ants.get_center_of_mass(fi) self.assertEqual(len(com), fi.dimension) fi = ants.image_read(ants.get_ants_data("r64")) com = ants.get_center_of_mass(fi) self.assertEqual(len(com), fi.dimension) fi = fi.clone("unsigned int") com = ants.get_center_of_mass(fi) self.assertEqual(len(com), fi.dimension) # 3d img = ants.image_read(ants.get_ants_data("mni")) com = ants.get_center_of_mass(img) self.assertEqual(len(com), img.dimension)
class TestModule_reorient_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_reorient_image(self): pass def test_get_center_of_mass(self): pass
5
0
6
1
5
0
1
0.05
1
0
0
0
4
0
4
76
29
7
21
10
16
1
21
10
16
1
2
0
4
1,774
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_reflect_image
class TestModule_reflect_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): fi = ants.image_read(ants.get_ants_data("r16")) axis = 2 asym = ants.reflect_image(fi, axis, "Affine")["warpedmovout"] asym = asym - fi
class TestModule_reflect_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
12
2
10
7
6
0
10
7
6
1
2
0
3
1,775
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_random
class TestModule_random(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_landmark_transforms(self): fixed = np.array([[50.0,50.0],[200.0,50.0],[200.0,200.0]]) moving = np.array([[50.0,50.0],[50.0,200.0],[200.0,200.0]]) xfrm = ants.fit_transform_to_paired_points(moving, fixed, transform_type="syn", domain_image=ants.image_read(ants.get_data('r16')), verbose=True) xfrm = ants.fit_transform_to_paired_points(moving, fixed, transform_type="tv", domain_image=ants.image_read(ants.get_data('r16'))) xfrm = ants.fit_transform_to_paired_points(moving, fixed, transform_type="affine") xfrm = ants.fit_transform_to_paired_points(moving, fixed, transform_type="rigid") xfrm = ants.fit_transform_to_paired_points(moving, fixed, transform_type="similarity") domain_image = ants.image_read(ants.get_ants_data("r16")) xfrm = ants.fit_transform_to_paired_points(moving, fixed, transform_type="bspline", domain_image=domain_image, number_of_fitting_levels=5) xfrm = ants.fit_transform_to_paired_points(moving, fixed, transform_type="diffeo", domain_image=domain_image, number_of_fitting_levels=6) res = ants.fit_time_varying_transform_to_point_sets([fixed, moving, moving], domain_image=ants.image_read(ants.get_data('r16')), verbose=True) def test_deformation_gradient(self): fi = ants.image_read( ants.get_ants_data('r16')) mi = ants.image_read( ants.get_ants_data('r64')) fi = ants.resample_image(fi,(128,128),1,0) mi = ants.resample_image(mi,(128,128),1,0) mytx = ants.registration(fixed=fi , moving=mi, type_of_transform = ('SyN') ) dg = ants.deformation_gradient( ants.image_read( mytx['fwdtransforms'][0] ) ) dg = ants.deformation_gradient( ants.image_read( mytx['fwdtransforms'][0] ), py_based=True) dg = ants.deformation_gradient( ants.image_read( mytx['fwdtransforms'][0] ), to_rotation=True) dg = ants.deformation_gradient( ants.image_read( mytx['fwdtransforms'][0] ), to_rotation=True, py_based=True) def test_jacobian(self): fi = ants.image_read( ants.get_ants_data('r16')) mi = ants.image_read( ants.get_ants_data('r64')) fi = ants.resample_image(fi,(128,128),1,0) mi = ants.resample_image(mi,(128,128),1,0) mytx = ants.registration(fixed=fi , moving=mi, type_of_transform = ('SyN') ) jac = ants.create_jacobian_determinant_image(fi,mytx['fwdtransforms'][0],1) def test_apply_transforms(self): fixed = ants.image_read( ants.get_ants_data('r16') ) moving = ants.image_read( ants.get_ants_data('r64') ) fixed = ants.resample_image(fixed, (64,64), 1, 0) moving = ants.resample_image(moving, (64,64), 1, 0) mytx = ants.registration(fixed=fixed , moving=moving , type_of_transform = 'SyN' ) mywarpedimage = ants.apply_transforms( fixed=fixed, moving=moving, transformlist=mytx['fwdtransforms'] ) def test_apply_transforms_to_points(self): fixed = ants.image_read( ants.get_ants_data('r16') ) moving = ants.image_read( ants.get_ants_data('r27') ) reg = ants.registration( fixed, moving, 'Affine' ) d = {'x': [128, 127], 'y': [101, 111]} pts = pd.DataFrame(data=d) ptsw = ants.apply_transforms_to_points( 2, pts, reg['fwdtransforms']) def test_warped_grid(self): fi = ants.image_read( ants.get_ants_data( 'r16' ) ) mi = ants.image_read( ants.get_ants_data( 'r64' ) ) mygr = ants.create_warped_grid( mi ) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = ('SyN') ) mywarpedgrid = ants.create_warped_grid( mi, grid_directions=(False,True), transform=mytx['fwdtransforms'], fixed_reference_image=fi ) def test_more_registration(self): fi = ants.image_read(ants.get_ants_data('r16')) mi = ants.image_read(ants.get_ants_data('r64')) fi = ants.resample_image(fi, (60,60), 1, 0) mi = ants.resample_image(mi, (60,60), 1, 0) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = 'SyN' ) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = 'antsRegistrationSyN[t]' ) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = 'antsRegistrationSyN[b]' ) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = 'antsRegistrationSyN[s]' ) def test_motion_correction(self): fi = ants.image_read(ants.get_ants_data('ch2')) mytx = ants.motion_correction( fi ) def test_label_image_registration(self): fi = ants.image_read(ants.get_ants_data('r16')) mi = ants.image_read(ants.get_ants_data('r64')) fi = ants.resample_image(fi, (60,60), 1, 0) mi = ants.resample_image(mi, (60,60), 1, 0) fi_seg = ants.threshold_image(fi, "Kmeans", 3)-1 mi_seg = ants.threshold_image(mi, "Kmeans", 3)-1 mytx = ants.label_image_registration([fi_seg], [mi_seg], fixed_intensity_images=fi, moving_intensity_images=mi) def test_reg_precision_option(self): # Check that registration and apply transforms works with float and double precision fi = ants.image_read(ants.get_ants_data("r16")) mi = ants.image_read(ants.get_ants_data("r64")) fi = ants.resample_image(fi, (60, 60), 1, 0) mi = ants.resample_image(mi, (60, 60), 1, 0) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform="SyN") # should be float precision info = ants.image_header_info(mytx["fwdtransforms"][0]) self.assertEqual(info['pixeltype'], 'float') mytx = ants.registration(fixed=fi, moving=mi, type_of_transform="SyN", singleprecision=False) info = ants.image_header_info(mytx["fwdtransforms"][0]) self.assertEqual(info['pixeltype'], 'double')
class TestModule_random(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_landmark_transforms(self): pass def test_deformation_gradient(self): pass def test_jacobian(self): pass def test_apply_transforms(self): pass def test_apply_transforms_to_points(self): pass def test_warped_grid(self): pass def test_more_registration(self): pass def test_motion_correction(self): pass def test_label_image_registration(self): pass def test_reg_precision_option(self): pass
13
0
9
0
8
0
1
0.02
1
0
0
0
12
0
12
84
116
16
99
55
86
2
85
55
72
1
2
0
12
1,776
ANTsX/ANTsPy
tests/test_plotting.py
test_plotting.TestModule_plot_hist
class TestModule_plot_hist(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) img3d = ants.image_read(ants.get_ants_data('mni')) self.imgs = [img2d, img3d] def tearDown(self): pass def test_plot_example(self): filename = mktemp(suffix='.png') for img in self.imgs: ants.plot_hist(img)
class TestModule_plot_hist(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_plot_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
1
3
75
14
3
11
9
7
0
11
9
7
2
2
1
4
1,777
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_metrics
class TestModule_metrics(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): fi = ants.image_read(ants.get_ants_data("r16")).clone("float") mi = ants.image_read(ants.get_ants_data("r64")).clone("float") mival = ants.image_mutual_information(fi, mi)
class TestModule_metrics(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
3
0
3
0
1
0.11
1
0
0
0
3
0
3
75
11
2
9
7
5
1
9
7
5
1
2
0
3
1,778
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_interface
class TestModule_interface(unittest.TestCase): def setUp(self): self.transform_types = { "SyNBold", "SyNBoldAff", "ElasticSyN", "SyN", "SyNRA", "SyNOnly", "SyNAggro", "SyNCC", "TRSAA", "SyNabp", "SyNLessAggro", "TVMSQ", "TVMSQC", "Rigid", "Similarity", "Translation", "Affine", "AffineFast", "BOLDAffine", "QuickRigid", "DenseRigid", "BOLDRigid", "antsRegistrationSyNQuick[b,32,26]", "antsRegistrationSyNQuick[s]", "antsRegistrationSyNRepro[s]", "antsRegistrationSyN[s]" } def tearDown(self): pass def test_example(self): fi = ants.image_read(ants.get_ants_data("r16")) mi = ants.image_read(ants.get_ants_data("r64")) fi = ants.resample_image(fi, (60, 60), 1, 0) mi = ants.resample_image(mi, (60, 60), 1, 0) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform="SyN") def test_affine_interface(self): print("Starting affine interface registration test") fi = ants.image_read(ants.get_ants_data("r16")) mi = ants.image_read(ants.get_ants_data("r64")) with self.assertRaises(ValueError): ants.registration( fixed=fi, moving=mi, type_of_transform="Translation", aff_iterations=4, aff_shrink_factors=4, aff_smoothing_sigmas=(4, 4), ) mytx = ants.registration( fixed=fi, moving=mi, type_of_transform="Affine", aff_iterations=(4, 4), aff_shrink_factors=(4, 4), aff_smoothing_sigmas=(4, 4), ) mytx = ants.registration( fixed=fi, moving=mi, type_of_transform="Translation", aff_iterations=4, aff_shrink_factors=4, aff_smoothing_sigmas=4, ) def test_registration_types(self): print("Starting long registration interface test") fi = ants.image_read(ants.get_ants_data("r16")) mi = ants.image_read(ants.get_ants_data("r64")) fi = ants.resample_image(fi, (60, 60), 1, 0) mi = ants.resample_image(mi, (60, 60), 1, 0) for ttype in self.transform_types: print(ttype) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform=ttype) # with mask fimask = fi > fi.mean() mytx = ants.registration( fixed=fi, moving=mi, mask=fimask, type_of_transform=ttype ) print("Finished long registration interface test")
class TestModule_interface(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass def test_affine_interface(self): pass def test_registration_types(self): pass
6
0
17
1
16
0
1
0.01
1
1
0
0
5
1
5
77
89
7
81
18
75
1
31
18
25
2
2
1
6
1,779
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_fsl2antstransform
class TestModule_fsl2antstransform(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): fslmat = np.zeros((4, 4)) np.fill_diagonal(fslmat, 1) img = ants.image_read(ants.get_ants_data("ch2")) tx = ants.fsl2antstransform(fslmat, img, img)
class TestModule_fsl2antstransform(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
12
2
10
7
6
0
10
7
6
1
2
0
3
1,780
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_multivar
class TestModule_multivar(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): image = ants.image_read(ants.get_ants_data("r16")) image2 = ants.image_read(ants.get_ants_data("r27")) demonsMetric = ["demons", image, image2, 1, 1] ccMetric = ["CC", image, image2, 2, 1] metrics = list() metrics.append(demonsMetric) reg3 = ants.registration(image, image2, "SyNOnly", multivariate_extras=metrics) metrics.append(ccMetric) reg2 = ants.registration( image, image2, "SyNOnly", multivariate_extras=metrics, verbose=True )
class TestModule_multivar(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
5
0
5
0
1
0
1
1
0
0
3
0
3
75
19
2
17
11
13
0
15
11
11
1
2
0
3
1,781
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_create_jacobian_determinant_image
class TestModule_create_jacobian_determinant_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): fi = ants.image_read(ants.get_ants_data("r16")) mi = ants.image_read(ants.get_ants_data("r64")) fi = ants.resample_image(fi, (128, 128), 1, 0) mi = ants.resample_image(mi, (128, 128), 1, 0) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform=("SyN")) try: jac = ants.create_jacobian_determinant_image( fi, mytx["fwdtransforms"][0], 1 ) except: pass
class TestModule_create_jacobian_determinant_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
5
0
5
0
1
0
1
0
0
0
3
0
3
75
19
2
17
8
13
0
15
8
11
2
2
1
4
1,782
ANTsX/ANTsPy
tests/test_plotting.py
test_plotting.TestModule_plot_ortho_stack
class TestModule_plot_ortho_stack(unittest.TestCase): def setUp(self): self.img = ants.image_read(ants.get_ants_data('mni')) def tearDown(self): pass def test_plot_example(self): filename = mktemp(suffix='.png') ants.plot_ortho_stack([self.img, self.img]) ants.plot_ortho_stack([self.img, self.img], filename=filename) def test_extra_ortho_stack(self): img = ants.image_read(ants.get_ants_data('mni')) ants.plot_ortho_stack([img, img], overlays=[img*2, img*2], domain_image_map=ants.image_read(ants.get_data('mni'))) img = ants.image_read(ants.get_ants_data('mni')) ants.plot_ortho_stack([img, img], overlays=[img*2, img*2], reorient=True, crop=True)
class TestModule_plot_ortho_stack(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_plot_example(self): pass def test_extra_ortho_stack(self): pass
5
0
4
0
4
0
1
0
1
0
0
0
4
1
4
76
20
5
15
8
10
0
14
8
9
1
2
0
4
1,783
ANTsX/ANTsPy
tests/test_plotting.py
test_plotting.TestModule_plot_ortho_stack
class TestModule_plot_ortho_stack(unittest.TestCase): def setUp(self): self.img = ants.image_read(ants.get_ants_data('mni')) def tearDown(self): pass def test_plot_example(self): filename = mktemp(suffix='.png') ants.plot_ortho_stack([self.img, self.img]) ants.plot_ortho_stack([self.img, self.img], filename=filename) def test_extra_ortho_stack(self): img = ants.image_read(ants.get_ants_data('mni')) ants.plot_ortho_stack([img, img], overlays=[img*2, img*2], domain_image_map=ants.image_read(ants.get_data('mni'))) img = ants.image_read(ants.get_ants_data('mni')) ants.plot_ortho_stack([img, img], overlays=[img*2, img*2], reorient=True, crop=True)
class TestModule_plot_ortho_stack(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_plot_example(self): pass def test_extra_ortho_stack(self): pass
5
0
11
2
9
0
1
0
1
1
0
0
3
0
3
75
35
7
28
7
24
0
25
7
21
1
2
1
3
1,784
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_affine_initializer
class TestModule_affine_initializer(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): # test ANTsPy/ANTsR example fi = ants.image_read(ants.get_ants_data("r16")) mi = ants.image_read(ants.get_ants_data("r27")) txfile = ants.affine_initializer(fi, mi) tx = ants.read_transform(txfile)
class TestModule_affine_initializer(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
3
0
3
0
1
0.1
1
0
0
0
3
0
3
75
13
2
10
8
6
1
10
8
6
1
2
0
3
1,785
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_apply_transforms
class TestModule_apply_transforms(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): # test ANTsPy/ANTsR example fixed = ants.image_read(ants.get_ants_data("r16")) moving = ants.image_read(ants.get_ants_data("r64")) fixed = ants.resample_image(fixed, (64, 64), 1, 0) moving = ants.resample_image(moving, (128, 128), 1, 0) mytx = ants.registration(fixed=fixed, moving=moving, type_of_transform="SyN") mywarpedimage = ants.apply_transforms( fixed=fixed, moving=moving, transformlist=mytx["fwdtransforms"] ) self.assertEqual(mywarpedimage.pixeltype, moving.pixeltype) self.assertTrue(ants.image_physical_space_consistency(fixed, mywarpedimage, 0.0001, datatype = False)) # Call with float precision for transforms, but should still return input type mywarpedimage2 = ants.apply_transforms( fixed=fixed, moving=moving, transformlist=mytx["fwdtransforms"], singleprecision=True ) self.assertEqual(mywarpedimage2.pixeltype, moving.pixeltype) self.assertLessEqual(np.sum((mywarpedimage.numpy() - mywarpedimage2.numpy()) ** 2), 0.1) # bad interpolator with self.assertRaises(Exception): mywarpedimage = ants.apply_transforms( fixed=fixed, moving=moving, transformlist=mytx["fwdtransforms"], interpolator="unsupported-interp", ) # transform doesnt exist with self.assertRaises(Exception): mywarpedimage = ants.apply_transforms( fixed=fixed, moving=moving, transformlist=["blah-blah.mat"], interpolator="unsupported-interp", )
class TestModule_apply_transforms(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
14
1
12
1
1
0.11
1
1
0
0
3
0
3
75
45
5
36
9
32
4
21
9
17
1
2
1
3
1,786
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_create_warped_grid
class TestModule_create_warped_grid(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): fi = ants.image_read(ants.get_ants_data("r16")) mi = ants.image_read(ants.get_ants_data("r64")) mygr = ants.create_warped_grid(mi) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform=("SyN")) mywarpedgrid = ants.create_warped_grid( mi, grid_directions=(False, True), transform=mytx["fwdtransforms"], fixed_reference_image=fi, )
class TestModule_create_warped_grid(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass
4
0
5
0
5
0
1
0
1
0
0
0
3
0
3
75
19
3
16
9
12
0
11
9
7
1
2
0
3
1,787
ANTsX/ANTsPy
tests/test_registration.py
test_registration.TestModule_build_template
class TestModule_build_template(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): image = ants.image_read(ants.get_ants_data("r16")) image2 = ants.image_read(ants.get_ants_data("r27")) timage = ants.build_template(image_list=(image, image2)) def test_type_of_transform(self): image = ants.image_read(ants.get_ants_data("r16")) image2 = ants.image_read(ants.get_ants_data("r27")) timage = ants.build_template(image_list=(image, image2)) timage = ants.build_template( image_list=(image, image2), type_of_transform="SyNCC" )
class TestModule_build_template(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_example(self): pass def test_type_of_transform(self): pass
5
0
4
0
4
0
1
0
1
0
0
0
4
0
4
76
19
3
16
11
11
0
14
11
9
1
2
0
4
1,788
APSL/django-kaio
APSL_django-kaio/kaio/mixins/debug.py
kaio.mixins.debug.DebugMixin
class DebugMixin(object): """Debug base settings""" @property def DEBUG(self): return get('DEBUG', False) @property def TEMPLATE_DEBUG(self): debug = get('TEMPLATE_DEBUG', self.DEBUG) for template in self.TEMPLATES: if template['BACKEND'] == 'django.template.backends.django.DjangoTemplates': template['OPTIONS']['debug'] = debug # https://django-debug-toolbar.readthedocs.io/en/stable/installation.html#explicit-setup DEBUG_TOOLBAR_PATCH_SETTINGS = False DEBUG_TOOLBAR_MIDDLEWARE = 'debug_toolbar.middleware.DebugToolbarMiddleware' @property def ENABLE_DEBUG_TOOLBAR(self): enabled = get('ENABLE_DEBUG_TOOLBAR', self.DEBUG) if enabled: try: import debug_toolbar # noqa: F401 except ImportError: return False else: self._add_debug_toolbar_to_installed_apps() self._add_debug_toolbar_to_middleware() return enabled @property def INTERNAL_IPS(self): ips = [ip.strip() for ip in get('INTERNAL_IPS', '127.0.0.1').split(',') if ip] # For Docker: https://django-debug-toolbar.readthedocs.io/en/stable/installation.html#configure-internal-ips if self.ENABLE_DEBUG_TOOLBAR: import socket _hostname, _aliases, docker_ips = socket.gethostbyname_ex(socket.gethostname()) ips += [ip[:-1] + '1' for ip in docker_ips] return ips def _add_debug_toolbar_to_installed_apps(self): if 'debug_toolbar' not in self.INSTALLED_APPS: self.INSTALLED_APPS.append('debug_toolbar') def _add_debug_toolbar_to_middleware(self): middlewares_settings = ( 'MIDDLEWARE', # django >= 1.10 'MIDDLEWARE_CLASSES', # django < 1.10 ) for middleware_setting in middlewares_settings: middlewares = getattr(self, middleware_setting, None) if middlewares is not None: if self.DEBUG_TOOLBAR_MIDDLEWARE not in middlewares: middlewares.insert(0, self.DEBUG_TOOLBAR_MIDDLEWARE)
class DebugMixin(object): '''Debug base settings''' @property def DEBUG(self): pass @property def TEMPLATE_DEBUG(self): pass @property def ENABLE_DEBUG_TOOLBAR(self): pass @property def INTERNAL_IPS(self): pass def _add_debug_toolbar_to_installed_apps(self): pass def _add_debug_toolbar_to_middleware(self): pass
11
1
7
0
6
1
3
0.13
1
1
0
0
6
0
6
6
56
8
45
23
32
6
38
19
29
4
1
3
15
1,789
APSL/django-kaio
APSL_django-kaio/kaio/mixins/email.py
kaio.mixins.email.EmailMixin
class EmailMixin(object): """Settings para enviar emails""" # Django settings: https://docs.djangoproject.com/en/1.11/ref/settings/#email-backend @property def DEFAULT_FROM_EMAIL(self): return get('DEFAULT_FROM_EMAIL', 'Example <[email protected]>') @property def EMAIL_BACKEND(self): backend = get('EMAIL_BACKEND') if backend: return backend if 'django_yubin' not in self.INSTALLED_APPS: return 'django.core.mail.backends.smtp.EmailBackend' try: import django_yubin # type: ignore # noqa except ImportError: logger.warn('WARNING: django_yubin in INSTALLED_APPS but not pip installed.') return 'django.core.mail.backends.smtp.EmailBackend' try: from django_yubin.version import VERSION # type: ignore # noqa if VERSION[0] > 1: return 'django_yubin.backends.QueuedEmailBackend' else: return 'django_yubin.smtp_queue.EmailBackend' except Exception: return 'django_yubin.smtp_queue.EmailBackend' @property def EMAIL_FILE_PATH(self): return get('EMAIL_FILE_PATH', None) @property def EMAIL_HOST(self): return get('EMAIL_HOST', 'localhost') @property def EMAIL_HOST_PASSWORD(self): return get('EMAIL_HOST_PASSWORD', '') @property def EMAIL_HOST_USER(self): return get('EMAIL_HOST_USER', '') @property def EMAIL_PORT(self): return get('EMAIL_PORT', 25) @property def EMAIL_SUBJECT_PREFIX(self): return get('EMAIL_SUBJECT_PREFIX', '[Django] ') @property def EMAIL_USE_TLS(self): return get('EMAIL_USE_TLS', False) # django-yubin settings: http://django-yubin.readthedocs.org/en/latest/settings.html @property def MAILER_PAUSE_SEND(self): return get('MAILER_PAUSE_SEND', False) @property def MAILER_USE_BACKEND(self): return get('MAILER_USE_BACKEND', 'django.core.mail.backends.smtp.EmailBackend') @property def MAILER_HC_QUEUED_LIMIT_OLD(self): return get('MAILER_HC_QUEUED_LIMIT_OLD', 30) @property def MAILER_STORAGE_BACKEND(self): return get('MAILER_STORAGE_BACKEND', "django_yubin.storage_backends.DatabaseStorageBackend") @property def MAILER_STORAGE_DELETE(self): return get('MAILER_STORAGE_DELETE', True) @property def MAILER_FILE_STORAGE_DIR(self): return get('MAILER_FILE_STORAGE_DIR', "yubin") # deprecated, for backwards compatibility @property def MAILER_MAIL_ADMINS_PRIORITY(self): try: from django_yubin import constants priority = constants.PRIORITY_HIGH except Exception: priority = 1 return get('MAILER_MAIL_ADMINS_PRIORITY', priority) @property def MAILER_MAIL_MANAGERS_PRIORITY(self): return get('MAILER_MAIL_MANAGERS_PRIORITY', None) @property def MAILER_EMPTY_QUEUE_SLEEP(self): return get('MAILER_EMPTY_QUEUE_SLEEP', 30) @property def MAILER_LOCK_WAIT_TIMEOUT(self): return get('MAILER_LOCK_WAIT_TIMEOUT', 0) @property def MAILER_LOCK_PATH(self): return get("MAILER_LOCK_PATH", os.path.join(self.APP_ROOT, "send_mail"))
class EmailMixin(object): '''Settings para enviar emails''' @property def DEFAULT_FROM_EMAIL(self): pass @property def EMAIL_BACKEND(self): pass @property def EMAIL_FILE_PATH(self): pass @property def EMAIL_HOST(self): pass @property def EMAIL_HOST_PASSWORD(self): pass @property def EMAIL_HOST_USER(self): pass @property def EMAIL_PORT(self): pass @property def EMAIL_SUBJECT_PREFIX(self): pass @property def EMAIL_USE_TLS(self): pass @property def MAILER_PAUSE_SEND(self): pass @property def MAILER_USE_BACKEND(self): pass @property def MAILER_HC_QUEUED_LIMIT_OLD(self): pass @property def MAILER_STORAGE_BACKEND(self): pass @property def MAILER_STORAGE_DELETE(self): pass @property def MAILER_FILE_STORAGE_DIR(self): pass @property def MAILER_MAIL_ADMINS_PRIORITY(self): pass @property def MAILER_MAIL_MANAGERS_PRIORITY(self): pass @property def MAILER_EMPTY_QUEUE_SLEEP(self): pass @property def MAILER_LOCK_WAIT_TIMEOUT(self): pass @property def MAILER_LOCK_PATH(self): pass
41
1
3
0
3
0
1
0.07
1
2
0
0
20
0
20
20
115
28
83
46
39
6
62
26
38
6
1
2
26
1,790
APSL/django-kaio
APSL_django-kaio/kaio/mixins/filerconf.py
kaio.mixins.filerconf.FilerMixin
class FilerMixin(object): """Settings para django-filer y easy_thumbnails""" THUMBNAIL_PROCESSORS = ( 'easy_thumbnails.processors.colorspace', 'easy_thumbnails.processors.autocrop', # 'easy_thumbnails.processors.scale_and_crop', 'filer.thumbnail_processors.scale_and_crop_with_subject_location', 'easy_thumbnails.processors.filters', ) @property def FILER_IS_PUBLIC_DEFAULT(self): return get('FILER_IS_PUBLIC_DEFAULT', True) @property def FILER_ENABLE_PERMISSIONS(self): return get('FILER_ENABLE_PERMISSIONS', False) @property def FILER_DEBUG(self): return get('FILER_DEBUG', False) @property def FILER_ENABLE_LOGGING(self): return get('FILER_ENABLE_LOGGING', False) @property def FILER_0_8_COMPATIBILITY_MODE(self): get('FILER_0_8_COMPATIBILITY_MODE', False) @property def THUMBNAIL_DEBUG(self): return get('THUBMNAIL_DEBUG', False) @property def THUMBNAIL_QUALITY(self): return get('THUMBNAIL_QUALITY', 85) @property def FILER_CUSTOM_NGINX_SERVER(self): """If true will serve secure file trough XNginxXAccelRedirectServer""" return get('FILER_CUSTOM_NGINX_SERVER', False) @property def default_file_storage(self): """Common storage for filer configs""" return getattr( Configuration, 'DEFAULT_FILE_STORAGE', 'django.core.files.storage.FileSystemStorage') @property def FILER_CUSTOM_SECURE_MEDIA_ROOT(self): """Secure media root As in filer settings, defaults to MEDIA_ROOT/../smedia""" return opts.get( 'FILER_CUSTOM_SECURE_MEDIA_ROOT', abspath(join(self.MEDIA_ROOT, '..', 'smedia'))) @property def filer_private_files_path(self): return abspath( join( self.FILER_CUSTOM_SECURE_MEDIA_ROOT, 'filer_private' )) @property def filer_private_thumbnails_path(self): return abspath( join( self.FILER_CUSTOM_SECURE_MEDIA_ROOT, 'filer_private_thumbnails')) @property def FILER_SERVERS(self): """Filer config to be served from XNginxXAccelRedirectServer see http://django-filer.readthedocs.org/en/0.9.4/secure_downloads.html#secure-downloads """ if not self.FILER_CUSTOM_NGINX_SERVER: return {} else: return { 'private': { 'main': { 'ENGINE': 'filer.server.backends.nginx.NginxXAccelRedirectServer', 'OPTIONS': { 'location': self.filer_private_files_path, 'nginx_location': '/nginx_filer_private', }, }, 'thumbnails': { 'ENGINE': 'filer.server.backends.nginx.NginxXAccelRedirectServer', 'OPTIONS': { 'location': self.filer_private_thumbnails_path, 'nginx_location': '/nginx_filer_private_thumbnails', }, }, }, } @property def FILER_STORAGES(self): """Filer config to set custom private media path http://django-filer.readthedocs.org/en/0.9.4/settings.html#filer-storages """ if not self.FILER_CUSTOM_NGINX_SERVER: return {} return { 'public': { 'main': { 'ENGINE': self.default_file_storage, 'OPTIONS': {}, 'UPLOAD_TO': 'filer.utils.generate_filename.by_date', 'UPLOAD_TO_PREFIX': 'filer_public', }, 'thumbnails': { 'ENGINE': self.default_file_storage, 'OPTIONS': {}, 'THUMBNAIL_OPTIONS': { 'base_dir': 'filer_public_thumbnails', }, }, }, 'private': { 'main': { 'ENGINE': 'filer.storage.PrivateFileSystemStorage', 'OPTIONS': { 'location': self.filer_private_files_path, 'base_url': '/smedia/filer_private/', }, 'UPLOAD_TO': 'filer.utils.generate_filename.by_date', 'UPLOAD_TO_PREFIX': '', }, 'thumbnails': { 'ENGINE': 'filer.storage.PrivateFileSystemStorage', 'OPTIONS': { 'location': self.filer_private_thumbnails_path, 'base_url': '/smedia/filer_private_thumbnails/', }, 'THUMBNAIL_OPTIONS': {}, }, }, }
class FilerMixin(object): '''Settings para django-filer y easy_thumbnails''' @property def FILER_IS_PUBLIC_DEFAULT(self): pass @property def FILER_ENABLE_PERMISSIONS(self): pass @property def FILER_DEBUG(self): pass @property def FILER_ENABLE_LOGGING(self): pass @property def FILER_0_8_COMPATIBILITY_MODE(self): pass @property def THUMBNAIL_DEBUG(self): pass @property def THUMBNAIL_QUALITY(self): pass @property def FILER_CUSTOM_NGINX_SERVER(self): '''If true will serve secure file trough XNginxXAccelRedirectServer''' pass @property def default_file_storage(self): '''Common storage for filer configs''' pass @property def FILER_CUSTOM_SECURE_MEDIA_ROOT(self): '''Secure media root As in filer settings, defaults to MEDIA_ROOT/../smedia''' pass @property def filer_private_files_path(self): pass @property def filer_private_thumbnails_path(self): pass @property def FILER_SERVERS(self): '''Filer config to be served from XNginxXAccelRedirectServer see http://django-filer.readthedocs.org/en/0.9.4/secure_downloads.html#secure-downloads ''' pass @property def FILER_STORAGES(self): '''Filer config to set custom private media path http://django-filer.readthedocs.org/en/0.9.4/settings.html#filer-storages ''' pass
29
6
8
0
7
1
1
0.1
1
0
0
0
14
0
14
14
145
16
117
30
88
12
34
16
19
2
1
1
16
1,791
APSL/django-kaio
APSL_django-kaio/kaio/mixins/logs.py
kaio.mixins.logs.LogsMixin
class LogsMixin(object): """Django Logging configuration""" @property def LOG_LEVEL(self): return get('LOG_LEVEL', 'DEBUG').upper() @property def DJANGO_LOG_LEVEL(self): return get('DJANGO_LOG_LEVEL', 'ERROR').upper() @property def LOG_FILE(self): return get('LOG_FILE', '') @property def EXTRA_LOGGING(self): """ lista modulos con los distintos niveles a logear y su nivel de debug Por ejemplo: [Logs] EXTRA_LOGGING = oscar.paypal:DEBUG, django.db:INFO """ input_text = get('EXTRA_LOGGING', '') modules = input_text.split(',') if input_text: modules = input_text.split(',') modules = [x.split(':') for x in modules] else: modules = [] return modules # The best way to propagate logs up to the root logger is to prevent # Django logging configuration and handle it ourselves. # # http://stackoverflow.com/questions/20282521/django-request-logger-not-propagated-to-root/22336174#22336174 # https://docs.djangoproject.com/en/1.10/topics/logging/#disabling-logging-configuration LOGGING_CONFIG = None @property def LOGGING(self): config = { 'version': 1, 'disable_existing_loggers': True, 'formatters': self.formatters, 'filters': self.filters, 'handlers': self.handlers, 'loggers': self.loggers, } import logging.config logging.config.dictConfig(config) return config @property def handlers(self): handlers = {} handlers['default'] = { 'level': self.LOG_LEVEL, 'class': 'logging.StreamHandler', 'formatter': 'default' } if self.LOG_FILE: handlers['default']['class'] = 'logging.FileHandler' handlers['default']['filename'] = self.LOG_FILE handlers['default']['encoding'] = 'utf-8' handlers['mail_admins'] = { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } return handlers @property def loggers(self): loggers = {} loggers[''] = { 'handlers': ['default'], 'level': self.LOG_LEVEL, 'propagate': True, } loggers['rq.worker'] = { 'handlers': ['default'], 'level': self.LOG_LEVEL, 'propagate': False, } loggers['requests.packages.urllib3'] = { 'handlers': ['default'], 'level': self.LOG_LEVEL, 'propagate': False, } loggers['django'] = { 'handlers': ['default'], 'level': self.DJANGO_LOG_LEVEL, 'propagate': False, } if self.EXTRA_LOGGING: try: for module, level in self.EXTRA_LOGGING: loggers[module] = { 'handlers': ['default'], 'level': level, 'propagate': False, } except Exception as exc: import sys sys.stderr.write(exc) return loggers @property def formatters(self): formatters_config = { 'default': { 'format': get('LOG_FORMATTER_FORMAT', '[%(asctime)s] %(levelname)s %(name)s-%(lineno)s %(message)s') } } formatter_class = get('LOG_FORMATTER_CLASS') if formatter_class: formatters_config['default']['()'] = formatter_class extra_fields = get('LOG_FORMATTER_EXTRA_FIELDS') if extra_fields: formatters_config['default']['extra_fields'] = extra_fields return formatters_config @property def filters(self): return { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', } }
class LogsMixin(object): '''Django Logging configuration''' @property def LOG_LEVEL(self): pass @property def DJANGO_LOG_LEVEL(self): pass @property def LOG_FILE(self): pass @property def EXTRA_LOGGING(self): ''' lista modulos con los distintos niveles a logear y su nivel de debug Por ejemplo: [Logs] EXTRA_LOGGING = oscar.paypal:DEBUG, django.db:INFO ''' pass @property def LOGGING(self): pass @property def handlers(self): pass @property def loggers(self): pass @property def formatters(self): pass @property def filters(self): pass
19
2
13
2
11
1
2
0.12
1
1
0
0
9
0
9
9
148
27
108
32
87
13
55
22
43
4
1
3
16
1,792
APSL/django-kaio
APSL_django-kaio/kaio/mixins/cms.py
kaio.mixins.cms.CMSMixin
class CMSMixin(object): CMS_SEO_FIELDS = True CMS_REDIRECTS = True CMS_SOFTROOT = False CMS_TEMPLATE_INHERITANCE = True CMS_MENU_TITLE_OVERWRITE = True CMS_USE_TINYMCE = False CMS_PERMISSION = True @property def CMS_LANGUAGES(self): langs_list = [{ 'code': code, 'name': name, 'hide_untranslated': code == self.LANGUAGE_CODE, 'redirect_on_fallback': not (code == self.LANGUAGE_CODE), } for code, name in self.LANGUAGES] return { self.SITE_ID: langs_list, 'default': { 'fallbacks': [self.LANGUAGE_CODE, ] } }
class CMSMixin(object): @property def CMS_LANGUAGES(self): pass
3
0
14
1
13
0
1
0
1
0
0
0
1
0
1
1
25
3
22
11
19
0
11
10
9
1
1
0
1
1,793
APSL/django-kaio
APSL_django-kaio/kaio/options.py
kaio.options.Option
class Option(object): """Option Object""" def __init__(self, value=None, section=None, default_value=None): self.value = value self.section = section self.default_value = default_value def __repr__(self): msg = u'Option(value=%r, section=%r, default=%r)' return msg % (self.value, self.section, self.default_value) def get_value_or_default(self): if self.value is not None: return self.value return self.default_value
class Option(object): '''Option Object''' def __init__(self, value=None, section=None, default_value=None): pass def __repr__(self): pass def get_value_or_default(self): pass
4
1
4
0
4
0
1
0.08
1
0
0
0
3
3
3
3
16
3
12
8
8
1
12
8
8
2
1
1
4
1,794
APSL/django-kaio
APSL_django-kaio/kaio/mixins/celeryconf.py
kaio.mixins.celeryconf.CeleryMixin
class CeleryMixin(object): """Celery APSL Custom mixin""" CELERY_DISABLE_RATE_LIMITS = True CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' def _redis_available(self): try: import redis # noqa: F401 except ImportError: return False if not self.REDIS_PORT or not self.REDIS_HOST: return False return True @property def CELERY_DEFAULT_QUEUE(self): return get('CELERY_DEFAULT_QUEUE', 'celery') @property def CELERY_RESULT_BACKEND(self): """Redis result backend config""" # allow specify directly configured = get('CELERY_RESULT_BACKEND', None) if configured: return configured if not self._redis_available(): return None host, port = self.REDIS_HOST, self.REDIS_PORT if host and port: return "redis://{host}:{port}/{db}".format( host=host, port=port, db=self.CELERY_REDIS_RESULT_DB, ) @property def CELERY_IGNORE_RESULT(self): """Whether to store the task return values or not (tombstones)""" return get('CELERY_IGNORE_RESULT', False) @property def CELERY_RESULT_EXPIRES(self): return get('CELERY_RESULT_EXPIRES', 86400) # 1 day in seconds @property def CELERY_MAX_CACHED_RESULTS(self): """This is the total number of results to cache before older results are evicted. The default is 5000.""" return get('CELERY_MAX_CACHED_RESULTS', 5000) @property def CELERY_CACHE_BACKEND(self): return get('CELERY_CACHE_BACKEND', 'default') @property def CELERY_ALWAYS_EAGER(self): return get('CELERY_ALWAYS_EAGER', False) @property def CELERY_EAGER_PROPAGATES_EXCEPTIONS(self): return get('CELERY_EAGER_PROPAGATES_EXCEPTIONS', True) @property def CELERY_REDIS_RESULT_DB(self): try: return int(get('CELERY_REDIS_RESULT_DB', 0)) except Exception: return 0 @property def CELERY_REDIS_BROKER_DB(self): try: return int(get('CELERY_REDIS_BROKER_DB', 0)) except ValueError: return 0 @property def RABBITMQ_HOST(self): return get('RABBITMQ_HOST', 'localhost') @property def RABBITMQ_PORT(self): return get('RABBITMQ_PORT', 5672) @property def RABBITMQ_USER(self): return get('RABBITMQ_USER', 'guest') @property def RABBITMQ_PASSWD(self): return get('RABBITMQ_PASSWD', 'guest') @property def RABBITMQ_VHOST(self): return get('RABBITMQ_VHOST', '/') @property def BROKER_TYPE(self): """Custom setting allowing switch between rabbitmq, redis""" broker_type = get('BROKER_TYPE', DEFAULT_BROKER_TYPE) if broker_type not in SUPPORTED_BROKER_TYPES: log.warn("Specified BROKER_TYPE {} not supported. Backing to default {}".format( broker_type, DEFAULT_BROKER_TYPE)) return DEFAULT_BROKER_TYPE else: return broker_type @property def BROKER_URL(self): """Sets BROKER_URL depending on redis or rabbitmq settings""" # also allow specify broker_url broker_url = get('BROKER_URL', None) if broker_url: log.info("Using BROKER_URL setting: {}".format(broker_url)) return broker_url redis_available = self._redis_available() broker_type = self.BROKER_TYPE if broker_type == 'redis' and not redis_available: log.warn("Choosed broker type is redis, but redis not available. \ Check redis package, and REDIS_HOST, REDIS_PORT settings") if broker_type == 'redis' and redis_available: return 'redis://{host}:{port}/{db}'.format( host=self.REDIS_HOST, port=self.REDIS_PORT, db=self.CELERY_REDIS_BROKER_DB) elif broker_type == 'rabbitmq': return 'amqp://{user}:{passwd}@{host}:{port}/{vhost}'.format( user=self.RABBITMQ_USER, passwd=self.RABBITMQ_PASSWD, host=self.RABBITMQ_HOST, port=self.RABBITMQ_PORT, vhost=self.RABBITMQ_VHOST) else: return DEFAULT_BROKER_URL
class CeleryMixin(object): '''Celery APSL Custom mixin''' def _redis_available(self): pass @property def CELERY_DEFAULT_QUEUE(self): pass @property def CELERY_RESULT_BACKEND(self): '''Redis result backend config''' pass @property def CELERY_IGNORE_RESULT(self): '''Whether to store the task return values or not (tombstones)''' pass @property def CELERY_RESULT_EXPIRES(self): pass @property def CELERY_MAX_CACHED_RESULTS(self): '''This is the total number of results to cache before older results are evicted. The default is 5000.''' pass @property def CELERY_CACHE_BACKEND(self): pass @property def CELERY_ALWAYS_EAGER(self): pass @property def CELERY_EAGER_PROPAGATES_EXCEPTIONS(self): pass @property def CELERY_REDIS_RESULT_DB(self): pass @property def CELERY_REDIS_BROKER_DB(self): pass @property def RABBITMQ_HOST(self): pass @property def RABBITMQ_PORT(self): pass @property def RABBITMQ_USER(self): pass @property def RABBITMQ_PASSWD(self): pass @property def RABBITMQ_VHOST(self): pass @property def BROKER_TYPE(self): '''Custom setting allowing switch between rabbitmq, redis''' pass @property def BROKER_URL(self): '''Sets BROKER_URL depending on redis or rabbitmq settings''' pass
36
6
6
1
5
1
2
0.1
1
4
0
0
18
2
18
18
145
29
107
47
70
11
73
28
53
5
1
1
30
1,795
APSL/django-kaio
APSL_django-kaio/kaio/mixins/cache.py
kaio.mixins.cache.CachesMixin
class CachesMixin(object): # Settings for default cache. @property def CACHE_TYPE(self): return get('CACHE_TYPE', 'locmem') @property def REDIS_HOST(self): return get('REDIS_HOST', 'localhost') @property def REDIS_PORT(self): return get('REDIS_PORT', 6379) @property def CACHE_REDIS_DB(self): return get('CACHE_REDIS_DB', 2) @property def CACHE_REDIS_PASSWORD(self): return get('CACHE_REDIS_PASSWORD', None) @property def CACHE_PREFIX(self): return get('CACHE_PREFIX', self.APP_SLUG) @property def CACHE_TIMEOUT(self): return get('CACHE_TIMEOUT', 3600) @property def CACHE_MAX_ENTRIES(self): return get('CACHE_MAX_ENTRIES', 10000) @property def DEFAULT_CACHE(self): if self.CACHE_TYPE == 'redis': CACHE = { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://%s:%s/%s' % (self.REDIS_HOST, self.REDIS_PORT, self.CACHE_REDIS_DB), 'KEY_PREFIX': self.CACHE_PREFIX, 'TIMEOUT': self.CACHE_TIMEOUT, 'OPTIONS': { "CLIENT_CLASS": "django_redis.client.DefaultClient", 'MAX_ENTRIES': self.CACHE_MAX_ENTRIES, }, } if self.CACHE_REDIS_PASSWORD is not None: CACHE['OPTIONS']['PASSWORD'] = self.CACHE_REDIS_PASSWORD elif self.CACHE_TYPE == 'locmem': CACHE = { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'CACHE_PREFIX': self.CACHE_PREFIX, 'LOCATION': 'unique-key-apsl' } else: CACHE = { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } return CACHE # Settings for session cache. # You must set SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # (or cached_db). By default use almost same settings as default cache. @property def SESSION_CACHE_TYPE(self): return get('SESSION_CACHE_TYPE', self.CACHE_TYPE) @property def SESSION_REDIS_HOST(self): return get('SESSION_REDIS_HOST', self.REDIS_HOST) @property def SESSION_REDIS_PORT(self): return get('SESSION_REDIS_PORT', self.REDIS_PORT) @property def SESSION_CACHE_REDIS_DB(self): return get('SESSION_CACHE_REDIS_DB', 3) @property def SESSION_CACHE_REDIS_PASSWORD(self): return get('SESSION_CACHE_REDIS_PASSWORD', self.CACHE_REDIS_PASSWORD) @property def SESSION_CACHE_PREFIX(self): return get('SESSION_CACHE_PREFIX', '%s_session' % self.CACHE_PREFIX) @property def SESSION_CACHE_TIMEOUT(self): return get('SESSION_CACHE_TIMEOUT', None) @property def SESSION_CACHE_MAX_ENTRIES(self): return get('SESSION_CACHE_MAX_ENTRIES', 1000000) @property def SESSION_CACHE(self): # Support for Redis only if self.SESSION_CACHE_TYPE != 'redis' or self.SESSION_ENGINE not in ( 'django.contrib.sessions.backends.cache', 'django.contrib.sessions.backends.cached_db'): return CACHE = { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://%s:%s/%s' % (self.SESSION_REDIS_HOST, self.SESSION_REDIS_PORT, self.SESSION_CACHE_REDIS_DB), 'KEY_PREFIX': self.SESSION_CACHE_PREFIX, 'TIMEOUT': self.SESSION_CACHE_TIMEOUT, 'OPTIONS': { "CLIENT_CLASS": "django_redis.client.DefaultClient", 'MAX_ENTRIES': self.SESSION_CACHE_MAX_ENTRIES, }, } if self.SESSION_CACHE_REDIS_PASSWORD is not None: CACHE['OPTIONS']['PASSWORD'] = self.SESSION_CACHE_REDIS_PASSWORD return CACHE @property def SESSION_CACHE_ALIAS(self): return get('SESSION_CACHE_ALIAS', 'session') # Main cache settings. @property def CACHES(self): caches = {'default': self.DEFAULT_CACHE} session_cache = self.SESSION_CACHE if session_cache: caches[self.SESSION_CACHE_ALIAS] = session_cache return caches
class CachesMixin(object): @property def CACHE_TYPE(self): pass @property def REDIS_HOST(self): pass @property def REDIS_PORT(self): pass @property def CACHE_REDIS_DB(self): pass @property def CACHE_REDIS_PASSWORD(self): pass @property def CACHE_PREFIX(self): pass @property def CACHE_TIMEOUT(self): pass @property def CACHE_MAX_ENTRIES(self): pass @property def DEFAULT_CACHE(self): pass @property def SESSION_CACHE_TYPE(self): pass @property def SESSION_REDIS_HOST(self): pass @property def SESSION_REDIS_PORT(self): pass @property def SESSION_CACHE_REDIS_DB(self): pass @property def SESSION_CACHE_REDIS_PASSWORD(self): pass @property def SESSION_CACHE_PREFIX(self): pass @property def SESSION_CACHE_TIMEOUT(self): pass @property def SESSION_CACHE_MAX_ENTRIES(self): pass @property def SESSION_CACHE_TYPE(self): pass @property def SESSION_CACHE_ALIAS(self): pass @property def CACHES(self): pass
41
0
5
0
4
0
1
0.06
1
0
0
0
20
0
20
20
141
27
108
45
67
6
56
25
35
4
1
2
26
1,796
APSL/django-kaio
APSL_django-kaio/kaio/mixins/whitenoise.py
kaio.mixins.whitenoise.WhiteNoiseMixin
class WhiteNoiseMixin(object): """Settings for http://whitenoise.evans.io version 3""" @property def ENABLE_WHITENOISE(self): enabled = get('ENABLE_WHITENOISE', False) if enabled: try: import whitenoise # noqa: F401 self._add_whitenoise_to_installed_apps() self._add_whitenoise_to_middleware() except ImportError: return False return enabled @property def WHITENOISE_AUTOREFRESH(self): return get('WHITENOISE_AUTOREFRESH', True) @property def WHITENOISE_USE_FINDERS(self): return get('WHITENOISE_USE_FINDERS', True) def _add_whitenoise_to_installed_apps(self): if 'whitenoise.runserver_nostatic' not in self.INSTALLED_APPS: index = self.INSTALLED_APPS.index('django.contrib.staticfiles') self.INSTALLED_APPS.insert(index, 'whitenoise.runserver_nostatic') def _add_whitenoise_to_middleware(self): middlewares_settings = ( 'MIDDLEWARE', # django >= 1.10 'MIDDLEWARE_CLASSES', # django < 1.10 ) for middleware_setting in middlewares_settings: middlewares = getattr(self, middleware_setting, None) if middlewares is not None: if 'whitenoise.middleware.WhiteNoiseMiddleware' not in middlewares: try: index = middlewares.index('django.middleware.security.SecurityMiddleware') + 1 except ValueError: index = 0 middlewares.insert(index, 'whitenoise.middleware.WhiteNoiseMiddleware')
class WhiteNoiseMixin(object): '''Settings for http://whitenoise.evans.io version 3''' @property def ENABLE_WHITENOISE(self): pass @property def WHITENOISE_AUTOREFRESH(self): pass @property def WHITENOISE_USE_FINDERS(self): pass def _add_whitenoise_to_installed_apps(self): pass def _add_whitenoise_to_middleware(self): pass
9
1
6
0
6
1
2
0.11
1
2
0
0
5
0
5
5
42
5
36
16
26
4
30
13
23
5
1
4
12
1,797
APSL/django-kaio
APSL_django-kaio/kaio/mixins/database.py
kaio.mixins.database.DatabasesMixin
class DatabasesMixin(object): @staticmethod def get_engine(prefix): """ Retrieve the database engine. Only change the full engine string if there is no «backends» in it. """ engine = get('{}DATABASE_ENGINE'.format(prefix), 'sqlite3') if 'backends' in engine: return engine return 'django.db.backends.' + engine def get_databases(self, prefix=''): databases = { 'default': { 'ENGINE': self.get_engine(prefix), 'NAME': get('{}DATABASE_NAME'.format(prefix), '{}db.sqlite'.format(prefix.lower())), 'USER': get('{}DATABASE_USER'.format(prefix), None), 'PASSWORD': get('{}DATABASE_PASSWORD'.format(prefix), ''), 'HOST': get('{}DATABASE_HOST'.format(prefix), ''), 'PORT': get('{}DATABASE_PORT'.format(prefix), ''), 'CONN_MAX_AGE': get('{}DATABASE_CONN_MAX_AGE'.format(prefix), 0), 'TEST': { 'NAME': get('{}DATABASE_NAME'.format(prefix), None), } } } options = get('DATABASE_OPTIONS_OPTIONS') if options: databases['default']['OPTIONS'] = {'options': options} return databases def DATABASES(self): return self.get_databases()
class DatabasesMixin(object): @staticmethod def get_engine(prefix): ''' Retrieve the database engine. Only change the full engine string if there is no «backends» in it. ''' pass def get_databases(self, prefix=''): pass def DATABASES(self): pass
5
1
11
1
9
1
2
0.14
1
0
0
0
2
0
3
3
37
5
28
8
23
4
14
7
10
2
1
1
5
1,798
APSL/django-kaio
APSL_django-kaio/kaio/management/commands/generate_ini.py
kaio.management.commands.generate_ini.Command
class Command(NoArgsCommand): help = """Print a .ini with default values in stdout.""" requires_model_validation = False def handle_noargs(self, **options): # Inspired by Postfix's "postconf -n". from django.conf import settings # Because settings are imported lazily, we need to explicitly load them. settings._setup() user_settings = module_to_dict(settings._wrapped) opts = Options() pformat = "%-25s = %s" puts('') for section in opts.sections: puts(colored.green("[%s]" % section)) for key, kaio_value in opts.items(section): keycolor = colored.magenta(key) if key in user_settings: keycolor = colored.blue(key) default_value = opts.options[key].default_value value = kaio_value or default_value if sys.version_info[0] < 3: value = unicode(value).encode('utf8') # noqa: F821 else: value = str(value) try: puts(pformat % (keycolor, value)) except Exception as e: raise e puts('') def handle(self, **options): return self.handle_noargs(**options)
class Command(NoArgsCommand): def handle_noargs(self, **options): pass def handle_noargs(self, **options): pass
3
0
17
3
13
2
4
0.1
1
2
0
0
2
0
2
2
40
9
29
15
25
3
28
14
24
6
1
3
7
1,799
APSL/django-kaio
APSL_django-kaio/kaio/options.py
kaio.options.Options
class Options(object): """Option Parser. By now based on ini files""" # Options that will not be interpolated. RAW_OPTIONS = {'LOG_FORMATTER_FORMAT'} def __init__(self): """Parse initial options""" self.config = ConfigParser() self.config_file = None self._read_config() self.defaults = {} self.options = {} self._parse_options() @classmethod def _is_raw_option(cls, option): return option.upper() in cls.RAW_OPTIONS def _conf_path(self): """Search .ini file from current directory (included) up to "/" (excluded)""" current = abspath(curdir) while current != "/": filename = join(current, DEFAULT_CONF_NAME) if isfile(filename): return filename current = abspath(join(current, pardir)) # If the .ini file doesn't exist returns an empty filename so default values are used return '' def _read_config(self): try: self.config_file = self.config.read(self._conf_path())[0] except IndexError: self.config_file = abspath(join(curdir, DEFAULT_CONF_NAME)) def _cast_value(self, value): """Support: int, bool, str""" try: value = int(value) except ValueError: if value.lower().strip() in ["true", "t", "1", "yes"]: value = True elif value.lower().strip() in ["false", "f", "no", "0"]: value = False return value def _parse_options(self): """Parse .ini file and set options in self.options""" for section in self.config.sections(): for option in self.config.options(section): raw = self._is_raw_option(option) value = self.config.get(section=section, option=option, raw=raw) value = self._cast_value(value) self.options[option.upper()] = Option(value, section) def __iter__(self): """Return an iterator of options""" return (o for o in self.options.items()) @property def sections(self): """Get defined sections""" return set(o.section for k, o in self.options.items()) def items(self, section=None): """Iterate items of a section in format (name, value)""" if section: return ((k, o.value) for k, o in self.options.items() if o.section == section) else: return ((k, o.value) for k, o in self.options.items()) def keys(self, section=None): """Returns all configured option names (keys)""" return [k for k, v in self.items(section)] def write(self): """Save all defined options""" for name, option in self.options.items(): if sys.version_info[0] < 3: try: value = unicode(option.value) # noqa except UnicodeDecodeError: value = unicode(option.value, 'utf-8') # noqa else: value = str(value) try: self.config.set(section=option.section, option=name.upper(), value=value) except NoSectionError: self.config.add_section(option.section) self.config.set(section=option.section, option=name, value=value) self._write_file() def _write_file(self): import codecs with codecs.open(self.config_file, 'w', "utf-8") as config_file: self.config.write(config_file) def set(self, name, value, section=DEFAULT_SECTION): name = name.strip() if type(value) == str: if sys.version_info[0] < 3: value = value.decode('utf-8') value = value.strip() if name in self.options: self.options[name].value = value else: self.options[name] = Option(value, section) def get(self, name, default=None, section=DEFAULT_SECTION): """Returns value, and also saves the requested default If value exists in environ, return environ value""" name = name.strip() try: self.options[name].default_value = default if not self.options[name].section: self.options[name].section = section except KeyError: self.options[name] = Option(value=None, section=section, default_value=default) try: value = self._cast_value(os.environ[name].strip()) return value except KeyError: if self.options[name].value is not None: return self.options[name].value else: return default
class Options(object): '''Option Parser. By now based on ini files''' def __init__(self): '''Parse initial options''' pass @classmethod def _is_raw_option(cls, option): pass def _conf_path(self): '''Search .ini file from current directory (included) up to "/" (excluded)''' pass def _read_config(self): pass def _cast_value(self, value): '''Support: int, bool, str''' pass def _parse_options(self): '''Parse .ini file and set options in self.options''' pass def __iter__(self): '''Return an iterator of options''' pass @property def sections(self): '''Get defined sections''' pass def items(self, section=None): '''Iterate items of a section in format (name, value)''' pass def keys(self, section=None): '''Returns all configured option names (keys)''' pass def write(self): '''Save all defined options''' pass def _write_file(self): pass def set(self, name, value, section=DEFAULT_SECTION): pass def get(self, name, default=None, section=DEFAULT_SECTION): '''Returns value, and also saves the requested default If value exists in environ, return environ value''' pass
17
11
8
0
7
1
2
0.16
1
11
1
0
13
4
14
14
130
18
98
35
80
16
91
30
75
5
1
3
34