source: branches/FitnessLandscapeAnalysis/VRPProblemAnalyzer/KMeansClustering.cs @ 7231

Last change on this file since 7231 was 7231, checked in by svonolfe, 11 years ago

Added VRP problem analyzer (#1696)

File size: 1.9 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading;
6using System.Diagnostics;
7
8namespace VRPProblemAnalyzer {
9  class Cluster {
10    public List<double[]> Items { get; set; }
11    public double[] Center { get; set; }   
12
13    public Cluster() {
14      Items = new List<double[]>();
15      Center = new double[2];
16    }
17  }
18
19  class KMeansClustering {
20    public static List<Cluster> Cluster(double[,] vertices, int k, int restarts) {
21      while (true) {
22        int info = 0;
23        double[,] centers = null;
24        int[] xyc = null;
25        bool aborted = false;
26
27
28        Thread t = new Thread(delegate() {
29          alglib.kmeansgenerate(vertices, vertices.Length / 2, 2, k, restarts + 1, out info, out centers, out xyc);
30        });
31
32        t.Start();
33        Stopwatch sw = new Stopwatch();
34        sw.Start();
35        while (t.ThreadState == System.Threading.ThreadState.Running && sw.ElapsedMilliseconds < 1000) {
36          Thread.Sleep(10);
37        }
38        sw.Stop();
39
40        if (t.ThreadState == System.Threading.ThreadState.Running) {
41          aborted = true;
42          t.Abort();
43        }
44
45        if (info == -3)
46          return new List<Cluster>();
47        else if (info == 1 && !aborted) {
48          List<Cluster> result = new List<Cluster>();
49          int count = centers.Length / 2;
50          for (int i = 0; i < count; i++) {
51            result.Add(new Cluster());
52            result[i].Center[0] = centers[0, i];
53            result[i].Center[1] = centers[1, i];
54          }
55
56          for (int i = 0; i < xyc.Length; i++) {
57            double[] coords = new double[2];
58            coords[0] = vertices[i, 0];
59            coords[1] = vertices[i, 1];
60
61            result[xyc[i]].Items.Add(coords);
62          }
63
64          result.RemoveAll(c => c.Items.Count == 0);
65
66          return result;
67        }
68      }
69    }
70  }
71}
Note: See TracBrowser for help on using the repository browser.