示例#1
0
    def show(self, npath):

        niftifiledim = len(image.load_img(npath).shape)
        if niftifiledim == 3:
            display = plotting.view_img(npath)
        else:
            print('>1 volume, plotting only the first for convenience')
            firstim = image.index_img(npath, 0, bg_img=False)
            display = plotting.view_img(firstim, bg_img=False)
        return display
def search_and_display_img(img_factory):
    try:
        img, img_name = img_factory()
    except Exception:
        with output:
            output.clear_output()
            display_html(
                "sorry, there was a problem with your image."
                "please upload a .nii.gz 3D image",
                raw=True,
            )
    else:
        results = search(img, n_terms=12)
        terms_table = terms_to_html_table(results["terms"])
        studies_table = studies_to_html_table(results["studies"])
        with output:
            output.clear_output()
            display_html("<h3>{}</h3>".format(img_name), raw=True)
            display_html(
                view_img(results["image"], threshold="95%").get_iframe(),
                raw=True,
            )
            display_html(f"<h3>Similar terms:</h3>\n{terms_table}", raw=True)
            display_html(f"<h3>Similar studies:</h3>\n{studies_table}",
                         raw=True)
示例#3
0
def decode_and_display_uploaded_img(_):
    if not uploader.value:
        with output:
            output.clear_output()
            display_html("please upload a .nii.gz 3D image", raw=True)
        return
    try:
        uploaded, *_ = uploader.value.values()
        file_name, *_ = uploader.value.keys()
        with tempfile.TemporaryDirectory() as tmp_dir:
            image_path = str(pathlib.Path(tmp_dir) / "image.nii.gz")
            with open(image_path, "wb") as f:
                f.write(uploaded["content"])
            img = image.load_img(image_path)
    except Exception:
        with output:
            output.clear_output()
            display_html(
                "sorry, there was a problem with your image."
                "please upload a .nii.gz 3D image",
                raw=True)
    else:
        top_terms = list(decode(img))
        with output:
            output.clear_output()
            display_html("<h3>{}</h3>".format(file_name), raw=True)
            display_html(view_img(img, threshold="95%").get_iframe(), raw=True)
            display_html("<h3>Top terms:</h3>{}".format(", ".join(top_terms)),
                         raw=True)
示例#4
0
def results_to_html(results, title="NeuroQuery Image Search"):
    """Create an HTML page displaying results of NeuroQueryImageSearch

    Parameters
    ----------
    results : dict returned by `NeuroQueryImageSearch()(img)`

    title : str, title of the resulting page

    Returns
    -------
    html : nilearn.plotting.html_document.HTMLDocument
       An object representing an HTML page; methods of interest are
       `save_as_html` and `open_in_browser`.

    """
    studies_table = studies_to_html_table(results["studies"])
    terms_table = terms_to_html_table(results["terms"])
    img_display = plotting.view_img(results["image"],
                                    threshold="95%").get_iframe()
    template = (Path(__file__).parent.joinpath(
        "data", "search_results_template.html").read_text())
    html = Template(template).safe_substitute({
        "title": title,
        "img_display": img_display,
        "studies_table": studies_table,
        "terms_table": terms_table,
    })
    return plotting.html_document.HTMLDocument(html)
示例#5
0
def plot_view_mask(img,
                   timestep=4,
                   vmin=None,
                   vmax=None,
                   resampling_factor=4,
                   symmetric_cmap=False,
                   save_file="/tmp/plot.html"):
    img = image.index_img(img, timestep)

    if (vmin is None):
        vmin = np.amin(img.get_data())
    if (vmax is None):
        vmax = np.amax(img.get_data())

    view = plotting.view_img(img,
                             threshold=None,
                             colorbar=True,
                             annotate=False,
                             draw_cross=False,
                             cut_coords=[0, 0, 0],
                             black_bg=True,
                             bg_img=False,
                             cmap="inferno",
                             symmetric_cmap=symmetric_cmap,
                             vmax=vmax,
                             vmin=vmin,
                             dim=-2,
                             resampling_interpolation="nearest",
                             title="Dataset 01 Downsampling " +
                             str(resampling_factor))

    view.save_as_html(save_file)
