papilo-sys 0.1.0

Rust bindings for the PaPILO library
Documentation
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
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                           */
/*               This file is part of the program and library                */
/*    PaPILO --- Parallel Presolve for Integer and Linear Optimization       */
/*                                                                           */
/* Copyright (C) 2020-2025 Zuse Institute Berlin (ZIB)                       */
/*                                                                           */
/* Licensed under the Apache License, Version 2.0 (the "License");           */
/* you may not use this file except in compliance with the License.          */
/* You may obtain a copy of the License at                                   */
/*                                                                           */
/*     http://www.apache.org/licenses/LICENSE-2.0                            */
/*                                                                           */
/* Unless required by applicable law or agreed to in writing, software       */
/* distributed under the License is distributed on an "AS IS" BASIS,         */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  */
/* See the License for the specific language governing permissions and       */
/* limitations under the License.                                            */
/*                                                                           */
/* You should have received a copy of the Apache-2.0 license                 */
/* along with PaPILO; see the file LICENSE. If not visit scipopt.org.        */
/*                                                                           */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include "papilo/core/ConstraintMatrix.hpp"
#include "papilo/core/Problem.hpp"
#include "papilo/core/VariableDomains.hpp"
#include "papilo/io/Parser.hpp"
#include "papilo/misc/Hash.hpp"
#include "papilo/misc/Vec.hpp"
#include "papilo/misc/fmt.hpp"
#include "papilo/Config.hpp"
#ifdef PAPILO_TBB
#include "papilo/misc/tbb.hpp"
#endif
#include "papilo/external/pdqsort/pdqsort.h"
#include <algorithm>
#include <sys/stat.h>

using namespace papilo;

bool
fileExists( const std::string& name )
{
   struct stat buff;
   return ( stat( name.c_str(), &buff ) == 0 );
}

