예제 #1
0
def test_mean_img():
    rng = np.random.RandomState(42)
    data1 = np.zeros((5, 6, 7))
    data2 = rng.rand(5, 6, 7)
    data3 = rng.rand(5, 6, 7, 3)
    affine = np.diag((4, 3, 2, 1))
    img1 = nibabel.Nifti1Image(data1, affine=affine)
    img2 = nibabel.Nifti1Image(data2, affine=affine)
    img3 = nibabel.Nifti1Image(data3, affine=affine)
    for imgs in ([img1, ],
                   [img1, img2],
                   [img2, img1, img2],
                   [img3, img1, img2],  # Mixture of 4D and 3D images
                  ):

        arrays = list()
        # Ground-truth:
        for img in imgs:
            img = img.get_data()
            if img.ndim == 4:
                img = np.mean(img, axis=-1)
            arrays.append(img)
        truth = np.mean(arrays, axis=0)

        mean_img = image.mean_img(imgs)
        assert_array_equal(mean_img.get_affine(), affine)
        assert_array_equal(mean_img.get_data(), truth)

        # Test with files
        with testing.write_tmp_imgs(*imgs) as imgs:
            mean_img = image.mean_img(imgs)
            assert_array_equal(mean_img.get_affine(), affine)
            assert_array_equal(mean_img.get_data(), truth)
예제 #2
0
def test_mean_img():
    rng = np.random.RandomState(42)
    data1 = np.zeros((5, 6, 7))
    data2 = rng.rand(5, 6, 7)
    data3 = rng.rand(5, 6, 7, 3)
    affine = np.diag((4, 3, 2, 1))
    img1 = nibabel.Nifti1Image(data1, affine=affine)
    img2 = nibabel.Nifti1Image(data2, affine=affine)
    img3 = nibabel.Nifti1Image(data3, affine=affine)
    for imgs in (
        [
            img1,
        ],
        [img1, img2],
        [img2, img1, img2],
        [img3, img1, img2],  # Mixture of 4D and 3D images
    ):

        arrays = list()
        # Ground-truth:
        for img in imgs:
            img = img.get_data()
            if img.ndim == 4:
                img = np.mean(img, axis=-1)
            arrays.append(img)
        truth = np.mean(arrays, axis=0)

        mean_img = image.mean_img(imgs)
        assert_array_equal(mean_img.get_affine(), affine)
        assert_array_equal(mean_img.get_data(), truth)

        # Test with files
        with testing.write_tmp_imgs(*imgs) as imgs:
            mean_img = image.mean_img(imgs)
            assert_array_equal(mean_img.get_affine(), affine)
            if X64:
                assert_array_equal(mean_img.get_data(), truth)
            else:
                # We don't really understand but arrays are not
                # exactly equal on 32bit. Given that you can not do
                # much real world data analysis with nilearn on a
                # 32bit machine it is not worth investigating more
                assert_allclose(mean_img.get_data(),
                                truth,
                                rtol=np.finfo(truth.dtype).resolution,
                                atol=0)
예제 #3
0
def test_mean_img():
    rng = np.random.RandomState(42)
    data1 = np.zeros((5, 6, 7))
    data2 = rng.rand(5, 6, 7)
    data3 = rng.rand(5, 6, 7, 3)
    affine = np.diag((4, 3, 2, 1))
    img1 = nibabel.Nifti1Image(data1, affine=affine)
    img2 = nibabel.Nifti1Image(data2, affine=affine)
    img3 = nibabel.Nifti1Image(data3, affine=affine)
    for imgs in ([img1, ],
                   [img1, img2],
                   [img2, img1, img2],
                   [img3, img1, img2],  # Mixture of 4D and 3D images
                  ):

        arrays = list()
        # Ground-truth:
        for img in imgs:
            img = img.get_data()
            if img.ndim == 4:
                img = np.mean(img, axis=-1)
            arrays.append(img)
        truth = np.mean(arrays, axis=0)

        mean_img = image.mean_img(imgs)
        assert_array_equal(mean_img.affine, affine)
        assert_array_equal(mean_img.get_data(), truth)

        # Test with files
        with testing.write_tmp_imgs(*imgs) as imgs:
            mean_img = image.mean_img(imgs)
            assert_array_equal(mean_img.affine, affine)
            if X64:
                assert_array_equal(mean_img.get_data(), truth)
            else:
                # We don't really understand but arrays are not
                # exactly equal on 32bit. Given that you can not do
                # much real world data analysis with nilearn on a
                # 32bit machine it is not worth investigating more
                assert_allclose(mean_img.get_data(), truth,
                                rtol=np.finfo(truth.dtype).resolution,
                                atol=0)
