Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JCInstantiator.cs @ 17379

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

#3026:

  • removed classes:
    • CheckedItemListConverter: unnecessary
    • ItemCollectionConverter: unnecessary
    • PrimitiveConverter: not possible to implement because it needs to Extract/Inject from/into objects (but interfaces pretends IItem)
    • StorableConverter: unnecessary
    • ConfigurableConverter: unnecessary
  • removed graphviz code in Heuristiclab.ConfigStarter/Program.cs
  • updated Constants
  • some simple code refactors in BaseConverter
  • in JsonItem:
    • renamed Parameters -> Children
    • removed Properties: Operators, Type, Reference, IsConfigurable, IsParameterizedItem
    • removed unnecessary/old code
  • implemented a new way to get data from an object, which is a matrix, in ValueTypeMatrixConverter method: CopyMatrixData
    • converts the object into an array -> rows: from array.Length, cols: when the length is > 0 pick length of first array of index 0 (it is saved as an array of arrays)
  • created a binding flag const in ValueRangeConverter to prevent duplicates in code
File size: 5.1 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 HeuristicLab.SequentialEngine;
14using Newtonsoft.Json.Linq;
15
16namespace HeuristicLab.JsonInterface {
17  /// <summary>
18  /// Static class to instantiate an IAlgorithm object with a json interface template and config.
19  /// </summary>
20  public static class JCInstantiator {
21    private struct InstData {
22      public JToken Template { get; set; }
23      public JArray Config { get; set; }
24      public IDictionary<string, JsonItem> Objects { get; set; }
25      public IDictionary<string, JsonItem> ResolvedItems { get; set; }
26    }
27
28    /// <summary>
29    /// Instantiate an IAlgorithm object with a template and config.
30    /// </summary>
31    /// <param name="templateFile">Template file (json), generated with JCGenerator.</param>
32    /// <param name="configFile">Config file (json) for the template.</param>
33    /// <returns>confugrated IAlgorithm object</returns>
34    public static IAlgorithm Instantiate(string templateFile, string configFile = "") {
35      InstData instData = new InstData() {
36        Objects = new Dictionary<string, JsonItem>(),
37        ResolvedItems = new Dictionary<string, JsonItem>()
38      };
39
40      // parse template and config files
41      instData.Template = JToken.Parse(File.ReadAllText(templateFile));
42      if(!string.IsNullOrEmpty(configFile))
43        instData.Config = JArray.Parse(File.ReadAllText(configFile));
44
45      // extract metadata information
46      string algorithmName = instData.Template[Constants.Metadata][Constants.Algorithm].ToString();
47      string problemName = instData.Template[Constants.Metadata][Constants.Problem].ToString();
48      string hLFileLocation = instData.Template[Constants.Metadata][Constants.HLFileLocation].ToString();
49
50      // deserialize hl file
51      ProtoBufSerializer serializer = new ProtoBufSerializer();
52      IAlgorithm algorithm = (IAlgorithm)serializer.Deserialize(hLFileLocation);
53
54      // collect all parameterizedItems from template
55      CollectParameterizedItems(instData);
56
57      // rebuild tree with paths
58      RebuildTree(instData);
59
60      // if config != null -> merge Template and Config
61      if (instData.Config != null)
62        MergeTemplateWithConfig(instData);
63
64      // get algorthm data and object
65      JsonItem algorithmData = GetData(algorithmName, instData);
66
67      // get problem data and object
68      JsonItem problemData = GetData(problemName, instData);
69
70      // inject configuration
71      JsonItemConverter.Inject(algorithm, algorithmData);
72      if(algorithm.Problem != null)
73        JsonItemConverter.Inject(algorithm.Problem, problemData);
74
75      return algorithm;
76    }
77
78    #region Helper
79    private static void CollectParameterizedItems(InstData instData) {
80      foreach (JObject item in instData.Template[Constants.Parameters]) {
81        JsonItem data = JsonItem.BuildJsonItem(item);
82        instData.Objects.Add(data.Path, data);
83      }
84    }
85   
86    private static JsonItem RebuildTreeHelper(IList<JsonItem> col, string name) {
87      JsonItem target = null;
88      foreach (var val in col) {
89        if (val.Name == name)
90          target = val;
91      }
92      if (target == null) {
93        target = new JsonItem() {
94          Name = name,
95          Path = name,
96          Children = new List<JsonItem>()
97        };
98        col.Add(target);
99      }
100      return target;
101    }
102
103    // rebuilds item tree with splitting paths of each jsonitem
104    private static void RebuildTree(InstData instData) {
105      List<JsonItem> values = new List<JsonItem>();
106      foreach (var x in instData.Objects) {
107        string[] pathParts = x.Key.Split('.');
108        JsonItem target = RebuildTreeHelper(values, pathParts[0]);
109
110        for (int i = 1; i < pathParts.Length; ++i) {
111          target = RebuildTreeHelper(target.Children, pathParts[i]);
112        }
113
114        JsonItem.Merge(target, x.Value);
115      }
116      foreach(var val in values) {
117        instData.ResolvedItems.Add(val.Name, val);
118      }
119    }
120   
121    private static void MergeTemplateWithConfig(InstData instData) {
122      foreach (JObject obj in instData.Config) {
123        // build item from config object
124        JsonItem item = JsonItem.BuildJsonItem(obj);
125        // override default value
126        if (instData.Objects.TryGetValue(item.Path, out JsonItem param)) {
127          param.Value = item.Value;
128          // override ActualName (for LookupParameters)
129          if (param.ActualName != null)
130            param.ActualName = item.ActualName;
131        } else throw new InvalidDataException($"No parameter with path='{item.Path}' defined!");
132      }
133    }
134
135    private static JsonItem GetData(string key, InstData instData)
136    {
137      if (instData.ResolvedItems.TryGetValue(key, out JsonItem value))
138        return value;
139      else
140        throw new InvalidDataException($"Type of item '{key}' is not defined!");
141    }
142    #endregion
143  }
144}
Note: See TracBrowser for help on using the repository browser.