MayaFlux 0.2.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches

◆ k_nearest_neighbors()

EdgeList MayaFlux::Kinesis::k_nearest_neighbors ( const Eigen::MatrixXd &  points,
size_t  k 
)

Compute K-nearest neighbors graph.

Parameters
pointsDx N matrix where each column is a point
kNumber of nearest neighbors per point
Returns
Edge list (point index pairs)

For each point, connects it to its k nearest neighbors. Directed graph: point i connects to k neighbors, but neighbor j might not reciprocally connect to i.

Complexity: O(n² log k) with partial sort

Definition at line 46 of file ProximityGraphs.cpp.

49{
50 Eigen::Index n = points.cols();
51 if (n < 2) {
52 return {};
53 }
54
55 k = std::min(k, static_cast<size_t>(n - 1));
56
57 EdgeList edges;
58 edges.reserve(n * k);
59
60 for (Eigen::Index i = 0; i < n; ++i) {
61 std::vector<std::pair<double, size_t>> distances;
62 distances.reserve(n - 1);
63
64 for (Eigen::Index j = 0; j < n; ++j) {
65 if (i == j)
66 continue;
67 double dist_sq = distance_squared(points.col(i), points.col(j));
68 distances.emplace_back(dist_sq, static_cast<size_t>(j));
69 }
70
71 std::partial_sort(
72 distances.begin(),
73 distances.begin() + k,
74 distances.end());
75
76 for (size_t neighbor_idx = 0; neighbor_idx < k; ++neighbor_idx) {
77 edges.emplace_back(static_cast<size_t>(i), distances[neighbor_idx].second);
78 }
79 }
80
81 MF_DEBUG(Journal::Component::Kinesis, Journal::Context::Runtime,
82 "k_nearest_neighbors: {} points, k={}, generated {} edges",
83 n, k, edges.size());
84
85 return edges;
86}
#define MF_DEBUG(comp, ctx,...)

References MayaFlux::Journal::Kinesis, MF_DEBUG, and MayaFlux::Journal::Runtime.

Referenced by generate_proximity_graph().

+ Here is the caller graph for this function: