Skip to content

Commit

Permalink
Zip correctly niftis
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthieuJoulot committed Nov 6, 2024
1 parent 2c95c28 commit 22ed875
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 60 deletions.
74 changes: 32 additions & 42 deletions clinica/iotools/converters/miriad_to_bids/miriad_to_bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,19 @@
from clinica.utils.filemanip import UserProvidedPath

def convert(
path_to_dataset: UserProvidedPath,
bids_dir: UserProvidedPath,
path_to_clinical: UserProvidedPath,
subjects: Optional[UserProvidedPath] = None,
path_to_dataset: str,
bids_dir: str,
path_to_clinical: str,
subjects: Optional[str] = None,
n_procs: Optional[int] = 1,
**kwargs,
):
"""_summary_
Args:
path_to_dataset (UserProvidedPath): _description_
bids_dir (UserProvidedPath): _description_
path_to_clinical (UserProvidedPath): _description_
subjects (Optional[UserProvidedPath], optional): _description_. Defaults to None.
n_procs (Optional[int], optional): _description_. Defaults to 1.
"""
from clinica.iotools.converters.miriad_to_bids.miriad_to_bids_utils import create_bids_structure, parse_filename
"""Convert MIRIAD data to BIDS format without removing original .nii files."""
from clinica.iotools.converters.miriad_to_bids.miriad_to_bids_utils import create_bids_structure, parse_filename, convert_to_nii_gz
metadata_csv = 'metadata.csv'

