Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17477 was 17477, checked in by dpiringe, 4 years ago

#3026:

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