static std::pair<Vec<int>, Vec<int>>
compute_row_and_column_permutation( const Problem<double>& prob, bool verbose )
{
   const ConstraintMatrix<double>& consmatrix = prob.getConstraintMatrix();
   if( verbose )
      fmt::print( "Computing Permutation for {}\n", prob.getName() );

   std::pair<Vec<int>, Vec<int>> retval;
   Vec<uint64_t> rowhashes;
   Vec<uint64_t> colhashes;

   auto obj = [&]( int col ) {
      double tmp = prob.getObjective().coefficients[col];
      uint64_t val;
      std::memcpy( &val, &tmp, sizeof( double ) );
      return val;
   };

   auto lb = [&]( int col ) {
      double tmp = prob.getColFlags()[col].test( ColFlag::kLbInf )
                       ? std::numeric_limits<double>::lowest()
                       : prob.getLowerBounds()[col];
      uint64_t val;
      std::memcpy( &val, &tmp, sizeof( double ) );
      return val;
   };

   auto ub = [&]( int col ) {
      double tmp = prob.getColFlags()[col].test( ColFlag::kUbInf )
                       ? std::numeric_limits<double>::max()
                       : prob.getUpperBounds()[col];
      uint64_t val;
      std::memcpy( &val, &tmp, sizeof( double ) );
      return val;
   };

   auto lhs = [&]( int row ) {
      double tmp = consmatrix.getRowFlags()[row].test( RowFlag::kLhsInf )
                       ? std::numeric_limits<double>::lowest()
                       : consmatrix.getLeftHandSides()[row];
      uint64_t val;
      std::memcpy( &val, &tmp, sizeof( double ) );
      return val;
   };

   auto rhs = [&]( int row ) {
      double tmp = consmatrix.getRowFlags()[row].test( RowFlag::kRhsInf )
                       ? std::numeric_limits<double>::max()
                       : consmatrix.getRightHandSides()[row];
      uint64_t val;
      std::memcpy( &val, &tmp, sizeof( double ) );
      return val;
   };

   auto col_is_integral = [&]( int col ) {
      return static_cast<uint64_t>(
          prob.getColFlags()[col].test( ColFlag::kIntegral ) );
   };

   int ncols = prob.getNCols();
   int nrows = prob.getNRows();
   colhashes.resize( ncols + 2 );
   rowhashes.resize( nrows + 4 );

   const int LHS = ncols;
   const int RHS = ncols + 1;

   colhashes[LHS] = UINT64_MAX;
   colhashes[RHS] = UINT64_MAX - 1;

   const int OBJ = nrows;
   const int INTEGRAL = nrows + 1;
   const int LB = nrows + 2;
   const int UB = nrows + 3;

   rowhashes[OBJ] = UINT64_MAX - 2;
   rowhashes[INTEGRAL] = UINT64_MAX - 3;
   rowhashes[LB] = UINT64_MAX - 4;
   rowhashes[UB] = UINT64_MAX - 5;

   Vec<std::pair<uint64_t, int>> csrvals;
   Vec<int> csrstarts;

   csrstarts.resize( nrows + 1 );
   csrvals.reserve( consmatrix.getNnz() + 2 * nrows );

   for( int i = 0; i < nrows; ++i )
   {
      csrstarts[i] = csrvals.size();

      auto rowvec = consmatrix.getRowCoefficients( i );
      for( int k = 0; k < rowvec.getLength(); ++k )
      {
         uint64_t coef;
         std::memcpy( &coef, rowvec.getValues() + k, sizeof( double ) );
         csrvals.emplace_back( coef, rowvec.getIndices()[k] );
      }

      csrvals.emplace_back( lhs( i ), LHS );
      csrvals.emplace_back( rhs( i ), RHS );
   }

   csrstarts[nrows] = csrvals.size();

   Vec<std::pair<uint64_t, int>> cscvals;
   Vec<int> cscstarts;
   cscstarts.resize( ncols + 1 );
   cscvals.reserve( consmatrix.getNnz() + 4 * ncols );

   for( int i = 0; i < ncols; ++i )
   {
      cscstarts[i] = cscvals.size();

      auto colvec = consmatrix.getColumnCoefficients( i );
      for( int k = 0; k < colvec.getLength(); ++k )
      {
         uint64_t coef;
         std::memcpy( &coef, colvec.getValues() + k, sizeof( double ) );
         cscvals.emplace_back( coef, colvec.getIndices()[k] );
      }

      cscvals.emplace_back( obj( i ), OBJ );
      cscvals.emplace_back( col_is_integral( i ), INTEGRAL );
      cscvals.emplace_back( lb( i ), LB );
      cscvals.emplace_back( ub( i ), UB );
   }

   cscstarts[ncols] = cscvals.size();

   auto comp_rowvals = [&]( const std::pair<uint64_t, int>& a,
                            const std::pair<uint64_t, int>& b ) {
      return std::make_pair( a.first, colhashes[a.second] ) <
             std::make_pair( b.first, colhashes[b.second] );
   };

   auto comp_colvals = [&]( const std::pair<uint64_t, int>& a,
                            const std::pair<uint64_t, int>& b ) {
      return std::make_pair( a.first, rowhashes[a.second] ) <
             std::make_pair( b.first, rowhashes[b.second] );
   };

   int iters = 0;
   int lastncols = -1;
   HashMap<uint64_t, size_t> distinct_hashes( ncols );

   int lastnrows = -1;
   HashMap<uint64_t, size_t> distinct_row_hashes( nrows );

   Vec<int>& colperm = retval.second;
   colperm.resize( ncols );
   for( int i = 0; i < ncols; ++i )
      colperm[i] = i;

   Vec<int>& rowperm = retval.first;
   rowperm.resize( nrows );
   for( int i = 0; i < nrows; ++i )
      rowperm[i] = i;

   int nrows2 = nrows;
   int ncols2 = ncols;

   while( nrows2 != 0 )
   {
#ifdef PAPILO_TBB
      tbb::parallel_for(
          tbb::blocked_range<int>( 0, nrows2 ),
          [&]( const tbb::blocked_range<int>& r ) {
             for( int i = r.begin(); i != r.end(); ++i )
#else
                for( int i = 0; i < nrows2; ++i )
#endif
             {
                int row = rowperm[i];
                int start = csrstarts[row];
                int end = csrstarts[row + 1];
                const auto csrvals_ptr = csrvals.data();
                pdqsort( &csrvals_ptr[start], &csrvals_ptr[end], comp_rowvals );

                Hasher<uint64_t> hasher( end - start );
                for( int k = start; k < end; ++k )
                {
                   hasher.addValue( csrvals[k].first );
                   hasher.addValue( colhashes[csrvals[k].second] );
                }

                rowhashes[row] = hasher.getHash() >> 1;
             }
#ifdef PAPILO_TBB
          } );
#endif
      distinct_row_hashes.clear();

      for( int i = 0; i < nrows2; ++i )
         distinct_row_hashes[rowhashes[rowperm[i]]] += 1;

      pdqsort( rowperm.begin(), rowperm.begin() + nrows2, [&]( int a, int b ) {
         return std::make_tuple( -distinct_row_hashes[rowhashes[a]],
                                 rowhashes[a], a ) <
                std::make_tuple( -distinct_row_hashes[rowhashes[b]],
                                 rowhashes[b], b );
      } );

      lastnrows = nrows2;
      nrows2 = 0;

      while( nrows2 < lastnrows )
      {
         uint64_t hashval = rowhashes[rowperm[nrows2]];
         size_t partitionsize = distinct_row_hashes[hashval];
         if( partitionsize <= 1 )
            break;

         nrows2 += partitionsize;
      }

      for( int i = nrows2; i < lastnrows; ++i )
      {
         rowhashes[rowperm[i]] = i;
      }

      if( nrows2 == lastnrows )
      {
         --nrows2;
         std::swap( rowperm[0], rowperm[nrows2] );
         rowhashes[rowperm[nrows2]] = nrows2;
      }

      if( ncols2 == 0 )
         break;

#ifdef PAPILO_TBB
      tbb::parallel_for(
          tbb::blocked_range<int>( 0, ncols2 ),
          [&]( const tbb::blocked_range<int>& r ) {
             for( int i = r.begin(); i != r.end(); ++i )
#else
                for( int i = 0; i < ncols; ++i )
#endif
             {
                int col = colperm[i];
                int start = cscstarts[col];
                int end = cscstarts[col + 1];
                const auto cscvals_ptr = cscvals.data();
                pdqsort( &cscvals_ptr[start], &cscvals_ptr[end], comp_colvals );

                Hasher<uint64_t> hasher( end - start );
                for( int k = start; k < end; ++k )
                {
                   hasher.addValue( cscvals[k].first );
                   hasher.addValue( rowhashes[cscvals[k].second] );
                }

                colhashes[col] = hasher.getHash() >> 1;
             }
#ifdef PAPILO_TBB
          } );
#endif
      distinct_hashes.clear();

      for( int i = 0; i < ncols2; ++i )
         distinct_hashes[colhashes[colperm[i]]] += 1;

      pdqsort( colperm.begin(), colperm.begin() + ncols2, [&]( int a, int b ) {
         return std::make_pair( -distinct_hashes[colhashes[a]], colhashes[a] ) <
                std::make_pair( -distinct_hashes[colhashes[b]], colhashes[b] );
      } );

      lastncols = ncols2;
      ncols2 = 0;

      while( ncols2 < lastncols )
      {
         uint64_t hashval = colhashes[colperm[ncols2]];
         size_t partitionsize = distinct_hashes[hashval];
         if( partitionsize <= 1 )
            break;

         ncols2 += partitionsize;
      }

      for( int i = ncols2; i < lastncols; ++i )
      {
         colhashes[colperm[i]] = i;
      }

      ++iters;

      if( verbose )
         fmt::print(
             "iter {:3}: {:6} non unit col partitions and {:6} non unit row "
             "partitions\n",
             iters, ncols2, nrows2 );
   }

   return retval;
}

