Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
10/08/19 14:13:42 (5 years ago)
Author:
dpiringe
Message:

#3026

  • changed project type from console to library
  • activated signing
  • lots of refactors in JCInstantiator and JsonItem
Location:
branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface
Files:
2 deleted
5 edited
1 copied

Legend:

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

    r17284 r17322  
    2929
    3030      dynamic val = item.Cast<dynamic>();
    31       foreach (var op in val.Operators) {
     31      foreach (var op in val.Operators)
    3232        val.Operators.SetItemCheckedState(op, GetOperatorState(op.Name, data));
    33       }
    3433    }
    3534
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/HeuristicLab.JsonInterface.csproj

    r17287 r17322  
    66    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    77    <ProjectGuid>{0E3AAB5E-F152-44E0-A054-4D9A83ECEE08}</ProjectGuid>
    8     <OutputType>Exe</OutputType>
     8    <OutputType>Library</OutputType>
    99    <RootNamespace>HeuristicLab.JsonInterface</RootNamespace>
    1010    <AssemblyName>HeuristicLab.JsonInterface</AssemblyName>
    11     <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
     11    <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
    1212    <FileAlignment>512</FileAlignment>
    1313    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    1414    <Deterministic>true</Deterministic>
     15    <TargetFrameworkProfile />
    1516  </PropertyGroup>
    1617  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
     
    1920    <DebugType>full</DebugType>
    2021    <Optimize>false</Optimize>
    21     <OutputPath>bin\Debug\</OutputPath>
     22    <OutputPath>..\bin\</OutputPath>
    2223    <DefineConstants>DEBUG;TRACE</DefineConstants>
    2324    <ErrorReport>prompt</ErrorReport>
     
    3233    <ErrorReport>prompt</ErrorReport>
    3334    <WarningLevel>4</WarningLevel>
     35  </PropertyGroup>
     36  <PropertyGroup>
     37    <StartupObject />
     38  </PropertyGroup>
     39  <PropertyGroup>
     40    <SignAssembly>true</SignAssembly>
     41  </PropertyGroup>
     42  <PropertyGroup>
     43    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
    3444  </PropertyGroup>
    3545  <ItemGroup>
     
    7181    <Compile Include="Converters\ValueTypeMatrixConverter.cs" />
    7282    <Compile Include="Converters\ValueTypeValueConverter.cs" />
    73     <Compile Include="Program.cs" />
    7483    <Compile Include="Properties\AssemblyInfo.cs" />
    7584    <Compile Include="JsonItem.cs" />
     
    7887  </ItemGroup>
    7988  <ItemGroup>
    80     <None Include="App.config" />
     89    <None Include="HeuristicLab.snk" />
    8190    <None Include="packages.config" />
    8291  </ItemGroup>
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JCGenerator.cs

    r17287 r17322  
    7777          objToRemove.Add(x);
    7878        } else {
    79           x.Property(nameof(JsonItem.Path))?.Remove();
     79          //x.Property(nameof(JsonItem.Path))?.Remove();
    8080          x.Property(nameof(JsonItem.Type))?.Remove();
    8181          x.Property(nameof(JsonItem.Parameters))?.Remove();
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JCInstantiator.cs

    r17287 r17322  
    1515  public class JCInstantiator {
    1616
    17     private JToken Config { get; set; }
     17    private JToken Template { get; set; }
     18    private JArray Config { get; set; }
     19
    1820    private Dictionary<string, string> TypeList = new Dictionary<string, string>();
     21    private IDictionary<string, JsonItem> ParameterizedItems { get; set; } = new Dictionary<string, JsonItem>();
     22    private IDictionary<string, JsonItem> ConfigurableItems { get; set; } = new Dictionary<string, JsonItem>();
     23   
     24    public IAlgorithm Instantiate(string templateFile, string configFile) {
    1925
    20     public IAlgorithm Instantiate(string configFile) {
    21       Config = JToken.Parse(File.ReadAllText(configFile));
    22       TypeList = Config[Constants.Types].ToObject<Dictionary<string, string>>();
     26      //1. Parse Template and Config files
     27      Template = JToken.Parse(File.ReadAllText(templateFile));
     28      Config = JArray.Parse(File.ReadAllText(configFile));
     29      TypeList = Template[Constants.Types].ToObject<Dictionary<string, string>>();
     30      string algorithmName = Template[Constants.Metadata][Constants.Algorithm].ToString();
     31      string problemName = Template[Constants.Metadata][Constants.Problem].ToString();
    2332
    24       JsonItem algorithmData = GetData(Config[Constants.Metadata][Constants.Algorithm].ToString());
    25       ResolveReferences(algorithmData);
     33      //2. Collect all parameterizedItems from template
     34      CollectParameterizedItems();
     35
     36      //3. select all ConfigurableItems
     37      SelectConfigurableItems();
     38
     39      //4. Merge Template and Config
     40      MergeTemplateWithConfig();
     41
     42      //5. resolve the references between parameterizedItems
     43      ResolveReferences();
     44
     45      //6. get algorthm data and object
     46      JsonItem algorithmData = GetData(algorithmName);
    2647      IAlgorithm algorithm = CreateObject<IAlgorithm>(algorithmData);
    27      
    28       JsonItem problemData = GetData(Config[Constants.Metadata][Constants.Problem].ToString());
    29       ResolveReferences(problemData);
     48
     49      //7. get problem data and object
     50      JsonItem problemData = GetData(problemName);
    3051      IProblem problem = CreateObject<IProblem>(problemData);
    3152      algorithm.Problem = problem;
    3253
     54      //8. inject configuration
    3355      JsonItemConverter.Inject(algorithm, algorithmData);
    34       JsonItemConverter.Inject(algorithm, problemData);
     56      JsonItemConverter.Inject(problem, problemData);
    3557
    3658      return algorithm;
    3759    }
    3860
    39     private void ResolveReferences(JsonItem data) {
    40       foreach (var p in data.Parameters)
    41         if (p.Default is string && p.Reference == null)
    42           p.Reference = GetData(p.Default.Cast<string>());
     61    private void CollectParameterizedItems() {
     62      foreach (JObject item in Template[Constants.Objects]) {
     63        JsonItem data = BuildJsonItem(item);
     64        ParameterizedItems.Add(data.Path, data);
     65      }
     66    }
     67
     68    private void SelectConfigurableItems() {
     69      foreach (var item in ParameterizedItems.Values) {
     70        if (item.Parameters != null)
     71          AddConfigurableItems(item.Parameters);
     72
     73        if (item.Operators != null)
     74          AddConfigurableItems(item.Operators);
     75      }
     76    }
     77
     78    private void AddConfigurableItems(IEnumerable<JsonItem> items) {
     79      foreach (var item in items)
     80        if (item.IsConfigurable)
     81          ConfigurableItems.Add(item.Path, item);
     82    }
     83
     84    private void ResolveReferences() {
     85      foreach(var x in ParameterizedItems.Values)
     86        foreach (var p in x.Parameters)
     87          if (p.Default is string) {
     88            string key = $"{p.Path}.{p.Default.Cast<string>()}";
     89            if (ParameterizedItems.TryGetValue(key, out JsonItem value))
     90              p.Reference = value;
     91          }
     92    }
     93
     94    private void MergeTemplateWithConfig() {
     95      foreach (JObject obj in Config) {
     96        // build item from config object
     97        JsonItem item = BuildJsonItem(obj);
     98        // override default value
     99        if (ConfigurableItems.TryGetValue(item.Path, out JsonItem param)) {
     100          param.Default = item.Default;
     101          // override default value of reference (for ValueLookupParameters)
     102          if (param.Reference != null)
     103            param.Reference.Default = item.Reference?.Default;
     104        } else throw new InvalidDataException($"No {Constants.FreeParameters.Trim('s')} with path='{item.Path}' defined!");
     105      }
    43106    }
    44107
    45108    private JsonItem GetData(string key)
    46109    {
    47       foreach(JObject item in Config[Constants.Objects])
    48       {
    49         JsonItem data = BuildJsonItem(item);
    50         if (data.Name == key) return data;
    51       }
    52       return null;
     110      if (ParameterizedItems.TryGetValue(key, out JsonItem value))
     111        return value;
     112      else
     113        throw new InvalidDataException($"Type of item '{key}' is not defined!");
    53114    }
    54115
     
    60121    }
    61122
     123    #region BuildJsonItemMethods
    62124    private JsonItem BuildJsonItem(JObject obj) =>
    63125      new JsonItem() {
    64126        Name = obj[nameof(JsonItem.Name)]?.ToString(),
     127        Path = obj[nameof(JsonItem.Path)]?.ToString(),
    65128        Default = obj[nameof(JsonItem.Default)]?.ToObject<object>(),
    66129        Range = obj[nameof(JsonItem.Range)]?.ToObject<object[]>(),
    67         Type = obj[nameof(JsonItem.Type)]?.ToObject<string>(),
     130        Type = GetType(obj[nameof(JsonItem.Path)]?.ToObject<string>()),
    68131        Reference = obj[nameof(JsonItem.Type)] == null ?
    69132                    null :
     
    73136      };
    74137
     138    private string GetType(string path) {
     139      if(!string.IsNullOrEmpty(path))
     140        if (TypeList.TryGetValue(path, out string value))
     141          return value;
     142      return null;
     143    }
     144
    75145    private IList<JsonItem> PopulateParameters(JObject obj) {
    76146      IList<JsonItem> list = new List<JsonItem>();
     147
     148      // add staticParameters
    77149      if (obj[Constants.StaticParameters] != null)
    78150        foreach (JObject param in obj[Constants.StaticParameters])
    79151          list.Add(BuildJsonItem(param));
    80152
     153      // merge staticParameter with freeParameter
    81154      if (obj[Constants.FreeParameters] != null) {
    82155        foreach (JObject param in obj[Constants.FreeParameters]) {
    83156          JsonItem tmp = BuildJsonItem(param);
     157         
     158          // search staticParameter from list
    84159          JsonItem comp = null;
    85           foreach (var p in list) // TODO: nicht notwendig, da immer alle params im static block sind
     160          foreach (var p in list)
    86161            if (p.Name == tmp.Name) comp = p;
    87           if (comp != null)
    88             JsonItem.Merge(comp, tmp);
    89           else list.Add(tmp);
     162          if (comp == null)
     163            throw new InvalidDataException($"Invalid {Constants.FreeParameters.Trim('s')}: '{tmp.Name}'!");
     164
     165          JsonItem.Merge(comp, tmp);
    90166        }
    91167      }
     
    95171    private IList<JsonItem> PopulateOperators(JObject obj) {
    96172      IList<JsonItem> list = new List<JsonItem>();
    97       if (obj[nameof(Operators)] != null)
    98         foreach (JObject sp in obj[nameof(Operators)]) {
    99           JsonItem tmp = BuildJsonItem(sp);
    100           list.Add(tmp);
    101         }
     173      JToken operators = obj[nameof(Operators)];
     174      if (operators != null)
     175        foreach (JObject sp in operators)
     176          list.Add(BuildJsonItem(sp));
    102177      return list;
    103178    }
     179    #endregion
    104180  }
    105181}
  • branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/JsonItem.cs

    r17287 r17322  
    1515    public string Name { get; set; }
    1616    public string Type { get; set; }
     17    public string Path { get; set; } = "";
     18    public IList<JsonItem> Parameters { get; set; }
     19    public IList<JsonItem> Operators { get; set; }
     20
    1721    public object Default {
    1822      get => defaultValue;
     
    2327      }
    2428    }
    25     public string Path { get; set; } = "";
    2629
    2730    public IList<object> Range {
     
    3336      }
    3437    }
     38       
     39    public JsonItem Reference { get; set; }
    3540
    36     public IList<JsonItem> Parameters { get; set; }
    37     public IList<JsonItem> Operators { get; set; }
    38    
    39     public override bool Equals(object obj) =>
    40       (obj is JsonItem ? (obj.Cast<JsonItem>().Name == this.Name) : false);
    41      
    42     public override int GetHashCode() => Name.GetHashCode();
     41    [JsonIgnore]
     42    public bool IsConfigurable => (Default != null && Range != null);
    4343
    44     public JsonItem Reference { get; set; }
    45    
    4644    public static void Merge(JsonItem target, JsonItem from) {
    4745      target.Name = from.Name ?? target.Name;
     
    7068      if (Parameters != null)
    7169        foreach (var p in Parameters)
    72           p.Path = Path + "." + p.Name;
     70          p.Path = $"{Path}.{p.Name}";
    7371
    7472      if (Operators != null)
    7573        foreach (var p in Operators)
    76           p.Path = Path + "." + p.Name;
     74          p.Path = $"{Path}.{p.Name}";
    7775    }
    7876
     
    8179      PrependPathHelper(Parameters, str);
    8280      PrependPathHelper(Operators, str);
    83     }
    84 
    85     private void PrependPathHelper(IEnumerable<JsonItem> items, string str) {
    86       if (items != null)
    87         foreach (var p in items)
    88           p.PrependPath(str);
    8981    }
    9082
     
    10092        (((T)min).CompareTo(value) == -1 || ((T)min).CompareTo(value) == 0) &&
    10193        (((T)max).CompareTo(value) == 1 || ((T)max).CompareTo(value) == 0));
     94
     95    private void PrependPathHelper(IEnumerable<JsonItem> items, string str) {
     96      if (items != null)
     97        foreach (var p in items)
     98          p.PrependPath(str);
     99    }
    102100    #endregion
    103101  }
Note: See TracChangeset for help on using the changeset viewer.