示例#6
0
def _viewer(brain, thresh, idx, percentile_threshold, surface, anatomical,
            **kwargs):
    if thresh == 0:
        thresh = 1e-6
    else:
        if percentile_threshold:
            thresh = str(thresh) + "%"
    if isinstance(idx, int):
        b = brain[idx].to_nifti()
    else:
        b = brain.to_nifti()
    if anatomical:
        bg_img = anatomical
    else:
        bg_img = "MNI152"
    cut_coords = kwargs.get("cut_coords", [0, 0, 0])

    if surface:
        return view_img_on_surf(b, threshold=thresh, **kwargs)
    else:
        return view_img(b,
                        bg_img=bg_img,
                        threshold=thresh,
                        cut_coords=cut_coords,
                        **kwargs)
示例#7
0
def plot_segmentation(anat, y_true, y_pred, out_file='segmentation', **kwargs):

    small_anat = image.resample_img(anat, target_affine=np.eye(3))
    small_y_true = image.resample_to_img(y_true,
                                         small_anat,
                                         interpolation='nearest')
    small_y_pred = image.resample_to_img(y_pred,
                                         small_anat,
                                         interpolation='nearest')

    true_view = niplot.view_img(small_y_true,
                                bg_img=small_anat,
                                cmap='tab20c_r')
    pred_view = niplot.view_img(small_y_pred,
                                bg_img=small_anat,
                                cmap='tab20c_r')
    filled_html = html.format(true_map=true_view.get_iframe(),
                              predicted_map=pred_view.get_iframe())
    with open('{}.html'.format(out_file), 'wb') as f:
        f.write(filled_html.encode('utf-8'))
    true_view.save_as_html('{}_y_true.html'.format(out_file))
    pred_view.save_as_html('{}_y_pred.html'.format(out_file))

    fig, axes = plt.subplots(2, 1)

    niplot.plot_roi(roi_img=y_true,
                    bg_img=anat,
                    black_bg=False,
                    vmin=0,
                    vmax=5,
                    axes=axes[0],
                    cut_coords=[0, 0, 0],
                    **kwargs)
    axes[0].set_title("Label")

    niplot.plot_roi(roi_img=y_pred,
                    bg_img=anat,
                    black_bg=False,
                    vmin=0,
                    vmax=5,
                    axes=axes[1],
                    cut_coords=[0, 0, 0],
                    **kwargs)
    axes[1].set_title("Prediction")

    plt.savefig('{}.png'.format(out_file))
def plot_nii(path: Path) -> str:
    html_doc = view_img(
        str(path),
        bg_img=False,
        cmap=cm.black_blue,
        symmetric_cmap=False,
    )
    return html_doc.get_iframe(**DEFAULT_NIFTI_SIZE)
示例#9
0
def plot_mean_results(runs: Iterable[Run],
                      output_key: str = "modulated_grey_matter"):
    results = [
        np.nan_to_num(nib.load(run.get_output(output_key)).get_fdata())
        for run in runs
    ]
    stacked = np.stack(results, axis=0)
    mean_modulated_gm_data = np.mean(stacked, axis=0)
    affine = nib.load(runs[0].get_output(output_key)).affine
    mean_image = nib.Nifti1Image(mean_modulated_gm_data, affine=affine)
    return view_img(mean_image)
def run_and_display_query(_):
    result = encoder(query.value)
    with output:
        output.clear_output()
        display_html(get_html_highlighted_text(result["highlighted_text"]),
                     raw=True)
        display_html(view_img(result["brain_map"],
                              threshold="97%",
                              colorbar=False).get_iframe(),
                     raw=True)
        display_html(utils.download_img_link(result["brain_map"], query.value),
                     raw=True)
def plot_mgz(path: Path) -> str:
    mgz = nib.load(path)
    data = mgz.get_fdata()
    nii = nib.Nifti1Image(data, mgz.affine, mgz.header, mgz.extra,
                          mgz.file_map)
    title = Path(path).name
    html_doc = view_img(
        nii,
        bg_img=False,
        cmap=cm.black_blue,
        symmetric_cmap=False,
        title=title,
    )
    return html_doc.get_iframe(**DEFAULT_NIFTI_SIZE)
