Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 18242 was 17778, checked in by abeham, 4 years ago

#2521: working on refactoring

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