Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization.Operators/3.3/SolutionSimilarityCalculator.cs @ 12931

Last change on this file since 12931 was 12129, checked in by bburlacu, 10 years ago

#2332: SolutionSimilarityCalculator: throw exception in the CheckQualityEquality method if the double arrays are not of the same length, simplify equality check for double arrays.

File size: 6.0 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 System;
23using System.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28
29namespace HeuristicLab.Optimization.Operators {
30  /// <summary>
31  /// A base class for items that perform similarity calculation between two solutions.
32  /// </summary>
33  [Item("SimilarityCalculator", "A base class for items that perform similarity calculation between two solutions.")]
34  [StorableClass]
35  public abstract class SolutionSimilarityCalculator : Item, ISolutionSimilarityCalculator {
36    protected abstract bool IsCommutative { get; }
37
38    #region Properties
39    [Storable]
40    public string SolutionVariableName { get; set; }
41    [Storable]
42    public string QualityVariableName { get; set; }
43    #endregion
44
45    [StorableConstructor]
46    protected SolutionSimilarityCalculator(bool deserializing) : base(deserializing) { }
47
48    protected SolutionSimilarityCalculator(SolutionSimilarityCalculator original, Cloner cloner)
49      : base(original, cloner) {
50      this.SolutionVariableName = original.SolutionVariableName;
51      this.QualityVariableName = original.QualityVariableName;
52    }
53    protected SolutionSimilarityCalculator() : base() { }
54
55    public double[][] CalculateSolutionCrowdSimilarity(IScope leftSolutionCrowd, IScope rightSolutionCrowd) {
56      if (leftSolutionCrowd == null || rightSolutionCrowd == null)
57        throw new ArgumentException("Cannot calculate similarity because one of the provided crowds or both are null.");
58
59      var leftIndividuals = leftSolutionCrowd.SubScopes;
60      var rightIndividuals = rightSolutionCrowd.SubScopes;
61
62      if (!leftIndividuals.Any() || !rightIndividuals.Any())
63        throw new ArgumentException("Cannot calculate similarity because one of the provided crowds or both are empty.");
64
65      var similarityMatrix = new double[leftIndividuals.Count][];
66      for (int i = 0; i < leftIndividuals.Count; i++) {
67        similarityMatrix[i] = new double[rightIndividuals.Count];
68        for (int j = 0; j < rightIndividuals.Count; j++) {
69          similarityMatrix[i][j] = CalculateSolutionSimilarity(leftIndividuals[i], rightIndividuals[j]);
70        }
71      }
72
73      return similarityMatrix;
74    }
75
76    public double[][] CalculateSolutionCrowdSimilarity(IScope solutionCrowd) {
77      if (solutionCrowd == null)
78        throw new ArgumentException("Cannot calculate similarity because the provided crowd is null.");
79
80      var individuals = solutionCrowd.SubScopes;
81
82      if (!individuals.Any())
83        throw new ArgumentException("Cannot calculate similarity because the provided crowd is empty.");
84
85      var similarityMatrix = new double[individuals.Count][];
86      for (int i = 0; i < individuals.Count; i++) similarityMatrix[i] = new double[individuals.Count];
87
88      if (IsCommutative) {
89        for (int i = 0; i < individuals.Count; i++) {
90          for (int j = i; j < individuals.Count; j++) {
91            similarityMatrix[i][j] = similarityMatrix[j][i] = CalculateSolutionSimilarity(individuals[i], individuals[j]);
92          }
93        }
94      } else {
95        for (int i = 0; i < individuals.Count; i++) {
96          for (int j = i; j < individuals.Count; j++) {
97            similarityMatrix[i][j] = CalculateSolutionSimilarity(individuals[i], individuals[j]);
98            if (i == j) continue;
99            similarityMatrix[j][i] = CalculateSolutionSimilarity(individuals[j], individuals[i]);
100          }
101        }
102      }
103
104      return similarityMatrix;
105    }
106
107    public abstract double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution);
108
109    public virtual bool Equals(IScope x, IScope y) {
110      if (ReferenceEquals(x, y)) return true;
111      if (x == null || y == null) return false;
112
113      var q1 = x.Variables[QualityVariableName].Value;
114      var q2 = y.Variables[QualityVariableName].Value;
115
116      return CheckQualityEquality(q1, q2) && CalculateSolutionSimilarity(x, y).IsAlmost(1.0);
117    }
118
119    public virtual int GetHashCode(IScope scope) {
120      var quality = scope.Variables[QualityVariableName].Value;
121      var dv = quality as DoubleValue;
122      if (dv != null)
123        return dv.Value.GetHashCode();
124
125      var da = quality as DoubleArray;
126      if (da != null) {
127        int hash = 17;
128        unchecked {
129          for (int i = 0; i < da.Length; ++i) {
130            hash += hash * 23 + da[i].GetHashCode();
131          }
132          return hash;
133        }
134      }
135      return 0;
136    }
137
138    private static bool CheckQualityEquality(IItem q1, IItem q2) {
139      var d1 = q1 as DoubleValue;
140      var d2 = q2 as DoubleValue;
141
142      if (d1 != null && d2 != null)
143        return d1.Value.IsAlmost(d2.Value);
144
145      var da1 = q1 as DoubleArray;
146      var da2 = q2 as DoubleArray;
147
148      if (da1 != null && da2 != null) {
149        if (da1.Length != da2.Length)
150          throw new ArgumentException("The quality arrays must have the same length.");
151
152        for (int i = 0; i < da1.Length; ++i) {
153          if (!da1[i].IsAlmost(da2[i]))
154            return false;
155        }
156
157        return true;
158      }
159
160      throw new ArgumentException("Could not determine quality equality.");
161    }
162  }
163}
Note: See TracBrowser for help on using the repository browser.