# ################################################################# #
#### LOAD LIBRARY AND DEFINE CORE SETTINGS                       ####
# ################################################################# #

### Clear memory
rm(list = ls())

### Load Apollo library
library(apollo)

### Set working directory to the folder of this script
apollo_setWorkDir()

### Initialise code
apollo_initialise()

### Set core controls
### Each row of the grouped data is one scenario, which is therefore the unit of observation (indivID), and each
### row is weighted by the number of observations it groups (weights)
apollo_control = list(
  modelDescr      = "Fractional NL model on mode choice SP data grouped by scenario, with shares weighted by the number of observations",
  indivID         = "scenario",
  weights         = "n_obs",
  outputDirectory = "output"
)

# ################################################################# #
#### LOAD DATA AND APPLY ANY TRANSFORMATIONS                     ####
# ################################################################# #

### Loading data from package
### if data is to be loaded from a file (e.g. called data.csv),
### the code would be: database = read.csv("data.csv",header=TRUE)
database = apollo_modeChoiceData
### for data dictionary, use ?apollo_modeChoiceData

### Use only SP data
database = subset(database,database$SP==1)

### Group the SP choices by scenario, i.e. by the combination of all the attributes used in the utilities, to create
### aggregate data: one row per scenario, with the share of the observations in which each mode was chosen, and the
### number of observations. Data of this kind could also be observed directly, e.g. as mode shares by zone pair
attributes = c("av_car", "av_bus", "av_air", "av_rail",
               "time_car", "cost_car",
               "time_bus", "cost_bus", "access_bus",
               "time_air", "cost_air", "access_air", "service_air",
               "time_rail", "cost_rail", "access_rail", "service_rail")
database$scenario = as.integer(factor(do.call(paste, database[,attributes])))
shares = aggregate(database[,attributes], by=list(scenario=database$scenario), FUN=function(x) x[1])
shares$share_car  = as.vector(tapply(database$choice==1, database$scenario, mean))
shares$share_bus  = as.vector(tapply(database$choice==2, database$scenario, mean))
shares$share_air  = as.vector(tapply(database$choice==3, database$scenario, mean))
shares$share_rail = as.vector(tapply(database$choice==4, database$scenario, mean))
shares$n_obs      = as.vector(table(database$scenario))
database = shares
rm(shares, attributes)

# ################################################################# #
#### DEFINE MODEL PARAMETERS                                     ####
# ################################################################# #

### Vector of parameters, including any that are kept fixed in estimation
apollo_beta=c(asc_car      = 0,
              asc_bus      = 0,
              asc_air      = 0,
              asc_rail     = 0,
              b_tt_car     = 0,
              b_tt_bus     = 0,
              b_tt_air     = 0,
              b_tt_rail    = 0,
              b_access     = 0,
              b_cost       = 0,
              b_no_frills  = 0,
              b_wifi       = 0,
              b_food       = 0,
              lambda_PT    = 1)

### Vector with names (in quotes) of parameters to be kept fixed at their starting value in apollo_beta, use apollo_fixed = c() if none
apollo_fixed = c("asc_car","b_no_frills")

# ################################################################# #
#### GROUP AND VALIDATE INPUTS                                   ####
# ################################################################# #

apollo_inputs = apollo_validateInputs()

# ################################################################# #
#### DEFINE MODEL AND LIKELIHOOD FUNCTION                        ####
# ################################################################# #

apollo_probabilities=function(apollo_beta, apollo_inputs, functionality="estimate"){

  ### Attach inputs and detach after function exit
  apollo_attach(apollo_beta, apollo_inputs)
  on.exit(apollo_detach(apollo_beta, apollo_inputs))

  ### Create list of probabilities P
  P = list()

  ### List of utilities: these must use the same names as in fnl_settings, order is irrelevant
  V = list()
  V[["car"]]  = asc_car  + b_tt_car  * time_car                           + b_cost * cost_car
  V[["bus"]]  = asc_bus  + b_tt_bus  * time_bus  + b_access * access_bus  + b_cost * cost_bus
  V[["air"]]  = asc_air  + b_tt_air  * time_air  + b_access * access_air  + b_cost * cost_air    + b_no_frills * ( service_air == 1 )  + b_wifi * ( service_air == 2 )  + b_food * ( service_air == 3 )
  V[["rail"]] = asc_rail + b_tt_rail * time_rail + b_access * access_rail + b_cost * cost_rail   + b_no_frills * ( service_rail == 1 ) + b_wifi * ( service_rail == 2 ) + b_food * ( service_rail == 3 )

  ### Specify nests for FNL model: bus and rail in a public transport nest
  nlNests      = list(root=1,
                      PT=lambda_PT)

  ### Specify tree structure for FNL model
  nlStructure= list()
  nlStructure[["root"]]   = c("car","air","PT")
  nlStructure[["PT"]]     = c("bus","rail")

  ### Define settings for FNL model component
  fnl_settings = list(
    alternatives  = c("car", "bus", "air", "rail"),
    avail         = list(car=av_car, bus=av_bus, air=av_air, rail=av_rail),
    choiceShares  = list(car=share_car, bus=share_bus, air=share_air, rail=share_rail),
    utilities     = V,
    nlNests       = nlNests,
    nlStructure   = nlStructure
  )

  ### Compute probabilities using FNL model
  P[["model"]] = apollo_fnl(fnl_settings, functionality)

  ### Weight each scenario by the number of observations it groups. With these weights, the log-likelihood is the
  ### same sum as that of a NL model with the same utilities and nests on the individual choices, so the estimates
  ### and classical standard errors are the same too. Without them, each scenario would count equally, however
  ### many observations it groups. Each scenario is a single row, so there is no product across observations
  P = apollo_weighting(P, apollo_inputs, functionality)

  ### Prepare and return outputs of function
  P = apollo_prepareProb(P, apollo_inputs, functionality)
  return(P)
}

# ################################################################# #
#### MODEL ESTIMATION                                            ####
# ################################################################# #

model = apollo_estimate(apollo_beta, apollo_fixed, apollo_probabilities, apollo_inputs)

# ################################################################# #
#### MODEL OUTPUTS                                               ####
# ################################################################# #

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO SCREEN)                               ----
# ----------------------------------------------------------------- #

apollo_modelOutput(model,modelOutput_settings = list(printT1=TRUE))

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO FILE, using model name)               ----
# ----------------------------------------------------------------- #

apollo_saveOutput(model,saveOutput_settings = list(printT1=TRUE))

# ################################################################# #
##### POST-PROCESSING                                            ####
# ################################################################# #

### Print outputs of additional diagnostics to new output file (remember to close file writing when complete)
apollo_sink()

# ----------------------------------------------------------------- #
#---- LR TEST AGAINST FMNL MODEL                                 ----
# ----------------------------------------------------------------- #

### The FMNL model on the same grouped data is the special case lambda_PT = 1
apollo_lrTest("FMNL_grouped_shares", model)

# ----------------------------------------------------------------- #
#---- switch off writing to file                                 ----
# ----------------------------------------------------------------- #

apollo_sink()
