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
extern crate lpsolve_sys as lp;
extern crate libc;
#[macro_use] extern crate bitflags;
use std::mem::transmute;
use std::io::Write;
use std::ffi::CStr;
use std::ops::Deref;
#[repr(C)]
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum Verbosity {
Critical = 1,
Severe = 2,
Important = 3,
Normal = 4,
Detailed = 5,
Full = 6,
}
#[repr(C)]
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum ConstraintType {
Le = 1,
Eq = 3,
Ge = 2,
Free = 0,
}
#[repr(C)]
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum SOSType {
Type1 = 1,
Type2 = 2,
}
#[repr(C)]
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum VarType {
Binary = 1,
Float = 0,
}
#[repr(u8)]
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum BoundsMode {
Restrictive = 1,
None = 0,
}
#[repr(C)]
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum SolveStatus {
OutOfMemory = -2,
NotRun = -1,
Optimal = 0,
Suboptimal = 1,
Infeasible = 2,
Unbounded = 3,
Degenerate = 4,
NumericalFailure = 5,
UserAbort = 6,
Timeout = 7,
Presolved = 8,
ProcFail = 9,
ProcBreak = 11,
FeasibleFound = 12,
NoFeasibleFound = 13,
}
bitflags! {
pub flags MPSOptions: ::libc::c_int {
const CRITICAL = 1,
const SEVERE = 2,
const IMPORTANT = 3,
const NORMAL = 4,
const DETAILED = 5,
const FULL = 6,
const FREE = 8,
const IBM = 16,
const NEGOBJCONST = 32,
}
}
pub struct Problem {
lprec: *mut lp::lprec,
}
macro_rules! cptr {
($e:expr) => { if $e.is_null() { None } else { Some(Problem { lprec: $e }) } }
}
unsafe extern "C" fn write_modeldata(val: *mut libc::c_void, buf: *mut libc::c_char) -> libc::c_int {
let val = transmute::<_, &mut &mut Write>(val);
let buf = CStr::from_ptr(buf);
match val.write(buf.to_bytes()) {
Ok(_) => 0,
Err(_) => 1,
}
}
impl Problem {
pub fn new(rows: libc::c_int, cols: libc::c_int) -> Option<Problem> {
let ptr = unsafe { lp::make_lp(rows, cols) };
cptr!(ptr)
}
pub fn read_lp<P: Deref<Target=CStr>, C: Deref<Target=CStr>>(path: &P, verbosity: Verbosity, initial_name: &C) -> Option<Problem> {
let ptr = unsafe { lp::read_LP(path.as_ptr() as *mut _, verbosity as libc::c_int, initial_name.as_ptr() as *mut _) };
cptr!(ptr)
}
pub fn read_freemps<P: Deref<Target=CStr>>(path: &P, options: MPSOptions) -> Option<Problem> {
let ptr = unsafe { lp::read_freeMPS(path.as_ptr() as *mut _, options.bits) };
cptr!(ptr)
}
pub fn read_fixedmps<P: Deref<Target=CStr>>(path: &P, options: MPSOptions) -> Option<Problem> {
let ptr = unsafe { lp::read_MPS(path.as_ptr() as *mut _, options.bits) };
cptr!(ptr)
}
pub fn write_lp(&self, out: &mut Write) -> bool {
1 == unsafe { lp::write_lpex(self.lprec, transmute::<_, *mut libc::c_void>(&out), write_modeldata) }
}
pub fn write_fixedmps(&self, out: &mut Write) -> bool {
self.write_mps(out, 1)
}
pub fn write_freemps(&self, out: &mut Write) -> bool {
self.write_mps(out, 2)
}
pub fn write_mps(&self, out: &mut Write, formatting: libc::c_int) -> bool {
debug_assert!(formatting == 1 || formatting == 2);
1 == unsafe { lp::MPS_writefileex(self.lprec, formatting, transmute::<_, *mut libc::c_void>(&out), write_modeldata) }
}
pub fn resize(&mut self, rows: libc::c_int, cols: libc::c_int) -> bool {
1 == unsafe { lp::resize_lp(self.lprec, rows, cols) }
}
pub fn add_column(&mut self, values: &[f64]) -> bool {
assert!(values.len() == self.num_rows() as usize + 1);
1 == unsafe { lp::add_column(self.lprec, values.as_ptr() as *mut _) }
}
pub fn add_column_scatter(&mut self, values: &[f64], indices: &[libc::c_int]) -> bool {
debug_assert!(values.len() == indices.len());
let len = std::cmp::max(values.len(), indices.len());
1 == unsafe { lp::add_columnex(self.lprec, len as libc::c_int, values.as_ptr() as *mut _, indices.as_ptr() as *mut _) }
}
pub fn get_column(&self, values: &mut [f64], column: libc::c_int) -> bool {
assert!(values.len() >= self.num_rows() as usize + 1);
1 == unsafe { lp::get_column(self.lprec, column, values.as_mut_ptr()) }
}
pub fn get_row(&self, values: &mut [f64], row: libc::c_int) -> bool {
assert!(values.len() >= self.num_cols() as usize + 1);
1 == unsafe { lp::get_row(self.lprec, row, values.as_mut_ptr()) }
}
pub fn add_constraint(&mut self, coeffs: &[f64], target: f64, kind: ConstraintType) -> bool {
assert!(coeffs.len() >= self.num_cols() as usize + 1);
1 == unsafe { lp::add_constraint(self.lprec, coeffs.as_ptr() as *mut _, kind as libc::c_int, target) }
}
pub fn add_sos_constraint(&mut self, name: &CStr, sostype: SOSType, priority: libc::c_int,
weights: &[f64], variables: &[libc::c_int]) -> bool {
let len = std::cmp::max(weights.len(), variables.len());
debug_assert!(weights.len() == variables.len());
0 != unsafe { lp::add_SOS(self.lprec, name.as_ptr() as *mut _, sostype as libc::c_int, priority,
len as libc::c_int, variables.as_ptr() as *mut _, weights.as_ptr() as *mut _) }
}
pub fn del_column(&mut self, col: libc::c_int) -> bool {
1 == unsafe { lp::del_column(self.lprec, col) }
}
pub fn del_constraint(&mut self, row: libc::c_int) -> bool {
1 == unsafe { lp::del_constraint(self.lprec, row) }
}
pub fn is_negative(&self, col: libc::c_int) -> Option<bool> {
if col > self.num_cols()+1 {
None
} else {
Some(unsafe { lp::is_negative(self.lprec, col) } == 1)
}
}
pub fn set_variable_type(&mut self, col: libc::c_int, vartype: VarType) -> bool {
1 == unsafe { lp::set_binary(self.lprec, col, vartype as libc::c_uchar) }
}
pub fn get_variable_type(&self, col: libc::c_int) -> Option<VarType> {
if col > self.num_cols()+1 {
None
} else {
let res = if unsafe { lp::is_binary(self.lprec, col) } == 1 {
VarType::Binary
} else {
VarType::Float
};
Some(res)
}
}
pub fn set_bounds(&mut self, col: libc::c_int, lower: f64, upper: f64) -> bool {
1 == unsafe { lp::set_bounds(self.lprec, col, lower, upper) }
}
pub fn set_bounds_mode(&mut self, tighten: BoundsMode) {
unsafe { lp::set_bounds_tighter(self.lprec, tighten as libc::c_uchar) };
}
pub fn get_bounds_mode(&self) -> BoundsMode {
if unsafe { lp::get_bounds_tighter(self.lprec) } == 1 {
BoundsMode::Restrictive
} else {
BoundsMode::None
}
}
pub fn set_constraint_type(&mut self, row: libc::c_int, contype: ConstraintType) -> bool {
1 == unsafe { lp::set_constr_type(self.lprec, row, contype as libc::c_int) }
}
pub fn get_constraint_type(&self, row: libc::c_int) -> Option<ConstraintType> {
if row > self.num_rows()+1 {
None
} else {
let res = unsafe { lp::get_constr_type(self.lprec, row) };
match res {
1 => Some(ConstraintType::Le),
2 => Some(ConstraintType::Ge),
3 => Some(ConstraintType::Eq),
_ => None,
}
}
}
pub fn set_unbounded(&mut self, col: libc::c_int) -> bool {
1 == unsafe { lp::set_unbounded(self.lprec, col) }
}
pub fn is_unbounded(&self, col: libc::c_int) -> Option<bool> {
if col > self.num_cols()+1 {
None
} else {
Some(unsafe { lp::is_unbounded(self.lprec, col) } == 1)
}
}
pub fn set_infinite(&mut self, infinity: f64) {
unsafe { lp::set_infinite(self.lprec, infinity) };
}
pub fn get_infinite(&self) -> f64 {
unsafe { lp::get_infinite(self.lprec) }
}
pub fn set_integer(&mut self, col: libc::c_int, must_be_integer: bool) -> bool {
1 == unsafe { lp::set_int(self.lprec, col, if must_be_integer { 1 } else { 0 }) }
}
pub fn is_integer(&self, col: libc::c_int) -> Option<bool> {
if col > self.num_cols()+1 {
None
} else {
Some(unsafe { lp::is_int(self.lprec, col) } == 1)
}
}
pub fn set_objective_function(&mut self, coeffs: &[f64]) -> bool {
assert!(coeffs.len() >= self.num_cols() as usize + 1);
1 == unsafe { lp::set_obj_fn(self.lprec, coeffs.as_ptr() as *mut _) }
}
pub fn scatter_objective_function(&mut self, coeffs: &[f64], indices: &[libc::c_int]) -> bool {
let len = std::cmp::max(coeffs.len(), indices.len());
debug_assert!(coeffs.len() == indices.len());
1 == unsafe { lp::set_obj_fnex(self.lprec, len as libc::c_int, coeffs.as_ptr() as *mut _, indices.as_ptr() as *mut _) }
}
pub fn set_constraint_range(&mut self, row: libc::c_int, range: f64) -> bool {
1 == unsafe { lp::set_rh_range(self.lprec, row, range) }
}
pub fn get_constraint_range(&self, row: libc::c_int) -> Option<f64> {
if row > self.num_rows() + 1 {
None
} else {
let delta = unsafe { lp::get_rh_range(self.lprec, row) };
if delta == self.get_infinite() {
None
} else {
Some(delta)
}
}
}
pub fn solve(&mut self) -> SolveStatus {
use SolveStatus::*;
match unsafe { lp::solve(self.lprec) } {
-2 => OutOfMemory,
-1 => NotRun,
0 => Optimal,
1 => Suboptimal,
2 => Infeasible,
3 => Unbounded,
4 => Degenerate,
5 => NumericalFailure,
6 => UserAbort,
7 => Timeout,
9 => Presolved,
10 => ProcFail,
11 => ProcBreak,
12 => FeasibleFound,
13 => NoFeasibleFound,
status => panic!("unknown solve status {}", status)
}
}
pub fn get_solution_variables<'a>(&self, vars: &'a mut [f64]) -> Option<&'a mut [f64]> {
let cols = self.num_cols();
if vars.len() < cols as usize {
None
} else {
unsafe { lp::get_variables(self.lprec, vars.as_mut_ptr()) };
Some(&mut vars[..cols as usize])
}
}
pub unsafe fn from_lprec(lprec: *mut lp::lprec) -> Problem {
Problem {
lprec: lprec
}
}
pub fn to_lprec(&self) -> *mut lp::lprec {
self.lprec
}
pub fn num_cols(&self) -> libc::c_int {
unsafe { lp::get_Ncolumns(self.lprec) }
}
pub fn num_rows(&self) -> libc::c_int {
unsafe { lp::get_Nrows(self.lprec) }
}
}
impl Drop for Problem {
fn drop(&mut self) {
unsafe { lp::delete_lp(self.lprec) }
}
}
impl Clone for Problem {
fn clone(&self) -> Problem {
let ptr = unsafe { lp::copy_lp(self.lprec) };
if ptr.is_null() {
panic!("OOM when trying to copy_lp")
}
Problem { lprec: ptr }
}
}
unsafe impl Send for Problem { }
#[cfg(test)]
mod tests {
use Problem;
#[test]
fn smoke() {
let mut lp = Problem::new(0, 0).unwrap();
assert_eq!(lp.solve(), ::SolveStatus::NotRun);
}
}