Skip to content
Snippets Groups Projects
lung_feature_patch_allPatients.py 31.5 KiB
Newer Older
  • Learn to ignore specific revisions
  • monj's avatar
    monj committed
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    #!/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