Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2708_ScopedAlgorithms/HeuristicLab.Problems.GeneticProgramming/3.3/ArtificialAnt/Problem.cs @ 16988

Last change on this file since 16988 was 13269, checked in by mkommend, 9 years ago

#2472: Moved cloning and persistence code near the default ctor for all new GP problems.

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