Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.QuadraticAssignment.Views/3.3/MultidimensionalScaling.cs @ 11170

Last change on this file since 11170 was 11170, checked in by ascheibe, 9 years ago

#2115 updated copyright year in stable branch

File size: 5.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.Problems.QuadraticAssignment.Views {
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      double epsg = 1e-7;
53      double epsf = 0;
54      double epsx = 0;
55      int maxits = 0;
56      alglib.mincgstate state = null;
57      alglib.mincgreport rep;
58
59      for (int iterations = 0; iterations < 10; iterations++) {
60        for (int i = 0; i < dimension; i++) {
61          double[] c = new double[] { coordinates[i, 0], coordinates[i, 1] };
62
63          if (iterations == 0 && i == 0) {
64            alglib.mincgcreate(c, out state);
65            alglib.mincgsetcond(state, epsg, epsf, epsx, maxits);
66          } else {
67            alglib.mincgrestartfrom(state, c);
68          }
69          alglib.mincgoptimize(state, StressGradient, null, new Info(coordinates, distances, i));
70          alglib.mincgresults(state, out c, out rep);
71
72          coordinates[i, 0] = c[0];
73          coordinates[i, 1] = c[1];
74        }
75      }
76      stress = CalculateNormalizedStress(dimension, distances, coordinates);
77      return coordinates;
78    }
79
80    private static void StressGradient(double[] x, ref double func, double[] grad, object obj) {
81      func = 0; grad[0] = 0; grad[1] = 0;
82      Info info = (obj as Info);
83      for (int i = 0; i < info.Coordinates.Rows; i++) {
84        double c = info.Distances[info.Row, i];
85        if (i != info.Row) {
86          double a = info.Coordinates[i, 0];
87          double b = info.Coordinates[i, 1];
88          func += Stress(x, c, a, b);
89          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);
90          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);
91        }
92      }
93    }
94
95    private static double Stress(double[] x, double distance, double xCoord, double yCoord) {
96      return Stress(x[0], x[1], distance, xCoord, yCoord);
97    }
98
99    private static double Stress(double x, double y, double distance, double otherX, double otherY) {
100      double d = Math.Sqrt((x - otherX) * (x - otherX)
101                         + (y - otherY) * (y - otherY));
102      return (d - distance) * (d - distance);
103    }
104
105    public static double CalculateNormalizedStress(int dimension, DoubleMatrix distances, DoubleMatrix coordinates) {
106      double stress = 0;
107      for (int i = 0; i < dimension - 1; i++) {
108        for (int j = i + 1; j < dimension; j++) {
109          if (distances[i, j] != 0) {
110            stress += Stress(coordinates[i, 0], coordinates[i, 1], distances[i, j], coordinates[j, 0], coordinates[j, 1])
111              / (distances[i, j] * distances[i, j]);
112          }
113        }
114      }
115      return stress;
116    }
117
118    private class Info {
119      public DoubleMatrix Coordinates { get; set; }
120      public DoubleMatrix Distances { get; set; }
121      public int Row { get; set; }
122
123      public Info(DoubleMatrix c, DoubleMatrix d, int r) {
124        Coordinates = c;
125        Distances = d;
126        Row = r;
127      }
128    }
129  }
130}
Note: See TracBrowser for help on using the repository browser.