# Generalized inverted exponential distribution
# probability density function
indicator <- function(condition) ifelse(condition,1,0)


dgied <- function(x, theta=1, lambda=1, log=FALSE){
    n <- length(x)
    c1 <- exp(-lambda/x)
    c2 <- (1-c1)^(theta-1)
    c3 <- theta*lambda/(x^2)
    if(log){
      y <- log(c3*c1*c2*indicator(x>0))
      if(n>1){
        id <- which(x<=0, arr.ind = TRUE)
        y[id] <- (-Inf)
      } else{
        y <- ifelse(x==0, -Inf, y)
      }
      
    } else{
      y <- c3*c2*c1*indicator(x>0)
      if(n>1){
        id <- which(x<=0, arr.ind = TRUE)
        y[id] <- 0
      } else{
        y <- ifelse(x==0, 0, y)
      }
    }
   y
}

# cumulative distribution function
pgied <-  function(q, theta=1, lambda=1, log.p=FALSE){
  c1 <- exp(-lambda/q)
  c2 <- (1-c1)^theta
  if(log.p){
    log((1-c2)*indicator(q>0))
  } else{
    (1-c2)*indicator(q>0)
  }
}

# survival function 
sgied <-  function(q, theta=1, lambda=1, log.s=FALSE){
  c1 <- exp(-lambda/q)
  c2 <- (1-c1)^theta
  if(log.s){
    log(c2*indicator(q>0))
  } else{
    c2*indicator(q>0)
  }
}


# quantile function
qgied <- function(p, theta=1, lambda=1, log.p=FALSE){
  if(log.p){
    p <- exp(p)
  } 
  c1 <- (1-(1-p)^(1/theta))
  c2 <- (-lambda)/log(c1)
  c2
}

# random sampling function
rgied <- function(n, theta=1, lambda=1){
  u <- runif(n)
  xr <- qgied(u, theta = theta, lambda=lambda)
  xr
}


# Left Truncated (one side only considered) generalized inverted exponential distribution
# probability density function
dtgied <- function(x, truncation, theta=1, lambda=1, log=FALSE){
  a <- pgied(truncation, theta = theta, lambda=lambda)
  ft <- dgied(x, theta = theta, lambda=lambda)
  if(log){
    dt <- (log(indicator(x>=truncation)*ft/(1-a)))
  } else{
    dt <- (indicator(x>=truncation)*ft/(1-a))
  }
  dt
}

# cumulative distribution function
ptgied <-  function(q, truncation, theta=1, lambda=1, log.p=FALSE){
  ntr <- length(truncation)
  a <- pgied(truncation, theta = theta, lambda=lambda)
  b <- pgied(q, theta = theta, lambda=lambda)
  c2 <- (b-a)/(1-a)*indicator(q>=truncation)
  if(log.p){
    pt <- log(c2)
  } else{
    pt <- c2
  }
  pt
}


# survival function 
stgied <-  function(q, truncation, theta=1, lambda=1, log.s=FALSE){
  c2 <- 1-ptgied(q=q, truncation=truncation, theta=theta,lambda=lambda)
  if(log.s){
    log(c2)
  } else{
    c2
  }
}


# quantile function
qtgied <- function(p, truncation, theta=1, lambda=1, log.p=FALSE){
  if(log.p){
    p <- exp(p)
  } 
  a <- pgied(truncation, theta=theta, lambda=lambda)
  p1 <- (1-a)*p+a
  qgied(p1, theta = theta, lambda=lambda)
}


# random sampling from truncated distribution function
rtgied <- function(n, truncation, theta=1, lambda=1){
  u <- runif(n)
  b <- pgied(truncation,theta = theta, lambda=lambda)
  u1 <- (1-b)*u+b
  xr <- qgied(u1, theta = theta, lambda=lambda)
  xr
}




