#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for extracting patches from max-projection images and visualizing their clustering

Basic functionality by Anders B. Dahl.
- Compute maximum projection images 
- Extract patches
- Cluster patches
- Build assignment histograms
- Build probability images from the ratio between the histogram for healthy and diseased. 

Extended functionality by Monica J. Emerson.
- Adapted the above to integrate image normalisation, e.g. modified max proj.image functions.
- Created a pipeline to analyse multiple samples/patients.
- Study of several diseases. 
- Added functionality for supporting the analysis of different data versions.
- Computation of health scores per image, sample and patient.
- Visualisation of cluster centres as a grid.
- Boxplots to compare probabilities across samples and to clinical values.
- Normalisation of intensities across images and channels.
- Possibility to ignore the background (air phase).
- Visualisation of assignment images to inspect results and support the development of the approach to ignore background.
- Implementation and investigation of feature variations (colour, bnw, bnw+colour).
- Study of the parameters (nr clusters and scale - relative patch/image size) 
- Extended visualisation of cluster centres to support the comparison across diseases and parameters.
    a) Visualisation of cluster centres split into channels.
    b) Compute a population (p) and condition probability (c) value for each cluster.
    c) Identify the presence of "weak" clusters. If they exist, rerun kmeans.
    d) Select and visualise characteristic clusters for the conditions based on p and c.
    e) Plot all clusters in the population/condition probability space.
    f) Order cluster centres according to condition probability 
