Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
07/11/19 16:30:22 (5 years ago)
Author:
msemenki
Message:

#2988:

  1. The file system was changed, folders was added and part of files was transferred in these folders.
  2. HelpFunctions class was divided on 2 parts: HelpFuctions for common purposes static functions and SelfConfiguration that include functions for self-configuration mechanism realization (is used in EMMSucsessMap).
  3. Parts of self-configuration mechanism was transferred from EMMSucsessMap.cs to SelfConfiguration.cs. Now EMMSucsessMap used SelfConfiguration like one of data member. Other parts of project was adopted for this changing.
  4. FileComunication class was added. It include the majority of functions for printing to files or reading from files. Here were realized possibility to write and read to hl files.
  5. ModelTreeNode.cs has additional possibility - to write sub-model in string (then it is possible to write it in file).
  6. InfixExpressionFormatter.cs can work with TreeModelNode.
  7. Possibility for different map types to be readable from files was extended and cheeked.
  8. Such parameters like - ClusterNumbers, ClusterNumbersShow, NegbourNumber, NegbourType (that is used only in several maps) was transferred from EMMAlgorithm to Map Parameters. Now EMMBaseMap class inherited from ParameterizedNamedItem (not from Item). And EMMIslandMap and EMMNetworkMap contains their parameters (constructors was modified). CreationMap calls functions were simplified.
  9. Functions for different distance metric calculation was added. Now, it is possible to calculate different types of distances between models (with different random values of constants).
  10. DistanceParametr was added. Now maps can be created according different types of distance calculations.
  11. The class EMMClustering has new name KMeansClusterizationAlgorithm. On KMeansClusterizationAlgorithm bug with bloating of centroids list was fixed. Algorithm was adopted for working with different type of distance metric and get maximum number of iterations.
  12. Possibilities for constants optimization in sub-models an whole tree was added. EMMAlgorithm get new function for evaluation of individuals (and some additional technical stuff for that). Function for trees with model in usual tree transformation and back was added.
  13. EMMAlgorithm was divided on 2 parts:
  • EMMAlgorithm, that contain evolutionary algorithm working with sub-models, and use ready to use maps;
  • ModelSetPreparation, that contain distance calculation, model set simplification and map creation.
Location:
branches/2988_ModelsOfModels2/HeuristicLab.Algorithms.EMM/EMMAlgorithm
Files:
1 added
1 moved

Legend:

