OR-Tools  9.6
cliques.cc
Go to the documentation of this file.
1 // Copyright 2010-2022 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #include "ortools/graph/cliques.h"
15 
16 #include <algorithm>
17 #include <functional>
18 #include <memory>
19 #include <utility>
20 #include <vector>
21 
22 #include "absl/container/flat_hash_set.h"
23 #include "ortools/base/hash.h"
24 
25 namespace operations_research {
26 namespace {
27 // Encapsulates graph() to make all nodes self-connected.
28 inline bool Connects(std::function<bool(int, int)> graph, int i, int j) {
29  return i == j || graph(i, j);
30 }
31 
32 // Implements the recursive step of the Bron-Kerbosch algorithm with pivoting.
33 // - graph is a callback such that graph->Run(i, j) returns true iff there is an
34 // arc between i and j.
35 // - callback is a callback called for all maximal cliques discovered by the
36 // algorithm.
37 // - input_candidates is an array that contains the list of nodes connected to
38 // all nodes in the current clique. It is composed of two parts; the first
39 // part contains the "not" set (nodes that were already processed and must not
40 // be added to the clique - see the description of the algorithm in the
41 // paper), and nodes that are candidates for addition. The candidates from the
42 // "not" set are at the beginning of the array.
43 // - first_candidate_index elements is the index of the first candidate that is
44 // not in the "not" set (which is also the number of candidates in the "not"
45 // set).
46 // - num_input_candidates is the number of elements in input_candidates,
47 // including both the "not" set and the actual candidates.
48 // - current_clique is the current clique discovered by the algorithm.
49 // - stop is a stopping condition for the algorithm; if the value it points to
50 // is true, the algorithm stops further exploration and returns.
51 // TODO(user) : rewrite this algorithm without recursion.
52 void Search(std::function<bool(int, int)> graph,
53  std::function<bool(const std::vector<int>&)> callback,
54  int* input_candidates, int first_candidate_index,
55  int num_input_candidates, std::vector<int>* current_clique,
56  bool* stop) {
57  // The pivot is a node from input_candidates that is disconnected from the
58  // minimal number of nodes in the actual candidates (excluding the "not" set);
59  // the algorithm then selects only candidates that are disconnected from the
60  // pivot (and the pivot itself), to reach the termination condition as quickly
61  // as possible (see the original paper for more details).
62  int pivot = 0;
63 
64  // A node that is disconnected from the selected pivot. This node is selected
65  // during the pivot matching phase to speed up the first iteration of the
66  // recursive call.
67  int disconnected_node = 0;
68 
69  // The number of candidates (that are not in "not") disconnected from the
70  // selected pivot. The value is computed during pivot selection. In the
71  // "recursive" phase, we only need to do explore num_disconnected_candidates
72  // nodes, because after this step, all remaining candidates will all be
73  // connected to the pivot node (which is in "not"), so they can't form a
74  // maximal clique.
75  int num_disconnected_candidates = num_input_candidates;
76 
77  // If the selected pivot is not in "not", we need to process one more
78  // candidate (the pivot itself). pre_increment is added to
79  // num_disconnected_candidates to compensate for this fact.
80  int pre_increment = 0;
81 
82  // Find Pivot.
83  for (int i = 0; i < num_input_candidates && num_disconnected_candidates != 0;
84  ++i) {
85  int pivot_candidate = input_candidates[i];
86 
87  // Count is the number of candidates (not including nodes in the "not" set)
88  // that are disconnected from the pivot candidate.
89  int count = 0;
90 
91  // The index of a candidate node that is not connected to pivot_candidate.
92  // This node will be used to quickly start the nested iteration (we keep
93  // track of the index so that we don't have to find a node that is
94  // disconnected from the pivot later in the iteration).
95  int disconnected_node_candidate = 0;
96 
97  // Compute the number of candidate nodes that are disconnected from
98  // pivot_candidate. Note that this computation is the same for the "not"
99  // candidates and the normal candidates.
100  for (int j = first_candidate_index;
101  j < num_input_candidates && count < num_disconnected_candidates; ++j) {
102  if (!Connects(graph, pivot_candidate, input_candidates[j])) {
103  count++;
104  disconnected_node_candidate = j;
105  }
106  }
107 
108  // Update the pivot candidate if we found a new minimum for
109  // num_disconnected_candidates.
110  if (count < num_disconnected_candidates) {
111  pivot = pivot_candidate;
112  num_disconnected_candidates = count;
113 
114  if (i < first_candidate_index) {
115  disconnected_node = disconnected_node_candidate;
116  } else {
117  disconnected_node = i;
118  // The pivot candidate is not in the "not" set. We need to pre-increment
119  // the counter for the node to compensate for that.
120  pre_increment = 1;
121  }
122  }
123  }
124 
125  std::vector<int> new_candidates;
126  new_candidates.reserve(num_input_candidates);
127  for (int remaining_candidates = num_disconnected_candidates + pre_increment;
128  remaining_candidates >= 1; remaining_candidates--) {
129  // Swap a node that is disconnected from the pivot (or the pivot itself)
130  // with the first candidate, so that we can later move it to "not" simply by
131  // increasing the index of the first candidate that is not in "not".
132  const int selected = input_candidates[disconnected_node];
133  std::swap(input_candidates[disconnected_node],
134  input_candidates[first_candidate_index]);
135 
136  // Fill the list of candidates and the "not" set for the recursive call:
137  new_candidates.clear();
138  for (int i = 0; i < first_candidate_index; ++i) {
139  if (Connects(graph, selected, input_candidates[i])) {
140  new_candidates.push_back(input_candidates[i]);
141  }
142  }
143  const int new_first_candidate_index = new_candidates.size();
144  for (int i = first_candidate_index + 1; i < num_input_candidates; ++i) {
145  if (Connects(graph, selected, input_candidates[i])) {
146  new_candidates.push_back(input_candidates[i]);
147  }
148  }
149  const int new_candidate_size = new_candidates.size();
150 
151  // Add the selected candidate to the current clique.
152  current_clique->push_back(selected);
153 
154  // If there are no remaining candidates, we have found a maximal clique.
155  // Otherwise, do the recursive step.
156  if (new_candidate_size == 0) {
157  *stop = callback(*current_clique);
158  } else {
159  if (new_first_candidate_index < new_candidate_size) {
160  Search(graph, callback, new_candidates.data(),
161  new_first_candidate_index, new_candidate_size, current_clique,
162  stop);
163  if (*stop) {
164  return;
165  }
166  }
167  }
168 
169  // Remove the selected candidate from the current clique.
170  current_clique->pop_back();
171  // Add the selected candidate to the set "not" - we've already processed
172  // all possible maximal cliques that use this node in 'current_clique'. The
173  // current candidate is the element of the new candidate set, so we can move
174  // it to "not" simply by increasing first_candidate_index.
175  first_candidate_index++;
176 
177  // Find the next candidate that is disconnected from the pivot.
178  if (remaining_candidates > 1) {
179  disconnected_node = first_candidate_index;
180  while (disconnected_node < num_input_candidates &&
181  Connects(graph, pivot, input_candidates[disconnected_node])) {
182  disconnected_node++;
183  }
184  }
185  }
186 }
187 
188 class FindAndEliminate {
189  public:
190  FindAndEliminate(std::function<bool(int, int)> graph, int node_count,
191  std::function<bool(const std::vector<int>&)> callback)
192  : graph_(graph), node_count_(node_count), callback_(callback) {}
193 
194  bool GraphCallback(int node1, int node2) {
195  if (visited_.find(
196  std::make_pair(std::min(node1, node2), std::max(node1, node2))) !=
197  visited_.end()) {
198  return false;
199  }
200  return Connects(graph_, node1, node2);
201  }
202 
203  bool SolutionCallback(const std::vector<int>& solution) {
204  const int size = solution.size();
205  if (size > 1) {
206  for (int i = 0; i < size - 1; ++i) {
207  for (int j = i + 1; j < size; ++j) {
208  visited_.insert(std::make_pair(std::min(solution[i], solution[j]),
209  std::max(solution[i], solution[j])));
210  }
211  }
212  callback_(solution);
213  }
214  return false;
215  }
216 
217  private:
218  std::function<bool(int, int)> graph_;
219  int node_count_;
220  std::function<bool(const std::vector<int>&)> callback_;
221  absl::flat_hash_set<std::pair<int, int>> visited_;
222 };
223 } // namespace
224 
225 // This method implements the 'version2' of the Bron-Kerbosch
226 // algorithm to find all maximal cliques in a undirected graph.
227 void FindCliques(std::function<bool(int, int)> graph, int node_count,
228  std::function<bool(const std::vector<int>&)> callback) {
229  std::unique_ptr<int[]> initial_candidates(new int[node_count]);
230  std::vector<int> actual;
231 
232  for (int c = 0; c < node_count; ++c) {
233  initial_candidates[c] = c;
234  }
235 
236  bool stop = false;
237  Search(graph, callback, initial_candidates.get(), 0, node_count, &actual,
238  &stop);
239 }
240 
241 void CoverArcsByCliques(std::function<bool(int, int)> graph, int node_count,
242  std::function<bool(const std::vector<int>&)> callback) {
243  FindAndEliminate cache(graph, node_count, callback);
244  std::unique_ptr<int[]> initial_candidates(new int[node_count]);
245  std::vector<int> actual;
246 
247  std::function<bool(int, int)> cached_graph = [&cache](int i, int j) {
248  return cache.GraphCallback(i, j);
249  };
250  std::function<bool(const std::vector<int>&)> cached_callback =
251  [&cache](const std::vector<int>& res) {
252  return cache.SolutionCallback(res);
253  };
254 
255  for (int c = 0; c < node_count; ++c) {
256  initial_candidates[c] = c;
257  }
258 
259  bool stop = false;
260  Search(cached_graph, cached_callback, initial_candidates.get(), 0, node_count,
261  &actual, &stop);
262 }
263 
264 } // namespace operations_research
int64_t max
Definition: alldiff_cst.cc:140
int64_t min
Definition: alldiff_cst.cc:139
MPCallback * callback
void swap(IdMap< K, V > &a, IdMap< K, V > &b)
Definition: id_map.h:269
Collection of objects used to extend the Constraint Solver library.
void CoverArcsByCliques(std::function< bool(int, int)> graph, int node_count, std::function< bool(const std::vector< int > &)> callback)
Definition: cliques.cc:241
void FindCliques(std::function< bool(int, int)> graph, int node_count, std::function< bool(const std::vector< int > &)> callback)
Definition: cliques.cc:227