예제 #4
0
def basic_plots():
    """
    Plot and save a mean EPI image and an EPI mask
    :return:
    """
    for input in glob('input/sub*'):
        sub = op.basename(input)
        func = input + '/func/{}_task-oneback_run-01_bold.nii.gz'.format(sub)
        mean = mean_img(func)
        plot_epi(mean).savefig('figures/{}_mean-epi.png'.format(sub))
        mask_img = compute_epi_mask(func)
        mask_img.to_filename('{}_brain-mask.nii.gz'.format(sub))
        plot_roi(mask_img, mean).savefig('figures/{}_brainmask.png'.format(sub))
def get_fc(func_mni_filename, atlas_filename, mask_filename,
           confounds_filename, output_filename, TR, TYPE, FWHM):
    """
    Extract connectivity matrix given atlas and processed fMRI data.
    """
    if FWHM == 0:
        FWHM = None

    confounds = pd.read_csv(confounds_filename, sep='\t')
    global_signal = confounds['GlobalSignal'].values
    FD = confounds['FramewiseDisplacement'].values

    #   get average signal value
    masker = NiftiMasker(mask_img=mask_filename,
                         memory_level=1,
                         memory='nilearn_cache')

    mymean = mean_img(func_mni_filename)

    signal = masker.fit_transform(mymean)
    meansignal = np.mean(signal)

    labelsmasker = NiftiLabelsMasker(
        labels_img=atlas_filename,
        #		     mask_img = mask_filename,
        #                    smoothing_fwhm = FWHM, already smoothed
        t_r=TR,
        memory_level=1,
        memory='nilearn_cache')

    #    X = labelsmasker.fit_transform(func_mni_filename, confounds = global_signal)
    X = labelsmasker.fit_transform(func_mni_filename)
    valid_voxels = labelsmasker.fit_transform(
        masker.inverse_transform(1 * (signal > meansignal * SIGNAL_FR)))

    nvols = X.shape[0]
    invalid_regions = valid_voxels < VOXELS_THR
    X[:, np.where(invalid_regions)] = np.nan
    fc = compute_fc(X, TYPE)
    fc = np.arctanh(fc)
    np.savetxt(output_filename, fc, delimiter=" ")

    # print average and max FD
    print("{};{};{};{};{}".format(np.mean(FD[1:]), np.max(FD[1:]),
                                  np.sum(FD[1:] > 0.2) / FD.size,
                                  np.sum(FD[1:] > 0.3) / FD.size,
                                  np.sum(invalid_regions)))
예제 #6
0
def test_mean_img_resample():
    # Test resampling in mean_img with a permutation of the axes
    rng = np.random.RandomState(42)
    data = rng.rand(5, 6, 7, 40)
    affine = np.diag((4, 3, 2, 1))
    img = nibabel.Nifti1Image(data, affine=affine)
    mean_img = nibabel.Nifti1Image(data.mean(axis=-1), affine=affine)

    target_affine = affine[:, [1, 0, 2, 3]]  # permutation of axes
    mean_img_with_resampling = image.mean_img(img, target_affine=target_affine)
    resampled_mean_image = resampling.resample_img(mean_img,
                                                   target_affine=target_affine)
    assert_array_equal(resampled_mean_image.get_data(),
                       mean_img_with_resampling.get_data())
    assert_array_equal(resampled_mean_image.get_affine(),
                       mean_img_with_resampling.get_affine())
    assert_array_equal(mean_img_with_resampling.get_affine(), target_affine)
예제 #7
0
def test_mean_img_resample():
    # Test resampling in mean_img with a permutation of the axes
    rng = np.random.RandomState(42)
    data = rng.rand(5, 6, 7, 40)
    affine = np.diag((4, 3, 2, 1))
    img = nibabel.Nifti1Image(data, affine=affine)
    mean_img = nibabel.Nifti1Image(data.mean(axis=-1), affine=affine)

    target_affine = affine[:, [1, 0, 2, 3]]  # permutation of axes
    mean_img_with_resampling = image.mean_img(img,
                                              target_affine=target_affine)
    resampled_mean_image = resampling.resample_img(mean_img,
                                              target_affine=target_affine)
    assert_array_equal(resampled_mean_image.get_data(),
                       mean_img_with_resampling.get_data())
    assert_array_equal(resampled_mean_image.get_affine(),
                       mean_img_with_resampling.get_affine())
    assert_array_equal(mean_img_with_resampling.get_affine(), target_affine)