# Load clinical data
clinical_data_file = None
for file in os.listdir(path_to_clinical):
if file.endswith('.csv'):
clinical_data_file = os.path.join(path_to_clinical, file)
Expand All @@ -42,7 +36,7 @@ def convert(
# Prepare CSV
with open(metadata_csv, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(['cohort', 'subject_id', 'diagnosis', 'gender', 'session', 'input_file', 'output_file'])
csvwriter.writerow(['cohort', 'subject_id', 'diagnosis', 'gender', 'session', 'run', 'input_file', 'output_file'])

participants_data = {}
sessions_data = []
Expand All @@ -51,23 +45,23 @@ def convert(
for root, dirs, files in os.walk(path_to_dataset):
for file in files:
if file.endswith('.nii'):
# Example: miriad_215_AD_M_01_MR_1.nii
parts = file.split('_')

# Extract information from filename
parts = file.split('_')
cohort = parts[0] # miriad
subject_id = parts[1] # 215
diagnosis = parts[2] # AD (Alzheimer's) or HC (Healthy Control)
gender = parts[3] # M or F
session = parts[4].lstrip('0') # Session number
session_alt = parts[4].lstrip('0') # Session number
scan_number = parts[6].replace('.nii', '') # Scan number from MR_1 or MR_2

# Parse subject ID, session ID, and run ID from the filename
# subject_id, session_id, run_id = parse_filename(file)
session = parts[4].lstrip('0') # Session number
run_number = parts[6].replace('.nii', '') # Scan number from MR_1 or MR_2

bids_subject_id = f"sub-{subject_id}"
bids_session_id = f"ses-{session}"

# Original file path
original_file_path = os.path.join(root, file)

# Extract MR ID
mr_id = f"{cohort}_{subject_id}_{session}_MR_{scan_number}"
mr_id = f"{cohort}_{subject_id}_{session}_MR_{run_number}"

# Extract relevant clinical information from the clinical data
clinical_row = clinical_data[clinical_data['MR ID'] == mr_id]
Expand All @@ -79,29 +73,25 @@ def convert(
group = clinical_row['Group'].values[0] # HC or AD
gender_clinical = clinical_row['M/F'].values[0] # M or F

# Full path of input file
input_file = os.path.join(root, file)

# Create BIDS structure and move the file
create_bids_structure(subject_id, session_alt, scan_number, cohort, diagnosis, gender, input_file, path_to_dataset, bids_dir, path_to_clinical)

# Write the extracted information to CSV
bids_filename = f"sub-MIRIAD{subject_id}_ses-{session}_T1w.nii.gz"
output_file = os.path.join(f"sub-MIRIAD{subject_id}", f"ses-{session}", 'anat', bids_filename)
csvwriter.writerow([cohort, subject_id, diagnosis, gender, session, input_file, output_file])
# Write metadata CSV
csvwriter.writerow([cohort, subject_id, diagnosis, gender, session, run_number, original_file_path, bids_subject_id])

# Track the minimum age for the participant for baseline
# Track baseline age (minimum age for each subject)
if subject_id not in participants_data or participants_data[subject_id]['age'] > age:
participants_data[subject_id] = {'participant_id': f"sub-MIRIAD{subject_id}",
'sex': gender_clinical,
'diagnosis': group,
'age': age}
participants_data[subject_id] = {
'participant_id': f"sub-MIRIAD{subject_id}",
'sex': gender_clinical,
'diagnosis': group,
'age': age
}

# Prepare sessions data
sessions_data.append([f"sub-MIRIAD{subject_id}", f"ses-{session}", age])


# Write participants.csv with baseline age (minimum age for each subject)
# Create BIDS structure and copy file with run number
create_bids_structure(subject_id, session, run_number, cohort, diagnosis, gender, original_file_path, path_to_dataset, bids_dir, path_to_clinical)

# Write participants.csv with baseline age (minimum age for each subject)
participants_csv = os.path.join(bids_dir, 'participants.csv')
with open(participants_csv, 'w', newline='') as participants_file:
participants_writer = csv.writer(participants_file)
Expand Down
36 changes: 18 additions & 18 deletions clinica/iotools/converters/miriad_to_bids/miriad_to_bids_utils.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,26 @@
import os
import shutil
import nibabel as nib

# Helper function to create BIDS folders and move files
def create_bids_structure(subject_id, session, run_label, cohort, diagnosis, gender, input_file, path_to_dataset, output_dir, path_to_clinical
):

"""_summary_
Args:
session (_type_): _description_
cohort (_type_): _description_
diagnosis (_type_): _description_
gender (_type_): _description_
input_file (_type_): _description_
output_dir (_type_): _description_
path_to_dataset (_type_, optional): _description_. Defaults to None, n_procs: Optional[int] = 1, **kwargs, ):#subject_id.
"""
def create_bids_structure(subject_id, session, run_label, cohort, diagnosis, gender, input_file, path_to_dataset, output_dir, path_to_clinical):
"""Create BIDS folder structure and move files into it."""
sub_id = f"sub-MIRIAD{subject_id}"
ses_id = f"ses-{session}"
run_id = f"run-{run_label}" # Run number (e.g., run-01)
run_id = f"run-{run_label}" # Run number (e.g., run-01)


# Create output directory for this subject/session
anat_dir = os.path.join(output_dir, sub_id, ses_id, 'anat')
os.makedirs(anat_dir, exist_ok=True)

# Destination filename in BIDS format
# Convert the input file to .nii.gz if necessary
input_file_gz = convert_to_nii_gz(input_file)

# Destination filename in BIDS format with run number
bids_filename = f"{sub_id}_{ses_id}_{run_id}_T1w.nii.gz"

# Copy and rename the file to BIDS format
shutil.copy(input_file, os.path.join(anat_dir, bids_filename))
shutil.copy(input_file_gz, os.path.join(anat_dir, bids_filename))


# Function to extract subject, session, and run info from filenames
Expand All @@ -44,3 +35,12 @@ def parse_filename(filename):
run_id = parts[6] # e.g., "1" (for run-01, run-02)

return subject_id, session_id, run_id

def convert_to_nii_gz(input_file):
"""Convert a .nii file to .nii.gz format without deleting the original .nii file."""
if input_file.endswith(".nii.gz"):
return input_file
img = nib.load(input_file)
output_file = input_file.replace(".nii", ".nii.gz")
nib.save(img, output_file)
return output_file

0 comments on commit 22ed875

Please sign in to comment.