"""
Spyder Editor

This is a temporary script file.
"""

import xlrd
import numpy as np
import matplotlib.pyplot as plt
import sys
import cv2
from PyQt4 import QtGui
import matplotlib.pyplot as plt
from scipy import stats

import time
import colorsys

app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()



####################### Open and read an Excel file


book = xlrd.open_workbook("Excel_file.xlsx")
sheet = book.sheet_by_index(0)

####################### ipmport video file
cap = cv2.VideoCapture("video_file.avi" )


classv0=[]
classv1=[]
classv2=[]
classv3=[]
classv4=[]
classv5=[]
classv6=[]

classvAll0=[]
classvAll1=[]
classvAll2=[]
classvAll3=[]
classvAll4=[]
classvAll5=[]
classvAll6=[]

tclassv0=[]
tclassv1=[]
tclassv2=[]
tclassv3=[]
tclassv4=[]
tclassv5=[]
tclassv6=[]

####################### set video parameters


FrameTime=150   

diffnew=-6  # shift of first cross frame
xname=[]
for FrameTime in range(45+diffnew, 230+45+diffnew,5):

    xname.append(FrameTime)
    cap = cv2.VideoCapture(filename )

    for x in range(0, (FrameTime)*FrameRate):
        ret, frame = cap.read()
        cv2.imshow('frame', frame)
        cv2.imwrite('01.png',frame)
        img0 = cv2.imread('01.png')
    
        zero_ratio=np.float(img0[img0==0].size)/img0.size
    
    if zero_ratio> 0.20:
        xname.append(FrameTime)
        cap = cv2.VideoCapture(filename )
    
        for x in range(0, FrameTime*FrameRate+1):
            ret, frame = cap.read()
        
        cv2.imshow('frame', frame)
        cv2.imwrite('01.png',frame)
        img0 = cv2.imread('01.png')

    img2=np.zeros(shape=(img0.shape[0],img0.shape[1],3))
    img=np.asarray( img2, dtype="uint8" )
    
    img[...,0]=img0[...,2]
    img[...,1]=img0[...,1]
    img[...,2]=img0[...,0]
    
    GPX=[]     # Gaze Point X
    GPY=[]     # Gaze Point Y
    GPT=[]     # Gaze Duration
    GPQ=[]     # Quality of point 
    
    GPT0=[]     # Time of point 
    
    E=[]       #Eval
    
    stamp=1
    shift=22
    D2V=-14
    st=shift+np.int((FrameTime+D2V-stamp)*10*12)
    
    ed=shift+np.int((FrameTime+D2V+stamp)*10*12)

          
####################### import gaze point coordinates from the columns of the excel file
 
    for row in range(st,ed):
        if sheet.cell(row,50).value and sheet.cell(row,51).value:
    
            GPX.append (sheet.cell(row,50).value)   #right
            GPY.append (sheet.cell(row,51).value)
            GPT.append (sheet.cell(row,44).value)
            GPQ.append (sheet.cell(row,77).value)
       
    GPQ=np.asarray(GPQ)        
    GPX=[np.str(x) for x in GPX]
    GPY=[np.str(x) for x in GPY]
    GPX=np.float32(np.asarray(GPX))
    GPY=np.float32(np.asarray(GPY))

    
    
    number_of_rows = sheet.nrows
    number_of_columns = sheet.ncols
    
    items = []
    rows = []

    GPXn=[]
    GPYn=[]
    GPTn=[]
    time1n=[]
    for i in range(len(GPQ)):

         if GPQ[i]==0:
            if (GPX[i]<1680 and GPY[i]<1050 and GPX[i]>0 and GPY[i]>0):
                GPXn.append( np.float(GPX[i]))
                GPYn.append( np.float(GPY[i]))
                GPTn.append( np.float(GPT[i]))

    
    GPXn=np.asarray(GPXn)        
    GPYn=np.asarray(GPYn) 
    GPTn=np.asarray(GPTn) 
    
    if GPT:
        