def get_fmri_preview():
    data = {"image": ""}

    x_size = 64
    y_size = 64
    n_slice = 64
    n_volumes = 96

    if request.method == 'POST':
        f = request.files['file']
        nii_file = os.path.join(app.config['UPLOAD_FOLDER'],
                                secure_filename(f.filename))
        f.save(nii_file)
        mean_haxby = mean_img(nii_file)

        plot_epi(mean_haxby, output_file="static/img/viz.png")

        data = {'image': "static/img/viz.png"}
    return jsonify(data)
예제 #9
0
"""

### Fetch data ################################################################

from nilearn import datasets
from nilearn.image.image import mean_img
from nilearn.plotting.img_plotting import plot_epi, plot_roi

haxby_files = datasets.fetch_haxby(n_subjects=1)

### Visualization #############################################################

import matplotlib.pyplot as plt

# Compute the mean EPI: we do the mean along the axis 3, which is time
mean_haxby = mean_img(haxby_files.func)

plot_epi(mean_haxby)

### Extracting a brain mask ###################################################

# Simple computation of a mask from the fMRI data
from nilearn.masking import compute_epi_mask
mask_img = compute_epi_mask(haxby_files.func[0])

plot_roi(mask_img, mean_haxby)

### Applying the mask #########################################################

from nilearn.masking import apply_mask
masked_data = apply_mask(haxby_files.func[0], mask_img)
예제 #10
0
# By default 2nd subject will be fetched
haxby_dataset = datasets.fetch_haxby()

# print basic information on the dataset
print('First anatomical nifti image (3D) located is at: %s' %
      haxby_dataset.anat[0])
print('First functional nifti image (4D) is located at: %s' %
      haxby_dataset.func[0])

##############################################################################
# Visualization
from nilearn.image.image import mean_img

# Compute the mean EPI: we do the mean along the axis 3, which is time
func_filename = haxby_dataset.func[0]
mean_haxby = mean_img(func_filename)

from nilearn.plotting import plot_epi, show
plot_epi(mean_haxby)

##############################################################################
# Extracting a brain mask

# Simple computation of a mask from the fMRI data
from nilearn.masking import compute_epi_mask
mask_img = compute_epi_mask(func_filename)

# Visualize it as an ROI
from nilearn.plotting import plot_roi
plot_roi(mask_img, mean_haxby)
예제 #11
0
    prediction = svc.predict(fmri_masked[test])
    cv_scores.append(np.sum(prediction == target[test])
                     / float(np.size(target[test])))

print cv_scores

### Unmasking #################################################################

# Retrieve the SVC discriminating weights
coef_ = svc.coef_

# Reverse masking thanks to the Nifti Masker
coef_niimg = nifti_masker.inverse_transform(coef_)

# Use nibabel to save the coefficients as a Nifti image
import nibabel
nibabel.save(coef_niimg, 'haxby_svc_weights.nii')

### Visualization #############################################################
import pylab as plt
from nilearn.image.image import mean_img
from nilearn.plotting import plot_roi, plot_stat_map

mean_epi = mean_img(data.func[0])
plot_stat_map(coef_niimg, mean_epi, title="SVM weights", display_mode="yx")

plot_roi(nifti_masker.mask_img_, mean_epi, title="Mask", display_mode="yx")

plt.show()

예제 #12
0
    prediction = svc.predict(fmri_masked[test])
    cv_scores.append(
        np.sum(prediction == target[test]) / float(np.size(target[test])))

print cv_scores

### Unmasking #################################################################

# Retrieve the SVC discriminating weights
coef_ = svc.coef_

# Reverse masking thanks to the Nifti Masker
coef_niimg = nifti_masker.inverse_transform(coef_)

# Use nibabel to save the coefficients as a Nifti image
import nibabel

nibabel.save(coef_niimg, 'haxby_svc_weights.nii')

### Visualization #############################################################
import pylab as plt
from nilearn.image.image import mean_img
from nilearn.plotting import plot_roi, plot_stat_map

mean_epi = mean_img(data.func[0])
plot_stat_map(coef_niimg, mean_epi, title="SVM weights")

plot_roi(nifti_masker.mask_img_, mean_epi, title="Mask")

plt.show()
예제 #13
0
haxby_dataset = datasets.fetch_haxby()

# print basic information on the dataset
print('First anatomical nifti image (3D) located is at: %s' %
      haxby_dataset.anat[0])
print('First functional nifti image (4D) is located at: %s' %
      haxby_dataset.func[0])

##############################################################################
# Visualization
# -------------
from nilearn.image.image import mean_img

# Compute the mean EPI: we do the mean along the axis 3, which is time
func_filename = haxby_dataset.func[0]
mean_haxby = mean_img(func_filename)

from nilearn.plotting import plot_epi, show
plot_epi(mean_haxby, colorbar=True, cbar_tick_format="%i")

##############################################################################
# Extracting a brain mask
# -----------------------
# Simple computation of a mask from the fMRI data
from nilearn.masking import compute_epi_mask
mask_img = compute_epi_mask(func_filename)

# Visualize it as an ROI
from nilearn.plotting import plot_roi
plot_roi(mask_img, mean_haxby)
예제 #14
0
mask_filename = os.getcwd() + "/dataset/train/Patient_01/GT.nii.gz"
scan_filename = os.getcwd() + "/dataset/train/Patient_01/Patient_01.nii.gz"

masker = MultiNiftiMasker(mask_img=mask_filename, standardize=True)
print(masker)


# We give the masker a filename and retrieve a 2D array ready
# for machine learning with scikit-learn

masker.fit(scan_filename)
#masker.transform(scan_filename)
scan_masked = masker.fit_transform(scan_filename)

# calculate mean image for the background
mean_func_img = mean_img(scan_filename)
'''
plot_roi(masker.mask_img_, mean_func_img, display_mode='y', cut_coords=4, title="Mask")
show()
'''
# maxes = np.max(labelArray, axis=0)
# calculate mean image for the background
# mean_func_img = mean_img(filename)

# plot_roi(mask_img, mean_func_img, display_mode='y', cut_coords=4, title="Mask")

# https://nilearn.github.io/auto_examples/02_decoding/plot_simulated_data.html
# Baysian ridge
# https://scikit-learn.org/0.18/modules/generated/sklearn.linear_model.BayesianRidge.html#sklearn.linear_model.BayesianRidge

예제 #15
0
"""

