import xlrd
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
from postProInstronDataTools import *
import os
os.chdir('..\\processedInstronData')

file = "combinedInstronData1.xlsx"
eMax = 1.7
writeModulusForEachSample = False

#breaking failure
bStrainI = list()
bStressI = list()
bStrainE = list()
bStressE = list()
bStrainW = list()
bStressW = list()
bStrainAll = list()
# init failure
fStrainI = list()
fStressI = list()
fStrainE = list()
fStressE = list()
fStrainW = list()
fStressW = list()
fStrainAll = list()
#damage
dStrainI = list()
dStressI = list()
dStrainE = list()
dStressE = list()
dStrainW = list()
dStressW = list()
dStrainAll = list()
#stiffness
stiffnessI = list()
stiffnessE = list()
stiffnessW = list()
#modulus
modulusI = list()
modulusE = list()
modulusW = list()
#thickness
thicknessI = list()
thicknessE = list()
thicknessW = list()
#thickness
widthI = list()
widthE = list()
widthW = list()
#thickness
heightI = list()
heightE = list()
heightW = list()
##area
# areaI = list()
# areaE = list()
# areaW = list()
#nb lamellae
nbI = list()
nbE = list()
nbW = list()
#nb local failure points
nbFailureI = list()
nbFailureE = list()
nbFailureW = list()
#goodness of linear fit (srtess-strain)
rSquares = list()
rSquaresI = list()
rSquaresE = list()
rSquaresW = list()

fullStrainRange = np.arange(0.,eMax+0.001,0.001)
for sheet in xlrd.open_workbook(file).sheets():
    if sheet.name.startswith('S'):
        geoData,fulStress,fulStrain = readSheet(sheet)
        thisThickness = geoData['Thickness']
        thisWidth = geoData['Length']
        thisDiscH = geoData['Width']
        thisArea = geoData['Area']
        thisNb = geoData['NbLamella']

        fullStressRange = np.interp(fullStrainRange, fulStrain, fulStress, right=np.nan)
        nanIdx = np.where(np.isfinite(fullStressRange) == 0)[0]
        ### MODULUS
        m0,residual,newMax = computeLinearSlope(fullStrainRange, fullStressRange,idxStart=5,stepSize=0.001)
        linearStress = m0*fullStrainRange
        rSquares.append(rsquare(linearStress[5:newMax],fullStressRange[5:newMax]))
        #stiffness
        ks0 = m0*thisArea/thisThickness
        ### BEGINNING OF DAMAGE 
        newMax = getEndOfLinearity(fullStrainRange, fullStressRange,5,newMax,residual)
        if not np.isnan(fullStressRange[newMax]): dStrainAll.append(fullStrainRange[newMax])    
        ### BEGINNING OF FAILURE
        ### to be computed only for the strain values greater than beginning of damage, for finite stress values
        try:
            endFullStrain = fullStrainRange[newMax:nanIdx[0]]
            endFullStress = fullStressRange[newMax:nanIdx[0]]
        except(IndexError):
            endFullStrain = fullStrainRange[newMax:]
            endFullStress = fullStressRange[newMax:]
        failureIdx = getBeginningOfFailure(endFullStrain,endFullStress,stepSize=0.001)
        failureStrain = endFullStrain[failureIdx:failureIdx+5]
        failureStress = endFullStress[failureIdx:failureIdx+5]
        fStrainAll.append(failureStrain[0])    
        ### MACROSCOPIC FAILURE
        if '_F' in sheet.name:
            breakStrain,breakStress,nbFailure = getMacroFailure(endFullStrain,endFullStress,stepSize=0.001)
            bStrainAll.append(breakStrain)    
        ### RECORD EVERYTHING IN LISTS       
        if 'I' in sheet.name:
            rSquaresI.append(rsquare(linearStress[5:newMax],fullStressRange[5:newMax]))
            if not np.isnan(fullStressRange[newMax]):
                dStrainI.append(fullStrainRange[newMax])
                dStressI.append(fullStressRange[newMax])
            fStrainI.append(failureStrain)
            fStressI.append(failureStress)
            thicknessI.append(thisThickness)
            heightI.append(thisDiscH)
            widthI.append(thisWidth)
            if '_F' in sheet.name:
                bStrainI.append(breakStrain)
                bStressI.append(breakStress)
                if nbFailure>0:
                    nbI.append(thisNb)
                    nbFailureI.append(nbFailure)
            modulusI.append(m0)
            stiffnessI.append(ks0)
        elif 'O' in sheet.name:
            rSquaresE.append(rsquare(linearStress[5:newMax],fullStressRange[5:newMax]))
            if not np.isnan(fullStressRange[newMax]):
                dStrainE.append(fullStrainRange[newMax])
                dStressE.append(fullStressRange[newMax])
            fStrainE.append(failureStrain)
            fStressE.append(failureStress)
            thicknessE.append(thisThickness)
            heightE.append(thisDiscH)
            widthE.append(thisWidth)
            if '_F' in sheet.name:
                bStrainE.append(breakStrain)
                bStressE.append(breakStress)
                if nbFailure>0:
                    nbE.append(thisNb)
                    nbFailureE.append(nbFailure)
            modulusE.append(m0)
            stiffnessE.append(ks0)
        else:
            rSquaresW.append(rsquare(linearStress[5:newMax],fullStressRange[5:newMax]))
            if not np.isnan(fullStressRange[newMax]):
                dStrainW.append(fullStrainRange[newMax])
                dStressW.append(fullStressRange[newMax])
            fStrainW.append(failureStrain)
            fStressW.append(failureStress)
            thicknessW.append(thisThickness)
            heightW.append(thisDiscH)
            widthW.append(thisWidth)
            if '_F' in sheet.name:
                bStrainW.append(breakStrain)
                bStressW.append(breakStress)
                if nbFailure>0:
                    nbW.append(thisNb)
                    nbFailureW.append(nbFailure)
            modulusW.append(m0)
            stiffnessW.append(ks0)

