Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.GeneticProgramming/3.3/Boolean/EvenParityProblem.cs @ 12938

Last change on this file since 12938 was 12938, checked in by gkronber, 7 years ago

#2472: added even parity and multiplexer problems (GP)

File size: 5.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.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32
33namespace HeuristicLab.Problems.GeneticProgramming.Boolean {
34  [Item("Even Parity Problem", "The Boolean even parity genetic programming problem. See Koza, 1992, page 529 section 20.2 Symbolic Regression of Even-Parity Functions")]
35  [Creatable(CreatableAttribute.Categories.GeneticProgrammingProblems, Priority = 900)]
36  [StorableClass]
37  public sealed class EvenParityProblem : SymbolicExpressionTreeProblem {
38
39    #region parameter names
40
41    private const string NumberOfBitsParameterName = "NumberOfBits";
42
43    #endregion
44
45    #region Parameter Properties
46    public IFixedValueParameter<IntValue> NumberOfBitsParameter {
47      get { return (IFixedValueParameter<IntValue>)Parameters[NumberOfBitsParameterName]; }
48    }
49
50    #endregion
51
52    #region Properties
53
54    public int NumberOfBits {
55      get { return NumberOfBitsParameter.Value.Value; }
56      set { NumberOfBitsParameter.Value.Value = value; }
57    }
58
59
60    #endregion
61
62    public override bool Maximization {
63      get { return true; }
64    }
65
66    public EvenParityProblem()
67      : base() {
68      Parameters.Add(new FixedValueParameter<IntValue>(NumberOfBitsParameterName, "The number of bits for the input parameter for the even parity function", new IntValue(4)));
69
70      var g = new SimpleSymbolicExpressionGrammar(); // will be replaced in update grammar
71      Encoding = new SymbolicExpressionTreeEncoding(g, 100, 17);
72
73      UpdateGrammar();
74      RegisterEventHandlers();
75    }
76
77    private void UpdateGrammar() {
78      var g = new SimpleSymbolicExpressionGrammar();
79      g.AddSymbols(new[] { "AND", "OR", "NAND", "NOR" }, 2, 2); // see Koza, 1992, page 529 section 20.2 Symbolic Regression of Even-Parity Functions
80
81      // add one terminal symbol for each bit
82      for (int i = 0; i < NumberOfBits; i++)
83        g.AddTerminalSymbol(string.Format("{0}", i));
84
85      Encoding.Grammar = g;
86    }
87
88
89    public override double Evaluate(ISymbolicExpressionTree tree, IRandom random) {
90      if (NumberOfBits <= 0) throw new NotSupportedException("Number of bits must be larger than zero.");
91      if (NumberOfBits > 10) throw new NotSupportedException("Even parity does not support problems with number of bits > 10.");
92      var bs = Enumerable.Range(0, (int)Math.Pow(2, NumberOfBits));
93      var targets = bs.Select(b => CalcTarget(b, NumberOfBits));
94      var pred = Interpret(tree, bs);
95      return targets.Zip(pred, (t, p) => t == p ? 1 : 0).Sum(); // count number of correct predictions
96    }
97
98    private static bool CalcTarget(int b, int numBits) {
99      bool res = GetBits(b, 0);
100      for (byte i = 1; i < numBits; i++)
101        res = res ^ GetBits(b, i); // XOR
102      return res;
103    }
104
105    private static IEnumerable<bool> Interpret(ISymbolicExpressionTree tree, IEnumerable<int> bs) {
106      // skip programRoot and startSymbol
107      return InterpretRec(tree.Root.GetSubtree(0).GetSubtree(0), bs);
108    }
109
110
111    private static IEnumerable<bool> InterpretRec(ISymbolicExpressionTreeNode node, IEnumerable<int> bs) {
112      Func<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode, Func<bool, bool, bool>, IEnumerable<bool>> eval2 =
113        (left, right, f) => InterpretRec(left, bs).Zip(InterpretRec(right, bs), f);
114
115      switch (node.Symbol.Name) {
116        case "AND": return eval2(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x & y);
117        case "OR": return eval2(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x | y);
118        case "NAND": return eval2(node.GetSubtree(0), node.GetSubtree(1), (x, y) => !(x & y));
119        case "NOR": return eval2(node.GetSubtree(0), node.GetSubtree(1), (x, y) => !(x | y));
120        default: {
121            byte bitPos;
122            if (byte.TryParse(node.Symbol.Name, out bitPos)) {
123              return bs.Select(b => GetBits(b, bitPos));
124            } else throw new NotSupportedException(string.Format("Found unexpected symbol {0}", node.Symbol.Name));
125          }
126      }
127    }
128
129    private static bool GetBits(int b, byte bitPos) {
130      return (b & (1 << bitPos)) != 0;
131    }
132
133    #region item cloning and persistence
134    // persistence
135    [StorableConstructor]
136    private EvenParityProblem(bool deserializing) : base(deserializing) { }
137
138    [StorableHook(HookType.AfterDeserialization)]
139    private void AfterDeserialization() {
140      RegisterEventHandlers();
141    }
142
143    // cloning
144    private EvenParityProblem(EvenParityProblem original, Cloner cloner)
145      : base(original, cloner) {
146      RegisterEventHandlers();
147    }
148    public override IDeepCloneable Clone(Cloner cloner) {
149      return new EvenParityProblem(this, cloner);
150    }
151    #endregion
152
153    #region events
154
155    private void RegisterEventHandlers() {
156      NumberOfBitsParameter.Value.ValueChanged += (sender, args) => UpdateGrammar();
157    }
158    #endregion
159  }
160}
Note: See TracBrowser for help on using the repository browser.