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
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 {
[17353]16  /// <summary>
17  /// Static class to instantiate an IAlgorithm object with a json interface template and config.
18  /// </summary>
[17394]19  public static class JsonTemplateInstantiator {
[17349]20    private struct InstData {
21      public JToken Template { get; set; }
22      public JArray Config { get; set; }
[17379]23      public IDictionary<string, JsonItem> Objects { get; set; }
[17349]24    }
[17263]25
[17353]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>
[17395]31    /// <returns>confugrated IOptimizer object</returns>
32    public static IOptimizer Instantiate(string templateFile, string configFile = "") {
[17349]33      InstData instData = new InstData() {
[17394]34        Objects = new Dictionary<string, JsonItem>()
[17349]35      };
[17322]36
[17379]37      // parse template and config files
[17349]38      instData.Template = JToken.Parse(File.ReadAllText(templateFile));
[17330]39      if(!string.IsNullOrEmpty(configFile))
[17349]40        instData.Config = JArray.Parse(File.ReadAllText(configFile));
[17379]41
42      // extract metadata information
[17395]43      string optimizerName = instData.Template[Constants.Metadata][Constants.Optimizer].ToString();
[17379]44      string hLFileLocation = instData.Template[Constants.Metadata][Constants.HLFileLocation].ToString();
[17263]45
[17379]46      // deserialize hl file
47      ProtoBufSerializer serializer = new ProtoBufSerializer();
[17395]48      IOptimizer optimizer = (IOptimizer)serializer.Deserialize(hLFileLocation);
[17379]49
50      // collect all parameterizedItems from template
[17349]51      CollectParameterizedItems(instData);
[17394]52     
[17379]53      // if config != null -> merge Template and Config
[17349]54      if (instData.Config != null)
55        MergeTemplateWithConfig(instData);
[17322]56
[17379]57      // get algorthm data and object
[17395]58      JsonItem optimizerData = instData.Objects[optimizerName];
[17322]59
[17379]60      // inject configuration
[17395]61      JsonItemConverter.Inject(optimizer, optimizerData);
[17266]62
[17395]63      return optimizer;
[17263]64    }
65
[17349]66    #region Helper
67    private static void CollectParameterizedItems(InstData instData) {
[17379]68      foreach (JObject item in instData.Template[Constants.Parameters]) {
[17394]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
[17379]88        JsonItem data = JsonItem.BuildJsonItem(item);
[17394]89        parent.AddChilds(data);
[17379]90        instData.Objects.Add(data.Path, data);
[17322]91      }
[17263]92    }
[17379]93   
[17349]94    private static void MergeTemplateWithConfig(InstData instData) {
95      foreach (JObject obj in instData.Config) {
[17322]96        // build item from config object
[17379]97        JsonItem item = JsonItem.BuildJsonItem(obj);
[17322]98        // override default value
[17379]99        if (instData.Objects.TryGetValue(item.Path, out JsonItem param)) {
[17342]100          param.Value = item.Value;
101          // override ActualName (for LookupParameters)
102          if (param.ActualName != null)
103            param.ActualName = item.ActualName;
[17379]104        } else throw new InvalidDataException($"No parameter with path='{item.Path}' defined!");
[17322]105      }
106    }
107
[17349]108    private static JsonItem GetData(string key, InstData instData)
[17269]109    {
[17394]110      if (instData.Objects.TryGetValue(key, out JsonItem value))
[17322]111        return value;
112      else
113        throw new InvalidDataException($"Type of item '{key}' is not defined!");
[17263]114    }
[17322]115    #endregion
[17263]116  }
117}
Note: See TracBrowser for help on using the repository browser.