library(dplyr)
### numerical experiment parameters
method = "alnsk"
start.method = "vns_extra_2"
nstart = 5
time.limit = 5
iteration.limit = 10000
destroy.connected = F
include.drone.initial = F
save.sols = F
vns.parameter = 5
tcost.list = vector("list", 80)
drone.list = vector("list", 80)
aaa = 0

custnodes = rep(c(20,30,40),each=4)
dtsets = paste(custnodes, 1:4, sep = "-")
dtlen = length(dtsets)
computer = unlist(strsplit(getwd(), "/"))[3]
wd.path = getwd()
shell(paste("cd", wd.path))
cooling.ratio = 0.99
reaction.factor = 0.8
min.temp = 200
min.prob = 0.05
vehicle.capacity = 5
ncust = 10
np.step = 0.001
prob.weights = c(60,30,10,0)
initial.d.factor = 0.2
vehicle.number.initial = g = vehicle.number = 2
truck.routes = vector("list", vehicle.number.initial)
drone.routes = vector("list", vehicle.number.initial)
source(paste0(wd.path, "/funcs.R"))
source(paste0(wd.path, "/feasibility2.R"))
trial = 0
gams.folder = paste0("gams-old-tw-",g)
data.folder = gams.folder
gams.file = "vrptw"
last.trial = 1
nsch = data.frame()
new.schedule = data.frame()

trial.param = c(1,3,5,7,10)

# while(any(sapply(cost.list, function(x) sum(x[,1])==0))){
for(trial in 2:5){
  errs = 0
  wars = 0
  chck = 0
  all.results = numeric(nstart)
  resultsdf = matrix(0, length(dtsets), nstart*5+1)
  movesdf = matrix(0, length(dtsets), max.move*4+1)
  get.data.from = paste(wd.path, data.folder, sep = "/")
  save.name = paste0("resultsdf-", method, "-", start.method, "-",
                     time.limit, "mins-", nstart, "runs-trial-",
                     trial, ".xlsx")
  vns.parameter = trial.param[trial]
  for(data.ind in 1:dtlen){
    dtset = dtsets[data.ind]
    # if(!(dtset %in% c(paste(30,1:4,sep = "-"),"40-3"))){
    #   next()
    # }
    print(method)
    print(dtset)
    vehicle.capacity = ceiling(custnodes[data.ind]/vehicle.number.initial)
    truck.velocity = 40/60
    drone.velocity = 60/60
    source("parameters.R")
    if(dtset%in%c("40-1","40-2","40-3")){
      truck.velocity = 60/60
      drone.velocity = 90/60
    }else{
      truck.velocity = 40/60
      drone.velocity = 60/60
    }
    data.folder = paste(get.data.from, paste0("gams-tw-",dtset), sep = "/")
    df = readxl::read_excel(paste(data.folder, "dataR.xlsx", sep = "/"))
    read_gams_sol_kvehicle(paste0(gams.folder,"/gams-tw-",dtset),vrptw = T)
    opt = read_optimal(dtset, gams.folder, "final", gams.file)
    # opt = 10000
    nodes = nrow(df)
    ncust = nodes-2
    dist.mat = calc_dist_mat(df[,c("x","y")])
    truck.time = round(dist.mat/truck.velocity,4)
    drone.time = round(dist.mat/drone.velocity,4)
    tw.df = find_timeloc_mat()
    
    ninitials = numeric(nstart)
    nresults = rep(NA, nstart)
    ntimes = numeric(nstart)
    seeds = numeric(nstart)
    ndevs = rep(NA, nstart)
    nvrp = numeric(nstart)
    last.trial = last.trial + 1

    for(ns in 1:nstart){
      aaa = aaa + 1
      print(paste0(dtset, ", run: ", ns))
      print(paste("optimal cost:         ", opt))
      starting.time = Sys.time()
      seed = as.numeric(starting.time)
      set.seed(seed)
      seeds[ns] = seed
      schedule = data.frame()
      candidate.schedule = data.frame()
      include.drone = include.drone.initial
      vehicle.number = vehicle.number.initial
      truck.routes = vector("list", vehicle.number)
      drone.routes = vector("list", vehicle.number)
      generate_edd_routes(vehicle.number)
      
      drone.vector = numeric()
      source(paste0(method, ".R"))
      # tcost.list[[aaa]] = cost.vector
      # drone.list[[aaa]] = drone.vector
      plot_dronetruck_kvehicle(best.truck.routes, best.drone.routes)
      title(main = paste("heuristic cost:", round(best.cost,2)))
      plot_costvector()
      
      nresults[ns] = best.cost
      ninitials[ns] = initial.cost
      ntimes[ns] = last.solution.time
      nvrp[ns] = vrp.cost
      ndevs[ns] = round(best.cost/opt-1,4)*100
      trs = best.truck.routes
      drs = best.drone.routes
      # if(g==1){
      #   save_solution(best.truck.routes, best.drone.routes, wd.path,
      #                 data.folder, TRUE, gams.folder, TRUE)
      # }
      
      
      print(paste("last solution time:     ", last.solution.time))
      print(paste("last temperature:       ", temperature))
      print(paste("last temperature length:", temperature.length))
      print(paste("last cost:              ", best.cost))
      print("deviations from optimal:")
      print(ndevs)
      print(paste("algorithm errors:       ", algo.errors))
      print(paste(rep("-", 40), collapse = "-"))
      # Sys.sleep(1)
    }

    opt.found = any(ndevs == 0)
    print(paste("is optimal solution found?:                ", opt.found))
    print(paste("minimum deviation from optimal solution:   ", min(ndevs)))
    print(paste("average deviation from optimal solution:   ", mean(ndevs)))
    print(paste("average time last incumbent solution found:", round(mean(ntimes))))
    chck = chck + checks
    wars = wars + warns
    errs = errs + errors
    print(paste("errors perc:", round(errors/checks,4)))
    print(paste(rep("-", 40), collapse = "-"))
    
    update_matrices(data.ind)
    plot(nresults, type="b")
    abline(h = mean(nresults, na.rm = T))
    xlsx::write.xlsx(resultsdf, save.name,
                     row.names = F, showNA = F, sheetName = "data")
    save.name2 = unlist(strsplit(save.name,"-"))
    save.name2[1] = "movesdf"
    xlsx::write.xlsx(movesdf, paste0(save.name2, collapse = "-"),
                     row.names = F, showNA = F, sheetName = "all")
    
    #Sys.sleep(5)
  }
}

