Free cookie consent management tool by TermsFeed Policy Generator

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

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

#3026

  • renamed ParameterData to Component
  • renamed File Template.cs to Component.cs
File size: 4.5 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Linq;
5using HeuristicLab.Algorithms.GeneticAlgorithm;
6using HeuristicLab.Core;
7using HeuristicLab.Data;
8using HeuristicLab.Encodings.PermutationEncoding;
9using HeuristicLab.Optimization;
10using HeuristicLab.Problems.TravelingSalesman;
11using Newtonsoft.Json;
12using Newtonsoft.Json.Linq;
13using Newtonsoft.Json.Serialization;
14
15namespace HeuristicLab.Manufacture {
16
17  public class CustomWriter : JsonTextWriter {
18    private const int ArrayFlatterLvl = 1;
19    private Stack<Formatting> formattings = new Stack<Formatting>();
20    private int lvl = 0;
21    public override void WriteStartArray() {
22      base.WriteStartArray();
23      if(lvl > ArrayFlatterLvl) {
24        formattings.Push(base.Formatting);
25        base.Formatting = Formatting.None;
26      }
27      lvl++;
28    }
29
30    public override void WriteEndArray() {
31      base.WriteEndArray();
32      lvl--;
33      if (lvl > ArrayFlatterLvl)
34        base.Formatting = formattings.Pop();
35    }
36
37    public CustomWriter(TextWriter writer) : base(writer) { }
38
39    public static string Serialize(JToken token) {
40      JsonSerializer serializer = new JsonSerializer();
41      StringWriter sw = new StringWriter();
42      CustomWriter writer = new CustomWriter(sw);
43      writer.Formatting = Formatting.Indented;
44      serializer.Serialize(writer, token);
45      return sw.ToString();
46    }
47  }
48
49  public class JCGenerator {
50
51    private JObject template = JObject.Parse(@"{
52      'Metadata': {
53        'Algorithm':'',
54        'Problem':''
55      },
56      'Objects': []
57    }");
58
59   
60    private Dictionary<string, string> TypeList = new Dictionary<string, string>();
61   
62    public string GenerateTemplate(IAlgorithm algorithm, IProblem problem, params string[] freeParameters) {
63      algorithm.Problem = problem;
64      Component algorithmData = Transformer.Extract(algorithm);
65      Component problemData = Transformer.Extract(problem);
66      IList<Component> items = algorithmData.ParameterizedItems;
67      foreach (var pItem in problemData.ParameterizedItems) items.Add(pItem);
68      JArray jsonItems = new JArray();
69     
70      foreach(var item in items.Distinct()) {
71        JToken token = JObject.FromObject(item, Settings());
72        token["StaticParameters"] = token["Parameters"];
73        token["FreeParameters"] = token["Parameters"];
74        token.Cast<JObject>().Property("Parameters")?.Remove();
75        RefactorFreeParameters(token, freeParameters);
76        RefactorStaticParameters(token);
77        if(token["StaticParameters"].HasValues || token["FreeParameters"].HasValues)
78          jsonItems.Add(token);
79      }
80
81      template["Metadata"]["Algorithm"] = algorithm.Name;
82      template["Metadata"]["Problem"] = problem.Name;
83      template["Objects"] = jsonItems;
84
85      return CustomWriter.Serialize(template);
86    }
87
88    #region Helper
89    private void RefactorFreeParameters(JToken token, string[] freeParameters) {
90
91      //token["FreeParameters"] = token["StaticParameters"];
92
93      IList<JObject> objToRemove = new List<JObject>();
94      TransformNodes(x => {
95        var p = x.ToObject<Component>();
96
97        /*bool isSelected = false;
98        string name = x["Name"].ToObject<string>();
99        foreach (var selected in freeParameters)
100          isSelected = (name == selected || isSelected);
101        */
102        if (/*!isSelected ||*/ p.Default == null || (p.Default != null && p.Default.GetType() == typeof(string) && p.Range == null)) {
103          objToRemove.Add(x);
104        } else {
105          x.Property("Path")?.Remove();
106          x.Property("Type")?.Remove();
107        }
108      }, token["FreeParameters"]);
109      foreach (var x in objToRemove) x.Remove();
110
111    }
112
113    private void RefactorStaticParameters(JToken token) {
114      IList<JObject> objToRemove = new List<JObject>();
115      TransformNodes(x => {
116        var p = x.ToObject<Component>();
117        x.Property("Range")?.Remove();
118        if (p.Default == null) objToRemove.Add(x);
119      }, token["StaticParameters"]);
120      foreach (var x in objToRemove) x.Remove();
121    }
122
123    private JsonSerializer Settings() => new JsonSerializer() {
124      TypeNameHandling = TypeNameHandling.None,
125      NullValueHandling = NullValueHandling.Ignore
126    };
127
128
129    private void TransformNodes(Action<JObject> action, params JToken[] tokens) {
130      foreach(JObject obj in tokens.SelectMany(x => x.Children<JObject>())) {
131        action(obj);
132      }
133    }
134    #endregion
135  }
136}
Note: See TracBrowser for help on using the repository browser.