# download data
!mkdir /data
%cd /data
!datalad install https://github.com/OpenNeuroDatasets/ds000102.git
!cd ds000102 && datalad get sub-01# This enables us to access FSL using Neurodesk
import lmod
await lmod.load('fsl/6.0.4')

# this makes it so FSL knows how we want our output files
os.environ["FSLOUTPUTTYPE"]="NIFTI_GZ"# run mcflirt
!mcflirt -in ds000102/sub-01/func/sub-01_task-flanker_run-1_bold.nii.gz -plotsfrom nipype.interfaces import fslhelp(fsl.MCFLIRT)moco = fsl.MCFLIRT(in_file = "ds000102/sub-01/func/sub-01_task-flanker_run-1_bold.nii.gz", out_file = "ds000102/sub-01/func/sub-01_task-flanker_run-1_bold_mfc.nii.gz",save_plots=True)print(moco.cmdline)moco_res = moco.run()moco_res.outputsimport numpy as np

motion_path = "ds000102/sub-01/func/sub-01_task-flanker_run-1_bold_mcf.par"
motion_parameters = np.loadtxt(motion_path)
print(f"Shape of motion parameter matrix: {motion_parameters.shape}")motion_parameters[:10,:]%matplotlib inline
import matplotlib.pyplot as plt

# Create plot
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(15,10))

# Plot motion parameters
axes[0].plot(motion_parameters[:, :3]) # x, y, z
axes[1].plot(motion_parameters[:, 3:]) # pitch, roll, yaw

# Add labels
axes[0].set_ylabel("translation (mm)")
axes[1].set_ylabel("rotation (radians)")
axes[1].set_xlabel("time (TR)")

axes[0].legend(["x","y","z"])
axes[1].legend(["pitch","roll","yaw"])

# Add main figure title
fig.suptitle(f"Subject 1, Flanker-Task Run 1: Motion Parameters",fontsize = 18)

plt.show()# Read in events
import pandas as pd
events_path = "/data/ds000102/sub-01/func/sub-01_task-flanker_run-1_events.tsv"
events = pd.read_csv(events_path, sep = '\t')

# get timings of task onset and offset
task_on = events["onset"]
task_off = events["duration"]

# Divide by TR
task_on_tr = (task_on/2).tolist()
task_off_tr = ((task_on + task_off)/2).tolist()

# Create plot
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(15,10))

# Plot motion parameters
axes[0].plot(motion_parameters[:, :3]) # x, y, z
axes[1].plot(motion_parameters[:, 3:]) # pitch, roll, yaw

# Plot effort blocks
for motion_on, motion_off in zip(task_on_tr, task_off_tr):
    axes[0].axvspan(motion_on, motion_off, color='grey', alpha=0.05, lw=0)

for motion_on, motion_off in zip(task_on_tr, task_off_tr):
    axes[1].axvspan(motion_on, motion_off, color='grey', alpha=0.05, lw=0)


# Add labels to plots
axes[0].set_ylabel("translation (mm)")
axes[1].set_ylabel("rotation (radians)")
axes[1].set_xlabel("time (TR)")

axes[0].legend(["x","y","z"])
axes[1].legend(["pitch","roll","yaw"])

# Add main figure title
fig.suptitle(f"Subject 1, Flanker-Task Run 1: Motion Parameters",fontsize = 18)ax = plt.axes(projection="3d")

# Plot movement
ax.plot3D(motion_parameters[:, 0], motion_parameters[:, 1], motion_parameters[:, 2], color = "black", alpha = 0.6)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")

plt.show()mo = fsl.MotionOutliers(
    in_file = "ds000102/sub-01/func/sub-01_task-flanker_run-1_bold.nii.gz",
    metric = "fdrms",
    out_metric_values = "ds000102/sub-01/func/sub-01_task-flanker_run-1_bold_fdrms.par",
    out_file = "ds000102/sub-01/func/sub-01_task-flanker_run-1_bold_outliers.txt"
)print(mo.cmdline)res = mo.run()res.outputsfdrms = np.loadtxt(res.outputs.out_metric_values )
outlier = np.loadtxt(res.outputs.out_file)

print(f"There is a maximum framewise displacement of {np.max(fdrms)} mm.")
print(f"There is a mean framewise displacement of {np.mean(fdrms)} mm.")
print(f"{round(np.sum(outlier)/len(outlier)*100,2)}% of timepoints are outliers.")