Free cookie consent management tool by TermsFeed Policy Generator

source: branches/QAP/HeuristicLab.Analysis/3.3/MultidimensionalScaling/MultidimensionalScaling.cs @ 5728

Last change on this file since 5728 was 5723, checked in by abeham, 14 years ago

#1330

  • Moved MDS into Analysis
  • Added test with some simple examples
File size: 5.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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 HeuristicLab.Data;
24
25namespace HeuristicLab.Analysis {
26  public static class MultidimensionalScaling {
27
28    /// <summary>
29    /// Performs the Kruskal-Shepard algorithm and applies a gradient descent method
30    /// to fit the coordinates such that the difference between the fit distances
31    /// and the actual distances is minimal.
32    /// </summary>
33    /// <param name="distances">A symmetric NxN matrix that specifies the distances between each element i and j. Diagonal elements are ignored.</param>
34    /// <param name="stress">Returns the stress between the fit distances and the actual distances.</param>
35    /// <returns>A Nx2 matrix where the first column represents the x- and the second column the y coordinates.</returns>
36    public static DoubleMatrix MetricByDistance(DoubleMatrix distances, out double stress) {
37      if (distances == null) throw new ArgumentNullException("distances");
38      if (distances.Rows != distances.Columns) throw new ArgumentException("Distance matrix must be a square matrix.", "distances");
39      stress = 0.0;
40
41      int dimension = distances.Rows;
42      if (dimension == 1) return new DoubleMatrix(new double[,] { { 0, 0 } });
43      else if (dimension == 2) return new DoubleMatrix(new double[,] { { 0, distances[0, 1] } });
44
45      DoubleMatrix coordinates = new DoubleMatrix(dimension, 2);
46      double rad = (2 * Math.PI) / coordinates.Rows;
47      for (int i = 0; i < dimension; i++) {
48        coordinates[i, 0] = 10 * Math.Cos(rad * i);
49        coordinates[i, 1] = 10 * Math.Sin(rad * i);
50      }
51
52      return MetricByDistance(distances, out stress, coordinates);
53    }
54
55    public static DoubleMatrix MetricByDistance(DoubleMatrix distances, out double stress, DoubleMatrix coordinates) {
56      int dimension = distances.Rows;
57      if (dimension != distances.Columns || coordinates.Rows != dimension) throw new ArgumentException("distances or coordinates");
58
59      stress = 0.0;
60      double epsg = 1e-7;
61      double epsf = 0;
62      double epsx = 0;
63      int maxits = 1000;
64      alglib.mincgstate state = null;
65      alglib.mincgreport rep;
66
67      for (int iterations = 0; iterations < 20; iterations++) {
68        for (int i = 0; i < dimension; i++) {
69          double[] c = new double[] { coordinates[i, 0], coordinates[i, 1] };
70
71          if (iterations == 0 && i == 0) {
72            alglib.mincgcreate(c, out state);
73            alglib.mincgsetcond(state, epsg, epsf, epsx, maxits);
74          } else {
75            alglib.mincgrestartfrom(state, c);
76          }
77          alglib.mincgoptimize(state, StressGradient, null, new Info(coordinates, distances, i));
78          alglib.mincgresults(state, out c, out rep);
79
80          coordinates[i, 0] = c[0];
81          coordinates[i, 1] = c[1];
82        }
83      }
84      stress = CalculateNormalizedStress(dimension, distances, coordinates);
85      return coordinates;
86    }
87
88    private static void StressGradient(double[] x, ref double func, double[] grad, object obj) {
89      func = 0; grad[0] = 0; grad[1] = 0;
90      Info info = (obj as Info);
91      for (int i = 0; i < info.Coordinates.Rows; i++) {
92        double c = info.Distances[info.Row, i];
93        if (i != info.Row) {
94          double a = info.Coordinates[i, 0];
95          double b = info.Coordinates[i, 1];
96          func += Stress(x, c, a, b);
97          grad[0] += ((2 * x[0] - 2 * a) * Math.Sqrt(x[1] * x[1] - 2 * b * x[1] + x[0] * x[0] - 2 * a * x[0] + b * b + a * a) - 2 * c * x[0] + 2 * a * c) / Math.Sqrt(x[1] * x[1] - 2 * b * x[1] + x[0] * x[0] - 2 * a * x[0] + b * b + a * a);
98          grad[1] += ((2 * x[1] - 2 * b) * Math.Sqrt(x[1] * x[1] - 2 * b * x[1] + x[0] * x[0] - 2 * a * x[0] + b * b + a * a) - 2 * c * x[1] + 2 * b * c) / Math.Sqrt(x[1] * x[1] - 2 * b * x[1] + x[0] * x[0] - 2 * a * x[0] + b * b + a * a);
99        }
100      }
101    }
102
103    private static double Stress(double[] x, double distance, double xCoord, double yCoord) {
104      return Stress(x[0], x[1], distance, xCoord, yCoord);
105    }
106
107    private static double Stress(double x, double y, double distance, double otherX, double otherY) {
108      double d = Math.Sqrt((x - otherX) * (x - otherX)
109                         + (y - otherY) * (y - otherY));
110      return (d - distance) * (d - distance);
111    }
112
113    public static double CalculateNormalizedStress(int dimension, DoubleMatrix distances, DoubleMatrix coordinates) {
114      double stress = 0;
115      for (int i = 0; i < dimension - 1; i++) {
116        for (int j = i + 1; j < dimension; j++) {
117          if (distances[i, j] != 0) {
118            stress += Stress(coordinates[i, 0], coordinates[i, 1], distances[i, j], coordinates[j, 0], coordinates[j, 1])
119              / (distances[i, j] * distances[i, j]);
120          }
121        }
122      }
123      return stress;
124    }
125
126    private class Info {
127      public DoubleMatrix Coordinates { get; set; }
128      public DoubleMatrix Distances { get; set; }
129      public int Row { get; set; }
130
131      public Info(DoubleMatrix c, DoubleMatrix d, int r) {
132        Coordinates = c;
133        Distances = d;
134        Row = r;
135      }
136    }
137  }
138}
Note: See TracBrowser for help on using the repository browser.