Changeset 17275


Ignore:
Timestamp:
09/26/19 17:43:44 (3 weeks ago)
Author:
dpiringe
Message:

#3026

  • deleted Util.cs
  • BaseTransformer merges now the component with its reference (if a reference exists) -> easier handling for transformers with parameterizedItems
  • MultiCheckedOperatorTransformer now sets the type name as default value
  • added a type list at the end of the template file -> is needed to instantiate objects
  • changed JCGenerator and JCInstantiator to test a format where FreeParameters and StaticParameters are saved as single Parameter array
Location:
branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture
Files:
1 deleted
8 edited

Legend:

Unmodified
Added
Removed
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture/Component.cs

    r17271 r17275  
    66using HeuristicLab.Core;
    77using Newtonsoft.Json;
     8using Newtonsoft.Json.Linq;
    89
    9 namespace HeuristicLab.Manufacture {   
    10   /*
    11   public class ParameterData { //Blueprint, Component,  ?
     10namespace HeuristicLab.Manufacture {
     11  public class Component {
     12    private IList<object> range;
     13    private object defaultValue;
     14
    1215    public string Name { get; set; }
    1316    public string Type { get; set; }
    14     public IList<ParameterData> FreeParameters { get; set; }
    15     public IList<ParameterData> StaticParameters { get; set; }
     17    public object Default {
     18      get => defaultValue;
     19      set {
     20        defaultValue = value;
     21        if(Range != null && value != null && !FulfillConstraints())
     22          throw new ArgumentOutOfRangeException("Default", "Default is not in range.");
     23      }
     24    }
     25    public string Path { get; set; }
    1626
    17   }*/
    18 
    19   public class Component {
    20     public string Name { get; set; }
    21     public string Type { get; set; }
    22     public object Default { get; set; }
    23     public string Path { get; set; }
    24     public IList<object> Range { get; set; }
     27    public IList<object> Range {
     28      get => range;
     29      set {
     30        range = value;
     31        if (Default != null && value != null && !FulfillConstraints())
     32          throw new ArgumentOutOfRangeException("Default", "Default is not in range.");
     33      }
     34    }
    2535
    2636    public IList<Component> Parameters { get; set; }
    2737    public IList<Component> Operators { get; set; }
    28 
    29     [JsonIgnore]
    30     public Component this[string index] {
    31       get {
    32         if (Parameters == null) return null;
    33         foreach (var p in Parameters)
    34           if (p.Name == index) return p;
    35         return null;
    36       }
    37       set {
    38         if (Parameters == null)
    39           Parameters = new List<Component>();
    40         Component data = this[index];
    41         if (data != null && CheckConstraints(value))
    42           Merge(data, value);
    43         else
    44           Parameters.Add(value);
    45       }
    46     }
    47 
    48     public override bool Equals(object obj) {
    49       if (!(obj is Component))
    50         return false;
    51       else
    52         return obj.Cast<Component>().Name == this.Name;
    53     }
    54 
    55     public override int GetHashCode() {
    56       return Name.GetHashCode();
    57     }
     38   
     39    public override bool Equals(object obj) =>
     40      (obj is Component ? (obj.Cast<Component>().Name == this.Name) : false);
     41     
     42    public override int GetHashCode() => Name.GetHashCode();
    5843
    5944    [JsonIgnore]
     
    6247    [JsonIgnore]
    6348    public Component Reference { get; set; }
    64 
    65     #region Helper
     49   
    6650    public static void Merge(Component target, Component from) {
    6751      target.Name = from.Name ?? target.Name;
     
    7357      target.Parameters = from.Parameters ?? target.Parameters;
    7458      target.ParameterizedItems = from.ParameterizedItems ?? target.ParameterizedItems;
     59      target.Operators = from.Operators ?? target.Operators;
    7560    }
    7661
    77     private bool CheckConstraints(Component data) =>
     62    public bool FulfillConstraints() => FulfillConstraints(this);
     63
     64    public static bool FulfillConstraints(Component data) =>
    7865      data.Range != null && data.Default != null && (
    7966      IsInRangeList(data.Range, data.Default) ||
    8067      IsInNumericRange<long>(data.Default, data.Range[0], data.Range[1]) ||
     68      IsInNumericRange<int>(data.Default, data.Range[0], data.Range[1]) ||
     69      IsInNumericRange<short>(data.Default, data.Range[0], data.Range[1]) ||
     70      IsInNumericRange<byte>(data.Default, data.Range[0], data.Range[1]) ||
     71      IsInNumericRange<float>(data.Default, data.Range[0], data.Range[1]) ||
    8172      IsInNumericRange<double>(data.Default, data.Range[0], data.Range[1]));
    8273
    83     private bool IsInRangeList(IEnumerable<object> list, object value) {
     74    #region Helper
     75
     76    private static bool IsInRangeList(IEnumerable<object> list, object value) {
    8477      foreach (var x in list)
    8578        if (x.Equals(value)) return true;
     
    8780    }
    8881
    89     private bool IsInNumericRange<T>(object value, object min, object max) where T : IComparable =>
     82    private static bool IsInNumericRange<T>(object value, object min, object max) where T : IComparable =>
    9083      (value != null && min != null && max != null && value is T && min is T && max is T &&
    9184        (((T)min).CompareTo(value) == -1 || ((T)min).CompareTo(value) == 0) &&
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture/HeuristicLab.Manufacture.csproj

    r17271 r17275  
    7373    <Compile Include="Interfaces\ITypeTransformer.cs" />
    7474    <Compile Include="Transformer.cs" />
    75     <Compile Include="Util.cs" />
    7675  </ItemGroup>
    7776  <ItemGroup>
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture/JCGenerator.cs

    r17271 r17275  
    1919    private Stack<Formatting> formattings = new Stack<Formatting>();
    2020    private int lvl = 0;
     21    private bool isRangeArray = false;
    2122    public override void WriteStartArray() {
    2223      base.WriteStartArray();
     24      /*
    2325      if(lvl > ArrayFlatterLvl) {
    2426        formattings.Push(base.Formatting);
     
    2628      }
    2729      lvl++;
     30      */
     31      if(isRangeArray) base.Formatting = Formatting.None;
    2832    }
    2933
    3034    public override void WriteEndArray() {
    3135      base.WriteEndArray();
     36      /*
    3237      lvl--;
    3338      if (lvl > ArrayFlatterLvl)
    3439        base.Formatting = formattings.Pop();
     40      */
     41      if(isRangeArray) {
     42        base.Formatting = Formatting.Indented;
     43        isRangeArray = false;
     44      }
     45    }
     46
     47    public override void WritePropertyName(string name) {
     48      base.WritePropertyName(name);
     49      isRangeArray = name == "Range";
    3550    }
    3651
     
    5469        'Problem':''
    5570      },
    56       'Objects': []
     71      'Objects': [],
     72      'Types': {}
    5773    }");
    5874
    59    
    6075    private Dictionary<string, string> TypeList = new Dictionary<string, string>();
    6176   
     
    6984     
    7085      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)
     86        JObject token = JObject.FromObject(item, Settings());
     87        //token["StaticParameters"] = token["Parameters"];
     88        //token["FreeParameters"] = token["Parameters"];
     89
     90        foreach (JObject x in token["Parameters"]) {
     91          x.Property("Parameters")?.Remove();
     92          x.Property("Type")?.Remove();
     93        }
     94        TypeList.Add(item.Name, item.Type);
     95        RefactorParameters(token);
     96        /*
     97        foreach (JObject x in token["StaticParameters"]) {
     98          x.Property("Parameters")?.Remove();
     99          x.Property("Type")?.Remove();
     100        }
     101        foreach (JObject x in token["FreeParameters"]) {
     102          x.Property("Parameters")?.Remove();
     103          x.Property("Type")?.Remove();
     104        }
     105        */
     106        //token.Cast<JObject>().Property("Parameters")?.Remove();
     107        token.Property("Default")?.Remove();
     108        token.Property("Type")?.Remove();
     109
     110        //RefactorFreeParameters(token, freeParameters);
     111        //RefactorStaticParameters(token);
     112        if (/*token["StaticParameters"].HasValues || token["FreeParameters"].HasValues ||*/ token["Parameters"].HasValues || (token["Operators"]?.HasValues ?? false))
    78113          jsonItems.Add(token);
     114
     115        if(!token["Parameters"].HasValues) {
     116          token.Property("Parameters")?.Remove();
     117        }
    79118      }
    80119
     
    82121      template["Metadata"]["Problem"] = problem.Name;
    83122      template["Objects"] = jsonItems;
     123      template["Types"] = JObject.FromObject(TypeList);
    84124
    85125      return CustomWriter.Serialize(template);
     
    121161    }
    122162
     163    private void RefactorParameters(JToken token) {
     164      IList<JObject> objToRemove = new List<JObject>();
     165      TransformNodes(x => {
     166        var p = x.ToObject<Component>();
     167        if (p.Default == null) objToRemove.Add(x);
     168      }, token["Parameters"]);
     169      foreach (var x in objToRemove) x.Remove();
     170    }
     171
    123172    private JsonSerializer Settings() => new JsonSerializer() {
    124173      TypeNameHandling = TypeNameHandling.None,
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture/JCInstantiator.cs

    r17271 r17275  
    1313
    1414namespace HeuristicLab.Manufacture {
    15 
    16  
    1715  public class JCInstantiator {
    1816
    1917    private JToken Config { get; set; }
     18    private Dictionary<string, string> TypeList = new Dictionary<string, string>();
    2019
    2120    public IAlgorithm Instantiate(string configFile) {
    2221      Config = JToken.Parse(File.ReadAllText(configFile));
     22      TypeList = Config["Types"].ToObject<Dictionary<string, string>>();
    2323
    2424      Component algorithmData = GetData(Config["Metadata"]["Algorithm"].ToString());
     
    3737    }
    3838
    39     /*
    40      * resolve references
    41      */
    42 
    4339    private void ResolveReferences(Component data) {
    44       foreach (var p in data.Parameters) {
    45         if (p.Default is string && p.Reference == null) {
     40      foreach (var p in data.Parameters)
     41        if (p.Default is string && p.Reference == null)
    4642          p.Reference = GetData(p.Default.Cast<string>());
    47         }
    48       }
    4943    }
    5044
     
    5347      foreach(JObject item in Config["Objects"])
    5448      {
    55         Component data = BuildDataFromJObject(item);
     49        Component data = item.ToObject<Component>();// Component.Build(item);
    5650        if (data.Name == key) return data;
    5751      }
     
    5953    }
    6054
    61     private Component BuildDataFromJObject(JObject obj) {
    62       Component data = new Component() {
    63         Name = obj["Name"]?.ToString(),
    64         Default = obj["Default"]?.ToObject<object>(),
    65         Range = obj["Range"]?.ToObject<object[]>(),
    66         Type = obj["Type"]?.ToObject<string>()
     55    private T CreateObject<T>(Component data) {
     56      if (TypeList.TryGetValue(data.Name, out string typeName)) {
     57        Type type = Type.GetType(typeName);
     58        return (T)Activator.CreateInstance(type);
     59      } else throw new TypeLoadException($"Cannot find AssemblyQualifiedName for {data.Name}.");
     60    }
     61
     62    private Component BuildComponent(JObject obj) =>
     63      new Component() {
     64        Name = obj[nameof(Component.Name)]?.ToString(),
     65        Default = obj[nameof(Component.Default)]?.ToObject<object>(),
     66        Range = obj[nameof(Component.Range)]?.ToObject<object[]>(),
     67        Type = obj[nameof(Component.Type)]?.ToObject<string>(),
     68        Parameters = PopulateParameters(obj),
     69        Operators = PopulateOperators(obj)
    6770      };
    6871
    69       if(obj["StaticParameters"] != null)
    70         foreach (JObject sp in obj["StaticParameters"])
    71           data[sp["Name"].ToString()] = BuildDataFromJObject(sp);
     72    private IList<Component> PopulateParameters(JObject obj) {
     73      IList<Component> list = new List<Component>();
     74      if (obj["StaticParameters"] != null)
     75        foreach (JObject param in obj["StaticParameters"])
     76          list.Add(BuildComponent(param));
    7277
    73       if (obj["FreeParameters"] != null)
    74         foreach (JObject sp in obj["FreeParameters"])
    75           data[sp["Name"].ToString()] = BuildDataFromJObject(sp);
    76 
    77       if (obj["Operators"] != null) {
    78         data.Operators = new List<Component>();
    79         foreach (JObject sp in obj["Operators"])
    80           data.Operators.Add(BuildDataFromJObject(sp));
     78      if (obj["FreeParameters"] != null) {
     79        foreach (JObject param in obj["FreeParameters"]) {
     80          Component tmp = BuildComponent(param);
     81          Component comp = null;
     82          foreach (var p in list)
     83            if (p.Name == tmp.Name) comp = p;
     84          if (comp != null)
     85            Component.Merge(comp, tmp);
     86          else list.Add(tmp);
     87        }
    8188      }
    82 
    83       return data;
     89      return list;
    8490    }
    8591
    86     private T CreateObject<T>(Component data) {
    87       Type type = Type.GetType(data.Type);
    88       return (T)Activator.CreateInstance(type);
     92    private IList<Component> PopulateOperators(JObject obj) {
     93      IList<Component> list = new List<Component>();
     94      if (obj[nameof(Operators)] != null)
     95        foreach (JObject sp in obj[nameof(Operators)]) {
     96          Component tmp = BuildComponent(sp);
     97          list.Add(tmp);
     98        }
     99      return list;
    89100    }
    90 
    91101  }
    92102}
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture/ParameterTransformer/ParameterizedItemTransformer.cs

    r17271 r17275  
    1313      IParameterizedItem pItem = item.Cast<IParameterizedItem>();
    1414
    15       foreach (var sp in data.Parameters)
    16         if (pItem.Parameters.TryGetValue(sp.Name, out IParameter param))
    17           Transformer.Inject(param, sp);
     15      if(data.Parameters != null) {
     16        foreach (var sp in data.Parameters)
     17          if (pItem.Parameters.TryGetValue(sp.Name, out IParameter param))
     18            Transformer.Inject(param, sp);
     19      }
    1820    }
    1921
     
    2527      obj.Type = value.GetType().AssemblyQualifiedName;
    2628      obj.ParameterizedItems = list;
     29      obj.Parameters = new List<Component>();
    2730      list.Add(obj);
    2831
     
    3033        if (!param.Hidden) {
    3134          Component data = Transformer.Extract(param);
    32           obj[data.Name] = data;
     35          obj.Parameters.Add(data);
    3336          if(data.ParameterizedItems != null)
    3437            list.AddRange(data.ParameterizedItems);
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture/Program.cs

    r17269 r17275  
    3535
    3636      JCGenerator gen = new JCGenerator();
    37       //File.WriteAllText(@"C:\Workspace\TemplateProto10.json", gen.GenerateTemplate(alg, tsp));
     37      File.WriteAllText(@"C:\Workspace\TemplateProto10.json", gen.GenerateTemplate(alg, tsp));
    3838     
    3939      JCInstantiator configurator = new JCInstantiator();
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture/TypeTransformer/BaseTransformer.cs

    r17271 r17275  
    1616    }
    1717
    18     public void Inject(IItem item, Component data) => InjectData(item, data);
     18    public void Inject(IItem item, Component data) {
     19      if(data.Reference != null) {
     20        Component.Merge(data, data.Reference);
     21      }
     22      InjectData(item, data);
     23    }
    1924
    2025    public abstract void InjectData(IItem item, Component data);
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture/TypeTransformer/MultiCheckedOperatorTransformer.cs

    r17271 r17275  
    1010    public override Component ExtractData(IItem value) {
    1111      Component data = base.ExtractData(value);
     12      data.Default = value.GetType().Name;
    1213
    1314      data.Operators = new List<Component>();
Note: See TracChangeset for help on using the changeset viewer.