Free cookie consent management tool by TermsFeed Policy Generator

source: addons/HeuristicLab.Problems.BioBoost/HeuristicLab.Problems.BioBoost/3.3/Data/DataItem.cs @ 15711

Last change on this file since 15711 was 13071, checked in by gkronber, 9 years ago

#2499: added license headers and removed unused usings

File size: 6.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using HeuristicLab.Common;
23using HeuristicLab.Core;
24using HeuristicLab.Data;
25using HeuristicLab.Parameters;
26using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
27using System;
28using System.Collections.Generic;
29using System.Globalization;
30using System.IO;
31using System.Linq;
32using System.Text;
33using System.Text.RegularExpressions;
34using YamlDotNet.RepresentationModel;
35
36namespace HeuristicLab.BioBoost.Data {
37
38  [StorableClass]
39  [Item("DataItem", "Generic Item for holding various pieces of information")]
40  public abstract class DataItem : ParameterizedNamedItem {
41
42    #region Construction & Cloning
43    [StorableConstructor]
44    protected DataItem(bool isDeserializing) : base(isDeserializing) {}
45    protected DataItem(DataItem orig, Cloner cloner) : base(orig, cloner) {}
46    protected DataItem() {}
47    #endregion
48
49    public static IEnumerable<DataItem> ParseFile(string filename) {
50      using (var reader = File.OpenText(filename)) {
51        return ParseStream(reader);
52      }
53    }
54
55    public abstract bool IsEquivalentTo(DataItem other);
56
57    public static IEnumerable<DataItem> ParseStream(TextReader reader) {
58      var yaml = new YamlStream();
59      yaml.Load(reader);
60      if (yaml.Documents.Count == 0) return Enumerable.Empty<DataItem>();
61      var root = yaml.Documents[0].RootNode as YamlMappingNode;
62      if (root == null) return Enumerable.Empty<DataItem>();
63      return ParseItems(root);
64    }
65
66    private static IEnumerable<DataItem> ParseItems(YamlMappingNode root) {
67      foreach (var child in root.Children) {
68        var type = child.Key as YamlScalarNode;
69        var value = child.Value as YamlSequenceNode;
70        if (type == null || value == null) {
71          // ignore or error?
72        } else {
73          switch (((string) type).ToLowerInvariant()) {
74            case "products":
75              foreach (var item in ParseSequence<Product>(value))
76                yield return item;
77              break;
78            case "logistics":
79              foreach (var item in ParseSequence<Logistic>(value))
80                yield return item;
81              break;
82            case "conversions":
83              foreach (var item in ParseSequence<Conversion>(value))
84                yield return item;
85              break;
86            case "cost-factors":
87              foreach (var item in ParseSequence<CostFactors>(value))
88                yield return item;
89              break;
90          }
91        }
92      }
93    }
94
95    public static IEnumerable<T> ParseSequence<T>(YamlSequenceNode seq) where T : DataItem, new() {
96      foreach (var node in seq.Children) {
97        var mappingNode = node as YamlMappingNode;
98        if (mappingNode == null) continue;
99        var item = new T();
100        item.Parse(mappingNode);
101        yield return item;
102      }
103    }
104
105    protected virtual void Parse(YamlMappingNode node) {
106      foreach (var child in node) {
107        var parameterNode = child.Key as YamlScalarNode;
108        if (parameterNode == null) continue;
109        var parameterName = ConvertNameYAML2NET(parameterNode.ToString());
110        IParameter param;
111        if (Parameters.TryGetValue(parameterName, out param) && param is IValueParameter) {
112          SetParameter(param, child.Value);
113        }
114      }
115      // TODO: check that all parameters have been filled
116    }
117
118    private static void SetParameter(IParameter param, YamlNode node) {
119      if (node is YamlScalarNode) {
120        SetScalarParameter((IValueParameter) param, (YamlScalarNode) node);
121      } else if (node is YamlMappingNode) {
122        SetMappingParameter((IValueParameter) param, (YamlMappingNode) node);
123      } else {
124        // TODO: parse error/warning?
125      }
126    }
127
128    private static void SetScalarParameter(IValueParameter param, YamlScalarNode node) {
129      if (param.DataType == typeof(StringValue)) {
130        param.Value = new StringValue(node.ToString());
131      } else if (param.DataType == typeof(DoubleValue)) {
132        param.Value = new DoubleValue(Double.Parse(node.ToString(), CultureInfo.InvariantCulture));
133      } else {
134        // TODO: parse error/warning?
135      }
136    }
137
138    private static void SetMappingParameter(IValueParameter param, YamlMappingNode node) {
139      if (typeof (DataItem).IsAssignableFrom(param.DataType)) {
140        var constructorInfo = param.DataType.GetConstructor(Type.EmptyTypes);
141        if (constructorInfo != null) {
142          var item = (DataItem) constructorInfo.Invoke(new object[0]);
143          item.Parse(node);
144          param.Value = item;
145          return;
146        }
147      } else if (param.DataType.IsAssignableFrom(typeof(ValueParameterCollection))) {
148        var dict = new ValueParameterCollection();
149        foreach (var child in node.Children) {
150          var key = child.Key as YamlScalarNode;
151          if (key != null) {
152            var p = new ValueParameter<DoubleValue>(key.ToString());
153            SetParameter(p, child.Value);
154            dict.Add(p);
155          } else {
156            // TODO: parse error/warning?
157          }
158        }
159        param.Value = dict;
160      }
161      // TODO: parse error? warning?
162    }
163
164    public static IItem CreateItem(YamlNode node) {
165      var n = node as YamlScalarNode;
166      if (n == null) return null;
167      double d;
168      string s = n.ToString();
169      if (Double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out d)) {
170        return new DoubleValue(d);
171      } else {
172        return new StringValue(s);
173      }
174    }
175
176    #region Auxiliary Methods
177    public static string ConvertNameYAML2NET(string s) {
178      var sb = new StringBuilder();
179      foreach (var word in s.Split('-')) {
180        sb.Append(CultureInfo.InvariantCulture.TextInfo.ToTitleCase(word.ToLower()));
181      }
182      return sb.ToString();
183    }
184
185    public static string ConvertNameNET2YAML(string s) {
186      return Regex.Replace(s, "([A-Z])", "-$1", RegexOptions.Compiled).Trim().ToLower();
187    }
188    #endregion
189
190  }
191}
Note: See TracBrowser for help on using the repository browser.