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

Last change on this file since 13267 was 13267, checked in by mkommend, 6 years ago

#2472: Minor code improvements in HL.Problems.GP (typos, code organization, code unification).

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