"""
'''
Created on Wed Apr 27 17:58:13 2016
'''

@author: nash
"""
import os
import numpy as np
from skimage import morphology, filters, io, measure
import pandas as pd
from scipy import ndimage
from PIL import Image


directory = r'C:\Users\nash\ActiveResearch\SkMel_ezrin_GFP\Analysis'

filelist = os.listdir(directory)

#Create a datastore for all files
collist = list(['Filename', 'NumberofCells','CellArea', 'CellIntensity', 'ClusterArea', 'ClusterIntensity', 'ClusterAreaFraction', 'AggregationScore'])
datastore = pd.DataFrame(columns=collist)


for file in filelist:
    im = io.imread(os.path.join(directory, file))
    im_thresh_yen = im > filters.threshold_yen(im)
    im_thresh_mean = im > np.mean(im)
    
    #Cells
    filledcell = ndimage.morphology.binary_fill_holes(im_thresh_mean)
    filledcell = morphology.remove_small_objects(filledcell, 1500)
    maskedcell = np.multiply(im, im_thresh_mean)
    labelcell = measure.label(filledcell)
    cellregion  = measure.regionprops(labelcell, maskedcell)
    cells = len(cellregion)
    CellAreaArray = np.zeros([cells])
    TotalCellIntensityArray = np.zeros([cells])
    
    for cell in range(len(cellregion)):
        CellAreaArray[cell] = cellregion[cell].area
        TotalCellIntensityArray[cell] = np.multiply(cellregion[cell].area,cellregion[cell].mean_intensity)
    
    CellAreaTotal = np.sum(CellAreaArray)
    CellTotalIntensity = np.sum(TotalCellIntensityArray)

    #Clusters        
    filledpole = ndimage.morphology.binary_fill_holes(im_thresh_yen)
    filledpole = morphology.remove_small_objects(filledpole, 5)
    maskedpole = np.multiply(im, filledpole)
    labelpole = measure.label(filledpole)
    poleregion = measure.regionprops(labelpole, maskedpole)
    clusters=len(poleregion)
    ClusterIntensityAreaArray = np.zeros([clusters,2])
        
        
        #TotalClusterIntensityArray[cluster] = np.multiply(poleregion[cluster].area,poleregion[cluster].mean_intensity)
    if (clusters == 0):
        ClusterArea = 0
        ClusterIntensity = 0
        ClusterAreaFraction = 0
        FractionPerCluster = 0
        AggregationScore = 0
    else:
        for cluster in range(len(poleregion)):
            ClusterIntensityAreaArray[cluster] = [poleregion[cluster].area, np.multiply(poleregion[cluster].area,poleregion[cluster].mean_intensity)]
        LargestClusterArea, LargestClusterIntensity = np.sort(ClusterIntensityAreaArray)[0]        
        ClusterArea = LargestClusterArea
        ClusterIntensity=LargestClusterIntensity
        ClusterAreaFraction = 100.0*np.divide(ClusterArea, CellAreaTotal)
        ClusterIntensityFraction=100.0*np.divide(ClusterIntensity,CellTotalIntensity)
        AggregationScore = ClusterIntensityFraction/ClusterAreaFraction
        
    
    #Create list of values and pass it into datastore
    RecordList = list([file, cells, CellAreaTotal, CellTotalIntensity, ClusterArea, ClusterIntensity, ClusterAreaFraction, AggregationScore])
    datastore.loc[len(datastore)] = RecordList
    
    #Create the composite image
    composite = np.zeros([np.shape(im)[0],np.shape(im)[1],3])
    composite[:,:,0]=im
    composite[:,:,1]=np.logical_xor(filledcell, filledpole).astype('uint8')*50
    composite[:,:,2]=filledpole.astype('uint8')*50
    composite = Image.fromarray(composite.astype('uint8'))
    composite.save(os.path.join(directory, file+'_regions_comp.png'), 'png')

#Write the datastore
datastore.to_csv(os.path.join(directory,'Summary_Results.csv'))