Esempio n. 1
0
File: test_glm.py Progetto: cni/nipy
def test_fmri_example():
    # Run FMRI analysis using example data
    from nipy.utils import example_data

    fmri_files = [example_data.get_filename("fiac", "fiac0", run) for run in ["run1.nii.gz", "run2.nii.gz"]]
    design_files = [example_data.get_filename("fiac", "fiac0", run) for run in ["run1_design.npz", "run2_design.npz"]]
    mask = example_data.get_filename("fiac", "fiac0", "mask.nii.gz")
    multi_session_model = FMRILinearModel(fmri_files, design_files, mask)
    multi_session_model.fit()
    z_image, = multi_session_model.contrast([np.eye(13)[1]] * 2)
    # Check number of voxels with p < 0.001
    assert_equal(np.sum(z_image.get_data() > 3.09), 671)
Esempio n. 2
0
def make_matcher(): 
    I = Image(load(example_data.get_filename('neurospin',
                                             'sulcal2000',
                                             'nobias_ammon.nii.gz')))
    J = Image(load(example_data.get_filename('neurospin',
                                             'sulcal2000',
                                             'nobias_anubis.nii.gz')))


    # Create a registration instance
    R = IconicRegistration(I, J)
    R.set_source_fov(fixed_npoints=64**3)
    R.similarity = 'llr_cc'
    return R
Esempio n. 3
0
def test_fmri_example():
    # Run FMRI analysis using example data
    from nipy.utils import example_data
    fmri_files = [
        example_data.get_filename('fiac', 'fiac0', run)
        for run in ['run1.nii.gz', 'run2.nii.gz']
    ]
    design_files = [
        example_data.get_filename('fiac', 'fiac0', run)
        for run in ['run1_design.npz', 'run2_design.npz']
    ]
    mask = example_data.get_filename('fiac', 'fiac0', 'mask.nii.gz')
    multi_session_model = FMRILinearModel(fmri_files, design_files, mask)
    multi_session_model.fit()
    z_image, = multi_session_model.contrast([np.eye(13)[1]] * 2)
    # Check number of voxels with p < 0.001
    assert_equal(np.sum(z_image.get_data() > 3.09), 671)
Esempio n. 4
0
def remake_images():
    # Get group data
    group_data = example_data.get_filename("neurospin", "language_babies", "offset_002.npz")
    f = np.load(group_data)
    data, vardata, xyz = f["mat"], f["var"], f["xyz"]
    dX = xyz[0, :].max() + 1
    dY = xyz[1, :].max() + 1
    dZ = xyz[2, :].max() + 1
    aux = np.zeros([dX, dY, dZ])
    data_images = []
    vardata_images = []
    mask_images = []
    for i in range(data.shape[0]):
        aux[list(xyz)] = data[i, :]
        data_images.append(Image(aux.copy(), np.eye(4)))
        aux[list(xyz)] = vardata[i, :]
        vardata_images.append(Image(aux.copy(), np.eye(4)))
        aux[list(xyz)] = 1
        mask_images.append(Image(aux.copy(), np.eye(4)))

    return data_images, vardata_images, mask_images
Esempio n. 5
0
def remake_images():
    # Get group data
    group_data = example_data.get_filename(
        'neurospin', 'language_babies', 'offset_002.npz')
    f = np.load(group_data)
    data, vardata, xyz = f['mat'], f['var'], f['xyz']
    dX = xyz[0].max() + 1
    dY = xyz[1].max() + 1
    dZ = xyz[2].max() + 1
    aux = np.zeros([dX, dY, dZ])
    data_images = []
    vardata_images = []
    mask_images = []
    for i in range(data.shape[0]):
        aux[list(xyz)] = data[i]
        data_images.append(Image(aux.copy(), np.eye(4)))
        aux[list(xyz)] = vardata[i]
        vardata_images.append(Image(aux.copy(), np.eye(4)))
        aux[list(xyz)] = 1
        mask_images.append(aux)

    return data_images, vardata_images, mask_images
