Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Tests/HeuristicLab-3.3/Samples/GAGroupingProblemSampleTest.cs @ 17946

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

#2521: fixed some problems in Samples.Create unit tests and updated samples

File size: 5.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.IO;
23using HEAL.Attic;
24using HeuristicLab.Algorithms.GeneticAlgorithm;
25using HeuristicLab.Encodings.LinearLinkageEncoding;
26using HeuristicLab.Problems.Programmable;
27using HeuristicLab.Selection;
28using Microsoft.VisualStudio.TestTools.UnitTesting;
29
30namespace HeuristicLab.Tests {
31  [TestClass]
32  public class GAGroupingProblemSampleTest {
33    private const string SampleFileName = "GA_Grouping";
34
35    private static readonly ProtoBufSerializer serializer = new ProtoBufSerializer();
36
37    #region Code
38    private const string ProblemCode = @"
39using System;
40using System.Linq;
41using System.Collections.Generic;
42using System.Threading;
43using HeuristicLab.Common;
44using HeuristicLab.Core;
45using HeuristicLab.Data;
46using HeuristicLab.Encodings.LinearLinkageEncoding;
47using HeuristicLab.Optimization;
48using HeuristicLab.Problems.Programmable;
49
50namespace HeuristicLab.Problems.Programmable {
51  public class CompiledSingleObjectiveProblemDefinition : CompiledSingleObjectiveProblemDefinition<LinearLinkageEncoding, LinearLinkage> {
52    private const int ProblemSize = 100;
53    public override bool Maximization { get { return false; } }
54
55    private bool[,] adjacencyMatrix;
56   
57    public override void Initialize() {
58      Encoding.Length = ProblemSize;
59      adjacencyMatrix = new bool[ProblemSize, ProblemSize];
60      var random = new System.Random(13);
61      for (var i = 0; i < ProblemSize - 1; i++)
62        for (var j = i + 1; j < ProblemSize; j++)
63          adjacencyMatrix[i, j] = adjacencyMatrix[j, i] = random.Next(2) == 0;
64    }
65
66    public override double Evaluate(LinearLinkage solution, IRandom random, CancellationToken token) {
67      var penalty = 0;
68      var groups = solution.GetGroups().ToList();
69      for (var i = 0; i < groups.Count; i++) {
70        for (var j = 0; j < groups[i].Count; j++)
71          for (var k = j + 1; k < groups[i].Count; k++)
72            if (!adjacencyMatrix[groups[i][j], groups[i][k]]) penalty++;
73      }
74      var result = groups.Count;
75      if (penalty > 0) result += penalty + ProblemSize;
76      return result;
77    }
78
79    public override void Analyze(LinearLinkage[] solutions, double[] qualities, ResultCollection results, IRandom random) { }
80
81    public override IEnumerable<LinearLinkage> GetNeighbors(LinearLinkage solution, IRandom random) {
82      foreach (var move in ExhaustiveSwap2MoveGenerator.Generate(solution)) {
83        var neighbor = (LinearLinkage)solution.Clone();
84        Swap2MoveMaker.Apply(neighbor, move);
85        yield return neighbor;
86      }
87    }
88  }
89}
90";
91    #endregion
92
93    [TestMethod]
94    [TestCategory("Samples.Create")]
95    [TestProperty("Time", "medium")]
96    public void CreateGaGroupingProblemSampleTest() {
97      var ga = CreateGaGroupingProblemSample();
98      string path = Path.Combine(SamplesUtils.SamplesDirectory, SampleFileName + SamplesUtils.SampleFileExtension);
99      serializer.Serialize(ga, path);
100    }
101
102    [TestMethod]
103    [TestCategory("Samples.Execute")]
104    [TestProperty("Time", "long")]
105    public void RunGaGroupingProblemSampleTest() {
106      var ga = CreateGaGroupingProblemSample();
107      ga.SetSeedRandomly.Value = false;
108      SamplesUtils.RunAlgorithm(ga);
109      Assert.AreEqual(127, SamplesUtils.GetDoubleResult(ga, "BestQuality"));
110      Assert.AreEqual(129,38, SamplesUtils.GetDoubleResult(ga, "CurrentAverageQuality"));
111      Assert.AreEqual(132, SamplesUtils.GetDoubleResult(ga, "CurrentWorstQuality"));
112      Assert.AreEqual(99100, SamplesUtils.GetIntResult(ga, "EvaluatedSolutions"));
113    }
114
115    private GeneticAlgorithm CreateGaGroupingProblemSample() {
116      GeneticAlgorithm ga = new GeneticAlgorithm();
117
118      #region Problem Configuration
119      var problem = new SingleObjectiveLinearLinkageProgrammableProblem() {
120        ProblemScript = { Code = ProblemCode }
121      };
122      problem.ProblemScript.Compile();
123      #endregion
124      #region Algorithm Configuration
125      ga.Name = "Genetic Algorithm - Graph Coloring";
126      ga.Description = "A genetic algorithm which solves a graph coloring problem using the linear linkage encoding.";
127      ga.Problem = problem;
128      SamplesUtils.ConfigureGeneticAlgorithmParameters<TournamentSelector, MultiLinearLinkageCrossover, MultiLinearLinkageManipulator>(
129        ga, 100, 1, 1000, 0.05, 2);
130      #endregion
131
132      return ga;
133    }
134  }
135}
Note: See TracBrowser for help on using the repository browser.