1 | using System.Collections.Generic;
|
---|
2 | using HeuristicLab.Optimization;
|
---|
3 | using Newtonsoft.Json.Linq;
|
---|
4 | using HEAL.Attic;
|
---|
5 | using System.IO;
|
---|
6 |
|
---|
7 | namespace HeuristicLab.JsonInterface {
|
---|
8 | /// <summary>
|
---|
9 | /// Class to generate json interface templates.
|
---|
10 | /// </summary>
|
---|
11 | public class JsonTemplateGenerator {
|
---|
12 |
|
---|
13 | public static void GenerateTemplate(string path, IOptimizer optimizer) =>
|
---|
14 | GenerateTemplate(path, optimizer.Name, optimizer);
|
---|
15 |
|
---|
16 | public static void GenerateTemplate(string path, string templateName, IOptimizer optimizer) =>
|
---|
17 | GenerateTemplate(path, templateName, optimizer, JsonItemConverter.Extract(optimizer));
|
---|
18 |
|
---|
19 | public static void GenerateTemplate(string path, string templateName, IOptimizer optimizer, IJsonItem rootItem) {
|
---|
20 | #region Init
|
---|
21 | JObject template = JObject.Parse(Constants.Template);
|
---|
22 | JArray parameterItems = new JArray();
|
---|
23 | JArray resultItems = new JArray();
|
---|
24 | IList<IJsonItem> jsonItems = new List<IJsonItem>();
|
---|
25 | string fullPath = Path.GetFullPath(path);
|
---|
26 | #endregion
|
---|
27 |
|
---|
28 | // recursively filter items with values/ranges/actualNames
|
---|
29 | PopulateJsonItems(rootItem, jsonItems);
|
---|
30 |
|
---|
31 | #region Serialize HL File
|
---|
32 | ProtoBufSerializer serializer = new ProtoBufSerializer();
|
---|
33 | string hlFilePath = Path.Combine(fullPath, templateName + ".hl");
|
---|
34 | serializer.Serialize(optimizer, hlFilePath);
|
---|
35 | #endregion
|
---|
36 |
|
---|
37 | #region Filter Items
|
---|
38 | foreach (var item in jsonItems) {
|
---|
39 | if (item is IResultJsonItem)
|
---|
40 | resultItems.Add(item.GenerateJObject());
|
---|
41 | else
|
---|
42 | parameterItems.Add(item.GenerateJObject());
|
---|
43 | }
|
---|
44 | #endregion
|
---|
45 |
|
---|
46 | #region Set Template Data
|
---|
47 | template[Constants.Metadata][Constants.TemplateName] = templateName;
|
---|
48 | template[Constants.Metadata][Constants.HLFileLocation] = hlFilePath;
|
---|
49 | template[Constants.Parameters] = parameterItems;
|
---|
50 | template[Constants.Results] = resultItems;
|
---|
51 | #endregion
|
---|
52 |
|
---|
53 | #region Serialize and write to file
|
---|
54 | File.WriteAllText(fullPath + @"\" + templateName + ".json", SingleLineArrayJsonWriter.Serialize(template));
|
---|
55 | #endregion
|
---|
56 | }
|
---|
57 |
|
---|
58 | #region Helper
|
---|
59 | private static void PopulateJsonItems(IJsonItem item, IList<IJsonItem> jsonItems) {
|
---|
60 | foreach(var x in item) {
|
---|
61 | if (x.Active && !(x is EmptyJsonItem)) {
|
---|
62 | jsonItems.Add(x);
|
---|
63 | }
|
---|
64 | }
|
---|
65 | }
|
---|
66 | #endregion
|
---|
67 | }
|
---|
68 | }
|
---|