Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 222
Expand file tree
/
Copy pathcuts.cpp
More file actions
Latest commit
6736 lines (6115 loc) · 256 KB
/
Copy pathcuts.cpp
File metadata and controls
6736 lines (6115 loc) · 256 KB
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
/* clang-format off */
/*
* SPDX-FileCopyrightText: Copyright (c) 2025-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
/* clang-format on */
#include<cuts/cuts.hpp>
#include<cuts/rational.hpp>
#include<dual_simplex/basis_solves.hpp>
#include<math_optimization/tic_toc.hpp>
#include<mip_heuristics/presolve/conflict_graph/clique_table.cuh>
#include<utilities/logger.hpp>
#include<utilities/macros.cuh>
#include<array>
#include<cstdint>
#include<cstdio>
#include<cstdlib>
#include<limits>
#include<stdexcept>
#include<tuple>
#include<unordered_set>
#include<linear_algebra/dense_matrix.hpp>
#include<numeric>
#include<queue>
namespacecuopt::mathematical_optimization::mip {
using simplex::basis_update_mpf_t;
using simplex::form_b;
using simplex::lp_problem_t;
using simplex::lp_solution_t;
using simplex::simplex_solver_settings_t;
using simplex::variable_status_t;
using simplex::variable_type_t;
namespace {
#defineDEBUG_CLIQUE_CUTS0
#defineDEBUG_ZERO_HALF_CUTS0
#defineCHECK_WORKSPACE0
enumclassclique_cut_build_status_t : int8_t { NO_CUT = 0, CUT_ADDED = 1, INFEASIBLE = 2 };
// Shared crash-tolerant debug logger: writes a prefixed line to stderr and
// flushes immediately so the last line is visible even if the process
// aborts/terminates right after. Each channel below enables it through its own
// DEBUG_* flag and supplies its own prefix; when the flag is 0 the call expands
// to a no-op that still consumes its arguments.
#defineCUTS_DEBUG_LOG(prefix, ...) \
do { \
std::fprintf(stderr, prefix ""); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
std::fflush(stderr); \
} while (0)
#defineCUTS_DEBUG_NOOP(...) \
do { \
} while (0)
#if DEBUG_CLIQUE_CUTS
#defineCLIQUE_CUTS_DEBUG(...) CUTS_DEBUG_LOG("[DEBUG_CLIQUE_CUTS]", __VA_ARGS__)
#else
#defineCLIQUE_CUTS_DEBUG(...) CUTS_DEBUG_NOOP(__VA_ARGS__)
#endif
#if DEBUG_ZERO_HALF_CUTS
#defineZERO_HALF_DEBUG(...) CUTS_DEBUG_LOG("[zero_half]", __VA_ARGS__)
#else
#defineZERO_HALF_DEBUG(...) CUTS_DEBUG_NOOP(__VA_ARGS__)
#endif
template <typenamei_t, typenamef_t>
clique_cut_build_status_tbuild_clique_cut(const std::vector<i_t>& clique_vertices,
i_t num_vars,
const std::vector<variable_type_t>& var_types,
[[maybe_unused]]const std::vector<f_t>& lower_bounds,
[[maybe_unused]]const std::vector<f_t>& upper_bounds,
const std::vector<f_t>& xstar,
f_t bound_tol,
f_t min_violation,
sparse_vector_t<i_t, f_t>& cut,
f_t& cut_rhs,
f_t* work_estimate,
f_t max_work_estimate)
{
if (clique_vertices.size() < 2) { returnclique_cut_build_status_t::NO_CUT; }
constf_t clique_size = static_cast<f_t>(clique_vertices.size());
CLIQUE_CUTS_DEBUG("build_clique_cut start clique_size=%lld",
static_cast<longlong>(clique_vertices.size()));
constf_t sort_work = clique_size > 0.0 ? 2.0 * clique_size * std::log2(clique_size + 1.0) : 0.0;
constf_t dot_work = 2.0 * clique_size;
constf_t estimated_work = 9.0 * clique_size + sort_work + dot_work;
if (add_work_estimate(estimated_work, work_estimate, max_work_estimate)) {
CLIQUE_CUTS_DEBUG("build_clique_cut skip work_limit clique_size=%lld work=%g limit=%g",
static_cast<longlong>(clique_vertices.size()),
work_estimate == nullptr ? -1.0 : static_cast<double>(*work_estimate),
static_cast<double>(max_work_estimate));
returnclique_cut_build_status_t::NO_CUT;
}
cuopt_assert(num_vars > 0, "Clique cut num_vars must be positive");
cuopt_assert(static_cast<size_t>(num_vars) <= lower_bounds.size(),
"Clique cut lower bounds size mismatch");
cuopt_assert(static_cast<size_t>(num_vars) <= xstar.size(), "Clique cut xstar size mismatch");
cut.i.clear();
cut.x.clear();
// First pass: collect literal/complement occurrences per variable and the
// set of variables that appear both as themselves and as their complement
// in the clique. Bounds / var_type sanity checks are folded in here so we
// touch each clique vertex once.
std::unordered_set<i_t> seen_original;
std::unordered_set<i_t> seen_complement;
std::unordered_set<i_t> complement_pairs;
seen_original.reserve(clique_vertices.size());
seen_complement.reserve(clique_vertices.size());
for (consti_t vertex_idx : clique_vertices) {
cuopt_assert(vertex_idx >= 0 && vertex_idx < 2 * num_vars, "Clique vertex out of range");
consti_t var_idx = vertex_idx % num_vars;
constbool complement = vertex_idx >= num_vars;
[[maybe_unused]]constf_t lower_bound = lower_bounds[var_idx];
[[maybe_unused]]constf_t upper_bound = upper_bounds[var_idx];
cuopt_assert(var_types[var_idx] != variable_type_t::CONTINUOUS,
"Clique contains continuous variable");
cuopt_assert(lower_bound >= -bound_tol, "Clique variable lower bound below zero");
cuopt_assert(upper_bound <= 1 + bound_tol, "Clique variable upper bound above one");
if (complement) {
cuopt_assert(seen_complement.count(var_idx) == 0, "Duplicate complement in clique");
if (seen_original.count(var_idx) > 0) { complement_pairs.insert(var_idx); }
seen_complement.insert(var_idx);
} else {
cuopt_assert(seen_original.count(var_idx) == 0, "Duplicate variable in clique");
if (seen_complement.count(var_idx) > 0) { complement_pairs.insert(var_idx); }
seen_original.insert(var_idx);
}
}
// >= 2 complement pairs force two distinct variables each into
// {0} \cap {1} simultaneously => node is LP-infeasible. The caller is
// expected to short-circuit the rest of cut generation on INFEASIBLE.
if (complement_pairs.size() >= 2) {
CLIQUE_CUTS_DEBUG("build_clique_cut infeasible: %lld complement-pairs",
static_cast<longlong>(complement_pairs.size()));
returnclique_cut_build_status_t::INFEASIBLE;
}
// Exactly one complement pair (x + (1-x) = 1) contributes nothing to the
// sum but forces every other clique member to 0. We drop the paired
// variable from the support and bump rhs by 1, producing a fixing cut.
constbool has_pair = complement_pairs.size() == 1;
i_t num_complements = 0;
for (consti_t vertex_idx : clique_vertices) {
consti_t var_idx = vertex_idx % num_vars;
constbool complement = vertex_idx >= num_vars;
if (has_pair && complement_pairs.count(var_idx) > 0) { continue; }
cut.i.push_back(var_idx);
cut.x.push_back(complement ? static_cast<f_t>(1.0) : static_cast<f_t>(-1.0));
if (complement) { num_complements++; }
}
if (cut.i.empty()) {
CLIQUE_CUTS_DEBUG("build_clique_cut no_cut empty support");
returnclique_cut_build_status_t::NO_CUT;
}
cut_rhs = has_pair ? static_cast<f_t>(num_complements) : static_cast<f_t>(num_complements - 1);
cut.sort();
constf_t dot = cut.dot(xstar);
constf_t violation = cut_rhs - dot;
if (violation > min_violation) {
CLIQUE_CUTS_DEBUG(
"build_clique_cut accepted has_pair=%d nz=%lld rhs=%g dot=%g violation=%g threshold=%g "
"complements=%lld",
has_pair ? 1 : 0,
static_cast<longlong>(cut.i.size()),
static_cast<double>(cut_rhs),
static_cast<double>(dot),
static_cast<double>(violation),
static_cast<double>(min_violation),
static_cast<longlong>(num_complements));
returnclique_cut_build_status_t::CUT_ADDED;
}
CLIQUE_CUTS_DEBUG(
"build_clique_cut rejected has_pair=%d nz=%lld rhs=%g dot=%g violation=%g threshold=%g "
"complements=%lld",
has_pair ? 1 : 0,
static_cast<longlong>(cut.i.size()),
static_cast<double>(cut_rhs),
static_cast<double>(dot),
static_cast<double>(violation),
static_cast<double>(min_violation),
static_cast<longlong>(num_complements));
returnclique_cut_build_status_t::NO_CUT;
}
template <typenamei_t, typenamef_t>
structbk_bitset_context_t {
const std::vector<std::vector<uint64_t>>& adj;
const std::vector<f_t>& weights;
f_t min_weight;
i_t max_calls;
f_t start_time;
f_t time_limit;
size_t words;
f_t* work_estimate;
f_t max_work_estimate;
i_t num_calls{0};
bool work_limit_reached{false};
bool call_limit_reached{false};
std::vector<std::vector<i_t>> cliques;
booladd_work(f_t accesses)
{
returnadd_work_estimate(accesses, work_estimate, max_work_estimate, &work_limit_reached);
}
boolover_work_limit() const
{
if (work_limit_reached) { returntrue; }
if (work_estimate == nullptr) { returnfalse; }
return *work_estimate > max_work_estimate;
}
boolover_call_limit() const { return call_limit_reached || num_calls >= max_calls; }
};
inlinesize_tbitset_words(size_t n) { return (n + 63) / 64; }
inlineboolbitset_any(const std::vector<uint64_t>& bs)
{
for (constuint64_t word : bs) {
if (word != 0) { returntrue; }
}
returnfalse;
}
inlinevoidbitset_set(std::vector<uint64_t>& bs, size_t idx)
{
bs[idx >> 6] |= (uint64_t(1) << (idx & 63));
}
inlinevoidbitset_clear(std::vector<uint64_t>& bs, size_t idx)
{
bs[idx >> 6] &= ~(uint64_t(1) << (idx & 63));
}
template <typenamei_t, typenamef_t>
f_tsum_weights_bitset(const std::vector<uint64_t>& bs, const std::vector<f_t>& weights)
{
f_t sum = 0.0;
for (size_t w = 0; w < bs.size(); ++w) {
uint64_t word = bs[w];
while (word) {
constint bit = __builtin_ctzll(word);
constsize_t idx = w * 64 + static_cast<size_t>(bit);
sum += weights[idx];
word &= (word - 1);
}
}
return sum;
}
template <typenamei_t, typenamef_t>
voidbron_kerbosch(bk_bitset_context_t<i_t, f_t>& ctx,
std::vector<i_t>& R, // current clique
std::vector<uint64_t>& P, // potential candidates
std::vector<uint64_t>& X, // already in the clique
f_t weight_R)
{
if (ctx.over_work_limit() || ctx.over_call_limit()) { return; }
if (toc(ctx.start_time) >= ctx.time_limit) { return; }
ctx.num_calls++;
// stop the recursion, for perf reasons
if (ctx.num_calls > ctx.max_calls) {
ctx.call_limit_reached = true;
return;
}
if (ctx.add_work(static_cast<f_t>(4 * ctx.words))) { return; }
// if P and X are empty, we are at maximal clique
if (!bitset_any(P) && !bitset_any(X)) {
// if the weight is enough, add and exit
if (weight_R >= ctx.min_weight) {
ctx.add_work(static_cast<f_t>(R.size()));
ctx.cliques.push_back(R);
}
return;
}
constf_t sumP = sum_weights_bitset<i_t, f_t>(P, ctx.weights);
// check if all P is added to clique, would we exceed the weight?
if (weight_R + sumP < ctx.min_weight) { return; }
i_t pivot = -1;
i_t max_deg = -1;
i_t pivot_vertices_examined = 0;
// pivoting rule according to the highest degree vertex
// TODO try other pivoting strategies, we can also implement some online learning like MAB
for (size_t w = 0; w < ctx.words; ++w) {
// union of P and X
uint64_t word = P[w] | X[w];
while (word) {
pivot_vertices_examined++;
// least significant set bit idnex
constint bit = __builtin_ctzll(word);
// overall vertex index
consti_t v = static_cast<i_t>(w * 64 + static_cast<size_t>(bit));
// clear the least significant set bit (v)
word &= (word - 1);
i_t count = 0;
// count the number of neighbors of v in P
for (size_t k = 0; k < ctx.words; ++k) {
count += __builtin_popcountll(P[k] & ctx.adj[v][k]);
}
// chose the highest degree v as the pivot
// we choose the highest degree as the pivot to reduce the recursion size
// later in this function we recurse on the candidate P / N(v)
// so it is good to maximize P n N(v)
if (count > max_deg) {
max_deg = count;
pivot = v;
}
}
}
ctx.add_work(static_cast<f_t>(2 * ctx.words) +
static_cast<f_t>(pivot_vertices_examined) * static_cast<f_t>(2 * ctx.words));
std::vector<i_t> candidates;
candidates.reserve(ctx.weights.size());
cuopt_assert(pivot >= 0, "Pivot must be valid when P or X is non-empty");
for (size_t w = 0; w < ctx.words; ++w) {
// P / N(pivot)
uint64_t word = P[w] & ~ctx.adj[pivot][w];
while (word) {
constint bit = __builtin_ctzll(word);
consti_t v = static_cast<i_t>(w * 64 + static_cast<size_t>(bit));
word &= (word - 1);
candidates.push_back(v);
}
}
consti_t num_candidates = static_cast<i_t>(candidates.size());
ctx.add_work(static_cast<f_t>(2 * ctx.words + num_candidates));
ctx.add_work(static_cast<f_t>(num_candidates) * static_cast<f_t>(7 * ctx.words + 6));
// note that candidates will include pivot if it is in P
for (consti_t v : candidates) {
if (ctx.over_call_limit()) {
ctx.call_limit_reached = true;
return;
}
if (toc(ctx.start_time) >= ctx.time_limit) { return; }
R.push_back(v);
std::vector<uint64_t> P_next(ctx.words, 0);
std::vector<uint64_t> X_next(ctx.words, 0);
for (size_t k = 0; k < ctx.words; ++k) {
P_next[k] = P[k] & ctx.adj[v][k];
X_next[k] = X[k] & ctx.adj[v][k];
}
bron_kerbosch(ctx, R, P_next, X_next, weight_R + ctx.weights[v]);
if (ctx.over_work_limit()) { return; }
if (ctx.over_call_limit()) {
ctx.call_limit_reached = true;
return;
}
R.pop_back();
bitset_clear(P, static_cast<size_t>(v));
bitset_set(X, static_cast<size_t>(v));
}
}
// ---- Shared helpers for greedy CG-based set extension (clique & odd-wheel) ----
// Pick the seed vertex with the smallest conflict-graph degree. Returns -1 if
// the seed is empty or the time limit is hit while scanning.
template <typenamei_t, typenamef_t>
i_tmin_degree_anchor(const std::vector<i_t>& seed,
mip::clique_table_t<i_t, f_t>& graph,
f_t start_time,
f_t time_limit)
{
i_t smallest_degree = std::numeric_limits<i_t>::max();
i_t smallest_degree_var = -1;
for (consti_t v : seed) {
if (toc(start_time) >= time_limit) { return -1; }
i_t degree = graph.get_degree_of_var(v);
if (degree < smallest_degree) {
smallest_degree = degree;
smallest_degree_var = v;
}
}
return smallest_degree_var;
}
// Reduced-cost key for a CG vertex. A complement vertex (idx >= num_vars) maps
// to the original variable and flips the sign. Sorting candidates by this key
// keeps xstar minimally disturbed so the resulting cut stays binding and the
// dual simplex resolve stays cheap.
template <typenamei_t, typenamef_t>
f_tcg_reduced_cost(i_t vertex_idx, const std::vector<f_t>& reduced_costs, i_t num_vars)
{
i_t var_idx = vertex_idx % num_vars;
cuopt_assert(var_idx >= 0 && var_idx < static_cast<i_t>(reduced_costs.size()),
"Reduced cost index out of range");
f_t rc = reduced_costs[var_idx];
if (!std::isfinite(rc)) { rc = 0.0; }
return vertex_idx >= num_vars ? -rc : rc;
}
template <typenamei_t, typenamef_t>
voidsort_candidates_by_reduced_cost(std::vector<i_t>& candidates,
const std::vector<f_t>& reduced_costs,
i_t num_vars)
{
std::sort(candidates.begin(), candidates.end(), [&](i_t a, i_t b) {
returncg_reduced_cost(a, reduced_costs, num_vars) <
cg_reduced_cost(b, reduced_costs, num_vars);
});
}
// Greedily grow `selected` by appending candidates (assumed already ordered by
// reduced cost) that are adjacent to every current member of `selected`. The
// resulting `selected` is therefore a clique. Stops early when the time or work
// budget is exhausted.
template <typenamei_t, typenamef_t>
voidgreedy_extend_clique(std::vector<i_t>& selected,
const std::vector<i_t>& candidates,
mip::clique_table_t<i_t, f_t>& graph,
f_t adj_check_cost,
f_t start_time,
f_t time_limit,
f_t* work_estimate,
f_t max_work_estimate)
{
for (consti_t candidate : candidates) {
if (toc(start_time) >= time_limit) { return; }
bool add = true;
i_t checks = 0;
for (consti_t v : selected) {
checks++;
if (!graph.check_adjacency(candidate, v)) {
add = false;
break;
}
}
if (add_work_estimate(adj_check_cost * checks, work_estimate, max_work_estimate)) { break; }
if (add) { selected.push_back(candidate); }
}
}
template <typenamei_t, typenamef_t>
voidextend_clique_vertices(std::vector<i_t>& clique_vertices,
mip::clique_table_t<i_t, f_t>& graph,
const std::vector<f_t>& xstar,
const std::vector<f_t>& reduced_costs,
i_t num_vars,
f_t integer_tol,
f_t start_time,
f_t time_limit,
f_t* work_estimate,
f_t max_work_estimate)
{
if (toc(start_time) >= time_limit) { return; }
if (clique_vertices.empty()) { return; }
#if DEBUG_CLIQUE_CUTS
constsize_t initial_clique_vertices = clique_vertices.size();
#endif
CLIQUE_CUTS_DEBUG("extend_clique_vertices start size=%lld",
static_cast<longlong>(clique_vertices.size()));
constf_t initial_clique_size = static_cast<f_t>(clique_vertices.size());
consti_t smallest_degree_var = min_degree_anchor(clique_vertices, graph, start_time, time_limit);
if (smallest_degree_var < 0) { return; }
std::unordered_set<i_t> adj_set = graph.get_adj_set_of_var(smallest_degree_var);
std::unordered_set<i_t> clique_members(clique_vertices.begin(), clique_vertices.end());
std::vector<i_t> candidates;
candidates.reserve(adj_set.size());
// the candidate list if only the integer valued vertices
for (consti_t& candidate : adj_set) {
if (toc(start_time) >= time_limit) { return; }
if (clique_members.count(candidate) != 0) { continue; }
i_t var_idx = candidate % num_vars;
f_t value = candidate >= num_vars ? (1.0 - xstar[var_idx]) : xstar[var_idx];
if (std::abs(value - std::round(value)) <= integer_tol) { candidates.push_back(candidate); }
}
CLIQUE_CUTS_DEBUG("extend_clique_vertices anchor=%lld adj_size=%lld integer_candidates=%lld",
static_cast<longlong>(smallest_degree_var),
static_cast<longlong>(adj_set.size()),
static_cast<longlong>(candidates.size()));
constf_t candidate_size = static_cast<f_t>(candidates.size());
constf_t sort_work =
candidate_size > 0.0 ? 2.0 * candidate_size * std::log2(candidate_size + 1.0) : 0.0;
constf_t adj_set_build_cost = 2.0 * static_cast<f_t>(adj_set.size());
constf_t addtl_cliques_scan_cost =
1.0 + static_cast<f_t>(graph.var_clique_addtl.avg_slice_size());
constf_t adj_check_cost = 5.0 + addtl_cliques_scan_cost;
constf_t estimated_preloop_work =
2.0 * initial_clique_size + adj_set_build_cost + 3.0 * static_cast<f_t>(adj_set.size()) +
sort_work + 2.0 * candidate_size + addtl_cliques_scan_cost * initial_clique_size +
addtl_cliques_scan_cost;
if (add_work_estimate(estimated_preloop_work, work_estimate, max_work_estimate)) {
CLIQUE_CUTS_DEBUG("extend_clique_vertices skip work_limit work=%g limit=%g",
work_estimate == nullptr ? -1.0 : static_cast<double>(*work_estimate),
static_cast<double>(max_work_estimate));
return;
}
// sort the candidates by reduced cost.
// smaller reduce cost disturbs dual simplex less
// less refactors and less iterations after resolve.
// it also increases the cut's effectiveness by keeping xstar not disturbed much
// if it is disturbed too much, the cut might become non-binding
sort_candidates_by_reduced_cost(candidates, reduced_costs, num_vars);
// adj_check_cost folds in addtl_cliques_scan_cost so each check_adjacency
// charges its own addtl scan cost as the clique grows.
greedy_extend_clique(clique_vertices,
candidates,
graph,
adj_check_cost,
start_time,
time_limit,
work_estimate,
max_work_estimate);
CLIQUE_CUTS_DEBUG("extend_clique_vertices done start=%lld final=%lld added=%lld",
static_cast<longlong>(initial_clique_vertices),
static_cast<longlong>(clique_vertices.size()),
static_cast<longlong>(clique_vertices.size() - initial_clique_vertices));
}
// Build a zero-half (odd-cycle / odd-wheel) cut from a cycle and optional wheel
// centers. cycle_vertices is a simple odd cycle in the conflict graph using the
// 2*num_vars vertex indexing (var j and complement j+num_vars). wheel_centers
// are extra vertices each adjacent to every vertex in cycle_vertices. The
// resulting cut is stored in the form a^T x >= rhs to match cut_pool_t.
template <typenamei_t, typenamef_t>
clique_cut_build_status_tbuild_zero_half_cut(const std::vector<i_t>& cycle_vertices,
const std::vector<i_t>& wheel_centers,
i_t num_vars,
const std::vector<variable_type_t>& var_types,
const std::vector<f_t>& lower_bounds,
const std::vector<f_t>& upper_bounds,
const std::vector<f_t>& xstar,
f_t bound_tol,
f_t min_violation,
sparse_vector_t<i_t, f_t>& cut,
f_t& cut_rhs,
f_t* work_estimate,
f_t max_work_estimate)
{
constsize_t cycle_size = cycle_vertices.size();
if (cycle_size < 5 || (cycle_size % 2) == 0) {
ZERO_HALF_DEBUG("build_zero_half_cut reject cycle_size=%zu", cycle_size);
returnclique_cut_build_status_t::NO_CUT;
}
cuopt_assert(num_vars > 0, "Zero-half cut num_vars must be positive");
cuopt_assert(static_cast<size_t>(num_vars) <= lower_bounds.size(),
"Zero-half cut lower bounds size mismatch");
cuopt_assert(static_cast<size_t>(num_vars) <= xstar.size(), "Zero-half cut xstar size mismatch");
consti_t m = static_cast<i_t>((cycle_size - 1) / 2);
constf_t f_m = static_cast<f_t>(m);
// The guard above rejects even or <5 cycles, so the cycle decomposes as
// exactly 2m+1 literals with m >= 2. The whole zero-half lift (rhs = -m,
// unit cycle coefficients, m-weighted wheel centers) depends on this.
cuopt_assert(2 * m + 1 == static_cast<i_t>(cycle_size),
"Zero-half cut: cycle_size must equal 2m+1 (odd cycle)");
cuopt_assert(m >= 2, "Zero-half cut: odd cycle must have length >= 5 (m >= 2)");
constf_t total_size = static_cast<f_t>(cycle_size + wheel_centers.size());
constf_t estimated_work = 8.0 * total_size + 2.0 * total_size * std::log2(total_size + 1.0);
if (add_work_estimate(estimated_work, work_estimate, max_work_estimate)) {
ZERO_HALF_DEBUG("build_zero_half_cut work_limit hit");
returnclique_cut_build_status_t::NO_CUT;
}
cut.i.clear();
cut.x.clear();
std::unordered_map<i_t, f_t> coeff_by_var;
std::unordered_set<i_t> seen_original;
std::unordered_set<i_t> seen_complement;
coeff_by_var.reserve(cycle_size + wheel_centers.size());
seen_original.reserve(cycle_size + wheel_centers.size());
seen_complement.reserve(cycle_size + wheel_centers.size());
f_t rhs_acc = -f_m;
auto accumulate =
[&](const std::vector<i_t>& verts, f_t weight, bool is_cycle) -> clique_cut_build_status_t {
ZERO_HALF_DEBUG("build_zero_half_cut accumulate verts.size=%zu weight=%g is_cycle=%d",
verts.size(),
static_cast<double>(weight),
static_cast<int>(is_cycle));
for (consti_t vertex_idx : verts) {
ZERO_HALF_DEBUG(" acc vertex_idx=%lld (range [0, %lld))",
static_cast<longlong>(vertex_idx),
static_cast<longlong>(2 * num_vars));
cuopt_assert(vertex_idx >= 0 && vertex_idx < 2 * num_vars, "Zero-half vertex out of range");
consti_t var_idx = vertex_idx % num_vars;
constbool complement = vertex_idx >= num_vars;
constf_t lower_bound = lower_bounds[var_idx];
constf_t upper_bound = upper_bounds[var_idx];
cuopt_assert(var_types[var_idx] != variable_type_t::CONTINUOUS,
"Zero-half cut contains continuous variable");
cuopt_assert(lower_bound >= -bound_tol, "Zero-half variable lower bound below zero");
cuopt_assert(upper_bound <= 1 + bound_tol, "Zero-half variable upper bound above one");
if (complement) {
if (seen_original.count(var_idx) > 0) { returnclique_cut_build_status_t::NO_CUT; }
seen_complement.insert(var_idx);
coeff_by_var[var_idx] += weight;
rhs_acc += weight;
} else {
if (seen_complement.count(var_idx) > 0) { returnclique_cut_build_status_t::NO_CUT; }
seen_original.insert(var_idx);
coeff_by_var[var_idx] -= weight;
}
}
returnclique_cut_build_status_t::CUT_ADDED;
};
if (accumulate(cycle_vertices, static_cast<f_t>(1), true) !=
clique_cut_build_status_t::CUT_ADDED) {
ZERO_HALF_DEBUG("build_zero_half_cut cycle accumulate failed");
returnclique_cut_build_status_t::NO_CUT;
}
if (m > 0 && !wheel_centers.empty()) {
if (accumulate(wheel_centers, f_m, false) != clique_cut_build_status_t::CUT_ADDED) {
ZERO_HALF_DEBUG("build_zero_half_cut wheel accumulate failed");
returnclique_cut_build_status_t::NO_CUT;
}
}
constf_t coeff_zero_tol = static_cast<f_t>(1e-12);
cut.i.reserve(coeff_by_var.size());
cut.x.reserve(coeff_by_var.size());
for (const std::pair<consti_t, f_t>& kv : coeff_by_var) {
if (std::abs(kv.second) <= coeff_zero_tol) { continue; }
// Each variable appears at most once on the cycle (contributing +/-1) and
// at most once among the wheel centers (contributing +/-m), so no final
// coefficient can exceed 1 + m in magnitude. A larger value means a vertex
// was double-counted in accumulation.
cuopt_assert(std::abs(kv.second) <= f_m + static_cast<f_t>(1) + bound_tol,
"Zero-half coefficient exceeds 1 + m (vertex double-counted?)");
cut.i.push_back(kv.first);
cut.x.push_back(kv.second);
}
// Support is bounded by the number of distinct accumulated vertices.
cuopt_assert(cut.i.size() <= cycle_size + wheel_centers.size(),
"Zero-half cut support exceeds accumulated vertex count");
if (cut.i.empty()) {
ZERO_HALF_DEBUG("build_zero_half_cut empty support after accumulation");
returnclique_cut_build_status_t::NO_CUT;
}
cut_rhs = rhs_acc;
cut.sort();
constf_t dot = cut.dot(xstar);
constf_t violation = cut_rhs - dot;
ZERO_HALF_DEBUG(
"build_zero_half_cut nz=%lld rhs=%g dot=%g violation=%g threshold=%g cycle=%lld wheel=%lld",
static_cast<longlong>(cut.i.size()),
static_cast<double>(cut_rhs),
static_cast<double>(dot),
static_cast<double>(violation),
static_cast<double>(min_violation),
static_cast<longlong>(cycle_size),
static_cast<longlong>(wheel_centers.size()));
cuopt_assert(violation > -bound_tol, "Zero-half cut violation flipped sign unexpectedly");
if (violation > min_violation) { returnclique_cut_build_status_t::CUT_ADDED; }
returnclique_cut_build_status_t::NO_CUT;
}
// Reusable scratch for dijkstra_odd_cycle. The separation loop runs Dijkstra
// once per source vertex; re-allocating and re-initializing dist/prev. Instead
// we allocate the buffers once and reset them in O(1) using a generation stamp:
// dist[v]/prev[v] are considered valid for the current call only when
// stamp[v] == gen.
template <typenamei_t, typenamef_t>
structdijkstra_scratch_t {
std::vector<f_t> dist;
std::vector<i_t> prev;
std::vector<std::uint64_t> stamp; // stamp[v] == gen <=> dist[v]/prev[v] valid this call
std::uint64_t gen{0};
voidensure_size(std::size_t n)
{
if (stamp.size() < n) {
dist.resize(n);
prev.resize(n);
stamp.assign(n, 0);
gen = 0;
}
}
};
template <typenamei_t, typenamef_t>
booldijkstra_odd_cycle(i_t source_local,
const std::vector<std::vector<i_t>>& local_adj,
const std::vector<f_t>& weights,
f_t cutoff,
std::vector<i_t>& path,
f_t& total_weight,
f_t* work_estimate,
f_t max_work_estimate,
dijkstra_scratch_t<i_t, f_t>& scratch)
{
consti_t num_local = static_cast<i_t>(local_adj.size());
if (source_local < 0 || source_local >= num_local) { returnfalse; }
if (weights.size() != static_cast<size_t>(num_local)) { returnfalse; }
cuopt_assert(source_local >= 0 && source_local < num_local,
"Zero-half Dijkstra source out of range");
cuopt_assert(weights.size() == static_cast<size_t>(num_local),
"Zero-half Dijkstra weights size mismatch");
consti_t source_idx = source_local;
consti_t target_idx = source_local + num_local;
consti_t total_idx = 2 * num_local;
constf_t f_inf = std::numeric_limits<f_t>::infinity();
scratch.ensure_size(static_cast<std::size_t>(total_idx));
++scratch.gen;
const std::uint64_t gen = scratch.gen;
std::vector<f_t>& dist = scratch.dist;
std::vector<i_t>& prev = scratch.prev;
std::vector<std::uint64_t>& stamp = scratch.stamp;
// dist[v]/prev[v] are valid only if last written this call (stamp[v] == gen);
// otherwise the node is unreached, i.e. distance infinity.
auto cur_dist = [&](i_t v) -> f_t { return stamp[v] == gen ? dist[v] : f_inf; };
dist[source_idx] = 0;
prev[source_idx] = -1;
stamp[source_idx] = gen;
usingnode_t = std::pair<f_t, i_t>;
std::priority_queue<node_t, std::vector<node_t>, std::greater<node_t>> pq;
pq.emplace(static_cast<f_t>(0), source_idx);
i_t pops = 0;
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
++pops;
if (d > cur_dist(u)) { continue; }
if (u == target_idx) { break; }
if (cutoff > 0 && d >= cutoff) { break; }
consti_t u_local = u % num_local;
consti_t u_part = u / num_local;
consti_t v_part = 1 - u_part;
cuopt_assert(u_part == 0 || u_part == 1, "Bipartite part out of range");
const std::vector<i_t>& neigh = local_adj[u_local];
if (add_work_estimate(static_cast<f_t>(neigh.size()) + 4.0, work_estimate, max_work_estimate)) {
ZERO_HALF_DEBUG("dijkstra_odd_cycle work_limit hit pops=%lld", static_cast<longlong>(pops));
returnfalse;
}
for (consti_t v_local : neigh) {
cuopt_assert(v_local >= 0 && v_local < num_local, "Zero-half Dijkstra neighbor out of range");
f_t edge_w = (static_cast<f_t>(1) - weights[u_local] - weights[v_local]) / 2;
if (edge_w < 0) { edge_w = 0; }
consti_t v = v_local + v_part * num_local;
constf_t nd = d + edge_w;
if (nd < cur_dist(v)) {
dist[v] = nd;
prev[v] = u;
stamp[v] = gen;
pq.emplace(nd, v);
}
}
}
constf_t target_dist = cur_dist(target_idx);
if (!std::isfinite(target_dist)) {
ZERO_HALF_DEBUG("dijkstra_odd_cycle no path pops=%lld", static_cast<longlong>(pops));
returnfalse;
}
total_weight = target_dist;
// All G' edge weights are clamped to >= 0, so the shortest-path distance must
// be non-negative; a negative total means the clamp/relaxation invariant broke.
cuopt_assert(total_weight >= -static_cast<f_t>(1e-9),
"Zero-half Dijkstra shortest-path distance must be non-negative");
if (cutoff > 0 && total_weight >= cutoff) {
ZERO_HALF_DEBUG("dijkstra_odd_cycle path too long total=%g cutoff=%g",
static_cast<double>(total_weight),
static_cast<double>(cutoff));
returnfalse;
}
path.clear();
for (i_t cur = target_idx; cur != -1; cur = prev[cur]) {
path.push_back(cur);
if (cur == source_idx) { break; }
}
cuopt_assert(!path.empty(), "Zero-half Dijkstra path empty");
cuopt_assert(path.back() == source_idx, "Zero-half Dijkstra path missing source");
std::reverse(path.begin(), path.end());
cuopt_assert(path.front() == source_idx, "Zero-half Dijkstra path must start at source");
cuopt_assert(path.back() == target_idx, "Zero-half Dijkstra path must end at target");
// bipartite path from j1 to j2 must have odd number of edges
cuopt_assert((path.size() % 2) == 0, "Zero-half bipartite path must have even node count");
#ifdef ASSERT_MODE
// Every G' edge crosses between the two bipartite copies, so consecutive path
// nodes must live in opposite parts (part = bipartite_idx / num_local).
for (size_t k = 0; k + 1 < path.size(); ++k) {
cuopt_assert((path[k] / num_local) != (path[k + 1] / num_local),
"Zero-half Dijkstra path must alternate bipartite parts");
}
#endif
ZERO_HALF_DEBUG("dijkstra_odd_cycle done path.size=%zu total_weight=%g pops=%lld",
path.size(),
static_cast<double>(total_weight),
static_cast<longlong>(pops));
returntrue;
}
template <typenamei_t, typenamef_t>
boolpath_to_odd_cycle(const std::vector<i_t>& bipartite_path,
const std::vector<i_t>& vertices,
i_t num_local,
i_t num_vars,
std::vector<i_t>& cycle_vertices,
f_t* work_estimate,
f_t max_work_estimate)
{
ZERO_HALF_DEBUG(
"path_to_odd_cycle enter bipartite_path.size=%zu vertices.size=%zu num_local=%lld "
"num_vars=%lld",
bipartite_path.size(),
vertices.size(),
static_cast<longlong>(num_local),
static_cast<longlong>(num_vars));
cycle_vertices.clear();
if (bipartite_path.size() < 4) {
ZERO_HALF_DEBUG("path_to_odd_cycle reject short path");
returnfalse;
}
if (add_work_estimate(
static_cast<f_t>(bipartite_path.size()) * 2.0, work_estimate, max_work_estimate)) {
ZERO_HALF_DEBUG("path_to_odd_cycle work_limit hit");
returnfalse;
}
std::vector<i_t> local_seq;
local_seq.reserve(bipartite_path.size());
for (consti_t bv : bipartite_path) {
local_seq.push_back(bv % num_local);
}
cuopt_assert(local_seq.front() == local_seq.back(), "Zero-half cycle path endpoints must match");
// Drop the duplicate end so we have a sequence covering each cycle vertex once
local_seq.pop_back();
std::unordered_set<i_t> seen_local;
seen_local.reserve(local_seq.size());
for (consti_t lv : local_seq) {
if (!seen_local.insert(lv).second) {
// Same CG vertex appears twice in the path; reject (degenerate cycle)
ZERO_HALF_DEBUG("path_to_odd_cycle duplicate local vertex lv=%lld",
static_cast<longlong>(lv));
returnfalse;
}
}
cycle_vertices.reserve(local_seq.size());
std::unordered_set<i_t> seen_var;
seen_var.reserve(local_seq.size());
for (consti_t lv : local_seq) {
consti_t global = vertices[lv];
cuopt_assert(global >= 0 && global < 2 * num_vars, "Zero-half global vertex out of range");
consti_t var_idx = global % num_vars;
if (!seen_var.insert(var_idx).second) {
// Variable appears as both x and ¯x in the cycle; reject (degenerate)
ZERO_HALF_DEBUG("path_to_odd_cycle duplicate var_idx=%lld", static_cast<longlong>(var_idx));
returnfalse;
}
cycle_vertices.push_back(global);
}
cuopt_assert(cycle_vertices.size() == local_seq.size(),
"Zero-half cycle dropped vertices during global mapping");
cuopt_assert((cycle_vertices.size() % 2) == 1, "Zero-half extracted cycle must have odd length");
ZERO_HALF_DEBUG("path_to_odd_cycle done cycle_vertices.size=%zu", cycle_vertices.size());
return cycle_vertices.size() >= 5;
}
// Greedy lifting: extend an odd cycle by attaching a clique of "wheel center"
// vertices that are adjacent (in CG) to every vertex of the cycle.
template <typenamei_t, typenamef_t>
voidextend_to_odd_wheel(const std::vector<i_t>& cycle_vertices,
std::vector<i_t>& wheel_centers,
mip::clique_table_t<i_t, f_t>& graph,
const std::vector<f_t>& reduced_costs,
i_t num_vars,
f_t start_time,
f_t time_limit,
f_t* work_estimate,
f_t max_work_estimate)
{
ZERO_HALF_DEBUG(
"extend_to_odd_wheel enter cycle.size=%zu num_vars=%lld reduced_costs.size=%zu "
"graph.n_variables=%lld",
cycle_vertices.size(),
static_cast<longlong>(num_vars),
reduced_costs.size(),
static_cast<longlong>(graph.n_variables));
wheel_centers.clear();
if (cycle_vertices.empty()) { return; }
if (toc(start_time) >= time_limit) { return; }
consti_t smallest_degree_var = min_degree_anchor(cycle_vertices, graph, start_time, time_limit);
ZERO_HALF_DEBUG("extend_to_odd_wheel smallest_degree_var=%lld",
static_cast<longlong>(smallest_degree_var));
if (smallest_degree_var < 0) { return; }
std::unordered_set<i_t> adj_set = graph.get_adj_set_of_var(smallest_degree_var);
ZERO_HALF_DEBUG("extend_to_odd_wheel adj_set.size=%zu", adj_set.size());
std::vector<char> cycle_members(2 * num_vars, 0);
for (consti_t v : cycle_vertices) {
cuopt_assert(v >= 0 && v < 2 * num_vars, "Zero-half cycle vertex out of range");
cycle_members[v] = 1;
}
std::vector<i_t> candidates;
candidates.reserve(adj_set.size());
for (consti_t candidate : adj_set) {
if (toc(start_time) >= time_limit) { return; }
if (cycle_members[candidate] != 0) { continue; }
bool adj_to_all = true;
for (consti_t v : cycle_vertices) {
if (candidate == v) {
adj_to_all = false;
break;
}
if (!graph.check_adjacency(candidate, v)) {
adj_to_all = false;
break;
}
}
if (adj_to_all) { candidates.push_back(candidate); }
}
ZERO_HALF_DEBUG("extend_to_odd_wheel candidates.size=%zu", candidates.size());
if (candidates.empty()) { return; }
constf_t candidate_size = static_cast<f_t>(candidates.size());
constf_t cycle_size_f = static_cast<f_t>(cycle_vertices.size());
constf_t adj_set_cost = 2.0 * static_cast<f_t>(adj_set.size());
constf_t sort_cost =
candidate_size > 0.0 ? 2.0 * candidate_size * std::log2(candidate_size + 1.0) : 0.0;
if (add_work_estimate(adj_set_cost + cycle_size_f * candidate_size + sort_cost,
work_estimate,
max_work_estimate)) {
ZERO_HALF_DEBUG("extend_to_odd_wheel work_limit hit pre-sort");
return;
}
sort_candidates_by_reduced_cost(candidates, reduced_costs, num_vars);
// Candidates are already adjacent to every cycle vertex (filtered above), so
// growing a clique among them yields centers adjacent to the whole cycle and
// to each other.
constf_t adj_check_cost = 5.0;
greedy_extend_clique(wheel_centers,
candidates,
graph,
adj_check_cost,
start_time,
time_limit,
work_estimate,
max_work_estimate);
#ifdef ASSERT_MODE
// Post-condition: the selected centers must form a clique that is fully
// adjacent to the cycle — each center adjacent to every cycle vertex and to
// every other center. This is exactly what makes the m-weighted wheel lift a
// valid zero-half inequality.
for (size_t a = 0; a < wheel_centers.size(); ++a) {
for (consti_t cv : cycle_vertices) {
cuopt_assert(graph.check_adjacency(wheel_centers[a], cv),
"Zero-half wheel center not adjacent to every cycle vertex");
}
for (size_t b = a + 1; b < wheel_centers.size(); ++b) {
cuopt_assert(graph.check_adjacency(wheel_centers[a], wheel_centers[b]),
"Zero-half wheel centers must be mutually adjacent (clique)");
}
}
#endif
ZERO_HALF_DEBUG("extend_to_odd_wheel done wheel_centers.size=%zu", wheel_centers.size());
}
} // namespace