/// Returns True if variables in given permutation have same attributes
static bool
check_cols( const Problem<double>& prob1, const Problem<double>& prob2,
            const Vec<int>& perm1, const Vec<int>& perm2 )
{
   assert( perm1.size() == perm2.size() );
   int ncols = perm1.size();

   const VariableDomains<double>& vd1 = prob1.getVariableDomains();
   const VariableDomains<double>& vd2 = prob2.getVariableDomains();

   const Vec<String> cnames1 = prob1.getVariableNames();
   const Vec<String> cnames2 = prob2.getVariableNames();

   auto printVarsAndIndex = [&]( int i1, int i2 ) {
      fmt::print( "Differing Variables: Problem 1: {:6} at index {:<5} vs ",
                  cnames1[i1], i1 );
      fmt::print( "Problem 2: {:6} at index {:<5}\n", cnames2[i2], i2 );
   };

   for( int i = 0; i < ncols; ++i )
   {
      int i1 = perm1[i];
      int i2 = perm2[i];

      if( vd1.flags[i1].test( ColFlag::kIntegral ) !=
          vd2.flags[i2].test( ColFlag::kIntegral ) )
      {
         // kein duplikat: eine variable ist ganzzahlig die andere nicht
         fmt::print( "Variable is integer the other not!\n" );
         printVarsAndIndex( i1, i2 );
         return false;
      }

      if( vd1.flags[i1].test( ColFlag::kUbInf ) !=
          vd2.flags[i2].test( ColFlag::kUbInf ) )
      {
         // kein duplikat: ein upper bound ist +infinity, der andere nicht
         fmt::print(
             "Variable's Upper Bound is +infty and the others is not!\n" );
         printVarsAndIndex( i1, i2 );
         return false;
      }

      if( vd1.flags[i1].test( ColFlag::kLbInf ) !=
          vd2.flags[i2].test( ColFlag::kLbInf ) )
      {
         // kein duplikat: ein lower bound ist -infinity, der andere nicht
         fmt::print(
             "Variable's Lower Bound is -infty and the others is not! " );
         printVarsAndIndex( i1, i2 );
         return false;
      }

      if( !vd1.flags[i1].test( ColFlag::kLbInf ) &&
          vd1.lower_bounds[i1] != vd2.lower_bounds[i2] )
      {
         assert( !vd2.flags[i2].test( ColFlag::kLbInf ) );
         // kein duplikat: lower bounds sind endlich aber unterschiedlich
         fmt::print( "Lower Bounds are different!\n" );
         printVarsAndIndex( i1, i2 );
         return false;
      }

      if( !vd1.flags[i1].test( ColFlag::kUbInf ) &&
          vd1.upper_bounds[i1] != vd2.upper_bounds[i2] )
      {
         assert( !vd2.flags[i2].test( ColFlag::kUbInf ) );
         // kein duplikat: upper bounds sind endlich aber unterschiedlich
         fmt::print( "Upper Bounds are different!\n" );
         printVarsAndIndex( i1, i2 );
         return false;
      }
   }
   return true;
}

