Free cookie consent management tool by TermsFeed Policy Generator

Changeset 17379


Ignore:
Timestamp:
12/17/19 17:16:03 (5 years ago)
Author:
dpiringe
Message:

#3026:

  • removed classes:
    • CheckedItemListConverter: unnecessary
    • ItemCollectionConverter: unnecessary
    • PrimitiveConverter: not possible to implement because it needs to Extract/Inject from/into objects (but interfaces pretends IItem)
    • StorableConverter: unnecessary
    • ConfigurableConverter: unnecessary
  • removed graphviz code in Heuristiclab.ConfigStarter/Program.cs
  • updated Constants
  • some simple code refactors in BaseConverter
  • in JsonItem:
    • renamed Parameters -> Children
    • removed Properties: Operators, Type, Reference, IsConfigurable, IsParameterizedItem
    • removed unnecessary/old code
  • implemented a new way to get data from an object, which is a matrix, in ValueTypeMatrixConverter method: CopyMatrixData
    • converts the object into an array -> rows: from array.Length, cols: when the length is > 0 pick length of first array of index 0 (it is saved as an array of arrays)
  • created a binding flag const in ValueRangeConverter to prevent duplicates in code
Location:
branches/3026_IntegrationIntoSymSpace
Files:
5 deleted
16 edited

Legend:

Unmodified
Added
Removed
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Constants.cs

    r17353 r17379  
    1414    internal const string Algorithm = "Algorithm";
    1515    internal const string Problem = "Problem";
    16     internal const string Objects = "Objects";
    17     internal const string Types = "Types";
    18     internal const string StaticParameters = "StaticParameters";
    19     internal const string FreeParameters = "FreeParameters";
     16    internal const string HLFileLocation = "HLFileLocation";
     17    internal const string Parameters = "Parameters";
    2018
    2119    internal const string Template = @"{
    22       'Metadata': {
    23         'Algorithm':'',
    24         'Problem':''
     20      '" + Metadata + @"': {
     21        '" + Algorithm + @"':'',
     22        '" + Problem + @"':'',
     23        '" + HLFileLocation + @"':''
    2524      },
    26       'Objects': [],
    27       'Types': {}
     25      '" + Parameters + @"': []
    2826    }";
    2927  }
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/BaseConverter.cs

    r17374 r17379  
    1212  {
    1313    public void Inject(IItem item, JsonItem data) {
    14       if (data.Reference != null) {
    15         JsonItem.Merge(data, data.Reference);
    16       }
    1714      InjectData(item, data);
    1815    }
     
    2118      JsonItem data = ExtractData(value);
    2219      data.Name = string.IsNullOrEmpty(data.Name) ? value.ItemName : data.Name;
    23       data.Type = string.IsNullOrEmpty(data.Type) ? value.GetType().AssemblyQualifiedName : data.Type;
    2420      return data;
    2521    }
     
    3127    protected ValueType CastValue<ValueType>(object obj) {
    3228      if (obj is JToken)
    33         return (obj.Cast<JToken>()).ToObject<ValueType>();
     29        return obj.Cast<JToken>().ToObject<ValueType>();
    3430      else if (obj is IConvertible)
    3531        return Convert.ChangeType(obj, typeof(ValueType)).Cast<ValueType>();
     
    4945
    5046      switch (typeCode) {
    51         case TypeCode.Int16: return Int16.MaxValue;
    52         case TypeCode.Int32: return Int32.MaxValue;
    53         case TypeCode.Int64: return Int64.MaxValue;
    54         case TypeCode.UInt16: return UInt16.MaxValue;
    55         case TypeCode.UInt32: return UInt32.MaxValue;
    56         case TypeCode.UInt64: return UInt64.MaxValue;
    57         case TypeCode.Single: return Single.MaxValue;
    58         case TypeCode.Double: return Double.MaxValue;
    59         case TypeCode.Decimal: return Decimal.MaxValue;
    60         case TypeCode.Byte: return Byte.MaxValue;
     47        case TypeCode.Int16: return short.MaxValue;
     48        case TypeCode.Int32: return int.MaxValue;
     49        case TypeCode.Int64: return long.MaxValue;
     50        case TypeCode.UInt16: return ushort.MaxValue;
     51        case TypeCode.UInt32: return uint.MaxValue;
     52        case TypeCode.UInt64: return ulong.MaxValue;
     53        case TypeCode.Single: return float.MaxValue;
     54        case TypeCode.Double: return double.MaxValue;
     55        case TypeCode.Decimal: return decimal.MaxValue;
     56        case TypeCode.Byte: return byte.MaxValue;
    6157        case TypeCode.Boolean: return true;
    6258        default: return GetDefaultValue(t);
     
    7167
    7268      switch (typeCode) {
    73         case TypeCode.Int16: return Int16.MinValue;
    74         case TypeCode.Int32: return Int32.MinValue;
    75         case TypeCode.Int64: return Int64.MinValue;
    76         case TypeCode.UInt16: return UInt16.MinValue;
    77         case TypeCode.UInt32: return UInt32.MinValue;
    78         case TypeCode.UInt64: return UInt64.MinValue;
    79         case TypeCode.Single: return Single.MinValue;
    80         case TypeCode.Double: return Double.MinValue;
    81         case TypeCode.Decimal: return Decimal.MinValue;
    82         case TypeCode.Byte: return Byte.MinValue;
     69        case TypeCode.Int16: return short.MinValue;
     70        case TypeCode.Int32: return int.MinValue;
     71        case TypeCode.Int64: return long.MinValue;
     72        case TypeCode.UInt16: return ushort.MinValue;
     73        case TypeCode.UInt32: return uint.MinValue;
     74        case TypeCode.UInt64: return ulong.MinValue;
     75        case TypeCode.Single: return float.MinValue;
     76        case TypeCode.Double: return double.MinValue;
     77        case TypeCode.Decimal: return decimal.MinValue;
     78        case TypeCode.Byte: return byte.MinValue;
    8379        case TypeCode.Boolean: return false;
    8480        default: return GetDefaultValue(t);
     
    8783
    8884    protected object GetDefaultValue(Type t) => t.IsValueType ? Activator.CreateInstance(t) : null;
    89 
    9085    #endregion
    9186  }
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ConstrainedValueParameterConverter.cs

    r17353 r17379  
    1414          parameter.ActualValue = x;
    1515
    16       if (parameter.ActualValue is IParameterizedItem && data.Reference != null)
    17         JsonItemConverter.Inject(parameter.ActualValue, data.Reference);
     16      if (parameter.ActualValue is IParameterizedItem && data.Children != null) {
     17        foreach(var param in data.Children) {
     18          if(param.Name == parameter.ActualValue.ItemName)
     19            JsonItemConverter.Inject(parameter.ActualValue, param);
     20        }
     21      }
    1822    }
    1923
     
    2327        Value = value.ActualValue?.ToString(),
    2428        Range = GetValidValues(value).Select(x => x.ToString()),
    25         Parameters = GetParameterizedChilds(value)
     29        Children = GetParameterizedChilds(value)
    2630      };
    2731
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/MultiCheckedOperatorConverter.cs

    r17374 r17379  
    1212      JsonItem data = base.ExtractData(value);
    1313
    14       if(data.Parameters == null)
    15         data.Parameters = new List<JsonItem>();
     14      if(data.Children == null)
     15        data.Children = new List<JsonItem>();
    1616      dynamic val = value.Cast<dynamic>();
    1717      foreach (var op in val.Operators) {
    18         data.Parameters.Add(new JsonItem() {
     18        data.Children.Add(new JsonItem() {
    1919          Name = op.Name,
    2020          Value = val.Operators.ItemChecked(op),
    21           Range = new object[] { false, true }/*,
    22           Path = data.Path + "." + op.Name*/
     21          Range = new object[] { false, true }
    2322        });
    2423      }
     
    3534
    3635    private bool GetOperatorState(string name, JsonItem data) {
    37       foreach(var op in data.Operators) {
    38         if (op.Name == name) return op.Value.Cast<bool>();
     36      foreach(var op in data.Children) {
     37        if (op.Name == name && op.Value is bool) return op.Value.Cast<bool>();
    3938      }
    4039      return false;
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ParameterBaseConverter.cs

    r17374 r17379  
    88namespace HeuristicLab.JsonInterface {
    99  public abstract class ParameterBaseConverter : BaseConverter {
    10     public override JsonItem ExtractData(IItem value) {
    11       IParameter param = value.Cast<IParameter>();
    12       JsonItem comp = ExtractData(param);
    13       return comp;
    14     }
     10    public override JsonItem ExtractData(IItem value) =>
     11      ExtractData(value.Cast<IParameter>());
     12
    1513    public abstract JsonItem ExtractData(IParameter value);
    1614
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ParameterizedItemConverter.cs

    r17374 r17379  
    1111      IParameterizedItem pItem = item.Cast<IParameterizedItem>();
    1212
    13       if(data.Parameters != null) {
    14         foreach (var sp in data.Parameters)
     13      if(data.Children != null) {
     14        foreach (var sp in data.Children)
    1515          if (pItem.Parameters.TryGetValue(sp.Name, out IParameter param))
    1616            JsonItemConverter.Inject(param, sp);
     
    2727          //data.Name = param.Name;
    2828
    29           if (item.Parameters == null)
    30             item.Parameters = new List<JsonItem>();
    31           item.Parameters.Add(data);
     29          if (item.Children == null)
     30            item.Children = new List<JsonItem>();
     31          item.Children.Add(data);
    3232        }
    3333      }
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/RegressionProblemDataConverter.cs

    r17375 r17379  
    1414      JsonItem item = new JsonItem() {
    1515        Path = value.ItemName,
    16         Parameters = new List<JsonItem>()
     16        Children = new List<JsonItem>()
    1717      };
    18 
    19       Type type = value.GetType();
    20 
     18     
    2119      dynamic val = (dynamic)value;
    2220      object dataset = (object)val.Dataset;
     
    2422      FieldInfo dataInfo = dataset.GetType().GetField("storableData", flags);
    2523      // TODO: aufteilen in trainings und test daten abschnitte
    26       item.Parameters.Add(new JsonItem() {
     24      item.Children.Add(new JsonItem() {
    2725        Name = "Dataset",
    2826        Value = dataInfo.GetValue(dataset),
     
    3129
    3230      IEnumerable<StringValue> variables = (IEnumerable<StringValue>)val.InputVariables;
    33       item.Parameters.Add(new JsonItem() {
     31      item.Children.Add(new JsonItem() {
    3432        Name = "TargetVariable",
    3533        Value = (object)targetVariable,
     
    3937
    4038
    41       item.Parameters.Add(new JsonItem() {
     39      item.Children.Add(new JsonItem() {
    4240        Name = "AllowedInputVariables",
    4341        Value = (object)val.AllowedInputVariables,
     
    4644      });
    4745
    48       /*
    49       item.Parameters.Add(new JsonItem() {
    50         Name = "InputVariables",
    51         Value = variables.Select(x => x.Value),
    52         Path = "InputVariables"
    53       });
    54       */
    5546      item.UpdatePath();
    5647
     
    5950
    6051    public override void InjectData(IItem item, JsonItem data) {
     52      // TODO: inject data
    6153      throw new NotImplementedException();
    6254    }
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ValueLookupParameterConverter.cs

    r17353 r17379  
    1616        actualValue = tmp.Value;
    1717        actualRange = tmp.Range;
     18      } else {
     19        actualRange = new object[] { GetMinValue(param.DataType), GetMaxValue(param.DataType) };
    1820      }
     21
    1922      return new JsonItem() {
    2023        Name = value.Name,
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ValueRangeConverter.cs

    r17374 r17379  
    1919    where TType : struct {
    2020
     21    private const BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Instance;
     22
    2123    public override JsonItem ExtractData(IItem value) {
    22       var field = value.GetType().GetField("values", BindingFlags.NonPublic | BindingFlags.Instance);
     24      var field = value.GetType().GetField("values", Flags);
    2325      Tuple<T,T> tuple = (Tuple<T,T>)field.GetValue(value);
    2426
     
    3436      object[] arr = (object[])data.Value;
    3537      Tuple<T,T> tuple = new Tuple<T,T>(Instantiate<T>(arr[0]), Instantiate<T>(arr[1]));
    36       var field = item.GetType().GetField("values", BindingFlags.NonPublic | BindingFlags.Instance);
     38      var field = item.GetType().GetField("values", Flags);
    3739      field.SetValue(tuple, item);
    3840    }
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ValueTypeMatrixConverter.cs

    r17374 r17379  
    1414  {
    1515    public override void InjectData(IItem item, JsonItem data) =>
    16       CopyMatrixData(item.Cast<MatrixType>(), CastValue<T[,]>(data.Value));
     16      CopyMatrixData(item.Cast<MatrixType>(), data.Value);
    1717
    1818    public override JsonItem ExtractData(IItem value) =>
     
    2323
    2424    #region Helper
    25     private void CopyMatrixData(MatrixType matrix, T[,] data) {
    26       var rowInfo = matrix.GetType().GetProperty("Rows");
    27       rowInfo.SetValue(matrix, data.GetLength(0));
    28       var colInfo = matrix.GetType().GetProperty("Columns");
    29       colInfo.SetValue(matrix, data.GetLength(1));
     25    private void CopyMatrixData(MatrixType matrix, object data) {
     26      if (data is Array arr) {
     27        var rows = arr.Length;
     28        var cols = arr.Length > 0 && arr.GetValue(0) is JArray jarr ? jarr.Count : 0;
    3029
    31       for (int x = 0; x < data.GetLength(0); ++x) {
    32         for (int y = 0; y < data.GetLength(1); ++y) {
    33           matrix[x, y] = data[x, y];
     30        var rowInfo = matrix.GetType().GetProperty("Rows");
     31        rowInfo.SetValue(matrix, rows);
     32        var colInfo = matrix.GetType().GetProperty("Columns");
     33        colInfo.SetValue(matrix, cols);
     34
     35        for (int x = 0; x < rows; ++x) {
     36          jarr = (JArray)arr.GetValue(x);
     37          for (int y = 0; y < cols; ++y) {
     38            matrix[x, y] = jarr[y].ToObject<T>();
     39          }
    3440        }
    3541      }
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/HeuristicLab.JsonInterface.csproj

    r17374 r17379  
    6363    <Compile Include="Attributes\ConvertableAttribute.cs" />
    6464    <Compile Include="Constants.cs" />
    65     <Compile Include="Converters\CheckedItemListConverter.cs" />
    66     <Compile Include="Converters\ConfigurableConverter.cs" />
    67     <Compile Include="Converters\ItemCollectionConverter.cs" />
    68     <Compile Include="Converters\PrimitiveConverter.cs" />
    6965    <Compile Include="Converters\RegressionProblemDataConverter.cs" />
    70     <Compile Include="Converters\StorableConverter.cs" />
    7166    <Compile Include="Converters\ValueLookupParameterConverter.cs" />
    7267    <Compile Include="Converters\ValueRangeConverter.cs" />
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JCGenerator.cs

    r17374 r17379  
    1717    private struct GenData {
    1818      public JObject Template { get; set; }
    19       public IDictionary<string, string> TypeList { get; set; }
    2019      public JArray JsonItems { get; set; }
    2120    }
     
    2524      GenData genData = new GenData() {
    2625        Template = JObject.Parse(Constants.Template),
    27         TypeList = new Dictionary<string, string>(),
    2826        JsonItems = new JArray()
    2927      };
     
    3129      ProtoBufSerializer serializer = new ProtoBufSerializer();
    3230      serializer.Serialize(algorithm, @"C:\Workspace\template.hl");
    33      
     31      genData.Template[Constants.Metadata][Constants.HLFileLocation] = @"C:\Workspace\template.hl";
    3432
    35       // 1.1. extract JsonItem, save the name in the metadata section of the
     33      // extract JsonItem, save the name in the metadata section of the
    3634      // template and save it an JArray incl. all parameters of the JsonItem,
    3735      // which have parameters aswell
    3836      AddInstantiableIItem(Constants.Algorithm, algorithm, genData);
    3937      //IsConvertable(algorithm, true);
    40       if (algorithm.Problem != null) // 1.2. only when an problem exists
     38      if (algorithm.Problem != null) // only when an problem exists
    4139        AddInstantiableIItem(Constants.Problem, algorithm.Problem, genData);
    4240
    43       // 2. save the JArray with JsonItems (= IParameterizedItems)
    44       genData.Template[Constants.Objects] = genData.JsonItems;
    45       // 3. save the types of the JsonItems (for instatiation)
    46       genData.Template[Constants.Types] = JObject.FromObject(genData.TypeList);
    47       // 4. serialize template and return string
     41      // save the JArray with JsonItems (= IParameterizedItems)
     42      genData.Template[Constants.Parameters] = genData.JsonItems;
     43      // serialize template and return string
    4844      return CustomJsonWriter.Serialize(genData.Template);
    4945    }
     
    6561    // serializes ParameterizedItems and saves them in list "JsonItems".
    6662    private static void PopulateJsonItems(JsonItem item, GenData genData) {
    67       if (item.Parameters != null) {
    68         foreach (var p in item.Parameters) {
     63      IEnumerable<JsonItem> tmpParameter = item.Children;
     64      item.Children = null;
     65
     66      if (item.Value != null || item.Range != null) {
     67        genData.JsonItems.Add(Serialize(item));
     68      }
     69
     70      if (tmpParameter != null) {
     71        foreach (var p in tmpParameter) {
    6972          PopulateJsonItems(p, genData);
    7073        }
    71       }else if (item.Value != null || item.Range != null /*|| item.ActualName != null*/) {
    72         genData.JsonItems.Add(Serialize(item, genData));
    7374      }
    74       /*
    75       if (item.Parameters != null) {
    76         if (item.Range == null)
    77           genData.JsonItems.Add(Serialize(item, genData));
    78         foreach (var p in item.Parameters)
    79           if (p.IsParameterizedItem)
    80             PopulateJsonItems(p, genData);
    81       }*/
    8275    }
    8376
    84     private static JObject Serialize(JsonItem item, GenData genData) {
    85       JObject obj = JObject.FromObject(item, Settings());
    86       //obj[Constants.StaticParameters] = obj[nameof(JsonItem.Parameters)];
    87       //obj[Constants.FreeParameters] = obj[nameof(JsonItem.Parameters)];
    88 
    89       //obj.Property(nameof(JsonItem.Parameters))?.Remove();
    90       //RefactorFreeParameters(obj, genData);
    91       //RefactorStaticParameters(obj, genData);
    92 
    93       //obj.Property(nameof(JsonItem.Value))?.Remove();
    94       obj.Property(nameof(JsonItem.Type))?.Remove();
    95 
    96       if(!genData.TypeList.ContainsKey(item.Path))
    97         genData.TypeList.Add(item.Path, item.Type);
    98       return obj;
    99     }
    100 
    101     // deletes unnecessary properties for free parameters.
    102     private static void RefactorFreeParameters(JToken token, GenData genData) {
    103       IList<JObject> objToRemove = new List<JObject>();
    104       TransformNodes(x => {
    105         var p = JsonItem.BuildJsonItem(x, genData.TypeList);
    106         x.Property(nameof(JsonItem.Type))?.Remove();
    107         x.Property(nameof(JsonItem.Parameters))?.Remove();
    108         /*
    109         if ((p.Value == null || (p.Value != null && p.Value.GetType() == typeof(string) && p.Range == null) && p.ActualName == null)) {
    110           objToRemove.Add(x);
    111         } else {
    112           x.Property(nameof(JsonItem.Type))?.Remove();
    113           x.Property(nameof(JsonItem.Parameters))?.Remove();
    114         }*/
    115       }, token[Constants.FreeParameters]);
    116       //foreach (var x in objToRemove) x.Remove();
    117     }
    118 
    119     // deletes unnecessary properties for static parameters.
    120     private static void RefactorStaticParameters(JToken token, GenData genData) {
    121       IList<JObject> objToRemove = new List<JObject>();
    122       TransformNodes(x => {
    123         var p = JsonItem.BuildJsonItem(x, genData.TypeList);
    124         x.Property(nameof(JsonItem.Range))?.Remove();
    125         x.Property(nameof(JsonItem.Operators))?.Remove();
    126         x.Property(nameof(JsonItem.Parameters))?.Remove();
    127         x.Property(nameof(JsonItem.Type))?.Remove();
    128         //TODO: maybe allow JsonItems with Value==null in static parameters too?
    129         if (p.Value == null) objToRemove.Add(x);
    130       }, token[Constants.StaticParameters]);
    131       //foreach (var x in objToRemove) x.Remove();
    132     }
     77    private static JObject Serialize(JsonItem item) =>
     78      JObject.FromObject(item, Settings());
    13379
    13480    /// <summary>
     
    14187      ReferenceLoopHandling = ReferenceLoopHandling.Serialize
    14288    };
    143 
    144     private static void TransformNodes(Action<JObject> action, params JToken[] tokens) {
    145       foreach(JObject obj in tokens.SelectMany(x => x.Children<JObject>()))
    146         action(obj);
    147     }
    14889    #endregion
    14990  }
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JCInstantiator.cs

    r17354 r17379  
    77using System.Text;
    88using System.Threading.Tasks;
     9using HEAL.Attic;
    910using HeuristicLab.Core;
    1011using HeuristicLab.Data;
     
    2122      public JToken Template { get; set; }
    2223      public JArray Config { get; set; }
    23       public Dictionary<string, string> TypeList { get; set; }
    24       public IDictionary<string, JsonItem> ParameterizedItems { get; set; }
    25       public IDictionary<string, JsonItem> ConfigurableItems { get; set; }
     24      public IDictionary<string, JsonItem> Objects { get; set; }
     25      public IDictionary<string, JsonItem> ResolvedItems { get; set; }
    2626    }
    2727
     
    3434    public static IAlgorithm Instantiate(string templateFile, string configFile = "") {
    3535      InstData instData = new InstData() {
    36         TypeList = new Dictionary<string, string>(),
    37         ParameterizedItems = new Dictionary<string, JsonItem>(),
    38         ConfigurableItems = new Dictionary<string, JsonItem>()
     36        Objects = new Dictionary<string, JsonItem>(),
     37        ResolvedItems = new Dictionary<string, JsonItem>()
    3938      };
    4039
    41       //1. Parse Template and Config files
     40      // parse template and config files
    4241      instData.Template = JToken.Parse(File.ReadAllText(templateFile));
    4342      if(!string.IsNullOrEmpty(configFile))
    4443        instData.Config = JArray.Parse(File.ReadAllText(configFile));
    45       instData.TypeList = instData.Template[Constants.Types].ToObject<Dictionary<string, string>>();
     44
     45      // extract metadata information
    4646      string algorithmName = instData.Template[Constants.Metadata][Constants.Algorithm].ToString();
    4747      string problemName = instData.Template[Constants.Metadata][Constants.Problem].ToString();
     48      string hLFileLocation = instData.Template[Constants.Metadata][Constants.HLFileLocation].ToString();
    4849
    49       //2. Collect all parameterizedItems from template
     50      // deserialize hl file
     51      ProtoBufSerializer serializer = new ProtoBufSerializer();
     52      IAlgorithm algorithm = (IAlgorithm)serializer.Deserialize(hLFileLocation);
     53
     54      // collect all parameterizedItems from template
    5055      CollectParameterizedItems(instData);
    5156
    52       //3. select all ConfigurableItems
    53       SelectConfigurableItems(instData);
     57      // rebuild tree with paths
     58      RebuildTree(instData);
    5459
    55       //4. if config != null -> merge Template and Config
     60      // if config != null -> merge Template and Config
    5661      if (instData.Config != null)
    5762        MergeTemplateWithConfig(instData);
    5863
    59       //5. resolve the references between parameterizedItems
    60       ResolveReferences(instData);
     64      // get algorthm data and object
     65      JsonItem algorithmData = GetData(algorithmName, instData);
    6166
    62       //6. get algorthm data and object
    63       JsonItem algorithmData = GetData(algorithmName, instData);
    64       IAlgorithm algorithm = CreateObject<IAlgorithm>(algorithmData, instData);
     67      // get problem data and object
     68      JsonItem problemData = GetData(problemName, instData);
    6569
    66       //7. get problem data and object
    67       JsonItem problemData = GetData(problemName, instData);
    68       IProblem problem = CreateObject<IProblem>(problemData, instData);
    69       algorithm.Problem = problem;
    70 
    71       //8. inject configuration
     70      // inject configuration
    7271      JsonItemConverter.Inject(algorithm, algorithmData);
    73       JsonItemConverter.Inject(problem, problemData);
    74 
    75       // TODO: let the engine be configurable
    76       if (algorithm is EngineAlgorithm)
    77         algorithm.Cast<EngineAlgorithm>().Engine = new SequentialEngine.SequentialEngine();
     72      if(algorithm.Problem != null)
     73        JsonItemConverter.Inject(algorithm.Problem, problemData);
    7874
    7975      return algorithm;
     
    8278    #region Helper
    8379    private static void CollectParameterizedItems(InstData instData) {
    84       foreach (JObject item in instData.Template[Constants.Objects]) {
    85         JsonItem data = JsonItem.BuildJsonItem(item, instData.TypeList);
    86         instData.ParameterizedItems.Add(data.Path, data);
     80      foreach (JObject item in instData.Template[Constants.Parameters]) {
     81        JsonItem data = JsonItem.BuildJsonItem(item);
     82        instData.Objects.Add(data.Path, data);
    8783      }
    8884    }
     85   
     86    private static JsonItem RebuildTreeHelper(IList<JsonItem> col, string name) {
     87      JsonItem target = null;
     88      foreach (var val in col) {
     89        if (val.Name == name)
     90          target = val;
     91      }
     92      if (target == null) {
     93        target = new JsonItem() {
     94          Name = name,
     95          Path = name,
     96          Children = new List<JsonItem>()
     97        };
     98        col.Add(target);
     99      }
     100      return target;
     101    }
    89102
    90     private static void SelectConfigurableItems(InstData instData) {
    91       foreach (var item in instData.ParameterizedItems.Values) {
    92         if (item.Parameters != null)
    93           AddConfigurableItems(item.Parameters, instData);
     103    // rebuilds item tree with splitting paths of each jsonitem
     104    private static void RebuildTree(InstData instData) {
     105      List<JsonItem> values = new List<JsonItem>();
     106      foreach (var x in instData.Objects) {
     107        string[] pathParts = x.Key.Split('.');
     108        JsonItem target = RebuildTreeHelper(values, pathParts[0]);
    94109
    95         if (item.Operators != null)
    96           AddConfigurableItems(item.Operators, instData);
     110        for (int i = 1; i < pathParts.Length; ++i) {
     111          target = RebuildTreeHelper(target.Children, pathParts[i]);
     112        }
     113
     114        JsonItem.Merge(target, x.Value);
     115      }
     116      foreach(var val in values) {
     117        instData.ResolvedItems.Add(val.Name, val);
    97118      }
    98119    }
    99 
    100     private static void AddConfigurableItems(IEnumerable<JsonItem> items, InstData instData) {
    101       foreach (var item in items)
    102         if (item.IsConfigurable)
    103           instData.ConfigurableItems.Add(item.Path, item);
    104     }
    105 
    106     private static void ResolveReferences(InstData instData) {
    107       foreach(var x in instData.ParameterizedItems.Values)
    108         foreach (var p in x.Parameters)
    109           if (p.Value is string) {
    110             string key = p.Path;
    111             if (p.Range != null)
    112               key = $"{p.Path}.{p.Value.Cast<string>()}";
    113 
    114             if (instData.ParameterizedItems.TryGetValue(key, out JsonItem value))
    115               p.Reference = value;
    116           }
    117     }
    118 
     120   
    119121    private static void MergeTemplateWithConfig(InstData instData) {
    120122      foreach (JObject obj in instData.Config) {
    121123        // build item from config object
    122         JsonItem item = JsonItem.BuildJsonItem(obj, instData.TypeList);
     124        JsonItem item = JsonItem.BuildJsonItem(obj);
    123125        // override default value
    124         if (instData.ConfigurableItems.TryGetValue(item.Path, out JsonItem param)) {
     126        if (instData.Objects.TryGetValue(item.Path, out JsonItem param)) {
    125127          param.Value = item.Value;
    126128          // override ActualName (for LookupParameters)
    127129          if (param.ActualName != null)
    128130            param.ActualName = item.ActualName;
    129         } else throw new InvalidDataException($"No {Constants.FreeParameters.Trim('s')} with path='{item.Path}' defined!");
     131        } else throw new InvalidDataException($"No parameter with path='{item.Path}' defined!");
    130132      }
    131133    }
     
    133135    private static JsonItem GetData(string key, InstData instData)
    134136    {
    135       if (instData.ParameterizedItems.TryGetValue(key, out JsonItem value))
     137      if (instData.ResolvedItems.TryGetValue(key, out JsonItem value))
    136138        return value;
    137139      else
    138140        throw new InvalidDataException($"Type of item '{key}' is not defined!");
    139141    }
    140 
    141     private static T CreateObject<T>(JsonItem data, InstData instData) {
    142       if (instData.TypeList.TryGetValue(data.Name, out string typeName)) {
    143         Type type = Type.GetType(typeName);
    144         return (T)Activator.CreateInstance(type);
    145       } else throw new TypeLoadException($"Cannot find AssemblyQualifiedName for {data.Name}.");
    146     }
    147142    #endregion
    148143  }
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JsonItem.cs

    r17374 r17379  
    2828          string oldName = Name;
    2929          name = value;
     30          // replace name in path if path != null
    3031          if (Path != null) {
    3132            var parts = Path.Split('.');
    32             for (int i = 0; i < parts.Length; ++i)
    33               if (parts[i] == oldName)
    34                 parts[i] = Name;
    35 
     33            parts[Array.IndexOf(parts, oldName)] = name;
    3634            Path = string.Join(".", parts);
    3735          } else
     
    4240      }
    4341    }
    44     public string Type { get; set; }
    4542    public string Path { get; set; }
    46     public IList<JsonItem> Parameters { get; set; } // -> für flachen aufbau -> childs?
    47     public IList<JsonItem> Operators { get; set; }
     43    public IList<JsonItem> Children { get; set; }
    4844    public object Value {
    4945      get => value;
     
    6258    public string ActualName { get; set; }
    6359
    64     #region JsonIgnore Properties
    65     [JsonIgnore]
    66     public JsonItem Reference { get; set; }
    67 
    68     [JsonIgnore]
    69     public bool IsConfigurable => (Value != null && Range != null);
    70 
    71     [JsonIgnore]
    72     public bool IsParameterizedItem => Parameters != null;
    73     #endregion
    74 
    7560    #region Public Static Methods
    7661    public static void Merge(JsonItem target, JsonItem from) {
    7762      target.Name = from.Name ?? target.Name;
    78       target.Type = from.Type ?? target.Type;
    7963      target.Range = from.Range ?? target.Range;
    8064      target.Path = from.Path ?? target.Path;
    8165      target.Value = from.Value ?? target.Value;
    82       target.Reference = from.Reference ?? target.Reference;
    8366      target.ActualName = from.ActualName ?? target.ActualName;
    84       target.Parameters = from.Parameters ?? target.Parameters;
    85       target.Operators = from.Operators ?? target.Operators;
     67      if(target.Children != null) {
     68        if (from.Children != null)
     69          ((List<JsonItem>)from.Children).AddRange(target.Children);
     70      } else {
     71        target.Children = from.Children;
     72      }
    8673    }
    8774    #endregion
     
    8976    #region Public Methods
    9077    public void AddParameter(JsonItem item) {
    91       if (Parameters == null)
    92         Parameters = new List<JsonItem>();
    93       Parameters.Add(item);
     78      if (Children == null)
     79        Children = new List<JsonItem>();
     80      Children.Add(item);
    9481      item.Path = $"{Path}.{item.Name}";
    9582      item.UpdatePath();
     
    9784
    9885    public void UpdatePath() {
    99       if (Parameters != null)
    100         UpdatePathHelper(Parameters);
    101 
    102       if (Operators != null)
    103         UpdatePathHelper(Operators);
    104 
    105       if (Reference != null)
    106         UpdatePathHelper(Reference);
     86      if (Children != null)
     87        UpdatePathHelper(Children);
    10788    }
    10889    #endregion
    10990
    11091    #region Helper
    111     private void UpdatePathHelper(params JsonItem[] items) =>
    112       UpdatePathHelper((IEnumerable<JsonItem>)items);
    113 
    11492    private void UpdatePathHelper(IEnumerable<JsonItem> items) {
    11593      foreach (var item in items) {
     
    136114        b2 = IsInNumericRange(Value);
    137115      }
    138 
    139116      return b1 || b2;
    140117    }
     
    166143        (((T)max).CompareTo(value) == 1 || ((T)max).CompareTo(value) == 0);
    167144    }
    168 
    169145    #endregion
    170146
    171147    #region BuildJsonItemMethods
    172     public static JsonItem BuildJsonItem(JObject obj, IDictionary<string, string> typeList) {
     148    public static JsonItem BuildJsonItem(JObject obj) {
    173149      object val = obj[nameof(Value)]?.ToObject<object>();
    174       if (val is JContainer) {
    175         //try {
    176           val = ((JContainer)val).ToObject<object[]>();
    177         /*} catch (Exception) { }
    178         try {
    179           val = ((JContainer)val).ToObject<object[,]>();
    180         } catch (Exception) { }*/
    181       }
     150      if (val is JContainer jContainer) // for resolving array values
     151        val = jContainer.ToObject<object[]>();
    182152       
    183 
    184153      return new JsonItem() {
    185154        Name = obj[nameof(Name)]?.ToString(),
     
    187156        Value = val,
    188157        Range = obj[nameof(Range)]?.ToObject<object[]>(),
    189         Type = GetType(obj[nameof(Path)]?.ToObject<string>(), typeList),
    190         ActualName = obj[nameof(ActualName)]?.ToString(),
    191         Parameters = PopulateParameters(obj, typeList),
    192         Operators = PopulateOperators(obj, typeList)
     158        ActualName = obj[nameof(ActualName)]?.ToString()
    193159      };
    194   }
    195 
    196     private static string GetType(string path, IDictionary<string, string> typeList) {
    197       if (!string.IsNullOrEmpty(path))
    198         if (typeList.TryGetValue(path, out string value))
    199           return value;
    200       return null;
    201     }
    202 
    203     private static IList<JsonItem> PopulateParameters(JObject obj, IDictionary<string, string> typeList) {
    204       IList<JsonItem> list = new List<JsonItem>();
    205 
    206       // add staticParameters
    207       if (obj[Constants.StaticParameters] != null)
    208         foreach (JObject param in obj[Constants.StaticParameters])
    209           list.Add(BuildJsonItem(param, typeList));
    210 
    211       // merge staticParameter with freeParameter
    212       if (obj[Constants.FreeParameters] != null) {
    213         foreach (JObject param in obj[Constants.FreeParameters]) {
    214           JsonItem tmp = BuildJsonItem(param, typeList);
    215 
    216           // search staticParameter from list
    217           JsonItem comp = null;
    218           foreach (var p in list)
    219             if (p.Name == tmp.Name) comp = p;
    220           if (comp == null)
    221             throw new InvalidDataException($"Invalid {Constants.FreeParameters.Trim('s')}: '{tmp.Name}'!");
    222 
    223           JsonItem.Merge(comp, tmp);
    224         }
    225       }
    226       return list;
    227     }
    228 
    229     private static IList<JsonItem> PopulateOperators(JObject obj, IDictionary<string, string> typeList) {
    230       IList<JsonItem> list = new List<JsonItem>();
    231       JToken operators = obj[nameof(JsonItem.Operators)];
    232       if (operators != null)
    233         foreach (JObject sp in operators)
    234           list.Add(BuildJsonItem(sp, typeList));
    235       return list;
    236160    }
    237161    #endregion
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JsonItemConverter.cs

    r17374 r17379  
    3434        Converters.Add(type, new ConverterPriorityContainer() { Converter = converter, Priority = priority });
    3535    }
    36 
    3736
    3837    public static void Register(string atticGuid, IJsonItemConverter converter, int priority) =>
     
    126125     
    127126      Register("EE612297-B1AF-42D2-BF21-AF9A2D42791C", new RegressionProblemDataConverter(), 20);
    128 
    129       // ISymbol
    130       /*
    131       Register("25137f88-66b9-48d7-a2bd-60190082e044",
    132         new ConfigurableConverter()
    133         .Primitive("InitialFrequency", ElementType.Property, new object[] { 0.0, 1.0 })
    134         .Primitive("Enabled", ElementType.Property, true)
    135         .Primitive("MinimumArity", ElementType.Property, 0)
    136         .Primitive("MaximumArity", ElementType.Property, 10),
    137         5);
    138       */
    139       // SymbolicRegressionProblem
    140       /*
    141       Register("7DDCF683-96FC-4F70-BF4F-FE3A0B0DE6E0",
    142         new ConfigurableConverter()
    143         .
    144         10);
    145       */
    146 
    147       // Dataset
    148       /*
    149       Register("49F4D145-50D7-4497-8D8A-D190CD556CC8",
    150         new ConfigurableConverter() //TODO: set guid to enable "inheritance"?
    151         .PrimitiveEnumerable("storableData", ElementType.Field, new double[,] { }),
    152         5);
    153       */
    154       // ItemCollection<>
    155       /*
    156       Register("0BD4F01E-2D52-4E41-AEF8-611F10856D90",
    157         new ConfigurableConverter()
    158         .This((o, t) => {
    159           dynamic itemList = o as dynamic;
    160           IList<JsonItem> jsonItems = new List<JsonItem>();
    161           foreach (var obj in itemList) {
    162             IItem item = obj as IItem;
    163             jsonItems.Add(Extract(item));
    164           }
    165           return jsonItems;
    166         }),
    167         5);
    168       */
    169       // IItemList<>
    170       /*
    171       Register("466747d2-6a73-495b-ac68-7b0199d0f830",
    172         new ConfigurableConverter()
    173         .This((o, t) => {
    174           dynamic itemList = o as dynamic;
    175           IList<JsonItem> jsonItems = new List<JsonItem>();
    176           foreach (var obj in itemList) {
    177             IItem item = obj as IItem;
    178             jsonItems.Add(Extract(item));
    179           }
    180           return jsonItems;
    181         }),
    182         6);
    183       */
    184       // ICheckedItemList<>
    185       /*
    186       Register("ba4a82ca-92eb-47a1-95a7-f41f6ef470f4",
    187         new ConfigurableConverter()
    188         .This((o,t) => {
    189           dynamic itemList = o as dynamic;
    190           IList<JsonItem> jsonItems = new List<JsonItem>();
    191           int count = 0;
    192           foreach(var obj in itemList) {
    193             IItem item = obj as IItem;
    194             JsonItem checkedStatus = new JsonItem() {
    195               Name = "Checked",
    196               Value = itemList.ItemChecked(obj),
    197               Range = new object[] { false, true }
    198             };
    199             JsonItem value = Extract(item);
    200 
    201             jsonItems.Add(new JsonItem() {
    202               Name = item.ItemName + count++,
    203               Parameters = new JsonItem[] {
    204                 checkedStatus, value
    205               },
    206               Type = item.GetType().AssemblyQualifiedName
    207             });
    208           }
    209           return jsonItems;
    210         }),
    211         6);
    212       */
    213       //ISymbolicExpressionGrammar - "1f6afcbe-b309-44e2-8d35-2d33eaeb9649"
    214       //ISymbolicExpressionGrammarBase - "119f5e94-bc7d-42fc-a48b-ac0230115ef2"
    215       /*
    216       Register("119f5e94-bc7d-42fc-a48b-ac0230115ef2",
    217         new ConfigurableConverter()
    218         .Enumerable("Symbols", ElementType.Property, (o,t) => new JsonItem[] { Extract(o as IItem) }),
    219         10);
    220       */
    221127    }
    222128  }
  • branches/3026_IntegrationIntoSymSpace/Heuristiclab.ConfigStarter/Program.cs

    r17374 r17379  
    1717namespace Heuristiclab.ConfigStarter {
    1818  public class Program {
    19 
    20     private static string Reduce(string str) =>
    21       str
    22       .Replace(" ", "")
    23       .Replace("-", "")
    24       .Replace("`", "")
    25       .Replace(".", "")
    26       .Replace("<", "")
    27       .Replace(">", "")
    28       .Replace("(", "_")
    29       .Replace(")", "_");
    30 
    31     private static void Visualize(JsonItem item, StringBuilder sb) {
    32       sb.Append($"  {item.GetHashCode()} [label=\"{item.Name}\"];\n");
    33       foreach (var i in item.Parameters) {
    34         sb.Append($"  {item.GetHashCode()} -> {i.GetHashCode()};\n");
    35       }
    36       foreach(var i in item.Parameters) {
    37         Visualize(i, sb);
    38       }
    39     }
    4019
    4120    public static void Main(string[] args) {
     
    6443      SymbolicRegressionSingleObjectiveProblem prop = new SymbolicRegressionSingleObjectiveProblem();
    6544     
    66       alg.Problem = prop;
     45      alg.Problem = tsp;
    6746
    68       alg.Engine = new SequentialEngine();
    69       Task t = alg.StartAsync();
    70       Thread.Sleep(1000);
    71       alg.Stop();
    72 
    73       StorableConverter storableConverter = new StorableConverter();
    74       JsonItem item = storableConverter.Extract(alg);
    75 
    76       StringBuilder sb = new StringBuilder();
    77 
    78       //Visualize(item, sb);
    79 
    80       //File.WriteAllText(@"C:\Workspace\item.gv", $"digraph G {{\n{sb.ToString()}}}");
    81 
    82 
    83       //Console.WriteLine(alg);
    8447      File.WriteAllText(@"C:\Workspace\Template.json", JCGenerator.GenerateTemplate(alg));
    85 
     48      JCInstantiator.Instantiate(@"C:\Workspace\Template.json");
    8649      /*
    8750      List<ICommandLineArgument> arguments = new List<ICommandLineArgument>();
Note: See TracChangeset for help on using the changeset viewer.