示例#12
0
 def html_plot(self):
     # First make sure an associated NIfTI instance exists or create it.
     nii = self._nifti
     if not nii:
         try:
             nii = self.nifti
         except RuntimeError as e:
             # In case NIfTI conversion fails, return exception message.
             message = messages.NIFTI_CONVERSION_FAILURE_HTML.format(
                 scan_id=self.id, exception=e)
             return message
         else:
             if not isinstance(nii, NIfTI):
                 e = "NIfTI format generation failure"
                 message = messages.NIFTI_CONVERSION_FAILURE_HTML.format(
                     scan_id=self.id, exception=e)
                 return message
     # Determine the number of dimensions.
     has_3d_flag = any(
         [flag in self.description.lower() for flag in FLAG_3D])
     has_4d_flag = any(
         [flag in self.description.lower() for flag in FLAG_4D])
     if not (has_3d_flag or has_4d_flag):
         data = nii.get_data()
         ndim = data.ndim
     else:
         ndim = 3 if has_3d_flag else 4
     # 3D parameters.
     if ndim == 3:
         image = str(nii.path)
         title = self.description
     # 4D parameters.
     elif ndim == 4:
         image = mean_img(str(nii.path))
         title = f"{self.description} (Mean Image)"
     return view_img(
         image,
         bg_img=False,
         cmap=cm.black_blue,
         symmetric_cmap=False,
         title=title,
     )
示例#13
0
def run_and_display_query(_):
    result = encoder(query.value)
    similar_docs = result["similar_documents"].head(20).copy()
    similar_docs.loc[:, 'title'] = title_as_link(similar_docs)
    with output:
        output.clear_output()
        display_html(get_html_highlighted_text(result["highlighted_text"]),
                     raw=True)
        display_html(view_img(result["brain_map"], threshold=3.1).get_iframe(),
                     raw=True)
        display_html(utils.download_img_link(result["brain_map"], query.value),
                     raw=True)
        sw = result["similar_words"].head(12).drop("weight_in_query", axis=1)
        display(Markdown("## Similar Words"))
        display(
            sw.style.bar(subset=['similarity', 'weight_in_brain_map'],
                         color='lightgreen',
                         width=95))
        display(Markdown("## Similar Documents"))
        display(similar_docs[['title', 'similarity'
                              ]].style.hide_index().bar(color='lightgreen'))
示例#14
0
    def visualize(self, statmap, space='fsnative', threshold=0, hemi='R', mask=None, **plot_args):
        """ Visualizes a statmap on an image/surface background. """
        if 'fs' in space and isinstance(statmap, nib.Nifti1Image):
            raise ValueError("Statmap is an image, but space is fs* something ...")
        
        bg = 'surface' if 'fs' in space else 'volume'
        self.logger.info(f"Visualizing statmap on {bg} ...")
        if 'fs' in space:
            fs_base = op.dirname(self.fs_dir)
            if space == 'fsnative':
                fs_id = f'sub-{self.sub}'
            else:
                fs_id = space
                    
            return plotting.view_surf(
                surf_mesh=op.join(fs_base, fs_id, 'surf', f'{hemi.lower()}h.inflated'),
                surf_map=statmap,
                bg_map=op.join(fs_base, fs_id, 'surf', f'{hemi.lower()}h.sulc'),
                threshold=threshold,
                **plot_args
            )
        else:
            
            if mask is not None:
                statmap = masking.unmask(statmap, mask)

            if space == 'T1w':
                bg = op.join(self.fp_dir, 'anat', f'sub-{self.sub}_desc-preproc_T1w.nii.gz')
            else:
                bg = 'MNI152'

                
            return plotting.view_img(
                stat_map_img=statmap,
                bg_img=bg,
                threshold=threshold,
                **plot_args
            )
示例#15
0
def decode_and_display_img_from_url(_):
    url = url_field.value
    try:
        resp = requests.get(url)
        with tempfile.TemporaryDirectory() as tmp_dir:
            image_path = str(pathlib.Path(tmp_dir) / "image.nii.gz")
            with open(image_path, "wb") as f:
                f.write(resp.content)
            img = image.load_img(image_path)
    except Exception:
        with output:
            output.clear_output()
            display_html(
                "sorry, there was a problem with your image."
                "please enter a URL pointing to a .nii.gz 3D image",
                raw=True)
    else:
        top_terms = list(decode(img))
        with output:
            output.clear_output()
            display_html("<h3>{}</h3>".format(url), raw=True)
            display_html(view_img(img, threshold="95%").get_iframe(), raw=True)
            display_html("<h3>Top terms:</h3>{}".format(", ".join(top_terms)),
                         raw=True)
