<commit_before>"""
GLM fitting in fMRI
===================

Full step-by-step example of fitting a GLM to experimental data and visualizing
the results.

More specifically:

1. A sequence of fMRI volumes are loaded
2. A design matrix describing all the effects related to the data is computed
3. a mask of the useful brain volume is computed
4. A GLM is applied to the dataset (effect/covariance,
   then contrast estimation)

"""

from os import mkdir, path

import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame
from nibabel import save

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

from nilearn import plotting


#######################################
# Data and analysis parameters
#######################################

# timing
n_scans = 128
tr = 2.4
# paradigm
frame_times = np.linspace(0.5 * tr, (n_scans - .5) * tr, n_scans)

# write directory
write_dir = 'results'
if not path.exists(write_dir):
    mkdir(write_dir)

data = datasets.fetch_localizer_first_level()
paradigm_file = data.paradigm
epi_img = data.epi_img

########################################
# Design matrix
########################################

paradigm = DataFrame.from_csv(paradigm_file)
onset = [float(x[0].split(' ')[2]) for x in paradigm.iterrows()]
name = [x[0].split(' ')[1] for x in paradigm.iterrows()]
n_conditions = len(np.unique(name))
paradigm = DataFrame({'onset': onset, 'name': name})
design_matrix = make_design_matrix(frame_times, paradigm,
                                   hrf_model='canonical with derivative',
                                   drift_model="cosine", hfcut=128)

# Plot the design matrix
ax = design_matrix.show()
ax.set_position([.05, .25, .9, .65])
ax.set_title('Design matrix')
plt.savefig(path.join(write_dir, 'design_matrix.png'))

########################################
# Perform a GLM analysis
########################################

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

#########################################
# Estimate contrasts
#########################################

# Specify the contrasts

# simplest ones
contrasts = {}
n_columns = len(design_matrix.names)
for i in range(n_conditions):
    contrasts['%s' % design_matrix.names[2 * i]] = np.eye(n_columns)[2 * i]<commit_msg>improved example (t with better use of DataFrame<commit_after>"""
GLM fitting in fMRI
===================

Full step-by-step example of fitting a GLM to experimental data and visualizing
the results.

More specifically:

1. A sequence of fMRI volumes are loaded
2. A design matrix describing all the effects related to the data is computed
3. a mask of the useful brain volume is computed
4. A GLM is applied to the dataset (effect/covariance,
   then contrast estimation)

"""

from os import mkdir, path

import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame
from nibabel import save

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

from nilearn import plotting


#######################################
# Data and analysis parameters
#######################################

# timing
n_scans = 128
tr = 2.4
# paradigm
frame_times = np.linspace(0.5 * tr, (n_scans - .5) * tr, n_scans)

# write directory
write_dir = 'results'
if not path.exists(write_dir):
    mkdir(write_dir)

data = datasets.fetch_localizer_first_level()
paradigm_file = data.paradigm
epi_img = data.epi_img

########################################
# Design matrix
########################################

paradigm = DataFrame.from_csv(paradigm_file, sep=' ', header=None,
                              index_col=None)
paradigm.columns = ['session', 'name', 'onset']
n_conditions = len(paradigm.name.unique())
design_matrix = make_design_matrix(frame_times, paradigm,
                                   hrf_model='canonical with derivative',
                                   drift_model="cosine", hfcut=128)

# Plot the design matrix
ax = design_matrix.show()
ax.set_position([.05, .25, .9, .65])
ax.set_title('Design matrix')
plt.savefig(path.join(write_dir, 'design_matrix.png'))

########################################
# Perform a GLM analysis
########################################

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

#########################################
# Estimate contrasts
#########################################

# Specify the contrasts

# simplest ones
contrasts = {}
n_columns = len(design_matrix.names)
for i in range(n_conditions):
    contrasts['%s' % design_matrix.names[2 * i]] = np.eye(n_columns)[2 * i]
{'fraction_non_alphanumeric': 0.2222222222222222, 'fraction_numerical': 0.011131725417439703, 'mean_word_length': 4.583429228998849, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3205096', 'n_tokens_mistral': 1492, 'n_tokens_neox': 1387, 'n_words': 412}