library(data.table)

print("Reading data")
train <- fread('../input/train.csv', 
               select = c('Semana','Cliente_ID', 'Producto_ID', 'Agencia_ID', 'Ruta_SAK', 'Demanda_uni_equil'))

test <- fread('../input/test.csv', 
              select = c('id','Semana', 'Cliente_ID', 'Producto_ID', 'Agencia_ID', 'Ruta_SAK'))

train$log_demand = log1p(train$Demanda_uni_equil) 

mean_P <-  train[, .(MP = mean(log_demand)), by = .(Semana, Producto_ID)]

mean_P_a = train[, .(MPa= mean(log_demand)), by = .(Producto_ID)]

w <- mean_P[, .(b = lm(MP~Semana)$coefficients[1], a = lm(MP~Semana)$coefficients[2] ), by = Producto_ID]
print(w)

#y <- w[,.(Predic = Semana * a + b), by = .(Producto_ID)]
print(test)
#submit <- merge(test, mean_P_a , all.x = TRUE, by = c("Producto_ID"))
submit <- merge(test, w , all.x = TRUE, by = c("Producto_ID"))
print(submit)
x <- submit[, .(id = id, Producto_ID = Producto_ID, Predic = Semana * a + b)] 
print(x)
#submit <- merge(test, x , all.x = TRUE, by = c("Producto_ID"))
#y <- merge(submit, x , all.x = TRUE, by = c("Producto_ID"))
print(submit)
#submit[is.na(Predic)]$Predic <- expm1(submit[is.na(Predic)]$MPa)*0.789+0.091
#u <- subset(submit, Predic == "NA")
#print(x)

#setnames(submit,"Predic","Demanda_uni_equil")
# Any results you write to the current directory are saved as output.
#write.csv(submit[,.(id,Demanda_uni_equil)],"submit_mean_by_Agency_Ruta_Client.csv", row.names = FALSE)
print("Done!")


