Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JsonTemplateInstantiator.cs @ 17834

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

#3026

  • added ResultFormatter to add an extra layer of result transformation logic (converting a result value to a string with a defined logic, e.g. MatlabResultFormatter for ISymbolicRegressionSolution)
  • extended the IResultJsonItem with two properties for result formatting
  • added a new control to selected a result formatter for a result value
  • refactored the Runner for the new result formatting process
File size: 4.9 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Linq;
5using HEAL.Attic;
6using HeuristicLab.Optimization;
7using Newtonsoft.Json.Linq;
8
9namespace HeuristicLab.JsonInterface {
10  public readonly struct InstantiatorResult {
11    public InstantiatorResult(IOptimizer optimizer, IEnumerable<IResultJsonItem> configuredResultItems) {
12      Optimizer = optimizer;
13      ConfiguredResultItems = configuredResultItems;
14    }
15
16    public IOptimizer Optimizer { get; }
17    public IEnumerable<IResultJsonItem> ConfiguredResultItems { get; }
18  }
19
20
21  /// <summary>
22  /// Class to instantiate an IAlgorithm object with a json interface template and config.
23  /// </summary>
24  public class JsonTemplateInstantiator {
25
26    #region Private Properties
27    private JToken Template { get; set; }
28    private JArray Config { get; set; }
29    private IDictionary<string, IJsonItem> Objects { get; set; } = new Dictionary<string, IJsonItem>();
30    #endregion
31
32    /// <summary>
33    /// Instantiate an IAlgorithm object with a template and config.
34    /// </summary>
35    /// <param name="templateFile">Template file (json), generated with JCGenerator.</param>
36    /// <param name="configFile">Config file (json) for the template.</param>
37    /// <returns>confugrated IOptimizer object</returns>
38    public static InstantiatorResult Instantiate(string templateFile, string configFile = null) {
39      JsonTemplateInstantiator instantiator = new JsonTemplateInstantiator();
40      return instantiator.ExecuteInstantiaton(templateFile, configFile);
41    }
42
43    #region Helper
44    private InstantiatorResult ExecuteInstantiaton(string templateFile, string configFile = null) {
45
46      #region Parse Files
47      Template = JToken.Parse(File.ReadAllText(templateFile));
48      if(!string.IsNullOrEmpty(configFile))
49        Config = JArray.Parse(File.ReadAllText(configFile));
50      #endregion
51
52      // extract metadata information
53      string hLFileLocation = Path.GetFullPath(Template[Constants.Metadata][Constants.HLFileLocation].ToString());
54
55      #region Deserialize HL File
56      ProtoBufSerializer serializer = new ProtoBufSerializer();
57      IOptimizer optimizer = (IOptimizer)serializer.Deserialize(hLFileLocation);
58      #endregion
59
60      // collect all parameterizedItems from template
61      CollectParameterizedItems(optimizer);
62     
63      if (Config != null)
64        MergeTemplateWithConfig();
65
66      // get algorithm root item
67      IJsonItem rootItem = Objects.First().Value;
68
69      // validation
70      ValidationResult validationResult = rootItem.GetValidator().Validate();
71      if (!validationResult.Success)
72        throw validationResult.GenerateException();
73
74      // inject configuration
75      JsonItemConverter.Inject(optimizer, rootItem);
76
77      return new InstantiatorResult(optimizer, CollectResults());
78    }
79
80    private IEnumerable<IResultJsonItem> CollectResults() {
81      IList<IResultJsonItem> res = new List<IResultJsonItem>();
82      foreach(JObject obj in Template[Constants.Results]) {
83        //string name = obj.Property("Name").Value.ToString();
84        var resultItem = new ResultJsonItem();
85        resultItem.SetJObject(obj);
86        res.Add(resultItem);
87        //res.Add(new ResultJsonItem() { Name = name });
88      }
89      return res;
90    }
91
92    private void CollectParameterizedItems(IOptimizer optimizer) {
93      IJsonItem root = JsonItemConverter.Extract(optimizer);
94      Objects.Add(root.Path, root);
95
96      foreach (JObject obj in Template[Constants.Parameters]) {
97        string path = obj.Property("Path").Value.ToString();
98        foreach(var tmp in root) {
99          if(tmp.Path == path) {
100            tmp.SetJObject(obj);
101            Objects.Add(tmp.Path, tmp);
102          }
103        }
104      }
105    }
106   
107    private void MergeTemplateWithConfig() {
108      foreach (JObject obj in Config) {
109        // build item from config object
110        string path = obj.Property("Path").Value.ToString();
111        // override default value
112        if (Objects.TryGetValue(path, out IJsonItem param)) {
113          // remove fixed template parameter from config => dont allow to copy them from concrete config
114          // TODO: shift this into JsonItems?
115          obj.Property(nameof(IIntervalRestrictedJsonItem<int>.Minimum))?.Remove();
116          obj.Property(nameof(IIntervalRestrictedJsonItem<int>.Maximum))?.Remove();
117          obj.Property(nameof(IConcreteRestrictedJsonItem<string>.ConcreteRestrictedItems))?.Remove();
118          obj.Property(nameof(IMatrixJsonItem.ColumnsResizable))?.Remove();
119          obj.Property(nameof(IMatrixJsonItem.RowsResizable))?.Remove();
120          obj.Property(nameof(IArrayJsonItem.Resizable))?.Remove();
121          // merge
122          param.SetJObject(obj);
123        } else throw new InvalidDataException($"No parameter with path='{path}' defined!");
124      }
125    }
126    #endregion
127  }
128}
Note: See TracBrowser for help on using the repository browser.