"""

import numpy as np
import matplotlib.pyplot as plt
import sklearn.cluster
import microscopy_analysis as ma
import skimage.io 
import skimage.transform
 
import os
from datetime import datetime
import sys
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

startTime = datetime.now()

plt.close('all')

sc_fac = 0.25 #25 #25 #0.5 # scaling factor of the image
patch_size = 17
nr_clusters = 100 # number of clusters

#%% Directories

version = 'corrected_bis'
preprocessing = ''  #'/preprocessed_ignback/' #''(none)
colour_mode = 'colour' #'bnw' #colour
disease = ['sarcoidosis']#diseased (mix, 2 of each condition)' #''emphysema' 'sarcoidosis'


# input directories - images start with the name 'frame'
dir_in = '../maxProjImages_'+version + preprocessing 
# dir_control = dir_in + 'control/' # 200401_109a/'
# dir_sick = dir_in + disease + '/' #191216_100a/'
base_name = 'frame'


#output directories
dir_results = '../results_monj/patches/data_' + version+'/' #rerun just to make sure not to muck up the results
os.makedirs(dir_results, exist_ok = True)  

dir_probs = dir_results + disease + '_' + colour_mode + '_%dclusters_%ddownscale_%dpatchsize/'%(nr_clusters,1/sc_fac,patch_size)
ma.make_output_dirs(dir_probs, disease)

dir_probs_withBack = dir_probs + 'withBackground'
ma.make_output_dirs(dir_probs_withBack, disease)

# if not os.path.exists(dir_probs):
#         os.mkdir(dir_probs)
#         os.mkdir(dir_probs + 'control/')
#         os.mkdir(dir_probs + disease + '/')
#         os.mkdir(dir_probs + 'control_withBackground/')
#         os.mkdir(dir_probs + disease + '_withBackground/')
        
#%% Read (preprocessed) maximum corrected images
#Read maximum projection images (runtime ~= 20 s )
print('Reading maximum projection images')

max_img_list_control = ma.read_max_imgs(dir_in+ 'control', base_name)
max_img_list_sick = ma.read_max_imgs(dir_in+ disease, base_name)

 
# max_im_list_control = ma.read_max_ims(dir_in_max + 'control/' ,base_name,sc_fac,colour_mode)

# max_im_list_sick = []    
# for sample in dir_list_sick:
#     in_dir = dir_sick + sample + '/'
#     dir_list = [dI for dI in sorted(os.listdir(in_dir)) if dI[0:len(base_name)]==base_name]
#     frames_list = []
#     for ind, frame in enumerate(dir_list):
#         frame_path = in_dir + frame
#         if colour_mode == 'bnw':
#             img = skimage.color.rgb2gray(skimage.io.imread(frame_path).astype(float))
#             max_im_list_sick += [skimage.transform.rescale(img, sc_fac)] 
#         else:
#             img = skimage.io.imread(frame_path).astype(float)
#             max_im_list_sick += [skimage.transform.rescale(img, sc_fac, multichannel=True)] 

#TO DO: Rescale max proj. images, overwrite original variables
#TO DO: Compute bnw version, but keep the colour one for displaying it at the end

#%% Compute patches
patch_feat_list_control = []
for max_im in max_im_list_control:
    patch_feat_list_control += [ma.ndim2col_pad(max_im, (patch_size, patch_size),norm=False).transpose()]

patch_feat_list_sick = []
for max_im in max_im_list_sick:
    patch_feat_list_sick += [ma.ndim2col_pad(max_im, (patch_size, patch_size),norm=False).transpose()]

patch_feat_total = []
patch_feat_total += patch_feat_list_control
patch_feat_total += patch_feat_list_sick

#%% features for clustering
nr_keep = 10000 # number of features randomly picked for clustering 
n_im = len(patch_feat_total)
feat_dim = patch_feat_total[0].shape[1]
patch_feat_to_cluster = np.zeros((nr_keep*n_im,feat_dim))
f = 0
for patch_feat in patch_feat_total:
    keep_indices = np.random.permutation(np.arange(patch_feat.shape[0]))[:nr_keep]
    patch_feat_to_cluster[f:f+nr_keep,:] = patch_feat[keep_indices,:]
    f += nr_keep

#%% k-means clustering
batch_size = 1000
th_nr_pathesINcluster = 5

if os.path.exists(dir_probs + 'array_cluster_centres'+colour_mode+'.npy'):
     cluster_centres = np.load(dir_probs + 'array_cluster_centres'+colour_mode+'.npy')
     #kmeans = sklearn.cluster.MiniBatchKMeans(n_clusters=nr_clusters, init = cluster_centres, batch_size = batch_size)
     #kmeans.fit(patch_feat_to_cluster)
     kmeans = sklearn.cluster.MiniBatchKMeans(n_clusters=nr_clusters, batch_size = batch_size)
     kmeans.cluster_centers_=cluster_centres
     reusing_clusters = True
else:
    kmeans = sklearn.cluster.MiniBatchKMeans(n_clusters=nr_clusters, batch_size = batch_size)
    kmeans.fit(patch_feat_to_cluster)
    all_cluster_centres = kmeans.cluster_centers_
    
    #Cluster statistics
    features_in_cluster = []
    for cluster in range(0,nr_clusters):
        features_in_cluster += [[ind for ind,i in enumerate(kmeans.labels_) if i==cluster]]  
    nr_feat_in_cluster =  [len(i) for i in features_in_cluster]  
    
    nr_weakClusters = len([1 for i in nr_feat_in_cluster if i<th_nr_pathesINcluster])
    
    if nr_weakClusters!=0:
        sys.exit(str(nr_weakClusters)+ " clusters composed of less than "+str(th_nr_pathesINcluster)+" images") 
    else:
        np.save(dir_probs + 'array_cluster_centres'+colour_mode+'.npy', all_cluster_centres)    # .npy extension is added if not given
    
     
#%% Read background pixels
dir_background = dir_in + 'background/'
dir_background_list = [dI for dI in os.listdir(dir_background) if os.path.isdir(os.path.join(dir_background,dI))]

fig, axs = plt.subplots(2,len(dir_background_list), sharex=True, sharey=True)
patch_feat_back = []
for ind, directory in enumerate(dir_background_list):
    #load images and corresponding background labels
    file_names = [f for f in os.listdir(dir_background +directory) if f.endswith('.png')]
    im_file = [f for f in file_names if not f.startswith('back')].pop()
    label_file = [f for f in file_names if f.startswith('back')].pop() 
    im_back = skimage.io.imread(dir_background + directory + '/' + im_file).astype('uint8')
    label_back = skimage.color.rgb2gray(skimage.io.imread(dir_background + directory + '/' + label_file).astype('float'))
    label_back += -np.min(label_back)
    label_back = label_back.astype('bool')
    #plot imagesand corresonding labels
    axs[0][ind].imshow(im_back)
    axs[1][ind].imshow(label_back,'gray')
    plt.show()
    #compute features
    if colour_mode == 'bnw':
        im_back = skimage.transform.rescale(skimage.color.rgb2gray(im_back.astype(float)), sc_fac, multichannel=False)
    else :
        im_back = skimage.transform.rescale(im_back.astype(float), sc_fac, multichannel=True)
    im_feat = ma.ndim2col_pad(im_back, (patch_size, patch_size)).transpose()
    patch_feat_back += [im_feat[(skimage.transform.rescale(label_back, sc_fac, multichannel=False)==True).ravel(),:]]

#%% Plot all cluster centres

plot_grid_cluster_centres(kmeans.cluster_centers_)

if nr_clusters==100:
    fig, axs = plt.subplots(10,10, figsize=(5,5), sharex=True, sharey=True)
if nr_clusters==200:
    w, h = plt.figaspect(2.)
    fig, axs = plt.subplots(20,10, figsize=(w,h), sharex=True, sharey=True)  
if nr_clusters==1000:
    fig, axs = plt.subplots(100,100, figsize=(5,5), sharex=True, sharey=True)  

intensities = []
for ax, cluster_nr in zip(axs.ravel(), np.arange(0,nr_clusters)):
    if colour_mode == 'bnw':
        cluster_centre = np.reshape(kmeans.cluster_centers_[cluster_nr,:],(patch_size,patch_size))
        intensities += [sum((cluster_centre).ravel())] 
        ax.imshow(cluster_centre.astype('uint8'),cmap='gray')
    else:
        cluster_centre = np.transpose((np.reshape(kmeans.cluster_centers_[cluster_nr,:],(3,patch_size,patch_size))),(1,2,0))
        intensities += [sum((np.max(cluster_centre,2)).ravel())] 
        ax.imshow(cluster_centre.astype('uint8'))
    
plt.setp(axs, xticks=[], yticks=[])
plt.savefig(dir_probs + 'clusterCentres_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
 

#%% Histograms for background, healthy and sick
#hist_control, assignment_list_control, hist_back, assignment_back = ma.compute_assignment_hist(patch_feat_list_control, kmeans, background_feat=im_feat_back)

hist_background, assignment_list_background = ma.compute_assignment_hist(patch_feat_back, kmeans)
hist_control, assignment_list_control= ma.compute_assignment_hist(patch_feat_list_control, kmeans)
hist_sick, assignment_list_sick = ma.compute_assignment_hist(patch_feat_list_sick, kmeans)

#%% Cluster centres in the 2d space determined by the relationshop between histogram
occurrence_ratio = hist_control/hist_sick
occurrence_ratio[occurrence_ratio<1] = -1/occurrence_ratio[occurrence_ratio<1] 
populated = hist_control+hist_sick

plt.hist2d(occurrence_ratio,populated)

fig_control, ax_control = plt.subplots(figsize=(15,15))
ax_control.scatter(populated[occurrence_ratio>1], occurrence_ratio[occurrence_ratio>1]) 
ax_control.set_ylim(0.8,7)
ax_control.set_xlim(0,0.08)

fig_sick, ax_sick = plt.subplots(figsize=(15,15))
ax_sick.scatter(populated[occurrence_ratio<1], -occurrence_ratio[occurrence_ratio<1]) 
ax_sick.set_ylim(0.8,7)
ax_sick.set_xlim(0,0.08)

for x0, y0, cluster_nr in zip(populated, occurrence_ratio, np.arange(0,nr_clusters)):
    if colour_mode == 'bnw':
        cluster_centre = np.reshape(kmeans.cluster_centers_[cluster_nr,:],(patch_size,patch_size))
    else:
       cluster_centre = np.transpose((np.reshape(kmeans.cluster_centers_[cluster_nr,:],(3,patch_size,patch_size))),(1,2,0))
    if y0>0:
        if colour_mode == 'bnw':
            ab = AnnotationBbox(OffsetImage(cluster_centre.astype('uint8'),cmap='gray'), (x0, y0), frameon=False)
        else:
            ab = AnnotationBbox(OffsetImage(cluster_centre.astype('uint8')), (x0, y0), frameon=False)
        ax_control.add_artist(ab)
        plt.savefig(dir_probs + 'controlClusterCentres_2Dspace_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
    else:
        if colour_mode == 'bnw':
            ab = AnnotationBbox(OffsetImage(cluster_centre.astype('uint8'),cmap='gray'), (x0, -y0), frameon=False)
        else:
           ab = AnnotationBbox(OffsetImage(cluster_centre.astype('uint8')), (x0, -y0), frameon=False)
        ax_sick.add_artist(ab)
        plt.savefig(dir_probs + 'sickClusterCentres_2Dspace_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)

    
    
#%% show bar plot of healthy and sick

fig, ax = plt.subplots(1,1)
ax.bar(np.array(range(0,nr_clusters)), hist_background, width = 1)
plt.show()
plt.savefig(dir_probs + 'backgroundHistogram_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
  
fig, ax = plt.subplots(1,1)
ax.bar(np.array(range(0,nr_clusters))-0.25, hist_control, width = 0.5, label='Control', color = 'r')
ax.bar(np.array(range(0,nr_clusters))+0.25, hist_sick, width = 0.5, label='Sick', color = 'b')
ax.legend()
plt.savefig(dir_probs + 'assignmentHistograms_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
  

#%% Find background and characteristic clusters

#background clusters
clusters_background_intBased = [i for i in range(len(intensities)) if intensities[i] < 7000]
clusters_background_annotBased = [ind for ind, value in enumerate(hist_background)  if value>0]

clusters_background = list(set(clusters_background_intBased) | set(clusters_background_annotBased)) 
print('Background clusters'+str(clusters_background))

#characteristic clusters
th_proportion = 2#2 #2.4
th_populated = 0.01#0.005#0.015

clusters_sick = (hist_sick>th_populated)&(hist_sick>th_proportion*hist_control)
clusters_sick = [ind for ind,value in enumerate(clusters_sick) if value == True]
clusters_control = (hist_control>th_populated)&(hist_control>th_proportion*hist_sick)
clusters_control = [ind for ind,value in enumerate(clusters_control) if value == True]

#eliminate backgorund clusters if contained here
clusters_control = [i for i in clusters_control if i not in clusters_background]
clusters_sick = [i for i in clusters_sick if i not in clusters_background]

print('Clusters characteristic of the ' + disease + ' tissue',clusters_sick)
print('Clusters characteristic of the control tissue',clusters_control)

#%% Plot centres of the characteristic clusters 
cluster_centres_control = kmeans.cluster_centers_[clusters_control]

#control clusters and contrast enhanced
cluster_centres_control = kmeans.cluster_centers_[clusters_control]
fig, axs = plt.subplots(1,len(clusters_control), figsize=(len(clusters_control)*3,3), sharex=True, sharey=True)
fig.suptitle('Cluster centres for control')
if colour_mode!='bnw':
    fig_split, axs_split = plt.subplots(3,len(clusters_control), figsize=(len(clusters_control)*3,9), sharex=True, sharey=True)
    fig_split.suptitle('Control centres split channels (contrast enhanced)')
for l in np.arange(0,len(clusters_control)):
    if colour_mode == 'bnw':
        cluster_centre = np.reshape(cluster_centres_control[l,:],(patch_size,patch_size))
        axs[l].imshow(cluster_centre.astype(np.uint8),cmap='gray')
        axs[l].axis('off')
        axs[l].set_title(clusters_control[l])
    else:    
        cluster_centre = np.transpose((np.reshape(cluster_centres_control[l,:],(3,patch_size,patch_size))),(1,2,0))
        axs_split[0][l].imshow(cluster_centre[...,0].astype(np.uint8),cmap='gray')
        axs_split[0][l].axis('off')
        axs_split[0][l].set_title(clusters_control[l])
        axs_split[1][l].imshow(cluster_centre[...,1].astype(np.uint8),cmap='gray')
        axs_split[1][l].axis('off')
        axs_split[2][l].imshow(cluster_centre[...,2].astype(np.uint8),cmap='gray')
        axs_split[2][l].axis('off')
        plt.figure(fig_split.number),
        plt.savefig(dir_probs + 'clusterCentres_control_splitContrastEnhanced_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
        axs[l].imshow(cluster_centre.astype(np.uint8))
        axs[l].axis('off')
        axs[l].set_title(clusters_control[l])
    plt.figure(fig.number),
    plt.savefig(dir_probs + 'clusterCentres_control_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
    
#sick clusters and contrast enhanced
cluster_centres_sick = kmeans.cluster_centers_[clusters_sick]
fig, axs = plt.subplots(1,len(clusters_sick), figsize=(len(clusters_sick)*3,3), sharex=True, sharey=True)
fig.suptitle('Cluster centres for sick')
if colour_mode!='bnw':
    fig_split, axs_split = plt.subplots(3,len(clusters_sick), figsize=(len(clusters_sick)*3,9), sharex=True, sharey=True)
    fig_split.suptitle('sick centres split channels (contrast enhanced)')
for l in np.arange(0,len(clusters_sick)):
    if colour_mode == 'bnw':
        cluster_centre = np.reshape(cluster_centres_sick[l,:],(patch_size,patch_size))
        axs[l].imshow(cluster_centre.astype(np.uint8),cmap='gray')
        axs[l].axis('off')
        axs[l].set_title(clusters_sick[l])
    else:
        cluster_centre = np.transpose((np.reshape(cluster_centres_sick[l,:],(3,patch_size,patch_size))),(1,2,0))
        axs_split[0][l].imshow(cluster_centre[...,0].astype(np.uint8),cmap='gray')
        axs_split[0][l].axis('off')
        axs_split[0][l].set_title(clusters_sick[l])
        axs_split[1][l].imshow(cluster_centre[...,1].astype(np.uint8),cmap='gray')
        axs_split[1][l].axis('off')
        axs_split[2][l].imshow(cluster_centre[...,2].astype(np.uint8),cmap='gray')
        axs_split[2][l].axis('off')
        plt.figure(fig_split.number),
        plt.savefig(dir_probs + 'clusterCentres_'+disease+'_splitContrastEnhanced_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
        axs[l].imshow(cluster_centre.astype(np.uint8))
        axs[l].axis('off')
        axs[l].set_title(clusters_sick[l])
    plt.figure(fig.number),
    plt.savefig(dir_probs + 'clusterCentres_'+disease+'_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
    
if colour_mode!='bnw':
    #plot sick and control clusters with the same intensity range
    max_value = []
    min_value = []
    for l in np.arange(0,len(clusters_control)):
        cluster_centre = np.transpose((np.reshape(cluster_centres_control[l,:],(3,patch_size,patch_size))),(1,2,0))
        max_value += [cluster_centre.max()]
        min_value += [cluster_centre.min()]
        
    for l in np.arange(0,len(clusters_sick)):
        cluster_centre = np.transpose((np.reshape(cluster_centres_sick[l,:],(3,patch_size,patch_size))),(1,2,0))
        max_value += [cluster_centre.max()]
        min_value += [cluster_centre.min()]
       
    range_max = max(max_value)
    range_min = min(min_value)
    
    fig_split, axs_split = plt.subplots(3,len(clusters_control), figsize=(len(clusters_control)*3,9),sharex=True, sharey=True)
    fig_split.suptitle('Control centres split channels (fixed intensity range)')
    for l in np.arange(0,len(clusters_control)):
        cluster_centre = np.transpose((np.reshape(cluster_centres_control[l,:],(3,patch_size,patch_size))),(1,2,0))
        im = np.zeros(cluster_centre.shape)
        im[...,0] = cluster_centre[...,0]
        axs_split[0][l].imshow(im.astype(np.uint8))
        axs_split[0][l].axis('off')
        axs_split[0][l].set_title(clusters_control[l])
        im = np.zeros(cluster_centre.shape)
        im[...,1] = cluster_centre[...,1]
        axs_split[1][l].imshow(im.astype(np.uint8))
        axs_split[1][l].axis('off')
        im = np.zeros(cluster_centre.shape)
        im[...,2] = cluster_centre[...,2]
        axs_split[2][l].imshow(im.astype(np.uint8))
        axs_split[2][l].axis('off')
        plt.savefig(dir_probs + 'clusterCentres_control_split_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
        
        
    fig_split, axs_split = plt.subplots(3,len(clusters_sick), figsize=(len(clusters_sick)*3,9),sharex=True, sharey=True)
    fig_split.suptitle('sick centres split channels (fixed intensity range)')
    for l in np.arange(0,len(clusters_sick)):
        cluster_centre = np.transpose((np.reshape(cluster_centres_sick[l,:],(3,patch_size,patch_size))),(1,2,0))
        im = np.zeros(cluster_centre.shape)
        im[...,0] = cluster_centre[...,0]
        axs_split[0][l].imshow(im.astype(np.uint8),vmin = range_min, vmax = range_max)
        axs_split[0][l].axis('off')
        im = np.zeros(cluster_centre.shape)
        im[...,1] = cluster_centre[...,1]
        axs_split[0][l].set_title(clusters_sick[l])
        axs_split[1][l].imshow(im.astype(np.uint8),vmin = range_min, vmax = range_max)
        axs_split[1][l].axis('off')
        im = np.zeros(cluster_centre.shape)
        im[...,2] = cluster_centre[...,2]
        axs_split[2][l].imshow(im.astype(np.uint8),vmin = range_min, vmax = range_max)
        axs_split[2][l].axis('off')
        plt.savefig(dir_probs + 'clusterCentres_'+disease+'_split_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
        
        
        
#%% display
                 
startTime_probs = datetime.now()

r,c = max_im_list_control[0].shape[:2]

version = '_withBackground'  #''#'_withBackground' #''

# prob_control_back = hist_control/(hist_control+hist_sick)
# prob_sick_back = hist_sick/(hist_control+hist_sick)
prob_control= hist_control/(hist_control+hist_sick)
prob_sick = hist_sick/(hist_control+hist_sick)

#Assign equal probability to the background clusters
# prob_sick = prob_sick_back
# prob_control = prob_control_back
if version == '':
    prob_sick[clusters_background] = 0.5
    prob_control[clusters_background] = 0.5
else:
    if not os.path.exists(dir_probs + 'control'+version+'/'):
        os.mkdir(dir_probs + 'control'+version+'/')
        os.mkdir(dir_probs + disease +version+'/')


#Pixel-wise probabilities for control patients
prob_im_control = []
for assignment in assignment_list_control:
    prob = prob_control[assignment.astype(int)]
    prob_im_control += [prob.reshape(r,c)]
   
# prob_im_control_back = []
# for assignment in assignment_list_control:
#     prob_back = prob_control_back[assignment.astype(int)]
#     prob_im_control_back += [prob_back.reshape(r,c)]

prob_im_list = []
prob_px_list = []
nr_list = 0
for directory in dir_list_control:
    in_dir = dir_control + directory + '/'
    dir_list = [dI for dI in os.listdir(in_dir) if dI[0:len(base_name)]==base_name]
    print(dir_list)
    im_all_control = []
    im_all_control += prob_im_control[nr_list:nr_list+len(dir_list)]
    im_all_control += max_im_list_control[nr_list:nr_list+len(dir_list)]
    fig, axs = plt.subplots(2,len(dir_list), figsize = (30,10), sharex=True, sharey=True)
    nr = 0
    prob_sample = np.zeros((len(dir_list),1))
    for ax, im in zip(axs.ravel(), im_all_control):
        print(nr)
        if nr<len(dir_list):
            if version == '':
                prob_im = sum(im[im!=0.5])/(im[im!=0.5]).size
            else:
                prob_im = sum(sum(im))/(r*c)
            prob_sample[nr] = prob_im
            
            ax.set_title('Pc '+str(round(prob_im,2)))
            #print(prob_sample)
        # elif nr<2*len(dir_list):
        #     prob_im_back = sum(im)/(r*c)
            
        nr += 1
        if nr<=len(im_all_control)/2:
            #ax.imshow(skimage.transform.resize(im, (1024,1024)), cmap=plt.cm.bwr, vmin = 0, vmax = 1)
            ax.imshow(im, cmap=plt.cm.bwr, vmin = 0, vmax = 1)
        else:
            #ax.imshow(skimage.transform.resize(im.astype(np.uint8), (1024,1024)))
            if colour_mode == 'bnw':
                ax.imshow(im.astype(np.uint8),cmap='gray')
            else:
                ax.imshow(im.astype(np.uint8))
    prob_im_list += [prob_sample]
    #prob_px_list += [(np.array(im_all_control[:len(dir_list)])).ravel()]
    plt.suptitle('Probability control of sample '+str(directory)+', avg:' + str(round(prob_sample.mean(),2))+ ' std:' + str(round(prob_sample.std(),2)))
    plt.savefig(dir_probs + 'control'+version+'/' + 'probImControl_'+str(directory)+'_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
    plt.show()
    nr_list += len(dir_list)

#Pixel-wise cluster assignments for control patients
if True: #sc_fac == 1:
    assignment_im_control = []
    for assignment in assignment_list_control:
        cluster_assignment = assignment.astype(int)
        assignment_im_control += [cluster_assignment.reshape(r,c)]
    
    nr_list = 0
    for directory in dir_list_control:
        in_dir = dir_control + directory + '/'
        dir_list = [dI for dI in os.listdir(in_dir) if dI[0:len(base_name)]==base_name]
        print(dir_list)
        im_all_control = []
        im_all_control += assignment_im_control[nr_list:nr_list+len(dir_list)]
        im_all_control += max_im_list_control[nr_list:nr_list+len(dir_list)]
        fig, axs = plt.subplots(2,len(dir_list), figsize = (30,10), sharex=True, sharey=True)
        for ax, im in zip(axs.ravel(), im_all_control):
            if ( im.ndim == 2 ):
                #ax.imshow(skimage.transform.resize(im, (1024,1024), order=0, preserve_range = True),cmap=plt.cm.gist_ncar,vmin = 0,vmax = nr_clusters-1)
                ax.imshow(im,cmap=plt.cm.gist_ncar,vmin = 0,vmax = nr_clusters-1)
            
            else:
                #ax.imshow(skimage.transform.resize(im.astype(np.uint8), (1024,1024)))
                ax.imshow(im.astype(np.uint8))
        plt.suptitle('Sample '+str(directory))
        plt.savefig(dir_probs + 'control/' + 'assignmentImControl_'+str(directory)+'_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
        plt.show()
        nr_list += len(dir_list)
                          
#Pixel-wise probabilities for sick patients
prob_im_sick = []
for assignment in assignment_list_sick:
    prob = prob_control[assignment.astype(int)]
    prob_im_sick += [prob.reshape(r,c)]

nr_list = 0
for directory in dir_list_sick:
    in_dir = dir_sick + directory + '/'
    dir_list = [dI for dI in os.listdir(in_dir) if dI[0:len(base_name)]==base_name]
    print(dir_list)
    im_all_sick = []
    im_all_sick += prob_im_sick[nr_list:nr_list+len(dir_list)]
    im_all_sick += max_im_list_sick[nr_list:nr_list+len(dir_list)]
    fig, axs = plt.subplots(2,len(dir_list), figsize = (30,10), sharex=True, sharey=True)
    nr = 0
    prob_sample = np.zeros((len(dir_list),1))
    for ax, im in zip(axs.ravel(), im_all_sick):
        print(nr)
        if nr<len(dir_list):
            if version == '':
                prob_im = sum(im[im!=0.5])/(im[im!=0.5]).size
            else:
                prob_im = sum(sum(im))/(r*c)
            #print(prob_im)
            prob_sample[nr] = prob_im
            ax.set_title('Pc '+str(round(prob_im,2)))
            #print(prob_sample)
        nr += 1
        if ( im.ndim == 2 ):
            #ax.imshow(skimage.transform.resize(im, (1024,1024)), cmap=plt.cm.bwr, vmin = 0, vmax = 1)
            ax.imshow(im, cmap=plt.cm.bwr, vmin = 0, vmax = 1)
        else:
            #ax.imshow(skimage.transform.resize(im.astype(np.uint8), (1024,1024)))
            ax.imshow(im.astype(np.uint8))
    prob_im_list += [prob_sample]
    prob_px_list += [(np.array(im_all_sick[:len(dir_list)])).ravel()]
    plt.suptitle('Probability control of sample '+str(directory)+', avg:' + str(round(prob_sample.mean(),2))+ ' std:' + str(round(prob_sample.std(),2)))
    plt.savefig(dir_probs + disease +version+'/' + 'probImSick_'+str(directory)+'_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
    plt.show()
    nr_list += len(dir_list)
    
    
#Pixel-wise cluster assignments for sick patients
if True: #sc_fac == 1:
    assignment_im_sick = []
    for assignment in assignment_list_sick:
        cluster_assignment = assignment.astype(int)
        assignment_im_sick += [cluster_assignment.reshape(r,c)]
    
    nr_list = 0
    for directory in dir_list_sick:
        in_dir = dir_sick + directory + '/'
        dir_list = [dI for dI in os.listdir(in_dir) if dI[0:len(base_name)]==base_name]
        print(dir_list)
        im_all_sick = []
        im_all_sick += assignment_im_sick[nr_list:nr_list+len(dir_list)]
        im_all_sick += max_im_list_sick[nr_list:nr_list+len(dir_list)]
        fig, axs = plt.subplots(2,len(dir_list), figsize = (30,10), sharex=True, sharey=True)
        for ax, im in zip(axs.ravel(), im_all_sick):
            if ( im.ndim == 2 ):
                #ax.imshow(skimage.transform.resize(im, (1024,1024), order=0, preserve_range = True),cmap=plt.cm.gist_ncar,vmin = 0,vmax = nr_clusters-1)
                ax.imshow(im,cmap=plt.cm.gist_ncar,vmin = 0,vmax = nr_clusters-1)
            else:
                #ax.imshow(skimage.transform.resize(im.astype(np.uint8), (1024,1024)))
                ax.imshow(im.astype(np.uint8))
        plt.suptitle('Sample '+str(directory))
        plt.savefig(dir_probs + disease + '/' + 'assignmentImSick_'+str(directory)+'_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
        plt.show()
        nr_list += len(dir_list)
              
endTime_probs = datetime.now() - startTime_probs
print(endTime_probs)

#%% Print computational time
endTime = datetime.now() - startTime
print(endTime)

#%% Box plots
fig, ax = plt.subplots(figsize = (15,5))
ax.set_title('Probability of scans capturing healthy tissue')
array_probs = np.squeeze(np.asarray(prob_im_list))
bp_healthy = ax.boxplot((array_probs[:12,...]).T, positions = range(12), patch_artist = True)
bp_sick = ax.boxplot(array_probs[12:,...].T, positions = range(13,25), patch_artist = True)

for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
    plt.setp(bp_healthy[element], color='black')

for patch in bp_healthy['boxes']:
    patch.set(facecolor='red')
    
for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
    plt.setp(bp_sick[element], color='black')

for patch in bp_sick['boxes']:
    patch.set(facecolor='blue')  
    
ax.set_xticklabels([i[-4:] for i in dir_list_control]+[i[-4:] for i in dir_list_sick])
ax.set_ylim(0.35,0.65)
ax.set_ylabel('Probability health')
#ax.set_ylim(0,1)

ax.tick_params(
    axis='both',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    #labelleft = False,      # ticks along the top edge are off
    #labelbottom=False
    )
    
if disease == 'emphysema':
    #overlay FEV1 values
    ax2 = ax.twinx()
    ax2.set_ylabel('FEV1')
    FEV1 = np.array([99.00, 98.90,np.nan,116.00,118.70,99.70, 26, 27.20, 31.00, 25.00, 22.00, 33.70])
    patients = np.concatenate((np.arange(0.5, 12.5, 2), np.arange(13.5,25.5,2)))
    ax2.plot(patients,FEV1,'kD')
    ax2.set_ylim(-20,160)
    
plt.savefig(dir_probs + 'boxPlots'+version+'_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
    
if disease == 'sarcoidosis':
    #overlay FEV1 values
    ax2 = ax.twinx()
    ax2.set_ylabel('FVC')
    FVC = np.array([99.00, 115.60,np.nan,121.00,118.70,119.50,60.20,54.00,75.30,27.00,48.50,40.30])
    patients = np.concatenate((np.arange(0.5, 12.5, 2), np.arange(13.5,25.5,2)))
    ax2.plot(patients,FVC,'kD')
    ax2.set_ylim(-20,160)
    
plt.savefig(dir_probs + 'boxPlots'+version+'_%dclusters_%ddownscale_%dpatchsize.png'%(nr_clusters,1/sc_fac,patch_size), dpi=300)
   
#%% Plot lung functions from the clinic

# cmap = plt.cm.bwr
# it = 0
# for im in prob_im_control:
#     im_tmp = skimage.transform.resize(im,(1024,1024),order=3)
#     norm = plt.Normalize(vmin=0, vmax=1)
#     im_out = cmap(norm(im_tmp))
#     out_name = '../results/prob_map/control_%02d.png' % int(it)
#     skimage.io.imsave(out_name, (255*im_out).astype(np.uint8))
#     it += 1

# it = 0
# for im in prob_im_sick:
#     im_tmp = skimage.transform.resize(im,(1024,1024),order=3)
#     norm = plt.Normalize(vmin=0, vmax=1)
#     im_out = cmap(norm(im_tmp))
#     out_name = '../results/prob_map/sick_%02d.png' % int(it)
#     skimage.io.imsave(out_name, (255*im_out).astype(np.uint8))
#     it += 1

# #%%
# max_im_list_control = ma.compute_max_im_list(dir_control, '.png', 'frame', 1)
# max_im_list_sick = ma.compute_max_im_list(dir_sick, '.png', 'frame', 1)
# #%%
# it = 0
# for im in max_im_list_control:
#     out_name = '../results/prob_map/control_max_im_%02d.png' % int(it)
#     skimage.io.imsave(out_name, (im).astype(np.uint8))
#     it += 1

# it = 0
# for im in max_im_list_sick:
#     out_name = '../results/prob_map/sick_max_im_%02d.png' % int(it)
#     skimage.io.imsave(out_name, (im).astype(np.uint8))
#     it += 1