Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3026_IntegrationIntoSymSpace/HeuristicLab.JsonInterface/Converters/ValueTypeMatrixConverter.cs @ 17407

Last change on this file since 17407 was 17407, checked in by dpiringe, 4 years ago

#3026:

  • simplified converter inheritance:
    • BaseConverter now only has Inject and Extract from IJsonItemConverter as abstract methods
    • removed ParameterBaseConverter
    • concrete converters have to initialize their JsonItem now -> enables better handling with different types of JsonItem
File size: 2.2 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6using Newtonsoft.Json.Linq;
7using HeuristicLab.Data;
8using HeuristicLab.Core;
9
10namespace HeuristicLab.JsonInterface {
11  public class IntMatrixConverter : ValueTypeMatrixConverter<IntMatrix, int> {
12    public override int Priority => 1;
13    public override Type ConvertableType => typeof(IntMatrix);
14  }
15
16  public class DoubleMatrixConverter : ValueTypeMatrixConverter<DoubleMatrix, double> {
17    public override int Priority => 1;
18    public override Type ConvertableType => typeof(DoubleMatrix);
19  }
20
21  public class PercentMatrixConverter : ValueTypeMatrixConverter<PercentMatrix, double> {
22    public override int Priority => 2;
23    public override Type ConvertableType => typeof(PercentMatrix);
24  }
25
26  public class BoolMatrixConverter : ValueTypeMatrixConverter<BoolMatrix, bool> {
27    public override int Priority => 1;
28    public override Type ConvertableType => typeof(BoolMatrix);
29  }
30
31  public abstract class ValueTypeMatrixConverter<MatrixType, T> : BaseConverter
32    where MatrixType : ValueTypeMatrix<T>
33    where T : struct
34  {
35    public override void Inject(IItem item, IJsonItem data, IJsonItemConverter root) =>
36      CopyMatrixData(item as MatrixType, data.Value);
37
38    public override IJsonItem Extract(IItem value, IJsonItemConverter root) =>
39      new JsonItem() {
40        Name = "[OverridableParamName]",
41        Value = ((MatrixType)value).CloneAsMatrix()
42
43      };
44
45    #region Helper
46    private void CopyMatrixData(MatrixType matrix, object data) {
47      if (data is Array arr) {
48        var rows = arr.Length;
49        var cols = arr.Length > 0 && arr.GetValue(0) is JArray jarr ? jarr.Count : 0;
50
51        var rowInfo = matrix.GetType().GetProperty("Rows");
52        rowInfo.SetValue(matrix, rows);
53        var colInfo = matrix.GetType().GetProperty("Columns");
54        colInfo.SetValue(matrix, cols);
55
56        for (int x = 0; x < rows; ++x) {
57          jarr = (JArray)arr.GetValue(x);
58          for (int y = 0; y < cols; ++y) {
59            matrix[x, y] = jarr[y].ToObject<T>();
60          }
61        }
62      }
63    }
64    #endregion
65  }
66}
Note: See TracBrowser for help on using the repository browser.