# Import system modules
import arcpy
from arcpy import env
from arcpy.sa import *
import os
import tempfile 

env.overwriteOutput = True
  
#############################5.Restrend##################################
def restrend():#(inDirPrecipitation,inDirNDVI,outDir,writeResi = False):   

    inDirPrecipitation=r"e:\Users\XX\Desktop\ttttt\const9"#X
    inDirNDVI =r"e:\Users\XX\Desktop\ttttt\1998-2006"  #Y    
    outDir=r"e:\Users\XX\Desktop\ttttt\aaa"
    writeResi= True
   
    
    if os.path.exists(outDir) == False:
        os.mkdir(outDir)
        
   
    ext=".tif" 
    outDir_resi =  outDir + "/resi"
    
    if os.path.exists(outDir_resi) == False:
        os.mkdir(outDir_resi)
            
    arcpy.CheckOutExtension("Spatial") 
    
    #===============NDVI(Y) ~ year(X) /regression =======
    #1    
    #=================read raster files =====================
    env.workspace = inDirPrecipitation #X 

    rstListX = arcpy.ListRasters("*", "ALL")
    nx=len(rstListX)
    print rstListX
    
    env.workspace = inDirNDVI          #Y
    rstListY = arcpy.ListRasters("*", "ALL")
    ny=len(rstListY)
    print rstListY
    
    temppath=tempfile.mkdtemp() 
    env.workspace = temppath    
    #=================X===========================   
    print "reading images......"

    zeroImage = Raster(inDirNDVI + "/" + rstListY[0]) * 0 
    p_mean =zeroImage
    lxx= zeroImage
    
    for rst in rstListX: #Xmean
        p_mean += Raster(inDirPrecipitation + "/" + rst)
        #print ">"
    p_mean = p_mean/nx
    
    #print "p_mean>"
    
    X=[] #xi-Xmean
    for rst in rstListX: #lxx
        tmprst=Raster(inDirPrecipitation + "/" + rst)-p_mean
        X.append(tmprst)  
        lxx = lxx + Square(tmprst)
        #print ">" 
    print "lxx" + ext
    #=====================Y=======================    
    NDVI_mean=zeroImage
    lxy=zeroImage
    lyy=zeroImage
    
    print "reading images......"
    for rst in rstListY: #Ymean
        NDVI_mean = NDVI_mean + Raster(inDirNDVI + "/" +rst)    
    NDVI_mean = NDVI_mean/ny
    
    Y=[] #yi-ymean
    for rst in rstListY: #lyy
        tmprst=Raster(inDirNDVI + "/" +rst) - NDVI_mean
        Y.append(tmprst)    
        lyy = lyy + Square(tmprst)
    print "lyy" + ext
    for i in range(nx): #lxy
        lxy =lxy + X[i] * Y[i]
    print "lxy" + ext
    #=============a,b==============================   
    b=lxy/lxx #b
    
    print "b" + ext
    a=NDVI_mean - b * p_mean
    
    print "a" + ext
    #=============file out=======================    
    NDVI_mean.save(outDir + "/ndvi_mean"+ ext)
    p_mean.save(outDir + "/p_mean"+ ext)
    a.save(outDir + "/a" + ext)
    b.save(outDir + "/b"+ ext)
    lxx.save(outDir + "/lxx"+ ext)
    lxy.save(outDir + "/lxy"+ ext)
    lyy.save(outDir + "/lyy"+ ext)

    #========================================
    
    #==========t-test=========================    
    Q = zeroImage
    
    residual2=[]
    residual=[]
    for i in range(ny): #(Y-Y^)^2
        tmprst=Raster(inDirNDVI + "/" + rstListY[i])-( b * Raster(inDirPrecipitation + "/" + rstListX[i]) + a)
        
        #if writeResi == True : #
        if i<9:
            tmprst.save(outDir_resi + "/resi" + "0"+ str(i+1)+ ext) 
        else:      
            tmprst.save(outDir_resi + "/resi"+ str(i+1)+ ext) 
            
        residual2.append(Square(tmprst)) 
        residual.append(tmprst)
    
    for i in range(ny):
        Q += residual2[i]
        
    Syx = SquareRoot(Q/(ny-2))     
    t=b/(Syx/SquareRoot(lxx))    
    t.save(outDir + "/t" + ext) #t
    print "t" + ext
    #===============D-W======================
    s=zeroImage
    
    for i in range( ny -1 ): #dw
        s += Square(residual[i+1] - residual[i])
    dw=s/Q
    
    dw.save(outDir + "/DW"+ ext)
    print "DW" + ext

    #==========R^2=======================
    Corr=lxy/SquareRoot(lxx*lyy)
        
    R2=Square(Corr)    
    
    Corr.save(outDir + "/corr"+ ext) #Corr
    R2.save(outDir + "/r2"+ ext) #R2
    
    print "R^2" + ext
 
    del R2,Corr,Syx,residual2,Q,a,b,lxx,lxy,lyy,NDVI_mean,p_mean,X,Y    
if __name__ == '__main__':
    restrend()
