Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17399 was 17395, checked in by dpiringe, 5 years ago

#3026:

  • moved from usage of IAlgorithm to IOptimizer (in JCGenerator and JsonTemplateInstantiator)
  • added new converter: AlgorithmConverter
File size: 4.3 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  /// <summary>
17  /// Static class to instantiate an IAlgorithm object with a json interface template and config.
18  /// </summary>
19  public static class JsonTemplateInstantiator {
20    private struct InstData {
21      public JToken Template { get; set; }
22      public JArray Config { get; set; }
23      public IDictionary<string, JsonItem> Objects { get; set; }
24    }
25
26    /// <summary>
27    /// Instantiate an IAlgorithm object with a template and config.
28    /// </summary>
29    /// <param name="templateFile">Template file (json), generated with JCGenerator.</param>
30    /// <param name="configFile">Config file (json) for the template.</param>
31    /// <returns>confugrated IOptimizer object</returns>
32    public static IOptimizer Instantiate(string templateFile, string configFile = "") {
33      InstData instData = new InstData() {
34        Objects = new Dictionary<string, JsonItem>()
35      };
36
37      // parse template and config files
38      instData.Template = JToken.Parse(File.ReadAllText(templateFile));
39      if(!string.IsNullOrEmpty(configFile))
40        instData.Config = JArray.Parse(File.ReadAllText(configFile));
41
42      // extract metadata information
43      string optimizerName = instData.Template[Constants.Metadata][Constants.Optimizer].ToString();
44      string hLFileLocation = instData.Template[Constants.Metadata][Constants.HLFileLocation].ToString();
45
46      // deserialize hl file
47      ProtoBufSerializer serializer = new ProtoBufSerializer();
48      IOptimizer optimizer = (IOptimizer)serializer.Deserialize(hLFileLocation);
49
50      // collect all parameterizedItems from template
51      CollectParameterizedItems(instData);
52     
53      // if config != null -> merge Template and Config
54      if (instData.Config != null)
55        MergeTemplateWithConfig(instData);
56
57      // get algorthm data and object
58      JsonItem optimizerData = instData.Objects[optimizerName];
59
60      // inject configuration
61      JsonItemConverter.Inject(optimizer, optimizerData);
62
63      return optimizer;
64    }
65
66    #region Helper
67    private static void CollectParameterizedItems(InstData instData) {
68      foreach (JObject item in instData.Template[Constants.Parameters]) {
69        string[] pathParts = item.Property("Path").Value.ToString().Split('.');
70       
71        // rebuilds object tree
72        JsonItem parent = null;
73        StringBuilder partialPath = new StringBuilder();
74        for(int i = 0; i < pathParts.Length-1; ++i) {
75          partialPath.Append(pathParts[i]);
76          JsonItem tmp = null;
77          if (instData.Objects.TryGetValue(partialPath.ToString(), out JsonItem value)) {
78            tmp = value;
79          } else {
80            tmp = new JsonItem() { Name = pathParts[i] };
81            if (parent != null) parent.AddChilds(tmp);
82            instData.Objects.Add(partialPath.ToString(), tmp);
83          }
84          partialPath.Append(".");
85          parent = tmp;
86        }
87
88        JsonItem data = JsonItem.BuildJsonItem(item);
89        parent.AddChilds(data);
90        instData.Objects.Add(data.Path, data);
91      }
92    }
93   
94    private static void MergeTemplateWithConfig(InstData instData) {
95      foreach (JObject obj in instData.Config) {
96        // build item from config object
97        JsonItem item = JsonItem.BuildJsonItem(obj);
98        // override default value
99        if (instData.Objects.TryGetValue(item.Path, out JsonItem param)) {
100          param.Value = item.Value;
101          // override ActualName (for LookupParameters)
102          if (param.ActualName != null)
103            param.ActualName = item.ActualName;
104        } else throw new InvalidDataException($"No parameter with path='{item.Path}' defined!");
105      }
106    }
107
108    private static JsonItem GetData(string key, InstData instData)
109    {
110      if (instData.Objects.TryGetValue(key, out JsonItem value))
111        return value;
112      else
113        throw new InvalidDataException($"Type of item '{key}' is not defined!");
114    }
115    #endregion
116  }
117}
Note: See TracBrowser for help on using the repository browser.