Unmodified
Added
Removed
  • branches/2988_ModelsOfModels2/HeuristicLab.Algorithms.EMM/EMMAlgorithm/EMMAlgorithm.cs

    r17133 r17134  
    2525using HeuristicLab.Data;
    2626using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
     27using HeuristicLab.Problems.DataAnalysis;
    2728using HeuristicLab.Problems.DataAnalysis.Symbolic;
     29using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
    2830using HeuristicLab.Random;
    2931using HeuristicLab.Selection;
     
    3436
    3537namespace HeuristicLab.Algorithms.EvolvmentModelsOfModels {
    36   [Item("Evolvment Models Of Models Algorithm (EMM) ", "EMM implementation")]
     38  [Item("Evolvement Models Of Models Algorithm (EMM) ", "EMM implementation")]
    3739  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms, Priority = 125)]
    3840  [StorableType("AD23B21F-089A-4C6C-AD2E-1B01E7939CF5")]
    3941  public class EMMAlgorithm : EvolvmentModelsOfModelsAlgorithmBase {
     42    #region Constructors
    4043    public EMMAlgorithm() : base() { }
    4144    protected EMMAlgorithm(EMMAlgorithm original, Cloner cloner) : base(original, cloner) { }
     
    4649    [StorableConstructor]
    4750    protected EMMAlgorithm(StorableConstructorFlag _) : base(_) { }
    48 
     51    #endregion
     52    #region Algorithm run
    4953    protected override void Run(CancellationToken cancellationToken) {
     54
     55      Map.DistanceParametr = DistanceType.Value;
     56
    5057      if (AlgorithmImplemetationType.Value == "Read") {
    51         Map.MapRead(RandomParameter.Value, trees, "Map.txt");
     58        Map.MapRead(trees);
    5259      } else {
    5360        Map.MapCreationPrepare(trees);
    54         Map.CreateMap(RandomParameter.Value, ClusterNumbersParameter.Value.Value);
    55         // Map.WriteMapToTxtFile(RandomParameter.Value); хайв этого не любит.. ворчит
    56       }
    57       ClusterNumbersShowParameter.Value.Value = Map.Map.Count;
    58 
    59       if (AlgorithmImplemetationType.Value == "OnlyMap") {
    60         globalScope = new Scope("Global Scope");
    61         executionContext = new ExecutionContext(null, this, globalScope);
    62       } else {
    63         if (previousExecutionState != ExecutionState.Paused) {
    64           InitializeAlgorithm(cancellationToken);
    65         }
    66         if (!globalScope.Variables.ContainsKey("TreeModelMap"))
    67           globalScope.Variables.Add(new Variable("TreeModelMap", Map));
    68         if (!globalScope.Variables.ContainsKey("Map"))
    69           globalScope.Variables.Add(new Variable("Map", Map));
    70         EMMAlgorithmRun(cancellationToken);
    71       }
     61        Map.CreateMap(RandomParameter.Value, Problem);
     62      }
     63      if (previousExecutionState != ExecutionState.Paused) {
     64        InitializeAlgorithm(cancellationToken);
     65      }
     66      if (!globalScope.Variables.ContainsKey("TreeModelMap"))
     67        globalScope.Variables.Add(new Variable("TreeModelMap", Map));
     68      if (!globalScope.Variables.ContainsKey("Map"))
     69        globalScope.Variables.Add(new Variable("Map", Map));
     70      EMMAlgorithmRun(cancellationToken);
    7271    }
    7372    private void EMMAlgorithmRun(CancellationToken cancellationToken) {
     
    8887      var rand = RandomParameter.Value;
    8988      var elites = Elites.Value;
    90 
    91       // cancellation token for the inner operations which should not be immediately cancelled
     89      var fmd = new InfixExpressionFormatter();
     90      // cancellation token for the inner operations which should not be immediately canceled
    9291      var innerToken = new CancellationToken();
     92      // for future
     93      //var mutatorTypes = new SymbolicExpressionTreeManipulator[]
     94      //{
     95      //     new EMMMultyPointsMutator(),
     96      //     new EMMMultyPointsMutatorNodeTypeSaving (),
     97      //     new EMMMutators()
     98      //};
     99      //var tuu = MutatorParameter.ValidValues;
     100      //var select = SelectorParameter.ValidValues;
    93101
    94102      while (EvaluatedSolutions < maximumEvaluatedSolutions && !cancellationToken.IsCancellationRequested) {
     
    113121
    114122        for (int i = 0; i < selector.NumberOfSelectedSubScopesParameter.Value.Value; i += 2) {
    115           // crossover
    116123          IScope childScope = null;
     124          // for future
     125          //var obbbb = CrossoverParameter.ValidValues.ToList();
     126          //int nn = 3;
     127          //if (rand.NextDouble() < crossoverProbability) {
     128          //  childScope = new Scope($"{i}+{i + 1}") { Parent = executionContext.Scope };
     129          //  childScope.SubScopes.Add(selected.SubScopes[i]);
     130          //  childScope.SubScopes.Add(selected.SubScopes[i + 1]);
     131          //  var op1 = executionContext.CreateChildOperation(obbbb[nn], childScope);
     132          //  ExecuteOperation(executionContext, innerToken, op1);
     133          //  childScope.SubScopes.Clear();
     134          //}
     135
    117136          if (rand.NextDouble() < crossoverProbability) {
    118137            childScope = new Scope($"{i}+{i + 1}") { Parent = executionContext.Scope };
     
    133152          // evaluation
    134153          if (childScope != null) {
    135             var op3 = executionContext.CreateChildOperation(evaluator, childScope);
    136             ExecuteOperation(executionContext, innerToken, op3);
    137             //if (Problem.ProblemData is IRegressionProblemData problemData) {
    138             //  SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(Problem.SymbolicExpressionTreeInterpreter, (ISymbolicExpressionTree)childScope.Variables["SymbolicExpressionTree"].Value, problemData, problemData.TestIndices, true, 100 /*max iterration*/, true);
    139             //}
    140             ++EvaluatedSolutions;
    141             Population.Add(new EMMSolution(childScope));
     154            if (!childScope.Variables.ContainsKey("Quality"))
     155              childScope.Variables.Add(new Variable("Quality"));
     156            EvaluationComplex(executionContext, innerToken, childScope);
    142157          } else {// no crossover or mutation were applied, a child was not produced, do nothing
    143158            Population.Add(new EMMSolution(selected.SubScopes[i]));
     
    146161            break;
    147162          }
    148 
    149         }
    150         if (Map is EMMSucsessMap) {
    151           var population = new Dictionary<ISymbolicExpressionTree, double>();
    152           foreach (var individ in Population) {
    153             var tree = (ISymbolicExpressionTree)(((IScope)individ.Individual).Variables["SymbolicExpressionTree"].Value);
    154             population.Add(tree, individ.Qualities.Value);
    155           }
    156           Map.MapUpDate(population);
    157           population.Clear();
    158         }
    159         //List<object> A = new List<object>();
    160         //A.Add(new Scope ());
    161         //A.Add(new SymbolicExpressionTree());
     163        }
     164
     165        UpDateParameters();
    162166
    163167        globalScope.SubScopes.Replace(Population.Select(x => (IScope)x.Individual));
     
    165169        var analyze = executionContext.CreateChildOperation(analyzer, globalScope);
    166170        ExecuteOperation(executionContext, innerToken, analyze);
     171
    167172        Results.AddOrUpdateResult("Evaluated Solutions", new IntValue(EvaluatedSolutions));
    168173      }
    169174    }
     175    protected virtual void UpDateParameters() {
     176      if (Map is EMMSucsessMap) {
     177        var population = new Dictionary<ISymbolicExpressionTree, double>();
     178        foreach (var individ in Population) {
     179          var tree = (ISymbolicExpressionTree)(((IScope)individ.Individual).Variables["SymbolicExpressionTree"].Value);
     180          population.Add(tree, individ.Qualities.Value);
     181        }
     182        Map.MapUpDate(population);
     183        population.Clear();
     184      }
     185    }
     186    #endregion
     187    #region Initialization
    170188    protected void InitializeAlgorithm(CancellationToken cancellationToken) {
    171189      globalScope = new Scope("Global Scope");
     
    181199      if (SetSeedRandomly) Seed = RandomSeedGenerator.GetSeed();
    182200      rand.Reset(Seed);
    183 
     201      EvaluatedSolutions = 0;
     202      //  InitializeParametrs(); for future
    184203      InitializePopulation(executionContext, cancellationToken, rand);
    185       EvaluatedSolutions = PopulationSize.Value;
     204
    186205
    187206      base.Initialize(cancellationToken);
    188207    }
     208    protected virtual void InitializeParametrs() { }
    189209
    190210    private void InitializePopulation(ExecutionContext executionContext, CancellationToken cancellationToken, IRandom random) {
    191211      Population = new List<IEMMSolution>();
     212      var fmd = new InfixExpressionFormatter();
    192213      var evaluator = Problem.Evaluator;
    193214      var creator = Problem.SolutionCreator;
     215      var parser = new InfixExpressionParser();
     216
    194217      var parentScope = executionContext.Scope; //main scope for the next step work
    195218                                                // first, create all individuals
     
    199222        var name = ((ISymbolicExpressionTreeCreator)creator).SymbolicExpressionTreeParameter.ActualName;
    200223        var tree = (ISymbolicExpressionTree)childScope.Variables[name].Value;
     224
    201225        foreach (var node in tree.IterateNodesPostfix().OfType<TreeModelTreeNode>()) {
    202226          Map.NodeManipulationForInizializtion(random, node);
     
    207231      for (int i = 0; i < PopulationSize.Value; ++i) {
    208232        var childScope = parentScope.SubScopes[i];
    209         ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(evaluator, childScope));
    210         Population.Add(new EMMSolution(childScope));  // Create solution and push individual inside. push solution to Population
    211       }
    212     }
    213 
     233        if (!childScope.Variables.ContainsKey("Quality"))
     234          childScope.Variables.Add(new Variable("Quality", new DoubleValue(0)));
     235        EvaluationComplex(executionContext, cancellationToken, childScope);
     236      }
     237    }
     238    #endregion
     239    #region Evaluators
     240    private void EvaluationComplex(ExecutionContext executionContext, CancellationToken cancellationToken, IScope childScope) {
     241      var evaluator = Problem.Evaluator;
     242      if (evaluator is SymbolicRegressionConstantOptimizationEvaluator eval) {
     243        var creator = Problem.SolutionCreator;
     244        var name = ((ISymbolicExpressionTreeCreator)creator).SymbolicExpressionTreeParameter.ActualName;
     245        var tree = (ISymbolicExpressionTree)childScope.Variables[name].Value;
     246        var treeWithModelInside = ModelToTreePusher(tree);
     247
     248        //ExecuteOperation(executionContext, cancellationToken, executionContext.CreateChildOperation(evaluator, treeScope));
     249        var pd = (IRegressionProblemData)Problem.ProblemData;
     250        var estimationLimits = ((SymbolicRegressionSingleObjectiveProblem)Problem).EstimationLimits;
     251        var interpreter = new SymbolicDataAnalysisExpressionTreeBatchInterpreter();
     252        var quality = SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, treeWithModelInside, pd, pd.TrainingIndices, applyLinearScaling: true, maxIterations: 10, updateVariableWeights: true, lowerEstimationLimit: estimationLimits.Lower, upperEstimationLimit: estimationLimits.Upper, updateConstantsInTree: true);
     253        childScope.Variables["Quality"].Value = new DoubleValue(quality);
     254
     255        int index = 0;
     256        ConstuntValuesInTreeUpdate(tree, ConstantValuesFromTreeToListExtruction(treeWithModelInside), ref index);
     257        childScope.Variables[name].Value = tree;
     258        EvaluatedSolutions += 10;
     259      } else {
     260        var op3 = executionContext.CreateChildOperation(evaluator, childScope);
     261        ExecuteOperation(executionContext, cancellationToken, op3);
     262        EvaluatedSolutions += 1;
     263      }
     264      Population.Add(new EMMSolution(childScope));
     265    }
     266    private ISymbolicExpressionTree ModelToTreePusher(ISymbolicExpressionTree tree) {
     267      //All model nodes in tree are exchange to trees that are stored in model nodes.
     268      // After this function we have deal with usual tree
     269      var clone = (ISymbolicExpressionTree)tree.Clone();
     270      foreach (var node in clone.IterateNodesPostfix().OfType<TreeModelTreeNode>()) {
     271        var newChild = node.Tree.Root.GetSubtree(0).GetSubtree(0);
     272        Swap(node, newChild);
     273      }
     274      return clone;
     275    }
     276    protected static void Swap(ISymbolicExpressionTreeNode oldChild, ISymbolicExpressionTreeNode newChild) {
     277      var parent = oldChild.Parent;
     278      if (parent == null)
     279        return;
     280
     281      var index = parent.IndexOfSubtree(oldChild);
     282      parent.RemoveSubtree(index);
     283      parent.InsertSubtree(index, newChild);
     284    }
     285    private List<double> ConstantValuesFromTreeToListExtruction(ISymbolicExpressionTree tree) {
     286      //This function stored in a list all constants and coefficients from the tree
     287      var constants = new List<double>();
     288      foreach (var node in tree.IterateNodesPostfix()) {
     289        if (node is ConstantTreeNode cNode) {
     290          constants.Add(cNode.Value);
     291        }
     292        if (node is VariableTreeNode vNode) {
     293          constants.Add(vNode.Weight);
     294        }
     295      }
     296      return constants;
     297    }
     298    private void ConstuntValuesInTreeUpdate(ISymbolicExpressionTree tree, List<double> constants, ref int index) {
     299      foreach (var node in tree.IterateNodesPostfix()) {
     300        if (node is ConstantTreeNode cNode) {
     301          cNode.Value = constants[index];
     302          index++;
     303        } else if (node is VariableTreeNode vNode) {
     304          vNode.Weight = constants[index];
     305          index++;
     306        } else if (node is TreeModelTreeNode mNode) {
     307          ConstuntValuesInTreeUpdate(mNode.Tree, constants, ref index);
     308        }
     309
     310      }
     311    }
     312    #endregion
     313    #region Local Search
    214314    // next function was not tested in real work
    215315    private void LocalDecent(ISymbolicDataAnalysisSingleObjectiveProblem problem, CancellationToken cancellationToken, IScope childScope) {
     
    257357      }
    258358    }
     359    #endregion
    259360  }
    260361
Note: See TracChangeset for help on using the changeset viewer.