dwave-preprocessing 0.6.7__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. dwave/__init__.py +16 -0
  2. dwave/preprocessing/__init__.py +42 -0
  3. dwave/preprocessing/composites/__init__.py +19 -0
  4. dwave/preprocessing/composites/clip.py +114 -0
  5. dwave/preprocessing/composites/connected_components.py +113 -0
  6. dwave/preprocessing/composites/fix_variables.py +153 -0
  7. dwave/preprocessing/composites/scale.py +144 -0
  8. dwave/preprocessing/composites/spin_reversal_transform.py +221 -0
  9. dwave/preprocessing/cyfix_variables.cp313-win_amd64.pyd +0 -0
  10. dwave/preprocessing/cyfix_variables.cpp +29498 -0
  11. dwave/preprocessing/cyfix_variables.pyx +58 -0
  12. dwave/preprocessing/include/dwave/exceptions.hpp +28 -0
  13. dwave/preprocessing/include/dwave/flags.hpp +63 -0
  14. dwave/preprocessing/include/dwave/presolve.hpp +91 -0
  15. dwave/preprocessing/include/dwave-preprocessing/fix_variables.hpp +119 -0
  16. dwave/preprocessing/include/dwave-preprocessing/helper_data_structures.hpp +152 -0
  17. dwave/preprocessing/include/dwave-preprocessing/helper_graph_algorithms.hpp +476 -0
  18. dwave/preprocessing/include/dwave-preprocessing/implication_network.hpp +690 -0
  19. dwave/preprocessing/include/dwave-preprocessing/mapping_policy.hpp +124 -0
  20. dwave/preprocessing/include/dwave-preprocessing/posiform_info.hpp +384 -0
  21. dwave/preprocessing/include/dwave-preprocessing/push_relabel.hpp +775 -0
  22. dwave/preprocessing/libcpp.pxd +59 -0
  23. dwave/preprocessing/lower_bounds.py +94 -0
  24. dwave/preprocessing/presolve/__init__.pxd +13 -0
  25. dwave/preprocessing/presolve/__init__.py +16 -0
  26. dwave/preprocessing/presolve/cypresolve.cp313-win_amd64.pyd +0 -0
  27. dwave/preprocessing/presolve/cypresolve.cpp +39255 -0
  28. dwave/preprocessing/presolve/cypresolve.pxd +45 -0
  29. dwave/preprocessing/presolve/cypresolve.pyi +50 -0
  30. dwave/preprocessing/presolve/cypresolve.pyx +340 -0
  31. dwave/preprocessing/presolve/exceptions.py +21 -0
  32. dwave/preprocessing/presolve/pypresolve.py +173 -0
  33. dwave/preprocessing/src/exceptions.cpp +21 -0
  34. dwave/preprocessing/src/presolve.cpp +105 -0
  35. dwave/preprocessing/src/presolveimpl.hpp +1060 -0
  36. dwave_preprocessing-0.6.7.dist-info/DELVEWHEEL +2 -0
  37. dwave_preprocessing-0.6.7.dist-info/LICENSE +203 -0
  38. dwave_preprocessing-0.6.7.dist-info/METADATA +114 -0
  39. dwave_preprocessing-0.6.7.dist-info/RECORD +42 -0
  40. dwave_preprocessing-0.6.7.dist-info/WHEEL +5 -0
  41. dwave_preprocessing-0.6.7.dist-info/top_level.txt +1 -0
  42. dwave_preprocessing.libs/msvcp140-c5f1b59771da57851103ca2011763553.dll +0 -0
@@ -0,0 +1,775 @@
1
+ /**
2
+ #
3
+ # Copyright 2000 University of Notre Dame.
4
+ # Authors: Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee
5
+ #
6
+ # Boost Software License - Version 1.0 - August 17th, 2003
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person or organization
9
+ # obtaining a copy of the software and accompanying documentation covered by
10
+ # this license (the "Software") to use, reproduce, display, distribute,
11
+ # execute, and transmit the Software, and to prepare derivative works of the
12
+ # Software, and to permit third-parties to whom the Software is furnished to
13
+ # do so, all subject to the following:
14
+ #
15
+ # The copyright notices in the Software and this entire statement, including
16
+ # the above license grant, this restriction and the following disclaimer,
17
+ # must be included in all copies of the Software, in whole or in part, and
18
+ # all derivative works of the Software, unless such copies or derivative
19
+ # works are solely in the form of machine-executable object code generated by
20
+ # a source language processor.
21
+ #
22
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ # FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
25
+ # SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
26
+ # FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
27
+ # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28
+ # DEALINGS IN THE SOFTWARE.
29
+ #
30
+ #
31
+ # MIT License
32
+ #
33
+ # Copyright (c) 2019 Jan Groschaft
34
+ #
35
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
36
+ # of this software and associated documentation files (the "Software"), to deal
37
+ # in the Software without restriction, including without limitation the rights
38
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
39
+ # copies of the Software, and to permit persons to whom the Software is
40
+ # furnished to do so, subject to the following conditions:
41
+ #
42
+ # The above copyright notice and this permission notice shall be included in all
43
+ # copies or substantial portions of the Software.
44
+ #
45
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
46
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
47
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
48
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
49
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
50
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
51
+ # SOFTWARE.
52
+ */
53
+
54
+ #ifndef PUSH_RELABEL_HPP_INCLUDED
55
+ #define PUSH_RELABEL_HPP_INCLUDED
56
+
57
+ #include <algorithm>
58
+ #include <iostream>
59
+ #include <tuple>
60
+ #include <vector>
61
+
62
+ #include "helper_data_structures.hpp"
63
+
64
+ //#define COLLECT_STATISTICS
65
+
66
+ #ifdef COLLECT_STATISTICS
67
+ #define DEBUG_INCREMENT(x) ((x)++)
68
+ #else
69
+ #define DEBUG_INCREMENT(x)
70
+ #endif
71
+
72
+ // Maximum flow solver based on Push-Relabel algorithm, using the heuristics of
73
+ // Global Relabeling, Gap Relabeling, & Highest Vertex First. This is based on
74
+ // Cherkassky, B., Goldberg, A. On Implementing the Push-Relabel Method for the
75
+ // Maximum Flow Problem . Algorithmica 19, 390-410 (1997).
76
+ // https://doi.org/10.1007/PL00009180.
77
+ template <class EdgeType> class PushRelabelSolver {
78
+ public:
79
+ using edge_iterator = typename std::vector<EdgeType>::iterator;
80
+ using capacity_t = typename EdgeType::capacity_type;
81
+
82
+ PushRelabelSolver(std::vector<std::vector<EdgeType>> &adjacency_list,
83
+ int source, int sink);
84
+
85
+ capacity_t computeMaximumPreflow();
86
+
87
+ void convertPreflowToFlow(bool handle_self_loops = false);
88
+
89
+ capacity_t computeMaximumFlow(bool handle_self_loops = false);
90
+
91
+ void printStatistics();
92
+
93
+ private:
94
+ // We use preallocated vertex nodes for maintaining the linked list since we
95
+ // know the total number of vertices. Vertex number is redundant but when
96
+ // capacity_t is of a type consuming 8 bytes, structural padding will waste
97
+ // the same amount of memory if it were removed.
98
+ struct vertex_node_t {
99
+ int vertex_number;
100
+ int height;
101
+ capacity_t excess;
102
+ vertex_node_t *next;
103
+ vertex_node_t *prev;
104
+ };
105
+
106
+ // Linked lists to keep track of active/inactive vertices at different
107
+ // heights/distances from the sink.
108
+ struct level_t {
109
+ preallocated_linked_list<vertex_node_t> active_vertices;
110
+ preallocated_linked_list<vertex_node_t> inactive_vertices;
111
+ };
112
+
113
+ // This will always be manually inlined, without relying on the compiler to do
114
+ // so since this function is very small and the algorithm calls this the
115
+ // highest number of times.
116
+ // void push(edge_iterator eit) {
117
+ // int from_vertex = eit->from_vertex;
118
+ // int to_vertex = eit->to_vertex;
119
+ // capacity_t flow = std::min(eit->residual,
120
+ // _vertices[from_vertex].excess); eit->residual -= flow;
121
+ // _adjacency_list[to_vertex][eit->reverse_edge_index].residual += flow;
122
+ // _vertices[from_vertex].excess -= flow;
123
+ // _vertices[to_vertex].excess += flow;
124
+ // }
125
+
126
+ void relabel(int vertex);
127
+
128
+ void discharge(int vertex);
129
+
130
+ // Relabel the vertices with the current distance from the sink, found by
131
+ // using reverse breadth first search.
132
+ void globalRelabel();
133
+
134
+ // When there is no vertex at a particular height/distance from the sink, all
135
+ // the other vertices at higher heights are then disconnected from the sink,
136
+ // so label them as such (set their height to the number of vertices) so they
137
+ // are not processed during the computation of the preflow.
138
+ void gapRelabel(int empty_level_height);
139
+
140
+ // Get the iterator pair of edges which need to be processed for a vertex next
141
+ // time it is encountered, we may want to skip the edges which have been
142
+ // saturated already before relabeling of the vertex happened.
143
+ inline std::pair<edge_iterator, edge_iterator>
144
+ outEdges(const int &vertex) const {
145
+ return {_adjacency_list[vertex].begin(), _adjacency_list[vertex].end()};
146
+ }
147
+
148
+ inline edge_iterator reverseEdgeIterator(const edge_iterator &eit) const {
149
+ return _adjacency_list[eit->to_vertex].begin() + eit->reverse_edge_index;
150
+ }
151
+
152
+ void printLevels();
153
+
154
+ private:
155
+ int _sink;
156
+ int _source;
157
+ int _num_vertices;
158
+ size_t _num_edges;
159
+ int _max_active_height, _min_active_height, _max_height;
160
+ size_t _num_global_relabels, _num_gap_relabels, _num_gap_vertices,
161
+ _num_pushes, _num_relabels;
162
+
163
+ // Thresholds and counters for triggering global relabeling.
164
+ size_t _relabel_work;
165
+ size_t GLOBAL_RELABEL_THRESHOLD;
166
+ static const int ALPHA = 6, BETA = 12;
167
+ static constexpr double GLOBAL_RELABEL_FREQUENCY = 0.5;
168
+
169
+ std::vector<level_t> _levels;
170
+ std::vector<vertex_node_t> _vertices;
171
+ vector_based_queue<int> _vertex_queue;
172
+ std::vector<std::vector<EdgeType>> &_adjacency_list;
173
+
174
+ // In different phases of the algorithm, we might know that we do not need to
175
+ // traverse all the outgoing edges from a vertex, and may need to start from a
176
+ // certain point. For example when we relabel a vertex, we know the edge from
177
+ // which we may be able to push flow out of the vertex when we return to the
178
+ // discharge routine, thus we save the iterator of that edge in this
179
+ // _pending_out_edges vector.
180
+ std::vector<std::pair<edge_iterator, edge_iterator>> _pending_out_edges;
181
+ };
182
+
183
+ // We assume that the flow graph has the correct residuals assigned to the
184
+ // edges. Or namely initial value of residual of an edge is equal to its
185
+ // capacity.
186
+ template <class EdgeType>
187
+ PushRelabelSolver<EdgeType>::PushRelabelSolver(
188
+ std::vector<std::vector<EdgeType>> &adjacency_list, int source, int sink)
189
+ : _sink(sink),_source(source),
190
+ _vertex_queue(vector_based_queue<int>(adjacency_list.size())), _adjacency_list(adjacency_list) {
191
+ _num_global_relabels = 0;
192
+ _num_gap_relabels = 0;
193
+ _num_gap_vertices = 0;
194
+ _num_relabels = 0;
195
+ _num_pushes = 0;
196
+ _num_vertices = _adjacency_list.size();
197
+ _vertices.resize(_num_vertices);
198
+ _levels.resize(_num_vertices);
199
+ _pending_out_edges.resize(_num_vertices);
200
+
201
+ _num_edges = 0;
202
+ for (int vertex = 0; vertex < _num_vertices; vertex++) {
203
+ _pending_out_edges[vertex] = outEdges(vertex);
204
+ _vertices[vertex].vertex_number = vertex;
205
+ _vertices[vertex].height = 1;
206
+ _vertices[vertex].excess = 0;
207
+ _num_edges += _adjacency_list[vertex].size();
208
+ }
209
+ _vertices[_source].height = _num_vertices;
210
+ _vertices[_sink].height = 0;
211
+
212
+ GLOBAL_RELABEL_THRESHOLD = (ALPHA * _num_vertices) + (_num_edges / 2);
213
+
214
+ // Saturate the edges coming out of the source. We assume initially there is
215
+ // no flow and residual of edges are equal to their capacities.
216
+ double overflow_detector = 0;
217
+ edge_iterator eit, eit_end;
218
+ for (std::tie(eit, eit_end) = outEdges(_source); eit != eit_end; eit++) {
219
+ overflow_detector += eit->residual;
220
+ DEBUG_INCREMENT(_num_pushes);
221
+ capacity_t flow = eit->residual;
222
+ eit->residual = 0;
223
+ auto eit_reverse = reverseEdgeIterator(eit);
224
+ eit_reverse->residual += flow;
225
+ _vertices[eit->to_vertex].excess += flow;
226
+ }
227
+
228
+ if (overflow_detector >
229
+ static_cast<double>(std::numeric_limits<capacity_t>::max())) {
230
+ std::cout << "WARNING : Overflow is possible in the flow network. Sum of "
231
+ "capacity of out edges from source exceed numeric limit of "
232
+ "the type used for capacity."
233
+ << std::endl;
234
+ }
235
+
236
+ _max_height = 1;
237
+ _max_active_height = 0;
238
+ _min_active_height = _num_vertices;
239
+
240
+ globalRelabel();
241
+ }
242
+
243
+ // Relabel the vertices with the current distance from the sink, found by using
244
+ // reverse breadth first search. Assumes that the unreachable vertices are
245
+ // marked as such.
246
+ template <class EdgeType> void PushRelabelSolver<EdgeType>::globalRelabel() {
247
+ DEBUG_INCREMENT(_num_global_relabels);
248
+ for (int h = 0; h <= _max_height; h++) {
249
+ _levels[h].active_vertices.clear();
250
+ _levels[h].inactive_vertices.clear();
251
+ }
252
+ _max_height = 0;
253
+ _max_active_height = 0;
254
+ _min_active_height = _num_vertices;
255
+
256
+ // The value of height being the number of vertices means it is not reachable
257
+ // from the sink as the value of height can be at most one less than the
258
+ // number of vertices.
259
+ int already_unreachable = 0;
260
+ assert((_vertices[_sink].height != _num_vertices) &&
261
+ "Sink should have been reachable before globalRelabel");
262
+ for (int i = 0; i < _num_vertices; i++) {
263
+ if (_vertices[i].height == _num_vertices) {
264
+ already_unreachable++;
265
+ } else {
266
+ _vertices[i].height = _num_vertices;
267
+ }
268
+ }
269
+
270
+ int num_vertices_to_find = _num_vertices - already_unreachable;
271
+ int num_vertices_found = 0;
272
+ _vertices[_sink].height = 0;
273
+ _vertex_queue.reset(); // Reset as we are reusing the queue.
274
+ _vertex_queue.push(_sink);
275
+ num_vertices_found++; // We had assumed sink is reachable, so reaching it.
276
+ while (!_vertex_queue.empty()) {
277
+ int parent_vertex = _vertex_queue.pop();
278
+ int current_height = _vertices[parent_vertex].height + 1;
279
+ edge_iterator eit, eit_end;
280
+ for (std::tie(eit, eit_end) = outEdges(parent_vertex); eit != eit_end;
281
+ eit++) {
282
+ int to_vertex = eit->to_vertex;
283
+ if (eit->getReverseEdgeResidual() &&
284
+ _vertices[to_vertex].height == _num_vertices) {
285
+ _vertices[to_vertex].height = current_height;
286
+ if (_vertices[to_vertex].excess > 0) {
287
+ _levels[current_height].active_vertices.push_front(
288
+ &_vertices[to_vertex]);
289
+ } else {
290
+ _levels[current_height].inactive_vertices.push_front(
291
+ &_vertices[to_vertex]);
292
+ }
293
+ _pending_out_edges[to_vertex] = outEdges(to_vertex);
294
+ num_vertices_found++;
295
+ _vertex_queue.push(to_vertex);
296
+ }
297
+ }
298
+
299
+ if (!_levels[current_height].active_vertices.empty()) {
300
+ _max_height = std::max(_max_height, current_height);
301
+ _max_active_height = std::max(_max_active_height, current_height);
302
+ _min_active_height = std::min(_min_active_height, current_height);
303
+ } else if (!_levels[current_height].inactive_vertices.empty()) {
304
+ _max_height = std::max(_max_height, current_height);
305
+ }
306
+
307
+ if (num_vertices_found == num_vertices_to_find) {
308
+ break;
309
+ }
310
+ }
311
+ }
312
+
313
+ // Set the height of the vertex such that it is one more than the minimum height
314
+ // of the vertices to which it has edgese with residual capacity. If there is no
315
+ // such edge then it should be discarded from this phase of the algorithm by
316
+ // setting a height equal to the number of vertices.
317
+ template <class EdgeType>
318
+ void PushRelabelSolver<EdgeType>::relabel(int vertex) {
319
+ DEBUG_INCREMENT(_num_relabels);
320
+ int min_relabel_height = _num_vertices;
321
+ _vertices[vertex].height = min_relabel_height;
322
+ edge_iterator eit, eit_end, eit_min_relabel;
323
+ std::tie(eit, eit_end) = outEdges(vertex);
324
+ _relabel_work += BETA + std::distance(eit, eit_end);
325
+ for (; eit != eit_end; eit++) {
326
+ if (eit->residual) {
327
+ int to_vertex = eit->to_vertex;
328
+ if (_vertices[to_vertex].height < min_relabel_height) {
329
+ min_relabel_height = _vertices[to_vertex].height;
330
+ eit_min_relabel = eit;
331
+ }
332
+ }
333
+ }
334
+
335
+ min_relabel_height++;
336
+ if (min_relabel_height < _num_vertices) {
337
+ _vertices[vertex].height = min_relabel_height;
338
+ _pending_out_edges[vertex].first = eit_min_relabel;
339
+ _max_height = std::max(_max_height, min_relabel_height);
340
+ }
341
+ }
342
+
343
+ // Keep on pushing flow out of a vertex till it has any excess left, if all of
344
+ // its excess is discharged, it becomes inactive.
345
+ template <class EdgeType>
346
+ void PushRelabelSolver<EdgeType>::discharge(int vertex) {
347
+ assert(_vertices[vertex].excess > 0);
348
+ while (1) {
349
+ edge_iterator eit, eit_end;
350
+ int pushable_height = _vertices[vertex].height - 1;
351
+ for (std::tie(eit, eit_end) = _pending_out_edges[vertex]; eit != eit_end;
352
+ eit++) {
353
+ if (eit->residual) {
354
+ int to_vertex = eit->to_vertex;
355
+ if (_vertices[to_vertex].height == pushable_height) {
356
+ if (to_vertex != _sink && _vertices[to_vertex].excess == 0) {
357
+ _levels[pushable_height].inactive_vertices.erase(
358
+ &_vertices[to_vertex]);
359
+ _levels[pushable_height].active_vertices.push_front(
360
+ &_vertices[to_vertex]);
361
+ }
362
+
363
+ // Push flow - inlined.
364
+ // DO NOT use utility functions like reverseEdgeIterator here
365
+ // as the compiler may decide not to inline them and it will
366
+ // significantly impact performance.
367
+ DEBUG_INCREMENT(_num_pushes);
368
+ capacity_t flow = std::min(eit->residual, _vertices[vertex].excess);
369
+ eit->residual -= flow;
370
+ _adjacency_list[to_vertex][eit->reverse_edge_index].residual += flow;
371
+ _vertices[vertex].excess -= flow;
372
+ _vertices[to_vertex].excess += flow;
373
+ if (_vertices[vertex].excess == 0) {
374
+ break;
375
+ }
376
+ }
377
+ }
378
+ }
379
+
380
+ if (!_levels[pushable_height].active_vertices.empty()) {
381
+ _max_active_height = std::max(_max_active_height, pushable_height);
382
+ _min_active_height = std::min(_min_active_height, pushable_height);
383
+ }
384
+
385
+ // The loop did not break thus the vertex still has some excess flow to
386
+ // discharge so relabel.
387
+ if (eit == eit_end) {
388
+ int preRelabelHeight = _vertices[vertex].height;
389
+ relabel(vertex);
390
+ if (_levels[preRelabelHeight].active_vertices.empty() &&
391
+ _levels[preRelabelHeight].inactive_vertices.empty()) {
392
+ gapRelabel(preRelabelHeight);
393
+ // We just relabelled all the vertices at its previous height to a
394
+ // height of the number of vertices, so this vertex does not have any
395
+ // residual edge to a vertex that has height/distance one less than its
396
+ // current height, since the level at that height is empty. So we set
397
+ // this one to a height of _num_vertices as well.
398
+ _vertices[vertex].height = _num_vertices;
399
+ }
400
+ if (_vertices[vertex].height == _num_vertices) {
401
+ break;
402
+ }
403
+ } else {
404
+ _pending_out_edges[vertex].first = eit;
405
+ _levels[_vertices[vertex].height].inactive_vertices.push_front(
406
+ &_vertices[vertex]);
407
+ break;
408
+ }
409
+ }
410
+ assert(_max_height >= 0 && _max_height < _num_vertices);
411
+ assert(_max_active_height >= 0 && _max_active_height < _num_vertices);
412
+ }
413
+
414
+ // When there is no vertex at a particular height/distance from sink, all the
415
+ // other vertices at higher heights are then disconnected from the sink, so
416
+ // label them as such (set their height to number of vertices) so they are not
417
+ // processed during the computation of the preflow.
418
+ template <class EdgeType>
419
+ void PushRelabelSolver<EdgeType>::gapRelabel(int empty_level_height) {
420
+ DEBUG_INCREMENT(_num_gap_relabels);
421
+ assert(empty_level_height <= _max_height);
422
+ auto level_it = _levels.begin() + empty_level_height + 1;
423
+ auto level_it_end = _levels.begin() + _max_height + 1;
424
+ for (; level_it != level_it_end; level_it++) {
425
+ // The last highest active vertex processed was from the empty_level_height.
426
+ assert(level_it->active_vertices.empty());
427
+ int inactive_level_size = level_it->inactive_vertices.size();
428
+ vertex_node_t *vertex_node_ptr = level_it->inactive_vertices.front();
429
+ for (int i = 0; i < inactive_level_size; i++) {
430
+ DEBUG_INCREMENT(_num_gap_vertices);
431
+ vertex_node_ptr->height = _num_vertices;
432
+ vertex_node_ptr = vertex_node_ptr->next;
433
+ }
434
+ level_it->inactive_vertices.clear();
435
+ }
436
+ _max_height = empty_level_height - 1;
437
+ _max_active_height = empty_level_height - 1;
438
+ assert(_max_height >= 0 && _max_height < _num_vertices);
439
+ assert(_max_active_height >= 0 && _max_active_height < _num_vertices);
440
+ }
441
+
442
+ // Compute the maximum preflow, that is we compute the value of the max-flow but
443
+ // the flow graph is not valid since there are vertices with excess flow in
444
+ // them.
445
+ template <class EdgeType>
446
+ typename EdgeType::capacity_type
447
+ PushRelabelSolver<EdgeType>::computeMaximumPreflow() {
448
+
449
+ _relabel_work = 0;
450
+ while (_max_active_height >= _min_active_height) {
451
+ if (_levels[_max_active_height].active_vertices.empty()) {
452
+ _max_active_height--;
453
+ } else {
454
+ vertex_node_t *vertex_node_ptr =
455
+ _levels[_max_active_height].active_vertices.pop();
456
+ discharge(vertex_node_ptr->vertex_number);
457
+ }
458
+
459
+ if (_relabel_work * GLOBAL_RELABEL_FREQUENCY > GLOBAL_RELABEL_THRESHOLD) {
460
+ globalRelabel();
461
+ _relabel_work = 0;
462
+ }
463
+ }
464
+ return _vertices[_sink].excess;
465
+ }
466
+
467
+ // This is the algorithm used in the boost graph library. An iterative depth
468
+ // first search (DFS) is applied to do a topological sort of the vertices with
469
+ // excess flow so that flow can be pushed away from them in order. This way
470
+ // preflow can be converted to flow. Since we want to do the topological sort to
471
+ // have the vertices having excess flow to be at the root/parent positions and
472
+ // vertices producing flow to them to be their children, we do the depth first
473
+ // search along reverse edges of the flow network. A cycle in the directed graph
474
+ // would prevent a proper topological sort thus in the same depth first search
475
+ // if any flow cycle is detected, the cycle is cutoff by reducing the flow by
476
+ // the minimum "magnitude" of flow in the cycle, this causes the edges with flow
477
+ // equal to the minimum flow to get saturated. The depth first search then backs
478
+ // off, or in other words, undoes what was done since encountering the vertex
479
+ // from which the saturated edge was incident from, so that it can go on as
480
+ // before from that point. Note there will be no explicit stack used for this
481
+ // depth first search, but instead the iterators pointing to the edges to be
482
+ // traversed for each vertex will be updated and an array containing parents of
483
+ // vertices will help simulate the stack. When we want to pop the stack we can
484
+ // basically look at the parent of the current vertex being processed and when
485
+ // we want to push a vertex into the stack, we can save it as the parent of the
486
+ // child vertex and restart the loop with the child vertex as the current
487
+ // vertex. For solving max-flows on graphs induced from posiforms, we do not
488
+ // need to consider self loops since we do not have terms like X_i*X_i'
489
+ // which might create a self loop for X_i or X_i'.
490
+ template <class EdgeType>
491
+ void PushRelabelSolver<EdgeType>::convertPreflowToFlow(bool handle_self_loops) {
492
+
493
+ // If there are self loops then we can just eliminate the flow, as it does not
494
+ // contribute to the excess of the vertex, what goes out through an edge comes
495
+ // back through its reverse counterpart.
496
+ if (handle_self_loops) {
497
+ for (int from_vertex = 0; from_vertex < _num_vertices; from_vertex++) {
498
+ edge_iterator eit, eit_end;
499
+ for (std::tie(eit, eit_end) = outEdges(from_vertex); eit != eit_end;
500
+ eit++) {
501
+ if (eit->to_vertex == from_vertex) {
502
+ eit->residual = eit->getCapacity();
503
+ }
504
+ }
505
+ }
506
+ }
507
+
508
+ // Vertex at the start of the topological sort.
509
+ int topology_start_vertex = -1;
510
+ bool topology_initialized = false;
511
+ std::vector<int> parent(_num_vertices, -1);
512
+
513
+ // An entry of -1 for a vertex would mean there is no successor to that vertex
514
+ // in the topological ordering.
515
+ std::vector<int> topology_next(_num_vertices, -1);
516
+
517
+ // White - not processed yet.
518
+ // Grey - under process.
519
+ // Black - finished processing.
520
+ enum DFS_COLOR { WHITE, GREY, BLACK };
521
+ std::vector<int> dfs_color(_num_vertices, DFS_COLOR::WHITE);
522
+
523
+ for (int vertex = 0; vertex < _num_vertices; vertex++) {
524
+ _pending_out_edges[vertex] = outEdges(vertex);
525
+ }
526
+
527
+ // Iterative DFS.
528
+ for (int current_vertex = 0; current_vertex < _num_vertices;
529
+ current_vertex++) {
530
+ if ((dfs_color[current_vertex] == DFS_COLOR::WHITE) &&
531
+ (_vertices[current_vertex].excess > 0) && (current_vertex != _source) &&
532
+ (current_vertex != _sink)) {
533
+
534
+ // The root of a DFS tree.
535
+ int root_vertex = current_vertex;
536
+ dfs_color[root_vertex] = DFS_COLOR::GREY;
537
+
538
+ while (true) {
539
+
540
+ // We need to increment the actual iterator in the array. Think
541
+ // of recursive DFS, the counter of a for loop belonging to a particular
542
+ // stack frame is saved in the stack frame while the function calls
543
+ // itself recursively so when it comes back it finds the counter with
544
+ // the proper value.
545
+ for (; _pending_out_edges[current_vertex].first !=
546
+ _pending_out_edges[current_vertex].second;
547
+ _pending_out_edges[current_vertex].first++) {
548
+
549
+ // We are traversing reverse edges with capacity 0, i.e the children
550
+ // are sending flow to the parent. So we denote the main iterator by
551
+ // eit_reverse unlike other places in the file.
552
+ // The edge brings flow to the current_vertex, we want to
553
+ // topologically sort such that the root receives flow from the source
554
+ // through its children, so that we can push them back.
555
+ auto eit_reverse = _pending_out_edges[current_vertex].first;
556
+ if ((eit_reverse->getCapacity() == 0) &&
557
+ (eit_reverse->residual > 0)) {
558
+ int child_vertex = eit_reverse->to_vertex;
559
+ if (dfs_color[child_vertex] == DFS_COLOR::WHITE) {
560
+ dfs_color[child_vertex] = DFS_COLOR::GREY;
561
+
562
+ // Equivalent to calling DFS, i.e pushing into the stack. The
563
+ // while loop above will start the for loop all over again, but
564
+ // this time the current_vertex will be the child_vertex, and we
565
+ // will be able to trace back as the parent-child relationship is
566
+ // saved in the parent array. Note breaking the loop does not
567
+ // allow the iterator of edges to be incremented for the parent,
568
+ // just like in a recursive DFS, the for loop does not get
569
+ // incremented till the recursive call to DFS finishes.
570
+ parent[child_vertex] = current_vertex;
571
+ current_vertex = child_vertex;
572
+ break;
573
+ }
574
+
575
+ // We have detected a cycle, now we need to break the cycle and then
576
+ // back the DFS up to the vertex from which emanates the first edge
577
+ // that will be saturated/flow nullified in order to remove the
578
+ // cycle.
579
+ else if (dfs_color[child_vertex] == DFS_COLOR::GREY) {
580
+
581
+ // We chose to enter the condition only for reverse/residual edges
582
+ // and the iterators in _pending_out_edges are not incremented
583
+ // while pushing, thus we can cycle over the cycle found, as the
584
+ // path formed by the iterators in _pending_out_edges outlines the
585
+ // cycle we just discovered. The value of residual in a reverse
586
+ // edge is equal to the flow in the orignal edge/absolute value of
587
+ // flow in the reverse edge. We are currently traversing reverse
588
+ // edges, so we take the minimum of residuals.
589
+ capacity_t min_flow_magnitude = eit_reverse->residual;
590
+ int cycle_traversing_vertex = child_vertex;
591
+ while (cycle_traversing_vertex != current_vertex) {
592
+ min_flow_magnitude =
593
+ std::min(min_flow_magnitude,
594
+ _pending_out_edges[cycle_traversing_vertex]
595
+ .first->residual);
596
+ cycle_traversing_vertex =
597
+ _pending_out_edges[cycle_traversing_vertex]
598
+ .first->to_vertex;
599
+ }
600
+
601
+ // Reduce the flow in the edges with minimum flow in the cycle,
602
+ // that is saturate the reverse edge or say zero out the residual.
603
+ // Process the back edge first.
604
+ eit_reverse = _pending_out_edges[current_vertex].first;
605
+ eit_reverse->residual -= min_flow_magnitude;
606
+ auto eit = reverseEdgeIterator(eit_reverse);
607
+ eit->residual += min_flow_magnitude;
608
+
609
+ // Reduce the flow on the other edges of the cycle, but this time
610
+ // starting from the child_vertex.
611
+ // The vertex from which the first saturated vertex emanates is
612
+ // the one we should restart our DFS from.
613
+ cycle_traversing_vertex = child_vertex;
614
+ int restart_vertex = current_vertex;
615
+ bool restart_vertex_found = false;
616
+ while (cycle_traversing_vertex != current_vertex) {
617
+ eit_reverse = _pending_out_edges[cycle_traversing_vertex].first;
618
+ eit_reverse->residual -= min_flow_magnitude;
619
+ auto eit = reverseEdgeIterator(eit_reverse);
620
+ eit->residual += min_flow_magnitude;
621
+
622
+ // Undo the DFS coloring from the point of restart_vertex if
623
+ // found.
624
+ if ((eit_reverse->residual == 0) && !restart_vertex_found) {
625
+ restart_vertex_found = true;
626
+ restart_vertex = cycle_traversing_vertex;
627
+ dfs_color[eit_reverse->to_vertex] = DFS_COLOR::WHITE;
628
+ } else if (restart_vertex_found) {
629
+ dfs_color[eit_reverse->to_vertex] = DFS_COLOR::WHITE;
630
+ }
631
+
632
+ cycle_traversing_vertex = eit_reverse->to_vertex;
633
+ }
634
+
635
+ if (restart_vertex != current_vertex) {
636
+ current_vertex = restart_vertex;
637
+ _pending_out_edges[current_vertex].first++;
638
+ break;
639
+ }
640
+ } // else if (dfs_color[child_vertex] == DFS_COLOR::GREY)
641
+ } // if ((..->getCapacity() == 0) && (..->residual > 0))
642
+ } // for (; _pending_out_edges[current_vertex]...
643
+
644
+ // The current vertex has finished checking all ita out edges, we can
645
+ // put it in its proper place in the topological order, and then
646
+ // backtrack.
647
+ if (_pending_out_edges[current_vertex].first ==
648
+ _pending_out_edges[current_vertex].second) {
649
+ dfs_color[current_vertex] = DFS_COLOR::BLACK;
650
+ if (current_vertex != _source) {
651
+ if (!topology_initialized) {
652
+ topology_start_vertex = current_vertex;
653
+ topology_initialized = true;
654
+ } else {
655
+ topology_next[current_vertex] = topology_start_vertex;
656
+ topology_start_vertex = current_vertex;
657
+ }
658
+ }
659
+
660
+ // If it is a root, then we break the while loop and the for loop
661
+ // above will automatically select the next vertex. It is similar to
662
+ // the situation that in DFS a wrapper function calls the first
663
+ // instance of DFS on different roots, and before the call there is no
664
+ // stack frame for DFS function. If it is not the root we need
665
+ // to simulate the popping of the stack, this we do by setting the
666
+ // current_vertex to be the parent of the child_vertex, we should
667
+ // also increment the edge iterator of the current vertex since in DFS
668
+ // we increment the iterator when the call to child DFS returns. The
669
+ // for loop will start again for the parent. Note: the current_vertex
670
+ // is changing within the loop so the edge iterator for the original
671
+ // current_vertex does not get incremented until and unless edges
672
+ // which cannot be traversed are encountered.
673
+ if (current_vertex != root_vertex) {
674
+ current_vertex = parent[current_vertex];
675
+ _pending_out_edges[current_vertex].first++;
676
+ } else {
677
+ break;
678
+ }
679
+ }
680
+ } // while(true)
681
+ } // if(dfs_color[current_vertex] == DFS_COLOR::WHITE...
682
+ } // for(int current_vertex = 0; ...
683
+
684
+ // We push the excess flow back to the source according to the topological
685
+ // order we found by our search above. topology_next[vertex] == -1 means there
686
+ // is no successor of vertex in topological ordering.
687
+ if (topology_initialized) {
688
+ for (int vertex = topology_start_vertex; vertex >= 0;
689
+ vertex = topology_next[vertex]) {
690
+ edge_iterator eit, eit_end;
691
+ std::tie(eit, eit_end) = outEdges(vertex);
692
+ while ((_vertices[vertex].excess > 0) && (eit != eit_end)) {
693
+ if (eit->getCapacity() == 0 && (eit->residual > 0)) {
694
+ DEBUG_INCREMENT(_num_pushes);
695
+ int to_vertex = eit->to_vertex;
696
+ capacity_t flow = std::min(eit->residual, _vertices[vertex].excess);
697
+ eit->residual -= flow;
698
+ auto eit_reverse = reverseEdgeIterator(eit);
699
+ eit_reverse->residual += flow;
700
+ _vertices[vertex].excess -= flow;
701
+ _vertices[to_vertex].excess += flow;
702
+ }
703
+ eit++;
704
+ }
705
+ }
706
+ }
707
+ } // end convertPreflowToFlow
708
+
709
+ // The top level function to compute max-flow and also convert the preflow to
710
+ // flow so that the resulting graph is a valid flow network.
711
+ template <class EdgeType>
712
+ typename EdgeType::capacity_type
713
+ PushRelabelSolver<EdgeType>::computeMaximumFlow(bool handle_self_loops) {
714
+ capacity_t maximum_flow = computeMaximumPreflow();
715
+ convertPreflowToFlow(handle_self_loops);
716
+ return maximum_flow;
717
+ }
718
+
719
+ // Print the linked lists used to keep track of the active and inactive vertices
720
+ // at different height. The vertices which have height of _num_vertices, or in
721
+ // other words disconnected from the sink are not kept in the linked lists.
722
+ template <class EdgeType> void PushRelabelSolver<EdgeType>::printLevels() {
723
+ std::cout << "Printing Levels. " << _levels.size() << " in total for "
724
+ << _num_vertices << " vertices." << std::endl;
725
+ for (int i = 0; i < _levels.size(); i++) {
726
+ int size_active = _levels[i].active_vertices.size();
727
+ int size_inactive = _levels[i].inactive_vertices.size();
728
+
729
+ if ((size_active == 0) && (size_inactive == 0)) {
730
+ continue;
731
+ }
732
+
733
+ std::cout << std::endl;
734
+ std::cout << "Level " << i << std::endl << std::endl;
735
+ std::cout << "Active list : " << size_active << " vertices" << std::endl;
736
+
737
+ vertex_node_t *vertex_node_ptr = _levels[i].active_vertices.front();
738
+ for (int n = 0; n < size_active; n++) {
739
+ std::cout << vertex_node_ptr->vertex_number << " ";
740
+ vertex_node_ptr = vertex_node_ptr->next;
741
+ }
742
+ std::cout << std::endl;
743
+ std::cout << std::endl;
744
+
745
+ std::cout << "Inactive list : " << size_inactive << " vertices"
746
+ << std::endl;
747
+
748
+ vertex_node_ptr = _levels[i].inactive_vertices.front();
749
+ for (int n = 0; n < size_inactive; n++) {
750
+ std::cout << vertex_node_ptr->vertex_number << " ";
751
+ vertex_node_ptr = vertex_node_ptr->next;
752
+ }
753
+ std::cout << std::endl;
754
+ }
755
+ }
756
+
757
+ // Print the number of basic operations performed in the algorithm.
758
+ template <class EdgeType> void PushRelabelSolver<EdgeType>::printStatistics() {
759
+ #ifdef COLLECT_STATISTICS
760
+ std::cout << std::endl;
761
+ std::cout << "Printing Statistics : " << std::endl << std::endl;
762
+ std::cout << "Number of Pushes : " << _num_pushes << std::endl;
763
+ std::cout << "Number of Relabels : " << _num_relabels << std::endl;
764
+ std::cout << "Number of Global Relabels : " << _num_global_relabels
765
+ << std::endl;
766
+ std::cout << "Number of Gap Relabels : " << _num_gap_relabels << std::endl;
767
+ std::cout << "Number of Gap Vertices : " << _num_gap_vertices << std::endl;
768
+ std::cout << std::endl;
769
+ #else
770
+ std::cout << std::endl;
771
+ std::cout << "Statistics not collected." << std::endl << std::endl;
772
+ #endif
773
+ }
774
+
775
+ #endif // PUSH_RELABEL_INCLUDED