### Fetch data ################################################################

from nilearn import datasets
from nilearn.image.image import mean_img
from nilearn.plotting.img_plotting import plot_epi, plot_roi

haxby_files = datasets.fetch_haxby(n_subjects=1)

### Visualization #############################################################

import matplotlib.pyplot as plt

# Compute the mean EPI: we do the mean along the axis 3, which is time
mean_haxby = mean_img(haxby_files.func)

plot_epi(mean_haxby)

### Extracting a brain mask ###################################################

# Simple computation of a mask from the fMRI data
from nilearn.masking import compute_epi_mask
mask_img = compute_epi_mask(haxby_files.func[0])

plot_roi(mask_img, mean_haxby)

### Applying the mask #########################################################

from nilearn.masking import apply_mask
masked_data = apply_mask(haxby_files.func[0], mask_img)
예제 #16
0
# As this is raw resting-state EPI, the background is noisy and we cannot
# rely on the 'background' masking strategy. We need to use the 'epi' one
nifti_masker = NiftiMasker(standardize=False, mask_strategy='epi',
                           memory="nilearn_cache", memory_level=2)
func_filename = nyu_dataset.func[0]
nifti_masker.fit(func_filename)
mask_img = nifti_masker.mask_img_

### Visualize the mask ########################################################
import matplotlib.pyplot as plt
from nilearn.plotting import plot_roi
from nilearn.image.image import mean_img

# calculate mean image for the background
mean_func_img = mean_img(func_filename)

plot_roi(mask_img, mean_func_img, display_mode='y', cut_coords=4, title="Mask")


### Preprocess data ###########################################################
nifti_masker.fit(func_filename)
fmri_masked = nifti_masker.transform(func_filename)

### Run an algorithm ##########################################################
from sklearn.decomposition import FastICA
n_components = 20
ica = FastICA(n_components=n_components, random_state=42)
components_masked = ica.fit_transform(fmri_masked.T).T

