public ProductForCast getProductSalesPredictions(int productID, int numPredictions, int value1 = 1, int value2 = 5) { var toreturn = new ProductForCast(); var pastSales = (from c in db.productsalespermonths where c.Product_ID == productID select c.sales.Value).ToList(); toreturn.productID = productID; toreturn.name = db.products.Find(productID).productName; toreturn.previouse = Array.ConvertAll(pastSales.ToArray(), x => (double)x); ArimaModel model = new ArimaModel(toreturn.previouse, value1, value2); model.Compute(); toreturn.predictions = Array.ConvertAll(model.Forecast(numPredictions).ToArray(), x => (double)x); return(toreturn); }
public static void Optimize() { SARIMAForm bpf = new SARIMAForm(); if (bpf.ShowDialog() != DialogResult.OK) { return; } SelectData(bpf.dateTimePicker1.Value, bpf.dateTimePicker2.Value, int.Parse(bpf.tbM.Text)); NumericalVariable traf = new NumericalVariable("Трафик", arrTraf); ArimaModel model = new ArimaModel(traf, int.Parse(bpf.tbAR.Text), int.Parse(bpf.tbD.Text), int.Parse(bpf.tbMA.Text)); //model.Compute(); List <string> list = new List <string>(); list.Add("Параметры модели авторегрессии:"); //for (int i = 0; i < model.AutoRegressiveParameters.Count; i++) //list.Add(string.Format("{0} = {1:g4}", model.AutoRegressiveParameters[i].Name, model.AutoRegressiveParameters[i].PValue)); //list.Add("Параметры модели скользящего среднего:"); //for (int i = 0; i < model.MovingAverageParameters.Count; i++) //list.Add(string.Format("{0} = {1:g4}", model.MovingAverageParameters[i].Name, model.MovingAverageParameters[i].PValue)); //list.Add(string.Format("Среднее: {0:g4}", model.Mean)); int p = int.Parse(bpf.tbProg.Text); List <double> lF = new List <double>(); TimeSpan ts = arrDT.Last() - arrDT[arrDT.Length - 2], ts2 = new TimeSpan(ts.Ticks / 2); DateTime dt = arrDT.Last() + ts; double av = arrTraf.Average(); for (int i = 0; i < p; i++) { lF.Add(prInt(dt - ts2, dt + ts2)); dt += ts; } arrF = lF.ToArray(); double avF = arrF.Average(); for (int i = 0; i < arrF.Length; i++) { arrF[i] /= avF / av; } //arrF = model.Forecast(p).ToArray(); ModelForm mf = new ModelForm(list.ToArray()); mf.ShowDialog(); }
public double[][] Forecast(int days) { var openVector = Vector.Create(openValues); var closeVector = Vector.Create(closeValues); ArimaModel openModel = new ArimaModel(openVector, parameters[0], parameters[1], parameters[2]); ArimaModel closeModel = new ArimaModel(openVector, parameters[0], parameters[1], parameters[2]); openModel.Fit(); closeModel.Fit(); double[][] forecast = new double[2][]; forecast[0] = openModel.Forecast(days).ToArray(); // open forecast forecast[1] = closeModel.Forecast(days).ToArray(); // close forecast return(forecast); }
public double[] ArimaTest(int lag) { // The time series data is stored in a numerical variable: var sunspots = Vector.Create(100.8, 81.6, 66.5, 34.8, 30.6, 7, 19.8, 92.5, 154.4, 125.9, 84.8, 68.1, 38.5, 22.8, 10.2, 24.1, 82.9, 132, 130.9, 118.1, 89.9, 66.6, 60, 46.9, 41, 21.3, 16, 6.4, 4.1, 6.8, 14.5, 34, 45, 43.1, 47.5, 42.2, 28.1, 10.1, 8.1, 2.5, 0, 1.4, 5, 12.2, 13.9, 35.4, 45.8, 41.1, 30.4, 23.9, 15.7, 6.6, 4, 1.8, 8.5, 16.6, 36.3, 49.7, 62.5, 67, 71, 47.8, 27.5, 8.5, 13.2, 56.9, 121.5, 138.3, 103.2, 85.8, 63.2, 36.8, 24.2, 10.7, 15, 40.1, 61.5, 98.5, 124.3, 95.9, 66.5, 64.5, 54.2, 39, 20.6, 6.7, 4.3, 22.8, 54.8, 93.8, 95.7, 77.2, 59.1, 44, 47, 30.5, 16.3, 7.3, 37.3, 73.9); //Find 'd'. AugmentedDickeyFullerTest adf = new AugmentedDickeyFullerTest(sunspots, 0); double d = adf.Statistic; // Console.WriteLine(d); // Console.WriteLine(adf.PValue); // An integrated model (with differencing) is constructed // by supplying the degree of differencing. Note the order // of the orders is the traditional one for an ARIMA(p,d,q) // model (p, d, q). // The following constructs an ARIMA(0,1,1) model: ArimaModel model = new ArimaModel(sunspots, 2, 1); model.EstimateMean = true; // The Compute methods fits the model. model.Fit(); //Predict a specified number of values: var nextValues = model.Forecast(5); //Cast to double[]. var castedNextValues = new double[nextValues.Length]; for (var i = 0; i < nextValues.Length; i++) { castedNextValues[i] = nextValues[i]; } return(castedNextValues); }
public double[] Arima(int forecast, double[] values) { Vector <double> tempValues = Vector.Create(values); //Find 'd'. var adf = new AugmentedDickeyFullerTest(values, 0); var p = adf.PValue; var acf = tempValues.AutocorrelationFunction(20); if (p > 0.05D) { p = 1; } tempValues = tempValues.Difference(); // An integrated model (with differencing) is constructed // by supplying the degree of differencing. Note the order // of the orders is the traditional one for an ARIMA(p,d,q) // model (p, d, q). var model = new ArimaModel(values, (int)p, 3, 3); model.EstimateMean = true; // The Compute methods fits the model. model.Fit(); //Predict a specified number of values: var nextValues = model.Forecast(forecast); //Cast to double[]. var castedNextValues = new double[nextValues.Length]; for (var i = 0; i < nextValues.Length; i++) { castedNextValues[i] = nextValues[i]; } // return castedNextValues; return(castedNextValues); }
} // pure static class /// <summary> /// Raw-level ARIMA forecasting function. /// </summary> /// <param name="data"> UNMODIFIED, list of double numbers representing time-series with constant time-gap </param> /// <param name="forecastSize"> integer representing how many data points AFTER the data series to be /// forecasted </param> /// <param name="params"> ARIMA parameters </param> /// <returns> a ForecastResult object, which contains the forecasted values and/or error message(s) </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static TimeSeries.Forecast.TimeSeries.Arima.struct.ForecastResult forecast_arima(final double[] data, final int forecastSize, TimeSeries.Forecast.TimeSeries.Arima.struct.ArimaParams params) public static ForecastResult forecast_arima(double[] data, int forecastSize, ArimaParams @params) { try { int p = @params.p; int d = @params.d; int q = @params.q; int P = @params.P; int D = @params.D; int Q = @params.Q; int m = @params.m; ArimaParams paramsForecast = new ArimaParams(p, d, q, P, D, Q, m); ArimaParams paramsXValidation = new ArimaParams(p, d, q, P, D, Q, m); // estimate ARIMA model parameters for forecasting ArimaModel fittedModel = ArimaSolver.estimateARIMA(paramsForecast, data, data.Length, data.Length + 1); // compute RMSE to be used in confidence interval computation double rmseValidation = ArimaSolver.computeRMSEValidation(data, ForecastUtil.testSetPercentage, paramsXValidation); fittedModel.RMSE = rmseValidation; ForecastResult forecastResult = fittedModel.Forecast(forecastSize); // populate confidence interval forecastResult.Sigma2AndPredicationInterval = fittedModel.Params; // add logging messages forecastResult.Log("{" + "\"Best ModelInterface Param\" : \"" + fittedModel.Params.summary() + "\"," + "\"Forecast Size\" : \"" + forecastSize + "\"," + "\"Input Size\" : \"" + data.Length + "\"" + "}"); // successfully built ARIMA model and its forecast return(forecastResult); } catch (Exception ex) { // failed to build ARIMA model throw new Exception("Failed to build ARIMA forecast: " + ex.Message); } }
static void Main(string[] args) { //require R 2.15, package forecast on R var envPath = Environment.GetEnvironmentVariable("PATH"); var rBinPath = GetRPath(); //C:\Program Files\R\R-2.15.1\bin\i386 Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath); REngine engine = REngine.CreateInstance("RDotNet"); engine.Initialize(); string currentPath = Directory.GetCurrentDirectory(); string dataPath = currentPath + @"\data\paper.dat"; string readDataCommand = string.Format("predata <- read.table(\"{0}\", header=FALSE)", dataPath).Replace('\\', '/'); engine.Evaluate("library(forecast)"); engine.Evaluate(readDataCommand); engine.Evaluate("data <- predata[,1]"); var model = engine.Evaluate("fit <- auto.arima(data)").AsList(); var coef = model["coef"].AsList(); int lengthData = engine.Evaluate("data").AsNumeric().Length; double[] dataSeries = new double[lengthData]; double[] errorSeries = new double[lengthData]; engine.Evaluate("data").AsNumeric().CopyTo(dataSeries, lengthData); model["residuals"].AsNumeric().CopyTo(errorSeries, lengthData); //residuals int arOrder = model["arma"].AsInteger().ElementAt(0); int maOrder = model["arma"].AsInteger().ElementAt(1); int arSeasonOrder = model["arma"].AsInteger().ElementAt(2); int maSeasonOrder = model["arma"].AsInteger().ElementAt(3); int seasonOrder = model["arma"].AsInteger().ElementAt(4); int diffOrder = model["arma"].AsInteger().ElementAt(5); int diffSeasonOrder = model["arma"].AsInteger().ElementAt(6); double[] arCoef = new double[arOrder]; double[] maCoef = new double[maOrder]; double[] arSeasonCoef = new double[arSeasonOrder]; double[] maSeasonCoef = new double[maSeasonOrder]; double intercept = 0; int n = model["coef"].AsNumeric().Length; int start = 0; model["coef"].AsNumeric().CopyTo(arCoef, arOrder, start, 0); start += arOrder; model["coef"].AsNumeric().CopyTo(maCoef, maOrder, start, 0); start += maOrder; model["coef"].AsNumeric().CopyTo(arSeasonCoef, arSeasonOrder, start, 0); start += arSeasonOrder; model["coef"].AsNumeric().CopyTo(maSeasonCoef, maSeasonOrder, start, 0); start += maSeasonOrder; if (n > start) { intercept = model["coef"].AsNumeric().ElementAt(start); } ArimaModel arimaModel = new ArimaModel(arCoef, maCoef, arSeasonCoef, maSeasonCoef, intercept, (uint)seasonOrder, (uint)diffOrder, (uint)diffSeasonOrder); Polynomial arModel = arimaModel.ComputeARModel(); Polynomial maModel = arimaModel.ComputeMAModel(); double interceptModel = arimaModel.ComputeIntercept(); double test = arimaModel.ComputeValue(dataSeries, errorSeries, dataSeries.Length); Console.WriteLine("Forecast"); Console.WriteLine(test); Console.WriteLine("Model"); Console.WriteLine(interceptModel); Console.WriteLine("Ar"); Console.WriteLine(arModel.ToString()); Console.WriteLine("Ma"); Console.WriteLine(maModel.ToString()); Console.ReadLine(); }
public void Test(HomeController controller) { //require R 2.15, package forecast on R //var envPath = Environment.GetEnvironmentVariable("PATH"); //var rBinPath = GetRPath(); //C:\Program Files\R\R-2.15.1\bin\i386 //var BinPath = GetWinRegistryPath(); //var envPath = Environment.GetEnvironmentVariable("PATH"); // this statement not work under iis //Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + BinPath); REngine engine = REngine.GetInstance(); engine.Initialize(); string currentPath = @"C:\Workspace\SAM\SAM\VisualAnalytics\bin"; //Directory.GetCurrentDirectory(); string dataPath = currentPath + @"\data\paper.dat"; string readDataCommand = string.Format("predata <- read.table(\"{0}\", header=FALSE)", dataPath).Replace('\\', '/'); //engine.Evaluate("install.packages(\"forecast\")"); engine.Evaluate("library(jsonlite)"); engine.Evaluate("library(forecast)"); String JsonData = @"http://localhost:25910/Home/getBigTable";//controller.getBigTable().Content; log.Debug("JSON:" + JsonData); string evaluate = string.Format("data <-fromJSON(\"{0}\")", JsonData); log.Debug("evaluateString:" + evaluate); engine.Evaluate(evaluate); //log.Debug(engine.Evaluate("data")); //engine.Evaluate("data <- predata[,1]"); var model = engine.Evaluate("fit <- auto.arima(data$Amount)").AsList(); foreach (var item in model) { log.Debug(item.ToString()); } var coef = model["coef"].AsList(); int lengthData = engine.Evaluate("data$Amount").AsNumeric().Length; double[] dataSeries = new double[lengthData]; double[] errorSeries = new double[lengthData]; engine.Evaluate("data$Amount").AsNumeric().CopyTo(dataSeries, lengthData); model["residuals"].AsNumeric().CopyTo(errorSeries, lengthData); //residuals int arOrder = model["arma"].AsInteger().ElementAt(0); int maOrder = model["arma"].AsInteger().ElementAt(1); int arSeasonOrder = model["arma"].AsInteger().ElementAt(2); int maSeasonOrder = model["arma"].AsInteger().ElementAt(3); int seasonOrder = model["arma"].AsInteger().ElementAt(4); int diffOrder = model["arma"].AsInteger().ElementAt(5); int diffSeasonOrder = model["arma"].AsInteger().ElementAt(6); double[] arCoef = new double[arOrder]; double[] maCoef = new double[maOrder]; double[] arSeasonCoef = new double[arSeasonOrder]; double[] maSeasonCoef = new double[maSeasonOrder]; double intercept = 0; int n = model["coef"].AsNumeric().Length; int start = 0; model["coef"].AsNumeric().CopyTo(arCoef, arOrder, start, 0); start += arOrder; model["coef"].AsNumeric().CopyTo(maCoef, maOrder, start, 0); start += maOrder; model["coef"].AsNumeric().CopyTo(arSeasonCoef, arSeasonOrder, start, 0); start += arSeasonOrder; model["coef"].AsNumeric().CopyTo(maSeasonCoef, maSeasonOrder, start, 0); start += maSeasonOrder; if (n > start) { intercept = model["coef"].AsNumeric().ElementAt(start); } ArimaModel arimaModel = new ArimaModel(arCoef, maCoef, arSeasonCoef, maSeasonCoef, intercept, (uint)seasonOrder, (uint)diffOrder, (uint)diffSeasonOrder); Polynomial arModel = arimaModel.ComputeARModel(); Polynomial maModel = arimaModel.ComputeMAModel(); double interceptModel = arimaModel.ComputeIntercept(); double test = arimaModel.ComputeValue(dataSeries, errorSeries, dataSeries.Length); log.Info("Forecast"); log.Info(test); log.Info("Model"); log.Info(interceptModel); log.Info("Ar"); log.Info(arModel.ToString()); log.Info("Ma"); log.Info(maModel.ToString()); //Console.ReadLine(); }
void Start() { var Et = new List <double>(); var Zt = new List <double>(); var Lt = new List <double>(); timeSeriGenerator = new TimeSeriGenerator <double>(); arimaLogger = new StreamWriter("Best_Hybrid_ArimaGALog.txt"); int numInp = 0; this.Dispatcher.Invoke(new Action(() => numInp = Int32.Parse(NumberOfInpTextBox.Text))); timeSeriGenerator.load(numInp); Dispatcher.Invoke(new Action(() => ActivityProgressBar.IsIndeterminate = true)); Dispatcher.Invoke(new Action(() => numberOfTests = Int32.Parse(OptimumTestTextBox.Text))); Dispatcher.Invoke(new Action(() => numberOfForecastTests = Int32.Parse(ForecastTestTextBox.Text))); MyTimeSeriForBestHybrid <double> myTimeSeriForBestHybrid = timeSeriGenerator.generateForBestHybrid(numberOfForecastTests); //maxGAIteretionInArima = 1000; //var train = new double[timeSeriGenerator.TimeSeri.Length - 5]; //var test = new double[5]; //for (int i = 0; i < train.Length; i++) //{ // train[i] = timeSeriGenerator.TimeSeri[i]; //} //for (int i = train.Length, j = 0; i < timeSeriGenerator.TimeSeri.Length; i++, j++) //{ // test[j] = timeSeriGenerator.TimeSeri[i]; //} //ArimaGA aga=new ArimaGA(); //aga.StartArima(train); //NumericalVariable timeSeriii = new NumericalVariable("timeSeriii", train); //arimaModel = new ArimaModel(timeSeriii, aga.bestP, aga.bestD, aga.bestQ); //arimaModel.Compute(); //var fv2 = arimaModel.Forecast(numberOfForecastTests); //double ea2 = MyErrorParameters.ERROR_Percent(fv2.ToArray(), test);) for (int i = 0; i < myTimeSeriForBestHybrid.part2.Count; i++) { StartArima(myTimeSeriForBestHybrid.part1.ToArray()); //// converting to double[] //double[] db = new double[myTimeSeriForBestHybrid.part1.Count]; //for (int j = 0; j < db.Length; j++) //{ // db[j] = myTimeSeriForBestHybrid.part1.ToArray()[j]; //} NumericalVariable timeSerii = new NumericalVariable("timeSerii", myTimeSeriForBestHybrid.part1.ToArray()); arimaModel = new ArimaModel(timeSerii, myBestP, myBestD, myBestQ); arimaModel.Compute(); var res = arimaModel.Forecast(1); float lt = (float)res[0]; Lt.Add(lt); double target = myTimeSeriForBestHybrid.part2[i]; double e = lt - target; Et.Add(e); myTimeSeriForBestHybrid.part1.Add(target); double mu = myTimeSeriForBestHybrid.part1.Average(); if (myBestD == 0) { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - mu); } else if (myBestD == 1) { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 2] - mu); } else { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - 2 * myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 2] + myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 3] - mu); } } ArimaModel EtArimaModel = new ArimaGA().GetBestModel(Et.ToArray()); ArimaModel ZtArimaModel = new ArimaGA().GetBestModel(Zt.ToArray()); int a = 0; SVM svm = new SVM(); //TimeSeriGenerator<double> gen = new TimeSeriGenerator<double>(); //gen.NumberOfInputVariables = Int32.Parse(NumberOfInpTextBox.Text); //gen.TimeSeri = Et.ToArray(); //var EtTimeSeries = gen.generate(); //gen = new TimeSeriGenerator<double>(); //gen.NumberOfInputVariables = Int32.Parse(NumberOfInpTextBox.Text); //gen.TimeSeri = Zt.ToArray(); //var ZtTimeSeries = gen.generate(); //// biaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Pair <int> bestAB = CreateComplexHybridModel(Et.ToArray(), Lt.ToArray(), Zt.ToArray()); double minErr = SVMComplexModelForBestModel(bestAB.First, bestAB.Second, Et.ToArray(), Lt.ToArray(), Zt.ToArray()); MessageBox.Show(bestAB.First + " , " + bestAB.Second + "\nMinError In Training Is => " + minErr, "Now Best M & N Found", MessageBoxButton.OK, MessageBoxImage.Asterisk); // --------------------------------- now our complex hybrid model is created ----------------------------------------------------------------- double mse = 0; double errorPercent = 0; double sumTargets = 0; if (myTimeSeriForBestHybrid.part1.Count != timeSeriGenerator.TimeSeri.Length - numberOfForecastTests) { MessageBox.Show("Input For Arima Model Is Not Completed", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error); } // << CHECK HERE >> (FOR CHECKING PURPOSE ONLY , COMMENT HERE LATER) var forecastedVector = arimaModel.Forecast(numberOfForecastTests); double eoa = MyErrorParameters.ERROR_Percent(forecastedVector.ToArray(), myTimeSeriForBestHybrid.testCases.ToArray()); MessageBox.Show("Error Of Arima Is => " + eoa, "Arima Error", MessageBoxButton.OK, MessageBoxImage.Information); //maxGAIteretionInArima = 1000; //StartArima(myTimeSeriForBestHybrid.part1.ToArray()); //double[] dbb = new double[myTimeSeriForBestHybrid.part1.Count]; //for (int j = 0; j < dbb.Length; j++) //{ // dbb[j] = myTimeSeriForBestHybrid.part1.ToArray()[j]; //} //NumericalVariable timeSeriTest = new NumericalVariable("timeSerii", dbb); //arimaModel = new ArimaModel(timeSeriTest, myBestP, myBestD, myBestQ); //arimaModel.Compute(); StreamWriter hybridWriter = new StreamWriter(OUTPUT_FILE_NAME); List <double> results = new List <double>(); //double errorOfArima = MyErrorParameters.ERROR_Percent(forcastedVector.ToArray(), myTimeSeriForBestHybrid.testCases.ToArray()); //MessageBox.Show("Error Of Arima Is => " + errorOfArima, "Arima Error", MessageBoxButton.OK, // MessageBoxImage.Information); // --------------------------------------------------------------- int numOfInp = bestAB.First + bestAB.Second + 1; int rows = Et.Count - Math.Max(bestAB.First, bestAB.Second); float[,] inps = new float[rows, numOfInp]; double[] targs = new double[rows]; int y = bestAB.First; int z = bestAB.Second; int ll = 0; for (int o = 0; o < rows; o++) { if (y > z) { for (int j = 0; j < y; j++) { inps[o, j] = (float)Et[ll + j]; } inps[o, y] = (float)Lt[ll + y]; for (int j = 0; j < z; j++) { inps[o, y + j + 1] = (float)Zt[ll + y - z + j]; } targs[o] = timeSeriGenerator.TimeSeri[ll + y]; } else { for (int j = 0; j < y; j++) { inps[o, j] = (float)Et[ll + z - y + j]; } inps[o, y] = (float)Lt[ll + z]; for (int j = 0; j < z; j++) { inps[o, j + y + 1] = (float)Zt[ll + j]; } targs[o] = timeSeriGenerator.TimeSeri[ll + z]; } ll++; } float[,] trainInputs = new float[rows - numberOfTests, numOfInp]; float[] trainTargets = new float[rows - numberOfTests]; float[,] testInputs = new float[numberOfTests, numOfInp]; float[] testTargets = new float[numberOfTests]; int t = 0; for (; t < rows - numberOfTests; t++) { for (int j = 0; j < numOfInp; j++) { trainInputs[t, j] = inps[t, j]; } trainTargets[t] = (float)targs[t]; } for (int o = 0; t < rows; o++, t++) { for (int j = 0; j < numOfInp; j++) { testInputs[o, j] = inps[t, j]; } testTargets[o] = (float)targs[t]; } svmModelHybrid = new SVM(); SVM_KERNEL_TYPE bestKernelType = SVM_KERNEL_TYPE.RBF; double bestEps = 0.001; SVMParams p; Matrix <float> trainData = new Matrix <float>(trainInputs); Matrix <float> trainClasses = new Matrix <float>(trainTargets); p = new SVMParams(); p.KernelType = bestKernelType; p.SVMType = Emgu.CV.ML.MlEnum.SVM_TYPE.EPS_SVR; // for regression p.C = 1; p.TermCrit = new MCvTermCriteria(100, bestEps); p.Gamma = 1; p.Degree = 1; p.P = 1; p.Nu = 0.1; bool _trained = svmModelHybrid.TrainAuto(trainData, trainClasses, null, null, p.MCvSVMParams, 10); // --------------------------------------------------------------- for (int i = 0; i < numberOfForecastTests; i++) { float[,] inpTest = new float[bestAB.First + bestAB.Second + 1, 1]; int l = 0; for (int j = 0; j < bestAB.First; j++, l++) { inpTest[l, 0] = (float)Et[Et.Count - bestAB.First + j]; } inpTest[l++, 0] = (float)forecastedVector[i]; for (int j = 0; j < bestAB.Second; j++, l++) { inpTest[l, 0] = (float)Zt[Zt.Count - bestAB.Second + j]; } // injaaaaaaaaaaaaaaaaaaaa float result = svmModelHybrid.Predict(new Matrix <float>(inpTest)); results.Add(result); hybridWriter.WriteLine(result); double target = myTimeSeriForBestHybrid.testCases[i]; // preparing for next use in this for loop double resi = target - (float)forecastedVector[i]; // float resi = target - result; << CHECK HERE IMPORTANT >> Et.Add(resi); myTimeSeriForBestHybrid.part1.Add(target); double mu = myTimeSeriForBestHybrid.part1.Average(); if (myBestD == 0) { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - mu); } else if (myBestD == 1) { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 2] - mu); } else //else if (bestD == 2) << CHECK HERE >> { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - 2 * myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 2] + myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 3] - mu); } } double _mse = MyErrorParameters.MSE(results.ToArray(), myTimeSeriForBestHybrid.testCases.ToArray()); double _errorPercent = MyErrorParameters.ERROR_Percent(results.ToArray(), myTimeSeriForBestHybrid.testCases.ToArray()); hybridWriter.WriteLine("\n\n\nMSE & ERROR% are =>\n\n{0} {1}", _mse, _errorPercent); hybridWriter.Flush(); hybridWriter.Close(); MessageBox.Show( String.Format( "Complex Hybrid Model Created File {0} For Output Successfully Now , Please Check It Out .", OUTPUT_FILE_NAME), "Hybrid SVM Arima Done", MessageBoxButton.OK, MessageBoxImage.Information); }
public static async Task <ScalingState> ScalingFunction( [OrchestrationTrigger] DurableOrchestrationContext context, ILogger log) { log.LogScalingFunction("Get new input."); var scalingState = context.GetInput <ScalingState>(); log.LogScalingFunction($"Scaling for {scalingState.CurrentPartOfPeriod} part of period."); log.LogScalingFunction("Waiting for event from Metrics Collection"); if (scalingState.Wait) { var @event = await context.WaitForExternalEvent <MetricCollected>(nameof(MetricCollected)); log.LogScalingFunction($"Update current metrics data."); scalingState.AddMetric(@event.Metric); } log.LogScalingFunction($"Prepare ARIMA model. Autoregresive: {AutoregresiveParam}, Integration: {IntegrationParam}, Move Averrage: {MoveAverrageParam}"); var vectorMetricsData = Vector.Create(scalingState.MetricData.ToArray()); var model = new ArimaModel(vectorMetricsData, AutoregresiveParam, IntegrationParam, MoveAverrageParam); model.EstimateMean = true; log.LogScalingFunction("Fit ARIMA model."); model.Fit(); log.LogScalingFunction("Forecast capacity for rest period."); var period = MasterPerformMetricsCollector.Period - scalingState.CurrentPartOfPeriod - 1; var forecastedData = model.Forecast(period); log.LogScalingFunction("Calculate capacity"); var capacityPerDay = forecastedData.Select(z => CapacityHelpers.CalculateCapacity(z)).ToList(); var cost = capacityPerDay.Select(z => CapacityHelpers.CalculateCostOfCapacity(z)).Sum(); var restCost = scalingState.RestCost - cost; var division = (int)restCost / period; if (division >= 1) { var additionalMachine = division > 2 ? division / MasterPerformMetricsCollector.Q : 1; capacityPerDay = capacityPerDay.Select(z => z + additionalMachine).ToList(); restCost -= (additionalMachine * capacityPerDay.Count); } log.LogScalingFunction("Get capacity for part of period."); var capacity = capacityPerDay.First(); log.LogScalingFunction($"Capacity to set: {capacity}"); var action = new ScaleAction(capacity); await context.CallActivityAsync(nameof(Scaler), action); log.LogScalingFunction("Start new Scaling Function with new scaling state."); scalingState.NextPart(CapacityHelpers.CalculateCostOfCapacity(capacity)); context.ContinueAsNew(scalingState); return(scalingState); }