####################### create the heatmap
    
        heatmap, xedges, yedges = np.histogram2d(GPXn, GPYn, bins=50)
        extent = [xedges[0], xedges[-1], yedges[-1], yedges[0]]
        

        m1, m2 = GPXn, GPYn
  
        xmin, xmax = 0, 1680
        ymin, ymax = 0, 1050
        

        x, y = np.mgrid[0:xmax:100j, 0:ymax:100j]
        positions = np.vstack([x.ravel(), y.ravel()])
        values = np.vstack([m1, m2])
        kernel = stats.gaussian_kde(values)
        f =np.reshape(kernel(positions).T, x.shape)
        f=np.size(GPXn)*f/(np.max(f)-np.min(f))
        x1, y1 = 1, 1
        
 
        dif_frame=45+diffnew-(432./60)
    
        FrameRateClass=60
 
        frame_class_name1='green_'
        frame_class_name2=np.str(np.int(FrameRateClass*(FrameTime-dif_frame))).zfill(5)
        frame_class_name3='.pairwise.txt'
        frame_class_name='D:\green_segmentation_results\\'+frame_class_name1+frame_class_name2+frame_class_name3
    
        arr = []
   
        inp = open (frame_class_name,"r")
        #read line into array 
        for line in inp.readlines():
            # add a new sublist
            arr.append([])
            # loop over the elemets, split by whitespace
            for i in line.split():
                    arr[-1].append(int(i))
                
        imgc=np.array(arr).astype('uint8') +1     

####################### overlay the heatmap with the corresponding frame of the video file
   
        rows,cols = imgc.shape
        pts1 = np.float32([[0,0],[0,1080],[1920,0],[1920,1080]])
        pts2 = np.float32([[0,50],[0,1050-55],[1680,50],[1680,1050-55]])
        
        M = cv2.getPerspectiveTransform(pts1,pts2)
        imgc_new = cv2.warpPerspective(imgc,M,(1680,1050),cv2.INTER_NEAREST)
       
        rowc=np.uint(np.round(GPYn))
        colc=np.uint(np.round(GPXn))
        Class=imgc_new
                   
        Class_vlaue=Class[rowc,colc]        
        class1=Class_vlaue[Class_vlaue==5].size        
        class2=Class_vlaue[Class_vlaue==6].size        
        class3=Class_vlaue[Class_vlaue==4].size        
        class4=Class_vlaue[Class_vlaue==1].size        
        class5=Class_vlaue[Class_vlaue==3].size        
        class6=Class_vlaue[Class_vlaue==2].size        
          
        classes0=[class1,class2,class3,class4,class5,class6]
        classes=np.array(classes0)
        classesn=100.*np.float16(classes)/np.sum(classes)
        
        classv1.append(classesn[0])
        classv2.append(classesn[1])
        classv3.append(classesn[2])
        classv4.append(classesn[3])
        classv5.append(classesn[4])
        classv6.append(classesn[5])
        
        tclass1=np.sum(GPTn[Class_vlaue==5])
        tclass2=np.sum(GPTn[Class_vlaue==6])
        tclass3=np.sum(GPTn[Class_vlaue==4])
        tclass4=np.sum(GPTn[Class_vlaue==1])
        tclass5=np.sum(GPTn[Class_vlaue==3])
        tclass6=np.sum(GPTn[Class_vlaue==2])
        
        tclasses0=[tclass1,tclass2,tclass3,tclass4,tclass5,tclass6]
        tclasses=np.array(tclasses0)
        tclassesn=100.*tclasses/np.sum(tclasses)    
        
        tclassv1.append(tclassesn[0])
        tclassv2.append(tclassesn[1])
        tclassv3.append(tclassesn[2])
        tclassv4.append(tclassesn[3])
        tclassv5.append(tclassesn[4])
        tclassv6.append(tclassesn[5])
               
        classAll1=Class[Class==5].size        
        classAll2=Class[Class==6].size        
        classAll3=Class[Class==4].size        
        classAll4=Class[Class==1].size        
        classAll5=Class[Class==3].size        
        classAll6=Class[Class==2].size   
      
        classesAll0=[ classAll1,classAll2,classAll3,classAll4,classAll5,classAll6]
        classesAll=(classesAll0)
        classesnAll=100.*np.float32(classesAll)/np.sum(classesAll)
        
        classvAll1.append(classesnAll[0])
        classvAll2.append(classesnAll[1])
        classvAll3.append(classesnAll[2])
        classvAll4.append(classesnAll[3])
        classvAll5.append(classesnAll[4])
        classvAll6.append(classesnAll[5])
         
