Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
08/04/21 17:19:05 (3 years ago)
Author:
dpiringe
Message:

#3026

  • added some test cases for JsonInterface
  • deleted the HeuristicLab namespace part in a lot of test classes (this caused a lot of compile errors)
  • enhanced the OS path logic for absolute and relative path in JsonTemplateGenerator and JsonTemplateInstantiator
  • fixed a bug in ValueParameterConverter -> the injection logic was not working correctly
  • changed the folder determination in Main.cs for the HeadlessRun method
  • added a new abstract type of JsonItem IntervalRestrictedJsonItem for JsonItems with a need of Minimum and Maximum bounds but without a specific value
    • changed in RangedJsonItem the base class from IntervalRestrictedValueJsonItem to IntervalRestrictedJsonItem
Location:
branches/3026_IntegrationIntoSymSpace/HeuristicLab.Tests/HeuristicLab.JsonInterface
Files:
1 deleted
1 edited

Legend:

Unmodified
Added
Removed
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.Tests/HeuristicLab.JsonInterface/GeneratorInstantiatorTest.cs

    r17353 r18040  
    11using System;
     2using System.Collections.Generic;
    23using System.IO;
    34using System.Linq;
     
    78using HeuristicLab.Operators;
    89using HeuristicLab.Optimization;
     10using HeuristicLab.PluginInfrastructure.Manager;
    911using HeuristicLab.Problems.TravelingSalesman;
    1012using Microsoft.VisualStudio.TestTools.UnitTesting;
     13using Newtonsoft.Json.Linq;
    1114
    1215namespace HeuristicLab.JsonInterface.Tests {
    1316  [TestClass]
    1417  public class GeneratorInstantiatorTest {
    15     private string templateFilePath = Directory.GetCurrentDirectory()+"\\Template.json";
    16     private string configFilePath = Directory.GetCurrentDirectory() + "\\Config.json";
     18    private string TmpDirectoryPath => Path.Combine(Directory.GetCurrentDirectory(), "JsonInterfaceTestEnvironment");
     19    private string TemplateName => Path.Combine(TmpDirectoryPath, "Template");
     20    private string TemplateFilePath => $"{TemplateName}.json";
     21    private string ConfigFilePath => Path.Combine(TmpDirectoryPath, "Config.json");
     22    private string OutFilePath => Path.Combine(TmpDirectoryPath, "out.json");
    1723
    1824    [TestInitialize()]
    1925    public void CreateTempFiles() {
     26      string pluginPath = Path.GetFullPath(Directory.GetCurrentDirectory());
     27      var pluginManager = new PluginManager(pluginPath);
     28      pluginManager.DiscoverAndCheckPlugins();
     29
     30
     31      Directory.CreateDirectory(TmpDirectoryPath);
     32
    2033      GeneticAlgorithm alg = new GeneticAlgorithm();
     34      alg.PopulationSize.Value = 200;
    2135      alg.Problem = new TravelingSalesmanProblem();
    22       //File.WriteAllText(@"C:\Workspace\Template.json", gen.GenerateTemplate(alg, tsp));
    23       File.WriteAllText(templateFilePath, JCGenerator.GenerateTemplate(alg));
    24       File.WriteAllText(configFilePath, "["+
    25         "{\"Name\": \"Seed\",\"Default\": 55555,\"Path\": \"Genetic Algorithm (GA).Seed\"},"+
    26         "{\"Name\": \"Crossover\", \"Path\": \"Genetic Algorithm (GA).Crossover\", \"Default\": \"MultiPermutationCrossover\"}," +
    27         "{\"Name\": \"Elites\", \"Path\": \"Genetic Algorithm (GA).Elites\", \"Default\": 5,\"Range\":[-2147483648,2147483647]}" +
    28         "]");
     36     
     37      var rootItem = JsonItemConverter.Extract(alg);
     38      foreach (var item in rootItem)
     39        item.Active = true; //activate all items
     40      JsonTemplateGenerator.GenerateTemplate(TemplateName, alg, rootItem);
     41
     42
     43      var populationItem =
     44        (IntJsonItem)rootItem.Where(x => x.Name.Contains("PopulationSize")).FirstOrDefault();
     45
     46      populationItem.Value = 500;
     47
     48      JArray configItems = new JArray();
     49      configItems.Add(populationItem.GenerateJObject());
     50
     51      File.WriteAllText(ConfigFilePath, SingleLineArrayJsonWriter.Serialize(configItems));
     52
    2953    }
    30    
    31     [TestCleanup()]
    32     public void ClearTempFiles() {
    33       File.Delete(templateFilePath);
    34       File.Delete(configFilePath);
     54
     55    private void CreateTestEnvironment(IOptimizer optimizer, Func<IJsonItem,IEnumerable<IJsonItem>> selectConfigItems, Action body) {
     56      // initialization
     57      Directory.CreateDirectory(TmpDirectoryPath);
     58
     59      var rootItem = JsonItemConverter.Extract(optimizer);
     60      foreach (var item in rootItem)
     61        item.Active = true; //activate all items
     62      JsonTemplateGenerator.GenerateTemplate(TemplateName, optimizer, rootItem);
     63
     64      JArray configItemsJArray = new JArray();
     65      var configItems = selectConfigItems(rootItem);
     66
     67      foreach(var item in configItems) {
     68        configItemsJArray.Add(item.GenerateJObject());
     69      }
     70      File.WriteAllText(ConfigFilePath, SingleLineArrayJsonWriter.Serialize(configItemsJArray));
     71
     72      // execute test
     73      body();
     74
     75      // cleanup
     76      var files = Directory.GetFiles(TmpDirectoryPath);
     77      foreach (var file in files)
     78        File.Delete(file);
     79      Directory.Delete(TmpDirectoryPath);
    3580    }
    3681
    3782    [TestMethod]
    38     public void TestInstantiator() {
    39       GeneticAlgorithm alg = (GeneticAlgorithm)JCInstantiator.Instantiate(templateFilePath, configFilePath);
     83    public void TestGATSP() {
     84      var ga = new GeneticAlgorithm();
     85      ga.PopulationSize.Value = 200;
     86      ga.Problem = new TravelingSalesmanProblem();
    4087
    41       Assert.AreEqual(55555, alg.Seed.Value);
    42       Assert.IsTrue(alg.Crossover is MultiPermutationCrossover);
    43       Assert.AreEqual(5, alg.Elites.Value);
     88      CreateTestEnvironment(ga,
     89        r => r.Where(x => x.Name.Contains("PopulationSize"))
     90              .Cast<IntJsonItem>()
     91              .Select(x => { x.Value = 500; return x; }),
     92        () => {
     93          var result = JsonTemplateInstantiator.Instantiate(TemplateFilePath, ConfigFilePath);
     94          var optimizer = (GeneticAlgorithm)result.Optimizer;
     95          Assert.AreEqual(500, optimizer.PopulationSize.Value);
     96
     97          PluginInfrastructure.Main.HeadlessRun(new string[] { "/start:JsonInterface", TemplateFilePath, ConfigFilePath, OutFilePath });
     98          Assert.IsTrue(File.Exists(OutFilePath));
     99
     100          var runs = JArray.Parse(File.ReadAllText(OutFilePath));
     101          var results = (JObject)runs[0];
     102          results.Property("Generations");
     103        });
    44104    }
    45105
    46106    [TestMethod]
    47     [ExpectedException(typeof(ArgumentOutOfRangeException))]
    48     public void TestRangeChangeWithConfig() {
    49       File.WriteAllText(configFilePath, "[{\"Name\": \"MutationProbability\", \"Path\": \"Genetic Algorithm (GA).MutationProbability\", \"Default\": 2.0,\"Range\":[0.0,2.0]}]");
    50       GeneticAlgorithm alg = (GeneticAlgorithm)JCInstantiator.Instantiate(templateFilePath, configFilePath);
     107    public void TestGASymReg() {
     108      var ga = new GeneticAlgorithm();
     109      ga.PopulationSize.Value = 200;
     110      ga.Problem = new Problems.DataAnalysis.Symbolic.Regression.SymbolicRegressionSingleObjectiveProblem();
     111
     112      CreateTestEnvironment(ga,
     113        r => r.Where(x => x.Name.Contains("PopulationSize"))
     114              .Cast<IntJsonItem>()
     115              .Select(x => { x.Value = 500; return x; }),
     116        () => {
     117          var result = JsonTemplateInstantiator.Instantiate(TemplateFilePath, ConfigFilePath);
     118          var optimizer = (GeneticAlgorithm)result.Optimizer;
     119          Assert.AreEqual(500, optimizer.PopulationSize.Value);
     120
     121          PluginInfrastructure.Main.HeadlessRun(new string[] { "/start:JsonInterface", TemplateFilePath, ConfigFilePath, OutFilePath });
     122          Assert.IsTrue(File.Exists(OutFilePath));
     123
     124          var runs = JArray.Parse(File.ReadAllText(OutFilePath));
     125          var results = (JObject)runs[0];
     126          results.Property("Generations");
     127        });
     128    }
     129
     130    [TestMethod]
     131    public void TestOSGASymReg() {
     132      var osga = new Algorithms.OffspringSelectionGeneticAlgorithm.OffspringSelectionGeneticAlgorithm();
     133      osga.PopulationSize.Value = 200;
     134      osga.Problem = new Problems.DataAnalysis.Symbolic.Regression.SymbolicRegressionSingleObjectiveProblem();
     135
     136      CreateTestEnvironment(osga,
     137        r => r.Where(x => x.Name.Contains("PopulationSize"))
     138              .Cast<IntJsonItem>()
     139              .Select(x => { x.Value = 500; return x; }),
     140        () => {
     141          var result = JsonTemplateInstantiator.Instantiate(TemplateFilePath, ConfigFilePath);
     142          var optimizer = (Algorithms.OffspringSelectionGeneticAlgorithm.OffspringSelectionGeneticAlgorithm)result.Optimizer;
     143          Assert.AreEqual(500, optimizer.PopulationSize.Value);
     144
     145          PluginInfrastructure.Main.HeadlessRun(new string[] { "/start:JsonInterface", TemplateFilePath, ConfigFilePath, OutFilePath });
     146          Assert.IsTrue(File.Exists(OutFilePath));
     147
     148          var runs = JArray.Parse(File.ReadAllText(OutFilePath));
     149          var results = (JObject)runs[0];
     150          results.Property("Generations");
     151        });
     152    }
     153
     154    [TestMethod]
     155    public void TestOSGATSP() {
     156      var osga = new Algorithms.OffspringSelectionGeneticAlgorithm.OffspringSelectionGeneticAlgorithm();
     157      osga.PopulationSize.Value = 200;
     158      osga.Problem = new TravelingSalesmanProblem();
     159
     160      CreateTestEnvironment(osga,
     161        r => r.Where(x => x.Name.Contains("PopulationSize"))
     162              .Cast<IntJsonItem>()
     163              .Select(x => { x.Value = 500; return x; }),
     164        () => {
     165          var result = JsonTemplateInstantiator.Instantiate(TemplateFilePath, ConfigFilePath);
     166          var optimizer = (Algorithms.OffspringSelectionGeneticAlgorithm.OffspringSelectionGeneticAlgorithm)result.Optimizer;
     167          Assert.AreEqual(500, optimizer.PopulationSize.Value);
     168
     169          PluginInfrastructure.Main.HeadlessRun(new string[] { "/start:JsonInterface", TemplateFilePath, ConfigFilePath, OutFilePath });
     170          Assert.IsTrue(File.Exists(OutFilePath));
     171
     172          var runs = JArray.Parse(File.ReadAllText(OutFilePath));
     173          var results = (JObject)runs[0];
     174          results.Property("Generations");
     175        });
    51176    }
    52177  }
Note: See TracChangeset for help on using the changeset viewer.