Esempio n. 6
0
def remake_images():
    # Get group data
    group_data = example_data.get_filename(
        'neurospin', 'language_babies', 'offset_002.npz')
    f = np.load(group_data)
    data, vardata, xyz = f['mat'], f['var'], f['xyz']
    dX = xyz[0].max() + 1
    dY = xyz[1].max() + 1
    dZ = xyz[2].max() + 1
    aux = np.zeros([dX, dY, dZ])
    data_images = []
    vardata_images = []
    mask_images = []
    for i in range(data.shape[0]):
        aux[list(xyz)] = data[i]
        data_images.append(Image(aux.copy(), np.eye(4)))
        aux[list(xyz)] = vardata[i]
        vardata_images.append(Image(aux.copy(), np.eye(4)))
        aux[list(xyz)] = 1
        mask_images.append(aux)

    return data_images, vardata_images, mask_images
Esempio n. 7
0
File: viz.py Progetto: Naereen/nipy
# get the data
data_dir = get_second_level_dataset()

# First example, with a anatomical template
img = load(os.path.join(data_dir, 'spmT_0029.nii.gz'))
data = img.get_data()
affine = img.get_affine()

viz.plot_map(data, affine, cut_coords=(-52, 10, 22),
                        threshold=2.0, cmap=viz.cm.cold_hot)
plt.savefig('ortho_view.png')

# Second example, with a given anatomical image slicing in the Z direction
try:
    anat_img = load(example_data.get_filename('neurospin', 'sulcal2000',
                                              'nobias_anubis.nii.gz'))
    anat = anat_img.get_data()
    anat_affine = anat_img.get_affine()
except OSError as e:
    # File does not exist: the data package is not installed
    print(e)
    anat = None
    anat_affine = None

viz.plot_map(data, affine, anat=anat, anat_affine=anat_affine,
             slicer='z', threshold=2, cmap=viz.cm.cold_hot, black_bg=True)
plt.savefig('z_view.png')

viz.plot_map(data, affine, anat=anat, anat_affine=anat_affine,
             slicer='x', threshold=2, cmap=viz.cm.cold_hot, black_bg=True)
plt.savefig('x_view.png')
Esempio n. 8
0
# First example, with a anatomical template
img = load(os.path.join(data_dir, 'spmT_0029.nii.gz'))
data = img.get_data()
affine = img.get_affine()

viz.plot_map(data,
             affine,
             cut_coords=(-52, 10, 22),
             threshold=2.0,
             cmap=viz.cm.cold_hot)
plt.savefig('ortho_view.png')

# Second example, with a given anatomical image slicing in the Z direction
try:
    anat_img = load(
        example_data.get_filename('neurospin', 'sulcal2000',
                                  'nobias_anubis.nii.gz'))
    anat = anat_img.get_data()
    anat_affine = anat_img.get_affine()
except OSError, e:
    # File does not exist: the data package is not installed
    print e
    anat = None
    anat_affine = None

viz.plot_map(data,
             affine,
             anat=anat,
             anat_affine=anat_affine,
             slicer='z',
             threshold=2,
             cmap=viz.cm.cold_hot)
Esempio n. 9
0
rarun2.nii

