<gh_stars>0

import os
import ants
import shutil
import nibabel as nib
import numpy as np
import pandas as pd

from glob import glob

working_root = '/data/public/data/003_STROKE_CTP/002_NIIX_SITE005'
clinical_root = '/data/public/data/003_STROKE_CTP/003_CLINICAL_SITE005'
output_xlsx_filename = '002_NIIX_SITE005_CTP_mean_mc_mni'

CTP_nii_files = glob(os.path.join(working_root, 'PID*PNAME*', '20*', 'CTP_1mm_mc_mni.nii.gz'))
failed_cases = []
tags = {'Name':[], 'Date':[], 'CTP_P01':[], 'CTP_P02':[], 'CTP_P03':[], 'CTP_P04':[], 'CTP_P05':[],
        'CTP_P06':[], 'CTP_P07':[], 'CTP_P08':[], 'CTP_P09':[], 'CTP_P10':[], 'CTP_P11':[], 'CTP_P12':[],
        'CTP_P13':[], 'CTP_P14':[], 'CTP_P15':[], 'CTP_P16':[], 'CTP_P17':[], 'CTP_P18':[], 'CTP_P19':[],
        'CTP_P20':[], 'CTP_P21':[], 'CTP_P22':[], 'CTP_P23':[], 'CTP_P24':[], 'CTP_P25':[], 'CTP_P26':[],
        'CTP_P27':[], 'CTP_P28':[], 'CTP_P29':[], 'CTP_P30':[], 'CTP_P31':[], 'CTP_P32':[], 'CTP_P33':[],
        'CTP_P34':[], 'CTP_P35':[], 'CTP_P36':[], 'CTP_P37':[], 'CTP_P38':[], 'CTP_P39':[], 'CTP_P40':[]}
for CTP_nii_file in CTP_nii_files:
    series_root = os.path.dirname(CTP_nii_file)
    date = os.path.basename(series_root)
    pname = os.path.basename(os.path.dirname(series_root))
    
    try:
        if not os.path.exists(CTP_nii_file): continue
        else:
            print('working on %s - %s'%(pname, date))
            nib_ctp = nib.load(CTP_nii_file)
            np_ctp = nib_ctp.get_fdata()
            tags['Name'].append(pname)
            tags['Date'].append(date)
            k1 = min(40, np_ctp.shape[3])
            k2 = max(40, np_ctp.shape[3])
            for i in range(k1):
                tagkey = 'CTP_P{:02d}'.format(i+1)
                tags[tagkey].append(np.mean(np_ctp[:,:,:,i]))
            for i in range(abs(k2 - k1)):
                tagkey = 'CTP_P{:02d}'.format(i+k1+1)
                tags[tagkey].append(0.0)
    except:
        failed_cases.append(pname)

df = pd.DataFrame(tags)
df.to_excel(os.path.join(clinical_root, output_xlsx_filename + '.xlsx'))
print(failed_cases)