/// Returns True if rows in given Permutation are same for also given variable
/// permutation
static bool
check_rows( const Problem<double>& prob1, const Problem<double>& prob2,
            Vec<int> permrow1, Vec<int> permrow2, Vec<int> permcol1,
            Vec<int> permcol2 )
{
   assert( permrow1.size() == permrow2.size() );
   assert( permcol1.size() == permcol2.size() );

   const ConstraintMatrix<double>& cm1 = prob1.getConstraintMatrix();
   const ConstraintMatrix<double>& cm2 = prob2.getConstraintMatrix();

   int nrows = permrow1.size();

   // Row flags
   const Vec<RowFlags>& rflags1 = cm1.getRowFlags();
   const Vec<RowFlags>& rflags2 = cm2.getRowFlags();
   // Get sides
   const Vec<double>& lhs1 = cm1.getLeftHandSides();
   const Vec<double>& lhs2 = cm2.getLeftHandSides();
   const Vec<double>& rhs1 = cm1.getRightHandSides();
   const Vec<double>& rhs2 = cm2.getRightHandSides();

   HashMap<int, double> coefmap;

   const Vec<String> cnames1 = prob1.getVariableNames();
   const Vec<String> cnames2 = prob2.getVariableNames();
   const Vec<String> rnames1 = prob1.getConstraintNames();
   const Vec<String> rnames2 = prob2.getConstraintNames();

   auto printConstraintsAndIndex = [&]( int i1, int i2 ) {
      fmt::print( "Differing Constraints: Problem 1: {:6} at index {:<5} vs ",
                  rnames1[i1], i1 );
      fmt::print( "Problem 2: {:6} at index {:<5}\n", rnames2[i2], i2 );
   };

   auto findcol = []( int col, Vec<int> perm ) {
      return std::distance( perm.begin(),
                            std::find( perm.begin(), perm.end(), col ) );
   };

   for( int i = 0; i < nrows; ++i )
   {
      int i1row = permrow1[i];
      int i2row = permrow2[i];

      // Check Row flags for dissimilarities
      if( rflags1[i1row].test( RowFlag::kLhsInf ) !=
          rflags2[i2row].test( RowFlag::kLhsInf ) )
      {
         fmt::print( "Row has infinite LHS in only one of both problems!\n" );
         printConstraintsAndIndex( i1row, i2row );
         return false;
      }

      if( rflags1[i1row].test( RowFlag::kRhsInf ) !=
          rflags2[i2row].test( RowFlag::kRhsInf ) )
      {
         fmt::print( "Row has infinite RHS in only one of both problems!\n" );
         printConstraintsAndIndex( i1row, i2row );
         return false;
      }

      if( rflags1[i1row].test( RowFlag::kEquation ) !=
          rflags2[i2row].test( RowFlag::kEquation ) )
      {
         fmt::print( "Row is equation in only one of both problems!\n" );
         printConstraintsAndIndex( i1row, i2row );
         return false;
      }

      if( rflags1[i1row].test( RowFlag::kIntegral ) !=
          rflags2[i2row].test( RowFlag::kIntegral ) )
      {
         fmt::print( "Row is Integral in only one of both problems!\n" );
         printConstraintsAndIndex( i1row, i2row );
         return false;
      }

      // needed? probably not
      if( rflags1[i1row].test( RowFlag::kRedundant ) !=
          rflags2[i2row].test( RowFlag::kRedundant ) )
      {
         fmt::print( "Row is redundant in only one of both problems!\n" );
         printConstraintsAndIndex( i1row, i2row );
         return false;
      }

      // Check Row LHS values
      if( rflags1[i1row].test( RowFlag::kLhsInf ) &&
          lhs1[i1row] != lhs2[i2row] )
      {
         assert( rflags2[i2row].test( RowFlag::kLhsInf ) );
         fmt::print( "Row has different LHS in both problems!\n" );
         printConstraintsAndIndex( i1row, i2row );
         return false;
      }

      // Check Row RHS values
      if( rflags1[i1row].test( RowFlag::kRhsInf ) &&
          rhs1[i1row] != rhs2[i2row] )
      {
         assert( rflags2[i2row].test( RowFlag::kRhsInf ) );
         fmt::print( "Row has different RHS in both problems!\n" );
         printConstraintsAndIndex( i1row, i2row );
         return false;
      }

      // Check Row coefficients
      const SparseVectorView<double> row1 = cm1.getRowCoefficients( i1row );
      const SparseVectorView<double> row2 = cm2.getRowCoefficients( i2row );

      // Assume: If there is different amounts of variables in constraint it is
      // not the same (not entirely true)
      const int curr_ncols = row1.getLength();
      if( curr_ncols != row2.getLength() )
      {
         fmt::print( "Row has different amounts of variables!\n" );
         printConstraintsAndIndex( i1row, i2row );
         return false;
      }

      const int* inds1 = row1.getIndices();
      const int* inds2 = row2.getIndices();
      const double* vals1 = row1.getValues();
      const double* vals2 = row2.getValues();

      for( int x = 0; x < curr_ncols; ++x )
      {
         int col = findcol( inds1[x], permcol1 );
         coefmap[col] = vals1[x];
      }

      for( int x = 0; x < curr_ncols; ++x )
      {
         int final_index2 = findcol( inds2[x], permcol2 );

         // Check if same variables are defined for row
         if( coefmap.count( final_index2 ) == 0 )
         {
            fmt::print( "Row has different variables!\n" );
            printConstraintsAndIndex( i1row, i2row );
            fmt::print( "Variable `{}` at index {} is defined for Problem 2, "
                        "but not for Problem1",
                        cnames2[i], i );
            return false;
         }

         // Check if values are same
         if( coefmap[final_index2] != vals2[x] )
         {
            fmt::print( "Row has different coefficients for variable!\n" );
            printConstraintsAndIndex( i1row, i2row );
            fmt::print( "Variables: Problem1: {} at {} vs Problem2: {} at {}\n",
                        coefmap[final_index2], permrow1[final_index2], vals2[x],
                        inds2[x] );
            return false;
         }
      }

      // clear map for next row
      coefmap.clear();
   }
   return true;
}

