<jupyter_start><jupyter_text>from matplotlib import pyplot as pltplt.rcParams['figure.figsize'] = [20, 20]for index in range(len(test_inputs)):     img = test_inputs[index:index+1]     truth = test_truths[index:index+1]    img = train_inputs[index:index+1]    truth = train_truths[index:index+1]    pred = model.predict(img)    pred = np.round(pred)    plt.figure(figsize=(5,5))    plt.imshow(img[0,...,0], cmap='gray')    plt.contour(truth[0,...,0], colors='yellow', alpha=0.5)    plt.contour(pred[0,...,0], colors='red', alpha=0.5)    plt.show()<jupyter_code>from matplotlib import pyplot as plt

#random_indexes = np.random.randint(0, test_inputs.shape[0], number)
random_indexes = [107, 120, 61, 95, 185]
number = len(random_indexes)
print(random_indexes)
fig, axs = plt.subplots(nrows=number, ncols=4, sharex=True, sharey=True, squeeze=True, figsize=(12,15))
for j, index in enumerate(random_indexes):
    ax = axs[j]
    
    for a in ax:
        a.set_xticklabels([])
        a.set_yticklabels([])
        a.set_xticks([])
        a.set_yticks([])
        
    img = test_inputs[index:index+1]
    truth = test_truths[index:index+1]
    pred = model.predict(img)
    pred = np.round(pred)
    diff = truth - pred
    
    ax[0].imshow(np.log(1+img[0,...,0]))
    ax[1].imshow(truth[0,...,0])
    ax[2].imshow(pred[0,...,0])
    ax[3].imshow(diff[0,...,0])
plt.tight_layout()

axs[0][0].set_title('Input', fontdict={'fontsize': 15, 'fontweight': 'medium'})
axs[0][1].set_title('Truth', fontdict={'fontsize': 15, 'fontweight': 'medium'})
axs[0][2].set_title('Output', fontdict={'fontsize': 15, 'fontweight': 'medium'})
axs[0][3].set_title('Difference', fontdict={'fontsize': 15, 'fontweight': 'medium'})

#plt.savefig("vacbag.svg", bbox_inches='tight')
spacing_mm=[0.85, 0.85, 1.907]

from metrics import *

def google_metrics(y_true, y_pred, spacing_mm, organ_tol_mm, organ_index=None):
    if organ_index == None:
        y_pred = np.array(y_pred, dtype=bool)
        y_true = np.array(y_true, dtype=bool)
    else:
        y_pred = np.array(y_pred[...,organ_index], dtype=bool)
        y_true = np.array(y_true[...,organ_index], dtype=bool)
    surface_dice_list = []
    msd_list = []
    dice_list = []

    for true, pred in zip(y_true, y_pred):

        
        if np.max(true) >= 1 and np.max(pred) >= 1:
            surface_distances = compute_surface_distances(pred, true, spacing_mm)   
            surface_dice = compute_surface_dice_at_tolerance(surface_distances, organ_tol_mm)
            surface_dice_list.append(surface_dice)
            msd = np.mean(np.absolute(compute_average_surface_distance(surface_distances)))
            msd_list.append(msd)
            
            dice = compute_dice_coefficient(true, pred)
            dice_list.append(dice)
            
            
        elif np.max(true) >= 1 and np.max(pred) <= 1:
            msd_list.append(9999)
            surface_dice_list.append(0.00)
            dice_list.append(0.00)
            
        elif np.max(true) <= 1 and np.max(pred) <= 1:
            msd_list.append(0.00)
            surface_dice_list.append(1.00)          
            dice_list.append(1.00)
            
            
    return dice_list, surface_dice_list, msd_list
from matplotlib import pyplot as plt

# number=5
# random_indexes = np.random.randint(0, test_inputs.shape[0], number)
# print(random_indexes)


organ_name = "vacbag"
organ_num = 0
random_indexes = [107, 120, 61, 95, 185]
number = len(random_indexes)
tol = 0.0
l=5





