예제 #1
0
        public double calculateAmoutFood(Lactation currentLactation)
        {
            int    windowSize = 7;
            double sumYield   = 0;
            double avgYield   = 0;
            double amoutFood  = 0;

            List <Yield> yield = currentLactation.yields.ToList();

            for (int i = yield.Count - windowSize; i < yield.Count; i++)
            {
                sumYield += yield[i].totalYield;
            }

            avgYield = sumYield / windowSize;
            if (avgYield <= 5)
            {
                //1kg de concentrado para 3kg de leite
                amoutFood = avgYield / 3;
            }
            else
            {
                //1kg de concentrado para 2,5kg de leite produzido -> produzem acima de 5kg
                amoutFood = avgYield / 2.5;
            }

            //Salva a quantidade na base de dados
            foodRepo.Add(new Food {
                date     = DateTime.Now,
                idCow    = currentLactation.idCow,
                quantity = amoutFood
            });

            return(amoutFood);
        }
예제 #2
0
        public ActionResult Details(int id)
        {
            List <Lactation> lactations = interfaceService.GetLactationCow(id);

            ViewBag.lastLactation = null;
            ViewBag.lastLactation = null;

            Lactation currentLactation = lactations.FirstOrDefault(l => l.finished == false);
            Lactation lastLactation    = null;

            if (currentLactation != null)
            {
                ViewBag.currentLactation = interfaceService.GetLactationEMA(currentLactation.idLactation);
            }

            if (lactations.Where(l => l.finished == true).Count() >= 1)
            {
                List <Lactation> lactationFinished = lactations.Where(l => l.finished == true).OrderBy(l => l.dateBirth).ToList();
                lastLactation         = lactationFinished[lactationFinished.Count - 1];
                ViewBag.lastLactation = interfaceService.GetLactationEMA(lastLactation.idLactation);
            }

            ViewBag.notifications = interfaceService.GetNotificationCow(id);
            ViewBag.foods         = interfaceService.GetAllFoodByCow(id).OrderByDescending(f => f.date).ToList();

            double forecastValue = interfaceService.GetPrediction(id);

            ViewBag.forecastValue = forecastValue;

            return(View(lactations));
        }
예제 #3
0
        private void VerifyCurrentLactation(int idCow, Lactation currentLactation)
        {
            Lactation lastCompleteLactation = lactationRepo.GetLastLactationFinished(idCow, new string[] { "yields" });
            //Lactation currentLactation = lactationRepo.GetLactationByQuery(l => l.finished == false, new string[] { "yields" }).FirstOrDefault(); //GetLastLactationFinished(idCow, new string[] { "yields" });

            int currentDayLactation = currentLactation.yields.Max(y => y.dayLactation); //Receber como parâmetro???

            int indexYieldLastLactation   = lastCompleteLactation.yields.ToList().IndexOf(lastCompleteLactation.yields.FirstOrDefault(y => y.dayLactation == currentDayLactation));
            int indexCurrentLastLactation = currentLactation.yields.ToList().IndexOf(currentLactation.yields.FirstOrDefault(y => y.dayLactation == currentDayLactation));

            int goahead = int.Parse(ConfigurationManager.AppSettings["goahead"]);

            //Excuta script em R para calcular o EMA das lactações
            string resultLastLactation    = string.Empty;
            string resultCurrentLactation = string.Empty;

            //Parametros windowSize e idLactation para última lactação
            string[] param = new string[] { "5", lastCompleteLactation.idLactation.ToString() };
            resultLastLactation = Helper.RScript.Run("lactation-EMA", param);

            //Parametros windowSize e idLactation para lactação atual
            param = new string[] { "5", currentLactation.idLactation.ToString() };
            resultCurrentLactation = Helper.RScript.Run("lactation-EMA", param);
            if (resultLastLactation != "" && resultCurrentLactation != "")
            {
                //Obtem os dados
                string[] arrayResultLastLactation    = resultLastLactation.Replace("NA", "0").Split(' ');
                string[] arrayResultCurrentLactation = resultCurrentLactation.Replace("NA", "0").Split(' ');

                //Obtem o valor da produção com EMA para o período do mesmo dia de lactação atual
                double yieldEMALastLactation    = double.Parse(arrayResultLastLactation[indexYieldLastLactation], new System.Globalization.CultureInfo("en-US"));
                double yieldEMACurrentLactation = double.Parse(arrayResultCurrentLactation[indexCurrentLastLactation], new System.Globalization.CultureInfo("en-US"));
                double threshould = (double.Parse(ConfigurationManager.AppSettings["threshould"]) / 100); //0.2;

                //Verifica se a produção atual da lactação corrente é inferior a produção da lactação anterior aplicado um threshould
                if (yieldEMACurrentLactation < (yieldEMALastLactation - yieldEMALastLactation * threshould))
                {
                    //NOTIFICAÇÃO!
                    //VERIFICAR SE NÃO TEVE UMA GOAHED ATRAS
                    AddNotification("CURRENT", currentLactation.idLactation, "");
                    //throw new Exception("NOTIFICATION - BAD CURRENT LACTATION");
                }
            }
        }
        public DTO_LactationDetails GetLactation(int id)
        {
            //Tratar referencia ciclica Loop
            Lactation lac = interfaceService.GetLactationById(id);

            DTO_LactationDetails dtoLac = new DTO_LactationDetails {
                idLactation = lac.idLactation,
                yields      = (from y in lac.yields
                               select new DTO_Yield
                {
                    date = y.date,
                    dayLactation = y.dayLactation,
                    totalYield = y.totalYield
                }).ToList(),
                yieldEMA = interfaceService.GetLactationEMA(id)
            };

            return(dtoLac);
        }
