Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17655 was 17655, checked in by abeham, 4 years ago

#2521: adapted readonly of reference parameters

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