Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.GeneticProgramming/3.3/Boolean/EvenParityProblem.cs @ 17270

Last change on this file since 17270 was 17270, checked in by abeham, 5 years ago

#2521: worked on removing virtual from Maximization for single-objective problems

File size: 6.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.Collections.Generic;
24using System.Linq;
25using HEAL.Attic;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Parameters;
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  [StorableType("76D6001D-135F-45FB-BC79-061EDAEE33A9")]
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    #region item cloning and persistence
57    // persistence
58    [StorableConstructor]
59    private EvenParityProblem(StorableConstructorFlag _) : base(_) { }
60    [StorableHook(HookType.AfterDeserialization)]
61    private void AfterDeserialization() {
62      RegisterEventHandlers();
63    }
64
65    // cloning
66    private EvenParityProblem(EvenParityProblem original, Cloner cloner)
67      : base(original, cloner) {
68      RegisterEventHandlers();
69    }
70    public override IDeepCloneable Clone(Cloner cloner) {
71      return new EvenParityProblem(this, cloner);
72    }
73    #endregion
74
75    public EvenParityProblem()
76      : base(new SymbolicExpressionTreeEncoding()) {
77      Maximization = true;
78      Parameters.Add(new FixedValueParameter<IntValue>(NumberOfBitsParameterName, "The number of bits for the input parameter for the even parity function", new IntValue(4)));
79
80      Encoding.TreeLength = 100;
81      Encoding.TreeDepth = 17;
82
83      UpdateGrammar();
84      RegisterEventHandlers();
85    }
86
87    private void UpdateGrammar() {
88      var g = new SimpleSymbolicExpressionGrammar();
89      g.AddSymbols(new[] { "AND", "OR", "NAND", "NOR" }, 2, 2); // see Koza, 1992, page 529 section 20.2 Symbolic Regression of Even-Parity Functions
90
91      // add one terminal symbol for each bit
92      for (int i = 0; i < NumberOfBits; i++)
93        g.AddTerminalSymbol(string.Format("{0}", i));
94
95      Encoding.GrammarParameter.ReadOnly = false;
96      Encoding.Grammar = g;
97      Encoding.GrammarParameter.ReadOnly = true;
98
99      BestKnownQualityParameter.ReadOnly = false;
100      BestKnownQuality = Math.Pow(2, NumberOfBits); // this is a benchmark problem (the best achievable quality is known for a given number of bits)
101      BestKnownQualityParameter.ReadOnly = true;
102    }
103
104
105    public override double Evaluate(ISymbolicExpressionTree tree, IRandom random) {
106      if (NumberOfBits <= 0) throw new NotSupportedException("Number of bits must be larger than zero.");
107      if (NumberOfBits > 10) throw new NotSupportedException("Even parity does not support problems with number of bits > 10.");
108      var bs = Enumerable.Range(0, (int)Math.Pow(2, NumberOfBits));
109      var targets = bs.Select(b => CalcTarget(b, NumberOfBits));
110      var pred = Interpret(tree, bs);
111      return targets.Zip(pred, (t, p) => t == p ? 1 : 0).Sum(); // count number of correct predictions
112    }
113
114    private static bool CalcTarget(int b, int numBits) {
115      bool res = GetBits(b, 0);
116      for (byte i = 1; i < numBits; i++)
117        res = res ^ GetBits(b, i); // XOR
118      return res;
119    }
120
121    private static IEnumerable<bool> Interpret(ISymbolicExpressionTree tree, IEnumerable<int> bs) {
122      // skip programRoot and startSymbol
123      return InterpretRec(tree.Root.GetSubtree(0).GetSubtree(0), bs);
124    }
125
126    private static IEnumerable<bool> InterpretRec(ISymbolicExpressionTreeNode node, IEnumerable<int> bs) {
127      Func<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode, Func<bool, bool, bool>, IEnumerable<bool>> binaryEval =
128        (left, right, f) => InterpretRec(left, bs).Zip(InterpretRec(right, bs), f);
129
130      switch (node.Symbol.Name) {
131        case "AND": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x & y);
132        case "OR": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x | y);
133        case "NAND": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => !(x & y));
134        case "NOR": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => !(x | y));
135        default: {
136            byte bitPos;
137            if (byte.TryParse(node.Symbol.Name, out bitPos)) {
138              return bs.Select(b => GetBits(b, bitPos));
139            } else throw new NotSupportedException(string.Format("Found unexpected symbol {0}", node.Symbol.Name));
140          }
141      }
142    }
143
144    private static bool GetBits(int b, byte bitPos) {
145      return (b & (1 << bitPos)) != 0;
146    }
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.