示例#16
0
def create_html_view(stat_map_img,
                     bg_img,
                     out_fname='viewer.html',
                     title=None,
                     opacity=1,
                     symmetric_cmap=True,
                     cmap='coolwarm',
                     threshold=None,
                     vmin=None,
                     vmax=None):
    '''Use Nilearn to create html of volumetric map.
    '''
    import os.path as op
    import numpy as np
    from nilearn import plotting
    import nibabel as nib

    # Check if stat_map_img is all 0, in which case the plotting will fail...
    stat_map_dat = nib.load(stat_map_img).dataobj
    if np.min(stat_map_dat) == 0 and np.max(stat_map_dat) == 0:
        vmin, vmax = (0, 0)

    html_view = plotting.view_img(stat_map_img,
                                  bg_img=bg_img,
                                  title=title,
                                  threshold=threshold,
                                  symmetric_cmap=symmetric_cmap,
                                  black_bg=False,
                                  cmap=cmap,
                                  vmin=vmin,
                                  vmax=vmax,
                                  opacity=opacity)

    html_view.save_as_html(out_fname)

    return op.abspath(out_fname)
示例#17
0
beta_masked = masker.fit_transform(mydata)

### SVC
svc_linear = SVC(kernel='linear')
svc_linear.fit(beta_masked, AMBIG)
prediction = svc_linear.predict(beta_masked)

### Unmasking & visualization
coef_img = masker.inverse_transform(svc_linear.coef_)
threshold = 1e-3
plotting.plot_stat_map(coef_img,
                       bg_img=T1,
                       threshold=threshold,
                       display_mode='z')
# Orth view
view = plotting.view_img(coef_img, bg_img=T1, threshold=threshold)
view.open_in_browser()
# Surf view
view = plotting.view_img_on_surf(coef_img, threshold=threshold)
view.open_in_browser()

### Cross validation
svc_crossval = SVC(kernel='linear')
cv = LeaveOneGroupOut()
cv_scores = cross_val_score(svc_crossval,
                            beta_masked,
                            AMBIG,
                            cv=cv,
                            groups=GROUP,
                            n_jobs=-1,
                            verbose=10)
