# WeightedMean examples
library(plyr)
WeightedMean()
WeightedMean(data = NULL)
WeightedMean(data = NULL, lon = NULL)
WeightedMean(data = NULL, lon = NULL, lat = NULL)
WeightedMean(data = "a", lon = NULL, lat = NULL)
WeightedMean(data = "a", lon = 1, lat = 1)
WeightedMean(data = 1, lon = 1, lat = 1)
a <- 1 : 6
dim(a) <- c(2, 3)
WeightedMean(data = a, lon = 1, lat = 1)
WeightedMean(data = a, lon = 1 : 2, lat = 1)
WeightedMean(data = a, lon = 1, lat = 1, londim = 1, latdim = 2)
WeightedMean(data = a, lon = 1 : 2, lat = 1, londim = 1, latdim = 2)
WeightedMean(data = a, lon = 1 : 2, lat = 1 : 3, londim = 1, latdim = 2)

WeightedMean(data = a, lon = 1 : 2, lat = 1 : 3)

a <- 1 : (2 * 3 * 4 * 5)
dim(a) <- c(2, 3, 4, 5)
WeightedMean(data = a, lon = 1 : 2, lat = 1 : 3)
dim(WeightedMean(data = a, lon = 1 : 2, lat = 1 : 3))

##Example synthetic data 1:
data <- 1:(2 * 3 * 4 * 5)
dim(data) <- c(lon = 2, lat = 3, time = 4, model = 5)
lat <- c(1, 10, 20)
lon <- c(1, 10)

a <- WeightedMean(data = data, lon = lon, lat = lat, region = NULL, mask = NULL, londim = 1, latdim = 2)
str(a)

mask <- c(0, 1, 0, 1, 0, 1)
dim(mask) <- c(lon = 2, lat = 3)
a <- WeightedMean(data = data, lon = lon, lat = lat, region = NULL, mask = mask, londim = 1, latdim = 2)
str(a)

region <- c(1, 10, 1, 10)
a <- WeightedMean(data = data, lon = lon, lat = lat, region = region, mask = mask, londim = 1, latdim = 2)
str(a)

##Example synthetic data:
data <- 1:(2 * 3 * 4)
dim(data) <- c(lon = 2, lat = 3, time=4)
lat <- c(1, 10, 20)
lon <- c(1, 10)

WeightedMean(data = data, lon = lon, lat = lat, region = NULL, mask = NULL, londim = 1, latdim = 2)
####--------------
# Test matrix of weights:  weight <- (dlon * dlat * cosphi)
#-----------------
lat <- seq(0, 20, 5)
lon <- seq(0, 30, 5)
  cosphi <- t(array(cos(lat * pi / 180), dim = c(length(lat), length(lon))))
  nblat <- length(lat)
  nblon <- length(lon)
  dlon <- abs(c(lon[2 : nblon] - lon[1 : nblon - 1])) * pi / 180
  dlon <- c(dlon, dlon[1])
  dlon <- array(dlon, dim = c(nblon, nblat))
  dlat <- abs(c(lat[2 : nblat] - lat[1 : nblat - 1])) * pi / 180
  dlat <- c(dlat, dlat[1])
  dlat <- t(array(dlat, dim = c(nblat, nblon)))
  weight <- (dlon * dlat * cosphi)
weight #doesn't depend on the longitude

lat <- seq(0, 20, 5)
lon <- seq(30, 0, -5)
  cosphi <- t(array(cos(lat * pi / 180), dim = c(length(lat), length(lon))))
  nblat <- length(lat)
  nblon <- length(lon)
  dlon <- abs(c(lon[2 : nblon] - lon[1 : nblon - 1])) * pi / 180
  dlon <- c(dlon, dlon[1])
  dlon <- array(dlon, dim = c(nblon, nblat))
  dlat <- abs(c(lat[2 : nblat] - lat[1 : nblat - 1])) * pi / 180
  dlat <- c(dlat, dlat[1])
  dlat <- t(array(dlat, dim = c(nblat, nblon)))
  weight <- (dlon * dlat * cosphi)
weight #doesn't depend on the longitude


