| | | 1 | | using System.Collections.Generic; |
| | | 2 | | using System.Linq; |
| | | 3 | | using UnityEngine; |
| | | 4 | | |
| | | 5 | | // The constrained k-means clusterer performs k-means clustering under size and radius constraints. |
| | | 6 | | public class ConstrainedKMeansClusterer : SizeAndRadiusConstrainedClustererBase { |
| | 0 | 7 | | public ConstrainedKMeansClusterer(int maxSize, float maxRadius) : base(maxSize, maxRadius) {} |
| | | 8 | | |
| | | 9 | | // Generate the clusters from the list of hierarchical objects. |
| | 0 | 10 | | public override List<Cluster> Cluster(IEnumerable<IHierarchical> hierarchicals) { |
| | 0 | 11 | | if (hierarchicals == null || !hierarchicals.Any()) { |
| | 0 | 12 | | return new List<Cluster>(); |
| | | 13 | | } |
| | | 14 | | |
| | 0 | 15 | | int numClusters = (int)Mathf.Ceil(hierarchicals.Count() / _maxSize); |
| | | 16 | | KMeansClusterer clusterer; |
| | | 17 | | List<Cluster> clusters; |
| | 0 | 18 | | while (true) { |
| | 0 | 19 | | clusterer = new KMeansClusterer(numClusters); |
| | 0 | 20 | | clusters = clusterer.Cluster(hierarchicals); |
| | | 21 | | |
| | | 22 | | // Count the number of over-populated and over-sized clusters. |
| | 0 | 23 | | int numOverPopulatedClusters = 0; |
| | 0 | 24 | | int numOverSizedClusters = 0; |
| | 0 | 25 | | foreach (var cluster in clusters) { |
| | 0 | 26 | | if (cluster.Size > _maxSize) { |
| | 0 | 27 | | ++numOverPopulatedClusters; |
| | 0 | 28 | | } |
| | 0 | 29 | | if (cluster.Radius() > _maxRadius) { |
| | 0 | 30 | | ++numOverSizedClusters; |
| | 0 | 31 | | } |
| | 0 | 32 | | } |
| | | 33 | | |
| | | 34 | | // If all clusters satisfy the size and radius constraints, the algorithm has converged. |
| | 0 | 35 | | if (numOverPopulatedClusters == 0 && numOverSizedClusters == 0) { |
| | 0 | 36 | | break; |
| | | 37 | | } |
| | | 38 | | |
| | 0 | 39 | | numClusters += |
| | | 40 | | (int)Mathf.Ceil(Mathf.Max(numOverPopulatedClusters, numOverSizedClusters) / 2f); |
| | 0 | 41 | | } |
| | 0 | 42 | | return clusters; |
| | 0 | 43 | | } |
| | | 44 | | } |