Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-2022]
os: [ubuntu-24.04, windows-2022]
cuda: ["12.4.0", "12.5.0", "12.6.0", "12.8.0", "12.9.0", "13.0.0", "13.1.0"]
runs-on: ${{ matrix.os }}

Expand Down
94 changes: 87 additions & 7 deletions src/mps_parser.c
Original file line number Diff line number Diff line change
Expand Up @@ -167,13 +167,29 @@ typedef struct
char *end_pos;
} FastLineReader;

/* Case-insensitive suffix match; suffix must be lowercase. */
static bool has_suffix(const char *s, const char *suffix)
{
size_t n = strlen(s);
size_t k = strlen(suffix);
if (n < k)
return false;
s += n - k;
for (size_t i = 0; i < k; ++i)
{
if (tolower((unsigned char)s[i]) != suffix[i])
return false;
}
return true;
}

static FastLineReader *fast_reader_open(const char *filename)
{
FastLineReader *reader = safe_calloc(1, sizeof(FastLineReader));

reader->buffer = safe_malloc(READER_BUFFER_SIZE);

if (strlen(filename) > 3 && strcmp(filename + strlen(filename) - 3, ".gz") == 0)
if (has_suffix(filename, ".gz"))
{
reader->is_gz = true;
reader->handle.gz_f = gzopen(filename, "rb");
Expand Down Expand Up @@ -307,6 +323,7 @@ typedef struct

NameMap row_map;
NameMap col_map;
NameMap free_row_map; /* N rows other than the objective; their entries are ignored */

CooMatrix coo_matrix;
BufferedRow *buffered_rows;
Expand Down Expand Up @@ -429,6 +446,13 @@ lp_problem_t *read_mps_file(const char *filename)
MpsParserState state = {0};
MpsSection current_section = SEC_NONE;
bool rows_finalized = false;
bool seen_rows = false;

if (!has_suffix(filename, ".mps") && !has_suffix(filename, ".mps.gz"))
{
fprintf(stderr, "ERROR: %s is not an MPS file; only .mps and .mps.gz are supported.\n", filename);
return NULL;
}

FastLineReader *reader = fast_reader_open(filename);
if (!reader)
Expand All @@ -439,6 +463,7 @@ lp_problem_t *read_mps_file(const char *filename)

namemap_init(&state.row_map, 1024);
namemap_init(&state.col_map, 1024);
namemap_init(&state.free_row_map, 16);

char line[4096];
while (fast_reader_gets(reader, line, sizeof(line)))
Expand Down Expand Up @@ -523,6 +548,8 @@ lp_problem_t *read_mps_file(const char *filename)
}

current_section = next_section;
if (current_section == SEC_ROWS)
seen_rows = true;
if (current_section == SEC_ENDATA)
break;

Expand Down Expand Up @@ -577,6 +604,14 @@ lp_problem_t *read_mps_file(const char *filename)

fast_reader_close(reader);

/* Unrecognized lines outside any section are skipped, so a file in another
* format (e.g. LP) would otherwise parse as an empty model. */
if (!state.error_flag && !seen_rows)
{
fprintf(stderr, "ERROR: No ROWS section found in %s; is it an MPS file?\n", filename);
state.error_flag = 1;
}

if (state.error_flag)
{
fprintf(stderr, "ERROR: Failed to parse MPS file.\n");
Expand Down Expand Up @@ -679,7 +714,12 @@ static int finalize_rows(MpsParserState *state)
continue;

char type = state->buffered_rows[i].type;
if (type == 'E' || type == 'L' || type == 'G')
if (type == 'N')
{
if (namemap_put(&state->free_row_map, state->buffered_rows[i].name) == -1)
return -1;
}
else if (type == 'E' || type == 'L' || type == 'G')
{
size_t current_size = state->row_map.size;
if (current_size >= state->constraint_capacity)
Expand All @@ -691,6 +731,11 @@ static int finalize_rows(MpsParserState *state)
namemap_put(&state->row_map, state->buffered_rows[i].name);
state->constraint_types[current_size] = type;
}
else
{
fprintf(stderr, "ERROR: Row %s has unknown type %c in ROWS section.\n", state->buffered_rows[i].name, type);
return -1;
}
}
size_t num_constraints = state->row_map.size;
if (num_constraints > 0)
Expand Down Expand Up @@ -721,6 +766,11 @@ static int finalize_rows(MpsParserState *state)
return 0;
}

static bool is_free_row(const MpsParserState *state, const char *name)
{
return namemap_get(&state->free_row_map, name) != -1;
}

static int parse_columns_section(MpsParserState *state, char **tokens, int n_tokens)
{
if (n_tokens < 2)
Expand Down Expand Up @@ -791,6 +841,11 @@ static int parse_columns_section(MpsParserState *state, char **tokens, int n_tok
return -1;
}
}
else if (!is_free_row(state, row_name))
{
fprintf(stderr, "ERROR: Row %s in COLUMNS section is not declared in ROWS.\n", row_name);
return -1;
}
}
}
return 0;
Expand All @@ -804,18 +859,29 @@ static bool is_known_row(const MpsParserState *state, const char *name)
{
if (state->objective_row_name && strcmp(name, state->objective_row_name) == 0)
return true;
return namemap_get(&state->row_map, name) != -1;
return namemap_get(&state->row_map, name) != -1 || is_free_row(state, name);
}

static int row_data_start(const MpsParserState *state, char **tokens, int n_tokens)
// Returns -1 when the fields after the set name are not (row, value) pairs,
// e.g. a line without a set name whose row is not declared in ROWS.
static int row_data_start(const MpsParserState *state, char **tokens, int n_tokens, const char *section)
{
return (n_tokens > 0 && is_known_row(state, tokens[0])) ? 0 : 1;
int start = (n_tokens > 0 && is_known_row(state, tokens[0])) ? 0 : 1;
if ((n_tokens - start) % 2 != 0)
{
fprintf(stderr, "ERROR: Malformed %s line starting with %s (undeclared row?).\n", section, tokens[0]);
return -1;
}
return start;
}

static int parse_rhs_section(MpsParserState *state, char **tokens, int n_tokens)
{
int start = row_data_start(state, tokens, n_tokens, "RHS");
if (start < 0)
return -1;

for (int i = row_data_start(state, tokens, n_tokens); i + 1 < n_tokens; i += 2)
for (int i = start; i + 1 < n_tokens; i += 2)
{
const char *row_name = tokens[i];
double value = atof(tokens[i + 1]);
Expand All @@ -840,15 +906,23 @@ static int parse_rhs_section(MpsParserState *state, char **tokens, int n_tokens)
state->constraint_upper_bounds[row_idx] = value;
}
}
else if (!is_free_row(state, row_name))
{
fprintf(stderr, "ERROR: Row %s in RHS section is not declared in ROWS.\n", row_name);
return -1;
}
}
}
return 0;
}

static int parse_ranges_section(MpsParserState *state, char **tokens, int n_tokens)
{
int start = row_data_start(state, tokens, n_tokens, "RANGES");
if (start < 0)
return -1;

for (int i = row_data_start(state, tokens, n_tokens); i + 1 < n_tokens; i += 2)
for (int i = start; i + 1 < n_tokens; i += 2)
{
const char *row_name = tokens[i];
double range_val = atof(tokens[i + 1]);
Expand Down Expand Up @@ -880,6 +954,11 @@ static int parse_ranges_section(MpsParserState *state, char **tokens, int n_toke
}
}
}
else if (!is_known_row(state, row_name))
{
fprintf(stderr, "ERROR: Row %s in RANGES section is not declared in ROWS.\n", row_name);
return -1;
}
}
return 0;
}
Expand Down Expand Up @@ -990,6 +1069,7 @@ static void free_parser_state(MpsParserState *state)

namemap_free(&state->row_map);
namemap_free(&state->col_map);
namemap_free(&state->free_row_map);

if (state->buffered_rows)
{
Expand Down
70 changes: 70 additions & 0 deletions test/test_read_mps.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,3 +324,73 @@ def test_read_unsupported_section_raises(tmp_path):
"""
with pytest.raises(Exception):
_read_text(tmp_path, "quadobj.mps", MPS_QUADOBJ)



# The same LP as MPS_MIN, in CPLEX LP format
LP_MIN = """\\ TESTLP
Minimize
COST: X1 + X2
Subject To
R1: X1 + 2 X2 = 5
R2: X2 <= 2
R3: 3 X1 + 2 X2 <= 8
End
"""


@pytest.mark.parametrize("name", ["min.lp", "min.txt", "min"])
def test_read_non_mps_extension_raises(tmp_path, name):
"""
Only .mps and .mps.gz files are read; any other extension is rejected
before the file is parsed, even if its content is valid MPS.
"""
with pytest.raises(RuntimeError):
_read_text(tmp_path, name, MPS_MIN)


def test_read_mps_extension_is_case_insensitive(tmp_path):
model = _read_text(tmp_path, "MIN.MPS", MPS_MIN)
_check_min_model_data(model)


@pytest.mark.parametrize("text", [LP_MIN, "", "hello world\n"])
def test_read_non_mps_content_raises(tmp_path, text):
"""
A .mps file without a ROWS section is not MPS and must raise instead
of being read as an empty model.
"""
with pytest.raises(RuntimeError):
_read_text(tmp_path, "bad.mps", text)


# A second N row is a free row: its entries are ignored, not an error.
MPS_FREE_ROW = (
MPS_MIN.replace(" L R3\n", " L R3\n N AUX\n")
.replace(" X1 R3 3.0\n", " X1 R3 3.0 AUX 9.0\n")
.replace(" RHS R3 8.0\n", " RHS R3 8.0 AUX 1.0\n")
)


def test_read_free_row_is_ignored(tmp_path):
model = _read_text(tmp_path, "free.mps", MPS_FREE_ROW)
_check_min_model_data(model)


@pytest.mark.parametrize(
"old, new",
[
(" X1 R3 3.0\n", " X1 R4 3.0\n"), # COLUMNS
(" RHS R3 8.0\n", " RHS R4 8.0\n"), # RHS
(" RHS R3 8.0\n", " R4 8.0\n"), # RHS, no set name
("ENDATA\n", "RANGES\n RNG R4 1.0\nENDATA\n"), # RANGES
(" L R3\n", " X R3\n"), # unknown row type
],
)
def test_read_undeclared_row_raises(tmp_path, old, new):
"""
An entry for a row not declared in ROWS must raise instead of being
silently dropped.
"""
with pytest.raises(RuntimeError):
_read_text(tmp_path, "undeclared.mps", MPS_MIN.replace(old, new))
Loading