#------------------------------------------------------------------------------------------#
#
# Minimum sample size - Negative binomial
# Authors: Eliardo G. Costa and Julio M. Singer
# License: GPL 2
# Last update: 29/03/2015
#
# References:
# 1. Chen, X. (2007). Exact computation of minimum sample size for estimation 
#    of Poisson parameters. http://arxiv.org/abs/0707.2116.
# 2. Chen, X. (2011). Exact computation of minimum sample size for estimation
#    of binomial parameters. Journal of Statistical Planning and Inference 141, 2622-2632.
# 3. Costa, E.G., Lopes, R.M. & Singer, J.M. (2015). Sample size for estimating the concentration 
#    of organisms in ballast water. Submitted. 
# 4. Costa, E.G. (2013). Aspectos estatsticos da amostragem de gua de lastro. MSc thesis,
#    Departamento de Estatstica. Universidade de So Paulo, So Paulo, In Portuguese.
#
#------------------------------------------------------------------------------------------#

sample.sizeNB=function(a=NULL,b=NULL,k,n0=2,lag=100,ea=NULL,er=NULL,d)
{

#-------------------------------------------------------#
#  Probabilities absolute error - Theo. 2 (Chen, 2011)
#-------------------------------------------------------#

caA=function(a,n,k,e)
{
pnbinom(ceiling(n*(a+e))-1,size=n*k,mu=n*a)-pnbinom(floor(n*(a-e)),size=n*k,mu=n*a)
}

cbA=function(b,n,k,e)
{
pnbinom(ceiling(n*(b+e))-1,size=n*k,mu=n*b)-pnbinom(floor(n*(b-e)),size=n*k,mu=n*b)
}

cmaisA=function(l,n,k,e)
{
pnbinom(l-1+ceiling(2*n*e),size=n*k,mu=n*(l/n+e))-pnbinom(l,size=n*k,mu=n*(l/n+e))
}

cmenosA=function(l,n,k,e)
{
pnbinom(l-1,size=n*k,mu=n*(l/n-e))-pnbinom(l-ceiling(2*n*e),size=n*k,mu=n*(l/n-e))
}

#--------------------------------------------------------------#
#   Sets which form 'S' absolute error - Theo. 2 (Chen, 2011)
#--------------------------------------------------------------#

con.maisA=function(a,b,n,k,e)
{
lim1=max(0,1+floor(n*(a-e)))
lim2=ceiling(n*(b-e))-1

l=seq.int(from=lim1,by=1,length.out=lim2-lim1+1)
con=cmaisA(l,n,k,e)
con
}

con.menosA=function(a,b,n,k,e)
{
lim1=1+floor(n*(a+e))
lim2=ceiling(n*(b+e))-1

l=seq.int(from=lim1,by=1,length.out=lim2-lim1+1)
con=cmenosA(l,n,k,e)
con
}

#--------------------------------------------------------#
#   Probabilities relative error - Theo. 4 (Chen, 2011)
#--------------------------------------------------------#

caR=function(a,n,k,e)
{
pnbinom(ceiling(n*a*(1+e))-1,size=n*k,mu=n*a)-pnbinom(floor(n*a*(1-e)),size=n*k,mu=n*a)
}

cbR=function(b,n,k,e)
{
pnbinom(ceiling(n*b*(1+e))-1,size=n*k,mu=n*b)-pnbinom(floor(n*b*(1-e)),size=n*k,mu=n*b)
}

cmaisR=function(l,n,k,e)
{
pnbinom(ceiling(l*(1+e)/(1-e))-1,size=n*k,mu=n*(l/(n*(1-e))))-pnbinom(l,size=n*k,mu=n*(l/(n*(1-e))))
}

cmenosR=function(l,n,k,e)
{
pnbinom(l-1,size=n*k,mu=n*(l/(n*(1+e))))-pnbinom(floor(l*(1-e)/(1+e)),size=n*k,mu=n*(l/(n*(1+e))))
}

#---------------------------------------------------------------#
#   Sets which form 'S' relative error - Theo. 4 (Chen, 2011)
#---------------------------------------------------------------#

con.maisR=function(a,b,n,k,e)
{
lim1=max(0,1+floor(n*a*(1-e)))
lim2=ceiling(n*b*(1-e))-1

l=seq.int(from=lim1,by=1,length.out=lim2-lim1+1)
con=cmaisR(l,n,k,e)
con
}

con.menosR=function(a,b,n,k,e)
{
lim1=1+floor(n*a*(1+e))
lim2=ceiling(n*b*(1+e))-1

l=seq.int(from=lim1,by=1,length.out=lim2-lim1+1)
con=cmenosR(l,n,k,e)
con
}

#----------------------------------------------------------#
#          Set 'S' absolute and relative errors
#----------------------------------------------------------#

SA=function(a,b,n,k,ea)
{
CAA1=caA(a,n,k,ea)
CBA1=cbA(b,n,k,ea)
CMAA1=con.maisA(a,b,n,k,ea)
CMEA1=con.menosA(a,b,n,k,ea)

s=c(CAA1,CBA1,CMAA1,CMEA1)
return(s)
}

#----------------------------------------------------------#
#            Set 'S' relative error
#----------------------------------------------------------#

SR=function(a,b,n,k,er)
{
CAR2=caR(a,n,k,er)
CBR2=cbR(b,n,k,er)
CMAR2=con.maisR(a,b,n,k,er)
CMER2=con.menosR(a,b,n,k,er)

s=c(CAR2,CBR2,CMAR2,CMER2)
return(s)
}

#-----------------------------------------------------------#
#            Set 'S' absolute and relative errors
#-----------------------------------------------------------#

SAR=function(a,b,n,k,ea,er)
{
CAA3=caA(a,n,k,ea)
CBA3=cbA(ea/er,n,k,ea)
CMAA3=con.maisA(a,ea/er,n,k,ea)
CMEA3=con.menosA(a,ea/er,n,k,ea)

CAR3=caR(ea/er,n,k,er)
CBR3=cbR(b,n,k,er)
CMAR3=con.maisR(ea/er,b,n,k,er)
CMER3=con.menosR(ea/er,b,n,k,er)

s=c(CAA3,CBA3,CMAA3,CMEA3,CAR3,CBR3,CMAR3,CMER3)
return(s)
}

#--------------------------------#
#      Initial checks
#--------------------------------#

if(is.null(ea) && is.null(er))
{
stop("At least one error must be specified")
}

if(length(d)<1)
{
stop("The length of vector 'd' must be at least one")
}

if(any(d<0) || any(d>1))
{
stop("The elements of vector 'd' must lie in interval (0,1)")
}

if(is.null(a) || is.null(b))
{
stop("The bounds 'a' and 'b' must be specified")
}

if(a>b)
{
stop("The bound 'a' must be smaller than bound 'b'")
}


#---------------------------------------------------------------------------#
#  Exact sample size - Absolute and relative errors - Theo. 5 (Chen, 2011)
#---------------------------------------------------------------------------#

if(!is.null(ea) && !is.null(er))
{

if(any(c(ea,er)<0) || any(c(ea,er)>1))
{
stop("The errors must lie in interval (0,1)")
}

if(ea/er<=a || ea/er>=b)
{
stop("The ratio 'ea/er' must lie in interval (a,b)")
}

cat("Calculating...\n")

d=sort(d,decreasing=T)

samples=numeric()

n=n0

for(i in 1:length(d))
{
s=SAR(a,b,n,k,ea,er)

while(min(s)<=1-d[i])
{
n=n+lag
s=SAR(a,b,n,k,ea,er)
}

samples=append(samples,n)
}

samples=samples-lag

for(i in 1:length(d))
{
s=SAR(a,b,samples[i],k,ea,er)

while(min(s)<=1-d[i])
{
samples[i]=samples[i]+1
s=SAR(a,b,samples[i],k,ea,er)
}
}

}

#---------------------------------------------------------------------#
#  Exact sample size - Absolute error - Theo. 1 and 2 (Chen, 2011)
#---------------------------------------------------------------------#

if(!is.null(ea) && is.null(er))
{

if(ea<0 || ea>1)
{
stop("The absolute error must lie in interval (0,1)")
}

cat("Calculating...\n")
d=sort(d,decreasing=T)

n=n0

samples=numeric()

for(i in 1:length(d))
{
s=SA(a,b,n,k,ea)

while(min(s)<=1-d[i])
{
n=n+lag
s=SA(a,b,n,k,ea)
}

samples=append(samples,n)
}

samples=samples-lag

for(i in 1:length(d))
{
s=SA(a,b,samples[i],k,ea)

while(min(s)<=1-d[i])
{
samples[i]=samples[i]+1
s=SA(a,b,samples[i],k,ea)
}
}

}

#---------------------------------------------------------------------#
#  Exact sample size - Relative error - Theos. 3 and 4 (Chen, 2011)
#---------------------------------------------------------------------#

if(is.null(ea) && !is.null(er))
{

if(er<0 || er>1)
{
stop("The relative error must lie in interval (0,1)")
}

cat("Calculating...\n")
d=sort(d,decreasing=T)

n=n0

samples=numeric()

for(i in 1:length(d))
{
s=SR(a,b,n,k,er)

while(min(s)<=1-d[i])
{
n=n+lag
s=SR(a,b,n,k,er)
}

samples=append(samples,n)
}

samples=samples-lag

for(i in 1:length(d))
{
s=SR(a,b,samples[i],k,er)

while(min(s)<=1-d[i])
{
samples[i]=samples[i]+1
s=SR(a,b,samples[i],k,er)
}
}

}

#--------------------------#
#       Output
#--------------------------#

cat("\nCall to negative binomial dist.: \n")
cat("--------------------------------\n")
cat(a,"< mu <",b,";k = ",k,"\n")
if(!is.null(ea) && !is.null(er))
{
cat("Absolute error = ",ea, "\n")
cat("Relative error = ",er, "\n")
}
if(!is.null(ea) && is.null(er))
{
cat("Absolute error = ",ea, "\n")
}
if(is.null(ea) && !is.null(er))
{
cat("Relative error = ",er, "\n")
}
cat("--------------------------------\n")
cat("\nSample size: \n")
cat("------------- \n")
print(matrix(c(samples,1-d),length(samples),2,dimnames=list(rep("",length(samples)),c("n","1-d"))))
cat("-------------\n")

} # END FUNCTION

#------------------------------------------#
#                Examples
#------------------------------------------#

# sample.sizeNB(a=5,b=20,lag=1,k=30,ea=0.9,d=c(0.05,0.25,0.1))
