- Timestamp:
- 03/17/20 16:29:48 (5 years ago)
- Location:
- branches/3057_DynamicALPS/HeuristicLab.Algorithms.DynamicALPS/3.4
- Files:
-
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/3057_DynamicALPS/HeuristicLab.Algorithms.DynamicALPS/3.4/DynamicALPSASolution.cs
r17438 r17479 115 115 { 116 116 Qualities = (double[])original.Qualities.Clone(); 117 Constraints = (double[])original.Qualities.Clone(); 118 HypervolumeContribution = (double[])original.HypervolumeContribution.Clone(); // kf, sms-emoa 119 NondominanceRanking = (int[])original.NondominanceRanking.Clone(); // kf, sms-emoa 120 Individual = (IItem)original.Individual.Clone(cloner); 117 Constraints = (double[])original.Constraints.Clone(); 118 if (original.HypervolumeContribution != null) { 119 HypervolumeContribution = (double[])original.HypervolumeContribution.Clone(); // kf, sms-emoa 120 } 121 if (original.NondominanceRanking != null) { 122 NondominanceRanking = (int[])original.NondominanceRanking.Clone(); // kf, sms-emoa 123 } 124 if (original.Individual != null) { 125 Individual = (IItem)original.Individual.Clone(cloner); 126 } 121 127 } 122 128 -
branches/3057_DynamicALPS/HeuristicLab.Algorithms.DynamicALPS/3.4/DynamicALPSAlgorithm.cs
r17438 r17479 120 120 121 121 // IMPROVE: ........ 122 int[] ageGapArray = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; 122 // 1 2 4 8 16 32 64 128 256 512 123 int[] ageGapArray = new int[] { 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240 }; 123 124 int[] numberDiscard = new int[10]; 124 125 … … 126 127 127 128 activeLayer = new bool[nLayerALPS]; 129 layerCrossoverProbability = new double[nLayerALPS]; 128 130 int[][] ageMatrix = new int[nLayerALPS][]; // layer * population size 129 131 … … 132 134 // cancellation token for the inner operations which should not be immediately cancelled 133 135 var innerToken = new CancellationToken(); 134 135 136 // run some analyzer on each layer (for now calculate scatter plots )137 List<Tuple<int, ScatterPlotAnalyzer>> layerAnalyzers;138 136 139 137 … … 143 141 layerJointPopulation = new IDynamicALPSSolution[nLayerALPS][]; 144 142 layerDiscardPopulation = new IDynamicALPSSolution[nLayerALPS][]; 143 layerDiscardIndivdual = new IDynamicALPSSolution[nLayerALPS]; 145 144 146 145 … … 148 147 // BUG: The size of offspring should vary in different layers!!!! 149 148 layerOffspringPopulation[counterLayerALPS] = new IDynamicALPSSolution[lambda]; 149 // layerDiscardPopulation[counterLayerALPS] = new IDynamicALPSSolution[populationSize]; // for the previous version, is used to store the individuals whose age is older than the age gap 150 150 layerDiscardPopulation[counterLayerALPS] = new IDynamicALPSSolution[populationSize]; 151 151 population.CopyTo(layerPopulation[counterLayerALPS], 0); 152 152 153 153 activeLayer[counterLayerALPS] = true; 154 layerCrossoverProbability[counterLayerALPS] = 0; 155 var test = UseAverageAge.Value; 154 156 for (int i = 0; i < nLayerALPS; i++) { 155 157 if (i == 0) { … … 158 160 else { activeLayer[i] = false; } 159 161 numberDiscard[i] = 0; 162 layerCrossoverProbability[i] = CrossoverProbability.Value; 160 163 } 161 164 int bottomLayerIDX = 0; 165 int godScope = 0; 162 166 // Mainloop 163 167 while (evaluatedSolutions < maximumEvaluatedSolutions && !cancellationToken.IsCancellationRequested) { 164 168 for (int i = 0; i < nLayerALPS; i++) { // loop for every layer 165 169 int discardedIndividualIndex = 0; 166 if (activeLayer[i] == true) { // check the layer is active or not. 167 evaluatedSolutions = SMSEMOA(populationSize, lambda, i); 170 var currentLayerIDX = i; 171 var nextLayerIDX = i + 1; 172 if (nextLayerIDX == nLayerALPS) { 173 nextLayerIDX = bottomLayerIDX; 174 godScope = 1; 175 } 176 else { godScope = 0; } 177 178 179 if (activeLayer[currentLayerIDX] == true) { // check the current layer is active or not. 180 evaluatedSolutions = SMSEMOA(populationSize, lambda, currentLayerIDX); // get the offspring -- layerJointPopulation 168 181 if (evaluatedSolutions >= maximumEvaluatedSolutions) { break; } // check evaluation budget 169 ageMatrix[i] = layerJointPopulation[i].Select(x => x.Age).ToArray(); // get age info of the current layer joint population 170 if (ageMatrix[i].Max() > ageGapArray[i]) { // mature: moving 171 discardedIndividualIndex = ageMatrix[i].ToList().IndexOf(ageMatrix[i].Max()); // BUG when two individual has the same maximal age???? NOT POSSBILE IN SMS-EMOA 172 layerDiscardPopulation[i][numberDiscard[i]] = layerJointPopulation[i][discardedIndividualIndex]; // move the individual to the next layer 173 layerJointPopulation[i].Where((x, idx) => idx != discardedIndividualIndex).ToArray().CopyTo(layerPopulation[i], 0); // discard the indivudal in the current layer 174 numberDiscard[i] += 1; 175 if (activeLayer[i + 1] == false) { // next layer is not active // bug, if i == number of layer, out of range . 176 if (numberDiscard[i] == populationSize) { 177 InitializeLayer(i + 1, populationSize, lambda); // initilizae the layerPopulation for the next layer && ACTIVE FLAGE 178 layerDiscardPopulation[i].CopyTo(layerPopulation[i + 1], 0); 179 numberDiscard[i] = 0; 182 ageMatrix[currentLayerIDX] = layerJointPopulation[currentLayerIDX].Select(x => x.Age).ToArray(); // get age info of the current layer joint population 183 #region version 1: use average to initialize the layer population 184 if (UseAverageAge.Value == true) { 185 if (activeLayer[nextLayerIDX] == false) {// next layer is not active yet 186 if (ageMatrix[currentLayerIDX].Average() > ageGapArray[currentLayerIDX]) { // the next layer is initialized 187 InitializeLayer(nextLayerIDX, populationSize, lambda); // initilizae the layerPopulation for the next layer && ACTIVE FLAGE 188 layerJointPopulation[currentLayerIDX].CopyTo(layerJointPopulation[nextLayerIDX], 0); 189 SmetricSelection(lambda, nextLayerIDX); // layerpopulation is updated here, 190 } 191 else {// the next layer is not initialized 192 SmetricSelection(lambda, currentLayerIDX); 193 } 194 } 195 else { // next layer is active 196 if (activeLayer.All(x => x) && godScope == 1) { // all the layers are active and the current layer is the top layer, move the discarded individual from the top to bottom, and reset the age 197 SmetricSelection(lambda, currentLayerIDX); 198 layerPopulation[bottomLayerIDX].CopyTo(layerJointPopulation[bottomLayerIDX], 0); 199 layerDiscardIndivdual[currentLayerIDX].Age = 0; 200 layerJointPopulation[bottomLayerIDX][populationSize] = layerDiscardIndivdual[currentLayerIDX]; 201 SmetricSelection(lambda, bottomLayerIDX); 202 } 203 else { 204 if (ageMatrix[currentLayerIDX].Max() > ageGapArray[currentLayerIDX]) { // moving 205 discardedIndividualIndex = ageMatrix[currentLayerIDX].ToList().IndexOf(ageMatrix[currentLayerIDX].Max()); 206 layerPopulation[nextLayerIDX].CopyTo(layerJointPopulation[nextLayerIDX], 0); 207 layerJointPopulation[currentLayerIDX].Where((x, idx) => idx == discardedIndividualIndex).ToArray().CopyTo(layerJointPopulation[nextLayerIDX], populationSize); 208 SmetricSelection(lambda, nextLayerIDX); // AGE and HVC 209 layerJointPopulation[currentLayerIDX].Where((x, idx) => idx != discardedIndividualIndex).ToArray().CopyTo(layerPopulation[currentLayerIDX], 0); // dicard the individual in the current layer 210 } 211 else { // next layer is active, but the age is not mature. 212 SmetricSelection(lambda, currentLayerIDX); 213 } 214 } 215 } 216 #endregion 217 } 218 else { 219 #region version 2: use individual age to to initialize the next layer 220 if (ageMatrix[currentLayerIDX].Max() > ageGapArray[currentLayerIDX]) { // mature: moving 221 discardedIndividualIndex = ageMatrix[currentLayerIDX].ToList().IndexOf(ageMatrix[currentLayerIDX].Max()); // BUG when two individual has the same maximal age???? NOT POSSBILE IN SMS-EMOA 222 layerDiscardPopulation[currentLayerIDX][numberDiscard[currentLayerIDX]] = layerJointPopulation[currentLayerIDX][discardedIndividualIndex]; // move the individual to the next layer 223 layerJointPopulation[currentLayerIDX].Where((x, idx) => idx != discardedIndividualIndex).ToArray().CopyTo(layerPopulation[currentLayerIDX], 0); // discard the indivudal in the current layer 224 numberDiscard[currentLayerIDX] += 1; 225 if (activeLayer[nextLayerIDX] == false) { // next layer is not active // bug, if i == number of layer, out of range . 226 if (numberDiscard[currentLayerIDX] == populationSize) { 227 InitializeLayer(nextLayerIDX, populationSize, lambda); // initilizae the layerPopulation for the next layer && ACTIVE FLAGE 228 layerDiscardPopulation[currentLayerIDX].CopyTo(layerPopulation[nextLayerIDX], 0); 229 numberDiscard[currentLayerIDX] = 0; 180 230 } 181 231 else { … … 184 234 } 185 235 else { // next layer is active 186 layerPopulation[ i+1].CopyTo(layerJointPopulation[i + 1], 0);187 layerJointPopulation[ i].Where((x, idx) => idx == discardedIndividualIndex).ToArray().CopyTo(layerJointPopulation[i + 1], populationSize);188 SmetricSelection(lambda, i + 1); // AGE and HVC189 numberDiscard[ i] = 0;236 layerPopulation[nextLayerIDX].CopyTo(layerJointPopulation[nextLayerIDX], 0); 237 layerJointPopulation[currentLayerIDX].Where((x, idx) => idx == discardedIndividualIndex).ToArray().CopyTo(layerJointPopulation[nextLayerIDX], populationSize); 238 SmetricSelection(lambda, nextLayerIDX); // AGE and HVC 239 numberDiscard[currentLayerIDX] = 0; 190 240 } 191 241 } 192 layerPopulation[i].CopyTo(population, 0); // BUG: should copy all the active layers to population. 242 layerPopulation[currentLayerIDX].CopyTo(population, 0); // BUG: should copy all the active layers to population. 243 #endregion 244 } 193 245 } 194 246 else { 195 247 // Some thing wrong? lol nothing wrong here ^_^ 196 248 } 197 } 198 249 250 251 } 252 253 254 255 256 int numberOfActiveLayer = activeLayer.Where(c => c).Count(); 257 population = new IDynamicALPSSolution[populationSize * numberOfActiveLayer]; 258 for (int i = 0; i < numberOfActiveLayer; i++) { 259 layerPopulation[i].CopyTo(population, i * populationSize); 260 } 199 261 200 262 … … 203 265 ExecuteOperation(executionContext, innerToken, analyze); 204 266 // update Pareto-front approximation sets 205 UpdateParetoFronts();267 // UpdateParetoFronts(); 206 268 // Show some results in the GUI. 207 269 Results.AddOrUpdateResult("IdealPoint", new DoubleArray(IdealPoint)); … … 209 271 Results.AddOrUpdateResult("Evaluated Solutions", new IntValue(evaluatedSolutions)); 210 272 211 var allLayerResults = new ResultCollection(); 212 Results.AddOrUpdateResult("LayerResults", allLayerResults); 213 273 274 275 276 277 278 // see if we already have a result collection for the layer results, and reuse that one 279 ResultCollection allLayerResults; 280 if (Results.TryGetValue("LayerResults", out IResult allLayerResultsResult)) { 281 allLayerResults = (ResultCollection)allLayerResultsResult.Value; 282 } 283 else { 284 allLayerResults = new ResultCollection(); 285 Results.AddOrUpdateResult("LayerResults", allLayerResults); 286 } 287 288 289 290 291 214 292 // run layer analyzers 215 293 for (int i = 0; i < activeLayer.Length; ++i) { … … 217 295 var scope = new Scope($"Layer {i}"); 218 296 var layer = layerPopulation[i]; 219 var layerResults = new ResultCollection(); 220 allLayerResults.Add(new Result(scope.Name, layerResults)); 221 222 var problem = (MultiObjectiveTestFunctionProblem)Problem; 223 //scope.Variables.Add(new Variable("Individuals", new ItemArray<IScope>(layer.Select(x => (IScope)x.Individual)))); 224 //scope.Variables.Add(new Variable("Qualities", new ItemArray<DoubleArray>(layer.Select(x => new DoubleArray(x.Qualities))))); 225 scope.SubScopes.AddRange(layer.Select(x => (IScope)x.Individual)); 226 scope.Variables.Add(new Variable("Results", layerResults)); 227 scope.Variables.Add(new Variable("TestFunction", problem.TestFunction)); 228 var scatterPlotAnalyzer = new ScatterPlotAnalyzer(); 229 scatterPlotAnalyzer.IndividualsParameter.ActualName = "RealVector"; 230 var scattetPlotAnalyzerContext = executionContext.CreateChildOperation(scatterPlotAnalyzer, scope); 231 ExecuteOperation(executionContext, CancellationToken.None, scattetPlotAnalyzerContext); 232 scope.SubScopes.Clear(); 233 scope.Variables.Clear(); 297 var tmp = UpdateParetoFronts(layer, IdealPoint); 298 299 // update the results in a way that avoids creating a new result collection at each iteration 300 if (allLayerResults.TryGetValue(scope.Name, out IResult lRes)) { 301 var lr = (ResultCollection)lRes.Value; 302 foreach (var result in tmp) { 303 lr.AddOrUpdateResult(result.Name, result.Value); 304 } 305 } 306 else { 307 allLayerResults.AddOrUpdateResult(scope.Name, tmp); 308 } 309 310 var layerResults = (ResultCollection)allLayerResults[scope.Name].Value; 311 312 //var layerQualities = new ItemArray<DoubleArray>(layer.Select(x => new DoubleArray(x.Qualities))); 313 // var layerSolutions = new ItemArray<IItem>(layer.Select(x => (IItem)x.Individual.Clone())); 314 315 // only store the decision vectors 316 var layerSolutions = new ItemArray<IItem>(layer.Select(x => (IItem)((IScope)x.Individual).Variables["RealVector"].Value.Clone())); 317 318 var layerAges = new ItemArray<IntValue>(layer.Select(x => new IntValue(x.Age))); 319 //layerResults.AddOrUpdateResult("Objective values", layerQualities); 320 layerResults.AddOrUpdateResult("Decision vectors", layerSolutions); 321 layerResults.AddOrUpdateResult("Age", layerAges); 322 323 var tableObjectives = new DataTable("Objective values"); 324 for (int j = 0; j < IdealPoint.Length; ++j) { 325 var row = new DataRow($"Objective {j + 1}"); 326 row.Values.AddRange(layer.Select(x => x.Qualities[j])); 327 tableObjectives.Rows.Add(row); 328 } 329 layerResults.AddOrUpdateResult("Objective values", tableObjectives); 330 331 332 // historical HV 333 DataTable hyperVolumeHistory; 334 if (layerResults.TryGetValue("Layer Hypervolume History", out IResult res)) { 335 hyperVolumeHistory = (DataTable)res.Value; 336 } 337 else { 338 hyperVolumeHistory = new DataTable("Layer Hypervolume History"); 339 var hrow = new DataRow($"Layer {i}"); 340 hrow.VisualProperties = new DataRowVisualProperties { 341 StartIndexZero = false, 342 }; 343 hyperVolumeHistory.Rows.Add(hrow); 344 layerResults.AddOrUpdateResult("Layer Hypervolume History", hyperVolumeHistory); 345 } 346 //var front = layer.Select(x => x.Qualities); 347 var reference = ReferencePoint.ToArray(); 348 //var hv = double.MinValue; 349 350 var layerQualities = layer.Select(x => x.Qualities).ToArray(); 351 var layerPF = DominationCalculator<IDynamicALPSSolution>.CalculateBestParetoFront(layer, layerQualities, maximization); 352 var nondominatedLayer = NonDominatedSelect.GetDominatingVectors(layerPF.Select(x => x.Item2), reference, maximization, false); 353 var layerHV = nondominatedLayer.Any() ? Hypervolume.Calculate(nondominatedLayer, reference, maximization) : 0; 354 hyperVolumeHistory.Rows[$"Layer {i}"].Values.Add(layerHV); 355 356 357 // historical crossover probability 358 DataTable crossoverProbabilityHistory; 359 if (layerResults.TryGetValue("CrossoverProbability History", out IResult resPm)) { 360 crossoverProbabilityHistory = (DataTable)resPm.Value; 361 } 362 else { 363 crossoverProbabilityHistory = new DataTable("CrossoverProbability History"); 364 var hrowPm = new DataRow($"Layer {i}"); 365 hrowPm.VisualProperties = new DataRowVisualProperties { 366 StartIndexZero = false, 367 }; 368 crossoverProbabilityHistory.Rows.Add(hrowPm); 369 layerResults.AddOrUpdateResult("CrossoverProbability History", crossoverProbabilityHistory); 370 } 371 crossoverProbabilityHistory.Rows[$"Layer {i}"].Values.Add(layerCrossoverProbability[i]); 372 373 374 375 if (i == 1) { 376 DataTable wholeLayerHypervolumeHistrory; 377 var qualities = population.Select(x => x.Qualities).ToArray(); 378 var pf = DominationCalculator<IDynamicALPSSolution>.CalculateBestParetoFront(population, qualities, maximization); 379 var nondominatedWhole = NonDominatedSelect.GetDominatingVectors(pf.Select(x => x.Item2), reference, maximization, false); 380 var hvWhole = nondominatedWhole.Any() ? Hypervolume.Calculate(nondominatedWhole, reference, maximization) : 0; 381 if (layerResults.TryGetValue("Hypervolume of the entire layers -- History", out IResult resHVWhole)) { 382 wholeLayerHypervolumeHistrory = (DataTable)resHVWhole.Value; 383 } 384 else { 385 wholeLayerHypervolumeHistrory = new DataTable("Hypervolume of the entire layers -- History"); 386 var hrowWhole = new DataRow($"Layer {i}"); 387 hrowWhole.VisualProperties = new DataRowVisualProperties { 388 StartIndexZero = false, 389 }; 390 wholeLayerHypervolumeHistrory.Rows.Add(hrowWhole); 391 layerResults.AddOrUpdateResult("Hypervolume of the entire layers -- History", wholeLayerHypervolumeHistrory); 392 } 393 wholeLayerHypervolumeHistrory.Rows[$"Layer {i}"].Values.Add(hvWhole); 394 } 395 else { 396 } 397 234 398 } 235 399 236 400 // Update globalScope 237 401 globalScope.SubScopes.Replace(population.Select(x => (IScope)x.Individual)); 238 239 240 //// intilize the population for the next layer241 //counterLayerALPS += 1;242 //layerPopulation[counterLayerALPS] = new IDynamicALPSSolution[populationSize];243 //layerPopulation[counterLayerALPS-1].CopyTo(layerPopulation[counterLayerALPS], 0); // DETELTE DUBGU244 //// BUG lambda should be different~~~~!!!!245 //layerOffspringPopulation[counterLayerALPS] = new IDynamicALPSSolution[lambda];246 402 } 247 403 } -
branches/3057_DynamicALPS/HeuristicLab.Algorithms.DynamicALPS/3.4/DynamicALPSAlgorithmBase.cs
r17438 r17479 87 87 88 88 [Storable] 89 protected double[] layerCrossoverProbability; 90 91 [Storable] 89 92 protected IDynamicALPSSolution[][] layerDiscardPopulation; 93 94 [Storable] 95 protected IDynamicALPSSolution[] layerDiscardIndivdual; 96 90 97 91 98 [Storable] … … 116 123 protected ExecutionState executionState; 117 124 118 pr ivateDoubleArray ReferencePoint {125 protected DoubleArray ReferencePoint { 119 126 get { 120 var problem = (MultiObjectiveTestFunctionProblem)Problem; 121 return problem.ReferencePoint; 127 if (Problem is MultiObjectiveTestFunctionProblem) { 128 var problem = (MultiObjectiveTestFunctionProblem)Problem; 129 return problem.ReferencePoint; 130 } 131 else { 132 return null; 133 } 122 134 } 123 135 } … … 136 148 private const string RandomParameterName = "Random"; 137 149 private const string AnalyzerParameterName = "Analyzer"; 150 151 138 152 // MOEA-D parameters 139 153 //private const string NeighbourSizeParameterName = "NeighbourSize"; … … 147 161 private const string ALPSLayersParameterName = "ALPSLayers"; // The number of offspring size 148 162 private const string ALPSAgeGapParameterName = "ALPSAgeGap"; // The number of offspring size 163 private const string InitializeLayerPopulationMethodName = "InitializationLayerPopulations"; 149 164 150 165 … … 199 214 } 200 215 216 private IValueParameter<BoolValue> ALPSInitialzeLayerPopulationParameter { 217 get { return (IValueParameter<BoolValue>)Parameters[InitializeLayerPopulationMethodName]; } 218 } 219 220 201 221 private IValueParameter<IntValue> ResultPopulationSizeParameter { 202 222 get { return (IValueParameter<IntValue>)Parameters[ResultPopulationSizeParameterName]; } … … 258 278 get { return ALPSAgeGapParameter.Value; } 259 279 set { ALPSAgeGapParameter.Value = value; } 280 } 281 public BoolValue UseAverageAge { 282 get { return ALPSInitialzeLayerPopulationParameter.Value; } 283 set { ALPSInitialzeLayerPopulationParameter.Value = value; } 260 284 } 261 285 … … 316 340 Parameters.Add(new ValueParameter<IntValue>(MaximumEvaluatedSolutionsParameterName, "The maximum number of evaluated solutions (approximately).", new IntValue(100_000))); 317 341 Parameters.Add(new ValueParameter<IRandom>(RandomParameterName, new FastRandom())); 342 Parameters.Add(new ValueParameter<BoolValue>(InitializeLayerPopulationMethodName, "Whether use average age to initialize the layer population or not. If not, move the older individuals to layer populations", new BoolValue(true))); 318 343 319 344 // SMS-EMOA, kf … … 532 557 var qualities = wholePopulation.Select(x => x.Qualities).ToArray(); 533 558 559 var maxPoint = Enumerable.Range(0, IdealPoint.Length).Select(idx => qualities.Max(q => q[idx])).ToArray(); 560 534 561 var maximization = Enumerable.Repeat(false, IdealPoint.Length).ToArray(); // Minimization or maximization ???? 535 562 var pf2 = DominationCalculator<IDynamicALPSSolution>.CalculateAllParetoFronts(wholePopulation, qualities, maximization, out int[] ranking); … … 550 577 // TODO: This can be use for dynamic reference point strategy later. Kaifeng , 02/2020 551 578 // smetric = Hypervolume.Calculate(lastLayer.Select(x => x.Item2), Enumerable.Repeat(11d, NadirPoint.Length).ToArray(), maximization); 552 var reference = ReferencePoint.ToArray(); 579 580 var reference = Enumerable.Repeat(double.MaxValue, maximization.Length).ToArray(); // TODO Dynamic Reference point for each layer. Maximum * 1.1 581 //if (nLayerALPS != 0) { 582 for (int i = 0; i < reference.Length; i++) { 583 reference[i] = 1.1 * maxPoint[i]; 584 if (reference[i] > 10000) { 585 reference[i] = 9999; // set a upper bound for the reference point 586 } 587 } 588 //} 589 //else { 590 // reference = ReferencePoint.ToArray(); 591 //} 592 553 593 var nondominated = NonDominatedSelect.GetDominatingVectors(lastLayer.Select(x => x.Item2), reference, maximization, false); 554 594 smetric = nondominated.Any() ? Hypervolume.Calculate(nondominated, reference, maximization) : int.MinValue; … … 565 605 tempHV = 0; 566 606 } 607 567 608 discardIndex = Array.IndexOf(hvc, hvc.Min()); 609 //layerDiscardPopulation[nLayerALPS] = pf2[numberOfLayer - 1][discardIndex].Item1.ToArray(); 610 layerDiscardIndivdual[nLayerALPS] = pf2[numberOfLayer - 1].Select(x => x.Item1).ToArray()[discardIndex]; 568 611 pf2[numberOfLayer - 1].RemoveAt(discardIndex); 569 612 } 570 613 else { 571 614 // TODO: This should be updated when $lambda > 1$ 615 discardIndex = pf2.Count() - 1; 616 layerDiscardIndivdual[nLayerALPS] = pf2[discardIndex].Select(x => x.Item1).ToArray()[0]; 572 617 pf2.RemoveAt(pf2.Count() - 1); 573 618 numberOfLayer = numberOfLayer - 1; 619 574 620 } 575 621 layerPopulation[nLayerALPS] = pf2.SelectMany(x => x.Select(y => y.Item1)).ToArray(); 622 623 } 624 625 public static double SampleGaussian(IRandom random, double mean, double stddev) { 626 // The method requires sampling from a uniform random of (0,1] 627 // but Random.NextDouble() returns a sample of [0,1). 628 double x1 = 1 - random.NextDouble(); 629 double x2 = 1 - random.NextDouble(); 630 631 double y1 = Math.Sqrt(-2.0 * Math.Log(x1)) * Math.Cos(2.0 * Math.PI * x2); 632 return y1 * stddev + mean; 576 633 } 577 634 … … 581 638 var maximumEvaluatedSolutions = MaximumEvaluatedSolutions.Value; 582 639 var crossover = Crossover; 583 var crossoverProbability = CrossoverProbability.Value;640 var crossoverProbability = layerCrossoverProbability[0]; 584 641 var mutator = Mutator; 585 642 var mutationProbability = MutationProbability.Value; … … 604 661 s1.Parent = s2.Parent = globalScope; 605 662 IScope childScope = null; 663 664 // crossoverProbability = crossoverProbability - 0.02* counterLayerALPS; 665 //var test = SampleGaussian(rand, 0, 1); 666 667 //crossoverProbability = 1 / (1 + Math.Exp(-0.02 * SampleGaussian(rand, 0, 1)) * (1 - crossoverProbability) / crossoverProbability); 668 669 if (crossoverProbability < 0.5) 670 crossoverProbability = 0.5; 671 else if(crossoverProbability > 0.95) 672 { 673 crossoverProbability = 0.95; 674 } 675 layerCrossoverProbability[counterLayerALPS] = crossoverProbability; 606 676 607 677 // crossover … … 617 687 else { // MUTATION POLISHI 618 688 if (childScope == null) { 619 offSpringAge = ages[mates[0]] + 1;689 offSpringAge = ages[mates[0]]; 620 690 } 621 691 else { … … 624 694 var opMutation = executionContext.CreateChildOperation(mutator, childScope); 625 695 ExecuteOperation(executionContext, innerToken, opMutation); 696 offSpringAge = offSpringAge + 1; 626 697 } 627 698 if (childScope != null) { // Evaluate the childScope … … 663 734 664 735 665 666 // Update the Pareto-front approximation set and scatter the solutions in PF approximation set. 667 protected void UpdateParetoFronts() { 736 // Update the Pareto-front approximation set and scatter the solutions in PF approximation set. 737 protected ResultCollection UpdateParetoFronts(IDynamicALPSSolution[] solutions, double[] IdealPoint) { 738 739 668 740 //var qualities = population.Select(x => Enumerable.Range(0, NadirPoint.Length).Select(i => x.Qualities[i] / NadirPoint[i]).ToArray()).ToArray(); 669 var qualities = population.Select(x => x.Qualities).ToArray();741 var qualities = solutions.Select(x => x.Qualities).ToArray(); 670 742 var maximization = Enumerable.Repeat(false, IdealPoint.Length).ToArray(); // DynamicALPS minimizes everything internally 671 var pf = DominationCalculator<IDynamicALPSSolution>.CalculateBestParetoFront( population, qualities, maximization);672 673 var pf2 = DominationCalculator<IDynamicALPSSolution>.CalculateAllParetoFronts( population, qualities, maximization, out int[] ranking);743 var pf = DominationCalculator<IDynamicALPSSolution>.CalculateBestParetoFront(solutions, qualities, maximization); 744 745 var pf2 = DominationCalculator<IDynamicALPSSolution>.CalculateAllParetoFronts(solutions, qualities, maximization, out int[] ranking); 674 746 var n = (int)EnumerableExtensions.BinomialCoefficient(IdealPoint.Length, 2); 675 747 … … 687 759 // True: maximization problem 688 760 // False: minimization problem 689 var reference = ReferencePoint.ToArray(); 761 var reference = Enumerable.Repeat(double.MaxValue, maximization.Length).ToArray(); 762 if (ReferencePoint is null) { // KF, 20200217 -- fix no reference point on real-world applications. If No reference points in Algorithms, use 1.1 \times max objective values as the reference point 763 for (int i = 0; i < reference.Length; i++) { 764 reference[i] = 1.1 * reference[i]; 765 if (reference[i] > 10000) { 766 reference[i] = 9999; // set a upper bound for the reference point 767 } 768 } 769 } 770 else { 771 reference = ReferencePoint.ToArray(); 772 } 773 690 774 var nondominated = NonDominatedSelect.GetDominatingVectors(pf.Select(x => x.Item2), reference, maximization, false); 691 775 hypervolumes[0, 0] = nondominated.Any() ? Hypervolume.Calculate(nondominated, reference, maximization) : int.MinValue; … … 696 780 697 781 var elementNames = new List<string>() { "Pareto Front" }; 698 699 ResultCollection results; 700 if (Results.ContainsKey("Hypervolume Analysis")) { 701 results = (ResultCollection)Results["Hypervolume Analysis"].Value; 782 var results = new ResultCollection(); 783 784 ResultCollection innerResults; 785 if (results.ContainsKey("Hypervolume Analysis")) { 786 innerResults = (ResultCollection)results["Hypervolume Analysis"].Value; 702 787 } 703 788 else { 704 results = new ResultCollection();705 Results.AddOrUpdateResult("Hypervolume Analysis", results);789 innerResults = new ResultCollection(); 790 results.AddOrUpdateResult("Hypervolume Analysis", innerResults); 706 791 } 707 792 … … 712 797 if (error != OnlineCalculatorError.None) { r = double.NaN; } 713 798 var resultName = "Pareto Front Analysis "; 714 if (! results.ContainsKey(resultName)) {799 if (!innerResults.ContainsKey(resultName)) { 715 800 sp = new ScatterPlot() { 716 VisualProperties = {717 XAxisMinimumAuto = false, XAxisMinimumFixedValue = 0d, XAxisMaximumAuto = false, XAxisMaximumFixedValue = 1d,718 YAxisMinimumAuto = false, YAxisMinimumFixedValue = 0d, YAxisMaximumAuto = false, YAxisMaximumFixedValue = 1d719 }801 //VisualProperties = { 802 // XAxisMinimumAuto = true, XAxisMinimumFixedValue = 0d, XAxisMaximumAuto = false, XAxisMaximumFixedValue = 1d, 803 // YAxisMinimumAuto = true, YAxisMinimumFixedValue = 0d, YAxisMaximumAuto = false, YAxisMaximumFixedValue = 1d 804 //} 720 805 }; 721 806 sp.Rows.Add(new ScatterPlotDataRow(resultName, "", points) { VisualProperties = { PointSize = 8 } }); 722 results.AddOrUpdateResult(resultName, sp);807 innerResults.AddOrUpdateResult(resultName, sp); 723 808 } 724 809 else { 725 sp = (ScatterPlot) results[resultName].Value;810 sp = (ScatterPlot)innerResults[resultName].Value; 726 811 sp.Rows[resultName].Points.Replace(points); 727 812 } … … 751 836 var pf2dPoints = pf2d.Select(x => new Point2D<double>(x.Item2[0], x.Item2[1])); 752 837 753 if (! results.ContainsKey(resultName)) {838 if (!innerResults.ContainsKey(resultName)) { 754 839 sp = new ScatterPlot() { 755 840 VisualProperties = { … … 760 845 sp.Rows.Add(new ScatterPlotDataRow("Pareto Front", "", points) { VisualProperties = visualProperties }); 761 846 sp.Rows.Add(new ScatterPlotDataRow($"Pareto Front [{c[0]}, {c[1]}]", "", pf2dPoints) { VisualProperties = { PointSize = 10, Color = Color.OrangeRed } }); 762 results.AddOrUpdateResult(resultName, sp);847 innerResults.AddOrUpdateResult(resultName, sp); 763 848 } 764 849 else { 765 sp = (ScatterPlot) results[resultName].Value;850 sp = (ScatterPlot)innerResults[resultName].Value; 766 851 sp.Rows["Pareto Front"].Points.Replace(points); 767 852 sp.Rows[$"Pareto Front [{c[0]}, {c[1]}]"].Points.Replace(pf2dPoints); … … 773 858 } 774 859 hypervolumes.RowNames = elementNames; 775 results.AddOrUpdateResult("Hypervolumes", hypervolumes); 860 innerResults.AddOrUpdateResult("Hypervolumes", hypervolumes); 861 862 return results; 776 863 } 777 864
Note: See TracChangeset
for help on using the changeset viewer.