# Output CPU information:
!cat /proc/cpuinfo | grep 'vendor' | uniq
!cat /proc/cpuinfo | grep 'model name' | uniqimport lmod
await lmod.load('qsmxt/7.2.2')
!qsmxt --versionfrom glob import glob
def show_nii(nii_path, title=None, cmap='gray', **imshow_args):
    from matplotlib import pyplot as plt
    import numpy as np
    import nibabel as nib
    import glob

    # load data\n",
    data_1 = nib.load(nii_path).get_fdata()

    # get middle slices\n",
    slc_data1 = np.rot90(data_1[np.shape(data_1)[0]//2,:,:])
    slc_data2 = np.rot90(data_1[:,np.shape(data_1)[1]//2,:])
    slc_data3 = np.rot90(data_1[:,:,np.shape(data_1)[2]//2])

    # show slices\n",
    fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(8,10))
    if title: plt.suptitle(title)

    axes[0].imshow(slc_data1, cmap=cmap, **imshow_args)
    axes[1].imshow(slc_data2, cmap=cmap, **imshow_args)
    axes[2].imshow(slc_data3, cmap=cmap, **imshow_args)

    axes[0].axis('off')
    axes[1].axis('off')
    axes[2].axis('off')

    fig.tight_layout()
    fig.subplots_adjust(top=1.55)
    plt.show()show_nii(glob("bids/sub-*/ses-*/anat/*mag*nii*")[0], title="Magnitude", vmax=500)
show_nii(glob("bids/sub-*/ses-*/anat/*phase*nii*")[0], title="Phase")
show_nii(glob("bids/sub-*/ses-*/anat/*T1w*nii*")[0], title="T1-weighted")from ipyniivue import AnyNiivue

nv_T1 = AnyNiivue()
nv_T1.load_volumes([{"path": glob("bids/sub-*/ses-*/anat/*T1w*nii*")[0]}])
nv_T1show_nii(glob("bids/derivatives/qsmxt-*-*/sub*/ses*/anat*/*Chimap.nii*")[0], cmap='gray', vmin=-0.15, vmax=+0.15, interpolation='nearest')nv_QSM = AnyNiivue()
nv_QSM.load_volumes([{"path": glob("bids/derivatives/qsmxt-*-*/sub*/ses*/anat*/*Chimap.nii*")[0],
                      "cal_min":-0.1,"cal_max":0.1}])
nv_QSMshow_nii(glob("bids/derivatives/qsmxt-2*/sub*/ses*/anat*/*space-qsm*dseg.nii*")[0], cmap='terrain', vmin=0, vmax=96, interpolation='nearest')volumes = [
    {   "path": glob("bids/derivatives/qsmxt-*-*/sub*/ses*/anat*/*Chimap.nii*")[0],
        "cal_min": -0.1,
        "cal_max": 0.1
    },
    {
        "path": glob("bids/derivatives/qsmxt-2*/sub*/ses*/anat*/*space-qsm*dseg.nii*")[0],
        "colormap": "freesurfer",
        "visible": True, "opacity": 0.5
    },
]
nv_Seg = AnyNiivue(
    back_color=(1, 1, 1, 1),
    show_3D_crosshair=True,
)
nv_Seg.load_volumes(volumes)
nv_Seg# import modules
import numpy as np
import nibabel as nib
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from glob import globpd.read_csv(glob("bids/derivatives/qsmxt-*-*/sub*/ses*/extra*/*.csv")[0])# define regions of interest
# see https://github.com/QSMxT/QSMxT/blob/main/qsmxt/aseg_labels.csv for a full list
rois = { 
    "Thalamus" : [9, 10, 48, 49],
    "Pallidum" : [12, 13, 52, 53],
    "Caudate" : [11, 50],
    "Putamen" : [12, 51],
    "Brain stem" : [16],
    "CSF" : [24, 122, 257, 701],
    "White matter" : [2, 7, 41, 46, 177]
}
roi_names = { value: key for key in rois for value in rois[key] }
roi_ids = [value for roi in rois.values() for value in roi]# load a reconstruction
qsm = nib.load(glob("bids/derivatives/qsmxt-*-*/sub*/ses*/anat*/*Chimap.nii*")[0]).get_fdata().flatten()
seg = nib.load(glob("bids/derivatives/qsmxt-*-*/sub*/ses*/anat*/*space-qsm*dseg.nii*")[0]).get_fdata().flatten()# retain only the rois
qsm = qsm[np.isin(seg, roi_ids)]
seg = seg[np.isin(seg, roi_ids)]# convert to a dataframe for plotting purposes
seg = pd.Series(seg).map(roi_names)
data = pd.DataFrame({ 'qsm' : qsm, 'seg' : seg })# summarise data by region including the average and standard deviation
data.groupby('seg')['qsm'].agg(['mean', 'std']).sort_values('mean').round(decimals=3)medians = data.groupby('seg')['qsm'].median().sort_values()
order = medians.index# plot
fig, ax = plt.subplots()
sns.boxplot(data=data, y='qsm', x='seg', fliersize=0, color='lightblue', order=order, ax=ax)
ax.set_xticks(range(len(ax.get_xticks())))  # Set tick positions explicitly
ax.set_xticklabels(ax.get_xticklabels(), ha='right', rotation=45)
ax.set_ylim(-0.2, 0.3)
ax.axhline(y=0, color='pink', linestyle='-', linewidth=1, zorder=-1)
ax.set_xlabel("Region of interest")
ax.set_ylabel("Susceptibility (ppm)")
ax.set_title("QSM")
plt.show()