Skip to content

Commit

Permalink
Switeched the examples to new API
Browse files Browse the repository at this point in the history
  • Loading branch information
bthirion committed Aug 28, 2015
1 parent 76ff45f commit 18853c1
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 58 deletions.
18 changes: 9 additions & 9 deletions examples/plot_fiac_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@
import matplotlib.pyplot as plt

from nilearn.plotting import plot_stat_map
from nilearn.image import mean_img
import nibabel as nib

from nistats.glm import FMRILinearModel
from nistats.design_matrix import make_design_matrix
from nistats.glm import FirstLevelGLM
from nistats import datasets


Expand All @@ -49,11 +49,11 @@
design_files = [data['design_matrix1'], data['design_matrix2']]

# Load all the data into a common GLM
multi_session_model = FMRILinearModel(fmri_files, design_files, data['mask'])
multi_session_model = FirstLevelGLM(data['mask'], standardize=False,
noise_model='ar1')

# GLM fitting
multi_session_model.fit(do_scaling=True, model='ar1')

multi_session_model.fit(fmri_files, design_files)

def make_fiac_contrasts(n_columns):
""" Specify some contrasts for the FIAC experiment"""
Expand All @@ -80,20 +80,20 @@ def _pad_vector(contrast_, n_columns):
contrasts = make_fiac_contrasts(n_columns)

print('Computing contrasts...')
mean_img = multi_session_model.means[0] # for display
mean_ = mean_img(data['func1'])
for index, (contrast_id, contrast_val) in enumerate(contrasts.items()):
print(' Contrast % 2i out of %i: %s' % (
index + 1, len(contrasts), contrast_id))
z_image_path = path.join(write_dir, '%s_z_map.nii' % contrast_id)
z_map, = multi_session_model.contrast(
[contrast_val] * 2, con_id=contrast_id, output_z=True)
z_map, = multi_session_model.transform(
[contrast_val] * 2, contrast_name=contrast_id, output_z=True)
nib.save(z_map, z_image_path)

# make a snapshot of the contrast activation
if contrast_id == 'Effects_of_interest':
vmax = max(- z_map.get_data().min(), z_map.get_data().max())
vmin = - vmax
display = plot_stat_map(z_map, bg_img=mean_img, threshold=2.5,
display = plot_stat_map(z_map, bg_img=mean_, threshold=2.5,
title=contrast_id)
display.savefig(path.join(write_dir, '%s_z_map.png' % contrast_id))

Expand Down
8 changes: 4 additions & 4 deletions examples/plot_localizer_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from pandas import DataFrame
from nibabel import save

from nistats.glm import FMRILinearModel
from nistats.glm import FirstLevelGLM
from nistats.design_matrix import (
make_design_matrix, plot_design_matrix, check_design_matrix)
from nistats import datasets
Expand Down Expand Up @@ -72,8 +72,7 @@
# Perform a GLM analysis
########################################

fmri_glm = FMRILinearModel(epi_img, matrix, mask='compute')
fmri_glm.fit(do_scaling=True, model='ar1')
fmri_glm = FirstLevelGLM().fit(epi_img, matrix)

#########################################
# Estimate contrasts
Expand Down Expand Up @@ -116,7 +115,8 @@
(index + 1, len(contrasts), contrast_id))
# save the z_image
image_path = path.join(write_dir, '%s_z_map.nii' % contrast_id)
z_map, = fmri_glm.contrast(contrast_val, con_id=contrast_id, output_z=True)
z_map, = fmri_glm.transform(contrast_val, contrast_name=contrast_id,
output_z=True)
save(z_map, image_path)

# Create snapshots of the contrasts
Expand Down
17 changes: 5 additions & 12 deletions examples/plot_spm_auditory.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from pandas import DataFrame
from nistats.design_matrix import (
make_design_matrix, plot_design_matrix, check_design_matrix)
from nistats.glm import FMRILinearModel
from nistats.glm import FirstLevelGLM
from nistats.datasets import fetch_spm_auditory
from nilearn.plotting import plot_stat_map
from nilearn.image import mean_img
Expand Down Expand Up @@ -65,24 +65,17 @@

# fit GLM
print('\r\nFitting a GLM (this takes time) ..')
fmri_glm = FMRILinearModel(nibabel.concat_images(subject_data.func),
matrix,
mask='compute')
fmri_glm.fit(do_scaling=True, model='ar1')

# save computed mask
mask_path = os.path.join(output_dir, "mask.nii.gz")
print("Saving mask image %s" % mask_path)
nibabel.save(fmri_glm.mask, mask_path)
fmri_glm = FirstLevelGLM(noise_model='ar1', standardize=False).fit(
[subject_data.func], matrix)

# compute bg unto which activation will be projected
mean_img = mean_img(subject_data.func)

