Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17591 was 17560, checked in by dpiringe, 5 years ago

#3026:

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