/// <summary> /// Updates the grid limits considering the solutions contained in a <code>SolutionSet</code>. /// </summary> /// <param name="solutionSet">The <code>SolutionSet</code> considered.</param> private void UpdateLimits(SolutionSet solutionSet) { //Init the lower and upper limits for (int obj = 0; obj < objectives; obj++) { //Set the lower limits to the max real lowerLimits[obj] = double.MaxValue; //Set the upper limits to the min real upperLimits[obj] = double.MinValue; } //Find the max and min limits of objetives into the population for (int ind = 0; ind < solutionSet.Size(); ind++) { Solution tmpIndividual = solutionSet.Get(ind); for (int obj = 0; obj < objectives; obj++) { if (tmpIndividual.Objective[obj] < lowerLimits[obj]) { lowerLimits[obj] = tmpIndividual.Objective[obj]; } if (tmpIndividual.Objective[obj] > upperLimits[obj]) { upperLimits[obj] = tmpIndividual.Objective[obj]; } } } }
public void AutoSet(SolutionSet s) { populationSize = 11; t = 2; population = new SolutionSet(populationSize); indArray = new Solution[Problem.NumberOfObjectives]; neighborhood = new int[populationSize][]; for (int i = 0; i < populationSize; i++) { neighborhood[i] = new int[t]; } z = new double[Problem.NumberOfObjectives]; lambda = new double[populationSize][]; for (int i = 0; i < populationSize; i++) { lambda[i] = new double[Problem.NumberOfObjectives]; } //Step 1. Initialization //Step 1.1 Compute euclidean distances between weight vectors and find T InitUniformWeight(); InitNeighborhood(); this.population = s; //Step 1.3 Initizlize z InitIdealPoint(); GetStdDev(neighborhood); }
/// <summary> /// Reads a set of non dominated solutions from a file /// </summary> /// <param name="path">The path of the file containing the data</param> /// <returns>A solution set</returns> public SolutionSet ReadSolutionSet(string path) { try { SolutionSet solutionSet = new SolutionSet(); /* Open the file */ using (StreamReader reader = new StreamReader(path)) { string aux = reader.ReadLine(); while (aux != null) { string[] st = aux.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); int i = 0; Solution solution = new Solution(st.Length); foreach (string s in st) { double value = JMetalCSharp.Utils.Utils.ParseDoubleInvariant(s); solution.Objective[i] = value; i++; } solutionSet.Capacity = solutionSet.Capacity + 1; solutionSet.Add(solution); aux = reader.ReadLine(); } } return(solutionSet); } catch (Exception e) { Console.WriteLine("ReadNonDominatedSolutionSet: " + path); Console.WriteLine(e.StackTrace); } return(null); }
public static void Main(string[] args) { PrologEngine pe = new PrologEngine(); SolutionSet ss = pe.GetAllSolutions("../../../MLAiP_VersionSpace.pl", "candidate_elim([[_,_,_]], [], [[small, medium, large], [red,blue,green], [ball, brick, cube]])."); if (ss.Success) { foreach (Solution s in ss.NextSolution) { Console.WriteLine(); foreach (Variable v in s.NextVariable) { Console.WriteLine(string.Format("{0} = {1}", v.Name, v.Value)); } } } else { Console.WriteLine(); Console.WriteLine(ss.ErrMsg); } //Console.WriteLine("Hello World!"); }
public double ComputeHypervolume(SolutionSet solutionSet, Solution referencePoint) { double hv = 0.0; if (solutionSet.Size() == 0) { hv = 0.0; } else { this.numberOfObjectives = solutionSet.Get(0).NumberOfObjectives; this.referencePoint = referencePoint; if (this.numberOfObjectives == 2) { solutionSet.Sort(new ObjectiveComparator(this.numberOfObjectives - 1, true)); hv = Get2DHV(solutionSet); } else { WFGHV wfg = new WFGHV(this.numberOfObjectives, solutionSet.Size()); Front front = new Front(solutionSet.Size(), numberOfObjectives, solutionSet); hv = wfg.GetHV(front, referencePoint); } } return(hv); }
/// <summary> /// Executes the operation /// </summary> /// <param name="obj">An object containing the population and the position (index) of the current individual</param> /// <returns>An object containing the three selected parents</returns> public override object Execute(object obj) { object[] parameters = (object[])obj; SolutionSet population = (SolutionSet)parameters[0]; int index = (int)parameters[1]; Solution[] parents = new Solution[3]; int r1, r2, r3; if (population.Size() < 4) { throw new Exception("DifferentialEvolutionSelection: the population has less than four solutions"); } do { r1 = (int)(JMetalRandom.Next(0, population.Size() - 1)); } while (r1 == index); do { r2 = (int)(JMetalRandom.Next(0, population.Size() - 1)); } while (r2 == index || r2 == r1); do { r3 = (int)(JMetalRandom.Next(0, population.Size() - 1)); } while (r3 == index || r3 == r1 || r3 == r2); parents[0] = population.Get(r1); parents[1] = population.Get(r2); parents[2] = population.Get(r3); return(parents); }
public override Solution GetOffspring(SolutionSet solutionSet, SolutionSet archive) { Solution[] parents = new Solution[2]; Solution offSpring = null; try { parents[0] = (Solution)selection.Execute(solutionSet); if (archive.Size() > 0) { parents[1] = (Solution)selection.Execute(archive); } else { parents[1] = (Solution)selection.Execute(solutionSet); } Solution[] children = (Solution[])crossover.Execute(parents); offSpring = children[0]; //Create a new solution, using DE } catch (Exception ex) { Logger.Log.Error("Error in: " + this.GetType().FullName + ".GetOffspring()", ex); Console.Error.WriteLine("Error in: " + this.GetType().FullName); } return(offSpring); }
public void ConsultFromString_GetAllSolutions_Adhoc() { var prolog = new PrologEngine(persistentCommandHistory: false); // 'socrates' is human. prolog.ConsultFromString("human(socrates)."); // 'R2-D2' is droid. prolog.ConsultFromString("droid(r2d2)."); // human is bound to die. prolog.ConsultFromString("mortal(X) :- human(X)."); prolog.GetFirstSolution(query: "listing."); SolutionSet solutionset1 = prolog.GetAllSolutions(null, "human(H)"); Console.WriteLine("====================================="); Console.WriteLine(solutionset1.ErrMsg); Console.WriteLine("====================================="); Assert.True(solutionset1.Success); if (solutionset1.Success) { var s = solutionset1[0]; foreach (Variable v in s.NextVariable) { Console.WriteLine(string.Format("{0} ({1}) = {2}", v.Name, v.Type, v.Value)); } } }
public int GetLessContributorHV(SolutionSet set) { Front wholeFront = new Front(); wholeFront.LoadFront(set, -1); int index = 0; double contribution = double.PositiveInfinity; for (int i = 0; i < set.Size(); i++) { double[] v = new double[set.Get(i).NumberOfObjectives]; for (int j = 0; j < v.Length; j++) { v[j] = set.Get(i).Objective[j]; } Point p = new Point(v); double aux = this.GetExclusiveHV(wholeFront, i); if ((aux) < contribution) { index = i; contribution = aux; } set.Get(i).CrowdingDistance = aux; } return(index); }
/// <summary> /// Return the index of the nearest solution in the solution set to a given solution /// </summary> /// <param name="solution"></param> /// <param name="solutionSet"></param> /// <returns>The index of the nearest solution; -1 if the solutionSet is empty</returns> public int IndexToNearestSolutionInSolutionSpace(Solution solution, SolutionSet solutionSet) { int index = -1; double minimumDistance = double.MaxValue; try { for (int i = 0; i < solutionSet.Size(); i++) { double distance = 0; distance = this.DistanceBetweenSolutions(solution, solutionSet.Get(i)); if (distance < minimumDistance) { minimumDistance = distance; index = i; } } } catch (Exception ex) { Logger.Log.Error("Exception in " + this.GetType().FullName + ".IndexToNearestSolutionInSolutionSpace()", ex); Console.WriteLine("Exception in " + this.GetType().FullName + ".IndexToNearestSolutionInSolutionSpace()"); } return(index); }
public void Set(SolutionSet s, int[][] n, double[][] l, double[] z) { this.population = s; this.neighborhood = n; this.z = z; this.lambda = l; }
/// <summary> /// Returns the generational distance of solution set /// </summary> /// <param name="solutionSet">Solution set</param> /// <returns>The value of the hypervolume indicator</returns> public double GetGD(SolutionSet solutionSet) { return(new GenerationalDistance().CalculateGenerationalDistance( solutionSet.WriteObjectivesToMatrix(), trueParetoFront.WriteObjectivesToMatrix(), problem.NumberOfObjectives)); }
public override Solution GetOffspring(SolutionSet solutionSet, int index) { Solution[] parents = new Solution[3]; Solution offSpring = null; try { int r1, r2; do { r1 = JMetalRandom.Next(0, solutionSet.Size() - 1); } while (r1 == index); do { r2 = JMetalRandom.Next(0, solutionSet.Size() - 1); } while (r2 == index || r2 == r1); parents[0] = solutionSet.Get(r1); parents[1] = solutionSet.Get(r2); parents[2] = solutionSet.Get(index); offSpring = (Solution)crossover.Execute(new object[] { solutionSet.Get(index), parents }); } catch (Exception ex) { Logger.Log.Error("Exception in " + this.GetType().FullName + ".GetOffSpring()", ex); Console.Error.WriteLine("Exception in " + this.GetType().FullName + ".GetOffSpring()"); } //Create a new solution, using DE return(offSpring); }
public SMPSO(Problem problem, string trueParetoFront) : base(problem) { hy = new HyperVolume(); MetricsUtil mu = new MetricsUtil(); trueFront = mu.ReadNonDominatedSolutionSet(trueParetoFront); trueHypervolume = hy.Hypervolume(trueFront.WriteObjectivesToMatrix(), trueFront.WriteObjectivesToMatrix(), problem.NumberOfObjectives); // Default configuration r1Max = 1.0; r1Min = 0.0; r2Max = 1.0; r2Min = 0.0; C1Max = 2.5; C1Min = 1.5; C2Max = 2.5; C2Min = 1.5; WMax = 0.1; WMin = 0.1; ChVel1 = -1; ChVel2 = -1; }
public SMPSO(Problem problem, List <double> variables, string trueParetoFront) : base(problem) { r1Max = variables[0]; r1Min = variables[1]; r2Max = variables[2]; r2Min = variables[3]; C1Max = variables[4]; C1Min = variables[5]; C2Max = variables[6]; C2Min = variables[7]; WMax = variables[8]; WMin = variables[9]; ChVel1 = variables[10]; ChVel2 = variables[11]; hy = new HyperVolume(); MetricsUtil mu = new MetricsUtil(); trueFront = mu.ReadNonDominatedSolutionSet(trueParetoFront); trueHypervolume = hy.Hypervolume(trueFront.WriteObjectivesToMatrix(), trueFront.WriteObjectivesToMatrix(), problem.NumberOfObjectives); }
public void LoadFront(SolutionSet solutionSet, int notLoadingIndex) { if (notLoadingIndex >= 0 && notLoadingIndex < solutionSet.Size()) { NumberOfPoints = solutionSet.Size() - 1; } else { NumberOfPoints = solutionSet.Size(); } NPoints = NumberOfPoints; dimension = solutionSet.Get(0).NumberOfObjectives; Points = new Point[NumberOfPoints]; int index = 0; for (int i = 0; i < solutionSet.Size(); i++) { if (i != notLoadingIndex) { double[] vector = new double[dimension]; for (int j = 0; j < dimension; j++) { vector[j] = solutionSet.Get(i).Objective[j]; } Points[index++] = new Point(vector); } } }
/// <summary> /// Returns a <code>SolutionSet</code> with the North, Sout, East and West /// neighbors solutions of ratio 0 of a given location into a given /// <code>SolutionSet</code>. /// </summary> /// <param name="solutionSet">The <code>SolutionSet</code>.</param> /// <param name="location">The location.</param> /// <returns>A <code>SolutionSet</code> with the neighbors.</returns> public SolutionSet GetFourNeighbors(SolutionSet solutionSet, int location) { //SolutionSet that contains the neighbors (to return) SolutionSet neighbors; //instance the solutionSet to a non dominated li of individuals neighbors = new SolutionSet(24); //Gets the neighboords N, S, E, W int index; //North index = structure[location][0][(int)Row.N]; neighbors.Add(solutionSet.Get(index)); //South index = structure[location][0][(int)Row.S]; neighbors.Add(solutionSet.Get(index)); //East index = structure[location][0][(int)Row.E]; neighbors.Add(solutionSet.Get(index)); //West index = structure[location][0][(int)Row.W]; neighbors.Add(solutionSet.Get(index)); //Return the list of non-dominated individuals return(neighbors); }
public EditCourses() { InitializeComponent(); var prolog = new PrologEngine(persistentCommandHistory: false); prolog.Consult("courses.pl"); /*// 'socrates' is human. * prolog.ConsultFromString("human(socrates)."); * // human is bound to die. * prolog.ConsultFromString("mortal(X) :- human(X).");*/ // Question: Shall 'socrates' die? //var solution = prolog.GetFirstSolution(query: "prereq(ece462,ZZZ)."); SolutionSet solution2 = prolog.GetAllSolutions("courses.pl", "prereq(ece462,ZZZ)."); //Console.WriteLine(solution2[0]); // = "True" (Yes!) //Console.WriteLine(string.Join(",", solution2)); for (int i = 0; i < solution2.Count; i++) // or: foreach (Solution s in ss.NextSolution) { Solution s = solution2[i]; Console.WriteLine("Solution {0}", i + 1); foreach (Variable v in s.NextVariable) { Console.WriteLine(string.Format("{0} ({1}) = {2}", v.Name, v.Type, v.Value)); } } //Console.WriteLine(solution.Solved); // = "True" (Yes!) }
public async Task <SolutionServiceResult> FinalizeSolutionSet(string id, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException(nameof(id)); } cancellationToken.ThrowIfCancellationRequested(); if (await SolutionCache.FetchSizeAsync(cancellationToken) > Configuration.MaxCache) { return(SolutionServiceResult.Full); } var solution = await SolutionSet.FetchSolutionMetdataAsync(id, cancellationToken); var result = SolutionValidator.Validate(solution, cancellationToken); if (result == ValidationResult.Incomplete) { return(SolutionServiceResult.Incomplete); } if (result == ValidationResult.Invalid) { await SolutionSet.RemoveSolutionMetadataAsync(id, cancellationToken); return(SolutionServiceResult.StartOver); } await SolutionCache.PutAsync(solution, cancellationToken); await SolutionSet.RemoveSolutionMetadataAsync(id, cancellationToken); return(SolutionServiceResult.Success); }
public double ComputeHypervolume(SolutionSet solutionSet) { double hv; if (solutionSet.Size() == 0) { hv = 0.0; } else { numberOfObjectives = solutionSet.Get(0).NumberOfObjectives; referencePoint = new Solution(numberOfObjectives); UpdateReferencePoint(solutionSet); if (numberOfObjectives == 2) { solutionSet.Sort(new ObjectiveComparator(numberOfObjectives - 1, true)); hv = Get2DHV(solutionSet); } else { UpdateReferencePoint(solutionSet); Front front = new Front(solutionSet.Size(), numberOfObjectives, solutionSet); hv = new WFGHV(numberOfObjectives, solutionSet.Size(), referencePoint).GetHV(front); } } return(hv); }
public void determinerEtatPompe() { int etat_marche = traductionBooleenne(kryptonCheckButton1.Checked); int etat_arret = traductionBooleenne(kryptonCheckButton2.Checked); var prolog = new PrologEngine(persistentCommandHistory: false); prolog.Consult("pompe_essence.pl"); SolutionSet resultat = new SolutionSet(); resultat = prolog.GetAllSolutions("pompe_essence.pl", "etat_pompe(" + etat_arret + "," + etat_marche + "," + etat_pompe + ", R)", 1); //MessageBox.Show(resultat.ToString()); foreach (Solution x in resultat.NextSolution) { foreach (Variable you in x.NextVariable) { //MessageBox.Show(you.Value); etat_pompe = int.Parse(you.Value); } } if (etat_pompe == 1) { toolStripStatusLabel1.ForeColor = Color.DarkGreen; toolStripStatusLabel1.Text = "La pompe fonctionne"; } else { toolStripStatusLabel1.ForeColor = Color.Red; toolStripStatusLabel1.Text = "La pompe est arrêtée"; } }
/// <summary> /// Returns a matrix with distances between solutions in a <code>SolutionSet</code>. /// </summary> /// <param name="solutionSet">The <code>SolutionSet</code>.</param> /// <returns>a matrix with distances.</returns> public double[][] DistanceMatrix(SolutionSet solutionSet) { Solution solutionI, solutionJ; //The matrix of distances double[][] distance = new double[solutionSet.Size()][]; for (int i = 0; i < solutionSet.Size(); i++) { distance[i] = new double[solutionSet.Size()]; } //-> Calculate the distances for (int i = 0; i < solutionSet.Size(); i++) { distance[i][i] = 0.0; solutionI = solutionSet.Get(i); for (int j = i + 1; j < solutionSet.Size(); j++) { solutionJ = solutionSet.Get(j); distance[i][j] = this.DistanceBetweenObjectives(solutionI, solutionJ); distance[j][i] = distance[i][j]; } } //->Return the matrix of distances return(distance); }
/// <summary> /// Computes the HV contribution of the solutions /// </summary> /// <param name="solutionSet"></param> public void ComputeHVContributions(SolutionSet solutionSet) { double[] contributions = new double[solutionSet.Size()]; double solutionSetHV = 0; solutionSetHV = ComputeHypervolume(solutionSet); for (int i = 0; i < solutionSet.Size(); i++) { Solution currentPoint = solutionSet.Get(i); solutionSet.Remove(i); if (numberOfObjectives == 2) { contributions[i] = solutionSetHV - Get2DHV(solutionSet); } else { Front front = new Front(solutionSet.Size(), numberOfObjectives, solutionSet); double hv = new WFGHV(numberOfObjectives, solutionSet.Size(), referencePoint).GetHV(front); contributions[i] = solutionSetHV - hv; } solutionSet.Add(i, currentPoint); } for (int i = 0; i < solutionSet.Size(); i++) { solutionSet.Get(i).CrowdingDistance = contributions[i]; } }
/// <summary> /// Assigns crowding distances to all solutions in a <code>SolutionSet</code>. /// </summary> /// <param name="solutionSet">The <code>SolutionSet</code>.</param> /// <param name="nObjs">Number of objectives.</param> public void CrowdingDistanceAssignment(SolutionSet solutionSet, int nObjs) { int size = solutionSet.Size(); if (size == 0) { return; } if (size == 1) { solutionSet.Get(0).CrowdingDistance = double.PositiveInfinity; return; } if (size == 2) { solutionSet.Get(0).CrowdingDistance = double.PositiveInfinity; solutionSet.Get(1).CrowdingDistance = double.PositiveInfinity; return; } //Use a new SolutionSet to evite alter original solutionSet SolutionSet front = new SolutionSet(size); for (int i = 0; i < size; i++) { front.Add(solutionSet.Get(i)); } for (int i = 0; i < size; i++) { front.Get(i).CrowdingDistance = 0.0; } double objetiveMaxn; double objetiveMinn; double distance; for (int i = 0; i < nObjs; i++) { // Sort the population by Obj n front.Sort(new ObjectiveComparator(i)); objetiveMinn = front.Get(0).Objective[i]; objetiveMaxn = front.Get(front.Size() - 1).Objective[i]; //Set de crowding distance front.Get(0).CrowdingDistance = double.PositiveInfinity; front.Get(size - 1).CrowdingDistance = double.PositiveInfinity; for (int j = 1; j < size - 1; j++) { distance = front.Get(j + 1).Objective[i] - front.Get(j - 1).Objective[i]; distance = distance / (objetiveMaxn - objetiveMinn); distance += front.Get(j).CrowdingDistance; front.Get(j).CrowdingDistance = distance; } } }
public ParetoSolver(SolutionSet solutions) { _solutions = solutions; var size = _solutions.GetObjectives().GetUpperBound(0) + 1; var ocount = _solutions.GetObjectives()[0].Length; var objectives = _solutions.GetObjectives(); var f1 = new double[size]; var f2 = new double[size]; var f3 = new double[] { }; if (ocount == 3) { f3 = new double[size]; } for (var i = 0; i < size; i++) { f1[i] = objectives[i][0]; if (ocount > 1) { f2[i] = objectives[i][1]; } if (ocount > 2) { f3[i] = objectives[i][2]; } } var f1min = f1.Min(); var f1max = f1.Max(); var f2min = f2.Min(); var f2max = f2.Max(); double f3min = 0; double f3max = 0; if (ocount == 3) { f3min = f3.Min(); f3max = f3.Max(); } _f1Scaled = new double[size]; _f2Scaled = new double[size]; _f3Scaled = new double[size]; for (var i = 0; i < size; i++) { _f1Scaled[i] = FMScaling.ScaleFromTo(f1min, f1max, 0, 1, f1[i]); if (ocount > 1) { _f2Scaled[i] = FMScaling.ScaleFromTo(f2min, f2max, 0, 1, f2[i]); } if (ocount == 3) { _f3Scaled[i] = FMScaling.ScaleFromTo(f3min, f3max, 0, 1, f3[i]); } } }
/// <summary> /// Constructor. /// Creates a new instance of Spea2Fitness for a given <code>SolutionSet</code>. /// </summary> /// <param name="solutionSet">The <code>SolutionSet</code></param> public Spea2Fitness(SolutionSet solutionSet) { this.distanceMatrix = distance.DistanceMatrix(solutionSet); this.solutionSet = solutionSet; for (int i = 0; i < solutionSet.Size(); i++) { solutionSet.Get(i).Location = i; } }
public async Task <TSolution> FetchSolutionSet(string id, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException(nameof(id)); } cancellationToken.ThrowIfCancellationRequested(); return(await SolutionSet.FetchSolutionMetdataAsync(id, cancellationToken)); }
static void Main(string[] args) { PrologEngine e = new PrologEngine(); // Example 1 -- the age/2 predicate is a builtin example; defined in Bootstrap.cs Console.WriteLine("Example 1"); Console.WriteLine(); e.Query = "age(lee,39)."; foreach (var s in e.SolutionIterator) { Console.WriteLine("{0}{1}", s, (s.IsLast ? null : ";")); } SolutionSet ss = e.GetAllSolutions(null, "age(P,N)"); if (ss.Success) { for (int i = 0; i < ss.Count; i++) // or: foreach (Solution s in ss.NextSolution) { Solution s = ss[i]; Console.WriteLine("Solution {0}", i + 1); foreach (Variable v in s.NextVariable) { Console.WriteLine(string.Format("{0} ({1}) = {2}", v.Name, v.Type, v.Value)); } } } else { Console.WriteLine("Failure"); } // Example 2 -- xml generation //Console.WriteLine ("Example 2"); //Console.WriteLine (); //string result = e.GetAllSolutionsXml (null, null, "age(P,N)"); //Console.WriteLine (result); //Console.WriteLine (); //// Example 3 -- error //Console.WriteLine ("Example 3"); //Console.WriteLine (); //ss = e.GetAllSolutions (null, "age(P,))))))))))"); //if (ss.HasError) // Console.WriteLine ("An error occurred: {0}", ss.ErrMsg); //Console.WriteLine ("Press any key to exit"); //Console.ReadKey (); }
/// <summary> /// Constructor /// </summary> /// <param name="problem">The problem</param> /// <param name="paretoFrontFile">Pareto front file</param> public QualityIndicator(Problem problem, string paretoFrontFile) { this.problem = problem; Utils = new MetricsUtil(); trueParetoFront = Utils.ReadNonDominatedSolutionSet(paretoFrontFile); TrueParetoFrontHypervolume = new HyperVolume().Hypervolume( trueParetoFront.WriteObjectivesToMatrix(), trueParetoFront.WriteObjectivesToMatrix(), problem.NumberOfObjectives); }
/// <summary> /// Computes the feasibility ratio /// </summary> /// <param name="solutionSet"></param> /// <returns>The ratio of feasible solutions</returns> private double MeanOveralViolation(SolutionSet solutionSet) { double aux = 0.0; for (int i = 0; i < solutionSet.Size(); i++) { aux += Math.Abs(solutionSet.Get(i).NumberOfViolatedConstraints *solutionSet.Get(i).OverallConstraintViolation); } return(aux / (double)solutionSet.Size()); }