예제 #5
0
        public bool AddYield(int idCow, double yieldMilk, DateTime?date = null)
        {
            try
            {
                DateTime dateYield;
                dateYield = (date ?? DateTime.Now);
                dateYield = new DateTime(dateYield.Year, dateYield.Month, dateYield.Day);

                //Verifica se a vaca existe
                Cow cowValid = repoCow.GetCow(idCow);
                if (cowValid != null)
                {
                    Lactation currentLact = cowValid.lactations.FirstOrDefault(l => l.finished == false);
                    Yield     yieldDay    = currentLact.yields.FirstOrDefault(y => y.date.Year == dateYield.Year && y.date.Month == dateYield.Month && y.date.Day == dateYield.Day);
                    if (yieldDay == null)
                    {
                        //Insere os dados na lactação corrente
                        Yield yield = new Yield
                        {
                            idLactation  = currentLact.idLactation,
                            totalYield   = yieldMilk,
                            date         = dateYield,
                            dayLactation = (int)(dateYield - currentLact.dateBirth).TotalDays
                        };
                        repoCow.AddYield(yield);
                    }
                    else
                    {
                        //Altera a produção do dia atual somando a quantidade informada
                        yieldDay.totalYield += yieldMilk;
                        repoCow.UpdateYield(yieldDay);
                    }
                    return(true);
                }
            }
            catch (Exception e)
            {
                //throw;
            }

            return(false);
        }
예제 #6
0
        public double ForecastYieldCow(int idCow)
        {
            double forecastValue = 0;

            //Verifica se a vaca existe
            Cow cowValid = repoCow.GetCow(idCow);

            if (cowValid != null)
            {
                Lactation currentLact = cowValid.lactations.FirstOrDefault(l => l.finished == false);
                int       numYields   = currentLact.yields.ToList().Count;
                int       minRecords  = 0;
                int.TryParse(ConfigurationManager.AppSettings["minRecords"], out minRecords);

                //Verifica se existe registros suficientes
                if (numYields >= minRecords)
                {
                    //Executa o script em R que calcula o valor de previsão
                    forecastValue = ForecastValue(idCow);
                    int        goahead    = int.Parse(ConfigurationManager.AppSettings["goahead"]);
                    Prediction prediction = new Prediction
                    {
                        idLactation           = currentLact.idLactation,
                        yield                 = forecastValue,
                        dayLactationPredicted = currentLact.yields.OrderByDescending(y => y.dayLactation).FirstOrDefault().dayLactation + goahead
                    };
                    predictionRepo.Add(prediction);
                }
                else
                {
                    //throw new Exception("Number of records is insufficient");
                }
                //Task.Run(() => notificationService.ValidateDataCow(idCow, currentLact, forecastValue));
                //CHAMA SERVIÇO DE NOTIFICAÇÃO
                notificationService.ValidateDataCow(idCow, currentLact, forecastValue);
            }

            return(forecastValue);
        }
예제 #7
0
        private void VerifyPredictionLactation(int idCow, Lactation currentLactation, double forecastValue)
        {
            //Obtem a última lactação para comparação
            Lactation lastLactation       = lactationRepo.GetLastLactationFinished(idCow, new string[] { "yields" });
            int       currentDayLactation = currentLactation.yields.Max(y => y.dayLactation); //Receber como parâmetro???

            //int currentDayLactation = 27; //Receber como parâmetro???
            int goahead      = int.Parse(ConfigurationManager.AppSettings["goahead"]);
            int dayPredicted = currentDayLactation + goahead;

            int indexYield = lastLactation.yields.ToList().IndexOf(lastLactation.yields.FirstOrDefault(y => y.dayLactation == dayPredicted));

            //Excuta script em R para calcular o EMA da última lactação
            string result = string.Empty;

            //Parametros windowSize e idLactation
            string[] param = new string[] { goahead.ToString(), lastLactation.idLactation.ToString() };
            result = Helper.RScript.Run("lactation-EMA", param);
            if (result != "")
            {
                //Obtem os dados
                string[] arrayResult = result.Replace("NA", "0").Split(' ');

                //Obtem o valor da produção para o mesmo período  mesmo dia da lactação
                double yieldEMALastLactation = double.Parse(arrayResult[indexYield], new System.Globalization.CultureInfo("en-US"));
                double threshould            = (double.Parse(ConfigurationManager.AppSettings["threshould"]) / 100); //0.2;

                //Verifica se a produção prevista para a lactação corrente é inferior a produção da lactação anterior aplicado um threshould
                if (forecastValue < (yieldEMALastLactation - yieldEMALastLactation * threshould))
                {
                    //NOTIFICAÇÃO!
                    //VERIFICAR SE NÃO TEVE UMA GOAHED ATRAS
                    AddNotification("PREDICTION", currentLactation.idLactation, "");
                    //throw new Exception("NOTIFICATION - BAD PREDICTION");
                }
            }
        }
예제 #8
0
 public void ValidateDataCow(int idCow, Lactation currentLactation, double forecastValue)
 {
     VerifyPredictionLactation(idCow, currentLactation, forecastValue);
     VerifyCurrentLactation(idCow, currentLactation);
 }