Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
03/17/20 16:29:48 (5 years ago)
Author:
kyang
Message:

#3057

  1. upload the latest version of ALPS with SMS-EMOA
  2. upload the related dynamic test problems (dynamic, single-objective symbolic regression), written by David Daninel.
Location:
branches/3057_DynamicALPS
Files:
109 added
3 edited

Legend:

Unmodified
Added
Removed
  • branches/3057_DynamicALPS/HeuristicLab.Algorithms.DynamicALPS/3.4/DynamicALPSASolution.cs

    r17438 r17479  
    115115    {
    116116      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      }
    121127    }
    122128
  • branches/3057_DynamicALPS/HeuristicLab.Algorithms.DynamicALPS/3.4/DynamicALPSAlgorithm.cs

    r17438 r17479  
    120120
    121121      // 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 };
    123124      int[] numberDiscard = new int[10];
    124125
     
    126127
    127128      activeLayer = new bool[nLayerALPS];
     129      layerCrossoverProbability = new double[nLayerALPS];
    128130      int[][] ageMatrix = new int[nLayerALPS][];      // layer * population size
    129131
     
    132134      // cancellation token for the inner operations which should not be immediately cancelled
    133135      var innerToken = new CancellationToken();
    134 
    135 
    136       // run some analyzer on each layer (for now calculate scatter plots )
    137       List<Tuple<int, ScatterPlotAnalyzer>> layerAnalyzers;
    138136
    139137
     
    143141      layerJointPopulation = new IDynamicALPSSolution[nLayerALPS][];
    144142      layerDiscardPopulation = new IDynamicALPSSolution[nLayerALPS][];
     143      layerDiscardIndivdual = new IDynamicALPSSolution[nLayerALPS];
    145144
    146145
     
    148147      // BUG: The size of offspring should vary in different layers!!!!
    149148      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
    150150      layerDiscardPopulation[counterLayerALPS] = new IDynamicALPSSolution[populationSize];
    151151      population.CopyTo(layerPopulation[counterLayerALPS], 0);
    152152
    153153      activeLayer[counterLayerALPS] = true;
     154      layerCrossoverProbability[counterLayerALPS] = 0;
     155      var test = UseAverageAge.Value;
    154156      for (int i = 0; i < nLayerALPS; i++) {
    155157        if (i == 0) {
     
    158160        else { activeLayer[i] = false; }
    159161        numberDiscard[i] = 0;
     162        layerCrossoverProbability[i] = CrossoverProbability.Value;
    160163      }
    161 
     164      int bottomLayerIDX = 0;
     165      int godScope = 0;
    162166      // Mainloop
    163167      while (evaluatedSolutions < maximumEvaluatedSolutions && !cancellationToken.IsCancellationRequested) {
    164168        for (int i = 0; i < nLayerALPS; i++) {            // loop for every layer
    165169          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
    168181            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;
    180230                }
    181231                else {
     
    184234              }
    185235              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 HVC
    189                 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;
    190240              }
    191241            }
    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            }
    193245          }
    194246          else {
    195247            // Some thing wrong? lol nothing wrong here ^_^
    196248          }
    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        }
    199261
    200262
     
    203265        ExecuteOperation(executionContext, innerToken, analyze);
    204266        // update Pareto-front approximation sets
    205         UpdateParetoFronts();
     267        // UpdateParetoFronts();
    206268        // Show some results in the GUI.
    207269        Results.AddOrUpdateResult("IdealPoint", new DoubleArray(IdealPoint));
     
    209271        Results.AddOrUpdateResult("Evaluated Solutions", new IntValue(evaluatedSolutions));
    210272
    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
    214292        // run layer analyzers
    215293        for (int i = 0; i < activeLayer.Length; ++i) {
     
    217295          var scope = new Scope($"Layer {i}");
    218296          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
    234398        }
    235399
    236400        // Update globalScope
    237401        globalScope.SubScopes.Replace(population.Select(x => (IScope)x.Individual));
    238 
    239 
    240         //// intilize the population for the next layer
    241         //counterLayerALPS += 1;
    242         //layerPopulation[counterLayerALPS] = new IDynamicALPSSolution[populationSize];
    243         //layerPopulation[counterLayerALPS-1].CopyTo(layerPopulation[counterLayerALPS], 0); // DETELTE DUBGU
    244         //// BUG lambda should be different~~~~!!!!
    245         //layerOffspringPopulation[counterLayerALPS] = new IDynamicALPSSolution[lambda];
    246402      }
    247403    }
  • branches/3057_DynamicALPS/HeuristicLab.Algorithms.DynamicALPS/3.4/DynamicALPSAlgorithmBase.cs

    r17438 r17479  
    8787
    8888    [Storable]
     89    protected double[] layerCrossoverProbability;
     90
     91    [Storable]
    8992    protected IDynamicALPSSolution[][] layerDiscardPopulation;
     93
     94    [Storable]
     95    protected IDynamicALPSSolution[] layerDiscardIndivdual;
     96   
    9097
    9198    [Storable]
     
    116123    protected ExecutionState executionState;
    117124
    118     private DoubleArray ReferencePoint {
     125    protected DoubleArray ReferencePoint {
    119126      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        }
    122134      }
    123135    }
     
    136148    private const string RandomParameterName = "Random";
    137149    private const string AnalyzerParameterName = "Analyzer";
     150   
     151   
    138152    // MOEA-D parameters
    139153    //private const string NeighbourSizeParameterName = "NeighbourSize";
     
    147161    private const string ALPSLayersParameterName = "ALPSLayers";   // The number of offspring size
    148162    private const string ALPSAgeGapParameterName = "ALPSAgeGap";   // The number of offspring size
     163    private const string InitializeLayerPopulationMethodName = "InitializationLayerPopulations";
    149164
    150165
     
    199214    }
    200215
     216    private IValueParameter<BoolValue> ALPSInitialzeLayerPopulationParameter {
     217      get { return (IValueParameter<BoolValue>)Parameters[InitializeLayerPopulationMethodName]; }
     218    }
     219   
     220
    201221    private IValueParameter<IntValue> ResultPopulationSizeParameter {
    202222      get { return (IValueParameter<IntValue>)Parameters[ResultPopulationSizeParameterName]; }
     
    258278      get { return ALPSAgeGapParameter.Value; }
    259279      set { ALPSAgeGapParameter.Value = value; }
     280    }
     281    public BoolValue UseAverageAge {
     282      get { return ALPSInitialzeLayerPopulationParameter.Value; }
     283      set { ALPSInitialzeLayerPopulationParameter.Value = value; }
    260284    }
    261285
     
    316340      Parameters.Add(new ValueParameter<IntValue>(MaximumEvaluatedSolutionsParameterName, "The maximum number of evaluated solutions (approximately).", new IntValue(100_000)));
    317341      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)));
    318343
    319344      // SMS-EMOA, kf
     
    532557      var qualities = wholePopulation.Select(x => x.Qualities).ToArray();
    533558
     559      var maxPoint = Enumerable.Range(0, IdealPoint.Length).Select(idx => qualities.Max(q => q[idx])).ToArray();
     560
    534561      var maximization = Enumerable.Repeat(false, IdealPoint.Length).ToArray(); // Minimization or maximization ????
    535562      var pf2 = DominationCalculator<IDynamicALPSSolution>.CalculateAllParetoFronts(wholePopulation, qualities, maximization, out int[] ranking);
     
    550577        // TODO: This can be use for dynamic reference point strategy later. Kaifeng , 02/2020
    551578        // 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
    553593        var nondominated = NonDominatedSelect.GetDominatingVectors(lastLayer.Select(x => x.Item2), reference, maximization, false);
    554594        smetric = nondominated.Any() ? Hypervolume.Calculate(nondominated, reference, maximization) : int.MinValue;
     
    565605          tempHV = 0;
    566606        }
     607
    567608        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];
    568611        pf2[numberOfLayer - 1].RemoveAt(discardIndex);
    569612      }
    570613      else {
    571614        // TODO: This should be updated when $lambda > 1$
     615        discardIndex = pf2.Count() - 1;
     616        layerDiscardIndivdual[nLayerALPS] = pf2[discardIndex].Select(x => x.Item1).ToArray()[0];
    572617        pf2.RemoveAt(pf2.Count() - 1);
    573618        numberOfLayer = numberOfLayer - 1;
     619       
    574620      }
    575621      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;
    576633    }
    577634
     
    581638      var maximumEvaluatedSolutions = MaximumEvaluatedSolutions.Value;
    582639      var crossover = Crossover;
    583       var crossoverProbability = CrossoverProbability.Value;
     640      var crossoverProbability = layerCrossoverProbability[0];
    584641      var mutator = Mutator;
    585642      var mutationProbability = MutationProbability.Value;
     
    604661      s1.Parent = s2.Parent = globalScope;
    605662      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;
    606676
    607677      // crossover
     
    617687      else { // MUTATION   POLISHI
    618688        if (childScope == null) {
    619           offSpringAge = ages[mates[0]] + 1;
     689          offSpringAge = ages[mates[0]];
    620690        }
    621691        else {
     
    624694        var opMutation = executionContext.CreateChildOperation(mutator, childScope);
    625695        ExecuteOperation(executionContext, innerToken, opMutation);
     696        offSpringAge = offSpringAge + 1;
    626697      }
    627698      if (childScope != null) { // Evaluate the childScope
     
    663734
    664735
    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
    668740      //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();
    670742      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);
    674746      var n = (int)EnumerableExtensions.BinomialCoefficient(IdealPoint.Length, 2);
    675747
     
    687759      //               True:  maximization problem
    688760      //               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
    690774      var nondominated = NonDominatedSelect.GetDominatingVectors(pf.Select(x => x.Item2), reference, maximization, false);
    691775      hypervolumes[0, 0] = nondominated.Any() ? Hypervolume.Calculate(nondominated, reference, maximization) : int.MinValue;
     
    696780
    697781      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;
    702787      }
    703788      else {
    704         results = new ResultCollection();
    705         Results.AddOrUpdateResult("Hypervolume Analysis", results);
     789        innerResults = new ResultCollection();
     790        results.AddOrUpdateResult("Hypervolume Analysis", innerResults);
    706791      }
    707792
     
    712797        if (error != OnlineCalculatorError.None) { r = double.NaN; }
    713798        var resultName = "Pareto Front Analysis ";
    714         if (!results.ContainsKey(resultName)) {
     799        if (!innerResults.ContainsKey(resultName)) {
    715800          sp = new ScatterPlot() {
    716             VisualProperties = {
    717               XAxisMinimumAuto = false, XAxisMinimumFixedValue = 0d, XAxisMaximumAuto = false, XAxisMaximumFixedValue = 1d,
    718               YAxisMinimumAuto = false, YAxisMinimumFixedValue = 0d, YAxisMaximumAuto = false, YAxisMaximumFixedValue = 1d
    719             }
     801            //VisualProperties = {
     802            //  XAxisMinimumAuto = true, XAxisMinimumFixedValue = 0d, XAxisMaximumAuto = false, XAxisMaximumFixedValue = 1d,
     803            //  YAxisMinimumAuto = true, YAxisMinimumFixedValue = 0d, YAxisMaximumAuto = false, YAxisMaximumFixedValue = 1d
     804            //}
    720805          };
    721806          sp.Rows.Add(new ScatterPlotDataRow(resultName, "", points) { VisualProperties = { PointSize = 8 } });
    722           results.AddOrUpdateResult(resultName, sp);
     807          innerResults.AddOrUpdateResult(resultName, sp);
    723808        }
    724809        else {
    725           sp = (ScatterPlot)results[resultName].Value;
     810          sp = (ScatterPlot)innerResults[resultName].Value;
    726811          sp.Rows[resultName].Points.Replace(points);
    727812        }
     
    751836          var pf2dPoints = pf2d.Select(x => new Point2D<double>(x.Item2[0], x.Item2[1]));
    752837
    753           if (!results.ContainsKey(resultName)) {
     838          if (!innerResults.ContainsKey(resultName)) {
    754839            sp = new ScatterPlot() {
    755840              VisualProperties = {
     
    760845            sp.Rows.Add(new ScatterPlotDataRow("Pareto Front", "", points) { VisualProperties = visualProperties });
    761846            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);
    763848          }
    764849          else {
    765             sp = (ScatterPlot)results[resultName].Value;
     850            sp = (ScatterPlot)innerResults[resultName].Value;
    766851            sp.Rows["Pareto Front"].Points.Replace(points);
    767852            sp.Rows[$"Pareto Front [{c[0]}, {c[1]}]"].Points.Replace(pf2dPoints);
     
    773858      }
    774859      hypervolumes.RowNames = elementNames;
    775       results.AddOrUpdateResult("Hypervolumes", hypervolumes);
     860      innerResults.AddOrUpdateResult("Hypervolumes", hypervolumes);
     861
     862      return results;
    776863    }
    777864
Note: See TracChangeset for help on using the changeset viewer.