示例#18
0
The model used here is the same as the one deployed on the neuroquery website
( https://neuroquery.saclay.inria.fr ).
"""
######################################################################
# Encode a query into a statistical map of the brain
# --------------------------------------------------
from neuroquery import fetch_neuroquery_model, NeuroQueryModel
from nilearn.plotting import view_img

encoder = NeuroQueryModel.from_data_dir(fetch_neuroquery_model())

######################################################################
query = """Huntington's disease"""
result = encoder(query)
view_img(result["z_map"], threshold=3.1)

######################################################################
# (drag the mouse on this interactive plot to see other slices)
#
# Note: if you are not using a jupyter notebook, use `.open_in_browser()` to
# open the plot above:

view_img(result["z_map"], threshold=3.1).open_in_browser()

######################################################################
# Display some relevant terms:

print(result["similar_words"].head(15))

######################################################################
示例#19
0
# Visualizing the fmri volume
# ............................
#
# One way to visualize a fmri volume is
# using :func:`nilearn.plotting.plot_epi`.
# We will visualize the previously fetched fmri data from Haxby dataset.
#
# Because fmri data is 4D (it consists of many 3D EPI images), we cannot
# plot it directly using :func:`nilearn.plotting.plot_epi` (which accepts
# just 3D input). Here we are using :func:`nilearn.image.mean_img` to
# extract a single 3D EPI image from the fmri data.
#
from nilearn import plotting
from nilearn.image import mean_img

plotting.view_img(mean_img(fmri_filename), threshold=None)

###########################################################################
# Feature extraction: from fMRI volumes to a data matrix
# .......................................................
#
# These are some really lovely images, but for machine learning
# we need matrices to work with the actual data. Fortunately, the
# :class:`nilearn.decoding.Decoder` object we will use later on can
# automatically transform Nifti images into matrices.
# All we have to do for now is define a mask filename.
#
# A mask of the Ventral Temporal (VT) cortex coming from the
# Haxby study is available:
mask_filename = haxby_dataset.mask_vt[0]
示例#20
0
from nilearn import plotting
import matplotlib.pyplot as plt

import matplotlib
matplotlib.use('Agg')

html_view = plotting.view_img(
    stat_map_img=snakemake.input.ref,
    bg_img=snakemake.input.flo,
    opacity=0.5,
    cmap='viridis',
    dim=-1,
    symmetric_cmap=False,
    title='sub-{subject}'.format(**snakemake.wildcards))

html_view.save_as_html(snakemake.output.html)

display = plotting.plot_anat(snakemake.input.flo, display_mode='ortho')
display.add_contours(snakemake.input.ref, colors='r')
display.savefig(snakemake.output.png)
display.close()
示例#21
0
rsa_motor_r = Brain_Data([x * y['mean']
                          for x, y in zip(mask_x, rsa_stats)]).sum()
rsa_motor_p = Brain_Data([x * y['p'] for x, y in zip(mask_x, rsa_stats)]).sum()

thresholded = threshold(rsa_motor_r, rsa_motor_p, thr=fdr_p)

plot_glass_brain(thresholded.to_nifti(), cmap='coolwarm')

# Looks like nothing survives FDR. Let's try a more liberal uncorrected threshold.
#

# In[124]:

thresholded = threshold(rsa_motor_r, rsa_motor_p, thr=0.01)

plot_glass_brain(thresholded.to_nifti(), cmap='coolwarm')

# In[125]:

view_img(thresholded.to_nifti())

# This looks a little better and makes it clear that the ROI that has the highest similarity with our model specifying the representational structure of motor cortex is precisely the left motor cortex. Though this only shows up using a liberal uncorrected threshold, remember that we are only using about 9 subjects for this demo.
#
# Though this was a very simple model using a very simple dataset, hopefully this example has illustrated how straightforward it is to run RSA style analyses using any type of data. Most people use this method to examine representations of much more complicated feature spaces.
#
# It is also possible to combine different hypotheses or models to decompose a brain representational similarity matrix. This method typically uses regression rather than correlations (see [Parkinson et al., 2017](https://www.nature.com/articles/s41562-017-0072))
#
# We have recently used this technique in our own work to map similarity in brain space to individual variability in a computational model of decision-making. If you are interested in seeing an example of intersubject RSA (IS-RSA), check out the [paper](https://www.nature.com/articles/s41467-019-09161-6), and accompanying python [code](https://github.com/jeroenvanbaar/MoralStrategiesFMRI).

# In[ ]:
decoder = Decoder(estimator='svc',
                  mask=mask_img,
                  standardize=True,
                  screening_percentile=5,
                  scoring='accuracy',
                  cv=cv)
# Compute the prediction accuracy for the different folds (i.e. session)
decoder.fit(func_img, conditions, groups=session_label)

# Print the CV scores
print(decoder.cv_scores_['face'])

#############################################################################
# Visualize the results
# ----------------------
# Look at the SVC's discriminating weights using
# :class:`nilearn.plotting.plot_stat_map`
weight_img = decoder.coef_img_['face']
from nilearn.plotting import plot_stat_map, show
plot_stat_map(weight_img, bg_img=haxby_dataset.anat[0], title='SVM weights')

show()
#############################################################################
# Or we can plot the weights using :class:`nilearn.plotting.view_img` as a
# dynamic html viewer
from nilearn.plotting import view_img
view_img(weight_img, bg_img=haxby_dataset.anat[0], title="SVM weights", dim=-1)
#############################################################################
# Saving the results as a Nifti file may also be important
weight_img.to_filename('haxby_face_vs_house.nii')
示例#23
0
# Visualizing t-map image on EPI template with manual
# positioning of coordinates using cut_coords given as a list
plotting.plot_stat_map(stat_img,
                       threshold=3,
                       title="plot_stat_map",
                       cut_coords=[36, -27, 66])

###############################################################################
# Making interactive visualizations with function `view_img`
# ----------------------------------------------------------
# An alternative to :func:`nilearn.plotting.plot_stat_map` is to use
# :func:`nilearn.plotting.view_img` that gives more interactive
# visualizations in a web browser. See :ref:`interactive-stat-map-plotting`
# for more details.

view = plotting.view_img(stat_img, threshold=3)
# In a Jupyter notebook, if ``view`` is the output of a cell, it will
# be displayed below the cell
view

##############################################################################

# uncomment this to open the plot in a web browser:
# view.open_in_browser()

###############################################################################
# Plotting statistical maps in a glass brain with function `plot_glass_brain`
# ---------------------------------------------------------------------------
#
# Now, the t-map image is mapped on glass brain representation where glass
# brain is always a fixed background template
######################################################################
import warnings
warnings.simplefilter('ignore')

######################################################################
# Statistical maps
# ================

######################################################################
# Download and plot an individual-level statistical map and plot it on the
# subject's T1 image:

from nilearn import datasets, plotting
localizer = datasets.fetch_localizer_button_task()
plotting.view_img(localizer['tmap'], bg_img=localizer['anat'], threshold='97%')


######################################################################
# Download and plot a group-level statistical map:

img = datasets.fetch_neurovault_motor_task()['images'][0]
plotting.view_img(img, threshold='95%')


######################################################################
# More about dataset downloaders: https://nilearn.github.io/modules/reference.html#module-nilearn.datasets
#
# More about plotting: https://nilearn.github.io/plotting/index.html

######################################################################
示例#25
0
    corpus_info={
        "tfidf": sparse.csr_matrix(tfidf),
        "metadata": corpus_metadata,
    },
)
encoder.to_data_dir(output_directory)