### Reverse masking ###########################################################
예제 #17
0
### Compute the mask ##########################################################

# As this is raw resting-state EPI, the background is noisy and we cannot
# rely on the 'background' masking strategy. We need to use the 'epi' one
nifti_masker = NiftiMasker(standardize=False, mask_strategy='epi',
                           memory="nilearn_cache", memory_level=2)
nifti_masker.fit(dataset.func[0])
mask_img = nifti_masker.mask_img_

### Visualize the mask ########################################################
import matplotlib.pyplot as plt
from nilearn.plotting import plot_roi
from nilearn.image.image import mean_img

# calculate mean image for the background
mean_func_img = mean_img(dataset.func[0])

plot_roi(mask_img, mean_func_img, display_mode='y', cut_coords=4, title="Mask")


### Preprocess data ###########################################################
nifti_masker.fit(dataset.func[0])
fmri_masked = nifti_masker.transform(dataset.func[0])

### Run an algorithm ##########################################################
from sklearn.decomposition import FastICA
n_components = 20
ica = FastICA(n_components=n_components, random_state=42)
components_masked = ica.fit_transform(fmri_masked.T).T

### Reverse masking ###########################################################
예제 #18
0
demo = pd.read_table(r'/Volumes/Byrgenwerth/Datasets/UCLA Consortium for Neuropsychiatric Phenomics LA5c Study/phenotype/demographics.tsv')

'''Take only the participants we need'''
scid_short = scid.loc[(scid['participant_id']== 'sub-10228') | (scid['participant_id']== 'sub-50006')
         | (scid['participant_id']== 'sub-60001') | (scid['participant_id']== 'sub-70001')]



'''let's flatten the correlation matrices'''
#cn_vector = np.tril(cn_matrix)
#cn_vector = cn_vector.flatten()
#cn_vector = cn_vector[cn_vector != 0]
#cn_vector = cn_vector[cn_vector != 1]

from nilearn.image.image import mean_img
mean_cn= mean_img(rest_img_cn_sub_10228)
from nilearn.plotting import plot_epi, show
plot_epi(mean_cn)
         
         
'''Assemble all FC matrices into one object'''
from nilearn.connectome import sym_matrix_to_vec
all_fc = np.stack((sz_matrix, bp_matrix, cn_matrix, adhd_matrix, test_sz_matrix, test_bp_matrix, test_adhd_matrix, test_cn_matrix))

#concat all the TS into one object
concat_ts = np.stack((rest_cn, rest_sz,rest_bp,rest_adhd, 
                test_rest_cn, test_rest_sz, test_rest_bp, test_rest_adhd))


concat_ts = np.asarray(concat_ts)
예제 #19
0
# As this is raw resting-state EPI, the background is noisy and we cannot
# rely on the 'background' masking strategy. We need to use the 'epi' one
nifti_masker = NiftiMasker(standardize=False,
                           mask_strategy='epi',
                           memory="nilearn_cache",
                           memory_level=2)
nifti_masker.fit(dataset.func[0])
mask_img = nifti_masker.mask_img_

### Visualize the mask ########################################################
import matplotlib.pyplot as plt
from nilearn.plotting import plot_roi
from nilearn.image.image import mean_img

# calculate mean image for the background
mean_func_img = mean_img(dataset.func[0])

plot_roi(mask_img, mean_func_img, display_mode='y', cut_coords=4, title="Mask")

### Preprocess data ###########################################################
nifti_masker.fit(dataset.func[0])
fmri_masked = nifti_masker.transform(dataset.func[0])

### Run an algorithm ##########################################################
from sklearn.decomposition import FastICA
n_components = 20
ica = FastICA(n_components=n_components, random_state=42)
components_masked = ica.fit_transform(fmri_masked.T).T

### Reverse masking ###########################################################
components = nifti_masker.inverse_transform(components_masked)
예제 #20
0
for train, test in cv:
    svc.fit(fmri_masked[train], target[train])
    prediction = svc.predict(fmri_masked[test])
    cv_scores.append(
        np.sum(prediction == target[test]) / float(np.size(target[test])))

print(cv_scores)

### Unmasking #################################################################

# Retrieve the SVC discriminating weights
coef_ = svc.coef_

# Reverse masking thanks to the Nifti Masker
coef_img = nifti_masker.inverse_transform(coef_)