Author: Alexis Roche, 2009. 
"""

from nipy.algorithms.registration import FmriRealign4d

from nipy import load_image, save_image
from nipy.utils import example_data

from os.path import join, split
import sys
import tempfile

# Input images are provided with the nipy-data package
runnames = [example_data.get_filename('fiac','fiac0',run+'.nii.gz') \
                for run in ('run1','run2')]
runs = [load_image(run) for run in runnames]

# Spatio-temporal realigner
R = FmriRealign4d(runs, tr=2.5, slice_order='ascending', interleaved=True)

# Estimate motion within- and between-sessions
R.estimate()

# Resample data on a regular space+time lattice using 4d interpolation
corr_runs = R.resample()

# Save images 
savedir = tempfile.mkdtemp()
for i in range(len(runs)):
Esempio n. 10
0
import numpy as np
import sys

# Optional argument
cvect = [1,0,0,0]
if len(sys.argv)>1: 
    tmp = list(sys.argv[1])
    tmp.remove('[')
    tmp.remove(']')
    for i in range(tmp.count(',')):
        tmp.remove(',')
    cvect = map(float, tmp)


# Input files
fmri_files = [example_data.get_filename('fiac','fiac0',run) for run in ['run1.nii.gz','run2.nii.gz']]
design_files = [example_data.get_filename('fiac','fiac0',run) for run in ['run1_design.npz','run2_design.npz']]
mask_file = example_data.get_filename('fiac','fiac0','mask.nii.gz') 

# Get design matrix as numpy array
print('Loading design matrices...')
X = [np.load(f)['X'] for f in design_files]

# Get multi-session fMRI data 
print('Loading fmri data...')
Y = [load_image(f) for f in fmri_files]

# Get mask image
print('Loading mask...')
mask = load_image(mask_file)
Esempio n. 11
0
else:
    if nargs == 2: # contrast as one string
        args = sys.argv[1].split(',')
    elif nargs == 5: # contrast as sequence of strings
        args = [arg.replace(',', '') for arg in sys.argv[1:]]
    if len(args) != 4:
        print USAGE
        exit(1)
    try:
        cvect = [float(arg) for arg in args]
    except ValueError:
        print USAGE
        exit(1)

# Input files
fmri_files = [example_data.get_filename('fiac', 'fiac0', run)
              for run in ['run1.nii.gz', 'run2.nii.gz']]
design_files = [example_data.get_filename('fiac', 'fiac0', run)
                for run in ['run1_design.npz', 'run2_design.npz']]
mask_file = example_data.get_filename('fiac', 'fiac0', 'mask.nii.gz')

# Get design matrix as numpy array
print('Loading design matrices...')
X = [np.load(f)['X'] for f in design_files]

# Get multi-session fMRI data
print('Loading fmri data...')
Y = [load_image(f) for f in fmri_files]

# Get mask image
print('Loading mask...')
Esempio n. 12
0
from optparse import OptionParser
import time

import numpy as np

from nipy.algorithms.registration import HistogramRegistration, resample
from nipy.utils import example_data
from nipy import load_image, save_image

print("Scanning data directory...")

# Input images are provided with the nipy-data package
source = "ammon"
target = "anubis"
source_file = example_data.get_filename("neurospin", "sulcal2000", "nobias_" + source + ".nii.gz")
target_file = example_data.get_filename("neurospin", "sulcal2000", "nobias_" + target + ".nii.gz")

# Parse arguments
parser = OptionParser(description=__doc__)

doc_similarity = "similarity measure: cc (correlation coefficient), \
cr (correlation ratio), crl1 (correlation ratio in L1 norm), \
mi (mutual information), nmi (normalized mutual information), \
pmi (Parzen mutual information), dpmi (discrete Parzen mutual \
information). Default is crl1."

doc_interp = "interpolation method: tri (trilinear), pv (partial volume), \
rand (random). Default is pv."

doc_optimizer = "optimization method: simplex, powell, steepest, cg, bfgs. \
Esempio n. 13
0
    pylab.pink()
    array = im.data
    if threshold==None: 
        pylab.imshow(array[:,slice,:])
    else:
        pylab.imshow(array[:,slice,:]>threshold)



"""
Main 
"""

# Load images 
I = load_image(example_data.get_filename('neurospin',
                                         'sulcal2000',
                                         'nobias_ammon.nii.gz'))
J = load_image(example_data.get_filename('neurospin',
                                         'sulcal2000',
                                         'nobias_anubis.nii.gz'))


# Create a registration instance
R = IconicRegistration(I, J)
R.set_source_fov(fixed_npoints=64**3)
R.similarity = 'llr_mi'
T = np.eye(4)
#T[0:3,3] = [4,5,6]

print R.eval(T)
Esempio n. 14
0
    if nargs == 2:  # contrast as one string
        args = sys.argv[1].split(',')
    elif nargs == 5:  # contrast as sequence of strings
        args = [arg.replace(',', '') for arg in sys.argv[1:]]
    if len(args) != 4:
        print USAGE
        exit(1)
    try:
        cvect = [float(arg) for arg in args]
    except ValueError:
        print USAGE
        exit(1)

# Input files
fmri_files = [
    example_data.get_filename('fiac', 'fiac0', run)
    for run in ['run1.nii.gz', 'run2.nii.gz']
]
design_files = [
    example_data.get_filename('fiac', 'fiac0', run)
    for run in ['run1_design.npz', 'run2_design.npz']
]
mask_file = example_data.get_filename('fiac', 'fiac0', 'mask.nii.gz')

# Get design matrix as numpy array
print('Loading design matrices...')
X = [np.load(f)['X'] for f in design_files]

# Get multi-session fMRI data
print('Loading fmri data...')
Y = [load_image(f) for f in fmri_files]
Esempio n. 15
0
#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Example of onesample permutation test

Needs *example data* package
"""