######################################################################
# Show an example prediction from our freshly trained model
# ---------------------------------------------------------
query = "Reading words"
print('Encoding "{}"'.format(query))

result = encoder(query)

plotting.view_img(result["brain_map"], threshold=3.0).open_in_browser()

print("Similar words:")
print(result["similar_words"].head())
print("\nSimilar documents:")
print(result["similar_documents"].head())

print("\nmodel saved in {}".format(output_directory))

# Display in notebook
plotting.view_img(result["brain_map"], threshold=3.0)

######################################################################
# Now that the model is trained and saved, it can easily be loaded in a later
# session
示例#26
0
# VISUALIZATION
# T1 weighted image for background
anatDir = os.path.join(dataDir,'derivatives_selected/fmriprep/sub-09/anat/')
imageT1 = os.path.join(anatDir,
                       'sub-09_space-MNI152NLin2009cAsym_desc-preproc_T1w.nii.gz')

# Thresholded zstat image
fThZStat=os.path.join(statsDir,'threshold_file/zstat' + contInd + '_threshold.nii.gz')
thImageStat=nib.load(fThZStat)

# global maximum cooridnates
X_zstat = nib.load(imgZStat).get_data()  # loading the zstat image
globalMax = np.unravel_index(np.argmax(X_zstat), X_zstat.shape) # voxel space
globalMaxMNI = coord_transform(globalMax[0],
                               globalMax[1],
                               globalMax[2],
                               thImageStat.affine)  # MNI space

# blob overlay at global max
plot_stat_map(thImageStat, bg_img=imageT1,
              colorbar=True, threshold=2.3, black_bg=True,
              draw_cross=True,
              cut_coords=globalMaxMNI)

# interactive visualization
view_img(thImageStat, bg_img=imageT1, cmap='black_red',
         symmetric_cmap=False, annotate=True,
         colorbar=True, threshold=2.3, black_bg=True,
         cut_coords=globalMaxMNI)
示例#27
0
preproc_dir = '/big_disk/ajoshi/ISLES2015/preproc/Training'
subid = 1
dirname = os.path.join(preproc_dir, str(subid))

# Three modalities of MRI data for the given subject
fnamet1 = os.path.join(dirname, 'T1mni.nii.gz')
fnamet2 = os.path.join(dirname, 'T2mni.nii.gz')
fnameflair = os.path.join(dirname, 'FLAIRmni.nii.gz')

