Skip to content

Commit

Permalink
wip2
Browse files Browse the repository at this point in the history
  • Loading branch information
AliceJoubert committed Aug 5, 2024
1 parent 92f2602 commit 47c3d0c
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 15 deletions.
29 changes: 26 additions & 3 deletions clinica/iotools/converters/ixi_to_bids/ixi_to_bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

import nibabel as nb
import numpy as np
from ixi_to_bids_utils import read_ixi_clinical_data
from iotools.bids_utils import write_modality_agnostic_files
from ixi_to_bids_utils import *

from clinica.utils.filemanip import UserProvidedPath

Expand Down Expand Up @@ -36,8 +37,30 @@ def convert(
lvl="warning",
)

path_to_clinical = "/Users/alice.joubert/Downloads" # todo : testing only here
clinical_data = read_ixi_clinical_data(path_to_clinical)

# todo : convert here
subjects = subjects if subjects else get_subjects_list_from_data(path_to_dataset)
subjects = filter_subjects_list(subjects, clinical_data)

# todo : treat DTI different (load and merge)

image_data = get_img_data_df(path_to_dataset)

for subject in subjects:
write_subject(select_subject_data(image_data, subject), bids_dir)

readme_data = {
"link": "https://brain-development.org/ixi-dataset/",
"desc": (
"IXI is the nickname for the Information eXtraction from Images project, "
"which issued a dataset of nearly 600 images from healthy subjects. The MR"
"acquisition protocol includes T1,T2, PD weighted, MRA and diffusion-weighted"
"images. Three hospitals in London were involved in data collection."
),
}

write_modality_agnostic_files(
study_name=StudyName.IXI, readme_data=readme_data, bids_dir=bids_dir
)

cprint("Conversion to BIDS succeeded.", lvl="info")
57 changes: 49 additions & 8 deletions clinica/iotools/converters/ixi_to_bids/ixi_to_bids_utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
# todo : verify typing compatibility with user input
import json
import re
import shutil
from pathlib import Path
from typing import List

import nibabel as nib
import pandas as pd
from nilearn.image import concat_imgs

from clinica.iotools.bids_utils import StudyName, bids_id_factory

Expand All @@ -27,6 +31,9 @@ def filter_subjects_list(
]


# todo : filter img data based on this


def read_ixi_clinical_data(clinical_data_path: Path) -> pd.DataFrame:
clinical_data = pd.read_excel(clinical_data_path / "IXI.xls")
clinical_data.dropna(inplace=True)
Expand All @@ -53,12 +60,19 @@ def rename_ixi_modalities(input_mod: str) -> str:
)


def get_data_df(data_directory: Path) -> pd.DataFrame:
def define_magnetic_field(hospital: str) -> str:
if hospital == "Guys" or hospital == "IOP":
return "1.5"
if hospital == "HH":
return "3"


def get_img_data_df(data_directory: Path) -> pd.DataFrame:
# todo : works for all except DTI !!! (I mean we should drop it after this)
df = pd.DataFrame(
{"img_path": [path for path in data_directory.rglob(pattern="IXI*.nii.gz")]}
)
# todo : rename modalities inside
# todo : regex pattern for 3 groups IXI\d{3}(-\w*){3}.nii.gz vs 4 groups IXI\d{3}(-\w*){4}.nii.gz
df = (
df.assign(img_name=lambda df: df.img_path.apply(lambda x: x.name))
.assign(img_name_no_ext=lambda df: df.img_name.apply(lambda x: x.split(".")[0]))
Expand All @@ -74,27 +88,54 @@ def get_data_df(data_directory: Path) -> pd.DataFrame:
lambda x: rename_ixi_modalities(x.split("-")[3])
)
)
.assign(field=lambda df: df.hospital.apply(lambda x: define_magnetic_field(x)))
.assign(session="ses-M000")
)
return df


def select_subject_data(data_df: pd.DataFrame, subject: str) -> pd.DataFrame:
"""Select subject images to copy based on IXI id"""
return data_df[data_df["subject"] == subject]


def bids_filename_from_ixi(img: pd.Series) -> str:
# todo : adapter for modalities
return f"{img['bids_id']}_{img['session']}"
# todo : has to work for both nifti and json
return f"{img['bids_id']}_{img['session']}_{img['modality']}"


def write_subject(subject_df: pd.DataFrame, bids_path: Path) -> None:
# todo : place in subject folder, anat folder (T1,T2,PD) or dwi (dwi) folder if modality there ; where angio ??
for _, row in subject_df.iterrows():
filename = bids_filename_from_ixi(row)

if row["modality"] in ["T1w", "T2w", "PDw", "angio"]:
data_path = bids_path / row["bids_id"] / row["session"] / "anat"
elif row["modality"] == "dwi":
data_path = bids_path / row["bids_id"] / row["session"] / "func"
else:
raise ValueError(
f"Modality {row['modality']} not recognized for IXI dataset."
)

data_path.mkdir(parents=True, exist_ok=True)
shutil.copy2(row["img_path"], f"{data_path}/{filename}.nii.gz")

with open(f"{data_path}/{filename}.json", "w") as f:
json.dump(
{
"InstitutionName": row["hospital"],
"MagneticFieldStrength (T)": row["field"],
},
f,
indent=4,
)


def merge_dti(dti_df: pd.DataFrame) -> pd.DataFrame:
pass


# todo : function to place in files
# todo : function to create jsons
# todo : write only one json per subject ?
# todo : test all

# todo : question DTI - sessions différentes ou images différentes ?
# todo : dataset descr? scans/sessions/...
4 changes: 0 additions & 4 deletions clinica/pipelines/t1_linear/anat_linear_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,6 @@ def _get_substitutions_datasink(bids_image_id: str, suffix: str) -> list:
f"{bids_image_id}Warped_cropped.nii.gz",
f"{bids_image_id_without_suffix}_space-MNI152NLin2009cSym_desc-Crop_res-1x1x1_{suffix}.nii.gz",
),
(
f"{bids_image_id}0GenericAffine.mat",
f"{bids_image_id_without_suffix}_space-MNI152NLin2009cSym_res-1x1x1_affine.mat",
),
(
f"{bids_image_id}Warped.nii.gz",
f"{bids_image_id_without_suffix}_space-MNI152NLin2009cSym_res-1x1x1_{suffix}.nii.gz",
Expand Down

0 comments on commit 47c3d0c

Please sign in to comment.