Last active
August 29, 2015 14:17
-
-
Save ougx/e9f44c6b4f8d19eafeaa to your computer and use it in GitHub Desktop.
flip NDVI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(raster) | |
flipMaxMin <-function(vin){ | |
n = length(vin) | |
nrw=nrow(vin) | |
#eleminate the null values | |
v <- na.omit(as.vector(vin)) | |
#length of the vector after elemination of null | |
nn =length(v) | |
#the regular rank | |
r1 <- order(v) | |
#inverse rank | |
r2 <- r1[nn:1] | |
#1 to n | |
ori = 1:nn | |
#flip first regular rank with the first in the inverse rank | |
for (i in 1:(nn/2)){ | |
ori[r1[i]]= r2[i] | |
ori[r2[i]]= r1[i] | |
} | |
#output | |
v = v[ori] | |
vin[! is.na(vin)] <- v | |
flipMaxMin <- vin | |
} | |
setwd("\\\\Server24\\iwm\\Projects\\Users\\Michael\\MODIS_Rwork\\MODIS_Rwork") | |
lst <- raster("LST_1km.tif") | |
ndvi <- raster("ndvi.tif") | |
nul <- NAvalue(ndvi) | |
ndvi[ndvi[] < 0] = nul | |
# 1 sum ndvi | |
# sum the ndvi in 250m grid to the 1km grid | |
sumNDVi <- aggregate(ndvi, fact=4,fun=sum) | |
# split the sum grid back to 250m grid | |
sumNDVI <- disaggregate(sumNDVi, fact = 4) | |
writeRaster(sumNDVI, "sumNDVI.tif",overwrite=TRUE) | |
# 2 percent | |
# calculation only perform between grids with same resolutions | |
fracNDVI = ndvi/sumNDVI*100 | |
writeRaster(fracNDVI, "percNDVI.tif",overwrite=TRUE) | |
# 3 flip order for each 1km cell | |
fn <- as.matrix(fracNDVI) | |
for (i in seq(0,nrow(fn)-4,4)){ | |
for (j in seq(0,ncol(fn)-4,4)){ | |
#v <- fn[i+1:4,j+1:4] | |
fn[i+1:4,j+1:4] <- flipMaxMin(fn[i+1:4,j+1:4]) | |
} | |
print (i/ nrow(fn)) | |
} | |
# output | |
fracNDVI[] <- fn | |
writeRaster(fracNDVI, "fracNDVI.tif",overwrite=TRUE) | |
##### | |
g1km <- readTIFF("1km.tif") | |
ndvi <- readTIFF("ndvi.tif") | |
# split the 1km grid | |
g250 <- disaggregate(g1km, fact = 4) | |
# do the math | |
var <- ndvi * g250 | |
writeRaster(var, "finalNDVI.tif",overwrite=TRUE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment