##--------------------------------------------------------
## CMSY analysis with estimation of total biomass, including Bayesian Schaefer 
## written by Rainer Froese with support from Gianpaolo Coro in 2013-2014
## This version adjusts biomass to average biomass over the year
## It also contains the FutureCrash option to improve prediction of final biomass
## Version 21 adds the purple point to indicate the 25th percentile of final biomass
## Version 22 accepts that no biomass or CPUE area available
##--------------------------------------------------------
library(R2jags)  # Interface with JAGS
library(coda) 

#-----------------------------------------
# Some general settings
#-----------------------------------------
# set.seed(999) # use for comparing results between runs
rm(list=ls(all=TRUE)) # clear previous variables etc
options(digits=3) # displays all numbers with three significant digits as default
graphics.off() # close graphics windows from previous sessions

#-----------------------------------------
# General settings for the analysis
#-----------------------------------------
sigR         <- 0.02 # overall process error; 0.05 works reasonable for simulations, 0.02 for real data; 0 if deterministic model
n            <- 10000 # initial number of r-k pairs
batch.mode   <- T # set to TRUE to suppress graphs
write.output <- T # set to true if table of output is wanted
FutureCrash  <- "No"

#-----------------------------------------
# Start output to screen
#-----------------------------------------
cat("-------------------------------------------\n")
cat("Catch-MSY Analysis,", date(),"\n")
cat("-------------------------------------------\n")

#------------------------------------------
# Read data and assign to vectors
#------------------------------------------
# filename_1  <- "AllStocks_Catch4.csv"
# filename_2  <- "AllStocks_ID4.csv"
# filename_1  <-  "SimCatch.csv"
# filename_2  <-  "SimSpec.csv"
# filename_2  <-  "SimSpecWrongS.csv"
# filename_2  <-  "SimSpecWrongI.csv"
# filename_2  <-  "SimSpecWrongF.csv"
# filename_2  <-  "SimSpecWrongH.csv"
# filename_2  <-  "SimSpecWrongL.csv"
# filename_1  <-  "FishDataLim.csv"
# filename_2  <-  "FishDataLimSpec.csv" 
filename_1  <-  "WKLIFE4Stocks.csv"
filename_2  <-  "WKLIFE4ID.csv"

outfile<-"outfile"
outfile.txt <- "outputfile.txt"

cdat         <- read.csv(filename_1, header=T, dec=".", stringsAsFactors = FALSE)
cinfo        <- read.csv(filename_2, header=T, dec=".", stringsAsFactors = FALSE)
cat("Files", filename_1, ",", filename_2, "read successfully","\n")

# Stocks with total biomass data and catch data from StartYear to EndYear
# stocks       <- sort(as.character(cinfo$stock)) # All stocks 
stocks<-"HLH_M07"

# select one stock after the other
for(stock in stocks) {
  # assign data from cinfo to vectors
  res          <- as.character(cinfo$Resilience[cinfo$stock==stock])
  StartYear    <- as.numeric(cinfo$StartYear[cinfo$stock==stock])
  EndYear      <- as.numeric(cinfo$EndYear[cinfo$stock==stock])
  r_low        <- as.numeric(cinfo$r_low[cinfo$stock==stock])
  r_hi         <- as.numeric(cinfo$r_hi[cinfo$stock==stock])
  stb_low      <- as.numeric(cinfo$stb_low[cinfo$stock==stock])
  stb_hi       <- as.numeric(cinfo$stb_hi[cinfo$stock==stock])
  intyr        <- as.numeric(cinfo$intyr[cinfo$stock==stock])
  intbio_low   <- as.numeric(cinfo$intbio_low[cinfo$stock==stock])
  intbio_hi    <- as.numeric(cinfo$intbio_hi[cinfo$stock==stock])
  endbio_low   <- as.numeric(cinfo$endbio_low[cinfo$stock==stock])
  endbio_hi    <- as.numeric(cinfo$endbio_hi[cinfo$stock==stock])
  Btype        <- as.character(cinfo$Btype[cinfo$stock==stock])
  FutureCrash  <- as.character(cinfo$FutureCrash[cinfo$stock==stock])
  comment      <- as.character(cinfo$comment[cinfo$stock==stock])
  
  
  # extract data on stock
  yr           <- as.numeric(cdat$yr[cdat$stock==stock & cdat$yr >= StartYear & cdat$yr <= EndYear])
  ct           <- as.numeric(cdat$ct[cdat$stock==stock & cdat$yr >= StartYear & cdat$yr <= EndYear])/1000  ## assumes that catch is given in tonnes, transforms to '000 tonnes
  if(Btype=="observed" | Btype=="CPUE" | Btype=="simulated") {
    bt <- as.numeric(cdat$TB[cdat$stock==stock & cdat$yr >= StartYear & cdat$yr <= EndYear])/1000  ## assumes that biomass is in tonnes, transforms to '000 tonnes
  } else {bt <- NA}
  nyr          <- length(yr) # number of years in the time series
  
  cat("->---------------------------------------
Species: NA
Name and region: NA , NA
Stock: HLH_M07
Catch data used from years 1 - 50
Prior initial relative biomass = 0.5 - 0.9
Prior intermediate rel. biomass= 0.01 - 0.4 in year 25
Prior final relative biomass   = 0.4 - 0.8
If current catches continue, is the stock likely to crash within 3 years? No
Prior range for r = 0.2 - 0.8 , prior range for k = 125 - 9965
Results from Bayesian Schaefer model using catch & biomass ( simulated )
MSY = 91.7 , 95% CL = 83.9 - 100
Mean catch / MSY = 0.882
r = 0.425 , 95% CL = 0.374 - 0.483
k = 863 , 95% CL = 783 - 951
Results of CMSY analysis
Altogether 2055 unique viable r-k pairs were found
1142 r-k pairs above the initial geometric mean of r = 0.343 were analysed
r = 0.522 , 95% CL = 0.349 - 0.782
k = 683 , 95% CL = 438 - 1067
MSY = 89.2 , 95% CL = 82.2 - 96.7
Predicted biomass in last year = 0.676 2.5th perc = 0.435 97.5th perc = 0.768
Predicted biomass in next year = 0.673 2.5th perc = 0.433 97.5th perc = 0.758
----------------------------------------------------------
",file=outfile.txt,append=T)

}  
  