# Save the coefficients as a Nifti image
coef_img.to_filename('haxby_svc_weights.nii')

### Visualization #############################################################
import matplotlib.pyplot as plt
from nilearn.image.image import mean_img
from nilearn.plotting import plot_roi, plot_stat_map

mean_epi = mean_img(func_filename)
plot_stat_map(coef_img, mean_epi, title="SVM weights", display_mode="yx")

plot_roi(nifti_masker.mask_img_, mean_epi, title="Mask", display_mode="yx")

plt.show()
예제 #21
0
for train, test in cv:
    svc.fit(fmri_masked[train], target[train])
    prediction = svc.predict(fmri_masked[test])
    cv_scores.append(np.sum(prediction == target[test])
                     / float(np.size(target[test])))

print(cv_scores)

### Unmasking #################################################################

# Retrieve the SVC discriminating weights
coef_ = svc.coef_

# Reverse masking thanks to the Nifti Masker
coef_img = nifti_masker.inverse_transform(coef_)

# Save the coefficients as a Nifti image
coef_img.to_filename('haxby_svc_weights.nii')

### Visualization #############################################################
import matplotlib.pyplot as plt
from nilearn.image.image import mean_img
from nilearn.plotting import plot_roi, plot_stat_map

mean_epi = mean_img(func_filename)
plot_stat_map(coef_img, mean_epi, title="SVM weights", display_mode="yx")

plot_roi(nifti_masker.mask_img_, mean_epi, title="Mask", display_mode="yx")

plt.show()
예제 #22
0
# rely on the 'background' masking strategy. We need to use the 'epi' one
nifti_masker = NiftiMasker(standardize=False,
                           mask_strategy='epi',
                           memory="nilearn_cache",
                           memory_level=2)
func_filename = nyu_dataset.func[0]
nifti_masker.fit(func_filename)
mask_img = nifti_masker.mask_img_

### Visualize the mask ########################################################
import matplotlib.pyplot as plt
from nilearn.plotting import plot_roi
from nilearn.image.image import mean_img

# calculate mean image for the background
mean_func_img = mean_img(func_filename)

plot_roi(mask_img, mean_func_img, display_mode='y', cut_coords=4, title="Mask")

### Preprocess data ###########################################################
nifti_masker.fit(func_filename)
fmri_masked = nifti_masker.transform(func_filename)

### Run an algorithm ##########################################################
from sklearn.decomposition import FastICA

n_components = 20
ica = FastICA(n_components=n_components, random_state=42)
components_masked = ica.fit_transform(fmri_masked.T).T

