options(scipen=20, digits=6)

#======================================================================================================
# Load packages

lapply(c("data.table", "ggplot2"), require, character.only=T)

#======================================================================================================
# Set working directory and load scripts

# setwd("/Users/Ben/Documents/Kaggle/GrupoBimbo")

#======================================================================================================
# Load data

train <- fread("../input/train.csv", select=c("Semana", "Cliente_ID", "Producto_ID", "Ruta_SAK", "Demanda_uni_equil"))
test <- fread("../input/test.csv", select=c("id", "Semana", "Cliente_ID", "Producto_ID", "Ruta_SAK", "Demanda_uni_equil"))

#--------------------------------------------------
# Transform Demand = log(Demand + 1)

train[, LogDemand := log1p(Demanda_uni_equil)]

#--------------------------------------------------
# Insert predictions into test and tranform values - Demand = log(Demand + 1)

# NOTE: If you use this script for real, make sure you supposed to comment/uncomment the lines below
test[, LogDemand := rnorm(.N, mean=1.6, sd=.3)]
# subm <- fread("Submissions/your_best_submission.csv")
# test[subm, LogDemand := log1p(Demanda_uni_equil), on="id"]

#--------------------------------------------------
# Adjust variables

train[, Ruta_SAK := factor(Ruta_SAK)]
test[, Ruta_SAK := factor(Ruta_SAK)]

#======================================================================================================
# Plot LogDemand per week per product per route (with projections) for a specified client

# Get the LogDemand per (product, week) pair
prodwks <- train[, list(LogDemand=mean(LogDemand)), keyby=list(Producto_ID, Semana)]

plotClient <- function(cliente_ID=sample(unique(train$Cliente_ID), 1), producto_ID=NULL){
  # Plot LogDemand per week per product per route (with projections) for a specified client
  
  # Get all rows of train with the specified client. Subset by producto_ID if given
  clientSamples <- train[J(Cliente_ID=cliente_ID), on="Cliente_ID"]
  if(!is.null(producto_ID)) clientSamples <- clientSamples[J(Producto_ID=producto_ID), on="Producto_ID", nomatch=0]
  clientSamples[, Grp := factor("Client", levels=c("Client", "Overall"))]
  
  # Get all rows of test with the specified client. Subset by producto_ID if given
  predpts <- test[J(Cliente_ID=cliente_ID), on="Cliente_ID", nomatch=0]
  if(!is.null(producto_ID)) predpts <- predpts[J(Producto_ID=producto_ID), on="Producto_ID", nomatch=0]
  
  # Build a dataset showing the average LogDemand for each product across all clients
  prodwks.matching <- prodwks[Producto_ID %in% unique(c(clientSamples$Producto_ID, predpts$Producto_ID))]
  prodwks.matching[, Grp := factor("Overall", levels=c("Client", "Overall"))]
  
  # Build a table with train and test samples together
  dt <- rbind(clientSamples, prodwks.matching, fill=TRUE)[order(!is.na(Cliente_ID))]
  
  # Add a product label
  dt[, Product := paste("Product", Producto_ID)]
  predpts[, Product := paste("Product", Producto_ID)]
  
  # Plot that sucker
  ggplot(dt, aes(x=Semana, y=LogDemand, group=Ruta_SAK, color=Ruta_SAK, linetype=Grp))+geom_line()+geom_point()+
    geom_vline(data=predpts, aes(xintercept=Semana))+facet_wrap(~Product)+
    geom_point(data=predpts, aes(x=Semana, y=LogDemand, linetype=NA))+
    xlim(3, 11)+labs(title=paste("Client", cliente_ID))+ylim(0,NA)+
    labs(title=paste("Client", cliente_ID))+theme_minimal()
}

plotClient(cliente_ID=764784L)
plotClient(cliente_ID=764784L, producto_ID=1250L)
