Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17511 was 17483, checked in by dpiringe, 5 years ago

#3026:

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