static bool
check_duplicates( const Problem<double>& prob1, const Problem<double>& prob2 )
{
   // Check for columns
   int ncols = prob1.getNCols();

   if( ncols != prob2.getNCols() )
   {
      // kein duplikat: unterschiedlich viele variablen
      fmt::print( "not same number of variables\n" );
      return false;
   }

   // Check for rows
   // First assume for being same you need to have same rows (even though not
   // true)
   int nrows = prob1.getNRows();

   if( nrows != prob2.getNRows() )
   {
      fmt::print( "not same number of rows: prob1:{} prob2:{}\n", nrows,
                  prob2.getNRows() );
      return false;
   }

   std::pair<Vec<int>, Vec<int>> perms1 =
       compute_row_and_column_permutation( prob1, true );
   std::pair<Vec<int>, Vec<int>> perms2 =
       compute_row_and_column_permutation( prob2, true );

   Vec<int>& perm_col1 = perms1.second;
   Vec<int>& perm_col2 = perms2.second;

   Vec<int>& perm_row1 = perms1.first;
   Vec<int>& perm_row2 = perms2.first;

   if( !check_cols( prob1, prob2, perm_col1, perm_col2 ) )
      return false;

   if( !check_rows( prob1, prob2, perm_row1, perm_row2, perm_col1, perm_col2 ) )
      return false;

   // All checks passed
   return true;
}

