def compute_error_map_by_level(data_path):
    original_path = os.path.abspath('.')
    diff_by_level = {'C1': [], 'C2': [], 'C3': [], 'C4': [], 'C5': [], 'C6': [], 'C7': [], 'T1': [], 'T2': [], '': []}
    error_map_abs_sum = None
    first = True
    n_slices = 0
    os.chdir(data_path)
    for subject_dir in os.listdir('.'):
        if os.path.isdir(subject_dir) and subject_dir != 'dictionary' and subject_dir != 'dic':
            os.chdir(subject_dir)

            subject = '_'.join(subject_dir.split('_')[1:3])
            if 'pilot' in subject:
                subject = subject.split('_')[0]

            # ref_gm_seg = ''
            # ref_sc_seg = ''
            sq_mask = ''
            level = ''
            res_wm_seg = ''
            res_dir = None
            for fname in os.listdir('.'):
                if 'tmp_' + subject in fname and os.path.isdir(fname):
                    res_dir = fname

            os.chdir(res_dir)
            for fname in os.listdir('.'):
                if 'level' in fname and 't2star' not in fname and 'IRP' in fname:
                    level = fname

                elif 'square_mask' in fname and 'IRP' in fname:
                    sq_mask = fname
                elif 'res_wmseg' in fname and 'corrected' in fname and 'original_dimension' not in fname:
                    res_wm_seg = fname
            if res_wm_seg != '' and level != '' and sq_mask!= '':

                ref_wm_seg = 'validation/ref_wm_seg.nii.gz'
                status, ref_ori = sct.run('sct_image -i ' + ref_wm_seg + ' -getorient')
                # ref_ori = ref_ori[4:7]
                if ref_ori != 'IRP':
                    sct.run('sct_image -i ' + ref_wm_seg + ' -setorient IRP')
                    ref_wm_seg = sct.extract_fname(ref_wm_seg)[0] + sct.extract_fname(ref_wm_seg)[1] + '_IRP' + sct.extract_fname(ref_wm_seg)[2]

                level_im = Image(level)

                ref_wm_seg_im = Image(ref_wm_seg)
                mask_im = Image(sq_mask)
                ref_wm_seg_im.crop_and_stack(mask_im, suffix='_croped', save=True)
                ref_wm_seg = ref_wm_seg_im.absolutepath

                res_wm_seg_im = Image(res_wm_seg)

                label_by_slice = {}
                level_label = {0: '', 1: 'C1', 2: 'C2', 3: 'C3', 4: 'C4', 5: 'C5', 6: 'C6', 7: 'C7', 8: 'T1', 9: 'T2',
                               10: 'T3', 11: 'T4', 12: 'T5', 13: 'T6'}
                nz_coord = level_im.getNonZeroCoordinates()
                for i_level_slice, level_slice in enumerate(level_im.data):
                    nz_val = []
                    for coord in nz_coord:
                        if coord.x == i_level_slice:
                            nz_val.append(level_slice[coord.y, coord.z])
                    try:
                        label_by_slice[i_level_slice] = int(round(sum(nz_val)/len(nz_val)))
                    except ZeroDivisionError:
                        sct.printv('No level label for slice ' + str(i_level_slice) + ' of subject ' + subject_dir)
                        label_by_slice[i_level_slice] = 0

                for i_slice in range(len(ref_wm_seg_im.data)):
                    if first:
                        error_map_abs_sum = np.zeros(ref_wm_seg_im.data[i_slice].shape)
                        first = False

                    error_3d_abs = abs(ref_wm_seg_im.data[i_slice] - res_wm_seg_im.data[i_slice])
                    slice_level = level_label[label_by_slice[i_slice]]
                    diff_by_level[slice_level].append(error_3d_abs)
                    error_map_abs_sum += error_3d_abs
                    n_slices += 1
            os.chdir('../..')
    for l, level_error in diff_by_level.items():
        try:
            n = len(level_error)
            if n != 0:
                Image(param=sum(level_error)/n, absolutepath='error_map_corrected_wm_' + str(l) + '.nii.gz').save()
        except ZeroDivisionError:
            sct.printv('WARNING: no data for level ' + str(l), 1, 'warning')
    Image(param=error_map_abs_sum/n_slices, absolutepath='error_map_abs_corrected_wm.nii.gz').save()
    os.chdir('..')
    os.chdir(original_path)


# ------------------------------------------------------------------------------------------------------------------
dataset/ETHPy150Open neuropoly/spinalcordtoolbox/scripts/msct_gmseg_utils.py/compute_error_map_by_level/original