####################### plot the image and points
        
        fig=plt.figure()
        plt.subplot(2, 2, 1)    
        size=[]
        size_seq=[]
        size=GPTn/np.max(GPTn)
        
        size_seq=np.arange(np.size(GPTn))/np.float(np.size(GPTn))
        
        plt.imshow(img)
        plt.scatter(GPXn, GPYn, s=1000*size, c=size_seq, alpha=0.5)
        plt.show()
    
        plt.subplot(2, 2, 2)    
    
        plt.xlim(xmin,xmax)
        plt.ylim(ymax,ymin)
        
        plt.imshow(img)
        f[f<1]=None
 
        plt.imshow(np.rot90(f), cmap='jet', extent=[xmin, xmax, ymin, ymax],  alpha=0.7)
       
        plt.colorbar()

        plt.xlabel('GPX (pixel)')
        plt.ylabel('GPY (pixel)')
        plt.show()
    
  
        plt.subplot(2, 2, 3)    
        plt.scatter(GPXn, GPYn, s=1000*size, c=size_seq, alpha=0.5)
        plt.imshow(imgc_new)
        plt.show()
   
        plt.subplot(2, 2, 4)    
        plt.xlim(xmin,xmax)
        plt.ylim(ymax,ymin)
        
        plt.imshow(imgc_new)
 
        plt.imshow(np.rot90(f), cmap='jet', extent=[xmin, xmax, ymin, ymax],  alpha=0.7)
        plt.colorbar()
        
        plt.xlabel('GPX (pixel)')
        plt.ylabel('GPY (pixel)')
        plt.show()
    
        frame_class_name1out='SLFrameOfSec'
        frame_class_name2out=np.str(FrameTime-diffnew).zfill(5)
        frame_class_name3out='.png'
        frame_class_nameout=frame_class_name1out+frame_class_name2out+frame_class_name3out
        mng = plt.get_current_fig_manager()
        mng.full_screen_toggle()
        fig.savefig(frame_class_nameout)   # save the figure to file
        plt.close(fig)    # close the figure
    
fig=plt.figure()
t= np.linspace(1,np.size(classv1),np.size(classv1))

plot1=plt.plot(t, classv1, '-o', color='sandybrown',label='Road'  )
plot2=plt.plot(t, classv2, '-p',color='sienna', label='Rock'  )
plot3=plt.plot(t, classv3, '-rs', label='Man-made'  )
plot4=plt.plot(t, classv4, '-gs',color='lime', label='Bush'  )
plot5=plt.plot(t, classv5, '-g^', label='Tree'  )
plot6=plt.plot(t, classv6, '-co', label='Sky'  )

plt.legend( loc='best', numpoints = 1 )

plt.xlabel('Frame number')
plt.ylabel('Fixation %')
plt.show()

frame_class_nameout1='Charts01.png'
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
fig.savefig(frame_class_nameout1)   # save the figure to file
plt.close(fig)

Tree=np.array(classv1)+np.array(classv2)+np.array(classv3)+np.array(classv4)+np.array(classv5)
Bush=np.array(classv1)+np.array(classv2)+np.array(classv3)+np.array(classv4)
Man_made=np.array(classv1)+np.array(classv2)+np.array(classv3)
Rock=np.array(classv1)+np.array(classv2)
Road=np.array(classv1)


fig=plt.figure()
plt.bar(t, classv1, color = 'sandybrown',label='Road' )
plt.bar(t, classv2, bottom=Road,color = 'sienna', label='Rock' )
plt.bar(t, classv3, bottom=Rock,color = 'r', label='Man-made'  )
plt.bar(t, classv4, bottom=Man_made,color = 'lime', label='Bush'  )
plt.bar(t, classv5, bottom=Bush,color = 'g', label='Tree'  )
plt.bar(t, classv6, bottom=Tree,color = 'b', label='Sky'  )

plt.xticks(t+0.5, xname,rotation=45)
plt.xlabel('Time (sec)')
plt.ylabel('Fixation %')
plt.legend( loc='best', numpoints = 1 )
plt.ylim([0,105])

plt.show()

frame_class_nameout2='C:\Users\Ebadat\Dropbox\ET prog\ZABFrames\Charts02.png'
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
fig.savefig(frame_class_nameout2)   # save the figure to file
plt.close(fig) 


TreeAll=np.array(classvAll1)+np.array(classvAll2)+np.array(classvAll3)+np.array(classvAll4)+np.array(classvAll5)
BushAll=np.array(classvAll1)+np.array(classvAll2)+np.array(classvAll3)+np.array(classvAll4)
Man_madeAll=np.array(classvAll1)+np.array(classvAll2)+np.array(classvAll3)
RockAll=np.array(classvAll1)+np.array(classvAll2)
RoadAll=np.array(classvAll1)


fig=plt.figure()
plt.bar(t, classvAll1, color = 'sandybrown',label='Road' )
plt.bar(t, classvAll2, bottom=RoadAll,color = 'sienna' , label='Rock' )
plt.bar(t, classvAll3, bottom=RockAll,color = 'r', label='Man-made'  )
plt.bar(t, classvAll4, bottom=Man_madeAll,color = 'lime', label='Bush'  )
plt.bar(t, classvAll5, bottom=BushAll,color = 'g', label='Tree'  )
plt.bar(t, classvAll6, bottom=TreeAll,color = 'b', label='Sky'  )

plt.xticks(t+0.5, xname,rotation=40)
plt.xlabel('Time (sec)')
plt.ylabel('Frame content %')
plt.legend( loc='best', numpoints = 1 )
plt.ylim([0,105])
plt.show()

frame_class_nameout3='C:\Users\Ebadat\Dropbox\ET prog\ZABFrames\Charts03.png'
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
fig.savefig(frame_class_nameout3)   # save the figure to file
plt.close(fig) 
#-------------------------------------

classnames=['Road', 'Rock', 'Man_made', 'Bush', 'Tree', 'Sky']
width = 0.5
ind = np.arange(6)  # points on the x-axis
classvalue0=[np.sum(classv1),np.sum(classv2),np.sum(classv3),np.sum(classv4),np.sum(classv5),np.sum(classv6)]
classvalue=classvalue0/(np.sum(classvalue0)/100)

tclassvalue0=[np.sum(tclassv1),np.sum(tclassv2),np.sum(tclassv3),np.sum(tclassv4),np.sum(tclassv5),np.sum(tclassv6)]

tclassvalue=tclassvalue0/(np.sum(tclassvalue0)/100)


classnames=[ 'Road', 'Rock', 'Man_made', 'Bush', 'Tree', 'Sky']
width = 0.5
ind = np.arange(6)  # points on the x-axis
classvalueAll0=[np.sum(classvAll1),np.sum(classvAll2),np.sum(classvAll3),np.sum(classvAll4),np.sum(classvAll5),np.sum(classvAll6)]

classvalueAll=classvalueAll0/(np.sum(classvalueAll0)/100)

#-------------------------------------

# data to plot
n_groups = 6
means_frank = classvalueAll
means_guido1 = classvalue
means_guido2 = tclassvalue
 
# create plot
fig= plt.figure()
index = np.arange(n_groups)
bar_width = 0.25
opacity = 0.8
 
rects1 = plt.bar(index-0.5*bar_width, means_frank, bar_width,
                 alpha=opacity,
                 color='b',
                 label='Frames')
 
rects2 = plt.bar(index +0.5*bar_width, means_guido1, bar_width,
                 alpha=opacity,
                 color='g',
                 label='Eye Tracking Instance')

rects3 = plt.bar(index +1.5*bar_width, means_guido2, bar_width,
                 alpha=opacity,
                 color='y',
                 label='Eye Tracking Time')
 
plt.xticks(index + bar_width, ('Road', 'Rock', 'Man_made', 'Bush', 'Tree', 'Sky'))
plt.legend()
plt.ylim([0,100])
plt.tight_layout()
plt.show()


frame_class_nameout='C:\Users\Ebadat\Dropbox\ET prog\ZABFrames\Charts04.png'
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
fig.savefig(frame_class_nameout)   # save the figure to file
plt.close(fig) 

####################### save the results in a an excel file

import xlsxwriter

filenameXLSX='output_excel_file1.xlsx'
classnames=['Sec' , 'Road', 'Rock', 'Man_made', 'Bush', 'Tree', 'Sky']
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook(filenameXLSX)
worksheet = workbook.add_worksheet()

# Iterate over the data and write it out row by row.
for j in range(len(classnames)):
    worksheet.write(0, j,classnames[j])

for i in range(len(classv1)):
    worksheet.write(i+1, 0,45+i*5)
    worksheet.write(i+1, 1,classv1[i])
    worksheet.write(i+1, 2,classv2[i])
    worksheet.write(i+1, 3,classv3[i])
    worksheet.write(i+1, 4,classv4[i])
    worksheet.write(i+1, 5,classv5[i])
    worksheet.write(i+1, 6,classv6[i])

workbook.close()

filenameXLSX='output_excel_file2.xlsx'
classnames=['Sec' , 'Road', 'Rock', 'Man_made', 'Bush', 'Tree', 'Sky']
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook(filenameXLSX)
worksheet = workbook.add_worksheet()

# Iterate over the data and write it out row by row.
for j in range(len(classnames)):
    worksheet.write(0, j,classnames[j])

for i in range(len(classv1)):
    worksheet.write(i+1, 0,45+i*5)
    worksheet.write(i+1, 1,classvAll1[i])
    worksheet.write(i+1, 2,classvAll2[i])
    worksheet.write(i+1, 3,classvAll3[i])
    worksheet.write(i+1, 4,classvAll4[i])
    worksheet.write(i+1, 5,classvAll5[i])
    worksheet.write(i+1, 6,classvAll6[i])

workbook.close()



