Free cookie consent management tool by TermsFeed Policy Generator

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

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

#3026:

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