# Segmentation
fnameseg = os.path.join(dirname, 'SEGMENTATIONmni.nii.gz')

# View the overlay of T1 image and thresholded FLAIR image
view = plotting.view_img(stat_map_img=fnameflair,
                         bg_img=fnamet1,
                         threshold=850)
view.open_in_browser()

# To get matrices of the images
t1 = ni.load_img(fnamet1)

t1_data = np.array(t1.get_data())

# Check the shape of the t1 matrix
print('Shape of the t1 data matrices is: ', t1_data.shape)

# To get matrices of the t2 images
t2 = ni.load_img(fnamet2)
t2_data = np.array(t2.get_data())
print('Shape of the t2 data matrices is: ', t2_data.shape)
def summarise_secondlevel():

    reg_folder = 'analysis/secondlevel/registration.feat/'

    highres_file = reg_folder + 'reg/highres2standard.nii.gz'
    standard_file = reg_folder + 'reg/standard.nii.gz'

    manual_reg_folder = reg_folder + 'reg/Manual_Reg_Standard/'

    if os.path.isdir(manual_reg_folder):
        print('Manual registration to standard has been performed')
    else:
        print(
            '!#!#!#!#!#!#!#!\n!#!#!#!#!#!#!#!\n\nCheck that you manually aligned HighRes to Standard\n\n!#!#!#!#!#!#!#!\n!#!#!#!#!#!#!#!\n'
        )

    # Load the files
    if os.path.isfile(highres_file):

        # Load the images
        highres = nibabel.load(highres_file)
        standard = nibabel.load(standard_file)

        # Show the interactive viewer for standard and highres
        fig = plotting.view_img(highres, bg_img=standard, opacity=0.4)

    else:
        # Set to nothing
        fig = []
        print('%s doesn' 't exist' % highres_file)

    # Check the secondlevel experiment folders that exist
    experiment_folders = glob.glob('analysis/secondlevel_*')

    for experiment_folder in experiment_folders:

        print('Found %s' % experiment_folder)

        timing_files = glob.glob(experiment_folder +
                                 '/default/Timing/*_Only.txt')

        for timing_file in timing_files:
            timing_mat = np.loadtxt(timing_file)

            if len(timing_mat.shape) == 1:
                timing_mat = timing_mat.reshape((1, 3))

            print('%s has %d included blocks and %d excluded blocks' %
                  (timing_file, np.sum(timing_mat[:, 2] == 1),
                   np.sum(timing_mat[:, 2] == 0)))

    # Load the ScanTimeAnalysis data for this participant
    stacked_data_name = 'analysis/Behavioral/ppt_stacked_data.mat'
    if os.path.isfile(stacked_data_name):

        if os.path.exists(
                'analysis/secondlevel/FunctionalSplitter_Log'
        ) == False or os.path.getmtime(
                'analysis/secondlevel/FunctionalSplitter_Log'
        ) > os.path.getmtime('analysis/Behavioral/ppt_stacked_data.mat'):
            print(
                '\n\n***********\n\n**WARNING**:\n\n***********\n\nThis graph relies on an output from ~/scripts/ScanTimeAnalysis.m and from a quick check it looks like this wasn'
                't run recently. This means this graph might be out of date. You should run that script again with this participant included in order to generate a new '
                'analysis/Behavioral/ppt_stacked_data.mat'
                ' file for this participant\n\n***********\n')

        # Load the matlab file
        stacked_data_all = loadmat(stacked_data_name)

        # Pull out the data
        stacked_labels = []
        stacked_data = []
        for category_counter in range(
                len(stacked_data_all['ppt_stacked_data'][0])):
            stacked_labels.append(
                stacked_data_all['stacked_labels'][0][category_counter][0])
            stacked_data.append(
                stacked_data_all['ppt_stacked_data'][0][category_counter])

        # Plot the figure
        plt.figure()
        plt.bar(range(len(stacked_data)), stacked_data)
        plt.ylabel('Minutes')
        plt.xticks(np.arange(len(stacked_data)), stacked_labels, rotation=15)
        print(stacked_labels)
    else:
        print('%s doesn' 't exist' % stacked_data_name)

    print(
        '\n\nReturning an interactive view of the registration from high res to standard for double-checking. If you want to do this for any of the functional to highres registrations, run this block of code (substitute func_run): \n\nimport nibabel as nib \nfrom nilearn import image \nfunc_run="01a" #which functional? \nfunc=nib.load("analysis/firstlevel/functional%s.feat/reg/example_func.nii.gz" % func_run)\nhighres=nib.load("analysis/firstlevel/functional%s.feat/reg/highres2example_func.nii.gz" % func_run) \nplotting.view_img(func,bg_img=highres,opacity=0.4)'
    )

    return fig
