source: branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture/JCGenerator.cs @ 17281

Last change on this file since 17281 was 17281, checked in by dpiringe, 3 years ago

#3026: renamed Transformers -> ...Transformer to ...Converter, ITypeTransformer to IJsonItemConverter, Transformer to JsonItemConverter

File size: 4.0 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using HeuristicLab.Algorithms.GeneticAlgorithm;
5using HeuristicLab.Core;
6using HeuristicLab.Data;
7using HeuristicLab.Encodings.PermutationEncoding;
8using HeuristicLab.Optimization;
9using HeuristicLab.Problems.TravelingSalesman;
10using Newtonsoft.Json;
11using Newtonsoft.Json.Linq;
12using Newtonsoft.Json.Serialization;
13
14namespace HeuristicLab.Manufacture {
15  public class JCGenerator {
16
17    private JObject template = JObject.Parse(@"{
18      'Metadata': {
19        'Algorithm':'',
20        'Problem':''
21      },
22      'Objects': [],
23      'Types': {}
24    }");
25
26    private Dictionary<string, string> TypeList = new Dictionary<string, string>();
27
28    JArray jsonItems = new JArray();
29    private void PopulateJsonItems(Component component) {
30      if (component.Parameters != null) {
31        if(component.Range == null)
32          jsonItems.Add(Serialize(component));
33        foreach (var p in component.Parameters)
34          if(p.Parameters != null)
35            PopulateJsonItems(p);
36      }
37    }
38
39    private JObject Serialize(Component component) {
40      JObject obj = JObject.FromObject(component, Settings());
41      obj["StaticParameters"] = obj["Parameters"];
42      obj["FreeParameters"] = obj["Parameters"];
43
44      obj.Property("Parameters")?.Remove();
45      RefactorFreeParameters(obj, null);
46      RefactorStaticParameters(obj);
47
48      obj.Property("Default")?.Remove();
49      obj.Property("Type")?.Remove();
50
51      TypeList.Add(component.Path, component.Type);
52      return obj;
53    }
54
55    public string GenerateTemplate(IAlgorithm algorithm, IProblem problem, params string[] freeParameters) {
56      algorithm.Problem = problem;
57      Component algorithmData = JsonItemConverter.Extract(algorithm);
58      Component problemData = JsonItemConverter.Extract(problem);
59      PopulateJsonItems(algorithmData);
60      PopulateJsonItems(problemData);
61
62      template["Metadata"]["Algorithm"] = algorithm.Name;
63      template["Metadata"]["Problem"] = problem.Name;
64      template["Objects"] = jsonItems;
65      template["Types"] = JObject.FromObject(TypeList);
66
67      return CustomJsonWriter.Serialize(template);
68    }
69
70    #region Helper
71    private void RefactorFreeParameters(JToken token, string[] freeParameters) {
72
73
74      IList<JObject> objToRemove = new List<JObject>();
75      TransformNodes(x => {
76        var p = x.ToObject<Component>();
77
78        /*bool isSelected = false;
79        string name = x["Name"].ToObject<string>();
80        foreach (var selected in freeParameters)
81          isSelected = (name == selected || isSelected);
82        */
83        if (/*!isSelected ||*/ p.Default == null || (p.Default != null && p.Default.GetType() == typeof(string) && p.Range == null)) {
84          objToRemove.Add(x);
85        } else {
86          x.Property("Path")?.Remove();
87          x.Property("Type")?.Remove();
88          x.Property("Parameters")?.Remove();
89        }
90      }, token["FreeParameters"]);
91      foreach (var x in objToRemove) x.Remove();
92
93    }
94
95    private void RefactorStaticParameters(JToken token) {
96      IList<JObject> objToRemove = new List<JObject>();
97      TransformNodes(x => {
98        var p = x.ToObject<Component>();
99        x.Property("Range")?.Remove();
100        x.Property("Operators")?.Remove();
101        x.Property("Parameters")?.Remove();
102        x.Property("Type")?.Remove();
103        if (p.Default == null) objToRemove.Add(x);
104      }, token["StaticParameters"]);
105      foreach (var x in objToRemove) x.Remove();
106    }
107
108
109    private JsonSerializer Settings() => new JsonSerializer() {
110      TypeNameHandling = TypeNameHandling.None,
111      NullValueHandling = NullValueHandling.Ignore,
112      ReferenceLoopHandling = ReferenceLoopHandling.Serialize
113    };
114
115    private void TransformNodes(Action<JObject> action, params JToken[] tokens) {
116      foreach(JObject obj in tokens.SelectMany(x => x.Children<JObject>()))
117        action(obj);
118    }
119    #endregion
120  }
121}
Note: See TracBrowser for help on using the repository browser.