Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.GeneticProgramming/3.3/LawnMower/Interpreter.cs @ 12911

Last change on this file since 12911 was 12911, checked in by gkronber, 9 years ago

#2472: created project structure for HeuristicLab.Problems.GeneticProgramming and added implementations of ArtificialAnt and LawnMower

File size: 6.9 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.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
26
27namespace HeuristicLab.Problems.GeneticProgramming.LawnMower {
28  public class Interpreter {
29    private enum Heading {
30      South,
31      East,
32      North,
33      West
34    };
35
36    private class MowerState {
37      public Heading Heading { get; set; }
38      public Tuple<uint, uint> Position { get; set; }
39      public int Energy { get; set; }
40      public MowerState() {
41        Heading = Heading.South;
42        Position = new Tuple<uint, uint>(0, 0);
43        Energy = 0;
44      }
45    }
46
47
48    public static bool[,] EvaluateLawnMowerProgram(int length, int width, ISymbolicExpressionTree tree) {
49
50      bool[,] lawn = new bool[length, width];
51      var mowerState = new MowerState();
52      mowerState.Heading = Heading.South;
53      mowerState.Energy = length * width * 2;
54      lawn[mowerState.Position.Item1, mowerState.Position.Item2] = true;
55      EvaluateLawnMowerProgram(tree.Root, mowerState, lawn, tree.Root.Subtrees.Skip(1).ToArray());
56      return lawn;
57    }
58
59
60    private static Tuple<int, int> EvaluateLawnMowerProgram(ISymbolicExpressionTreeNode node, MowerState mowerState, bool[,] lawn, IEnumerable<ISymbolicExpressionTreeNode> adfs) {
61      if (mowerState.Energy <= 0) return Tuple.Create(0, 0);
62
63      if (node.Symbol is ProgramRootSymbol) {
64        return EvaluateLawnMowerProgram(node.GetSubtree(0), mowerState, lawn, adfs);
65      } else if (node.Symbol is StartSymbol) {
66        return EvaluateLawnMowerProgram(node.GetSubtree(0), mowerState, lawn, adfs);
67      } else if (node.Symbol.Name == "Left") {
68        switch (mowerState.Heading) {
69          case Heading.East: mowerState.Heading = Heading.North;
70            break;
71          case Heading.North: mowerState.Heading = Heading.West;
72            break;
73          case Heading.West: mowerState.Heading = Heading.South;
74            break;
75          case Heading.South:
76            mowerState.Heading = Heading.East;
77            break;
78        }
79        return new Tuple<int, int>(0, 0);
80      } else if (node.Symbol.Name == "Forward") {
81        int dRow = 0;
82        int dCol = 0;
83        switch (mowerState.Heading) {
84          case Heading.East:
85            dCol++;
86            break;
87          case Heading.North:
88            dRow--;
89            break;
90          case Heading.West:
91            dCol--;
92            break;
93          case Heading.South:
94            dRow++;
95            break;
96        }
97        uint newRow = (uint)((mowerState.Position.Item1 + lawn.GetLength(0) + dRow) % lawn.GetLength(0));
98        uint newColumn = (uint)((mowerState.Position.Item2 + lawn.GetLength(1) + dCol) % lawn.GetLength(1));
99        mowerState.Position = Tuple.Create(newRow, newColumn);
100        mowerState.Energy = mowerState.Energy - 1;
101        lawn[newRow, newColumn] = true;
102        return Tuple.Create(0, 0);
103      } else if (node.Symbol.Name == "Sum") {
104        var p = EvaluateLawnMowerProgram(node.GetSubtree(0), mowerState, lawn, adfs);
105        var q = EvaluateLawnMowerProgram(node.GetSubtree(1), mowerState, lawn, adfs);
106        return Tuple.Create(p.Item1 + q.Item1, p.Item2 + q.Item2);
107      } else if (node.Symbol.Name == "Prog") {
108        EvaluateLawnMowerProgram(node.GetSubtree(0), mowerState, lawn, adfs);
109        return EvaluateLawnMowerProgram(node.GetSubtree(1), mowerState, lawn, adfs);
110      } else if (node.Symbol.Name == "Frog") {
111        var p = EvaluateLawnMowerProgram(node.GetSubtree(0), mowerState, lawn, adfs);
112        int x = p.Item1;
113        int y = p.Item2;
114        while (x < 0) x += lawn.GetLength(0);
115        while (y < 0) y += lawn.GetLength(1);
116        var newRow = (uint)((mowerState.Position.Item1 + x) % lawn.GetLength(0));
117        var newCol = (uint)((mowerState.Position.Item2 + y) % lawn.GetLength(1));
118        mowerState.Position = Tuple.Create(newRow, newCol);
119        mowerState.Energy = mowerState.Energy - 1;
120        lawn[newRow, newCol] = true;
121        return Tuple.Create(0, 0);
122      } else if (node.Symbol is InvokeFunction) {
123        var invokeNode = node as InvokeFunctionTreeNode;
124
125        // find the function definition for the invoke call
126        var functionDefinition = (from adf in adfs.Cast<DefunTreeNode>()
127                                  where adf.FunctionName == invokeNode.Symbol.FunctionName
128                                  select adf).Single();
129        // clone the function definition because we are replacing the argument nodes
130        functionDefinition = (DefunTreeNode)functionDefinition.Clone();
131        // find the argument tree nodes and their parents in the original function definition
132        // toList is necessary to prevent that newly inserted branches are iterated
133        var argumentCutPoints = (from parent in functionDefinition.IterateNodesPrefix()
134                                 from subtree in parent.Subtrees
135                                 where subtree is ArgumentTreeNode
136                                 select new { Parent = parent, Argument = subtree.Symbol as Argument, ChildIndex = parent.IndexOfSubtree(subtree) })
137                                 .ToList();
138        // replace all argument tree ndoes with the matching argument of the invoke node
139        foreach (var cutPoint in argumentCutPoints) {
140          cutPoint.Parent.RemoveSubtree(cutPoint.ChildIndex);
141          cutPoint.Parent.InsertSubtree(cutPoint.ChildIndex, (SymbolicExpressionTreeNode)invokeNode.GetSubtree(cutPoint.Argument.ArgumentIndex).Clone());
142        }
143        return EvaluateLawnMowerProgram(functionDefinition.GetSubtree(0), mowerState, lawn, adfs);
144      } else {
145        // try to parse as ephemeral random const with format: "x,y" (x, y in [0..32[)
146        int x, y;
147        var tokens = node.Symbol.Name.Split(',');
148        if (tokens.Length == 2 &&
149            int.TryParse(tokens[0], out x) &&
150            int.TryParse(tokens[1], out y)) {
151          return Tuple.Create(x, y);
152        } else {
153          throw new ArgumentException("Invalid symbol in the lawn mower program.");
154        }
155      }
156    }
157  }
158}
Note: See TracBrowser for help on using the repository browser.