### Reverse masking ###########################################################
예제 #23
0
def plotZslices_alloption(niftipath,mnipath='',ortho='z',cut_coords='',Nraw=1,smoothing=0,LR=False,outdir='',colorpos='r',colorneg='b',Zannotate=False,thresholdpos='def',Zannotates='def',thresholdneg=False,alphamap=1,alphabrain=1):
    "niftipath: path to the nifti file, can be a 3D - if activation map, specify thresholds,"
    "mnipath : path to the mni T1 brain
    "cut_coords can be a int as the number of zslices to display of a list of slices number (in MNI) (even list of one to get one specific slice)"
    "Nraw: the number of raw"
    "smoothing: number of voxel to smooth; LR:annotate left and right"
    "outdir:path to save the file"
    "color:list of color for each volume, or only one color, neg or pos if corresponding threshold to display"
    "Zannotate : Number=annotate z number, False=not annotate, Brain=on a X slice, with lign, or Both"
    "thresholdpos: specify threshold to cut and see above (can be a list for activation map: layer effect) or False will not be displayed or 'def' as 0.5 on normalized file"
    "thresholdneg: specify threshold to cut and see bellow (can be a list for activation map: layer effect) or False will not be displayed "
    import matplotlib.pyplot as plt
    import numpy as np
    import nilearn.plotting
    import nilearn.image   
    from nilearn.plotting import plot_roi, plot_stat_map
    from nilearn.plotting.find_cuts import find_cut_slices
    from nilearn.image.image import mean_img
    import nibabel
    import seaborn as sns
    initialcol=sns.light_palette((0,0,0), as_cmap=True)#'Greys'
    data=nibabel.load(niftipath)
    datasize=data.get_shape()
    lineW=1./(Nraw+int((Zannotate=='Brain' or Zannotate=='Both')))
    if mnipath=='':
        mnipath='/home/mrstats/maamen/Software/fsl/data/standard/MNI152_T1_1mm_brain.nii.gz' ##this only works for the donders institute (Nijmegen, The Neterlands)
    if type(cut_coords)==int or cut_coords=='':
        if cut_coords=='':
            cut_coords=6
        #find best cut
        if len(datasize)==4:
            #for 4D nifti
            cut_coords=find_cut_slices(mean_img(nibabel.nifti1.Nifti1Image(np.sign(np.abs(data.get_data())),data.get_affine())), n_cuts=cut_coords)
        else:
            #for 3D nifti
            cut_coords=find_cut_slices(data, n_cuts=cut_coords)
    
    #split in N raw
    if cut_coords!=(0,0,0):
        cut_coords=np.array(cut_coords)
        cc=cut_coords
        cut_coords=[cut_coords[i*len(cut_coords)/np.float(Nraw):(i+1)*len(cut_coords)/np.float(Nraw)] for i in range(Nraw)]
    else:
        cut_coords=[cut_coords]
    #define color as a vector (length :the number of volume):
    #if not enought color are proveded, the last of them is repeated
    #color are defined independantly for negative value display and positive value display
    if type(colorneg)==str:
        colorneg=[colorneg]
    if type(colorpos)==str:
        colorpos=[colorpos]
    if len(datasize)==4 and len(colorpos)!=datasize[3]:
        provcol=colorpos[len(colorpos)-1]
        colorpos=np.concatenate([colorpos,[provcol for i in range(datasize[3]-len(colorpos))]])
    if len(datasize)==4 and len(colorneg)!=datasize[3]:
        provcol=colorneg[len(colorneg)-1]
        colorneg=np.concatenate([colorneg,[provcol for i in range(datasize[3]-len(colorneg))]])

    #adjust threshold by normalizing image in the default version and taking 0.5
    if thresholdpos=='def':
        data=nibabel.nifti1.Nifti1Image(data.get_data()/np.float(np.max(data.get_data())),data.get_affine())
        thresholdpos=[0.5]
    #organize thresholds, more than 1 threshold to make a layer effect,
    #positive and negative values display are treated independantly:
    if type(thresholdpos)!=np.bool: thresholdpos=[i for i in np.sort(thresholdpos)]
    if type(thresholdneg)!=np.bool: thresholdneg=[i for i in -np.sort(-1*np.array(thresholdneg))]
    
    #load data to create a white backgroung
    func=mean_img(nibabel.nifti1.Nifti1Image(np.sign(np.abs(data.get_data())),data.get_affine()))
    
    ####################subplot
    for i in range(Nraw):
        
        ax=plt.subplot(Nraw+int((Zannotate=='Brain' or Zannotate=='Both')),1,i+1)
        
        #plot the white backgroung as a zeros value brain (without it, the view focus aroung the first area plotted)
        brain=nilearn.plotting.plot_roi(nibabel.nifti1.Nifti1Image(np.zeros(func.get_shape()),data.get_affine()), nibabel.nifti1.Nifti1Image(np.zeros(func.get_shape()),data.get_affine()),colorbar=False,cut_coords=cut_coords[i],display_mode=ortho,alpha=1,draw_cross=False,cmap=initialcol,black_bg=False,axes=ax,annotate=False)
        
        ###############plot the volumes for Z brain slices
        if len(datasize)==3:
            iter_imgs=[data]
        else:
            iter_imgs=nilearn.image.iter_img(niftipath)
        
        j=0
        for img in iter_imgs:
            
            ##plot the positive values
            if thresholdpos!=False:
                colorprovpos=sns.light_palette(colorpos[j],len(thresholdpos),reverse=True)[::-1]
            
                
                img2=nilearn.image.smooth_img(img,smoothing)
                ##plot the different threshold (layer effect) for the positive values
                for kn,k in enumerate(thresholdpos):
                    brain.add_contours(img2,filled=True,levels=[k],cmap=None,colors=[[colorprovpos[kn][0],colorprovpos[kn][1],colorprovpos[kn][2]]],linewidths=lineW,alpha=k/np.max(thresholdpos))#alphamap)                    
            ##plot the negative values   
            if thresholdneg!=False:
                colorprovneg=sns.light_palette(colorneg[j],len(thresholdneg),reverse=True)[::-1]
                #switch negative to positive
                img2=nibabel.nifti1.Nifti1Image(-1*nilearn.image.smooth_img(img,smoothing).get_data(),data.get_affine())
                ##plot the negatives values for each negative threshold
                for kn,k in enumerate(thresholdneg):
                    brain.add_contours(img2,filled=True,levels=[k],cmap=None,colors=[[colorprovneg[kn][0],colorprovneg[kn][1],colorprovneg[kn][2]]],linewidths=lineW,alpha=k/np.max(thresholdpos))#alphamap)                    
                    
            j+=1
        ##plot the brain contour for Z brain slices
        #externe
        brain.add_contours(nilearn.image.smooth_img(mnipath,5),alpha=1*alphabrain, levels=[95],linewidths=lineW, cmap=sns.dark_palette('w', as_cmap=True),)       
        #interne (a little transparent)
        brain.add_contours(nilearn.image.smooth_img(mnipath,0.5),alpha=0.8*alphabrain, levels=[5000],linewidths=lineW)
        #add annotation if reauested
        if Zannotate=='Both' or Zannotate=='Number' :
            brain.annotate(left_right=LR,size=int(12*lineW))
        
        print 'raw '+str(i)+' ready'

        
    ########################## plot the X brain (same process but on X)
    if Zannotate=='Brain' or Zannotate=='Both':
        print 'doing annotate X slice'
        ax=plt.subplot(Nraw+1,1,Nraw+1)
        if len(datasize)==4:
            cut_coords=find_cut_slices(mean_img(nibabel.nifti1.Nifti1Image(np.sign(np.abs(data.get_data())),data.get_affine())), n_cuts=1,direction='x')
        else:
            cut_coords=find_cut_slices(data, n_cuts=1,direction='x')
        
        #plot the white background Xbrain
        brain=nilearn.plotting.plot_roi(nibabel.nifti1.Nifti1Image(np.zeros(func.get_shape()),data.get_affine()), nibabel.nifti1.Nifti1Image(np.zeros(func.get_shape()),data.get_affine()),colorbar=False,cut_coords=cut_coords,display_mode='x',alpha=1,draw_cross=False,cmap=initialcol,black_bg=False,axes=ax,annotate=False)
        
        if Zannotate=='Both' or Zannotate=='Number' :
            brain.annotate(left_right=LR,size=int(12*lineW))
            
        if len(datasize)==3:
            iter_imgs=[data]
        else:
            iter_imgs=nilearn.image.iter_img(niftipath)
        #plot the volumes
        j=0
        for img in iter_imgs:
            if thresholdpos!=False:
                colorprovpos=sns.light_palette(colorpos[j],len(thresholdpos),reverse=True)[::-1]
                img2=nilearn.image.smooth_img(img,smoothing)
                for kn,k in enumerate(thresholdpos):
                    brain.add_contours(img2,filled=True,levels=[k],cmap=None,colors=[[colorprovpos[kn][0],colorprovpos[kn][1],colorprovpos[kn][2]]],linewidths=lineW,alpha=k/np.max(thresholdpos))#alphamap)                    
                    
            if thresholdneg!=False:
                colorprovneg=sns.light_palette(colorneg[j],len(thresholdneg),reverse=True)[::-1]
                img2=nibabel.nifti1.Nifti1Image(-1*nilearn.image.smooth_img(img,smoothing).get_data(),data.get_affine())
                for kn,k in enumerate(thresholdneg):
                    brain.add_contours(img2,filled=True,levels=[k],cmap=None,colors=[[colorprovneg[kn][0],colorprovneg[kn][1],colorprovneg[kn][2]]],linewidths=lineW,alpha=k/np.max(thresholdpos))#alphamap)                    
                
            j+=1
        brain.add_contours(nilearn.image.smooth_img(mnipath,5),alpha=1*alphabrain, levels=[95],linewidths=lineW, cmap=sns.dark_palette('w', as_cmap=True),)       
        brain.add_contours(nilearn.image.smooth_img(mnipath,0.5),alpha=0.8*alphabrain, levels=[5000],linewidths=lineW)
        ##plot the line indicating the cut
        for i in cc:
            ax.plot([-100, 100], [i, i], 'k-',lw=lineW)#/(85.+73.)
        ax.axis((-300.0, 300.0, -80.0, 110.0))   
    #save
    if outdir!='':
        plt.savefig(outdir,dpi=300)