-
Notifications
You must be signed in to change notification settings - Fork 77
Added DBScan clustering to ColorPaletteSampler #753
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Avid29
wants to merge
2
commits into
CommunityToolkit:main
Choose a base branch
from
Avid29:ColorAnalysis/Clustering_Refinement
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
160 changes: 160 additions & 0 deletions
160
components/ColorAnalyzer/src/ColorPaletteSampler/ColorPaletteSampler.DBScan.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
| // See the LICENSE file in the project root for more information. | ||
|
|
||
| using System.Numerics; | ||
|
|
||
| namespace CommunityToolkit.WinUI.Helpers; | ||
|
|
||
| public partial class ColorPaletteSampler | ||
| { | ||
| private ref struct DBScan | ||
| { | ||
| private const int Unclassified = -1; | ||
|
|
||
| public static Vector3[] Cluster(Span<Vector3> points, float epsilon, int minPoints, ref float[] weights) | ||
| { | ||
| var centroids = new List<Vector3>(); | ||
| var newWeights = new List<float>(); | ||
|
|
||
| // Create context | ||
| var context = new DBScan(points, weights, epsilon, minPoints); | ||
|
|
||
| // Attempt to create a cluster around each point, | ||
| // skipping that point if already classified | ||
| for (int i = 0; i < points.Length; i++) | ||
| { | ||
| // Already classified, skip | ||
| if (context.PointClusterIds[i] is not Unclassified) | ||
| continue; | ||
|
|
||
| // Attempt to create cluster | ||
| if(context.CreateCluster(i, out var centroid, out var weight)) | ||
| { | ||
| centroids.Add(centroid); | ||
| newWeights.Add(weight); | ||
| } | ||
| } | ||
|
|
||
| weights = newWeights.ToArray(); | ||
| return centroids.ToArray(); | ||
| } | ||
|
|
||
| private bool CreateCluster(int originIndex, out Vector3 centroid, out float weight) | ||
| { | ||
| weight = 0; | ||
| centroid = Vector3.Zero; | ||
| var seeds = GetSeeds(originIndex, out bool isCore); | ||
|
|
||
| // Not enough seeds to be a core point. | ||
| // Cannot create a cluster around it | ||
| if (!isCore) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| ExpandCluster(seeds, out centroid, out weight); | ||
| ClusterId++; | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| private void ExpandCluster(Queue<int> seeds, out Vector3 centroid, out float weight) | ||
| { | ||
| weight = 0; | ||
| centroid = Vector3.Zero; | ||
| while(seeds.Count > 0) | ||
| { | ||
| var seedIndex = seeds.Dequeue(); | ||
|
|
||
| // Skip duplicate seed entries | ||
| if (PointClusterIds[seedIndex] is not Unclassified) | ||
| continue; | ||
|
|
||
| // Assign this seed's id to the cluster | ||
| PointClusterIds[seedIndex] = ClusterId; | ||
| var w = Weights[seedIndex]; | ||
| centroid += Points[seedIndex] * w; | ||
| weight += w; | ||
|
|
||
| // Check if this seed is a core point | ||
| var grandSeeds = GetSeeds(seedIndex, out var seedIsCore); | ||
| if (!seedIsCore) | ||
| continue; | ||
|
|
||
| // This seed is a core point. Enqueue all its seeds | ||
| foreach(var grandSeedIndex in grandSeeds) | ||
| if (PointClusterIds[grandSeedIndex] is Unclassified) | ||
| seeds.Enqueue(grandSeedIndex); | ||
| } | ||
|
|
||
| centroid /= weight; | ||
| } | ||
|
|
||
| private Queue<int> GetSeeds(int originIndex, out bool isCore) | ||
| { | ||
| var origin = Points[originIndex]; | ||
|
|
||
| // NOTE: Seeding could be done using a spatial data structure to improve traversal | ||
| // speeds. However currently DBSCAN is run after KMeans with a maximum of 8 points. | ||
| // There is no need. | ||
|
|
||
| var seeds = new Queue<int>(); | ||
| for (int i = 0; i < Points.Length; i++) | ||
| { | ||
| if (Vector3.DistanceSquared(origin, Points[i]) <= Epsilon2) | ||
| seeds.Enqueue(i); | ||
| } | ||
|
|
||
| // Count includes self, so compare without checking equals | ||
| isCore = seeds.Count > MinPoints; | ||
| return seeds; | ||
| } | ||
|
|
||
| private DBScan(Span<Vector3> points, Span<float> weights, float epsilon, int minPoints) | ||
| { | ||
| Points = points; | ||
| Weights = weights; | ||
| Epsilon2 = epsilon * epsilon; | ||
| MinPoints = minPoints; | ||
|
|
||
| ClusterId = 0; | ||
| PointClusterIds = new int[points.Length]; | ||
| for(int i = 0; i < points.Length; i++) | ||
| PointClusterIds[i] = Unclassified; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the points being clustered. | ||
| /// </summary> | ||
| public Span<Vector3> Points { get; } | ||
|
|
||
| /// <summary> | ||
| /// Gets the weights of the points. | ||
| /// </summary> | ||
| public Span<float> Weights { get; } | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the id of the currently evaluating cluster. | ||
| /// </summary> | ||
| public int ClusterId { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Gets an array containing the id of the cluster each point belongs to. | ||
| /// </summary> | ||
| public int[] PointClusterIds { get; } | ||
|
|
||
| /// <summary> | ||
| /// Gets epsilon squared. Where epsilon is the max distance to consider two points connected. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// This is cached as epsilon squared to skip a sqrt operation when comparing distances to epsilon. | ||
| /// </remarks> | ||
| public double Epsilon2 { get; } | ||
|
|
||
| /// <summary> | ||
| /// Gets the minimum number of points required to make a core point. | ||
| /// </summary> | ||
| public int MinPoints { get; } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This creates an O(n²) algorithm for seed finding. For large datasets, consider using spatial data structures like KD-trees or grid-based approaches to improve performance.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is run after KMeans, there are only 8 points. Building a KD-Tree is far more effort than it's worth, and may introduce overhead with a net loss