np.savetxt("stifnessI.csv", stiffnessI, delimiter=",")
np.savetxt("stifnessE.csv", stiffnessE, delimiter=",")
np.savetxt("stifnessW.csv", stiffnessW, delimiter=",")
np.savetxt("modulusI.csv", modulusI, delimiter=",")
np.savetxt("modulusE.csv", modulusE, delimiter=",")
np.savetxt("modulusW.csv", modulusW, delimiter=",")

#just print stuff for sanity check#
firstBStrain = [strain[0] for strain in bStrainAll if len(strain)>0]
#print firstBStrain
print 'damage: ',np.mean(dStrainAll),np.std(dStrainAll),np.min(dStrainAll),np.max(dStrainAll)
print 'failure: ',np.mean(fStrainAll),np.std(fStrainAll),np.min(fStrainAll),np.max(fStrainAll)
print 'break: ',np.mean(firstBStrain),np.std(firstBStrain),np.min(firstBStrain),np.max(firstBStrain)
print 'rSquares: ',np.mean(rSquares),np.std(rSquares),np.min(rSquares),np.max(rSquares)
print 'rSquaresI: ',np.mean(rSquaresI),np.std(rSquaresI),np.min(rSquaresI),np.max(rSquaresI)
print 'rSquaresE: ',np.mean(rSquaresE),np.std(rSquaresE),np.min(rSquaresE),np.max(rSquaresE)
print 'rSquaresW: ',np.mean(rSquaresW),np.std(rSquaresW),np.min(rSquaresW),np.max(rSquaresW)
print 'sizes'
print 'h, t, w (inner)',np.mean(heightI),np.std(heightI),np.mean(thicknessI),np.std(thicknessI),np.mean(widthI),np.std(widthI)
print 'h, t, w (outer)',np.mean(heightE),np.std(heightE),np.mean(thicknessE),np.std(thicknessE),np.mean(widthE),np.std(widthE)
print 'h, t, w (whole)',np.mean(heightW),np.std(heightW),np.mean(thicknessW),np.std(thicknessW),np.mean(widthW),np.std(widthW)
#process damage
n1,m1,s1=getDamageValues(dStrainW,dStressW,'full')
n2,m2,s2=getDamageValues(dStrainE,dStressE,'O')
n3,m3,s3=getDamageValues(dStrainI,dStressI,'I')
#process failure
nF1,mF1,sF1,rF1=getFailureValues(fStrainW,fStressW,'full')
nF2,mF2,sF2,rF2=getFailureValues(fStrainE,fStressE,'O')
nF3,mF3,sF3,rF3=getFailureValues(fStrainI,fStressI,'I')
#process break
nB1,mB1,sB1,rB1=getFailureValues(bStrainW,bStressW,'full',name='break')
nB2,mB2,sB2,rB2=getFailureValues(bStrainE,bStressE,'O',name='break')
nB3,mB3,sB3,rB3=getFailureValues(bStrainI,bStressI,'I',name='break')

plt.figure(1)#failure and damage
plt.errorbar([mF1[0]],[mF1[1]], yerr=[sF1[1]], xerr=[sF1[0]], fmt='o',color='r',label='failure whole AF (N=%i)'%nF1)
plt.errorbar([mF2[0]],[mF2[1]], yerr=[sF2[1]], xerr=[sF2[0]], fmt='^',color='r',label='failure outer AF (N=%i)'%nF2)
plt.errorbar([mF3[0]],[mF3[1]], yerr=[sF3[1]], xerr=[sF3[0]], fmt='s',color='r',label='failure inner AF (N=%i)'%nF3)
plt.errorbar([m1[0]],[m1[1]], yerr=[s1[1]], xerr=[s1[0]], fmt='o',color='0.15',label='damage whole AF (N=%i)'%n1)
plt.errorbar([m2[0]],[m2[1]], yerr=[s2[1]], xerr=[s2[0]], fmt='^',color='0.15',label='damage outer AF (N=%i)'%n2)
plt.errorbar([m3[0]],[m3[1]], yerr=[s3[1]], xerr=[s3[0]], fmt='s',color='0.15',label='damage inner AF (N=%i)'%n3)
plt.errorbar([mB1[0]],[mB1[1]], yerr=[sB1[1]], xerr=[sB1[0]], fmt='o',color='g',label='break whole AF (N=%i)'%nB1)
plt.errorbar([mB2[0]],[mB2[1]], yerr=[sB2[1]], xerr=[sB2[0]], fmt='^',color='g',label='break outer AF (N=%i)'%nB2)
plt.errorbar([mB3[0]],[mB3[1]], yerr=[sB3[1]], xerr=[sB3[0]], fmt='s',color='g',label='break inner AF (N=%i)'%nB3)
plt.legend(loc=1)
plt.xlabel(r'Strain (-)', fontsize=20, position = (.95,0))
plt.ylabel(r'Stress (MPa)', fontsize=20, position = (0.15,1),rotation=0)
plt.savefig('damageAndFailure.eps', dpi=600,bbox_inches='tight')

# plt.figure(2)#failure only
# plt.errorbar([mF1[0]],[mF1[1]], yerr=[sF1[1]], xerr=[sF1[0]], fmt='o',color='b',label='whole AF (N=%i)'%nF1)
# plt.errorbar([mF2[0]],[mF2[1]], yerr=[sF2[1]], xerr=[sF2[0]], fmt='o',color='g',label='outer AF (N=%i)'%nF2)
# plt.errorbar([mF3[0]],[mF3[1]], yerr=[sF3[1]], xerr=[sF3[0]], fmt='o',color='r',label='inner AF (N=%i)'%nF3)
# plt.legend(loc=1)
# plt.xlabel(r'Strain (-)', fontsize=20, position = (.95,0))
# plt.ylabel(r'Stress (MPa)', fontsize=20, position = (0.15,1),rotation=0)
# plt.title(r'failure behaviour', fontsize=30)
# plt.savefig('failure.eps', dpi=600,bbox_inches='tight')

# plt.figure(3)#damage only
# plt.errorbar([m1[0]],[m1[1]], yerr=[s1[1]], xerr=[s1[0]], fmt='o',color='b',label='whole AF (N=%i)'%n1)
# plt.errorbar([m2[0]],[m2[1]], yerr=[s2[1]], xerr=[s2[0]], fmt='o',color='g',label='outer AF (N=%i)'%n2)
# plt.errorbar([m3[0]],[m3[1]], yerr=[s3[1]], xerr=[s3[0]], fmt='o',color='r',label='inner AF (N=%i)'%n3)
# plt.legend(loc=1)
# plt.xlabel(r'Strain (-)', fontsize=20, position = (.95,0))
# plt.ylabel(r'Stress (MPa)', fontsize=20, position = (0.15,1),rotation=0)
# plt.title(r'damage behaviour', fontsize=30)
# plt.savefig('damage.eps', dpi=600,bbox_inches='tight')

# plt.figure(4)
# ind = np.arange(3)
# plt.bar(ind, [mF1[2],mF2[2],mF3[2]],width=0.3,color='0.15',yerr=[sF1[2],sF2[2],sF3[2]],error_kw={'ecolor':'0.'},label='local failure')
# plt.bar(ind+0.3, [mB1[2],mB2[2],mB3[2]],width=0.3,color='0.75',yerr=[sB1[2],sB2[2],sB3[2]],error_kw={'ecolor':'0.'},label='macro failure')
# plt.xticks([0.4,1.4,2.4], ('whole AF','outer AF','inner AF') )
# plt.ylabel(r'Drop in Stress (kPa)', fontsize=20, position = (0.15,1),rotation=0)
# plt.legend()
# plt.savefig('dropInStressAtFailure.eps', dpi=600,bbox_inches='tight')

# plt.figure(5)
# plt.plot(nbI,nbFailureI,'o',color='r',label='inner AF (N=%i)'%len(nbFailureI))
# plt.plot(nbE,nbFailureE,'o',color='g',label='outer AF (N=%i)'%len(nbFailureE))
# plt.plot(nbW,nbFailureW,'o',color='b',label='whole AF (N=%i)'%len(nbFailureW))
# plt.legend()
# plt.ylabel(r'Number of occurence of local failure before macro failure', fontsize=20, position = (0.15,1),rotation=0)
# plt.xlabel(r'Number of lamellae', fontsize=20, position = (0.15,1),rotation=0)
# plt.savefig('nbFailure_nbLamellae.eps', dpi=600,bbox_inches='tight')


plt.show()

