source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GeneticProgramming/StandardGP.cs @ 12840

Last change on this file since 12840 was 12840, checked in by aballeit, 5 years ago

#2283 Final

File size: 4.2 KB
Line 
1using System;
2using System.IO;
3using System.IO.Compression;
4using System.Linq;
5using System.Threading;
6using HeuristicLab.Algorithms.GrammaticalOptimization;
7using HeuristicLab.Common;
8using HeuristicLab.Data;
9using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
10using HeuristicLab.Persistence.Default.Xml;
11using HeuristicLab.Problems.GrammaticalOptimization;
12using HeuristicLab.Selection;
13
14namespace HeuristicLab.Algorithms.GeneticProgramming {
15  public class StandardGP : SolverBase, IGPSolver {
16    public int PopulationSize { get; set; }
17    public double MutationRate { get; set; }
18    public int TournamentGroupSize { get; set; }
19    public int MaxSolutionSize { get; set; }
20    public int MaxSolutionDepth { get; set; }
21
22    private readonly ISymbolicExpressionTreeProblem problem;
23    private readonly Random random;
24    private readonly bool saveAlg;
25
26    public StandardGP(ISymbolicExpressionTreeProblem problem, Random random, bool saveAlg = false) {
27      this.problem = problem;
28      this.random = random;
29      // default parameter values
30      PopulationSize = 1000;
31      TournamentGroupSize = 4;
32      MutationRate = 0.15;
33      MaxSolutionSize = 201;
34      MaxSolutionDepth = 17;
35      this.saveAlg = saveAlg;
36    }
37
38    public override void Run(int maxEvaluations) {
39      var hlProblem = new GenericSymbExprProblem(problem);
40      var onEvalLocker = new object();
41      hlProblem.MaximumSymbolicExpressionTreeLength.Value = MaxSolutionSize;
42      hlProblem.MaximumSymbolicExpressionTreeDepth.Value = MaxSolutionDepth;
43
44
45      using (var wh = new AutoResetEvent(false)) {
46        var ga = new GeneticAlgorithm.GeneticAlgorithm();
47        ga.Engine = new ParallelEngine.ParallelEngine();
48        ga.ExceptionOccurred += (sender, args) => { Console.WriteLine(args.Value.Message); wh.Set(); };
49        ga.Stopped += (sender, args) => { wh.Set(); };
50
51        int numEvals = 0;
52        hlProblem.Evaluator.SolutionEvaluated += (sentence, quality) => {
53          // raise solution evaluated event for each GP solution, don't scale quality to 0..1
54          // need to synchronize in case we are using a parallel engine
55          lock (onEvalLocker) {
56            OnSolutionEvaluated(sentence, quality);
57
58            // stop when maxEvals has been reached
59            if (numEvals++ >= maxEvaluations) {
60              ga.Stop();
61            }
62          }
63        };
64
65
66        ga.Problem = hlProblem;
67        //ga.Problem.SolutionCreatorParameter.ActualValue = new FullTreeCreator();
68        var mutator = (MultiSymbolicExpressionTreeManipulator)ga.MutatorParameter.ValidValues.Single(op => op.Name == "MultiSymbolicExpressionTreeManipulator");
69        foreach (var op in mutator.Operators) {
70          if (op.Name == "ChangeNodeTypeManipulation"
71            || op.Name == "ReplaceBranchManipulation") mutator.Operators.SetItemCheckedState(op, true);
72          else mutator.Operators.SetItemCheckedState(op, false);
73        }
74        ga.Mutator = mutator;
75        ga.Crossover = ga.CrossoverParameter.ValidValues.Single(op => op.Name == "SubtreeSwappingCrossover");
76        var selector = (TournamentSelector)ga.SelectorParameter.ValidValues.Single(op => op.Name == "TournamentSelector");
77        selector.GroupSizeParameter.Value = new IntValue(TournamentGroupSize);
78        ga.Selector = selector;
79
80        ga.PopulationSize.Value = PopulationSize;
81        ga.MaximumGenerations.Value = 1000000; // very large value (we stop in the evaluate handler)
82        ga.MutationProbability.Value = MutationRate;
83
84        ga.SetSeedRandomly = new BoolValue(false);
85        ga.Seed = new IntValue(random.Next());
86
87        ga.Prepare();
88        ga.Start();
89
90        wh.WaitOne();
91
92
93        if (saveAlg) {
94          var path = @"C:\Users\P24581\Desktop";
95          var fileName = string.Format("osgp-{0}{1:D2}{2:D2}{3:D2}{4:D2}.hl", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute);
96          var fullPath = Path.Combine(path, fileName);
97          HeuristicLab.Persistence.Core.ConfigurationService.Instance.LoadSettings();
98          XmlGenerator.Serialize(ga, fullPath, CompressionLevel.Fastest);
99        }
100      }
101    }
102  }
103}
Note: See TracBrowser for help on using the repository browser.