Free cookie consent management tool by TermsFeed Policy Generator

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

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

#3026

  • removed the option to set the value for JsonItems via exporter
    • reworked some base controls
    • added new controls for JsonItem specific properties (e.g. ArrayResizable)
    • deleted a lot of obsolet controls
  • removed the Enable checkbox in the detail view of JsonItems
  • exporter now clones the IOptimizer object
  • added a check + message for unsupported exports
  • list of JsonItems now includes unsupported JsonItems (disabled and marked with 'unsupported')
  • refactored the converter type check
    • now every converter has to specify its supported type(s)
File size: 4.8 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        res.Add(new ResultJsonItem() { Name = name });
85      }
86      return res;
87    }
88
89    private void CollectParameterizedItems(IOptimizer optimizer) {
90      IJsonItem root = JsonItemConverter.Extract(optimizer);
91      Objects.Add(root.Path, root);
92
93      foreach (JObject obj in Template[Constants.Parameters]) {
94        string path = obj.Property("Path").Value.ToString();
95        foreach(var tmp in root) {
96          if(tmp.Path == path) {
97            tmp.SetJObject(obj);
98            Objects.Add(tmp.Path, tmp);
99          }
100        }
101      }
102    }
103   
104    private void MergeTemplateWithConfig() {
105      foreach (JObject obj in Config) {
106        // build item from config object
107        string path = obj.Property("Path").Value.ToString();
108        // override default value
109        if (Objects.TryGetValue(path, out IJsonItem param)) {
110          // remove fixed template parameter from config => dont allow to copy them from concrete config
111          // TODO: shift this into JsonItems?
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          obj.Property(nameof(IMatrixJsonItem.ColumnsResizable))?.Remove();
116          obj.Property(nameof(IMatrixJsonItem.RowsResizable))?.Remove();
117          obj.Property(nameof(IArrayJsonItem.Resizable))?.Remove();
118          // merge
119          param.SetJObject(obj);
120        } else throw new InvalidDataException($"No parameter with path='{path}' defined!");
121      }
122    }
123    #endregion
124  }
125}
Note: See TracBrowser for help on using the repository browser.