# This R environment comes with all of CRAN preinstalled, as well as many other helpful packages
# The environment is defined by the kaggle/rstats docker image: https://github.com/kaggle/docker-rstats
# For example, here's several helpful packages to load in 

library(ggplot2) # Data visualization
library(readr) # CSV file I/O, e.g. the read_csv function
library(lme4)

# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

system("ls ../input")




#import train data
sampleData <- read.csv("../input/train.csv", header = TRUE, nrows = 5, sep=",")
classes <- sapply(sampleData, class)
largeData <- read.csv("../input/train.csv", header = TRUE, colClasses = classes, nrows=200000)
str(largeData)

#import test data
testSampleData <- read.csv("../input/test.csv", header = TRUE, nrows = 5, sep=",")
classes <- sapply(testSampleData, class)
testLargeData <- read.csv("../input/test.csv", header = TRUE, colClasses = classes)
str(testLargeData)
summary(largeData$Semana)
length(unique(largeData$Agencia_ID))
length(unique(largeData$Semana))
length(unique(largeData$Cliente_ID))
length(unique(largeData$Producto_ID))
if(FALSE){
#create model
t0 <- Sys.time()
#modFit <- train(Demanda_uni_equil ~ .,method="gbm",data=largeData, verbose=FALSE)
modFit <- lmer(log(Demanda_uni_equil+1) ~ (1|Semana) + (1|Agencia_ID)+ (1|Cliente_ID)
+ (1|Producto_ID),data=largeData)
summary(modFit)
t1 <- Sys.time()
t1-t0


#create prediction
prediction <- predict(modFit, newdata = testLargeData)
t2 <- Sys.time()
t2-t1
str(prediction)

#fix negatives
prediction[prediction<0] = 0.01

#create submission file
submission <- data.frame(ID=testLargeData$id, Demanda_uni_equil=prediction)
write.csv(submission, "submission.csv", row.names = F)}

# Any results you write to the current directory are saved as output.