static uint64_t
compute_instancehash( const Problem<double>& prob )
{
   const int MAX_HASH_ITERS = 5;
   const ConstraintMatrix<double> cm = prob.getConstraintMatrix();

   int nrows = cm.getNRows();
   int ncols = cm.getNCols();
   int nnz = cm.getNnz();

   auto obj = [&]( int col ) {
      double tmp = prob.getObjective().coefficients[col];
      uint64_t val;
      std::memcpy( &val, &tmp, sizeof( double ) );
      return val;
   };

   auto lb = [&]( int col ) {
      double tmp = prob.getColFlags()[col].test( ColFlag::kLbInf )
                       ? std::numeric_limits<double>::lowest()
                       : prob.getLowerBounds()[col];
      uint64_t val;
      std::memcpy( &val, &tmp, sizeof( double ) );
      return val;
   };

   auto ub = [&]( int col ) {
      double tmp = prob.getColFlags()[col].test( ColFlag::kUbInf )
                       ? std::numeric_limits<double>::max()
                       : prob.getUpperBounds()[col];
      uint64_t val;
      std::memcpy( &val, &tmp, sizeof( double ) );
      return val;
   };

   auto col_is_integral = [&]( int col ) {
      return static_cast<uint64_t>(
          prob.getColFlags()[col].test( ColFlag::kIntegral ) );
   };

   auto lhs = [&]( int row ) {
      double tmp = cm.getRowFlags()[row].test( RowFlag::kLhsInf )
                       ? std::numeric_limits<double>::lowest()
                       : cm.getLeftHandSides()[row];
      uint64_t val;
      std::memcpy( &val, &tmp, sizeof( double ) );
      return val;
   };

   auto rhs = [&]( int row ) {
      double tmp = cm.getRowFlags()[row].test( RowFlag::kRhsInf )
                       ? std::numeric_limits<double>::max()
                       : cm.getRightHandSides()[row];
      uint64_t val;
      std::memcpy( &val, &tmp, sizeof( double ) );
      return val;
   };

   // Setup rowhashes and colhashes
   Vec<uint64_t> rowhashes;
   Vec<uint64_t> colhashes;
   colhashes.resize( ncols + 2 );
   rowhashes.resize( nrows + 4 );

   const int LHS = ncols;
   const int RHS = ncols + 1;

   colhashes[LHS] = UINT64_MAX;
   colhashes[RHS] = UINT64_MAX - 1;

   const int OBJ = nrows;
   const int INTEGRAL = nrows + 1;
   const int LB = nrows + 2;
   const int UB = nrows + 3;

   rowhashes[OBJ] = UINT64_MAX - 2;
   rowhashes[INTEGRAL] = UINT64_MAX - 3;
   rowhashes[LB] = UINT64_MAX - 4;
   rowhashes[UB] = UINT64_MAX - 5;

   // Datastructure to save coefficients columnwise
   Vec<std::pair<uint64_t, int>> csrvals;
   Vec<int> csrstarts;
   csrstarts.resize( nrows + 1 );
   csrvals.reserve( nnz + 2 * nrows );

   for( int i = 0; i < nrows; ++i )
   {
      csrstarts[i] = csrvals.size();

      auto rowvec = cm.getRowCoefficients( i );
      for( int k = 0; k < rowvec.getLength(); ++k )
      {
         uint64_t coef;
         std::memcpy( &coef, rowvec.getValues() + k, sizeof( double ) );
         csrvals.emplace_back( coef, rowvec.getIndices()[k] );
      }

      csrvals.emplace_back( lhs( i ), LHS );
      csrvals.emplace_back( rhs( i ), RHS );
   }

   csrstarts[nrows] = csrvals.size();

   // Datastructure to save coefficients rowwise
   Vec<std::pair<uint64_t, int>> cscvals;
   Vec<int> cscstarts;
   cscstarts.resize( ncols + 1 );
   cscvals.reserve( nnz + 4 * ncols );

   for( int i = 0; i < ncols; ++i )
   {
      cscstarts[i] = cscvals.size();

      auto colvec = cm.getColumnCoefficients( i );
      for( int k = 0; k < colvec.getLength(); ++k )
      {
         uint64_t coef;
         std::memcpy( &coef, colvec.getValues() + k, sizeof( double ) );
         cscvals.emplace_back( coef, colvec.getIndices()[k] );
      }

      cscvals.emplace_back( obj( i ), OBJ );
      cscvals.emplace_back( col_is_integral( i ), INTEGRAL );
      cscvals.emplace_back( lb( i ), LB );
      cscvals.emplace_back( ub( i ), UB );
   }

   cscstarts[ncols] = cscvals.size();

   auto comp_rowvals = [&]( const std::pair<uint64_t, int>& a,
                            const std::pair<uint64_t, int>& b ) {
      return std::make_pair( a.first, colhashes[a.second] ) <
             std::make_pair( b.first, colhashes[b.second] );
   };

   auto comp_colvals = [&]( const std::pair<uint64_t, int>& a,
                            const std::pair<uint64_t, int>& b ) {
      return std::make_pair( a.first, rowhashes[a.second] ) <
             std::make_pair( b.first, rowhashes[b.second] );
   };

   // Prepare permutation to not compute all hashes in each step newly
   Vec<int> colperm;
   colperm.resize( ncols );
   for( int i = 0; i < ncols; ++i )
      colperm[i] = i;

   Vec<int> rowperm;
   rowperm.resize( nrows );
   for( int i = 0; i < nrows; ++i )
      rowperm[i] = i;

   int iters = 0;

   int ncols2 = ncols;
   int lastncols = -1;
   HashMap<uint64_t, size_t> distinct_col_hashes( ncols );

   int nrows2 = nrows;
   int lastnrows = -1;
   HashMap<uint64_t, size_t> distinct_row_hashes( nrows );

   // Compute column and row hashes
   while( nrows2 != 0 && iters <= MAX_HASH_ITERS )
   {
#ifdef PAPILO_TBB
      tbb::parallel_for(
          tbb::blocked_range<int>( 0, nrows2 ),
          [&]( const tbb::blocked_range<int>& r ) {
             for( int i = r.begin(); i != r.end(); ++i )
#else
                for( int i = 0; i < nrows2; ++i )
#endif
             {
                int row = rowperm[i];
                int start = csrstarts[row];
                int end = csrstarts[row + 1];
                const auto csrvals_ptr = csrvals.data();
                pdqsort( &csrvals_ptr[start], &csrvals_ptr[end], comp_rowvals );

                Hasher<uint64_t> hasher( end - start );
                for( int k = start; k < end; ++k )
                {
                   hasher.addValue( csrvals[k].first );
                   hasher.addValue( colhashes[csrvals[k].second] );
                }

                rowhashes[row] = hasher.getHash() >> 1;
             }
#ifdef PAPILO_TBB
          } );
#endif

      distinct_row_hashes.clear();

      for( int i = 0; i < nrows2; ++i )
         distinct_row_hashes[rowhashes[rowperm[i]]] += 1;

      pdqsort( rowperm.begin(), rowperm.begin() + nrows2, [&]( int a, int b ) {
         return std::make_tuple( -distinct_row_hashes[rowhashes[a]],
                                 rowhashes[a], a ) <
                std::make_tuple( -distinct_row_hashes[rowhashes[b]],
                                 rowhashes[b], b );
      } );

      lastnrows = nrows2;
      nrows2 = 0;

      while( nrows2 < lastnrows )
      {
         uint64_t hashval = rowhashes[rowperm[nrows2]];
         size_t partitionsize = distinct_row_hashes[hashval];
         if( partitionsize <= 1 )
            break;

         nrows2 += partitionsize;
      }

      for( int i = nrows2; i < lastnrows; ++i )
      {
         rowhashes[rowperm[i]] = i;
      }

      if( nrows2 == lastnrows )
      {
         --nrows2;
         std::swap( rowperm[0], rowperm[nrows2] );
         rowhashes[rowperm[nrows2]] = nrows2;
      }

      if( ncols2 == 0 )
         break;

#ifdef PAPILO_TBB
      tbb::parallel_for(
          tbb::blocked_range<int>( 0, ncols2 ),
          [&]( const tbb::blocked_range<int>& r ) {
             for( int i = r.begin(); i != r.end(); ++i )
#else
       for( int i = 0; i < ncols; ++i )
#endif
             {
                int col = colperm[i];
                int start = cscstarts[col];
                int end = cscstarts[col + 1];
                const auto cscvals_ptr = cscvals.data();
                pdqsort( &cscvals_ptr[start], &cscvals_ptr[end], comp_colvals );

                Hasher<uint64_t> hasher( end - start );
                for( int k = start; k < end; ++k )
                {
                   hasher.addValue( cscvals[k].first );
                   hasher.addValue( rowhashes[cscvals[k].second] );
                }

                colhashes[col] = hasher.getHash() >> 1;
             }
#ifdef PAPILO_TBB
          } );
#endif
      distinct_col_hashes.clear();

      for( int i = 0; i < ncols2; ++i )
         distinct_col_hashes[colhashes[colperm[i]]] += 1;

      pdqsort( colperm.begin(), colperm.begin() + ncols2, [&]( int a, int b ) {
         return std::make_pair( -distinct_col_hashes[colhashes[a]],
                                colhashes[a] ) <
                std::make_pair( -distinct_col_hashes[colhashes[b]],
                                colhashes[b] );
      } );

      lastncols = ncols2;
      ncols2 = 0;

      while( ncols2 < lastncols )
      {
         uint64_t hashval = colhashes[colperm[ncols2]];
         size_t partitionsize = distinct_col_hashes[hashval];
         if( partitionsize <= 1 )
            break;

         ncols2 += partitionsize;
      }

      for( int i = ncols2; i < lastncols; ++i )
         colhashes[colperm[i]] = i;

      ++iters;
   }
   // Sort hashes
   pdqsort( rowhashes.begin(), rowhashes.end(),
            []( uint64_t a, uint64_t b ) { return a < b; } );
   pdqsort( colhashes.begin(), colhashes.end(),
            []( uint64_t a, uint64_t b ) { return a < b; } );

   // Put all values in the hasher
   Hasher<uint64_t> hasher( nnz );
   hasher.addValue( nrows );
   hasher.addValue( ncols );
   hasher.addValue( prob.getNumIntegralCols() );
   hasher.addValue( prob.getNumContinuousCols() );
   for( uint64_t hash : rowhashes )
      hasher.addValue( hash );
   for( uint64_t hash : colhashes )
      hasher.addValue( hash );
   return hasher.getHash();
}