import numpy as np

from nipy.labs.group.permutation_test import permutation_test_onesample

from nipy.utils import example_data

# Get group data
group_data = example_data.get_filename('neurospin', 'language_babies',
                                       'offset_002.npz')

f = np.load(group_data)
data, vardata, xyz = f['mat'], f['var'], f['xyz']

# Create one-sample permutation test instance
ptest = permutation_test_onesample(data, xyz, stat_id='wilcoxon')

# Cluster definition: (threshold, diameter)
# Note that a list of definitions can be passed to ptest.calibrate
cluster_def = (ptest.height_threshold(0.01), None)
print cluster_def

# Multiple calibration
# To get accurate pvalues, don't pass nperms (default is 1e4)
# Yet it will take longer to run
Esempio n. 16
0
Author: Alexis Roche, 2009. 
"""
from nipy.neurospin import register, transform
from nipy.utils import example_data
from nipy.io.imageformats import load as load_image, save as save_image

from os.path import join
import sys
import time

print('Scanning data directory...')

# Input images are provided with the nipy-data package
source = 'ammon'
target = 'anubis'
source_file = example_data.get_filename('neurospin','sulcal2000','nobias_'+source+'.nii.gz')
target_file = example_data.get_filename('neurospin','sulcal2000','nobias_'+target+'.nii.gz')

# Optional arguments
similarity = 'cr' 
interp = 'pv'
optimizer = 'powell'
if len(sys.argv)>1: 
    similarity = sys.argv[1]
    if len(sys.argv)>2: 
        interp = sys.argv[2]
        if len(sys.argv)>3: 
            optimizer = sys.argv[3]

# Print messages
print ('Source brain: %s' % source)
Esempio n. 17
0
try:
    import matplotlib.pyplot as plt
except ImportError:
    raise RuntimeError("This script needs the matplotlib library")

from nibabel import load, save, Nifti1Image

from nipy.modalities.fmri.glm import GeneralLinearModel, data_scaling
from nipy.utils import example_data
from nipy.labs.viz import plot_map, cm

# -----------------------------------------------------------
# --------- Get the data -----------------------------------
# -----------------------------------------------------------

fmri_files = [example_data.get_filename("fiac", "fiac0", run) for run in ["run1.nii.gz", "run2.nii.gz"]]
design_files = [example_data.get_filename("fiac", "fiac0", run) for run in ["run1_design.npz", "run2_design.npz"]]
mask_file = example_data.get_filename("fiac", "fiac0", "mask.nii.gz")
affine = load(mask_file).get_affine()

# Get design matrix as numpy array
print ("Loading design matrices...")
X = [np.load(f)["X"] for f in design_files]

# Get multi-run fMRI data
print ("Loading fmri data...")
Y = [load(f) for f in fmri_files]

# Get mask image
print ("Loading mask...")
mask = load(mask_file)
Esempio n. 18
0
from os.path import join

from nipy.io.imageformats import Nifti1Image, load as load_image, save as save_image
from nipy.utils import example_data
from nipy.neurospin.registration import FmriRealign4d
from pylab import * 

# Create Nifti1Image instances from both input files
rootpath = 'D:\\home\\Alexis\\data\\eccv'

mask = load_image(join(rootpath, 'mask.nii'))
xyz = np.where(mask.get_data()>0)

run = 'run1'

im_raw = load_image(example_data.get_filename('fiac','fiac0',run+'.nii.gz'))
im_npy = load_image(join(rootpath, 'npy_ra'+run+'.nii.gz'))
im_spm = load_image(join(rootpath, 'ra'+run+'.nii'))

raw = im_raw.get_data()
npy = im_npy.get_data()
spm = im_spm.get_data()

TR = 2.5

def compare(x, y, z):
    t = TR*np.arange(raw.shape[3])
    plot(t, raw[x,y,z,:], 'r')
    plot(t, spm[x,y,z,:], 'g')
    plot(t, npy[x,y,z,:], 'b')
    xlabel('time (sec)')
Esempio n. 19
0
Author: Alexis Roche, 2009.
"""
from __future__ import print_function  # Python 2/3 compatibility

