Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2988_ModelsOfModels2/HeuristicLab.Algorithms.EMM/EMMBaseMap.cs @ 17002

Last change on this file since 17002 was 17002, checked in by msemenki, 3 years ago

#2988:
Class HelpFuction get new static functions that are used in different Map’s classes and possible in other classes.
Branch was adapted to Hive.
New version of class structure for Maps:

  1. 3 new variants of maps (RankMap, SuccessMap and ZeroMap) are added.
  2. BaseMap class was simplified, some class members were deleted and other were transported to child class, because some of them are not used in all kinds of maps.
  3. Functions between base class and child class were divided in other way.
  4. Mutation operators were adapted to work with new class structure. Now mutation make less work for ModelNodes than previously.
  5. ModelNode and Model symbols were simplified. They should not take into account a map type.
  6. Models frequency analyzers were adapted for new variants of maps.
  7. EMMAlgorithm class was adapted to new maps
File size: 7.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using HEAL.Attic;
23using HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
26using HeuristicLab.Problems.DataAnalysis.Symbolic;
27using HeuristicLab.Random;
28using System.Collections.Generic;
29using System.IO;
30using System.Linq;
31
32namespace HeuristicLab.Algorithms.EvolvmentModelsOfModels {
33  [StorableType("83CF9650-98FF-454B-9072-82EA4D39C752")]
34  public abstract class EMMMapBase<T> : Item where T : class {
35    #region data members
36    [Storable]
37    public List<T> ModelSet { get; set; }
38    [Storable]
39    public List<List<int>> Map { get; set; }
40    #endregion
41    #region constructors
42    [StorableConstructor]
43    protected EMMMapBase(StorableConstructorFlag _) : base(_) { }
44    public EMMMapBase() {
45      Map = new List<List<int>>();
46    }
47    public EMMMapBase(EMMMapBase<T> original, Cloner cloner) {
48      if (original.ModelSet != null) {
49        if (original.ModelSet is List<ISymbolicExpressionTree> originalSet && ModelSet is List<ISymbolicExpressionTree> set)
50          set = originalSet.Select(cloner.Clone).ToList();
51        else ModelSet = original.ModelSet.ToList(); /// check this if you want to use it
52      }
53      if (original.Map != null) {
54        Map = original.Map.Select(x => x.ToList()).ToList();
55      }
56    }
57    #endregion
58    #region map creation functions
59    protected double[,] CalculateDistances() {
60      double[,] distances;
61      if (ModelSet is List<ISymbolicExpressionTree> set) {
62        distances = SymbolicExpressionTreeHash.ComputeSimilarityMatrix(set, simplify: false, strict: true);
63      } else { /// for future work
64        distances = new double[ModelSet.Count, ModelSet.Count];
65        for (int i = 0; i < ModelSet.Count - 1; i++) {
66          for (int j = 0; j <= i; j++) {
67            distances[i, j] = 0;
68          }
69        }
70      }
71      for (int i = 0; i < ModelSet.Count - 1; i++) {
72        for (int j = i + 1; j < ModelSet.Count; j++) {
73          distances[j, i] = distances[i, j] = 1 - distances[i, j];
74        }
75      }
76      return distances;
77    }
78    public abstract void CreateMap(IRandom random, int k);
79    public void MapCreationPrepare(IEnumerable<T> trees) {
80      ModelSet = trees.ToList();
81    }
82
83    protected void MapSizeCheck(int k) {
84      if (Map != null) Map.Clear();
85      else Map = new List<List<int>>();
86      if (Map.Count != k) {
87        if (Map.Count != 0) {
88          Map.Clear();
89        }
90        for (int i = 0; i < k; i++) {
91          Map.Add(new List<int>());
92        }
93      }
94    }
95    #endregion
96    #region map and files
97    public void MapRead(IRandom random, IEnumerable<T> trees, string fileName = "Map.txt") {
98      ModelSet = trees.ToList();
99      MapFromFileRead(fileName);
100      if (this is EMMIslandMap island) { island.ClusterNumbersCalculate(); }
101      if (this is EMMNetworkMap one) { one.NeghboorNumber = Map[0].Count; }
102    }
103    public void WriteMapToTxtFile(IRandom random) {
104      string s = random.ToString();
105      string fileName = "Map";
106      fileName += s;
107      fileName += ".txt";
108      File.WriteAllLines(fileName, MapToString());
109      string fileName2 = "MapToSee";
110      fileName2 += s;
111      fileName2 += ".txt";
112      File.WriteAllLines(fileName2, MapToSee());
113    }
114    public string[] MapToString() { // Function that preapre Map to printing in .txt File: create a set of strings for future reading by computer
115      string[] s;
116      s = new string[Map.Count];
117      for (int i = 0; i < Map.Count; i++) {
118        s[i] = "";
119        for (int j = 0; j < Map[i].Count; j++) {
120          s[i] += Map[i][j].ToString();
121          s[i] += " ";
122        }
123      }
124      return s;
125    }
126    public string[] MapToSee() { // Function that prepare Map to printing in .txt File: create a set of strings in human readable view
127      var fmt = new InfixExpressionFormatter();
128      string[] s;
129      s = new string[(ModelSet.Count) + 1];
130      s[0] = "ClusterNumber" + "," + "ModelNumber" + "," + "Model";
131      for (int i = 1; i < ((ModelSet.Count) + 1); i++) {
132        s[i] = "";
133        if (this is EMMIslandMap island) {
134          s[i] += island.ClusterNumber[i - 1].ToString() + ",";
135        }
136        s[i] += (i - 1).ToString() + ",";
137        if (ModelSet[i - 1] is ISymbolicExpressionTree model) {
138          s[i] += fmt.Format(model);
139        } else { s[i] += ModelSet[i - 1].ToString(); }
140      }
141      return s;
142    }
143    public void MapFromFileRead(string fileName) {
144      string input = File.ReadAllText(fileName);
145      int i = 0;
146      foreach (var row in input.Split('\n')) {
147        Map.Add(new List<int>());
148        foreach (var col in row.Trim().Split(' ')) {
149          Map[i].Add(int.Parse(col.Trim()));
150        }
151        i++;
152      }
153    }
154    #endregion
155
156    #region map use functions
157    public abstract T NewModelForInizializtionNotTree(IRandom random, out int treeNumber);
158    public ISymbolicExpressionTree NewModelForInizializtion(IRandom random, out int treeNumber) {
159      treeNumber = random.Next(ModelSet.Count);
160      if (ModelSet[treeNumber] is ISymbolicExpressionTree model)
161        return (ISymbolicExpressionTree)(model.Clone());
162      return new SymbolicExpressionTree();
163    }
164    public void NodeManipulationForInizializtion(IRandom random, TreeModelTreeNode node) {
165      node.Tree = NewModelForInizializtion(random, out int treeNumber);
166      node.SetLocalParameters(random, 0.5);
167      node.TreeNumber = treeNumber;
168    }
169    public abstract ISymbolicExpressionTree NewModelForMutation(IRandom random, out int treeNumber, int parentTreeNumber);
170    public virtual void NodeForMutationChange(IRandom random, TreeModelTreeNode treeNode) {
171      int treeNumber = treeNode.TreeNumber;
172      int treeNumber2 = treeNode.TreeNumber;
173      treeNode.Tree = new SymbolicExpressionTree(NewModelForMutation(random, out treeNumber, treeNumber2).Root);
174      treeNode.TreeNumber = treeNumber;
175      SetLocalParametersForTree(random, 0.5, treeNode.Tree);
176    }
177    public void SetLocalParametersForTree(IRandom random, double shakingFactor, ISymbolicExpressionTree tree) {
178      foreach (var node in tree.IterateNodesPrefix().Where(x => x.HasLocalParameters)) {
179        if (node is VariableTreeNode variableTreeNode) {
180          var symbol = variableTreeNode.Symbol;
181          variableTreeNode.Weight = NormalDistributedRandom.NextDouble(random, symbol.WeightManipulatorMu, symbol.WeightManipulatorSigma);
182        } else {
183          node.ResetLocalParameters(random);
184        }
185      }
186    }
187    public virtual void MapUpDate(Dictionary<ISymbolicExpressionTree, double> population) { }
188    #endregion
189  }
190}
Note: See TracBrowser for help on using the repository browser.