fig, axs = plt.subplots(nrows=number, ncols=4, sharex=True, sharey=True,squeeze=True, figsize=(12,12))
for j, index in enumerate(random_indexes):
    ax = axs[j]
    
    for a in ax:
        a.set_xticklabels([])
        a.set_yticklabels([])
        a.set_xticks([])
        a.set_yticks([])
        
    img = test_inputs[index:index+1,...]
    truth = test_truths[index:index+1,...,organ_num:organ_num+1]
    pred = model.predict(img)
    pred = np.round(pred[...,organ_num:organ_num+1])
    diff = truth - pred
    
    if np.max(truth) >= 1 and np.max(pred) >= 1:
        stats = google_metrics(truth, pred, spacing_mm, tol)
        print(stats)   
        stats = "DSC: {0:.3f} \nMSD: {1:.3f}".format(stats[0][0], stats[2][0])
        ax[3].text(1.05, 0.4, stats, size=18, ha="left", transform=ax[3].transAxes)

    
    ax[0].imshow(np.log(1+img[0,...,0][l:-l, l:-l]), cmap='gray')
    ax[0].contour(truth[0,...,0][l:-l, l:-l], colors='yellow', alpha=.25)
    ax[0].contour(pred[0,...,0][l:-l, l:-l],colors='red', alpha=.25)
    ax[1].imshow(truth[0,...,0][l:-l, l:-l])
    ax[2].imshow(pred[0,...,0][l:-l, l:-l])
    ax[3].imshow(diff[0,...,0][l:-l, l:-l])



axs[0][0].set_title('Input', fontdict={'fontsize': 23, 'fontweight': 'medium'})
axs[0][1].set_title('Truth (Y)', fontdict={'fontsize': 23, 'fontweight': 'medium'})
axs[0][2].set_title('Prediction (R)', fontdict={'fontsize': 23, 'fontweight': 'medium'})
axs[0][3].set_title('Difference', fontdict={'fontsize': 23, 'fontweight': 'medium'})

axs[0][0].text(-0.1,0.5, "A", size=23, ha="center", transform=axs[0][0].transAxes)
axs[1][0].text(-0.1,0.5, "B", size=23, ha="center", transform=axs[1][0].transAxes)
axs[2][0].text(-0.1,0.5, "C", size=23, ha="center", transform=axs[2][0].transAxes)
axs[3][0].text(-0.1,0.5, "D", size=23, ha="center", transform=axs[3][0].transAxes)
axs[4][0].text(-0.1,0.5, "E", size=23, ha="center", transform=axs[4][0].transAxes)
plt.tight_layout()
plt.savefig("/home/matthew/masters_presentation/images/vet_" + organ_name + ".png", bbox_inches='tight')

# from metrics import *

# def google_metrics(y_true, y_pred, spacing_mm, organ_tol_mm=0):
#     y_pred = np.array(y_pred, dtype=bool)
#     y_true = np.array(y_true, dtype=bool)
    
#     surface_dice_list = []
#     msd_list = []
#     hd95_list = []
#     dice_list = []

#     for batch_index in range(y_true.shape[0]):
#         dice = compute_dice_coefficient(y_true, y_pred)
#         dice_list.append(dice)
#         if np.max(y_true[batch_index])> 0 or np.max(y_pred[batch_index]) > 0:
#             surface_distances = compute_surface_distances(y_pred[batch_index], y_true[batch_index], spacing_mm)
            
#             surface_dice = compute_surface_dice_at_tolerance(surface_distances, organ_tol_mm)
#             surface_dice_list.append(surface_dice)
            
#         if np.max(y_true[batch_index]) > 0 and np.max(y_pred[batch_index]) > 0:
#             msd = compute_average_surface_distance(surface_distances)
#             msd_list.append(msd)
            
#             hd95 = compute_robust_hausdorff(surface_distances, 0.95)
#             hd95_list.append(hd95)
            
            
            
            
#     return surface_dice_list, msd_list, hd95_list, dice_list
preds = []
for index in range(len(test_inputs)):
    img = test_inputs[index:index+1]
    pred = model.predict(img)
    preds.append(pred[0])
    
preds = np.array(preds)
preds = np.round(preds)
stats_patient = google_metrics(test_truths, preds, spacing_mm=[0.85, 0.85, 1.907], organ_tol_mm= 0)
np.mean(stats_patient[0]), np.mean(stats_patient[1]), np.mean(stats_patient[2])
plt.figure()
plt.imshow(test_truths[0,...,-1])
plt.figure()
plt.imshow(preds[0,...,-1])
import medpy.metric.binary
print(medpy.metric.binary.dc(preds, test_truths))
print(medpy.metric.binary.sensitivity(preds, test_truths))
print(medpy.metric.binary.specificity(preds, test_truths))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17785234899328858, 'fraction_numerical': 0.03785234899328859, 'mean_word_length': 3.4036643026004727, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '659804', 'license': 'Apache-2.0', 'n_tokens_mistral': 3034, 'n_tokens_neox': 2861, 'n_words': 439, 'path': 'prototyping/auto-segmentation/mc_old_3/vacbag_evaluation-Copy1.ipynb', 'repo_name': 'dg1an3/pymedphys', 'size': '7450'}