# Copyright 2018-2026
# Institute of Neuroscience and Medicine (INM-1), Forschungszentrum Jülich GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Extracting Regionwise Signals From Activity Recording
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

siibra integrates nilearn to allow seemles extraction of signals given recordings
such as fMRI, PET, and others. This notebook downloads two fMRI images from
AOMIC-PIOP2 dataset (https://openneuro.org/datasets/ds002790/versions/2.0.0)
and compares the extraction results for different tasks.
"""
# %%
# We start by importing the Python packages used in this notebook. siibra
# provides access to brain atlases, spaces, maps, and datasets.
# nilearn.plotting is used for interactive neuroimaging visualizations.
# plotly.express.imshow helps us display matrix-like signal data, while
# matplotlib and pandas are used for plotting and tabular data analysis.
import siibra
from nilearn import plotting
from plotly.express import imshow
import matplotlib.pyplot as plt
import pandas as pd
import json
import pathlib
import requests
# sphinx_gallery_thumbnail_number = -2

# %%
# .. note::
#   The surface time-series analysis at the end of this notebook requires a
#   FreeSurfer `fsaverage5` template and a parcellation map defined in the same
#   space. The Julich-Brain `fsaverage5` map is not available out of the box,
#   however, `fsaverage7` version can be downsampled using `Workbench`. This
#   notebook loads the map from a dedicated configuration branch where this map
#   is precomputred.

siibra.use_configuration(
    siibra.retrieval.repositories.GithubConnector(
        owner="FZJ-INM1-BDA",
        repo="siibra-configurations",
        reftag="feat_timeseries_volume",
    )
)

# %%
# The fMRI data used in this example comes from the AOMIC-PIOP2 dataset hosted
# on OpenNeuro. Here we define the subject identifier and construct the base URL
# that points to the preprocessed fMRI files generated by fMRIPrep. This allows
# us to build the full download URLs for different tasks by changing only the
# file name.
subject = "sub-0001"
dataset_base_url = "https://s3.amazonaws.com/openneuro.org/ds002790/"
folder = f"derivatives/fmriprep/{subject}/func/"
url_template = dataset_base_url + folder + "{file}"
# %%
# We first load the preprocessed working-memory fMRI image. The file is in
# MNI152 space, which is a commonly used standard anatomical reference space.
# The image is wrapped as a siibra volume using siibra.volumes.from_url,
# which allows the data to be passed directly to siibra-based workflows.
# The time=[] argument indicates that the full 4D time series should be used.
file = f"{subject}_task-workingmemory_acq-seq_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz"
workingmemory_fmri = siibra.volumes.from_url(
    url_template.format(file=file), space="mni152", time=[]
)
print(type(workingmemory_fmri))

# %%
# Next, we load the resting-state fMRI recording from the same subject. This
# image has the same spatial reference space as the working-memory image, which
# makes it possible to compare the extracted region-wise signals across both
# recordings using the same brain atlas.
file = f"{subject}_task-restingstate_acq-seq_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz"
restingstate_fmri = siibra.volumes.from_url(
    url_template.format(file=file), space="mni152", time=[]
)


# %%
# Functional MRI recordings often contain noise caused by motion, physiology,
# scanner drift, or other non-neural sources. The fMRIPrep outputs include
# confound regressors that can be used during signal extraction. Here we load
# the confound files for both the working-memory and resting-state recordings
# into pandas DataFrames. Later, we will use the CSF signal as an example confound.
filename = f"{subject}_task-workingmemory_acq-seq_desc-confounds_regressors.tsv"
workingmemory_confounds = pd.read_csv(url_template.format(file=filename), sep="\t")
filename = f"{subject}_task-restingstate_acq-seq_desc-confounds_regressors.tsv"
restingstate_confounds = pd.read_csv(url_template.format(file=filename), sep="\t")

# %%
# We now select the brain parcellation that will define the regions from which
# signals are extracted. In this example, we use the Julich-Brain 3.1 in MNI152
# space. Since the fMRI data is also in MNI152 space, this atlas is suitable
# for extracting region-wise signals from the volume data.
julichbrain = siibra.get_map("julich 3.1", "mni152")

# %%
# The `extract_signals_with_nilearn`` method extracts one signal per region
# from the input fMRI image. Internally, this uses nilearn functionality to
# summarize the voxel-wise data within each labelled brain region. The result
# is returned as a pandas DataFrame, where each column corresponds to a region
# and each row corresponds to one time point of the fMRI recording. We also
# pass the CSF confound signal so that nilearn can regress it out during signal
# extraction.
workingmemory_signals = julichbrain.extract_signals_with_nilearn(
    workingmemory_fmri,
    confounds=workingmemory_confounds["csf"].values,
)
workingmemory_signals

# %%
# After extracting the time series, we summarize each regional signal using
# pandas. The describe() method computes statistics such as the mean, standard
# deviation, minimum, maximum, and quartiles. We transpose the result so that
# each row corresponds to one brain region, then sort the regions by their mean
# signal value.
workingmemory_signals_stats = workingmemory_signals.describe().T.sort_values(
    "mean", ascending=False
)
workingmemory_signals_stats

# %%
# To inspect the regional time series, we select the 20 regions with the highest
# mean signal values during the working-memory task. The selected signals are
# transposed so that regions are shown along one axis and time points along the
# other. This provides a compact overview of how the strongest regional signals
# vary over time.
imshow(workingmemory_signals[workingmemory_signals_stats.index[:20]].T)

# %%
# We repeat the same extraction workflow for the resting-state recording. This
# gives us a second region-wise signal matrix, again with time points as rows
# and atlas regions as columns. We then compute summary statistics for each
# region and sort them by the mean signal value, allowing direct comparison with
# the working-memory results.
restingstate_signals = julichbrain.extract_signals_with_nilearn(
    restingstate_fmri,
    confounds=restingstate_confounds["csf"].values,
)
restingstate_signals_stats = restingstate_signals.describe().T.sort_values(
    "mean", ascending=False
)
restingstate_signals_stats

# %%
# Here we create horizontal bar plots for the top 10 regions in each condition.
# The bar height represents the mean extracted signal, and the error bars show
# the standard deviation across time. These plots provide a simple summary of
# which regions have the strongest average signal in each recording.
fig, axs = plt.subplots(1, 2, figsize=(12, 5))
restingstate_signals_stats.iloc[:10, :].plot(
    ax=axs[0], title="resting state", kind="barh", y="mean", xerr="std"
)
workingmemory_signals_stats.iloc[:10, :].plot(
    ax=axs[1], title="working memory", kind="barh", y="mean", xerr="std"
)
fig.tight_layout()
# %%
# To compare the two recordings, we take the union of the top-ranked regions
# from the working-memory and resting-state summaries. We then create boxplots
# for the selected regions in both conditions. This allows us to compare the
# distribution of signal values across time for the same anatomical regions in
# the two fMRI recordings.
union = workingmemory_signals_stats.index[:20].union(
    restingstate_signals_stats.index[:20]
)
union_sorted = (
    workingmemory_signals_stats.loc[union, :].sort_values("mean", ascending=False).index
)

fig, ax = plt.subplots(figsize=(10, 10))
workingmemory_signals[union_sorted].boxplot(
    ax=ax, rot=90, color="b", label="working memory",
    flierprops={"marker": ".", "markeredgecolor": "b", "markersize": 3},
)
restingstate_signals[union_sorted].boxplot(
    ax=ax, rot=90, color="r", label="resting state",
    flierprops={"marker": ".", "markeredgecolor": "r", "markersize": 3},
)
ax.legend()
ax.set_title(f"Comparison of top {len(union_sorted)} regions for {subject}")
fig.tight_layout()

# %%
# Instead of extracting the mean signal from each region, we can also use a
# different summary strategy. Here we use strategy="variance" to compute the
# variance of the fMRI signal within each atlas region. This can be useful when
# we are interested in spatial or temporal variability rather than the average
# signal intensity.
workingmemory_signals_var = julichbrain.extract_signals_with_nilearn(
    workingmemory_fmri,
    confounds=workingmemory_confounds["csf"].values,
    strategy="variance",
)
workingmemory_signals_var

# %%
# The extracted region-wise variance values are mapped back onto the labelled
# atlas using `colorize` method. This creates a new image where each region is
# assigned the corresponding extracted value. We then visualize one time point
# of the resulting image with nilearn.plotting.view_img, using a magma colormap
# to show regional differences.
colored_map = julichbrain.colorize(workingmemory_signals_var.mean())
plotting.view_img(colored_map, cmap="magma", symmetric_cmap=False)

# %%
# So far, we used a labelled atlas map, where each voxel belongs to a discrete
# region. As an alternative, siibra can also work with probabilistic maps. Here
# we load the DiFuMo 64-component statistical map and use it to extract signals
# from the working-memory fMRI data. Probabilistic maps can represent spatially
# overlapping components and are often useful for functional parcellations.
difumo64_pmaps = siibra.get_map("DiFuMo 64", "mni152", "statistical")
difumo64_pmaps.extract_signals_with_nilearn(workingmemory_fmri)


# %%
# A similar workflow for surface-based fMRI data is possible.
julichbrain_fs5 = siibra.get_map("julich 3.1", "fsaverage5")
fs_variant = "inflated"
file_template = (
    f"{subject}_task-workingmemory_acq-seq_space-fsaverage5_hemi-" + "{}.func.gii"
)
url_template = dataset_base_url + folder + file_template

giivol = siibra.volumes.from_url(
    {h: url_template.format(h[0]) for h in ["Left", "Right"]},
    space="fsaverage5",
    format="gii-timeseries",
    time=list(range(160)),
)
signals = julichbrain_fs5.extract_signals_with_nilearn(
    giivol, surface_variant=fs_variant
)
signals

# %%
# `colorize`` method can be used on surface maps as well. In which case, the
# output is a `nilearn.surface.SurfaceImage` for compatibility with
# `nilearn.plotting`
surf_im = julichbrain_fs5.colorize(signals.std(), surface_variant=fs_variant)
plotting.view_surf(
    surf_map=surf_im,
    hemi="both",
    symmetric_cmap=False,
    cmap="magma",
)


# %%
config_output_folder = "./custom-configurations"


def create_config(subject, task):
    folder = f"derivatives/fmriprep/{subject}/func/"
    file_prefix = f"{subject}_task-{task}_acq-seq_space-fsaverage5"
    url_template = dataset_base_url + folder + file_prefix + "_hemi-{}.func.gii"
    conf = {
        "@type": "siibra/feature/voi/v0.1",
        "name": f"{subject} - fMRI - ds002790",
        "modality": f"fMRI - {task}",
        "space": {"name": "freesurfer fsaverage5"},
        "providers": {
            "gii-timeseries": {h: url_template.format(h[0]) for h in ["Left", "Right"]}
        },
        "time": {"start": 0, "stop": 10, "num": 160},
    }
    # discard unavailable data
    for url in conf["providers"]["gii-timeseries"].values():
        req = requests.get(url, stream=True)
        if not req.ok:
            return

    # create json config for future reuse
    filepath = f"{config_output_folder}/features/images/vois/fmri/{file_prefix}.json"
    pathlib.Path(filepath).parent.mkdir(parents=True, exist_ok=True)
    with open(filepath, "wt") as fp:
        json.dump(conf, fp=fp, indent="\t")


num_of_subjects = 10
tasks = ["restingstate", "workingmemory", "stopsignal"]
for task in tasks:
    for subject in range(num_of_subjects):
        create_config(f"sub-{subject + 1:04d}", task)


# %%
siibra.extend_configuration(config_output_folder)
fmri_vols = siibra.features.get(julichbrain_fs5.space, "FMRIVolumeOfInterest")
print(len(fmri_vols))


# %%
regional_signal_averages = {}
top_regions = pd.Index([])
for task in tasks:
    regional_signal_averages[task] = pd.concat(
        (
            julichbrain_fs5.extract_signals_with_nilearn(
                fmri_vol,
                strategy="mean",  # mean signal value per region per timepoint
                surface_variant=fs_variant,
            ).std()  # std over time per region
            for fmri_vol in fmri_vols
            if task in fmri_vol.name
        ),
        axis=1,
    )
    # compute the average of all subjects
    regional_signal_averages[task]["mean"] = regional_signal_averages[task].mean(axis=1)

    # find top 25 regions
    task_top_regions = regional_signal_averages[task].sort_values("mean", ascending=False).index[:25]
    top_regions = top_regions.union(task_top_regions)


# %%
top_regions_sorted = (
    regional_signal_averages["stopsignal"]
    .loc[top_regions, :]
    .sort_values("mean", ascending=False)
    .index
)
fig, ax = plt.subplots(figsize=(12, 10))
colors = ["r", "g", "b"]
for i, task in enumerate(tasks):
    regional_signal_averages[task].drop(columns="mean", inplace=True)
    regional_signal_averages[task].loc[top_regions_sorted, :].T.boxplot(
        ax=ax, rot=90, label=task, color=colors[i],
        flierprops={"marker": ".", "markersize": 1},
    )
ax.legend()
ax.set_title("Comparison of top regions between tasks across subjects")
fig.tight_layout()


# %%
fs_variant = "pial"
vmin = min([regional_signal_averages[task].min().min() for task in tasks])
vmax = max([regional_signal_averages[task].max().max() for task in tasks])
for task in tasks:
    surf_im = julichbrain_fs5.colorize(
        regional_signal_averages[task].mean(axis=1),
        surface_variant=fs_variant
    )
    plotting.plot_surf(
        surf_map=surf_im,
        hemi="both",
        cmap="magma",
        title=task,
        vmin=vmin,
        vmax=vmax,
    )
