def compute_level_similarities(data_path):
    similarity_sum = 0
    n_slices = 0
    os.chdir(data_path)
    level_file = open('levels_similarity.txt', 'w')
    for file_name in os.listdir('.'):
        if os.path.isdir(file_name) and file_name != 'dictionary':
            os.chdir(file_name)

            for im_file in os.listdir('.'):
                if 'seg.nii.gz' in im_file:
                    ref_seg = im_file
            subject = ref_seg[:8]
            n_slice = ref_seg[14:16]
            slice_level = ref_seg[-13:-11]

            selected_slices_levels = open('selected_slices.txt', 'r')
            line_list = selected_slices_levels.read().split("'")
            selected_slices_levels.close()
            levels = []
            similar_levels = 0
            for s in line_list:
                if s in ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6']:
                    levels.append(s)
            for l in levels:
                if l == slice_level:
                    similar_levels += 1
            slice_similarity = float(similar_levels)/len(levels)
            similarity_sum += slice_similarity
            level_file.write(subject + ' slice ' + n_slice + ': ' + str(slice_similarity*100) + '% (' + str(slice_level) + ')\n')
            os.chdir('..')
    level_file.write('\nmean similarity: ' + str(similarity_sum/n_slices) + '% ')
    level_file.close()
    os.chdir('..')
dataset/ETHPy150Open neuropoly/spinalcordtoolbox/scripts/msct_gmseg_utils.py/compute_level_similarities/original