def plot(self, limit=5, anatomical=None): """ Create a quick plot of self.data. Will plot each image separately Args: limit: max number of images to return anatomical: nifti image or file name to overlay """ if anatomical is not None: if not isinstance(anatomical, nib.Nifti1Image): if type(anatomical) is str: anatomical = nib.load(anatomical) else: raise ValueError("anatomical is not a nibabel instance") else: anatomical = get_anatomical() if self.data.ndim == 1: plot_stat_map(self.to_nifti(), anatomical, cut_coords=range(-40, 50, 10), display_mode='z', black_bg=True, colorbar=True, draw_cross=False) else: for i in xrange(self.data.shape[0]): if i < limit: # plot_roi(self.nifti_masker.inverse_transform(self.data[i,:]), self.anatomical) # plot_stat_map(self.nifti_masker.inverse_transform(self.data[i,:]), plot_stat_map(self[i].to_nifti(), anatomical, cut_coords=range(-40, 50, 10), display_mode='z', black_bg=True, colorbar=True, draw_cross=False)
def test_singleton_ax_dim(): for axis, direction in enumerate("xyz"): shape = [5, 6, 7] shape[axis] = 1 img = nibabel.Nifti1Image(np.ones(shape), np.eye(4)) plot_stat_map(img, None, display_mode=direction) plt.close()
def test_plotting_functions_with_cmaps(): img = load_mni152_template() cmaps = ['Paired', 'Set1', 'Set2', 'Set3'] for cmap in cmaps: plot_roi(img, cmap=cmap, colorbar=True) plot_stat_map(img, cmap=cmap, colorbar=True) plot_glass_brain(img, cmap=cmap, colorbar=True) if LooseVersion(matplotlib.__version__) >= LooseVersion('2.0.0'): plot_stat_map(img, cmap='viridis', colorbar=True) plt.close()
def test_plot_stat_map_with_nans(): img = _generate_img() data = img.get_data() data[6, 5, 1] = np.nan data[1, 5, 2] = np.nan data[1, 3, 2] = np.nan data[6, 5, 2] = np.inf img = nibabel.Nifti1Image(data, mni_affine) plot_epi(img) plot_stat_map(img) plot_glass_brain(img)
def test_plot_functions(): img = _generate_img() # smoke-test for each plotting function with default arguments for plot_func in [plot_anat, plot_img, plot_stat_map, plot_epi, plot_glass_brain]: with tempfile.NamedTemporaryFile(suffix=".png") as fp: plot_func(img, output_file=fp.name) # test for bad input arguments (cf. #510) ax = plt.subplot(111, rasterized=True) with tempfile.NamedTemporaryFile(suffix=".png") as fp: plot_stat_map(img, symmetric_cbar=True, output_file=fp.name, axes=ax, vmax=np.nan) plt.close()
def test_save_plot(): img = _generate_img() kwargs_list = [{}, {'display_mode': 'x', 'cut_coords': 3}] for kwargs in kwargs_list: with tempfile.NamedTemporaryFile(suffix='.png') as fp: display = plot_stat_map(img, output_file=fp.name, **kwargs) assert_true(display is None) display = plot_stat_map(img, **kwargs) with tempfile.NamedTemporaryFile(suffix='.png') as fp: display.savefig(fp.name)
def test_plotting_functions_with_cmaps(): img = load_mni152_template() # some cmaps such as 'viridis' (the new default in 2.0), 'magma', 'plasma', # and 'inferno' are not supported for older matplotlib version from < 1.5 cmaps = ['Paired', 'Set1', 'Set2', 'Set3'] for cmap in cmaps: plot_roi(img, cmap=cmap, colorbar=True) plot_stat_map(img, cmap=cmap, colorbar=True) plot_glass_brain(img, cmap=cmap, colorbar=True) if LooseVersion(matplotlib.__version__) >= LooseVersion('2.0.0'): plot_stat_map(img, cmap='viridis', colorbar=True) plt.close()
def test_save_plot(): mp.use('template', warn=False) import matplotlib.pyplot as plt plt.switch_backend('template') img = _generate_img() kwargs_list = [{}, {'display_mode': 'x', 'cut_coords': 3}] for kwargs in kwargs_list: with tempfile.TemporaryFile(suffix='.png') as fp: display = plot_stat_map(img, output_file=fp.name, **kwargs) assert_true(display is None) display = plot_stat_map(img, **kwargs) with tempfile.TemporaryFile(suffix='.png') as fp: display.savefig(fp.name)
def test_plotting_functions_with_nans_in_bg_img(): bg_img = _generate_img() bg_data = bg_img.get_data() bg_data[6, 5, 1] = np.nan bg_data[1, 5, 2] = np.nan bg_data[1, 3, 2] = np.nan bg_data[6, 5, 2] = np.inf bg_img = nibabel.Nifti1Image(bg_data, mni_affine) plot_anat(bg_img) # test with plot_roi passing background image which contains nans values # in it roi_img = _generate_img() plot_roi(roi_img=roi_img, bg_img=bg_img) stat_map_img = _generate_img() plot_stat_map(stat_map_img=stat_map_img, bg_img=bg_img) plt.close()
def test_save_plot(): img = _generate_img() kwargs_list = [{}, {'display_mode': 'x', 'cut_coords': 3}] for kwargs in kwargs_list: filename = tempfile.mktemp(suffix='.png') try: display = plot_stat_map(img, output_file=filename, **kwargs) finally: os.remove(filename) assert_true(display is None) display = plot_stat_map(img, **kwargs) filename = tempfile.mktemp(suffix='.png') try: display.savefig(filename) finally: os.remove(filename)
def test_plot_functions(): mp.use('template', warn=False) import matplotlib.pyplot as plt plt.switch_backend('template') img = _generate_img() # smoke-test for each plotting function with default arguments for plot_func in [plot_anat, plot_img, plot_stat_map, plot_epi, plot_glass_brain]: with tempfile.TemporaryFile(suffix='.png') as fp: plot_func(img, output_file=fp.name) # test for bad input arguments (cf. #510) ax = plt.subplot(111, rasterized=True) with tempfile.TemporaryFile(suffix='.png') as fp: plot_stat_map( img, symmetric_cbar=True, output_file=fp.name, axes=ax, vmax=np.nan) plt.close()
def test_plot_functions(): img = _generate_img() # smoke-test for each plotting function with default arguments for plot_func in [plot_anat, plot_img, plot_stat_map, plot_epi, plot_glass_brain]: filename = tempfile.mktemp(suffix='.png') try: plot_func(img, output_file=filename) finally: os.remove(filename) # test for bad input arguments (cf. #510) ax = plt.subplot(111, rasterized=True) filename = tempfile.mktemp(suffix='.png') try: plot_stat_map(img, symmetric_cbar=True, output_file=filename, axes=ax, vmax=np.nan) finally: os.remove(filename) plt.close()
def test_plot_stat_map_threshold_for_affine_with_rotation(): # threshold was not being applied when affine has a rotation # see https://github.com/nilearn/nilearn/issues/599 for more details data = np.random.randn(10, 10, 10) # matrix with rotation affine = np.array([[-3.0, 1.0, 0.0, 1.0], [-1.0, -3.0, 0.0, -2.0], [0.0, 0.0, 3.0, 3.0], [0.0, 0.0, 0.0, 1.0]]) img = nibabel.Nifti1Image(data, affine) display = plot_stat_map(img, bg_img=None, threshold=1e6, display_mode="z", cut_coords=1) # Next two lines retrieve the numpy array from the plot ax = list(display.axes.values())[0].ax plotted_array = ax.images[0].get_array() # Given the high threshold the array should be entirely masked assert_true(plotted_array.mask.all())
def test_plot_stat_map_threshold_for_uint8(): # mask was applied in [-threshold, threshold] which is problematic # for uint8 data. See https://github.com/nilearn/nilearn/issues/611 # for more details data = 10 * np.ones((10, 10, 10), dtype='uint8') affine = np.eye(4) img = nibabel.Nifti1Image(data, affine) threshold = np.array(5, dtype='uint8') display = plot_stat_map(img, bg_img=None, threshold=threshold, display_mode='z', cut_coords=1) # Next two lines retrieve the numpy array from the plot ax = list(display.axes.values())[0].ax plotted_array = ax.images[0].get_array() # Make sure that no data is masked assert_equal(plotted_array.mask.sum(), 0)
def test_plot_stat_map_threshold_for_uint8(): # mask was applied in [-threshold, threshold] which is problematic # for uint8 data. See https://github.com/nilearn/nilearn/issues/611 # for more details data = 10 * np.ones((10, 10, 10), dtype="uint8") # Having a zero minimum value is important to reproduce # https://github.com/nilearn/nilearn/issues/762 data[0, 0, 0] = 0 affine = np.eye(4) img = nibabel.Nifti1Image(data, affine) threshold = np.array(5, dtype="uint8") display = plot_stat_map(img, bg_img=None, threshold=threshold, display_mode="z", cut_coords=[0]) # Next two lines retrieve the numpy array from the plot ax = list(display.axes.values())[0].ax plotted_array = ax.images[0].get_array() # Make sure that there is one value masked assert_equal(plotted_array.mask.sum(), 1) # Make sure that the value masked is in the corner. Note that the # axis orientation seem to be flipped, hence (0, 0) -> (-1, 0) assert_true(plotted_array.mask[-1, 0])
def test_plot_stat_map_threshold_for_affine_with_rotation(): # threshold was not being applied when affine has a rotation # see https://github.com/nilearn/nilearn/issues/599 for more details data = np.random.randn(10, 10, 10) # matrix with rotation affine = np.array([[-3., 1., 0., 1.], [-1., -3., 0., -2.], [0., 0., 3., 3.], [0., 0., 0., 1.]]) img = nibabel.Nifti1Image(data, affine) display = plot_stat_map(img, bg_img=None, threshold=1e6, display_mode='z', cut_coords=1) # Next two lines retrieve the numpy array from the plot ax = list(display.axes.values())[0].ax plotted_array = ax.images[0].get_array() # Given the high threshold the array should be entirely masked assert_true(plotted_array.mask.all()) # Save execution time and memory plt.close()
def test_outlier_cut_coords(): """ Test to plot a subset of a large set of cuts found for a small area.""" bg_img = load_mni152_template() data = np.zeros((79, 95, 79)) affine = np.array([[-2., 0., 0., 78.], [0., 2., 0., -112.], [0., 0., 2., -70.], [0., 0., 0., 1.]]) # Color a cube around a corner area: x, y, z = 20, 22, 60 x_map, y_map, z_map = coord_transform(x, y, z, np.linalg.inv(affine)) data[int(x_map) - 1:int(x_map) + 1, int(y_map) - 1:int(y_map) + 1, int(z_map) - 1:int(z_map) + 1] = 1 img = nibabel.Nifti1Image(data, affine) cuts = find_cut_slices(img, n_cuts=20, direction='z') p = plot_stat_map(img, display_mode='z', cut_coords=cuts[-4:], bg_img=bg_img)
def test_outlier_cut_coords(): """ Test to plot a subset of a large set of cuts found for a small area.""" bg_img = load_mni152_template() data = np.zeros((79, 95, 79)) affine = np.array([[ -2., 0., 0., 78.], [ 0., 2., 0., -112.], [ 0., 0., 2., -70.], [ 0., 0., 0., 1.]]) # Color a cube around a corner area: x, y, z = 20, 22, 60 x_map, y_map, z_map = coord_transform(x, y, z, np.linalg.inv(affine)) data[int(x_map) - 1:int(x_map) + 1, int(y_map) - 1:int(y_map) + 1, int(z_map) - 1:int(z_map) + 1] = 1 img = nibabel.Nifti1Image(data, affine) cuts = find_cut_slices(img, n_cuts=20, direction='z') p = plot_stat_map(img, display_mode='z', cut_coords=cuts[-4:], bg_img=bg_img)
def test_plot_stat_map_threshold_for_uint8(): # mask was applied in [-threshold, threshold] which is problematic # for uint8 data. See https://github.com/nilearn/nilearn/issues/611 # for more details data = 10 * np.ones((10, 10, 10), dtype='uint8') # Having a zero minimum value is important to reproduce # https://github.com/nilearn/nilearn/issues/762 data[0, 0, 0] = 0 affine = np.eye(4) img = nibabel.Nifti1Image(data, affine) threshold = np.array(5, dtype='uint8') display = plot_stat_map(img, bg_img=None, threshold=threshold, display_mode='z', cut_coords=[0]) # Next two lines retrieve the numpy array from the plot ax = list(display.axes.values())[0].ax plotted_array = ax.images[0].get_array() # Make sure that there is one value masked assert_equal(plotted_array.mask.sum(), 1) # Make sure that the value masked is in the corner. Note that the # axis orientation seem to be flipped, hence (0, 0) -> (-1, 0) assert_true(plotted_array.mask[-1, 0]) # Save execution time and memory plt.close()
def test_plot_stat_map(): img = _generate_img() plot_stat_map(img, cut_coords=(80, -120, -60)) # Smoke test coordinate finder, with and without mask masked_img = nibabel.Nifti1Image( np.ma.masked_equal(img.get_data(), 0), mni_affine) plot_stat_map(masked_img, display_mode='x') plot_stat_map(img, display_mode='y', cut_coords=2) # 'yx' display_mode plot_stat_map(img, display_mode='yx') # regression test #510 data = np.zeros((91, 109, 91)) aff = np.eye(4) new_img = nibabel.Nifti1Image(data, aff) plot_stat_map(new_img, threshold=1000, colorbar=True) rng = np.random.RandomState(42) data = rng.randn(91, 109, 91) new_img = nibabel.Nifti1Image(data, aff) plot_stat_map(new_img, threshold=1000, colorbar=True) # Save execution time and memory plt.close()
def test_plot_stat_map(): mp.use('template', warn=False) import matplotlib.pyplot as plt plt.switch_backend('template') img = _generate_img() plot_stat_map(img, cut_coords=(80, -120, -60)) # Smoke test coordinate finder, with and without mask masked_img = nibabel.Nifti1Image(np.ma.masked_equal(img.get_data(), 0), mni_affine) plot_stat_map(masked_img, display_mode='x') plot_stat_map(img, display_mode='y', cut_coords=2) # 'yx' display_mode plot_stat_map(img, display_mode='yx') # regression test #510 data = np.zeros((91, 109, 91)) aff = np.eye(4) new_img = nibabel.Nifti1Image(data, aff) plot_stat_map(new_img, threshold=1000, colorbar=True) rng = np.random.RandomState(42) data = rng.randn(91, 109, 91) new_img = nibabel.Nifti1Image(data, aff) plot_stat_map(new_img, threshold=1000, colorbar=True)
def test_plot_stat_map(): mp.use('template', warn=False) import matplotlib.pyplot as plt plt.switch_backend('template') img = _generate_img() plot_stat_map(img, cut_coords=(80, -120, -60)) # Smoke test coordinate finder, with and without mask masked_img = nibabel.Nifti1Image( np.ma.masked_equal(img.get_data(), 0), mni_affine) plot_stat_map(masked_img, display_mode='x') plot_stat_map(img, display_mode='y', cut_coords=2) # 'yx' display_mode plot_stat_map(img, display_mode='yx') # regression test #510 data = np.zeros((91, 109, 91)) aff = np.eye(4) new_img = nibabel.Nifti1Image(data, aff) plot_stat_map(new_img, threshold=1000, colorbar=True) rng = np.random.RandomState(42) data = rng.randn(91, 109, 91) new_img = nibabel.Nifti1Image(data, aff) plot_stat_map(new_img, threshold=1000, colorbar=True)
def test_plotting_functions_with_display_mode_tiled(): img = _generate_img() plot_stat_map(img, display_mode='tiled') plot_anat(display_mode='tiled') plot_img(img, display_mode='tiled') plt.close()
def test_singleton_ax_dim(): for axis, direction in enumerate("xyz"): shape = [5, 6, 7] shape[axis] = 1 img = nibabel.Nifti1Image(np.ones(shape), np.eye(4)) plot_stat_map(img, None, display_mode=direction)
data = resampled_nii.get_data() data[data != 0] = 1 if len(data.shape) == 4: data.shape = data.shape[:3] freq_map_data += data return nb.Nifti1Image(freq_map_data, target_nii.get_affine()) if __name__ == '__main__': combined_df = get_images_with_collections_df() print combined_df[['DOI', 'url_collection', 'name_image', 'file']] #restrict to Z-, F-, or T-maps combined_df = combined_df[combined_df['map_type'].isin(["Z","F","T"])] print combined_df["name_collection"].value_counts() dest_dir = "/tmp/neurovault_analysis" target = "/usr/share/fsl/data/standard/MNI152_T1_2mm.nii.gz" download_and_resample(combined_df, dest_dir, target) freq_nii = get_frequency_map(combined_df, dest_dir, target) plot_stat_map(freq_nii, "/usr/share/fsl/data/standard/MNI152_T1_2mm.nii.gz", display_mode="z") freq_nii.to_filename("/tmp/freq_map.nii.gz") plt.show() combined_df.to_csv('%s/metadata.csv' % dest_dir, encoding='utf8')
def test_plotting_functions_with_display_mode_tiled(testdata_3d): img = testdata_3d['img'] plot_stat_map(img, display_mode='tiled') plot_anat(display_mode='tiled') plot_img(img, display_mode='tiled') plt.close()