public void ShowQualityIndicatorWindow(bool bshow) { qualityIndicatoWindow.ShowWindow = bshow; qualityIndicatoWindow.Refresh(); if (bshow) { qualityIndicatoWindow.UpdateWindow(); } else { _lastQuality = QualityIndicator.Unknown; } }
/// <summary> ///Usage: three choices /// - AbYSS /// - AbYSS problemName /// - AbYSS problemName paretoFrontFile /// </summary> /// <param name="args">Command line arguments.</param> public static void Main(string[] args) { Problem problem; // The problem to solve Algorithm algorithm; // The algorithm to use Operator crossover; // Crossover operator Operator mutation; // Mutation operator Operator improvement; // Operator for improvement Dictionary <string, object> parameters; // Operator parameters QualityIndicator indicators; // Object to get quality indicators // Logger object and file to store log messages var logger = Logger.Log; var appenders = logger.Logger.Repository.GetAppenders(); var fileAppender = appenders[0] as log4net.Appender.FileAppender; fileAppender.File = "AbYSS.log"; fileAppender.ActivateOptions(); indicators = null; if (args.Length == 1) { object[] param = { "Real" }; problem = ProblemFactory.GetProblem(args[0], param); } else if (args.Length == 2) { object[] param = { "Real" }; problem = ProblemFactory.GetProblem(args[0], param); indicators = new QualityIndicator(problem, args[1]); } else { // Default problem problem = new Kursawe("Real", 3); //problem = new Kursawe("BinaryReal", 3); //problem = new Water("Real"); //problem = new ZDT4("ArrayReal", 10); //problem = new ConstrEx("Real"); //problem = new DTLZ1("Real"); //problem = new OKA2("Real") ; } // STEP 2. Select the algorithm (AbYSS) algorithm = new JMetalCSharp.Metaheuristics.AbYSS.AbYSS(problem); // STEP 3. Set the input parameters required by the metaheuristic algorithm.SetInputParameter("populationSize", 20); algorithm.SetInputParameter("refSet1Size", 10); algorithm.SetInputParameter("refSet2Size", 10); algorithm.SetInputParameter("archiveSize", 100); algorithm.SetInputParameter("maxEvaluations", 25000); // STEP 4. Specify and configure the crossover operator, used in the // solution combination method of the scatter search parameters = new Dictionary <string, object>(); parameters.Add("probability", 0.9); parameters.Add("distributionIndex", 20.0); crossover = CrossoverFactory.GetCrossoverOperator("SBXCrossover", parameters); // STEP 5. Specify and configure the improvement method. We use by default // a polynomial mutation in this method. parameters = new Dictionary <string, object>(); parameters.Add("probability", 1.0 / problem.NumberOfVariables); parameters.Add("distributionIndex", 20.0); mutation = MutationFactory.GetMutationOperator("PolynomialMutation", parameters); parameters = new Dictionary <string, object>(); parameters.Add("improvementRounds", 1); parameters.Add("problem", problem); parameters.Add("mutation", mutation); improvement = new MutationLocalSearch(parameters); // STEP 6. Add the operators to the algorithm algorithm.AddOperator("crossover", crossover); algorithm.AddOperator("improvement", improvement); long initTime = Environment.TickCount; // STEP 7. Run the algorithm SolutionSet population = algorithm.Execute(); long estimatedTime = Environment.TickCount - initTime; // STEP 8. Print the results logger.Info("Total execution time: " + estimatedTime + "ms"); logger.Info("Variables values have been writen to file VAR"); population.PrintVariablesToFile("VAR"); logger.Info("Objectives values have been writen to file FUN"); population.PrintObjectivesToFile("FUN"); Console.WriteLine("Total execution time: " + estimatedTime + "ms"); Console.ReadLine(); if (indicators != null) { logger.Info("Quality indicators"); logger.Info("Hypervolume: " + indicators.GetHypervolume(population)); logger.Info("GD : " + indicators.GetGD(population)); logger.Info("IGD : " + indicators.GetIGD(population)); logger.Info("Spread : " + indicators.GetSpread(population)); logger.Info("Epsilon : " + indicators.GetEpsilon(population)); } }
/// <summary> /// Usage: three options /// - SPEA2 /// - SPEA2 problemName /// - SPEA2 problemName ParetoFrontFile /// </summary> /// <param name="args">Command line arguments. The first (optional) argument specifies the problem to solve.</param> public static void Main(string[] args) { Problem problem; // The problem to solve Algorithm algorithm; // The algorithm to use Operator crossover; // Crossover operator Operator mutation; // Mutation operator Operator selection; // Selection operator QualityIndicator indicators; // Object to get quality indicators Dictionary <string, object> parameters; // Operator parameters // Logger object and file to store log messages var logger = Logger.Log; var appenders = logger.Logger.Repository.GetAppenders(); var fileAppender = appenders[0] as log4net.Appender.FileAppender; fileAppender.File = "SPEA2.log"; fileAppender.ActivateOptions(); indicators = null; if (args.Length == 1) { object[] param = { "Real" }; problem = ProblemFactory.GetProblem(args[0], param); } else if (args.Length == 2) { object[] param = { "Real" }; problem = ProblemFactory.GetProblem(args[0], param); indicators = new QualityIndicator(problem, args[1]); } else { // Default problem problem = new Kursawe("Real", 3); //problem = new Water("Real"); //problem = new ZDT1("ArrayReal", 1000); //problem = new ZDT4("BinaryReal"); //problem = new WFG1("Real"); //problem = new DTLZ1("Real"); //problem = new OKA2("Real") ; } algorithm = new JMetalCSharp.Metaheuristics.SPEA2.SPEA2(problem); // Algorithm parameters algorithm.SetInputParameter("populationSize", 100); algorithm.SetInputParameter("archiveSize", 100); algorithm.SetInputParameter("maxEvaluations", 25000); // Mutation and Crossover for Real codification parameters = new Dictionary <string, object>(); parameters.Add("probability", 0.9); parameters.Add("distributionIndex", 20.0); crossover = CrossoverFactory.GetCrossoverOperator("SBXCrossover", parameters); parameters = new Dictionary <string, object>(); parameters.Add("probability", 1.0 / problem.NumberOfVariables); parameters.Add("distributionIndex", 20.0); mutation = MutationFactory.GetMutationOperator("PolynomialMutation", parameters); // Selection operator parameters = null; selection = SelectionFactory.GetSelectionOperator("BinaryTournament", parameters); // Add the operators to the algorithm algorithm.AddOperator("crossover", crossover); algorithm.AddOperator("mutation", mutation); algorithm.AddOperator("selection", selection); // Execute the algorithm long initTime = Environment.TickCount; SolutionSet population = algorithm.Execute(); long estimatedTime = Environment.TickCount - initTime; // Result messages logger.Info("Total execution time: " + estimatedTime + "ms"); logger.Info("Objectives values have been writen to file FUN"); population.PrintObjectivesToFile("FUN"); logger.Info("Variables values have been writen to file VAR"); population.PrintVariablesToFile("VAR"); if (indicators != null) { logger.Info("Quality indicators"); logger.Info("Hypervolume: " + indicators.GetHypervolume(population)); logger.Info("GD : " + indicators.GetGD(population)); logger.Info("IGD : " + indicators.GetIGD(population)); logger.Info("Spread : " + indicators.GetSpread(population)); logger.Info("Epsilon : " + indicators.GetEpsilon(population)); } Console.WriteLine("Total execution time: " + estimatedTime + "ms"); Console.ReadLine(); }
/// <summary> /// Runs the NSGA-II algorithm. /// </summary> /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns> public override SolutionSet Execute() { // !!!! NEEDED PARAMETES !!! start //J* Parameters int populationSize = -1; // J* store population size int maxEvaluations = -1; // J* store number of max Evaluations int evaluations; // J* number of current evaluations // J* Objects needed to illustrate the use of quality indicators inside the algorithms QualityIndicator indicators = null; // QualityIndicator object int requiredEvaluations; // Use in the example of use of the // indicators object (see below) // J* populations needed to implement NSGA-II SolutionSet population; //J* Current population SolutionSet offspringPopulation; //J* offspring population SolutionSet union; //J* population resultant from current and offpring population //J* Genetic Operators Operator mutationOperator; Operator crossoverOperator; Operator selectionOperator; //J* Used to evaluate crowding distance Distance distance = new Distance(); //J* !!!! NEEDED PARAMETES !!! end //J* !!! INITIALIZING PARAMETERS - start !!! //Read the parameters JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); //J* required JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); //J* required JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators); //J* optional //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; requiredEvaluations = 0; //Read the operators mutationOperator = Operators["mutation"]; crossoverOperator = Operators["crossover"]; selectionOperator = Operators["selection"]; //J* !!! INITIALIZING PARAMETERS - end !!! //J* !!! Creating first population !!! JMetalRandom.SetRandom(comp.MyRand); comp.LogAddMessage("Random seed = " + comp.Seed); // Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(Problem); Problem.Evaluate(newSolution); Problem.EvaluateConstraints(newSolution); evaluations++; population.Add(newSolution); } // Generations while (evaluations < maxEvaluations) { // Create the offSpring solutionSet offspringPopulation = new SolutionSet(populationSize); Solution[] parents = new Solution[2]; for (int i = 0; i < (populationSize / 2); i++) { if (evaluations < maxEvaluations) { //obtain parents parents[0] = (Solution)selectionOperator.Execute(population); parents[1] = (Solution)selectionOperator.Execute(population); Solution[] offSpring = (Solution[])crossoverOperator.Execute(parents); mutationOperator.Execute(offSpring[0]); mutationOperator.Execute(offSpring[1]); Problem.Evaluate(offSpring[0]); Problem.EvaluateConstraints(offSpring[0]); Problem.Evaluate(offSpring[1]); Problem.EvaluateConstraints(offSpring[1]); offspringPopulation.Add(offSpring[0]); offspringPopulation.Add(offSpring[1]); evaluations += 2; } } // Create the solutionSet union of solutionSet and offSpring union = ((SolutionSet)population).Union(offspringPopulation); // Ranking the union Ranking ranking = new Ranking(union); int remain = populationSize; int index = 0; SolutionSet front = null; population.Clear(); // Obtain the next front front = ranking.GetSubfront(index); while ((remain > 0) && (remain >= front.Size())) { //Assign crowding distance to individuals distance.CrowdingDistanceAssignment(front, Problem.NumberOfObjectives); //Add the individuals of this front for (int k = 0; k < front.Size(); k++) { population.Add(front.Get(k)); } //Decrement remain remain = remain - front.Size(); //Obtain the next front index++; if (remain > 0) { front = ranking.GetSubfront(index); } } // Remain is less than front(index).size, insert only the best one if (remain > 0) { // front contains individuals to insert distance.CrowdingDistanceAssignment(front, Problem.NumberOfObjectives); front.Sort(new CrowdingComparator()); for (int k = 0; k < remain; k++) { population.Add(front.Get(k)); } remain = 0; } // This piece of code shows how to use the indicator object into the code // of NSGA-II. In particular, it finds the number of evaluations required // by the algorithm to obtain a Pareto front with a hypervolume higher // than the hypervolume of the true Pareto front. if ((indicators != null) && (requiredEvaluations == 0)) { double HV = indicators.GetHypervolume(population); if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } } // Return as output parameter the required evaluations SetOutputParameter("evaluations", requiredEvaluations); comp.LogAddMessage("Evaluations = " + evaluations); // Return the first non-dominated front Ranking rank = new Ranking(population); Result = rank.GetSubfront(0); return(Result); }
public void GetIndicatorForScore_WithCustomValues(int score, int?passScore, int?warnScore, QualityIndicator expectedResult) { // Arrange this.configurationRepository.Setup(r => r.ReadValue <int>(ConfigurationKeys.PassScore)).Returns(passScore); this.configurationRepository.Setup(r => r.ReadValue <int>(ConfigurationKeys.WarnScore)).Returns(warnScore); //Act var result = this.qualityIndicatorService.Object.GetIndicatorForScore(score); // Assert Assert.That(result, Is.EqualTo(expectedResult)); }
public SolutionSet Mix() { QualityIndicator indicators = new QualityIndicator(problem, fileRead.Qi); // QualityIndicator object int requiredEvaluations = 0; // Use in the example of use of the // indicators object (see below) evaluations = 0; iteration = 0; populationSize = int.Parse(fileRead.Ps); iterationsNumber = int.Parse(fileRead.Itn); dataDirectory = "Data/Parameters/Weight"; int allR = int.Parse(fileRead.DERa) + int.Parse(fileRead.SBXRa) + int.Parse(fileRead.ACORa); double ACOR = (double)int.Parse(fileRead.ACORa) / allR; double DER = (double)int.Parse(fileRead.DERa) / allR; Logger.Log.Info("POPSIZE: " + populationSize); Console.WriteLine("POPSIZE: " + populationSize); population = new SolutionSet(populationSize); indArray = new Solution[problem.NumberOfObjectives]; t = int.Parse(fileRead.T); nr = int.Parse(fileRead.Nr); delta = double.Parse(fileRead.Delta); gamma = double.Parse(fileRead.Gamma); neighborhood = new int[populationSize][]; for (int i = 0; i < populationSize; i++) { neighborhood[i] = new int[t]; } z = new double[problem.NumberOfObjectives]; //znad = new double[Problem.NumberOfObjectives]; lambda = new double[populationSize][]; for (int i = 0; i < populationSize; i++) { lambda[i] = new double[problem.NumberOfObjectives]; } /**/ string dir = "Result/" + fileRead.Al; if (fileRead.DERa != "0") { dir = dir + "_DifferentialEvolutionCrossover"; } if (fileRead.SBXRa != "0") { dir = dir + "_SBXCrossover"; } if (fileRead.ACORa != "0") { dir = dir + "_ACOR"; } dir = dir + "/" + fileRead.Pb + "_" + fileRead.St + "/Record/DE(" + int.Parse(fileRead.DERa) + ")+SBX(" + int.Parse(fileRead.SBXRa) + ")+ACOR(" + int.Parse(fileRead.ACORa) + ")_NoMutation/nr=" + fileRead.Nr + "/ACOR+SBX"; if (Directory.Exists(dir)) { Console.WriteLine("The directory {0} already exists.", dir); } else { Directory.CreateDirectory(dir); Console.WriteLine("The directory {0} was created.", dir); } //Step 1. Initialization //Step 1.1 Compute euclidean distances between weight vectors and find T InitUniformWeight(); InitNeighborhood(); //Step 1.2 Initialize population InitPoputalion(); //Step 1.3 Initizlize z InitIdealPoint(); //Step 2 Update for (int a = 1; a <= iterationsNumber; a++) { int[] permutation = new int[populationSize]; JMetalCSharp.Metaheuristics.MOEAD.Utils.RandomPermutation(permutation, populationSize); Solution[] parents = new Solution[2]; int t = 0; if (a <= (ACOR)*iterationsNumber) { //ACOR for (int i = 0; i < populationSize; i++) { int n = permutation[i]; // or int n = i; int type; double rnd = JMetalRandom.NextDouble(); // STEP 2.1. ACOR selection based on probability if (rnd < gamma) // if (rnd < realb) { type = 1; // minmum //parents[0] = population.Get(ACOrSelection2(n, type, pro_T)); } else { type = 2; // whole neighborhood probability //parents[0] = population.Get(ACOrSelection2(n, type, pro_A)); } GetStdDev(neighborhood); //GetStdDev1(neighborhood, type); //List<int> p = new List<int>(); //MatingSelection(p, n, 1, type); // STEP 2.2. Reproduction Solution child; parents[0] = population.Get(ACOrSelection(n, type)); parents[1] = population.Get(n); //parents[0] = population.Get(p[0]); // Apply ACOR crossover child = (Solution)crossover[2].Execute(parents); child.NumberofReplace = t; // Apply mutation // mutation.Execute(child); // Evaluation problem.Evaluate(child); evaluations++; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ UpdateReference(child); // STEP 2.5. Update of solutions t = UpdateProblemWithReplace(child, n, 1); } } else if (a >= (1 - DER) * iterationsNumber) { //DE for (int i = 0; i < populationSize; i++) { int n = permutation[i]; // or int n = i; int type; double rnd = JMetalRandom.NextDouble(); // STEP 2.1. Mating selection based on probability if (rnd < delta) // if (rnd < realb) { type = 1; // neighborhood } else { type = 2; // whole population } List <int> p = new List <int>(); MatingSelection(p, n, 2, type); // STEP 2.2. Reproduction Solution child; Solution[] parent = new Solution[3]; parent[0] = population.Get(p[0]); parent[1] = population.Get(p[1]); parent[2] = population.Get(n); // Apply DE crossover child = (Solution)crossover[0].Execute(new object[] { population.Get(n), parent }); // Apply mutation mutation.Execute(child); // Evaluation problem.Evaluate(child); evaluations++; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ UpdateReference(child); // STEP 2.5. Update of solutions UpdateProblem(child, n, type); } } else { //SBX //Create the offSpring solutionSet SolutionSet offspringPopulation = new SolutionSet(populationSize); for (int i = 0; i < (populationSize / 2); i++) { int n = permutation[i]; // or int n = i; int type; double rnd = JMetalRandom.NextDouble(); // STEP 2.1. Mating selection based on probability if (rnd < delta) // if (rnd < realb) { type = 1; // neighborhood } else { type = 2; // whole population } List <int> p = new List <int>(); MatingSelection(p, n, 2, type); parents[0] = population.Get(p[0]); parents[1] = population.Get(p[1]); //obtain parents Solution[] offSpring = (Solution[])crossover[1].Execute(parents); //Solution child; mutation.Execute(offSpring[0]); mutation.Execute(offSpring[1]); /*if(rnd < 0.5) * { * child = offSpring[0]; * } * else * { * child = offSpring[1]; * }*/ problem.Evaluate(offSpring[0]); problem.Evaluate(offSpring[1]); problem.EvaluateConstraints(offSpring[0]); problem.EvaluateConstraints(offSpring[1]); offspringPopulation.Add(offSpring[0]); offspringPopulation.Add(offSpring[1]); evaluations += 2; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ UpdateReference(offSpring[0]); UpdateReference(offSpring[1]); // STEP 2.5. Update of solutions UpdateProblem(offSpring[0], n, type); UpdateProblem(offSpring[1], n, type); }
public SolutionSet Mix() { QualityIndicator indicators = new QualityIndicator(problem, fileRead.Qi); // QualityIndicator object int requiredEvaluations = 0; // Use in the example of use of the // indicators object (see below) evaluations = 0; iteration = 0; populationSize = int.Parse(fileRead.Ps); iterationsNumber = int.Parse(fileRead.Itn); dataDirectory = "Data/Parameters/Weight"; Logger.Log.Info("POPSIZE: " + populationSize); Console.WriteLine("POPSIZE: " + populationSize); population = new SolutionSet(populationSize); indArray = new Solution[problem.NumberOfObjectives]; t = int.Parse(fileRead.T); nr = int.Parse(fileRead.Nr); delta = double.Parse(fileRead.Delta); gamma = double.Parse(fileRead.Gamma); neighborhood = new int[populationSize][]; for (int i = 0; i < populationSize; i++) { neighborhood[i] = new int[t]; } z = new double[problem.NumberOfObjectives]; //znad = new double[Problem.NumberOfObjectives]; lambda = new double[populationSize][]; for (int i = 0; i < populationSize; i++) { lambda[i] = new double[problem.NumberOfObjectives]; } /*string dir = "Result/" + fileRead.Al + "_" + fileRead.Co + "_" + fileRead.Co2 + "/" + fileRead.Pb + "_" + fileRead.St + "/Record/SBX(" + double.Parse(fileRead.Ra).ToString("#0.00") + ")+ACOR(" + (1-double.Parse(fileRead.Ra)).ToString("#0.00") + ")"; * if (Directory.Exists(dir)) * { * Console.WriteLine("The directory {0} already exists.", dir); * } * else * { * Directory.CreateDirectory(dir); * Console.WriteLine("The directory {0} was created.", dir); * }*/ //Step 1. Initialization //Step 1.1 Compute euclidean distances between weight vectors and find T InitUniformWeight(); InitNeighborhood(); //Step 1.2 Initialize population InitPoputalion(); //Step 1.3 Initizlize z InitIdealPoint(); //Step 2 Update for (int a = 0; a < iterationsNumber; a++) { int[] permutation = new int[populationSize]; JMetalCSharp.Metaheuristics.MOEAD.Utils.RandomPermutation(permutation, populationSize); Solution[] parents = new Solution[2]; int t = 0; if (a >= double.Parse(fileRead.Ra) * iterationsNumber) { for (int i = 0; i < populationSize; i++) { int n = permutation[i]; // or int n = i; int type; double rnd = JMetalRandom.NextDouble(); // STEP 2.1. ACOR selection based on probability if (rnd < gamma) // if (rnd < realb) { type = 1; // minmum //parents[0] = population.Get(ACOrSelection2(n, type, pro_T)); } else { type = 2; // whole neighborhood probability //parents[0] = population.Get(ACOrSelection2(n, type, pro_A)); } GetStdDev(neighborhood); //GetStdDev1(neighborhood, type); //List<int> p = new List<int>(); //MatingSelection(p, n, 1, type); // STEP 2.2. Reproduction Solution child; parents[0] = population.Get(ACOrSelection(n, type)); parents[1] = population.Get(n); //parents[0] = population.Get(p[0]); // Apply ACOR crossover child = (Solution)crossover2.Execute(parents); child.NumberofReplace = t; // // Apply mutation mutation.Execute(child); // Evaluation problem.Evaluate(child); evaluations++; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ UpdateReference(child); // STEP 2.5. Update of solutions t = UpdateProblemWithReplace(child, n, 1); } } else { // Create the offSpring solutionSet SolutionSet offspringPopulation = new SolutionSet(populationSize); for (int i = 0; i < (populationSize / 2); i++) { int n = permutation[i]; // or int n = i; int type; double rnd = JMetalRandom.NextDouble(); // STEP 2.1. Mating selection based on probability if (rnd < delta) // if (rnd < realb) { type = 1; // neighborhood } else { type = 2; // whole population } List <int> p = new List <int>(); MatingSelection(p, n, 2, type); parents[0] = population.Get(p[0]); parents[1] = population.Get(p[1]); //obtain parents Solution[] offSpring = (Solution[])crossover1.Execute(parents); //Solution child; mutation.Execute(offSpring[0]); mutation.Execute(offSpring[1]); /*if(rnd < 0.5) * { * child = offSpring[0]; * } * else * { * child = offSpring[1]; * }*/ problem.Evaluate(offSpring[0]); problem.Evaluate(offSpring[1]); problem.EvaluateConstraints(offSpring[0]); problem.EvaluateConstraints(offSpring[1]); offspringPopulation.Add(offSpring[0]); offspringPopulation.Add(offSpring[1]); evaluations += 2; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ UpdateReference(offSpring[0]); UpdateReference(offSpring[1]); // STEP 2.5. Update of solutions UpdateProblem(offSpring[0], n, type); UpdateProblem(offSpring[1], n, type); } //for (int i = 0; i < populationSize; i++) //{ // int n = permutation[i]; // or int n = i; // int type; // double rnd = JMetalRandom.NextDouble(); // // STEP 2.1. Mating selection based on probability // if (rnd < delta) // if (rnd < realb) // { // type = 1; // neighborhood // } // else // { // type = 2; // whole population // } // List<int> p = new List<int>(); // MatingSelection(p, n, 2, type); // // STEP 2.2. Reproduction // Solution child; // Solution[] parent = new Solution[3]; // parent[0] = population.Get(p[0]); // parent[1] = population.Get(p[1]); // parent[2] = population.Get(n); // // Apply DE crossover // child = (Solution)crossover1.Execute(new object[] { population.Get(n), parent }); // // Apply mutation // mutation.Execute(child); // // Evaluation // problem.Evaluate(child); // evaluations++; // // STEP 2.3. Repair. Not necessary // // STEP 2.4. Update z_ // UpdateReference(child); // // STEP 2.5. Update of solutions // UpdateProblem(child, n, type); //} } /*string filevar = dir + "/VAR" + iteration; * string filefun = dir + "/FUN" + iteration; * population.PrintVariablesToFile(filevar); * population.PrintObjectivesToFile(filefun);*/ iteration++; if ((indicators != null) && (requiredEvaluations == 0)) { double HV = indicators.GetHypervolume(population); if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } } Logger.Log.Info("ITERATION: " + iteration); Console.WriteLine("ITERATION: " + iteration); SolutionSet Result = population; //return population; // Return the first non-dominated front Ranking rank = new Ranking(population); //SolutionSet Result = rank.GetSubfront(0); return(Result); }
private void Button_Click_2(object sender, RoutedEventArgs e) { FileRead read = new FileRead(); read.fileread(); Problem problem = read.GetProblem(); Algorithm algorithm = read.GetAlgorithm(); QualityIndicator indicators = new QualityIndicator(problem, read.Qi); NewAlgorithmTest test = new NewAlgorithmTest(); for (int i = 1; i <= int.Parse(read.Rt); i++) { // Logger object and file to store log messages var logger = Logger.Log; var appenders = logger.Logger.Repository.GetAppenders(); var fileAppender = appenders[0] as log4net.Appender.FileAppender; fileAppender.File = read.DirPath + "/" + read.Al + i + ".log"; fileAppender.ActivateOptions(); string filevar = read.DirPath + "/VAR" + i; string filefun = read.DirPath + "/FUN" + i; FileStream file = new FileStream(read.DirPath + "/MOEADnew" + i + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter newlogger = new StreamWriter(file); // Execute the Algorithm long initTime = Environment.TickCount; SolutionSet population = test.Mix(); long estimatedTime = Environment.TickCount - initTime; // Result messages logger.Info("Total execution time: " + estimatedTime + "ms"); logger.Info("Variables values have been writen to file " + filevar); newlogger.WriteLine("Total execution time: " + estimatedTime + "ms" + "\n"); newlogger.WriteLine("Variables values have been writen to file " + filevar + "\n"); population.PrintVariablesToFile(filevar); logger.Info("Objectives values have been writen to file " + filefun); population.PrintObjectivesToFile(filefun); Console.WriteLine("Time: " + estimatedTime); newlogger.WriteLine("Time: " + estimatedTime + "\n"); Console.ReadLine(); if (indicators != null) { logger.Info("Quality indicators"); logger.Info("Hypervolume: " + indicators.GetHypervolume(population)); logger.Info("GD : " + indicators.GetGD(population)); logger.Info("IGD : " + indicators.GetIGD(population)); logger.Info("Spread : " + indicators.GetSpread(population)); logger.Info("Epsilon : " + indicators.GetEpsilon(population)); newlogger.WriteLine("Quality indicators"); newlogger.WriteLine("Hypervolume: " + indicators.GetHypervolume(population).ToString("F18") + "\n"); newlogger.WriteLine("GD : " + indicators.GetGD(population).ToString("F18") + "\n"); newlogger.WriteLine("IGD : " + indicators.GetIGD(population).ToString("F18") + "\n"); newlogger.WriteLine("Spread : " + indicators.GetSpread(population).ToString("F18") + "\n"); newlogger.WriteLine("Epsilon : " + indicators.GetEpsilon(population).ToString("F18") + "\n"); int evaluations = test.GetEvaluations(); logger.Info("Speed : " + evaluations + " evaluations"); newlogger.WriteLine("Speed : " + evaluations + " evaluations" + "\n"); } newlogger.Close(); file.Close(); } }
public void MyAlgorithm() { Problem problem = null; // The problem to solve Algorithm algorithm = null; // The algorithm to use Operator crossover = null; // Crossover operator Operator mutation = null; // Mutation operator Operator selection = null; // Selection operator QualityIndicator indicators; // Object to get quality indicators FileRead fileRead = new FileRead(); fileRead.fileread(); problem = fileRead.GetProblem(); algorithm = fileRead.GetAlgorithm(); //crossover = fileRead.GetCrossover(); mutation = fileRead.GetMutation(); selection = fileRead.GetSelection(); // Quality Indicators Operator //indicators = new QualityIndicator(problem, "DTLZ1.3D.pf"); indicators = new QualityIndicator(problem, fileRead.Qi); //indicators = new QualityIndicator(problem, "LZ09_F1.pf"); // Add the operators to the algorithm algorithm.AddOperator("crossover", crossover); algorithm.AddOperator("mutation", mutation); algorithm.AddOperator("selection", selection); // Add the indicator object to the algorithm algorithm.SetInputParameter("indicators", indicators); for (int i = 1; i <= int.Parse(fileRead.Rt); i++) { // Logger object and file to store log messages var logger = Logger.Log; var appenders = logger.Logger.Repository.GetAppenders(); var fileAppender = appenders[0] as log4net.Appender.FileAppender; fileAppender.File = fileRead.DirPath + "/" + fileRead.Al + i + ".log"; fileAppender.ActivateOptions(); string filevar = fileRead.DirPath + "/VAR" + i; string filefun = fileRead.DirPath + "/FUN" + i; FileStream file = new FileStream(fileRead.DirPath + "/" + fileRead.Al + "new" + i + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter newlogger = new StreamWriter(file); // Execute the Algorithm long initTime = Environment.TickCount; SolutionSet population = algorithm.Execute(); long estimatedTime = Environment.TickCount - initTime; // Result messages logger.Info("Total execution time: " + estimatedTime + "ms"); logger.Info("Variables values have been writen to file " + filevar); newlogger.WriteLine("Total execution time: " + estimatedTime + "ms" + "\n"); newlogger.WriteLine("Variables values have been writen to file " + filevar + "\n"); population.PrintVariablesToFile(filevar); logger.Info("Objectives values have been writen to file " + filefun); population.PrintObjectivesToFile(filefun); Console.WriteLine("Time: " + estimatedTime); newlogger.WriteLine("Time: " + estimatedTime + "\n"); Console.ReadLine(); if (indicators != null) { logger.Info("Quality indicators"); logger.Info("Hypervolume: " + indicators.GetHypervolume(population)); logger.Info("GD : " + indicators.GetGD(population)); logger.Info("IGD : " + indicators.GetIGD(population)); logger.Info("Spread : " + indicators.GetSpread(population)); logger.Info("Epsilon : " + indicators.GetEpsilon(population)); newlogger.WriteLine("Quality indicators"); newlogger.WriteLine("Hypervolume: " + indicators.GetHypervolume(population).ToString("F18") + "\n"); newlogger.WriteLine("GD : " + indicators.GetGD(population).ToString("F18") + "\n"); newlogger.WriteLine("IGD : " + indicators.GetIGD(population).ToString("F18") + "\n"); newlogger.WriteLine("Spread : " + indicators.GetSpread(population).ToString("F18") + "\n"); newlogger.WriteLine("Epsilon : " + indicators.GetEpsilon(population).ToString("F18") + "\n"); int evaluations = (int)algorithm.GetOutputParameter("evaluations"); logger.Info("Speed : " + evaluations + " evaluations"); newlogger.WriteLine("Speed : " + evaluations + " evaluations" + "\n"); } newlogger.Close(); file.Close(); algorithm.AddOperator("mutation", mutation); } }
/// <summary> /// Usage: three options /// - NSGAIIAdaptive /// - NSGAIIAdaptive problemName /// - NSGAIIAdaptive problemName paretoFrontFile /// </summary> /// <param name="args">Command line arguments.</param> public static void Main(string[] args) { Problem problem; // The problem to solve Algorithm algorithm; // The algorithm to use Operator selection; // Selection operator Dictionary <string, object> parameters; // Operator parameters QualityIndicator indicators; // Object to get quality indicators // Logger object and file to store log messages var logger = Logger.Log; var appenders = logger.Logger.Repository.GetAppenders(); var fileAppender = appenders[0] as log4net.Appender.FileAppender; fileAppender.File = "NSGAIIAdaptive.log"; fileAppender.ActivateOptions(); indicators = null; if (args.Length == 1) { object[] param = { "Real" }; problem = ProblemFactory.GetProblem(args[0], param); } else if (args.Length == 2) { object[] param = { "Real" }; problem = ProblemFactory.GetProblem(args[0], param); indicators = new QualityIndicator(problem, args[1]); } else { // Default problem problem = new Kursawe("Real", 3); //problem = new Kursawe("BinaryReal", 3); //problem = new Water("Real"); //problem = new ZDT1("ArrayReal", 100); //problem = new ConstrEx("Real"); //problem = new DTLZ1("Real"); //problem = new OKA2("Real") ; } problem = new LZ09_F3("Real"); algorithm = new JMetalCSharp.Metaheuristics.NSGAII.NSGAIIAdaptive(problem); //algorithm = new ssNSGAIIAdaptive(problem); // Algorithm parameters algorithm.SetInputParameter("populationSize", 100); algorithm.SetInputParameter("maxEvaluations", 150000); // Selection Operator parameters = null; selection = SelectionFactory.GetSelectionOperator("BinaryTournament2", parameters); // Add the operators to the algorithm algorithm.AddOperator("selection", selection); // Add the indicator object to the algorithm algorithm.SetInputParameter("indicators", indicators); Offspring[] getOffspring = new Offspring[3]; double CR, F; CR = 1.0; F = 0.5; getOffspring[0] = new DifferentialEvolutionOffspring(CR, F); getOffspring[1] = new SBXCrossoverOffspring(1.0, 20); //getOffspring[1] = new BLXAlphaCrossoverOffspring(1.0, 0.5); getOffspring[2] = new PolynomialMutationOffspring(1.0 / problem.NumberOfVariables, 20); //getOffspring[2] = new NonUniformMutationOffspring(1.0/problem.getNumberOfVariables(), 0.5, 150000); algorithm.SetInputParameter("offspringsCreators", getOffspring); // Execute the Algorithm long initTime = Environment.TickCount; SolutionSet population = algorithm.Execute(); long estimatedTime = Environment.TickCount - initTime; // Result messages logger.Info("Total execution time: " + estimatedTime + "ms"); logger.Info("Variables values have been writen to file VAR"); population.PrintVariablesToFile("VAR"); logger.Info("Objectives values have been writen to file FUN"); population.PrintObjectivesToFile("FUN"); Console.WriteLine("Time: " + estimatedTime); Console.ReadLine(); if (indicators != null) { logger.Info("Quality indicators"); logger.Info("Hypervolume: " + indicators.GetHypervolume(population)); logger.Info("GD : " + indicators.GetGD(population)); logger.Info("IGD : " + indicators.GetIGD(population)); logger.Info("Spread : " + indicators.GetSpread(population)); logger.Info("Epsilon : " + indicators.GetEpsilon(population)); } }
/// <summary> /// Runs the NSGA-II algorithm. /// </summary> /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns> public override SolutionSet Execute() { int populationSize = -1; int maxEvaluations = -1; int evaluations; QualityIndicator indicators = null; // QualityIndicator object int requiredEvaluations; // Use in the example of use of the // indicators object (see below) SolutionSet population; SolutionSet offspringPopulation; SolutionSet union; Operator mutationOperator; Operator crossoverOperator; Operator selectionOperator; Distance distance = new Distance(); //Read the parameters JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators); //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; requiredEvaluations = 0; //Read the operators mutationOperator = Operators["mutation"]; crossoverOperator = Operators["crossover"]; selectionOperator = Operators["selection"]; var plotCounter = 0; var plotModulo = 4; Random random = new Random(2); JMetalRandom.SetRandom(random); // Create the initial solutionSet IntergenSolution newSolution; for (int i = 0; i < populationSize; i++) { //var test = (IntergenProblem) Problem; newSolution = new IntergenSolution((IntergenProblem)Problem); Problem.Evaluate(newSolution); Problem.EvaluateConstraints(newSolution); evaluations++; population.Add(newSolution); } // Generations while (evaluations < maxEvaluations) { // Create the offSpring solutionSet offspringPopulation = new SolutionSet(populationSize); IntergenSolution[] parents = new IntergenSolution[2]; for (int i = 0; i < (populationSize / 2); i++) { if (evaluations < maxEvaluations) { //obtain parents parents[0] = (IntergenSolution)selectionOperator.Execute(population); parents[1] = (IntergenSolution)selectionOperator.Execute(population); IntergenSolution[] offSpring = (IntergenSolution[])crossoverOperator.Execute(parents); mutationOperator.Execute(offSpring[0]); mutationOperator.Execute(offSpring[1]); Problem.Evaluate(offSpring[0]); Problem.EvaluateConstraints(offSpring[0]); Problem.Evaluate(offSpring[1]); Problem.EvaluateConstraints(offSpring[1]); offspringPopulation.Add(offSpring[0]); offspringPopulation.Add(offSpring[1]); evaluations += 2; } } // Create the solutionSet union of solutionSet and offSpring union = ((SolutionSet)population).Union(offspringPopulation); // Ranking the union Ranking ranking = new Ranking(union); int remain = populationSize; int index = 0; SolutionSet front = null; population.Clear(); // Obtain the next front front = ranking.GetSubfront(index); while ((remain > 0) && (remain >= front.Size())) { //Assign crowding distance to individuals distance.CrowdingDistanceAssignment(front, Problem.NumberOfObjectives); //Add the individuals of this front for (int k = 0; k < front.Size(); k++) { population.Add(front.Get(k)); } //Decrement remain remain = remain - front.Size(); //Obtain the next front index++; if (remain > 0) { front = ranking.GetSubfront(index); } } // Remain is less than front(index).size, insert only the best one if (remain > 0) { // front contains individuals to insert distance.CrowdingDistanceAssignment(front, Problem.NumberOfObjectives); front.Sort(new CrowdingComparator()); for (int k = 0; k < remain; k++) { population.Add(front.Get(k)); } remain = 0; } // This piece of code shows how to use the indicator object into the code // of NSGA-II. In particular, it finds the number of evaluations required // by the algorithm to obtain a Pareto front with a hypervolume higher // than the hypervolume of the true Pareto front. if ((indicators != null) && (requiredEvaluations == 0)) { double HV = indicators.GetHypervolume(population); if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } var sol0 = front.Best(new CrowdingComparator()); //if (plotCounter%plotModulo == 0) SolutionPlotter.Plot(sol0); ProgressReporter.ReportSolution(evaluations, sol0, _worker); } // Return as output parameter the required evaluations SetOutputParameter("evaluations", requiredEvaluations); // Return the first non-dominated front Ranking rank = new Ranking(population); Result = rank.GetSubfront(0); return(Result); }
/// <summary> ///Usage: three choices /// - GDE3 /// - GDE3 problemName /// - GDE3 problemName paretoFrontFile /// </summary> /// <param name="args">Command line arguments.</param> public static void Main(string[] args) { Problem problem; // The problem to solve Algorithm algorithm; // The algorithm to use Operator selection; Operator crossover; Dictionary <string, object> parameters; // Operator parameters QualityIndicator indicators; // Object to get quality indicators // Logger object and file to store log messages var logger = Logger.Log; var appenders = logger.Logger.Repository.GetAppenders(); var fileAppender = appenders[0] as log4net.Appender.FileAppender; fileAppender.File = "GDE3.log"; fileAppender.ActivateOptions(); indicators = null; if (args.Length == 1) { object[] param = { "Real" }; problem = ProblemFactory.GetProblem(args[0], param); } else if (args.Length == 2) { object[] param = { "Real" }; problem = ProblemFactory.GetProblem(args[0], param); indicators = new QualityIndicator(problem, args[1]); } else { // Default problem problem = new Kursawe("Real", 3); //problem = new Water("Real"); //problem = new ZDT1("ArrayReal", 100); //problem = new ConstrEx("Real"); //problem = new DTLZ1("Real"); //problem = new OKA2("Real") ; } algorithm = new JMetalCSharp.Metaheuristics.GDE3.GDE3(problem); // Algorithm parameters algorithm.SetInputParameter("populationSize", 100); algorithm.SetInputParameter("maxIterations", 250); // Crossover operator parameters = new Dictionary <string, object>(); parameters.Add("CR", 0.5); parameters.Add("F", 0.5); crossover = CrossoverFactory.GetCrossoverOperator("DifferentialEvolutionCrossover", parameters); // Add the operators to the algorithm parameters = null; selection = SelectionFactory.GetSelectionOperator("DifferentialEvolutionSelection", parameters); algorithm.AddOperator("crossover", crossover); algorithm.AddOperator("selection", selection); // Execute the Algorithm long initTime = Environment.TickCount; SolutionSet population = algorithm.Execute(); long estimatedTime = Environment.TickCount - initTime; // Result messages logger.Info("Total execution time: " + estimatedTime + "ms"); logger.Info("Objectives values have been writen to file FUN"); population.PrintObjectivesToFile("FUN"); logger.Info("Variables values have been writen to file VAR"); population.PrintVariablesToFile("VAR"); if (indicators != null) { logger.Info("Quality indicators"); logger.Info("Hypervolume: " + indicators.GetHypervolume(population)); logger.Info("GD : " + indicators.GetGD(population)); logger.Info("IGD : " + indicators.GetIGD(population)); logger.Info("Spread : " + indicators.GetSpread(population)); logger.Info("Epsilon : " + indicators.GetEpsilon(population)); } Console.WriteLine("Total execution time gde: moead" + estimatedTime + "ms"); Console.ReadLine(); }
/// <summary> /// Usage: three options /// - PMOEAD /// - PMOEAD problemName /// - PMOEAD problemName ParetoFrontFile /// - PMOEAD problemName numberOfThreads dataDirectory /// </summary> /// <param name="args">Command line arguments. The first (optional) argument specifies the problem to solve.</param> public static void Main(string[] args) { Problem problem; // The problem to solve Algorithm algorithm; // The algorithm to use Operator crossover; // Crossover operator Operator mutation; // Mutation operator QualityIndicator indicators; // Object to get quality indicators Dictionary <string, object> parameters; // Operator parameters int numberOfThreads = 4; string dataDirectory = ""; // Logger object and file to store log messages var logger = Logger.Log; var appenders = logger.Logger.Repository.GetAppenders(); var fileAppender = appenders[0] as log4net.Appender.FileAppender; fileAppender.File = "PMOEAD.log"; fileAppender.ActivateOptions(); indicators = null; if (args.Length == 1) { // args[0] = problem name object[] paramsList = { "Real" }; problem = ProblemFactory.GetProblem(args[0], paramsList); } else if (args.Length == 2) { // args[0] = problem name, [1] = pareto front file object[] paramsList = { "Real" }; problem = ProblemFactory.GetProblem(args[0], paramsList); indicators = new QualityIndicator(problem, args[1]); } else if (args.Length == 3) { // args[0] = problem name, [1] = threads, [2] = data directory object[] paramsList = { "Real" }; problem = ProblemFactory.GetProblem(args[0], paramsList); numberOfThreads = int.Parse(args[1]); dataDirectory = args[2]; } else { // Problem + number of threads + data directory problem = new Kursawe("Real", 3); //problem = new Kursawe("BinaryReal", 3); //problem = new Water("Real"); //problem = new ZDT1("ArrayReal", 100); //problem = new ConstrEx("Real"); //problem = new DTLZ1("Real"); //problem = new OKA2("Real") ; } algorithm = new JMetalCSharp.Metaheuristics.MOEAD.PMOEAD(problem); // Algorithm parameters algorithm.SetInputParameter("populationSize", 300); algorithm.SetInputParameter("maxEvaluations", 150000); algorithm.SetInputParameter("numberOfThreads", numberOfThreads); // Directory with the files containing the weight vectors used in // Q. Zhang, W. Liu, and H Li, The Performance of a New Version of MOEA/D // on CEC09 Unconstrained MOP Test Instances Working Report CES-491, School // of CS & EE, University of Essex, 02/2009. // http://dces.essex.ac.uk/staff/qzhang/MOEAcompetition/CEC09final/code/ZhangMOEADcode/moead0305.rar algorithm.SetInputParameter("dataDirectory", "Data/Parameters/Weight"); algorithm.SetInputParameter("T", 20); algorithm.SetInputParameter("delta", 0.9); algorithm.SetInputParameter("nr", 2); // Crossover operator parameters = new Dictionary <string, object>(); parameters.Add("CR", 1.0); parameters.Add("F", 0.5); crossover = CrossoverFactory.GetCrossoverOperator("DifferentialEvolutionCrossover", parameters); // Mutation operator parameters = new Dictionary <string, object>(); parameters.Add("probability", 1.0 / problem.NumberOfVariables); parameters.Add("distributionIndex", 20.0); mutation = MutationFactory.GetMutationOperator("PolynomialMutation", parameters); algorithm.AddOperator("crossover", crossover); algorithm.AddOperator("mutation", mutation); // Execute the Algorithm long initTime = Environment.TickCount; SolutionSet population = algorithm.Execute(); long estimatedTime = Environment.TickCount - initTime; // Result messages logger.Info("Total execution time: " + estimatedTime + " ms"); logger.Info("Objectives values have been writen to file FUN"); population.PrintObjectivesToFile("FUN"); logger.Info("Variables values have been writen to file VAR"); population.PrintVariablesToFile("VAR"); Console.ReadLine(); if (indicators != null) { logger.Info("Quality indicators"); logger.Info("Hypervolume: " + indicators.GetHypervolume(population)); logger.Info("GD : " + indicators.GetGD(population)); logger.Info("IGD : " + indicators.GetIGD(population)); logger.Info("Spread : " + indicators.GetSpread(population)); } }
public void UpdateQualityIndicator(QualityIndicator currentQuality) { if (_lastQuality != currentQuality) { var currentIndicator = "MediumIndicator"; var lastIndicator = "MediumIndicator"; switch (_lastQuality) { case QualityIndicator.ToBad: lastIndicator = "BadIndicator"; break; case QualityIndicator.VeryPoor: case QualityIndicator.Poor: lastIndicator = "PoorIndicator"; break; case QualityIndicator.Medium: lastIndicator = "MediumIndicator"; break; case QualityIndicator.Good: lastIndicator = "GoodIndicator"; break; default: lastIndicator = "None"; break; } switch (currentQuality) { case QualityIndicator.ToBad: currentIndicator = "BadIndicator"; break; case QualityIndicator.VeryPoor: case QualityIndicator.Poor: currentIndicator = "PoorIndicator"; break; case QualityIndicator.Medium: currentIndicator = "MediumIndicator"; break; case QualityIndicator.Good: currentIndicator = "GoodIndicator"; break; default: return; } _lastQuality = currentQuality; var container = FindChild <Grid>(qualityIndicatoWindow.TransparentWindow, "QualityContainer"); if (container != null) { var image = FindChild <Image>(container, lastIndicator); if (image != null) { image.Visibility = Visibility.Collapsed; } else { image = FindChild <Image>(container, "BadIndicator"); if (image != null) { image.Visibility = Visibility.Collapsed; } image = FindChild <Image>(container, "PoorIndicator"); if (image != null) { image.Visibility = Visibility.Collapsed; } image = FindChild <Image>(container, "MediumIndicator"); if (image != null) { image.Visibility = Visibility.Collapsed; } image = FindChild <Image>(container, "GoodIndicator"); if (image != null) { image.Visibility = Visibility.Collapsed; } } image = FindChild <Image>(container, currentIndicator); if (image != null) { image.Visibility = Visibility.Visible; } } } qualityIndicatoWindow.Refresh(); qualityIndicatoWindow.UpdateWindow(); }
public ActionResult ProviderTrafficLightStatus(int id = 0, bool forceStop = false) { const string mutexKey = "ProviderTrafficLightStatusMutex"; var mutex = (bool?)CacheManagement.CacheHandler.Get(mutexKey); if (mutex.HasValue && mutex.Value) { if (forceStop) { CacheManagement.CacheHandler.Invalidate(mutexKey); } Response.Write(forceStop ? "Job in progress, stopped..." : "Job in progress, skipping..."); return(null); } if (forceStop) { Response.Write("Not in progress..."); return(null); } CacheManagement.CacheHandler.Add(mutexKey, true, new TimeSpan(12, 0, 0)); var model = new ProviderTrafficLightStatusViewModel(); var providers = GetProviderTrafficLightStatusInfo(); var sendToList = new Dictionary <int, ProviderTrafficLightStatusViewModel.ProviderTrafficLightEmail>(); var today = Request.IsAuthenticated && userContext.IsAdministration() ? DateTime.UtcNow.AddDays(id).Date : DateTime.UtcNow.Date; model.Today = today; foreach (var item in providers) { var lastUpdate = item.ModifiedDateTimeUtc == null ? (DateTime?)null : item.ModifiedDateTimeUtc.Value.Date; var lastEmail = item.LastEmailDateTimeUtc; var action = model.Skipped; if (item.SFAFunded /* and it doesn't matter if they are also DfE funded, SFA emails trump the DfE ones */) { // Number of months the provider stays green after updating var greenPeriod = lastUpdate == null ? 0 : QualityIndicator.GetGreenDuration(lastUpdate.Value.Month); // Offset for when they go amber (alwas one month before going red) var amberPeriod = greenPeriod + 1; if (lastEmail == today) { action = model.EmailAlreadySent; } else if (lastUpdate == null) { action = model.Skipped; item.EmailTemplateId = null; item.NextEmailTemplateId = Constants.EmailTemplates.SfaProviderTrafficLightIsNowRed; item.NextEmailDateTimeUtc = item.ProviderCreatedDateTimeUtc.AddMonths(NewProviderGracePeriod).Date; item.TrafficLightStatusId = QualityIndicator.TrafficLight.Red; } else if (today < lastUpdate.Value.AddMonths(greenPeriod)) { action = model.Skipped; item.NextEmailTemplateId = Constants.EmailTemplates.SfaProviderTrafficLightIsNowAmber; item.NextEmailDateTimeUtc = lastUpdate.Value.AddMonths(greenPeriod); item.TrafficLightStatusId = QualityIndicator.TrafficLight.Green; } else if (today == lastUpdate.Value.AddMonths(greenPeriod)) { action = model.AmberToday; item.EmailTemplateId = Constants.EmailTemplates.SfaProviderTrafficLightIsNowAmber; item.NextEmailTemplateId = Constants.EmailTemplates.SfaProviderTrafficLightIsAmberWeek1; item.NextEmailDateTimeUtc = lastUpdate.Value.AddMonths(greenPeriod).AddDays(7); item.TrafficLightStatusId = QualityIndicator.TrafficLight.Amber; } else if (today == lastUpdate.Value.AddMonths(greenPeriod).AddDays(7)) { action = model.AmberForOneWeek; item.EmailTemplateId = Constants.EmailTemplates.SfaProviderTrafficLightIsAmberWeek1; item.NextEmailTemplateId = Constants.EmailTemplates.SfaProviderStatusRedInOneWeek; item.NextEmailDateTimeUtc = lastUpdate.Value.AddMonths(amberPeriod).AddDays(-7); item.TrafficLightStatusId = QualityIndicator.TrafficLight.Amber; } else if (today == lastUpdate.Value.AddMonths(amberPeriod).AddDays(-7)) { action = model.RedInOneWeek; item.EmailTemplateId = Constants.EmailTemplates.SfaProviderStatusRedInOneWeek; item.NextEmailTemplateId = Constants.EmailTemplates.SfaProviderTrafficLightIsNowRed; item.NextEmailDateTimeUtc = lastUpdate.Value.AddMonths(amberPeriod); item.TrafficLightStatusId = QualityIndicator.TrafficLight.Amber; } else if (today == lastUpdate.Value.AddMonths(amberPeriod)) { action = model.RedToday; item.EmailTemplateId = Constants.EmailTemplates.SfaProviderTrafficLightIsNowRed; item.NextEmailTemplateId = Constants.EmailTemplates.SfaProviderTrafficLightIsRedWeeklyReminder; item.NextEmailDateTimeUtc = lastUpdate.Value.AddMonths(amberPeriod).AddDays(7); item.TrafficLightStatusId = QualityIndicator.TrafficLight.Red; } else if (today > lastUpdate.Value.AddMonths(amberPeriod) && lastUpdate.Value.AddMonths(amberPeriod).DayOfWeek == today.DayOfWeek) { action = model.StillRed; item.EmailTemplateId = Constants.EmailTemplates.SfaProviderTrafficLightIsRedWeeklyReminder; item.NextEmailTemplateId = Constants.EmailTemplates.SfaProviderTrafficLightIsRedWeeklyReminder; item.NextEmailDateTimeUtc = today.AddDays(7); item.TrafficLightStatusId = QualityIndicator.TrafficLight.Red; } } else if (item.DFE1619Funded && lastUpdate == null) { var notifyDate = item.ProviderCreatedDateTimeUtc.Month < 11 ? new DateTime(today.Year, 11, 1) : new DateTime(today.AddYears(1).Year, 11, 1); action = model.Skipped; item.EmailTemplateId = null; item.NextEmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderTrafficLightIsNowRed; item.NextEmailDateTimeUtc = notifyDate; item.TrafficLightStatusId = QualityIndicator.TrafficLight.Red; } else if (item.DFE1619Funded && lastUpdate.HasValue) { item.TrafficLightStatusId = QualityIndicator.DfeProviderDateToIndex(lastUpdate.Value); var greenEndDate = QualityIndicator.GetDfeProviderGreenEndDate(lastUpdate.Value).Date; switch (item.TrafficLightStatusId) { case QualityIndicator.TrafficLight.Green: action = model.Skipped; item.NextEmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderTrafficLightIsNowAmber; item.NextEmailDateTimeUtc = greenEndDate.AddDays(1); break; case QualityIndicator.TrafficLight.Amber: if (today.Month == 10 && today.Day == 1) { action = model.AmberToday; item.EmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderTrafficLightIsNowAmber; item.NextEmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderTrafficLightIsAmberWeek1; item.NextEmailDateTimeUtc = today.AddDays(7); } else if (today.Month == 10 && today.Day == 8) { action = model.AmberForOneWeek; item.EmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderTrafficLightIsAmberWeek1; item.NextEmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderStatusRedInOneWeek; item.NextEmailDateTimeUtc = today.AddDays(17); } break; case QualityIndicator.TrafficLight.Red: if (today.Month == 10 && today.Day == 25 && today.Year == greenEndDate.Year) { action = model.RedInOneWeek; item.EmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderStatusRedInOneWeek; item.NextEmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderTrafficLightIsNowRed; item.NextEmailDateTimeUtc = today.AddDays(7); } else if (today.Month == 11 && today.Day == 1 && today.Year == greenEndDate.Year) { action = model.RedToday; item.EmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderTrafficLightIsNowRed; item.NextEmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderTrafficLightIsRedWeeklyReminder; item.NextEmailDateTimeUtc = today.AddDays(7); } else if ((int)(today - lastUpdate.Value).TotalDays % 7 == 0) { action = model.StillRed; item.EmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderTrafficLightIsRedWeeklyReminder; item.NextEmailTemplateId = Constants.EmailTemplates.Dfe1619ProviderTrafficLightIsRedWeeklyReminder; item.NextEmailDateTimeUtc = today.AddDays(7); } break; } } //if (item.EmailTemplateId != null || item.NextEmailTemplateId != null) //{ item.EmailDateTimeUtc = item.EmailTemplateId == null ? (DateTime?)null : today; item.HasValidRecipients = false; sendToList.Add(item.ProviderId, item); //} if (item.TrafficLightStatusId == 0) { item.TrafficLightStatusId = QualityIndicator.GetTrafficStatus(item.ModifiedDateTimeUtc, item.SFAFunded, item.DFE1619Funded); } model.Log[action].Add(item.ProviderName); } // Send the emails - this updates the sendToList SendProviderTrafficLightStatusEmails(sendToList, today); // Log the results SaveHistoryLog(sendToList, today); // Delete mutex CacheManagement.CacheHandler.Invalidate(mutexKey); return(View(model)); }
private void SendProviderTrafficLightStatusEmails(Dictionary <int, ProviderTrafficLightStatusViewModel.ProviderTrafficLightEmail> providers, DateTime today) { if (!providers.Any()) { return; } var sendToProviderIds = providers.Values .Where(x => x.EmailTemplateId != null) .Where(x => !x.QualityEmailsPaused) .Select(x => x.ProviderId) .ToList(); var superUsers = ProvisionUtilities.GetProviderUsers(db, sendToProviderIds, false, true); // Send the emails out foreach (var user in superUsers) { if (!providers.ContainsKey(user.ProviderId)) { continue; } var provider = providers[user.ProviderId]; if (provider.EmailTemplateId == null) { continue; } provider.HasValidRecipients = true; //AppGlobal.EmailQueue.AddToSendQueue( // TemplatedEmail.EmailMessage( // new MailAddress(user.Email, user.Name), // null, // null, // provider.EmailTemplateId.Value, // new List<EmailParameter> // { // new EmailParameter("%PROVIDERNAME%", provider.ProviderName), // new EmailParameter("%LASTUPDATEDATE%", // provider.ModifiedDateTimeUtc.HasValue // ? provider.ModifiedDateTimeUtc.Value.ToString( // Constants.ConfigSettings.ShortDateFormat) // : AppGlobal.Language.GetText(this, "NeverUpdated", "never")), // new EmailParameter("%MONTHSSINCEUPDATE%", // provider.ModifiedDateTimeUtc.HasValue // ? QualityIndicator.GetMonthsBetween(provider.ModifiedDateTimeUtc.Value, DateTime.UtcNow).ToString() // : NewProviderGracePeriod.ToString(CultureInfo.InvariantCulture)) // })); var emailMessage = TemplatedEmail.EmailMessage( new MailAddress(user.Email, user.Name), null, null, provider.EmailTemplateId.Value, new List <EmailParameter> { new EmailParameter("%PROVIDERNAME%", provider.ProviderName), new EmailParameter("%LASTUPDATEDATE%", provider.ModifiedDateTimeUtc.HasValue ? provider.ModifiedDateTimeUtc.Value.ToString( Constants.ConfigSettings.ShortDateFormat) : AppGlobal.Language.GetText(this, "NeverUpdated", "never")), new EmailParameter("%MONTHSSINCEUPDATE%", provider.ModifiedDateTimeUtc.HasValue ? QualityIndicator.GetMonthsBetween(provider.ModifiedDateTimeUtc.Value, DateTime.UtcNow).ToString() : NewProviderGracePeriod.ToString(CultureInfo.InvariantCulture)) }); var response = SfaSendGridClient.SendGridEmailMessage(emailMessage, null); } // Update the providers foreach (var providerId in sendToProviderIds) { var provider = new Provider { ProviderId = providerId, TrafficLightEmailDateTimeUtc = today }; db.Providers.Attach(provider); db.Entry(provider).Property(x => x.TrafficLightEmailDateTimeUtc).IsModified = true; providers[providerId].EmailDateTimeUtc = today; } db.Configuration.ValidateOnSaveEnabled = false; db.SaveChanges(); }