示例#29
0
# Visualizing t-map image on EPI template with manual
# positioning of coordinates using cut_coords given as a list
plotting.plot_stat_map(stat_img,
                       threshold=3, title="plot_stat_map",
                       cut_coords=[36, -27, 66])

###############################################################################
# Making interactive visualizations with function `view_img`
# ----------------------------------------------------------
# An alternative to :func:`nilearn.plotting.plot_stat_map` is to use
# :func:`nilearn.plotting.view_img` that gives more interactive
# visualizations in a web browser. See :ref:`interactive-stat-map-plotting`
# for more details.

view = plotting.view_img(stat_img, threshold=3)

# uncomment this to open the plot in a web browser:
# view.open_in_browser()

##############################################################################
# In a Jupyter notebook, if ``view`` is the output of a cell, it will
# be displayed below the cell

view

###############################################################################
# Plotting statistical maps in a glass brain with function `plot_glass_brain`
# ---------------------------------------------------------------------------
#
# Now, the t-map image is mapped on glass brain representation where glass
示例#30
0
import matplotlib.pyplot as plt
from nilearn.plotting import plot_stat_map, view_img
from nilearn.image import math_img, coord_transform

# Directory and file business
dataDir = '/tmp/Data/ds114'  # Data directory
anatDir = os.path.join(dataDir,'derivatives_selected/fmriprep/sub-09/anat/')
imageT1 = os.path.join(anatDir,
                       'sub-09_space-MNI152NLin2009cAsym_desc-preproc_T1w.nii.gz')
featDir = os.path.join(dataDir,
                       'WorkflowOutput/feat_dir/run0.feat/')
statDir = os.path.join(featDir,'stats')
imageStat = os.path.join(statDir, 'zstat6.nii.gz')

# thresholding the stat image to positive values only for visualization
thImageStat = math_img("np.ma.masked_less(img, 0)",
                                     img=imageStat)

# stat map at the maximum
plot_stat_map(thImageStat, bg_img=imageT1,
              colorbar=True, threshold=2.3, black_bg=True,
              draw_cross=True,
              cut_coords=coord_transform(23,27,36,thImageStat.affine))


# interactive visualization
view_img(thImageStat, bg_img=imageT1, cmap='black_red',
         symmetric_cmap=False, annotate=True,
         colorbar=True, threshold=2.3, black_bg=True,
         cut_coords=coord_transform(23,27,36,thImageStat.affine))
# %%
# As an exemplary input signal, we threshold a continuous map from the
# functional maps (DiFuMo 64) by Thirion et al.
with siibra.QUIET:  # suppress progress output here
    difumo_maps = atlas.get_map(space='mni152',
                                parcellation='difumo 64',
                                maptype='continuous')
from nilearn import image
img = image.math_img("im1+im2",
                     im1=image.threshold_img(difumo_maps.fetch(15), 0.0003),
                     im2=image.threshold_img(difumo_maps.fetch(44), 0.0003))
region1 = difumo_maps.decode_index(15)
region2 = difumo_maps.decode_index(44)

# let's look at the resulting image
from nilearn import plotting
plotting.view_img(img, title="Thresholded functional map", colorbar=False)

# %%
# We now assign Julich-Brain regions to this functional map with multiple
# modes. Note that when given an image as input, the ``assign`` method
# will output an image volume with labels for the detecteded components,
# so we can lookup which component corresponds to which part of the
# input volume.
# Since we are here ususally interested in correlations of the modes,
# we filter the result by significant (positive) correlations.
with siibra.QUIET:  # suppress progress output
    assignments, components = julich_pmaps.assign(img)
print(f"DiFuMo regions used: {region1.name}, {region2.name}")
assignments[assignments.Correlation >= 0.2]