print("Computing contrasts ..")
for contrast_id, contrast_val in contrasts.items():
print("\tcontrast id: %s" % contrast_id)
z_map, t_map, eff_map, var_map = fmri_glm.contrast(
contrasts[contrast_id], con_id=contrast_id, output_z=True,
z_map, t_map, eff_map, var_map = fmri_glm.transform(
contrasts[contrast_id], contrast_name=contrast_id, output_z=True,
output_stat=True, output_effects=True, output_variance=True)

# store stat maps to disk
Expand Down
20 changes: 10 additions & 10 deletions examples/plot_spm_multimodal_faces.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from pandas import DataFrame
from nilearn.image import concat_imgs, resample_img, mean_img
from nistats.design_matrix import make_design_matrix, check_design_matrix
from nistats.glm import FMRILinearModel
from nistats.glm import FirstLevelGLM
from nistats.datasets import fetch_spm_multimodal_fmri

# fetch spm multimodal_faces data
Expand All @@ -41,10 +41,11 @@
if not os.path.exists(output_dir):
os.makedirs(output_dir)

# resample the images
# resample the images
subject_data.func = [concat_imgs(subject_data.func1, auto_resample=True),
concat_imgs(subject_data.func2, auto_resample=True)]
affine, shape = subject_data.func[0].get_affine(), subject_data.func[0].shape
print('Resampling the second image (this takes time)...')
subject_data.func[1] = resample_img(subject_data.func[1], affine, shape[:3])

for x in range(2):
Expand Down Expand Up @@ -83,22 +84,21 @@
contrasts['scrambled']))

# fit GLM
print('Fitting a GLM (this takes time)...')
fmri_glm = FMRILinearModel(
subject_data.func,
[check_design_matrix(design_matrix)[1] for design_matrix in design_matrices],
mask='compute')
fmri_glm.fit(do_scaling=True, model='ar1')
print('Fitting a GLM')
X = [check_design_matrix(design_)[1] for design_ in design_matrices]
fmri_glm = FirstLevelGLM(standardize=False).fit(subject_data.func, X)


# Create mean image for display
mean_image = mean_img(subject_data.func)

# compute contrast maps
print('Computing contrasts')
from nilearn.plotting import plot_stat_map
for contrast_id, contrast_val in contrasts.items():
print("\tcontrast id: %s" % contrast_id)
z_map, t_map, effects_map, var_map = fmri_glm.contrast(
[contrast_val] * 2, con_id=contrast_id, output_z=True,
z_map, t_map, effects_map, var_map = fmri_glm.transform(
[contrast_val] * 2, contrast_name=contrast_id, output_z=True,
output_stat=True, output_effects=True, output_variance=True)
for map_type, out_map in zip(['z', 't', 'effects', 'variance'],
[z_map, t_map, effects_map, var_map]):
Expand Down
12 changes: 3 additions & 9 deletions nistats/glm.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,21 +245,15 @@ def fit(self, imgs, design_matrices):
imgs = [imgs]

if len(imgs) != len(design_matrices):
### temporary debug ######################################
print(imgs)
print(type(imgs))
print(imgs[0])
print(type(imgs[0]))
print(len(design_matrices))
##########################################################
raise ValueError(
'len(imgs) %d does not match len(design_matrices) %d'
% (len(imgs), len(design_matrices)))

# Loop on imgs and design matrices
self.labels_, self.results_ = [], []
self.masker_.fit(imgs)
for X, img in zip(design_matrices, imgs):
Y = self.masker_.fit_transform(img)
Y = self.masker_.transform(img)
if self.standardize is False:
Y, _ = data_scaling(Y)
labels_, results_ = session_glm(
Expand All @@ -278,7 +272,7 @@ def transform(self, con_vals, contrast_type=None, contrast_name='',
raise ValueError('The model has not been fit yet')

if isinstance(con_vals, np.ndarray):
con_val = [con_vals]
con_vals = [con_vals]
if len(con_vals) != len(self.results_):
raise ValueError(
'contrasts must be a sequence of %d session contrasts' %
Expand Down
14 changes: 0 additions & 14 deletions nistats/tests/test_glm.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,20 +146,6 @@ def test_session_glm():
assert_raises(ValueError, session_glm, Y, X, 'ar2')
assert_raises(ValueError, session_glm, Y, X.T)

"""
def ols_glm(n=100, p=80, q=10):
X, Y = np.random.randn(p, q), np.random.randn(p, n)
glm = GeneralLinearModel(X)
glm.fit(Y, 'ols')
return glm, n, p, q
def test_glm_beta():
mulm, n, p, q = ols_glm()
assert_equal(mulm.get_beta().shape, (q, n))
assert_equal(mulm.get_beta([0, -1]).shape, (2, n))
assert_equal(mulm.get_beta(6).shape, (1, n))
"""


def test_Tcontrast():
# new API
Expand Down

0 comments on commit 18853c1

Please sign in to comment.