Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9613 was 7232, checked in by epitzer, 13 years ago

#1696: Updated build configuration and simplified thread handling and removed hard coded paths

File size: 1.6 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
26
27        Thread t = new Thread(delegate() {
28          alglib.kmeansgenerate(vertices, vertices.Length / 2, 2, k, restarts + 1, out info, out centers, out xyc);
29        });
30        t.Start();
31        if (!t.Join(1000)) {
32          t.Abort();
33          continue;
34        }
35
36        if (info == -3)
37          return new List<Cluster>();
38        else if (info == 1) {
39          List<Cluster> result = new List<Cluster>();
40          int count = centers.Length / 2;
41          for (int i = 0; i < count; i++) {
42            result.Add(new Cluster());
43            result[i].Center[0] = centers[0, i];
44            result[i].Center[1] = centers[1, i];
45          }
46
47          for (int i = 0; i < xyc.Length; i++) {
48            double[] coords = new double[2];
49            coords[0] = vertices[i, 0];
50            coords[1] = vertices[i, 1];
51
52            result[xyc[i]].Items.Add(coords);
53          }
54
55          result.RemoveAll(c => c.Items.Count == 0);
56
57          return result;
58        }
59      }
60    }
61  }
62}
Note: See TracBrowser for help on using the repository browser.