import os
from os.path import split as psplit, abspath

from nipy.algorithms.registration import FmriRealign4d

from nipy import load_image, save_image
from nipy.utils import example_data

# Input images are provided with the nipy-data package
runnames = [
    example_data.get_filename('fiac', 'fiac0', run + '.nii.gz')
    for run in ('run1', 'run2')
]
runs = [load_image(run) for run in runnames]

# Declare interleaved ascending slice order
nslices = runs[0].shape[2]
slice_order = list(range(0, nslices, 2)) + list(range(1, nslices, 2))
print('Slice order: %s' % slice_order)

# Spatio-temporal realigner
R = FmriRealign4d(runs, tr=2.5, slice_order=slice_order)

# Estimate motion within- and between-sessions
R.estimate(refscan=None)
Esempio n. 20
0
from optparse import OptionParser
import time

import numpy as np

from nipy.algorithms.registration import HistogramRegistration, resample
from nipy.utils import example_data
from nipy import load_image, save_image

print('Scanning data directory...')

# Input images are provided with the nipy-data package
source = 'ammon'
target = 'anubis'
source_file = example_data.get_filename('neurospin', 'sulcal2000',
                                        'nobias_' + source + '.nii.gz')
target_file = example_data.get_filename('neurospin', 'sulcal2000',
                                        'nobias_' + target + '.nii.gz')

# Parse arguments
parser = OptionParser(description=__doc__)

doc_similarity = 'similarity measure: cc (correlation coefficient), \
cr (correlation ratio), crl1 (correlation ratio in L1 norm), \
mi (mutual information), nmi (normalized mutual information), \
pmi (Parzen mutual information), dpmi (discrete Parzen mutual \
information). Default is crl1.'

doc_interp = 'interpolation method: tri (trilinear), pv (partial volume), \
rand (random). Default is pv.'
Esempio n. 21
0
try:
    import matplotlib.pyplot as plt
except ImportError:
    raise RuntimeError("This script needs the matplotlib library")

from nibabel import load, save, Nifti1Image

from nipy.modalities.fmri.glm import GeneralLinearModel, data_scaling
from nipy.utils import example_data
from nipy.labs.viz import plot_map, cm

# -----------------------------------------------------------
# --------- Get the data -----------------------------------
#-----------------------------------------------------------

fmri_files = [example_data.get_filename('fiac', 'fiac0', run)
              for run in ['run1.nii.gz', 'run2.nii.gz']]
design_files = [example_data.get_filename('fiac', 'fiac0', run)
                for run in ['run1_design.npz', 'run2_design.npz']]
mask_file = example_data.get_filename('fiac', 'fiac0', 'mask.nii.gz')
affine = load(mask_file).get_affine()

# Get design matrix as numpy array
print('Loading design matrices...')
X = [np.load(f)['X'] for f in design_files]

# Get multi-run fMRI data
print('Loading fmri data...')
Y = [load(f) for f in fmri_files]

# Get mask image