Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JsonTemplateGenerator.cs @ 18056

Last change on this file since 18056 was 18056, checked in by dpiringe, 3 years ago

#3026

  • fixed a wrong description for the invert parameter in RunCollectionValueRemover
  • fixed the usage of a wrong formatter in RunCollectionSRSolutionGraphVizFormatter
  • fixed a bug in ListJsonItem where an empty guid field can cause an exception
  • started to rework the RegressionProblemDataConverter -> it causes a bug with the symbol Variable of the TypeCorherentGrammar (maybe more grammars)
    • the reasons for the rework: this converter was already the source of some problems in the past; it uses a lot of reflection and dynamic objects -> it is very complicated to read/understand
  • added an official description property Description in the metadata part of a template + entry in Constants.cs
File size: 3.9 KB
Line 
1using System.Collections.Generic;
2using HeuristicLab.Optimization;
3using Newtonsoft.Json.Linq;
4using HEAL.Attic;
5using System.IO;
6using HeuristicLab.Core;
7using System.Linq;
8
9namespace HeuristicLab.JsonInterface {
10  /// <summary>
11  /// Class to generate json interface templates.
12  /// </summary>
13  public class JsonTemplateGenerator {
14
15    /// <summary>
16    /// static Function to generate a template.
17    /// </summary>
18    /// <param name="templatePath">the path for the template files</param>
19    /// <param name="optimizer">the optimizer object to serialize</param>
20    /// <param name="rootItem">Root JsonItem for serialization, considers only active JsonItems for serialization</param>
21    public static void GenerateTemplate(string templatePath, IOptimizer optimizer, IJsonItem rootItem, IEnumerable<IRunCollectionModifier> runCollectionModifiers) {
22      // clear all runs
23      if (optimizer.ExecutionState == ExecutionState.Paused)
24        optimizer.Stop();
25      optimizer.Runs.Clear();
26
27      // validation
28      ValidationResult validationResult = rootItem.GetValidator().Validate();
29      if (!validationResult.Success)
30        throw validationResult.GenerateException();
31
32      #region Init
33      JObject template = JObject.Parse(Constants.Template);
34      JArray parameterItems = new JArray();
35      JArray resultItems = new JArray();
36      JArray runCollectionModifierItems = new JArray();
37      string templateName = Path.GetFileName(templatePath);
38      string templateDirectory = Path.GetDirectoryName(templatePath);
39      #endregion
40
41      // filter items with values/ranges/actualNames
42      var jsonItems = rootItem.Where(x => x.Active && !(x is EmptyJsonItem) && !(x is UnsupportedJsonItem));
43
44      #region Serialize HL File
45      ProtoBufSerializer serializer = new ProtoBufSerializer();
46      // get absolute path for serialization
47      string hlFilePath = Path.Combine(templateDirectory, $"{templateName}.hl");
48      serializer.Serialize(optimizer, hlFilePath);
49      // overwrite string for relative path
50      hlFilePath = Path.Combine($".", $"{templateName}.hl");
51      #endregion
52
53      #region Filter Items
54      foreach (var item in jsonItems) {
55        if (item is IResultJsonItem)
56          resultItems.Add(item.GenerateJObject());
57        else
58          parameterItems.Add(item.GenerateJObject());
59      }
60      #endregion
61
62      #region RunCollectionModifiers Serialization
63      foreach (var proc in runCollectionModifiers) {
64        JArray rcpParameterItems = new JArray();
65        var guid = StorableTypeAttribute.GetStorableTypeAttribute(proc.GetType()).Guid.ToString();
66        var item = JsonItemConverter.Extract(proc);
67
68        var rcpItems = item
69          .Where(x => !(x is EmptyJsonItem) && !(x is UnsupportedJsonItem))
70          .Select(x => x.GenerateJObject());
71
72        foreach (var i in rcpItems)
73          rcpParameterItems.Add(i);
74
75        JObject processorObj = new JObject();
76        processorObj.Add(nameof(IJsonItem.Name), item.Name);
77        processorObj.Add("GUID", guid);
78        processorObj.Add(Constants.Parameters, rcpParameterItems);
79        runCollectionModifierItems.Add(processorObj);
80      }
81      #endregion
82
83      #region Set Template Data
84      template[Constants.Metadata][Constants.TemplateName] = templateName;
85      template[Constants.Metadata][Constants.HLFileLocation] = hlFilePath;
86      template[Constants.Metadata][Constants.OptimizerDescription] = optimizer.Description;
87      template[Constants.Parameters] = parameterItems;
88      template[Constants.Results] = resultItems;
89      template[Constants.RunCollectionModifiers] = runCollectionModifierItems;
90      #endregion
91
92      #region Serialize and write to file
93      File.WriteAllText(Path.Combine(templateDirectory, $"{templateName}.json"), SingleLineArrayJsonWriter.Serialize(template));
94      #endregion
95    }
96  }
97}
Note: See TracBrowser for help on using the repository browser.