// Optimization process private async void btStart_Clicked(object sender, RoutedEventArgs e) { btStart.Visibility = Visibility.Collapsed; btStop.Visibility = Visibility.Visible; cvPage.Children.Clear(); OptMethod(method); if (uniqueTest) { btRecreat.Visibility = Visibility.Collapsed; tbResults.Text = ""; OptMethod(method); if (routingTest == null) { routingTest = new RoutingTest(this.Optimizer, new RouteTable(pointCount), this.cvPage, this.tbResults); } routingTest.optimizer = this.Optimizer; await Task.Run(() => this.routingTest.Optimize()); } else if (method != 20) { tbResults.Text = "Initial parameters: " + List(InitialParameters) + "\r\n" + "Lower bounds for the parameters: " + List(lbp) + "\r\n" + "Upper bounds for the parameters: " + List(ubp) + "\r\n"; var x = Task.Run(() => (Optimizer.Optimize())); var Results = await x; tbResults.Text = tbResults.Text + "Initial fitness: " + Results.InfoList[InfoTypes.InitialFitness] + "\r\n" + "Final parameters: " + List(Results.OptimizedParameters) + "\r\n" + "Final fitness: " + $"{Results.InfoList[InfoTypes.FinalFitness],10:F6}" + "\r\n" + "Number of generations: " + Results.InfoList[InfoTypes.Generations] + "\r\n" + "Number of fitness evaluations: " + Results.InfoList[InfoTypes.Evaluations] + "\r\n" + "Best affinities in each generation: " + List((ArrayList)Results.InfoList[InfoTypes.Affinities]); } else { tbResults.Text = ""; Result[,] results = new Result[9, 2]; var x = Task.Run(() => (Optimizer.Optimize())); var Results = await x; tbResults.Text += "Final Method: " + ((Type)Results.InfoList[InfoTypes.SelectAlgType]).Name + "\n\n"; foreach (Result item in (ArrayList)Results.InfoList[InfoTypes.SelectAlgInfos]) { if (item.InfoList.ContainsKey(InfoTypes.SelectAlgFitness)) { tbResults.Text += ((int)item.InfoList[InfoTypes.SelectAlgNum] + 1) + ". " + ((Type)item.InfoList[InfoTypes.AlgType]).Name + " fitness: " + $"{item.InfoList[InfoTypes.SelectAlgFitness],10:F30}" + "\n\n"; } } } btStart.Visibility = Visibility.Visible; if (btRecreat.Visibility == Visibility.Collapsed && this.uniqueTest) { btRecreat.Visibility = Visibility.Visible; } btStop.Visibility = Visibility.Collapsed; }
private void SetFitnessFunction(FitnessFunctionDelegate argDelegate) { //uncheck miXXplusYY.IsChecked = false; miTripod.IsChecked = false; miAlpine.IsChecked = false; miGriewank.IsChecked = false; miRosenbrock.IsChecked = false; //set ffd = argDelegate; //preview cvPage.Children.Clear(); if (Preview) { Optimizer = new PreviewDisplayer { LowerParamBounds = new ArrayList { -100, -100 }, UpperParamBounds = new ArrayList { 100, 100 }, FitnessFunction = ffd }; Optimizer.GenerationCreated += this.ShowAntibodies; Optimizer.Optimize(); } }
protected override void CreateNextGeneration() { ArrayList AllAlgInfos = new ArrayList(); Result[] result = new Result[3]; for (int l = 0; l < 3; l++) { Result[,] results = new Result[9, 2]; for (int j = 0; j < 9; j++) { for (int i = 0; i < 2; i++) { switch (i) { case 0: StoppingType = StoppingType.GenerationNumber; break; case 1: StoppingType = StoppingType.EvaluationNumber; break; case 2: StoppingType = StoppingType.PerformanceTreshold; break; } OptMethod(j); Result Results = Optimizer.Optimize(); Results.InfoList.Add(InfoTypes.AlgType, Optimizer.GetType()); Results.InfoList.Add(InfoTypes.SelectAlgNum, l); results[j, i] = Results; AllAlgInfos.Add(Results); } } result[l] = BestCalc(results); } int index = -1; double id = double.MaxValue; for (int i = 0; i < result.Length; i++) { if ((double)result[i].InfoList[InfoTypes.SelectAlgFitness] < id) { id = (double)result[i].InfoList[InfoTypes.SelectAlgFitness]; index = i; } } Info.Add(InfoTypes.SelectAlgType, result[index].InfoList[InfoTypes.AlgType]); Info.Add(InfoTypes.SelectAlgResult, result[index]); Info.Add(InfoTypes.SelectAlgInfos, AllAlgInfos); Stop = true; }
private async void OptimizeButton_Click(object sender, RoutedEventArgs e) { /*if (fuzzySystem.Type == FuzzyType.Sugeno && CheckOutput.IsChecked == true) * { * MessageBox.Show("Output optimization is not valid for Sugeno-type fuzzy systems.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); * return; * }*/ // Disable the optimize button and the optimization parameters OptimizeButton.IsEnabled = false; UseButton.IsEnabled = false; RadioBaseRatio.IsEnabled = false; RadioRefPoint.IsEnabled = false; CheckInput.IsEnabled = false; CheckOutput.IsEnabled = false; // Initialize variables ArrayList initParams = new ArrayList(); ArrayList lbp = new ArrayList(); ArrayList ubp = new ArrayList(); // Set up initial parameters if (CheckInput.IsChecked == true) { foreach (InputOutput input in fuzzySystem.Inputs) { foreach (MembershipFunction MF in input.MFs) { if (RadioRefPoint.IsChecked == true) { initParams.Add((double)(MF.GetReferencePoint())); lbp.Add((double)(input.Range[0])); ubp.Add((double)(input.Range[1])); } if (RadioBaseRatio.IsChecked == true) { initParams.Add((double)(MF.GetTrapBaseRatio())); lbp.Add(0.0); ubp.Add(0.95); } } } } if (CheckOutput.IsChecked == true) { foreach (InputOutput output in fuzzySystem.Outputs) { foreach (MembershipFunction MF in output.MFs) { if (RadioRefPoint.IsChecked == true) { initParams.Add((double)(MF.GetReferencePoint())); lbp.Add((double)(output.Range[0])); ubp.Add((double)(output.Range[1])); } if (RadioBaseRatio.IsChecked == true) { initParams.Add((double)(MF.GetTrapBaseRatio())); lbp.Add(0.0); ubp.Add(0.95); } } } } bool[] ints = new bool[initParams.Count]; // Set up the optimizer object depending on the settings switch (MethodId) { case 0: //Firework Optimizer = new Firework { // Number of particles in the swarm. NumberOfElements = NA, m = m, ymax = double.MaxValue, a = a, b = b, Amax = Amax, mhat = mhat, Slow = false }; break; case 1: //Particle Swarm Optimizer = new ParticleSwarm { // Number of particles in the swarm. NumberOfElements = NA, c0 = c0, // Multiplication factor for the distance to the personal best position. cp = cp, // Multiplication factor for the distance to the global best position. cg = cg, Slow = false }; break; case 2: //Clonal generation if (cgn > NA) { MessageBox.Show("Number of antibodies selected for cloning at the end of each generation greater than the number of antibodies.", "ERROR", MessageBoxButton.OK); OptimizeButton.IsEnabled = true; return; } Optimizer = new ClonalGeneration { // Size of the antibody pool. NumberOfElements = NA, // Number of antibodies selected for cloning. NumberSelectedForCloning = cgn, // Parameter determining the number of clones created for an antibody that was selected for cloning. (0,1] Beta = beta, // Number of antibodies created with random parameters in each new generation. RandomAntibodiesPerGeneration = d, // Mutation coefficient (0,1]. Ro = ro, Slow = false }; break; case 3: Optimizer = new GeneticAlgorithm { // Size of the individual pool. NumberOfElements = NA, // Number of parents in each generation. ParentsInEachGeneration = P, // The probability of mutation. MutationProbability = pm, // The number of crossovers in each generation. CrossoverPerGeneration = crossoverCount, Slow = false }; break; case 4: //Clonal generation if (cgn > NA) { MessageBox.Show("Number of antibodies selected for cloning at the end of each generation greater than the number of antibodies.", "ERROR", MessageBoxButton.OK); OptimizeButton.IsEnabled = true; return; } Optimizer = new ClonalGenerationLocal { // Size of the antibody pool. NumberOfElements = NA, // Number of antibodies selected for cloning. NumberSelectedForCloning = cgn, // Parameter determining the number of clones created for an antibody that was selected for cloning. (0,1] Beta = beta, // Number of antibodies created with random parameters in each new generation. RandomAntibodiesPerGeneration = d, // Mutation coefficient (0,1]. Ro = ro, // Local searches per generation LocalSearchesPerGeneration = cgln, Slow = false }; break; } // Set common parameters Optimizer.InitialParameters = initParams; Optimizer.LowerParamBounds = lbp; Optimizer.UpperParamBounds = ubp; // Bounds are required before setting this value if (MethodId == 4) { ((ClonalGenerationLocal)Optimizer).StepSizeRelative = cglssr; } Optimizer.Integer = ints; Optimizer.FitnessFunction = FitnessFunctionMSE; Optimizer.StoppingNumberOfGenerations = StopGenerationNumber; Optimizer.StoppingNumberOfEvaluations = StopAffinityEvaluation; Optimizer.StoppingFitnessTreshold = StopFitnessTreshold; Optimizer.StoppingType = StopType; // Output string string outstr = "Initial parameters: " + List(initParams) + "\r\n"; // Open progress window and begin the optimization ProgressWindow = new OptimizationProgressWindow(); ProgressWindow.OptWindow = this; ProgressWindow.Show(); if (IoputMfWindows != null) { foreach (MFsPreviewWindow window in IoputMfWindows) { window.Close(); } } IoputMfWindows = new List <MFsPreviewWindow>(); foreach (InputOutput input in fuzzySystem.Inputs) { IoputMfWindows.Add(new MFsPreviewWindow(input)); IoputMfWindows[IoputMfWindows.Count - 1].Show(); } foreach (InputOutput output in fuzzySystem.Outputs) { IoputMfWindows.Add(new MFsPreviewWindow(output)); IoputMfWindows[IoputMfWindows.Count - 1].Show(); } Optimizer.GenerationCreated += OnNewGeneration; // <DELAYER> /*var z = Task.Run(() => (delayer())); * int y = await z;*/ // </DELAYER> var x = Task.Run(() => (Optimizer.Optimize())); var Results = await x; ProgressWindow.Close(); // Add results to output string outstr += "Initial MSE: " + Results.InfoList[InfoTypes.InitialFitness] + "\r\n" + "Final parameters: " + List(Results.OptimizedParameters) + "\r\n" + "Final MSE: " + $"{Results.InfoList[InfoTypes.FinalFitness],10:F6}" + "\r\n" + "Number of generations: " + Results.InfoList[InfoTypes.Generations] + "\r\n" + "Number of fitness evaluations: " + Results.InfoList[InfoTypes.Evaluations] + "\r\n" + "Best affinities in each generation: " + List((ArrayList)Results.InfoList[InfoTypes.Affinities]) + "\r\n" + "Optimization time in milliseconds: " + Results.InfoList[InfoTypes.ExecutionTime]; fuzzySystem = GetModifiedFuzzySystem(Results.OptimizedParameters); FuzzyBox.Text = fuzzySystem.ToString(); // Display results and reenable the optimize button MessageBox.Show(outstr, "Optimization finished", MessageBoxButton.OK); OptimizeButton.IsEnabled = true; UseButton.IsEnabled = true; RadioBaseRatio.IsEnabled = true; RadioRefPoint.IsEnabled = true; CheckInput.IsEnabled = true; CheckOutput.IsEnabled = true; }
public void Optimize() { Result result = null; StreamWriter dok = new StreamWriter(this.optimizer.GetType().ToString() + ".txt"); Application.Current.Dispatcher.Invoke((Action)(() => { foreach (Car car in cars) { tbResults.Text += car.index + ". Car MaxDailyPath: " + car.MaxDailyPath + " MaxPathPoint: " + car.MaxPathPoint + " MaxPathDistance: " + car.MaxPathDistance + "\n"; dok.WriteLine(car.index + ". Car MaxDailyPath: " + car.MaxDailyPath + " MaxPathPoint: " + car.MaxPathPoint + " MaxPathDistance: " + car.MaxPathDistance + "\n"); } dok.WriteLine(); tbResults.Text += "\n"; for (int i = 0; i < this.fullTable.routeTable.Count; i++) { Dictionary <int, User> user = this.fullTable.routeTable[i]; tbResults.Text += i + " |"; dok.Write(i + " |"); foreach (int key in user.Keys) { tbResults.Text += "=>" + key + " : " + $"{user[key].km,10:F2}" + "-" + user[key].dem + "|"; dok.Write("=>" + key + " : " + $"{user[key].km,10:F2}" + "-" + user[key].dem + "|"); } dok.WriteLine(); tbResults.Text += "\n"; } tbResults.Text += "\n"; dok.WriteLine(); }), DispatcherPriority.Send, null); double avgAllFinalFitness = 0.0, avgAllInitFitness = 0.0, avgAllTime = 0.0; for (int i = 0; i < 3; i++) { double avgTime = 0.0, avgFitness = 0.0, initAvgFitness = 0.0; double avgEarchTime = 0.0; foreach (Car car in this.cars) { car.reset(); } double sumAvgEarchTime = 0.0; ArrayList pathLinesTmp = new ArrayList(); pathLinesTmp.AddRange(pathLines); double pathDistance = 0.0; avgTime = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; int g = 0; while (pathLinesTmp.Count > 0) { ArrayList path = (ArrayList)pathLinesTmp[g % pathLinesTmp.Count]; Car car = this.searchCar(path.Count, pathDistance); if (car != null) { avgEarchTime = DateTime.Now.Millisecond; ArrayList pathTmp = new ArrayList(); foreach (int point in path) { pathTmp.Add((double)point); } this.optimizer.InitialParameters = pathTmp; if (optimizer is ParticleSwarm) { ((ParticleSwarm)this.optimizer).reset(); } if (optimizer is ArtificialBeeColony) { ((ArtificialBeeColony)this.optimizer).reset(); } fullTable.pathList = path.Cast <int>().ToList(); this.optimizer.FitnessFunction = fullTable.FitnessFunction; ArrayList finalParam = new ArrayList(); car.Process = Task <Result> .Factory.StartNew(() => optimizer.Optimize()); result = car.Process.Result; double finalFitness = (double)result.InfoList[InfoTypes.FinalFitness]; if (car.MaxPathDistance < finalFitness) { pathDistance = finalFitness; continue; } else { car.MaxPathDistance -= finalFitness; if (car.MaxPathDistance < 0) { car.MaxPathDistance = 0.0; } pathDistance = 0.0; } g++; Application.Current.Dispatcher.Invoke((Action)(() => { tbResults.Text += i + " - " + g + " " + "Car ID: " + car.index + " Initial positions: " + List(fullTable.Encrypt(pathTmp)) + "\r\n" + "Initial fitness: " + $"{result.InfoList[InfoTypes.InitialFitness],10:F5}" + "\r\n" + "Final positions: " + List(fullTable.Encrypt(result.OptimizedParameters)) + "\r\n" + "Final fitness: " + $"{finalFitness,10:F5}" + "\r\n\n"; ShowRoutingAntibodies(fullTable.Encrypt(result.OptimizedParameters)); }), DispatcherPriority.Send, null); dok.Write("\n" + i + " - " + g + " " + "Car ID: " + car.index + " Initial positions: " + List(fullTable.Encrypt(pathTmp)) + "\r\n" + "Initial fitness: " + $"{result.InfoList[InfoTypes.InitialFitness],10:F5}" + "\r\n" + "Final positions: " + List(fullTable.Encrypt(result.OptimizedParameters)) + "\r\n" + "Final fitness: " + $"{finalFitness,10:F5}" + "\r\n\n"); sumAvgEarchTime += avgEarchTime - DateTime.Now.Millisecond; avgFitness += finalFitness; initAvgFitness += (double)result.InfoList[InfoTypes.InitialFitness]; car.Process = null; car.CurrentDailyPath++; } else { Debug.WriteLine("Nincs alkalmas jármű! fent maradt utak száma: " + pathLinesTmp.Count); break; } } avgAllFinalFitness += avgFitness / g; avgAllInitFitness += initAvgFitness / g; sumAvgEarchTime /= pathLines.Count; avgTime = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds - avgTime; avgAllTime += avgTime; } Application.Current.Dispatcher.Invoke((Action)(() => { tbResults.Text += "Initial Avg fitness: " + $"{avgAllInitFitness / 3,10:F5} \r\n"; tbResults.Text += "Final Avg fitness: " + $"{avgAllFinalFitness / 3,10:F5} \r\n"; tbResults.Text += "Final Avg time: " + $"{avgAllTime / 3,10:F3} second \r\n\n"; tbResults.Text += "Final Optimum ratio: " + $"{100 * (1 - (avgAllFinalFitness / 3) / (avgAllInitFitness / 3)),10:F3} % \r\n\n"; }), DispatcherPriority.Send, null); dok.Write("\n\nInitial Avg fitness: " + $"{avgAllInitFitness / 3,10:F5} \r\n"); dok.Write("Final Avg fitness: " + $"{avgAllFinalFitness / 3,10:F5} \r\n"); dok.Write("Final Avg time: " + $"{avgAllTime / 3,10:F3} second \r\n\n"); dok.Write("Final Optimum ratio: " + $"{100 * (1 - (avgAllFinalFitness / 3) / (avgAllInitFitness / 3)),10:F3} % \r\n\n"); dok.Close(); }