Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.GeneticProgramming/3.3/ArtificialAnt/Problem.cs @ 17745

Last change on this file since 17745 was 17745, checked in by mkommend, 4 years ago

#2971: Added first draft of results implementation and problem adaptation.

File size: 7.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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 System.Diagnostics.Contracts;
23using System.Threading;
24using HEAL.Attic;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31
32
33namespace HeuristicLab.Problems.GeneticProgramming.ArtificialAnt {
34  [Item("Artificial Ant Problem", "Represents the Artificial Ant problem.")]
35  [Creatable(CreatableAttribute.Categories.GeneticProgrammingProblems, Priority = 170)]
36  [StorableType("D365171B-7077-4CC2-835C-1827EA67C843")]
37  public sealed class Problem : SymbolicExpressionTreeProblem, IStorableContent {
38
39    #region constant for default world (Santa Fe)
40
41    private static readonly char[][] santaFeAntTrail = new[] {
42      " ###                            ".ToCharArray(),
43      "   #                            ".ToCharArray(),
44      "   #                    .###..  ".ToCharArray(),
45      "   #                    #    #  ".ToCharArray(),
46      "   #                    #    #  ".ToCharArray(),
47      "   ####.#####       .##..    .  ".ToCharArray(),
48      "            #       .        #  ".ToCharArray(),
49      "            #       #        .  ".ToCharArray(),
50      "            #       #        .  ".ToCharArray(),
51      "            #       #        #  ".ToCharArray(),
52      "            .       #        .  ".ToCharArray(),
53      "            #       .        .  ".ToCharArray(),
54      "            #       .        #  ".ToCharArray(),
55      "            #       #        .  ".ToCharArray(),
56      "            #       #  ...###.  ".ToCharArray(),
57      "            .   .#...  #        ".ToCharArray(),
58      "            .   .      .        ".ToCharArray(),
59      "            #   .      .        ".ToCharArray(),
60      "            #   #      .#...    ".ToCharArray(),
61      "            #   #          #    ".ToCharArray(),
62      "            #   #          .    ".ToCharArray(),
63      "            #   #          .    ".ToCharArray(),
64      "            #   .      ...#.    ".ToCharArray(),
65      "            #   .      #        ".ToCharArray(),
66      " ..##..#####.   #               ".ToCharArray(),
67      " #              #               ".ToCharArray(),
68      " #              #               ".ToCharArray(),
69      " #     .#######..               ".ToCharArray(),
70      " #     #                        ".ToCharArray(),
71      " .     #                        ".ToCharArray(),
72      " .####..                        ".ToCharArray(),
73      "                                ".ToCharArray()
74    };
75
76
77    #endregion
78
79    #region Parameter Properties
80    public IValueParameter<BoolMatrix> WorldParameter {
81      get { return (IValueParameter<BoolMatrix>)Parameters["World"]; }
82    }
83    public IFixedValueParameter<IntValue> MaxTimeStepsParameter {
84      get { return (IFixedValueParameter<IntValue>)Parameters["MaximumTimeSteps"]; }
85    }
86    #endregion
87
88    #region Properties
89    public BoolMatrix World {
90      get { return WorldParameter.Value; }
91      set { WorldParameter.Value = value; }
92    }
93    public int MaxTimeSteps {
94      get { return MaxTimeStepsParameter.Value.Value; }
95      set { MaxTimeStepsParameter.Value.Value = value; }
96    }
97    #endregion
98
99    #region item cloning and persistence
100    // persistence
101    [StorableConstructor]
102    private Problem(StorableConstructorFlag _) : base(_) { }
103    [StorableHook(HookType.AfterDeserialization)]
104    private void AfterDeserialization() { }
105
106    // cloning
107    private Problem(Problem original, Cloner cloner) : base(original, cloner) { }
108    public override IDeepCloneable Clone(Cloner cloner) {
109      return new Problem(this, cloner);
110    }
111    #endregion
112
113    public Problem() : base(new SymbolicExpressionTreeEncoding()) {
114      Maximization = true;
115      BoolMatrix world = new BoolMatrix(ToBoolMatrix(santaFeAntTrail));
116      Parameters.Add(new ValueParameter<BoolMatrix>("World", "The world for the artificial ant with scattered food items.", world));
117      Parameters.Add(new FixedValueParameter<IntValue>("MaximumTimeSteps", "The number of time steps the artificial ant has available to collect all food items.", new IntValue(600)));
118
119      var g = new SimpleSymbolicExpressionGrammar();
120      g.AddSymbols(new string[] { "IfFoodAhead", "Prog2" }, 2, 2);
121      g.AddSymbols(new string[] { "Prog3" }, 3, 3);
122      g.AddTerminalSymbols(new string[] { "Move", "Left", "Right" });
123
124      Encoding.TreeLength = 20;
125      Encoding.TreeDepth = 10;
126      Encoding.Grammar = g;
127      Encoding.GrammarParameter.ReadOnly = GrammarRefParameter.ReadOnly = true;
128
129      BestKnownQuality = 89;
130      BestKnownQualityParameter.ReadOnly = true;
131    }
132
133
134    public override ISingleObjectiveEvaluationResult Evaluate(ISymbolicExpressionTree tree, IRandom random, CancellationToken cancellationToken) {
135      var interpreter = new Interpreter(tree, World, MaxTimeSteps);
136      interpreter.Run();
137      var quality = interpreter.FoodEaten;
138      return new SingleObjectiveEvaluationResult(quality);
139    }
140
141    //TODO: change to new analyze interface
142    public override void Analyze(ISingleObjectiveSolutionContext<ISymbolicExpressionTree>[] solutionContexts, IRandom random) {
143      base.Analyze(solutionContexts, random);
144
145      //TODO reimplement code below using results directly
146      //  const string bestSolutionResultName = "Best Solution";
147      //  var bestQuality = Maximization ? qualities.Max() : qualities.Min();
148      //  var bestIdx = Array.IndexOf(qualities, bestQuality);
149
150      //  if (!results.ContainsKey(bestSolutionResultName)) {
151      //    results.Add(new Result(bestSolutionResultName, new Solution(World, trees[bestIdx], MaxTimeSteps, qualities[bestIdx])));
152      //  } else if (((Solution)(results[bestSolutionResultName].Value)).Quality < qualities[bestIdx]) {
153      //    results[bestSolutionResultName].Value = new Solution(World, trees[bestIdx], MaxTimeSteps, qualities[bestIdx]);
154      //  }
155    }
156
157    #region helpers
158    private bool[,] ToBoolMatrix(char[][] ch) {
159      var rows = ch.Length;
160      var cols = ch[0].Length;
161      var b = new bool[rows, cols];
162      for (int r = 0; r < rows; r++) {
163        Contract.Assert(ch[r].Length == cols); // all rows must have the same number of columns
164        for (int c = 0; c < cols; c++) {
165          b[r, c] = ch[r][c] == '#';
166        }
167      }
168      return b;
169    }
170    #endregion
171  }
172}
Note: See TracBrowser for help on using the repository browser.