-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.cpp
3489 lines (3048 loc) · 112 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Cut-matching component authored Ludvig Janiuk 2019 as part of individual
// project at KTH. Rest, by me.
#ifdef __clang__
#pragma clang diagnostic push
#pragma ide diagnostic ignored "cert-msc32-c"
#pragma ide diagnostic ignored "cppcoreguidelines-slicing"
#endif
#include <algorithm>
#include <array>
#include <bits/stdc++.h>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <lemon/adaptors.h>
#include <lemon/connectivity.h>
#include <lemon/core.h>
#include <lemon/edge_set.h>
#include <lemon/list_graph.h>
#include <lemon/preflow.h>
#include <memory>
#include <ostream>
#include <random>
#include <set>
#include <sstream>
#include <vector>
#include "cxxopts.hpp"
#include <limits.h>
#include <omp.h>
#include <sched.h>
using namespace lemon;
using namespace std;
using namespace std::chrono;
using G = ListGraph;
using NodeMapd = typename G::template NodeMap<double>;
using Node = typename G::Node;
using NodeIt = typename G::NodeIt;
using Snapshot = typename G::Snapshot;
using Edge = typename G::Edge;
using EdgeIt = typename G::EdgeIt;
using IncEdgeIt = typename G::IncEdgeIt;
using OutArcIt = typename G::OutArcIt;
using Paths = vector<array<Node, 2>>;
using ArcLookup = ArcLookUp<G>;
template <class T>
using EdgeMap = typename G::template EdgeMap<T>;
using EdgeMapi = EdgeMap<int>; // LEMON uses ints internally. We might want to
// look into this
using EdgeMapb = EdgeMap<bool>; // LEMON uses ints internally. We might want to
// look into this
template <class T>
using NodeMap = typename G::template NodeMap<T>;
using NodeMapi = NodeMap<int>;
using NodeMapb = NodeMap<bool>;
using NodeNeighborMap = NodeMap<vector<tuple<Node, int>>>;
using FlowAlgo = Preflow<G, EdgeMapi>;
using Matching = vector<array<Node, 2>>;
using Matchingp = unique_ptr<Matching>;
using Bisection = set<Node>;
using Bisectionp = unique_ptr<Bisection>;
using Cut = set<Node>;
using Cutp = unique_ptr<Cut>;
using CutMap = NodeMap<bool>;
#define MAX_PARALLEL_RECURSIVE_LEVEL 10
#define DEBUG 1
const int NUM_THREADS = 4;
const double MICROSECS = 1000000.0;
const double PHI_UNREACHABLE = 0.00000001;
const double PHI_ACCEPTANCE_TRIMMING = 0.166;
const auto& now = high_resolution_clock::now;
auto
duration_sec(const high_resolution_clock::time_point& start,
high_resolution_clock::time_point& stop) -> double
{
return duration_cast<microseconds>(stop - start).count() / MICROSECS;
}
void warn(bool condition, const string& message, double line) {
if (!condition) {
cout << "WARNING: pre/post condition failed at line " << line << endl;
cout << message << endl;
cout << "" << endl;
}
}
struct InputConfiguration {
bool load_from_file = false;
string file_name = "";
size_t n_nodes_to_generate{};
};
struct Configuration {
InputConfiguration input;
bool compare_partition = false;
string partition_file = "";
bool seed_randomness = false;
int seed{};
int max_rounds{};
bool output_cut{};
string output_file;
bool show_help_and_exit = false;
bool only_test_expander = false;
bool decompose_with_tests = false;
bool use_H_phi_target = false;
double H_phi_target = 0;
bool use_G_phi_target = false;
double G_phi_target = 0;
// we only break if we find a good enough cut that is also this balanced
// (has this minside volume)
bool use_volume_treshold = false;
double known_phi = 0.;
double volume_treshold_factor = 1;
double h_factor = 0;
double h_ratio = 0;
int n_nodes_orig = 0;
int e_edges_orig = 0;
};
struct Logger {
bool silent = false;
bool verbose = false;
ofstream nul; // UNopened file stream, will act like /dev/null
Logger() {};
auto
progress() -> decltype(cout)&
{
return silent ? nul : cout;
};
auto
debug() -> decltype(cout)&
{
return verbose ? cout : nul;
};
} l;
struct GraphContext {
G g;
vector<Node> nodes;
long num_edges{};
map<Node, int> orig_degree;
void
clear()
{
g.clear();
nodes.clear();
num_edges = 0;
orig_degree.clear();
}
};
using GraphContextp = unique_ptr<GraphContext>;
// I'd say implementing our own adaptor is more effort, we can just do the
// snapshot thing Actually lets just subdivide manually at the start and we dont
// even need to restore.
struct SubdividedGraphContext {
explicit SubdividedGraphContext(GraphContext& gc)
: origContext(gc),
nf(sub_g),
ef(sub_g),
n_ref(gc.g, INVALID),
n_cross_ref(sub_g, INVALID),
origs(sub_g, false),
only_splits(sub_g, nf, ef){};
GraphContext& origContext;
G sub_g;
NodeMapb nf;
EdgeMapb ef;
NodeMap<Node> n_ref;
NodeMap<Node> n_cross_ref;
NodeMap<bool> origs;
SubGraph<G> only_splits;
vector<Node> split_vertices;
};
// TODO: What chnages will be necessary?
struct RoundReport {
size_t index{};
size_t capacity_required_for_full_flow{};
double multi_h_conductance{};
double g_conductance{};
long volume{};
bool relatively_balanced{};
Cutp cut;
};
template <class G>
struct CutStats {
using Node = typename G::Node;
using Edge = typename G::Edge;
using Cut = set<Node>;
using EdgeIt = typename G::EdgeIt;
using Bisection = set<Node>;
size_t crossing_edges = 0;
private:
bool is_min_side{};
size_t min_side = 0;
size_t cut_volume = 0;
size_t max_side = 0;
size_t num_edges = 0;
auto
degreesum() -> long
{
return num_edges * 2;
}
auto
noncut_volume() -> long
{
return degreesum() - cut_volume;
}
public:
CutStats(const G& g, size_t num_vertices, const Cut& cut)
{
initialize(g, num_vertices, cut);
}
void
initialize(const G& g, size_t num_vertices, const Cut& cut)
{
cut_volume = 0;
crossing_edges = 0;
for (EdgeIt e(g); e != INVALID; ++e) {
++num_edges;
if (is_crossing(g, cut, e)) {
crossing_edges += 1;
}
// if (any_in_cut(g, cut, e)) cut_volume += 1;
if (cut.count(g.u(e))) {
cut_volume += 1;
}
if (g.u(e) == g.v(e)) {
continue;
}
if (cut.count(g.v(e))) {
cut_volume += 1;
}
}
assert(cut.size() <= num_vertices);
size_t other_size = num_vertices - cut.size();
min_side = min(cut.size(), other_size);
max_side = max(cut.size(), other_size);
is_min_side = cut.size() == min_side;
}
static auto
is_crossing(const G& g, const Bisection& c, const Edge& e) -> bool
{
bool u_in = c.count(g.u(e));
bool v_in = c.count(g.v(e));
return u_in != v_in;
}
static auto
any_in_cut(const G& g, const Bisection& c, const Edge& e) -> bool
{
bool u_in = c.count(g.u(e));
bool v_in = c.count(g.v(e));
return u_in || v_in;
}
auto
minside_volume() -> long
{
return is_min_side ? cut_volume : noncut_volume();
}
auto
maxside_volume() -> long
{
return is_min_side ? noncut_volume() : cut_volume;
}
auto
diff() -> size_t
{
return max_side - min_side;
}
auto
num_vertices() -> size_t
{
return min_side + max_side;
}
auto
imbalance() -> double
{
return diff() * 1. / num_vertices();
}
auto
expansion() -> double
{
return min_side == 0 ? 0 : crossing_edges * 1. / min_side;
}
auto
conductance() -> double
{
// Q: changed to 1
return minside_volume() == 0 ? 1
: crossing_edges * 1. / minside_volume();
}
void
print()
{
cout << "Edge crossings (E) : " << crossing_edges << endl;
cout << "cut size: (" << min_side << " | " << max_side << ")" << endl
<< "diff: " << diff() << " (" << imbalance()
<< " of total n vertices)" << endl;
cout << "Min side: " << min_side << endl;
// cout << "E/min(|S|, |comp(S)|) = " << expansion() << endl;
cout << "expansion: " << expansion() << endl;
cout << "conductance: " << conductance() << endl;
cout << "cut volume: " << cut_volume << endl;
cout << "noncut volume: " << noncut_volume() << endl;
}
};
// Reads the file filename,
// creates that graph in graph g which is assumed to be empty
// In the process fills nodes with each node created at the index of (its id in
// the file minus one) And sets each node's original_ids id to be (its id in the
// file minus one). Of course original_ids must be initialized onto the graph g
// already earlier.
static void
parse_chaco_format(const string& filename, ListGraph& g, vector<Node>& nodes)
{
assert(nodes.empty());
l.progress() << "Reading graph from " << filename << endl;
ifstream file;
file.open(filename);
if (!file) {
cerr << "Unable to read file " << filename << endl;
exit(1);
}
string line;
stringstream ss;
getline(file, line);
ss.str(line);
unsigned long n_verts;
unsigned long n_edges;
ss >> n_verts >> n_edges;
l.progress() << "Reading a graph with V " << n_verts << "E " << n_edges
<< endl;
g.reserveNode(n_verts);
g.reserveNode(n_edges);
for (size_t i = 0; i < n_verts; i++) {
Node n = g.addNode();
nodes.push_back(n);
}
for (size_t i = 0; i < n_verts; i++) {
getline(file, line);
Node u = nodes[i];
istringstream iss(line);
vector<string> tokens{istream_iterator<string>{iss},
istream_iterator<string>{}};
for (string& str : tokens) {
size_t v_name = stoi(str);
// cout << "edge to: " << v_name << "..." ;
assert(v_name != 0);
Node v = nodes[v_name - 1];
// TODO: is this right?
//Ignore multi-edges unless self-loop
//If self loop add multiple times
if (findEdge(g, u, v) == INVALID || u == v) {
g.addEdge(u, v);
}
//if (u == v)
// g.addEdge(v, u);
}
}
/*
if (n_verts % 2 != 0) {
l.progress() << "Odd number of vertices, adding extra one." << endl;
Node n = g.addNode();
g.addEdge(nodes[0], n);
nodes.push_back(n);
}
*/
}
void
generate_large_graph(G& g, vector<Node>& nodes, size_t n_nodes)
{
assert(n_nodes > 0);
nodes.reserve(n_nodes);
for (unsigned long i = 0; i < n_nodes; i++) {
nodes.push_back(g.addNode());
}
g.addEdge(nodes[0], nodes[1]);
g.addEdge(nodes[1], nodes[2]);
g.addEdge(nodes[2], nodes[0]);
unsigned long lim1 = n_nodes / 3;
unsigned long lim2 = 2 * n_nodes / 3;
for (unsigned long i = 3; i < lim1; i++) {
ListGraph::Node u = nodes[i];
ListGraph::Node v = nodes[0];
g.addEdge(u, v);
}
for (unsigned long i = lim1; i < lim2; i++) {
ListGraph::Node u = nodes[i];
ListGraph::Node v = nodes[1];
g.addEdge(u, v);
}
for (unsigned long i = lim2; i < n_nodes; i++) {
ListGraph::Node u = nodes[i];
ListGraph::Node v = nodes[2];
g.addEdge(u, v);
}
}
void
write_cut(const vector<Node>& nodes, const Cut& cut, const string& file_name)
{
ofstream file;
file.open(file_name);
if (!file) {
cout << "Cannot open file " << file_name << endl;
return;
}
cout << "Writing partition with " << nodes.size() << " nodes to file "
<< file_name << endl;
for (const auto& n : nodes) {
file << (cut.count(n) != 0U ? "1" : "0") << "\n";
}
file.close();
}
auto
read_partition_file(const string& filename, const vector<Node>& nodes,
vector<set<Node>> partition) -> vector<set<Node>>
{
ifstream file;
file.open(filename);
if (!file) {
cerr << "Unable to read file " << filename << endl;
exit(1);
}
ifstream is(filename);
string raw_input;
int n;
while( is >> n ) {
int iter = 0;
while(getline(file, raw_input)) {
partition.emplace_back();
istringstream iss(raw_input);
int m;
while (iss >> m) {
cout << m << endl;
partition[iter].insert(nodes[m]);
}
cout << raw_input << endl;
iter++;
}
}
return partition;
}
void
initGraph(GraphContext& gc, const InputConfiguration& config)
{
if (config.load_from_file) {
parse_chaco_format(config.file_name, gc.g, gc.nodes);
}
else {
l.debug() << "Generating graph with " << config.n_nodes_to_generate
<< " nodes." << endl;
generate_large_graph(gc.g, gc.nodes, config.n_nodes_to_generate);
}
for (NodeIt n(gc.g); n != INVALID; ++n) {
for (IncEdgeIt e(gc.g, n); e != INVALID; ++e) {
gc.orig_degree[n] += 1;
}
}
gc.num_edges = countEdges(gc.g);
}
// For some reason lemon returns arbitrary values for flow, the difference is
// correct tho
inline auto
flow(const ArcLookUp<G>& alp, const unique_ptr<Preflow<G, EdgeMapi>>& f, Node u,
Node v) -> int
{
return f->flow(alp(u, v)) - f->flow(alp(v, u));
}
void
print_end_round_message(int i)
{
l.debug() << "======================" << endl;
l.progress() << "== End round " << i << " ==" << endl;
l.debug() << "======================" << endl;
}
template <typename GG>
void
print_matching(GG& g, const Matchingp& m, decltype(cout)& stream)
{
for (auto& e : *m) {
stream << "(" << g.id(e[0]) << ", " << g.id(e[1]) << "), ";
}
stream << endl;
}
void
print_cut(const Bisection& out_cut, decltype(cout)& stream)
{
for (Node n : out_cut) {
stream << G::id(n) << ", ";
}
stream << endl;
}
void
print_graph(G& g, decltype(cout)& stream)
{
stream << "Printing a graph" << endl;
stream << "Vertices: " << countNodes(g) << ", Edges: " << countEdges(g)
<< endl;
stream << "==" << endl;
for (NodeIt n(g); n != INVALID; ++n) {
stream << G::id(n) << ", ";
}
stream << "\n==" << endl;
for (EdgeIt e(g); e != INVALID; ++e) {
stream << G::id(e) << ": " << G::id(g.u(e)) << " - " << G::id(g.v(e))
<< "\n";
}
stream << endl;
}
// Actually copies the graph.
void
createSubdividedGraph(SubdividedGraphContext& sgc)
{
graphCopy(sgc.origContext.g, sgc.sub_g).nodeCrossRef(sgc.n_cross_ref).run();
graphCopy(sgc.origContext.g, sgc.sub_g)
.nodeRef(sgc.n_ref)
.nodeCrossRef(sgc.n_cross_ref)
.run();
G& g = sgc.sub_g;
for (NodeIt n(g); n != INVALID; ++n) {
sgc.origs[n] = true;
}
vector<Edge> edges;
for (EdgeIt e(g); e != INVALID; ++e) {
if (g.u(e) != g.v(e)) {
edges.push_back(e);
}
}
for (NodeIt n(g); n != INVALID; ++n) {
sgc.only_splits.disable(n);
}
for (auto& e : edges) {
if (g.u(e) == g.v(e)) {
continue;
}
Node u = g.u(e);
Node v = g.v(e);
g.erase(e);
Node s = g.addNode();
sgc.origs[s] = false;
sgc.only_splits.enable(s);
g.addEdge(u, s);
if (u != v) {
g.addEdge(s, v);
}
// if (u !=v)
sgc.split_vertices.push_back(s);
}
}
struct CutMatching {
const Configuration& config;
GraphContext& gc;
SubdividedGraphContext sgc;
default_random_engine& random_engine;
// vector<unique_ptr<RoundReport>> sub_past_rounds;
vector<unique_ptr<RoundReport>> sub_past_rounds;
vector<Matchingp> matchings;
vector<Matchingp> sub_matchings;
bool reached_H_target = false;
// Input graph
CutMatching(GraphContext& gc, const Configuration& config_,
default_random_engine& random_engine_)
: config(config_), gc(gc), sgc{gc}, random_engine(random_engine_)
{
assert(static_cast<int>(gc.nodes.size()) % 2 == 0);
assert(!gc.nodes.empty()) ;
assert(connected(gc.g));
createSubdividedGraph(sgc);
};
// During the matching step a lot of local setup is actually made, so it
// makes sense to group it inside a "matching context" that exists for the
// duration of the mathing step
struct MatchingContext {
// This NEEDS to be the whole graph
G& g;
Node s;
Node t;
EdgeMapi capacity;
CutMap cut_map;
Snapshot snap; // RAII
explicit MatchingContext(G& g_)
: g(g_), capacity(g_), cut_map(g_), snap(g_)
{
}
~MatchingContext() { snap.restore(); }
auto
touches_source_or_sink(Edge& e) -> bool
{
return g.u(e) == s || g.v(e) == s || g.u(e) == t || g.v(e) == t;
}
// Fills given cut pointer with a copy of the cut map
auto
extract_cut() -> Cutp
{
Cutp cut(new Cut);
for (NodeIt n(g); n != INVALID; ++n) {
if (n == s || n == t) {
continue;
}
if (cut_map[n]) {
cut->insert(n);
}
}
return cut;
}
void
reset_cut_map()
{
for (NodeIt n(g); n != INVALID; ++n) {
cut_map[n] = false;
}
}
};
struct MatchResult {
Cutp cut_from_flow;
size_t capacity; // First capacity (minumum) that worked to get full
// flow thru
};
static inline void
extract_path_fast(const G& /*g*/, const unique_ptr<Preflow<G, EdgeMapi>>& /*f*/,
NodeNeighborMap& flow_children, Node u_orig,
Node t, // For assertsions
array<Node, 2>& out_path)
{
out_path[0] = u_orig;
Node u = u_orig;
int i = 0;
while (true) {
i++;
auto& vv = flow_children[u];
assert(!vv.empty());
auto& tup = vv.back();
Node v = get<0>(tup);
--get<1>(tup);
if (get<1>(tup) == 0) {
flow_children[u].pop_back();
}
if (flow_children[v].empty()) {
assert(v == t);
assert(u != u_orig);
out_path[1] = u;
break;
}
u = v;
}
}
void
decompose_paths_fast(const MatchingContext& mg,
const unique_ptr<FlowAlgo>& f, Paths& out_paths)
{
f->startSecondPhase();
EdgeMapi subtr(mg.g, 0);
NodeNeighborMap flow_children(mg.g, vector<tuple<Node, int>>());
out_paths.reserve(countNodes(mg.g) / 2);
// Calc flow children (one pass)
ArcLookup alp(mg.g);
for (EdgeIt e(mg.g); e != INVALID; ++e) {
if (mg.g.u(e) == mg.g.v(e)) {
continue;
}
Node u = mg.g.u(e);
Node v = mg.g.v(e);
long e_flow = flow(alp, f, u, v);
if (e_flow > 0) {
flow_children[u].push_back(tuple(v, e_flow));
}
else if (e_flow < 0) {
flow_children[v].push_back(tuple(u, -e_flow));
}
}
for (IncEdgeIt e(mg.g, mg.s); e != INVALID; ++e) {
if (mg.g.u(e) == mg.g.v(e)) {
continue;
}
assert(mg.g.u(e) == mg.s || mg.g.v(e) == mg.s);
Node u = mg.g.u(e) == mg.s ? mg.g.v(e) : mg.g.u(e);
out_paths.push_back(array<Node, 2>());
extract_path_fast(mg.g, f, flow_children, u, mg.t,
out_paths[out_paths.size() - 1]);
}
}
// Works for sub too, with the assumption that mg.g realy is the whole graph
static void
run_min_cut(const MatchingContext& mg, unique_ptr<FlowAlgo>& p)
{
p = std::make_unique<Preflow<G, EdgeMapi>>(mg.g, mg.capacity, mg.s, mg.t);
auto start2 = now();
p->runMinCut(); // Note that "startSecondPhase" must be run to get
// flows for individual verts
auto stop2 = now();
l.progress() << "flow: " << p->flowValue() << " ("
<< duration_sec(start2, stop2) << " s)" << endl;
}
// This should work well for sub too
static void
set_matching_capacities(MatchingContext& mg, size_t cap)
{
for (EdgeIt e(mg.g); e != INVALID; ++e) {
if (mg.touches_source_or_sink(e)) {
continue;
}
mg.capacity[e] = cap;
}
}
auto
bin_search_flows(MatchingContext& mg, unique_ptr<FlowAlgo>& p,
unsigned long flow_target) const -> MatchResult
{
auto start = now();
unsigned long cap = 1;
// for (; cap < mg.static_cast<int>(gc.nodes.size()); cap *= 2) {
for (; cap < flow_target * 2; cap *= 2) {
l.progress() << "Cap " << cap << " ... " << flush;
set_matching_capacities(mg, cap);
run_min_cut(mg, p);
// bool reachedFullFlow = p->flowValue() == mg.static_cast<int>(gc.nodes.size()) / 2;
bool reachedFullFlow = static_cast<unsigned long>(p->flowValue()) >= flow_target;
if (reachedFullFlow) {
l.debug()
<< "We have achieved full flow, but half this capacity "
"didn't manage that!"
<< endl;
}
// So it will always have the mincutmap of "before"
// mincuptmap is recomputed too many times of course but whatever
// If we reached it with cap 1, already an expander I guess?
// In this case this was never done even once, so we have to do it
// before breaking
if (!reachedFullFlow || cap == 1) {
mg.reset_cut_map();
p->minCutMap(mg.cut_map);
}
if (reachedFullFlow) {
break;
}
}
// Not we copy out the cut
MatchResult result{mg.extract_cut(), cap};
auto stop = now();
l.progress() << "Flow search took (seconds) "
<< duration_sec(start, stop) << endl;
return result;
}
void
decompose_paths(const MatchingContext& mg, const unique_ptr<FlowAlgo>& p,
vector<array<Node, 2>>& paths)
{
decompose_paths_fast(mg, p, paths);
}
template <typename GG>
void
make_sink_source(GG& g, MatchingContext& mg, const set<Node>& cut) const
{
mg.s = g.addNode();
mg.t = g.addNode();
int s_added = 0;
int t_added = 0;
for (typename GG::NodeIt n(g); n != INVALID; ++n) {
if (n == mg.s) {
continue;
}
if (n == mg.t) {
continue;
}
Edge e;
if (cut.count(n)) {
e = g.addEdge(mg.s, n);
s_added++;
}
else {
e = g.addEdge(n, mg.t);
t_added++;
}
mg.capacity[e] = 1;
}
int diff = s_added - t_added;
assert(-1 <= diff && diff <= 1);
}
// Actually, cut player gets H
// Actually Actually, sure it gets H but it just needs the matchings...
// TODO: Ok so can we just call this with split_only and matchings of those?
template <typename GG, typename M>
auto
cut_player(const GG& g, const vector<unique_ptr<M>>& given_matchings,
double& h_multi_cond_out) -> Bisectionp
{
l.debug() << "Running Cut player" << endl;
typename GG::template NodeMap<double> probs(g);
vector<Node> all_nodes;
// uniform_int_distribution<int> uniform_dist(0, 1);
for (typename GG::NodeIt n(g); n != INVALID; ++n) {
all_nodes.push_back(n);
}
uniform_int_distribution<int> uniform_dist(0, 1);
for (typename GG::NodeIt n(g); n != INVALID; ++n) {
probs[n] = uniform_dist(random_engine) ? 1.0 / all_nodes.size()
: -1.0 / all_nodes.size();
}
size_t num_vertices = all_nodes.size();
ListEdgeSet H(g);
ListEdgeSet H_single(g);
for (const unique_ptr<M>& m : given_matchings) {
for (auto& e : *m) {
Node u = e[0];
Node v = e[1];
double avg = probs[u] / 2 + probs[v] / 2;
probs[u] = avg;
probs[v] = avg;
H.addEdge(u, v);
// Updating H_single
if (findEdge(H_single, u, v) == INVALID) {
assert(findEdge(H_single, v, u) == INVALID);
H_single.addEdge(u, v);
}
}
}
shuffle(all_nodes.begin(), all_nodes.end(), random_engine);
sort(all_nodes.begin(), all_nodes.end(),
[&](Node a, Node b) { return probs[a] < probs[b]; });
size_t size = all_nodes.size();
// With subdivisions, won't be this way longer
// assert(size % 2 == 0);
all_nodes.resize(size / 2);
auto b = std::make_unique<Bisection>(all_nodes.begin(), all_nodes.end());
l.debug() << "Cut player gave the following cut: " << endl;
print_cut(*b, l.debug());
// So how does it give output?
// Ok it assigns h_outs, but actually also returns Bisectionp
auto hcs = CutStats<decltype(H)>(H, num_vertices, *b);
l.progress() << "H conductance: " << hcs.conductance()
<< ", num cross: " << hcs.crossing_edges << endl;
h_multi_cond_out = hcs.conductance();
auto hscs = CutStats<decltype(H_single)>(H_single, num_vertices, *b);
l.progress() << "H_single conductance: " << hscs.conductance()
<< ", num cross: " << hscs.crossing_edges << endl;
return b;
}
// returns capacity that was required
// Maybe: make the binsearch an actual binsearch
// TODO: Let listedgeset just be 2-arrays of nodes. Lemon is getting in the
// way too much. But also what is assigned in MtchResult?
auto
matching_player(const set<Node>& bisection, Matching& m_out) -> MatchResult
{
MatchingContext mg(gc.g);
make_sink_source(mg.g, mg, bisection);
unique_ptr<FlowAlgo> p;
MatchResult mr = bin_search_flows(mg, p, static_cast<int>(gc.nodes.size()) / 2);
decompose_paths(mg, p, m_out);
// Now how do we extract the cut?
// In this version, in one run of the matching the cut is strictly
// decided. We just need to decide which one of them. Only when we
// change to edge will the cut need to be explicitly extracted. Rn the
// important thing is to save cuts between rounds so I can choose the
// best.
return mr;
}
// returns capacity that was required
// Maybe: make the binsearch an actual binsearch
// TODO: Let listedgeset just be 2-arrays of nodes. Lemon is getting in the
// way too much. But also what is assigned in MtchResult?
auto
sub_matching_player(const set<Node>& bisection,
vector<array<Node, 2>>& m_out) -> MatchResult
{
MatchingContext mg(sgc.sub_g);
make_sink_source(sgc.only_splits, mg, bisection);
// TODO: so have s, t been created on the big graph?
// cout << id << endl;
// cout << countNodes(sgc.sub_g) << endl;
unique_ptr<FlowAlgo> p;
MatchResult mr = bin_search_flows(mg, p, sgc.split_vertices.size() / 2);
decompose_paths(mg, p, m_out);
// Now how do we extract the cut?
// In this version, in one run of the matching the cut is strictly
// decided. We just need to decide which one of them. Only when we
// change to edge will the cut need to be explicitly extracted. Rn the
// important thing is to save cuts between rounds so I can choose the
// best.
return mr;
}
auto
volume_treshold() -> long
{
return config.volume_treshold_factor * gc.num_edges;
}
// IS this right?
auto
sub_volume_treshold() -> long
{
// return config.volume_treshold_factor * sgc.origContext.nodes.size();
if (config.h_ratio > 0) {
return sgc.origContext.num_edges * config.h_ratio;
} {
return (double(sgc.origContext.num_edges) /
(10. * config.volume_treshold_factor *
pow(log(sgc.origContext.num_edges), 2)));
}