int
main( int argc, char* argv[] )
{
   if( argc != 2 && argc != 3 )
   {
      fmt::print( "usage:\n" );
      fmt::print( "./check_duplicates instance1.mps instance2.mps  - check for "
                  "duplicates\n" );
      fmt::print( "./check_duplicates instance1.mps                - compute "
                  "unique hash for instance" );
      return 1;
   }
   assert( argc == 2 || argc == 3 );

   // Load and check problem 1
   if( !fileExists( argv[1] ) )
   {
      fmt::print( "Error: Can not find instance at `{}`\n", argv[1] );
      return 1;
   }
   boost::optional<Problem<double>> prob1t =
       Parser<double>::loadProblem( argv[1] );
   if( !prob1t )
   {
      fmt::print( "error loading problem {}\n", argv[1] );
      return 1;
   }
   Problem<double> prob1 = *prob1t;

   if( argc == 2 )
   {
      uint64_t result = compute_instancehash( prob1 );
      fmt::print( "{}\n", result );
   }
   else
   {
      // Load and check problem 2
      if( !fileExists( argv[2] ) )
      {
         fmt::print( "Error: Can not find instance at `{}`\n", argv[2] );
         return 1;
      }
      boost::optional<Problem<double>> prob2t =
          Parser<double>::loadProblem( argv[2] );
      if( !prob2t )
      {
         fmt::print( "error loading problem {}\n", argv[1] );
         return 1;
      }
      Problem<double> prob2 = *prob2t;
      fmt::print( "duplicates: {}\n", check_duplicates( prob1, prob2 ) );
   }

   return 0;
}