blob: b2fd49ff71e3fc6db8e78bcb3d7128fa718b7cae [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
2// Copyright 2015 Google Inc. All rights reserved.
3// http://ceres-solver.org/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are met:
7//
8// * Redistributions of source code must retain the above copyright notice,
9// this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above copyright notice,
11// this list of conditions and the following disclaimer in the documentation
12// and/or other materials provided with the distribution.
13// * Neither the name of Google Inc. nor the names of its contributors may be
14// used to endorse or promote products derived from this software without
15// specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27// POSSIBILITY OF SUCH DAMAGE.
28//
29// Author: David Gallup (dgallup@google.com)
30// Sameer Agarwal (sameeragarwal@google.com)
31
32#include "ceres/canonical_views_clustering.h"
33
34#include <unordered_set>
35#include <unordered_map>
36
37#include "ceres/graph.h"
38#include "ceres/map_util.h"
39#include "glog/logging.h"
40
41namespace ceres {
42namespace internal {
43
44using std::vector;
45
46typedef std::unordered_map<int, int> IntMap;
47typedef std::unordered_set<int> IntSet;
48
49class CanonicalViewsClustering {
50 public:
51 CanonicalViewsClustering() {}
52
53 // Compute the canonical views clustering of the vertices of the
54 // graph. centers will contain the vertices that are the identified
55 // as the canonical views/cluster centers, and membership is a map
56 // from vertices to cluster_ids. The i^th cluster center corresponds
57 // to the i^th cluster. It is possible depending on the
58 // configuration of the clustering algorithm that some of the
59 // vertices may not be assigned to any cluster. In this case they
60 // are assigned to a cluster with id = kInvalidClusterId.
61 void ComputeClustering(const CanonicalViewsClusteringOptions& options,
62 const WeightedGraph<int>& graph,
63 vector<int>* centers,
64 IntMap* membership);
65
66 private:
67 void FindValidViews(IntSet* valid_views) const;
68 double ComputeClusteringQualityDifference(const int candidate,
69 const vector<int>& centers) const;
70 void UpdateCanonicalViewAssignments(const int canonical_view);
71 void ComputeClusterMembership(const vector<int>& centers,
72 IntMap* membership) const;
73
74 CanonicalViewsClusteringOptions options_;
75 const WeightedGraph<int>* graph_;
76 // Maps a view to its representative canonical view (its cluster
77 // center).
78 IntMap view_to_canonical_view_;
79 // Maps a view to its similarity to its current cluster center.
80 std::unordered_map<int, double> view_to_canonical_view_similarity_;
81};
82
83void ComputeCanonicalViewsClustering(
84 const CanonicalViewsClusteringOptions& options,
85 const WeightedGraph<int>& graph,
86 vector<int>* centers,
87 IntMap* membership) {
88 time_t start_time = time(NULL);
89 CanonicalViewsClustering cv;
90 cv.ComputeClustering(options, graph, centers, membership);
91 VLOG(2) << "Canonical views clustering time (secs): "
92 << time(NULL) - start_time;
93}
94
95// Implementation of CanonicalViewsClustering
96void CanonicalViewsClustering::ComputeClustering(
97 const CanonicalViewsClusteringOptions& options,
98 const WeightedGraph<int>& graph,
99 vector<int>* centers,
100 IntMap* membership) {
101 options_ = options;
102 CHECK(centers != nullptr);
103 CHECK(membership != nullptr);
104 centers->clear();
105 membership->clear();
106 graph_ = &graph;
107
108 IntSet valid_views;
109 FindValidViews(&valid_views);
110 while (valid_views.size() > 0) {
111 // Find the next best canonical view.
112 double best_difference = -std::numeric_limits<double>::max();
113 int best_view = 0;
114
115 // TODO(sameeragarwal): Make this loop multi-threaded.
116 for (const auto& view : valid_views) {
117 const double difference =
118 ComputeClusteringQualityDifference(view, *centers);
119 if (difference > best_difference) {
120 best_difference = difference;
121 best_view = view;
122 }
123 }
124
125 CHECK_GT(best_difference, -std::numeric_limits<double>::max());
126
127 // Add canonical view if quality improves, or if minimum is not
128 // yet met, otherwise break.
129 if ((best_difference <= 0) &&
130 (centers->size() >= options_.min_views)) {
131 break;
132 }
133
134 centers->push_back(best_view);
135 valid_views.erase(best_view);
136 UpdateCanonicalViewAssignments(best_view);
137 }
138
139 ComputeClusterMembership(*centers, membership);
140}
141
142// Return the set of vertices of the graph which have valid vertex
143// weights.
144void CanonicalViewsClustering::FindValidViews(
145 IntSet* valid_views) const {
146 const IntSet& views = graph_->vertices();
147 for (const auto& view : views) {
148 if (graph_->VertexWeight(view) != WeightedGraph<int>::InvalidWeight()) {
149 valid_views->insert(view);
150 }
151 }
152}
153
154// Computes the difference in the quality score if 'candidate' were
155// added to the set of canonical views.
156double CanonicalViewsClustering::ComputeClusteringQualityDifference(
157 const int candidate,
158 const vector<int>& centers) const {
159 // View score.
160 double difference =
161 options_.view_score_weight * graph_->VertexWeight(candidate);
162
163 // Compute how much the quality score changes if the candidate view
164 // was added to the list of canonical views and its nearest
165 // neighbors became members of its cluster.
166 const IntSet& neighbors = graph_->Neighbors(candidate);
167 for (const auto& neighbor : neighbors) {
168 const double old_similarity =
169 FindWithDefault(view_to_canonical_view_similarity_, neighbor, 0.0);
170 const double new_similarity = graph_->EdgeWeight(neighbor, candidate);
171 if (new_similarity > old_similarity) {
172 difference += new_similarity - old_similarity;
173 }
174 }
175
176 // Number of views penalty.
177 difference -= options_.size_penalty_weight;
178
179 // Orthogonality.
180 for (int i = 0; i < centers.size(); ++i) {
181 difference -= options_.similarity_penalty_weight *
182 graph_->EdgeWeight(centers[i], candidate);
183 }
184
185 return difference;
186}
187
188// Reassign views if they're more similar to the new canonical view.
189void CanonicalViewsClustering::UpdateCanonicalViewAssignments(
190 const int canonical_view) {
191 const IntSet& neighbors = graph_->Neighbors(canonical_view);
192 for (const auto& neighbor : neighbors) {
193 const double old_similarity =
194 FindWithDefault(view_to_canonical_view_similarity_, neighbor, 0.0);
195 const double new_similarity =
196 graph_->EdgeWeight(neighbor, canonical_view);
197 if (new_similarity > old_similarity) {
198 view_to_canonical_view_[neighbor] = canonical_view;
199 view_to_canonical_view_similarity_[neighbor] = new_similarity;
200 }
201 }
202}
203
204// Assign a cluster id to each view.
205void CanonicalViewsClustering::ComputeClusterMembership(
206 const vector<int>& centers,
207 IntMap* membership) const {
208 CHECK(membership != nullptr);
209 membership->clear();
210
211 // The i^th cluster has cluster id i.
212 IntMap center_to_cluster_id;
213 for (int i = 0; i < centers.size(); ++i) {
214 center_to_cluster_id[centers[i]] = i;
215 }
216
217 static const int kInvalidClusterId = -1;
218
219 const IntSet& views = graph_->vertices();
220 for (const auto& view : views) {
221 auto it = view_to_canonical_view_.find(view);
222 int cluster_id = kInvalidClusterId;
223 if (it != view_to_canonical_view_.end()) {
224 cluster_id = FindOrDie(center_to_cluster_id, it->second);
225 }
226
227 InsertOrDie(membership, view, cluster_id);
228 }
229}
230
231} // namespace internal
232} // namespace ceres