-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathmps_parser.cpp
More file actions
1449 lines (1317 loc) · 54.3 KB
/
mps_parser.cpp
File metadata and controls
1449 lines (1317 loc) · 54.3 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) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
/* clang-format on */
#include <mps_parser.hpp>
#include <utilities/error.hpp>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstring>
#include <fstream>
#include <iostream>
#include <limits>
#include <memory>
#include <sstream>
#include <string>
#ifdef MPS_PARSER_WITH_BZIP2
#include <bzlib.h>
#endif // MPS_PARSER_WITH_BZIP2
#ifdef MPS_PARSER_WITH_ZLIB
#include <zlib.h>
#endif // MPS_PARSER_WITH_ZLIB
#if defined(MPS_PARSER_WITH_BZIP2) || defined(MPS_PARSER_WITH_ZLIB)
#include <dlfcn.h>
#endif // MPS_PARSER_WITH_BZIP2 || MPS_PARSER_WITH_ZLIB
namespace {
using cuopt::mps_parser::error_type_t;
using cuopt::mps_parser::mps_parser_expects;
using cuopt::mps_parser::mps_parser_expects_fatal;
struct FcloseDeleter {
void operator()(FILE* fp)
{
mps_parser_expects_fatal(
fclose(fp) == 0, error_type_t::ValidationError, "Error closing MPS file!");
}
};
} // end namespace
#ifdef MPS_PARSER_WITH_BZIP2
namespace {
using BZ2_bzReadOpen_t = decltype(&BZ2_bzReadOpen);
using BZ2_bzReadClose_t = decltype(&BZ2_bzReadClose);
using BZ2_bzRead_t = decltype(&BZ2_bzRead);
std::vector<char> bz2_file_to_string(const std::string& file)
{
struct DlCloseDeleter {
void operator()(void* fp)
{
mps_parser_expects_fatal(
dlclose(fp) == 0, error_type_t::ValidationError, "Error closing libbz2.so!");
}
};
struct BzReadCloseDeleter {
void operator()(void* f)
{
int bzerror;
if (f != nullptr) fptr(&bzerror, f);
mps_parser_expects_fatal(
bzerror == BZ_OK, error_type_t::ValidationError, "Error closing bzip2 file!");
}
BZ2_bzReadClose_t fptr = nullptr;
};
std::unique_ptr<void, DlCloseDeleter> lbz2handle{dlopen("libbz2.so", RTLD_LAZY)};
mps_parser_expects(
lbz2handle != nullptr,
error_type_t::ValidationError,
"Could not open .mps.bz2 file since libbz2.so was not found. In order to open .mps.bz2 files "
"directly, please ensure libbzip2 is installed. Alternatively, decompress the .mps.bz2 file "
"manually and open the uncompressed .mps file. Given path: %s",
file.c_str());
BZ2_bzReadOpen_t BZ2_bzReadOpen =
reinterpret_cast<BZ2_bzReadOpen_t>(dlsym(lbz2handle.get(), "BZ2_bzReadOpen"));
BZ2_bzReadClose_t BZ2_bzReadClose =
reinterpret_cast<BZ2_bzReadClose_t>(dlsym(lbz2handle.get(), "BZ2_bzReadClose"));
BZ2_bzRead_t BZ2_bzRead = reinterpret_cast<BZ2_bzRead_t>(dlsym(lbz2handle.get(), "BZ2_bzRead"));
mps_parser_expects(
BZ2_bzReadOpen != nullptr && BZ2_bzReadClose != nullptr && BZ2_bzRead != nullptr,
error_type_t::ValidationError,
"Error loading libbzip2! Library version might be incompatible. Please decompress the .mps.bz2 "
"file manually and open the uncompressed .mps file. Given path: %s",
file.c_str());
std::unique_ptr<FILE, FcloseDeleter> fp{fopen(file.c_str(), "rb")};
mps_parser_expects(fp != nullptr,
error_type_t::ValidationError,
"Error opening MPS file! Given path: %s",
file.c_str());
int bzerror = BZ_OK;
std::unique_ptr<void, BzReadCloseDeleter> bzfile{
BZ2_bzReadOpen(&bzerror, fp.get(), 0, 0, nullptr, 0), {BZ2_bzReadClose}};
mps_parser_expects(bzerror == BZ_OK,
error_type_t::ValidationError,
"Could not open bzip2 compressed file! Given path: %s",
file.c_str());
std::vector<char> buf;
const size_t readbufsize = 1ull << 24; // 16MiB - just a guess.
std::vector<char> readbuf(readbufsize);
while (bzerror == BZ_OK) {
const size_t bytes_read = BZ2_bzRead(&bzerror, bzfile.get(), readbuf.data(), readbuf.size());
if (bzerror == BZ_OK || bzerror == BZ_STREAM_END) {
buf.insert(buf.end(), begin(readbuf), begin(readbuf) + bytes_read);
}
}
buf.push_back('\0');
mps_parser_expects(bzerror == BZ_STREAM_END,
error_type_t::ValidationError,
"Error in bzip2 decompression of MPS file! Given path: %s",
file.c_str());
return buf;
}
} // end namespace
#endif // MPS_PARSER_WITH_BZIP2
#ifdef MPS_PARSER_WITH_ZLIB
namespace {
using gzopen_t = decltype(&gzopen);
using gzclose_r_t = decltype(&gzclose_r);
using gzbuffer_t = decltype(&gzbuffer);
using gzread_t = decltype(&gzread);
using gzerror_t = decltype(&gzerror);
std::vector<char> zlib_file_to_string(const std::string& file)
{
struct DlCloseDeleter {
void operator()(void* fp)
{
mps_parser_expects_fatal(
dlclose(fp) == 0, error_type_t::ValidationError, "Error closing libbz2.so!");
}
};
struct GzCloseDeleter {
void operator()(gzFile_s* f)
{
int err = fptr(f);
mps_parser_expects_fatal(
err == Z_OK, error_type_t::ValidationError, "Error closing gz file!");
}
gzclose_r_t fptr = nullptr;
};
std::unique_ptr<void, DlCloseDeleter> lzhandle{dlopen("libz.so.1", RTLD_LAZY)};
mps_parser_expects(
lzhandle != nullptr,
error_type_t::ValidationError,
"Could not open .mps.gz file since libz.so was not found. In order to open .mps.gz files "
"directly, please ensure zlib is installed. Alternatively, decompress the .mps.gz file "
"manually and open the uncompressed .mps file. Given path: %s",
file.c_str());
gzopen_t gzopen = reinterpret_cast<gzopen_t>(dlsym(lzhandle.get(), "gzopen"));
gzclose_r_t gzclose_r = reinterpret_cast<gzclose_r_t>(dlsym(lzhandle.get(), "gzclose_r"));
gzbuffer_t gzbuffer = reinterpret_cast<gzbuffer_t>(dlsym(lzhandle.get(), "gzbuffer"));
gzread_t gzread = reinterpret_cast<gzread_t>(dlsym(lzhandle.get(), "gzread"));
gzerror_t gzerror = reinterpret_cast<gzerror_t>(dlsym(lzhandle.get(), "gzerror"));
mps_parser_expects(
gzopen != nullptr && gzclose_r != nullptr && gzbuffer != nullptr && gzread != nullptr &&
gzerror != nullptr,
error_type_t::ValidationError,
"Error loading zlib! Library version might be incompatible. Please decompress the .mps.gz file "
"manually and open the uncompressed .mps file. Given path: %s",
file.c_str());
std::unique_ptr<gzFile_s, GzCloseDeleter> gzfp{gzopen(file.c_str(), "rb"), {gzclose_r}};
mps_parser_expects(gzfp != nullptr,
error_type_t::ValidationError,
"Error opening compressed MPS file! Given path: %s",
file.c_str());
int zlib_status = gzbuffer(gzfp.get(), 1 << 20); // 1 MiB
mps_parser_expects(zlib_status == Z_OK,
error_type_t::ValidationError,
"Could not set zlib internal buffer size for decompression! Given path: %s",
file.c_str());
std::vector<char> buf;
const size_t readbufsize = 1ull << 24; // 16MiB
std::vector<char> readbuf(readbufsize);
int bytes_read = -1;
while (bytes_read != 0) {
bytes_read = gzread(gzfp.get(), readbuf.data(), readbuf.size());
if (bytes_read > 0) { buf.insert(buf.end(), begin(readbuf), begin(readbuf) + bytes_read); }
if (bytes_read < 0) {
gzerror(gzfp.get(), &zlib_status);
break;
}
}
buf.push_back('\0');
mps_parser_expects(zlib_status == Z_OK,
error_type_t::ValidationError,
"Error in zlib decompression of MPS file! Given path: %s",
file.c_str());
return buf;
}
} // end namespace
#endif // MPS_PARSER_WITH_ZLIB
namespace cuopt::mps_parser {
template <typename i_t>
std::string_view get_next_string(std::string_view line, i_t& pos, i_t& end)
{
pos = line.find_first_not_of(" \t", end);
if (pos == std::string_view::npos) return "";
end = line.find_first_of(" \t\n\r", pos);
if (end == std::string_view::npos) return line.substr(pos);
return line.substr(pos, end - pos);
}
std::string_view trim(std::string_view str)
{
auto start = str.find_first_not_of(" \r\t");
if (start == std::string::npos) { return ""; }
auto end = str.find_last_not_of(" \r\t");
return str.substr(start, end - start + 1);
}
BoundType convert(std::string_view str)
{
if (str == "LO") {
return LowerBound;
} else if (str == "UP") {
return UpperBound;
} else if (str == "FX") {
return Fixed;
} else if (str == "FR") {
return Free;
} else if (str == "MI") {
return LowerBoundNegInf;
} else if (str == "PL") {
return UpperBoundInf;
} else if (str == "BV") {
return BinaryVariable;
} else if (str == "LI") {
return LowerBoundIntegerVariable;
} else if (str == "UI") {
return UpperBoundIntegerVariable;
} else if (str == "LC") {
return SemiContiniousVariable;
} else {
mps_parser_expects(false,
error_type_t::ValidationError,
"Invalid variable bound type found in BOUNDS section! Bound type=%s",
std::string(str).c_str());
return SemiContiniousVariable;
}
}
ObjSenseType convert_to_obj_sense(const std::string& str)
{
if (str == "MIN" || str == "MINIMIZE") {
return Minimize;
} else if (str == "MAX" || str == "MAXIMIZE") {
return Maximize;
} else {
mps_parser_expects(false,
error_type_t::ValidationError,
"Invalid variable bound type found in OBJSENSE section! Objsense type=%s",
str.c_str());
return Minimize;
}
}
template <typename i_t, typename f_t>
void mps_parser_t<i_t, f_t>::fill_problem(mps_data_model_t<i_t, f_t>& problem)
{
{
std::vector<i_t> h_offsets{}, h_indices{};
std::vector<f_t> h_values{};
h_offsets.push_back(0);
for (i_t i = 0; i < (i_t)A_indices.size(); ++i) {
i_t off = h_offsets.size() > 0 ? h_offsets[h_offsets.size() - 1] : 0;
for (const auto& idx_itr : A_indices[i]) {
h_indices.push_back(idx_itr);
}
for (const auto& val_itr : A_values[i]) {
h_values.push_back(val_itr);
}
off += A_indices[i].size();
h_offsets.push_back(off);
}
problem.set_csr_constraint_matrix(h_values.data(),
h_values.size(),
h_indices.data(),
h_indices.size(),
h_offsets.data(),
h_offsets.size());
mps_parser_expects(A_indices.size() + 1 == h_offsets.size(),
error_type_t::ValidationError,
"The row indexing vector for the constraint matrix was not constructed "
"successfully. Should be size %zu, but was size %zu",
A_indices.size() + 1,
h_offsets.size());
mps_parser_expects(
h_indices.size() == h_values.size(),
error_type_t::ValidationError,
"The nonzero value vector or the column indexing vector for the constraint "
"matrix was not constructed "
"successfully. Should be the same size but nonzeroes were of size %zu and column "
"indexing vector of size %zu ",
h_indices.size(),
h_values.size());
mps_parser_expects(
h_offsets[h_offsets.size() - 1] == (i_t)h_values.size(),
error_type_t::ValidationError,
"The last row offset for the constraint matrix is not equal to the size of the "
"nonzero vector. Nonzero has size %zu but the last offset is %d.",
h_values.size(),
h_offsets[h_offsets.size() - 1]);
}
// Set b & c
problem.set_constraint_bounds(b_values.data(), b_values.size());
problem.set_objective_coefficients(c_values.data(), c_values.size());
// Set offset and scaling factor of objective function
problem.set_objective_scaling_factor(objective_scaling_factor_value);
problem.set_objective_offset(objective_offset_value);
// Set lower and upper bounds
problem.set_variable_lower_bounds(variable_lower_bounds.data(), variable_lower_bounds.size());
problem.set_variable_upper_bounds(variable_upper_bounds.data(), variable_upper_bounds.size());
mps_parser_expects(
(problem.get_variable_lower_bounds().size() == problem.get_variable_upper_bounds().size()) &&
(problem.get_variable_upper_bounds().size() == problem.get_objective_coefficients().size()),
error_type_t::ValidationError,
"Sizes for vectors related to the variables are not the same. The objective "
"vector has size %zu, the variable lower bounds vector has size %zu and the "
"variable upper bounds vector has size %zu.",
problem.get_objective_coefficients().size(),
problem.get_variable_lower_bounds().size(),
problem.get_variable_upper_bounds().size());
// Determine the constraint bounds based on row types
{
std::vector<f_t> h_constraint_lower_bounds{};
std::vector<f_t> h_constraint_upper_bounds{};
for (i_t i = 0; i < (i_t)row_types.size(); ++i) {
if (row_types[i] == Equality) {
h_constraint_lower_bounds.push_back(b_values[i]);
h_constraint_upper_bounds.push_back(b_values[i]);
if (ranges_values.size() > 0 &&
ranges_values[i] != unset_range_value) // Add range value if specified
{
mps_parser_expects(!std::isnan(h_constraint_lower_bounds[i]),
error_type_t::ValidationError,
"Constraints lower bound %d shouldn't be nan",
i);
mps_parser_expects(!std::isnan(h_constraint_upper_bounds[i]),
error_type_t::ValidationError,
"Constraints upper bound %d shouldn't be nan",
i);
mps_parser_expects(!std::isnan(ranges_values[i]),
error_type_t::ValidationError,
"Equality range value %d shouldn't be nan",
i);
if (ranges_values[i] < f_t(0))
h_constraint_lower_bounds[i] = h_constraint_lower_bounds[i] + ranges_values[i];
else // Positive
h_constraint_upper_bounds[i] = h_constraint_upper_bounds[i] + ranges_values[i];
}
} else if (row_types[i] == GreaterThanOrEqual) {
h_constraint_lower_bounds.push_back(b_values[i]);
h_constraint_upper_bounds.push_back(std::numeric_limits<f_t>::infinity());
if (ranges_values.size() > 0 &&
ranges_values[i] != unset_range_value) // Add range value if specified
{
mps_parser_expects(!std::isnan(h_constraint_lower_bounds[i]),
error_type_t::ValidationError,
"Constraints lower bound %d shouldn't be nan",
i);
mps_parser_expects(!std::isnan(ranges_values[i]),
error_type_t::ValidationError,
"Greater range value %d shouldn't be nan",
i);
h_constraint_upper_bounds[i] = h_constraint_lower_bounds[i] + std::abs(ranges_values[i]);
}
} else if (row_types[i] == LesserThanOrEqual) {
h_constraint_lower_bounds.push_back(-std::numeric_limits<f_t>::infinity());
h_constraint_upper_bounds.push_back(b_values[i]);
if (ranges_values.size() > 0 &&
ranges_values[i] != unset_range_value) // Add range value if specified
{
mps_parser_expects(!std::isnan(h_constraint_upper_bounds[i]),
error_type_t::ValidationError,
"Constraints upper bound %d shouldn't be nan",
i);
mps_parser_expects(!std::isnan(ranges_values[i]),
error_type_t::ValidationError,
"Lesser range value %d shouldn't be nan",
i);
h_constraint_lower_bounds[i] = h_constraint_upper_bounds[i] - std::abs(ranges_values[i]);
}
} else {
mps_parser_expects(false,
error_type_t::ValidationError,
"Unsupported row type was passed to the Optimization Problem");
}
mps_parser_expects(
!std::isnan(h_constraint_lower_bounds[i]), error_type_t::ValidationError, "Cannot be nan");
mps_parser_expects(
!std::isnan(h_constraint_upper_bounds[i]), error_type_t::ValidationError, "Cannot be nan");
}
problem.set_constraint_lower_bounds(h_constraint_lower_bounds.data(),
h_constraint_lower_bounds.size());
problem.set_constraint_upper_bounds(h_constraint_upper_bounds.data(),
h_constraint_upper_bounds.size());
mps_parser_expects(
(problem.get_constraint_lower_bounds().size() ==
problem.get_constraint_upper_bounds().size()) &&
(problem.get_constraint_upper_bounds().size() == problem.get_constraint_bounds().size()),
error_type_t::ValidationError,
"Sizes for vectors related to the constraints are not the same. The right hand side "
"vector has size %zu, the constraint lower bounds vector has size %zu and the "
"constraint upper bounds vector has size %zu.",
problem.get_constraint_bounds().size(),
problem.get_constraint_lower_bounds().size(),
problem.get_constraint_upper_bounds().size());
}
problem.set_problem_name(problem_name);
problem.set_objective_name(objective_name);
problem.set_variable_names(std::move(var_names));
problem.set_variable_types(std::move(var_types));
problem.set_row_names(std::move(row_names));
problem.set_maximize(maximize);
// Helper function to build CSR format using double transpose (O(m+n+nnz) instead of
// O(nnz*log(nnz))) For QUADOBJ: handles upper triangular input by expanding to full symmetric
// matrix
auto build_csr_via_transpose = [](const std::vector<std::tuple<i_t, i_t, f_t>>& entries,
i_t num_rows,
i_t num_cols,
bool is_quadobj = false) {
struct CSRResult {
std::vector<f_t> values;
std::vector<i_t> indices;
std::vector<i_t> offsets;
};
if (entries.empty()) {
CSRResult result;
result.offsets.resize(num_rows + 1, 0);
return result;
}
// First transpose: build CSC format (entries sorted by column)
std::vector<std::vector<std::pair<i_t, f_t>>> csc_data(num_cols);
for (const auto& entry : entries) {
i_t row = std::get<0>(entry);
i_t col = std::get<1>(entry);
f_t val = std::get<2>(entry);
// For QUADOBJ (upper triangular), add both (row,col) and (col,row) if off-diagonal
csc_data[col].emplace_back(row, val);
if (is_quadobj && row != col) { csc_data[row].emplace_back(col, val); }
}
// Second transpose: convert CSC to CSR (entries sorted by row, columns within rows sorted)
std::vector<std::vector<std::pair<i_t, f_t>>> csr_data(num_rows);
for (i_t col = 0; col < num_cols; ++col) {
for (const auto& [row, val] : csc_data[col]) {
csr_data[row].emplace_back(col, val);
}
}
// Build final CSR format
CSRResult result;
result.offsets.reserve(num_rows + 1);
result.offsets.push_back(0);
for (i_t row = 0; row < num_rows; ++row) {
for (const auto& [col, val] : csr_data[row]) {
// While the mps format expects to optimize for 0.5 xT Q x, cuopt optimizes for xT Q x
// so we have to multiply the value by 0.5 to get the correct value.
result.values.push_back(val * 0.5);
result.indices.push_back(col);
}
result.offsets.push_back(result.values.size());
}
return result;
};
// Process QUADOBJ data if present (upper triangular format)
if (!quadobj_entries.empty()) {
// Convert quadratic objective entries to CSR format using double transpose
// QUADOBJ stores upper triangular elements, so we expand to full symmetric matrix
i_t num_vars = static_cast<i_t>(var_names.size());
auto csr_result = build_csr_via_transpose(quadobj_entries, num_vars, num_vars, true);
// Use optimized double transpose method - O(m+n+nnz) instead of O(nnz*log(nnz))
problem.set_quadratic_objective_matrix(csr_result.values.data(),
csr_result.values.size(),
csr_result.indices.data(),
csr_result.indices.size(),
csr_result.offsets.data(),
csr_result.offsets.size());
} else if (!qmatrix_entries.empty()) {
// Convert quadratic objective entries to CSR format using double transpose
// QMATRIX stores full symmetric matrix
i_t num_vars = static_cast<i_t>(var_names.size());
auto csr_result = build_csr_via_transpose(qmatrix_entries, num_vars, num_vars, false);
// Use optimized double transpose method - O(m+n+nnz) instead of O(nnz*log(nnz))
problem.set_quadratic_objective_matrix(csr_result.values.data(),
csr_result.values.size(),
csr_result.indices.data(),
csr_result.indices.size(),
csr_result.offsets.data(),
csr_result.offsets.size());
}
}
template <typename i_t, typename f_t>
std::vector<char> mps_parser_t<i_t, f_t>::file_to_string(const std::string& file)
{
// raft::common::nvtx::range fun_scope("file to string");
#ifdef MPS_PARSER_WITH_BZIP2
if (file.size() > 4 && file.substr(file.size() - 4, 4) == ".bz2") {
return bz2_file_to_string(file);
}
#endif // MPS_PARSER_WITH_BZIP2
#ifdef MPS_PARSER_WITH_ZLIB
if (file.size() > 3 && file.substr(file.size() - 3, 3) == ".gz") {
return zlib_file_to_string(file);
}
#endif // MPS_PARSER_WITH_ZLIB
// Faster than using C++ I/O
std::unique_ptr<FILE, FcloseDeleter> fp{fopen(file.c_str(), "r")};
mps_parser_expects(fp != nullptr,
error_type_t::ValidationError,
"Error opening MPS file! Given path: %s",
mps_file.c_str());
mps_parser_expects(fseek(fp.get(), 0L, SEEK_END) == 0,
error_type_t::ValidationError,
"File browsing MPS file! Given path: %s",
mps_file.c_str());
const long bufsize = ftell(fp.get());
mps_parser_expects(bufsize != -1L,
error_type_t::ValidationError,
"File browsing MPS file! Given path: %s",
mps_file.c_str());
std::vector<char> buf(bufsize + 1);
rewind(fp.get());
mps_parser_expects(fread(buf.data(), sizeof(char), bufsize, fp.get()) == bufsize,
error_type_t::ValidationError,
"Error reading MPS file! Given path: %s",
mps_file.c_str());
buf[bufsize] = '\0';
return buf;
}
template <typename i_t, typename f_t>
void mps_parser_t<i_t, f_t>::parse_string(char* buf)
{
// raft::common::nvtx::range fun_scope("parse string");
// Faster than C++ std::get_line
char* saveptr = nullptr;
char* c_line = strtok_r(buf, "\n", &saveptr);
bool skip_line = false;
mps_parser_expects(c_line != nullptr,
error_type_t::ValidationError,
"Error parsing MPS file! No line return found (\"\\n\")");
do {
std::string_view line(c_line);
// ignore empty lines and comments
if (line.empty() || line[0] == '*' || line[0] == '$' || line[0] == '\n' || line[0] == '\r') {
continue;
}
// these lines mark the start of a particular "section"
if (line[0] != ' ') {
skip_line = false;
if (line.find("NAME", 0, 4) == 0) {
encountered_sections.insert("NAME");
auto name_start = line.find_first_not_of(" \t", 4);
if (name_start != std::string::npos) {
// max of 8 chars allowed
if (fixed_mps_format) {
problem_name = std::string(trim(line.substr(name_start, 8)));
} else {
std::stringstream ss{std::string(line)};
ss.seekg(name_start);
ss >> problem_name;
}
}
} else if (line.find("ROWS", 0, 4) == 0) {
encountered_sections.insert("ROWS");
inside_rows_ = true;
inside_columns_ = false;
inside_rhs_ = false;
inside_bounds_ = false;
inside_objsense_ = false;
inside_ranges_ = false;
inside_objname_ = false;
} else if (line.find("COLUMNS", 0, 7) == 0) {
encountered_sections.insert("COLUMNS");
inside_rows_ = false;
inside_columns_ = true;
inside_rhs_ = false;
inside_bounds_ = false;
inside_objsense_ = false;
inside_ranges_ = false;
inside_objname_ = false;
A_indices.resize(row_names.size());
A_values.resize(row_names.size());
b_values.resize(row_names.size());
// Needed if not all rows are mentioned in RHS
std::fill(b_values.begin(), b_values.end(), f_t(0));
} else if (line.find("RHS", 0, 3) == 0) {
encountered_sections.insert("RHS");
inside_rows_ = false;
inside_columns_ = false;
inside_rhs_ = true;
inside_bounds_ = false;
inside_objsense_ = false;
inside_ranges_ = false;
inside_objname_ = false;
} else if (line.find("BOUNDS", 0, 6) == 0) {
encountered_sections.insert("BOUNDS");
inside_rows_ = false;
inside_columns_ = false;
inside_rhs_ = false;
inside_bounds_ = true;
inside_objsense_ = false;
inside_ranges_ = false;
inside_objname_ = false;
variable_lower_bounds.resize(var_names.size());
variable_upper_bounds.resize(var_names.size());
std::fill(variable_lower_bounds.begin(), variable_lower_bounds.end(), f_t(0));
std::fill(variable_upper_bounds.begin(),
variable_upper_bounds.end(),
+std::numeric_limits<f_t>::infinity());
} else if (line.find("RANGES", 0, 6) == 0) {
encountered_sections.insert("RANGES");
inside_rows_ = false;
inside_columns_ = false;
inside_rhs_ = false;
inside_bounds_ = false;
inside_objsense_ = false;
inside_ranges_ = true;
inside_objname_ = false;
ranges_values.resize(row_types.size());
std::fill(ranges_values.begin(), ranges_values.end(), unset_range_value);
} else if (line.find("OBJSENSE", 0, 8) == 0) {
// Optimization direction is on same line
if (!std::none_of(line.begin() + 8, line.end(), ::isalpha)) {
parse_objsense(line);
continue;
}
encountered_sections.insert("OBJSENSE");
inside_rows_ = false;
inside_columns_ = false;
inside_rhs_ = false;
inside_bounds_ = false;
inside_ranges_ = false;
inside_objname_ = false;
inside_objsense_ = true;
} else if (line.find("OBJNAME", 0, 7) == 0) {
encountered_sections.insert("OBJNAME");
// Objective name is on same line
if (!std::none_of(line.begin() + 7, line.end(), ::isalpha)) {
parse_objname(line);
continue;
}
inside_rows_ = false;
inside_columns_ = false;
inside_rhs_ = false;
inside_bounds_ = false;
inside_ranges_ = false;
inside_objname_ = true;
inside_objsense_ = false;
} else if (line.find("QUADOBJ", 0, 7) == 0) {
encountered_sections.insert("QUADOBJ");
inside_rows_ = false;
inside_columns_ = false;
inside_rhs_ = false;
inside_bounds_ = false;
inside_ranges_ = false;
inside_objname_ = false;
inside_objsense_ = false;
inside_qmatrix_ = false;
inside_quadobj_ = true;
} else if (line.find("QMATRIX", 0, 7) == 0) {
encountered_sections.insert("QMATRIX");
inside_rows_ = false;
inside_columns_ = false;
inside_rhs_ = false;
inside_bounds_ = false;
inside_ranges_ = false;
inside_objname_ = false;
inside_objsense_ = false;
inside_quadobj_ = false;
inside_qmatrix_ = true;
} else if (line.find("ENDATA", 0, 6) == 0) {
encountered_sections.insert("ENDATA");
break;
}
// treating lazy constraints as normal constraints
else if (line.find("LAZYCONS", 0, 8) == 0) {
encountered_sections.insert("LAZYCONS");
inside_rows_ = true;
inside_columns_ = false;
inside_rhs_ = false;
inside_bounds_ = false;
inside_objsense_ = false;
inside_ranges_ = false;
inside_objname_ = false;
inside_quadobj_ = false;
inside_qmatrix_ = false;
} else {
mps_parser_expects(false,
error_type_t::ValidationError,
"Invalid named block found! Line=%s",
std::string(line).c_str());
}
} else if (skip_line) {
continue;
} else if (inside_rows_) {
parse_rows(line);
} else if (inside_columns_) {
parse_columns(line);
} else if (inside_rhs_) {
parse_rhs(line);
} else if (inside_bounds_) {
parse_bounds(line);
} else if (inside_ranges_) {
parse_ranges(line);
} else if (inside_objsense_) {
parse_objsense(line);
} else if (inside_objname_) {
parse_objname(line);
} else if (inside_quadobj_) {
parse_quad(line, true);
} else if (inside_qmatrix_) {
parse_quad(line, false);
} else {
mps_parser_expects(false,
error_type_t::ValidationError,
"Ended up at a bad parser state! Line=%s",
std::string(line).c_str());
}
} while ((c_line = strtok_r(nullptr, "\n", &saveptr)) != nullptr);
mps_parser_expects(!objective_name.empty(), error_type_t::ValidationError, "No objective found!");
mps_parser_expects(
encountered_sections.count("ROWS"), error_type_t::ValidationError, "ROWS section is missing");
mps_parser_expects(encountered_sections.count("COLUMNS"),
error_type_t::ValidationError,
"COLUMNS section is missing");
mps_parser_expects(
encountered_sections.count("RHS"), error_type_t::ValidationError, "RHS section is missing");
// Those sections are mandatory according to the MPS format specification, however some test cases
// rely on their absence Emit a warning in this case
if (!encountered_sections.count("NAME")) { printf("NAME section is missing"); }
if (!encountered_sections.count("ENDATA")) { printf("ENDATA section is missing"); }
if (variable_upper_bounds.size() == 0) // No variables bounds given, add the default values
{
variable_lower_bounds.resize(var_names.size());
variable_upper_bounds.resize(var_names.size());
std::fill(variable_lower_bounds.begin(), variable_lower_bounds.end(), f_t(0));
std::fill(variable_upper_bounds.begin(),
variable_upper_bounds.end(),
+std::numeric_limits<f_t>::infinity());
}
mps_parser_expects(variable_lower_bounds.size() == variable_upper_bounds.size() &&
variable_upper_bounds.size() == var_names.size(),
error_type_t::ValidationError,
"MPS Parser Internal Error - Please contact cuOpt team");
// Set all integer variables with bounds unspecified to [0, 1]
// Also bounds sanity check
for (i_t i = 0; i < var_names.size(); ++i) {
if (!bounds_defined_for_var_id.count(i) && var_types[i] == 'I') {
variable_lower_bounds[i] = 0;
variable_upper_bounds[i] = 1;
}
if (variable_lower_bounds[i] > variable_upper_bounds[i]) {
printf("WARNING: Variable %d has crossing bounds: %f > %f\n",
i,
variable_lower_bounds[i],
variable_upper_bounds[i]);
}
}
}
template <typename i_t, typename f_t>
mps_parser_t<i_t, f_t>::mps_parser_t(mps_data_model_t<i_t, f_t>& problem,
const std::string& file,
bool _fixed_mps_format)
: mps_file{file}, fixed_mps_format(_fixed_mps_format)
{
// raft::common::nvtx::range fun_scope("mps parser");
std::vector<char> buf = file_to_string(file);
parse_string(buf.data());
fill_problem(problem);
}
template <typename i_t, typename f_t>
void mps_parser_t<i_t, f_t>::parse_rows(std::string_view line)
{
// raft::common::nvtx::range fun_scope("parse rows");
RowType type;
std::string name;
if (fixed_mps_format) {
type = static_cast<RowType>(line[1]);
name = trim(line.substr(4, 8)); // max of 8 chars allowed
} else {
std::stringstream ss{std::string(line)};
char read_word;
ss >> read_word;
type = static_cast<RowType>(read_word);
ss >> name;
}
if (type == Objective) {
// Keep only the first name or OBJNAME since it was set before
if (objective_name.empty())
objective_name = name;
else
ignored_objective_names.emplace(name);
// If we wanted to strictly follow MPS definition: a new objective row ('N') should be treated
// as an unbounded constraints, aka an extra contraints row with lower bound -infinity and upper
// bound +infinity. Most solver ignore it to simplify the constraint matrix. We keep
// it in record as ignored to not consider finding it in COLUMNS section as an error.
return;
}
mps_parser_expects(row_names_map.find(name) == row_names_map.end(),
error_type_t::ValidationError,
"Duplicate row named '%s' found! line=%s",
name.c_str(),
std::string(line).c_str());
auto n_rows = row_names.size();
row_names.push_back(name);
row_names_map.insert(std::make_pair(name, n_rows));
row_types.push_back(type);
}
template <typename i_t, typename f_t>
i_t mps_parser_t<i_t, f_t>::parse_column_var_name(std::string_view line)
{
// raft::common::nvtx::range fun_scope("parse columns var name");
std::string_view var_name;
i_t pos;
if (fixed_mps_format) {
mps_parser_expects(line.size() >= 25,
error_type_t::ValidationError,
"COLUMNS should have atleast 3 entities! line=%s",
std::string(line).c_str());
var_name = trim(line.substr(4, 8)); // max of 8 chars allowed
pos = 14;
} else {
i_t end_var = 0;
var_name = get_next_string(line, pos, end_var);
pos = end_var;
}
if (line.find("\'MARKER\'") != std::string::npos) {
if (line.find("INTORG") != std::string::npos) {
mps_parser_expects(!inside_intcapture_,
error_type_t::ValidationError,
"Cannot capture an int section while already capturing an int section");
inside_intcapture_ = true;
}
if (line.find("INTEND") != std::string::npos) {
mps_parser_expects(inside_intcapture_,
error_type_t::ValidationError,
"Cannot stop int capture when a previous capture is not started");
inside_intcapture_ = false;
}
return -1;
}
char var_type = inside_intcapture_ ? 'I' : 'C';
if (!var_names.empty()) {
const auto& last = var_names.back();
if (last != var_name) {
mps_parser_expects(var_names_map.find(std::string(var_name)) == var_names_map.end(),
error_type_t::ValidationError,
"All rows for the column (%s) should occur contiguously! line=%s",
std::string(var_name).c_str(),
std::string(line).c_str());
var_names.emplace_back(var_name);
var_types.emplace_back(var_type);
var_names_map.insert(std::make_pair(std::string(var_name), var_names.size() - 1));
c_values.emplace_back(f_t(0));
}
} else {
var_names.emplace_back(var_name);
var_types.emplace_back(var_type);
var_names_map.insert(std::make_pair(var_name, var_names.size() - 1));
c_values.emplace_back(f_t(0));
}
return pos;
}
template <typename i_t, typename f_t>
void mps_parser_t<i_t, f_t>::parse_column_row_and_value(std::string_view line, i_t pos)
{
// raft::common::nvtx::range fun_scope("parse column row and value");
auto var_id = var_names.size() - 1;
if (fixed_mps_format) {
pos = read_row_and_value(line, pos, var_id);
if (pos == -1) return;
pos = 39;
} else {
pos = read_row_and_value(line, pos, var_id);
if (pos == -1) return;
}
if (line.find_last_not_of(" \r\t\n") > pos) { read_row_and_value(line, pos, var_id); }
}
template <typename i_t, typename f_t>
void mps_parser_t<i_t, f_t>::parse_columns(std::string_view line)
{
// raft::common::nvtx::range fun_scope("parse columns");
i_t pos;
if ((pos = parse_column_var_name(line)) == -1) return;
parse_column_row_and_value(line, pos);
}
template <typename i_t, typename f_t>
std::tuple<std::string_view, std::string_view, i_t> mps_parser_t<i_t, f_t>::parse_row_name_and_num(
std::string_view line, i_t start)
{
// raft::common::nvtx::range fun_scope("parse_row_name_and_num");
std::string_view row_name;
std::string_view num;
if (fixed_mps_format) {
row_name = trim(line.substr(start, 8)); // max of 8 chars allowed
num = line.substr(start + 10, 12); // max of 12 chars for numerical values
if (row_name[0] == '$') return std::tuple("", "", -1);
} else {
i_t pos;
row_name = get_next_string(line, pos, start);
if (row_name[0] == '$') return std::tuple("", "", -1);
num = get_next_string(line, pos, start);
}
return std::tuple(row_name, num, start);
}
template <typename i_t, typename f_t>
void mps_parser_t<i_t, f_t>::insert_row_name_and_value(std::string_view line,
std::string_view row_name,
std::string_view num,
i_t var_id)
{
// raft::common::nvtx::range fun_scope("insert_row_name_and_value");
static_assert(std::is_same_v<f_t, float> || std::is_same_v<f_t, double>,
"f_t must be float or double");
// Value for an ignored objective, can just skip it
if (ignored_objective_names.find(std::string(row_name)) != ignored_objective_names.end()) return;
f_t val;
mps_parser_no_except(
if constexpr (std::is_same_v<f_t, float>) {
val = std::stof(std::string(num));
} else if constexpr (std::is_same_v<f_t, double>) { val = std::stod(std::string(num)); },
error_type_t::ValidationError,
"Bad value found for row=%s in COLUMNS! line=%s. Num is %s",
std::string(row_name).c_str(),