source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.GeneticProgramming/OffspringSelectionGP.cs @ 11895

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

#2283: constant opt, expressioncompiler, autodiff, fixes in GP solvers

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