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
//! Safe rust bindings to the CPLEX solver API.
//!
//! # Example
//! ```
//! use cplex_rs::*;
//!
//! let env = Environment::new().unwrap();
//! let mut problem = Problem::new(env, "my_prob").unwrap();
//!
//! let v0 = problem.add_variable(Variable::new(VariableType::Continuous, 1.0, 0.0, 1.0, "x0")).unwrap();
//! let v1 = problem.add_variable(Variable::new(VariableType::Continuous, 10.0, 0.0, 1.0, "x1")).unwrap();
//! let c0 = problem.add_constraint(Constraint::new(ConstraintType::GreaterThanEq, 0.3, None, vec![(v0, 1.0)])).unwrap();
//! let c1 = problem.add_constraint(Constraint::new(ConstraintType::Eq, 1.0, None, vec![(v0, 1.0), (v1, 1.0)])).unwrap();
//!
//! let solution = problem.set_objective_type(ObjectiveType::Maximize)
//!    .unwrap()
//!    .solve_as(ProblemType::Linear)
//!    .unwrap();
//!
//! assert_eq!(solution.variable_value(v0), 0.3);
//! assert_eq!(solution.variable_value(v1), 0.7);
//! ```

pub mod constants;
mod constraints;
mod environment;
pub mod errors;
pub mod parameters;
mod solution;
mod variables;

pub use constraints::*;
pub use environment::*;
pub use errors::{Error, Result};
pub use ffi;
use ffi::{
    cpxlp, CPX_STAT_INForUNBD, CPXaddmipstarts, CPXaddrows, CPXchgobj, CPXchgobjsen,
    CPXchgprobtype, CPXcreateprob, CPXfreeprob, CPXgetobjval, CPXgetstat, CPXgetx, CPXlpopt,
    CPXmipopt, CPXnewcols, CPXwriteprob, CPXMIP_UNBOUNDED, CPXPROB_LP, CPXPROB_MILP, CPX_MAX,
    CPX_MIN, CPX_STAT_INFEASIBLE, CPX_STAT_UNBOUNDED,
};
use log::info;
pub use solution::*;
pub use variables::*;

use std::{
    ffi::{c_int, CString},
    time::Instant,
};

mod macros {
    macro_rules! cpx_lp_result {
    ( unsafe { $func:ident ( $env:expr, $lp:expr $(, $b:expr)* $(,)? ) } ) => {
        {
            let status = unsafe { $func($env, $lp $(,$b)* ) };
            if status != 0 {
                Err(errors::Error::from(errors::Cplex::from_code($env, $lp, status)))
            } else {
                Ok(())
            }
        }
    };
}

    pub(super) use cpx_lp_result;
}

/// A variable identifier, unique with respect to a given problem instance
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VariableId(usize);

impl VariableId {
    pub fn into_inner(self) -> usize {
        self.0
    }
}

/// A constraint identifier, unique with respect to a given problem instance
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ConstraintId(usize);

impl ConstraintId {
    pub fn into_inner(self) -> usize {
        self.0
    }
}

/// A CPLEX problem instance
pub struct Problem {
    inner: *mut cpxlp,
    env: Environment,
    variables: Vec<Variable>,
    constraints: Vec<Constraint>,
}

#[derive(Copy, Clone, Debug)]
pub enum ObjectiveType {
    Maximize,
    Minimize,
}

impl ObjectiveType {
    fn into_raw(self) -> c_int {
        match self {
            ObjectiveType::Minimize => CPX_MIN as c_int,
            ObjectiveType::Maximize => CPX_MAX as c_int,
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ProblemType {
    Linear,
    MixedInteger,
}

impl ProblemType {
    fn into_raw(self) -> c_int {
        match self {
            ProblemType::Linear => CPXPROB_LP as c_int,
            ProblemType::MixedInteger => CPXPROB_MILP as c_int,
        }
    }
}

impl Problem {
    /// Create a new CPLEX problem from a CPLEX environmant
    pub fn new<S>(env: Environment, name: S) -> Result<Self>
    where
        S: AsRef<str>,
    {
        let mut status = 0;
        let name =
            CString::new(name.as_ref()).map_err(|e| errors::Input::from_message(e.to_string()))?;
        let inner = unsafe { CPXcreateprob(env.0, &mut status, name.as_ptr()) };
        if inner.is_null() {
            Err(errors::Cplex::from_code(env.0, std::ptr::null(), status).into())
        } else {
            Ok(Problem {
                inner,
                env,
                variables: vec![],
                constraints: vec![],
            })
        }
    }

    /// Add a variable to the problem.
    ///
    /// The id for the Variable is returned.
    pub fn add_variable(&mut self, var: Variable) -> Result<VariableId> {
        let name = CString::new(var.name().as_bytes())
            .map_err(|e| errors::Input::from_message(e.to_string()))?;

        macros::cpx_lp_result!(unsafe {
            CPXnewcols(
                self.env.0,
                self.inner,
                1,
                &var.weight(),
                &var.lower_bound(),
                &var.upper_bound(),
                &var.type_().into_raw() as *const u8 as *const i8,
                &mut (name.as_ptr() as *mut _),
            )
        })?;

        let index = self.variables.len();
        self.variables.push(var);
        Ok(VariableId(index))
    }

    /// Add an array of variables to the problem.
    ///
    /// The id for the variables are returned, in the same order they have been given in the input.
    pub fn add_variables(&mut self, vars: Vec<Variable>) -> Result<Vec<VariableId>> {
        let names = vars
            .iter()
            .map(|v| {
                CString::new(v.name().as_bytes())
                    .map_err(|e| errors::Input::from_message(e.to_string()).into())
            })
            .collect::<Result<Vec<_>>>()?;

        let mut name_ptrs = names
            .iter()
            .map(|n| n.as_ptr() as *mut _)
            .collect::<Vec<_>>();

        let objs = vars.iter().map(|v| v.weight()).collect::<Vec<_>>();
        let lbs = vars.iter().map(|v| v.lower_bound()).collect::<Vec<_>>();
        let ubs = vars.iter().map(|v| v.upper_bound()).collect::<Vec<_>>();
        let types = vars
            .iter()
            .map(|v| v.type_().into_raw() as i8)
            .collect::<Vec<_>>();

        macros::cpx_lp_result!(unsafe {
            CPXnewcols(
                self.env.0,
                self.inner,
                vars.len() as i32,
                objs.as_ptr(),
                lbs.as_ptr(),
                ubs.as_ptr(),
                types.as_ptr(),
                name_ptrs.as_mut_ptr(),
            )
        })?;

        let indices: Vec<VariableId> = vars
            .iter()
            .enumerate()
            .map(|(idx, _)| VariableId(idx + self.variables.len()))
            .collect();
        self.variables.extend(vars);
        Ok(indices)
    }

    /// Add a constraint to the problem.
    ///
    /// The id for the constraint is returned.
    pub fn add_constraint(&mut self, constraint: Constraint) -> Result<ConstraintId> {
        let (ind, val): (Vec<c_int>, Vec<f64>) = constraint
            .weights()
            .iter()
            .filter(|(_, weight)| *weight != 0.0)
            .map(|(var_id, weight)| (var_id.0 as c_int, weight))
            .unzip();
        let nz = val.len() as c_int;
        let name = constraint
            .name()
            .map(|n| {
                CString::new(n.as_bytes()).map_err(|e| errors::Input::from_message(e.to_string()))
            })
            .transpose()?;
        macros::cpx_lp_result!(unsafe {
            CPXaddrows(
                self.env.0,
                self.inner,
                0,
                1,
                nz,
                &constraint.rhs(),
                &constraint.type_().into_raw(),
                &0,
                ind.as_ptr(),
                val.as_ptr(),
                std::ptr::null_mut(),
                &mut (name
                    .as_ref()
                    .map(|n| n.as_ptr())
                    .unwrap_or(std::ptr::null()) as *mut _),
            )
        })?;

        let index = self.constraints.len();
        self.constraints.push(constraint);
        Ok(ConstraintId(index))
    }

    /// Add an array of constraints to the problem.
    ///
    /// The id for the constraints are returned, in the same order they have been given in the input.
    pub fn add_constraints(&mut self, con: Vec<Constraint>) -> Result<Vec<ConstraintId>> {
        if con.is_empty() {
            return Err(errors::Input::from_message(
                "Called add_constraints with 0 constaints".to_owned(),
            )
            .into());
        }
        let beg = std::iter::once(0)
            .chain(con[..con.len() - 1].iter().map(|c| c.weights().len()))
            .scan(0, |state, x| {
                *state += x;
                Some(*state as i32)
            })
            .collect::<Vec<_>>();

        let (ind, val): (Vec<c_int>, Vec<f64>) = con
            .iter()
            .flat_map(|c| c.weights().iter())
            .filter(|(_, weight)| *weight != 0.0)
            .map(|(var_id, weight)| (var_id.0 as c_int, weight))
            .unzip();

        let nz = val.len() as c_int;
        let names = con
            .iter()
            .map(|c| {
                c.name()
                    .map(|n| {
                        CString::new(n.as_bytes())
                            .map_err(|e| errors::Input::from_message(e.to_string()).into())
                    })
                    .transpose()
            })
            .collect::<Result<Vec<_>>>()?;

        let mut name_ptrs = names
            .iter()
            .map(|n| {
                n.as_ref()
                    .map(|n| n.as_ptr())
                    .unwrap_or(std::ptr::null_mut()) as *mut _
            })
            .collect::<Vec<_>>();

        let rhss = con.iter().map(|c| c.rhs()).collect::<Vec<_>>();
        let senses = con.iter().map(|c| c.type_().into_raw()).collect::<Vec<_>>();

        macros::cpx_lp_result!(unsafe {
            CPXaddrows(
                self.env.0,
                self.inner,
                0,
                con.len() as i32,
                nz,
                rhss.as_ptr(),
                senses.as_ptr(),
                beg.as_ptr(),
                ind.as_ptr(),
                val.as_ptr(),
                std::ptr::null_mut(),
                name_ptrs.as_mut_ptr(),
            )
        })?;

        let indices = con
            .iter()
            .enumerate()
            .map(|(idx, _)| ConstraintId(idx + self.constraints.len()))
            .collect();
        self.constraints.extend(con);
        Ok(indices)
    }

    /// Set the objective coefficients.
    pub fn set_objective(self, ty: ObjectiveType, obj: Vec<(VariableId, f64)>) -> Result<Self> {
        let (ind, val): (Vec<c_int>, Vec<f64>) = obj
            .into_iter()
            .map(|(var_id, weight)| (var_id.0 as c_int, weight))
            .unzip();

        macros::cpx_lp_result!(unsafe {
            CPXchgobj(
                self.env.0,
                self.inner,
                ind.len() as c_int,
                ind.as_ptr(),
                val.as_ptr(),
            )
        })?;

        self.set_objective_type(ty)
    }

    /// Change the objective type. Default: `ObjectiveType::Minimize`.
    pub fn set_objective_type(self, ty: ObjectiveType) -> Result<Self> {
        macros::cpx_lp_result!(unsafe { CPXchgobjsen(self.env.0, self.inner, ty.into_raw()) })?;
        Ok(self)
    }

    /// Write the problem to a file named `name`.
    pub fn write<S>(&self, name: S) -> Result<()>
    where
        S: AsRef<str>,
    {
        let name =
            CString::new(name.as_ref()).map_err(|e| errors::Input::from_message(e.to_string()))?;

        macros::cpx_lp_result!(unsafe {
            CPXwriteprob(self.env.0, self.inner, name.as_ptr(), std::ptr::null())
        })
    }

    /// Add an initial solution to the problem.
    ///
    /// `vars` is an array of indices (i.e. the result of `prob.add_variable`) and `values` are
    /// their values.
    pub fn add_initial_soln(&mut self, vars: &[VariableId], values: &[f64]) -> Result<()> {
        if values.len() != vars.len() {
            return Err(errors::Input::from_message(
                "number of solution variables and values does not match".to_string(),
            )
            .into());
        }
        let vars = vars.iter().map(|&u| u.0 as c_int).collect::<Vec<_>>();

        macros::cpx_lp_result!(unsafe {
            CPXaddmipstarts(
                self.env.0,
                self.inner,
                1,
                vars.len() as c_int,
                &0,
                vars.as_ptr(),
                values.as_ptr(),
                &0,
                &mut std::ptr::null_mut(),
            )
        })
    }

    /// Solve the Problem, returning a `Solution` object with the
    /// result.
    pub fn solve_as(self, pt: ProblemType) -> Result<Solution> {
        macros::cpx_lp_result!(unsafe { CPXchgprobtype(self.env.0, self.inner, pt.into_raw()) })?;

        let start_optim = Instant::now();
        match pt {
            ProblemType::MixedInteger => {
                macros::cpx_lp_result!(unsafe { CPXmipopt(self.env.0, self.inner) })?
            }
            ProblemType::Linear => {
                macros::cpx_lp_result!(unsafe { CPXlpopt(self.env.0, self.inner) })?
            }
        };
        let elapsed = start_optim.elapsed();
        info!("CPLEX model solution took: {:?}", elapsed);

        let code = unsafe { CPXgetstat(self.env.0, self.inner) };
        if code as u32 == CPX_STAT_INFEASIBLE || code as u32 == CPX_STAT_INForUNBD {
            return Err(crate::errors::Cplex::Unfeasible {
                code,
                message: "Unfeasible problem".to_string(),
            }
            .into());
        }

        if code as u32 == CPX_STAT_UNBOUNDED || code as u32 == CPXMIP_UNBOUNDED {
            return Err(crate::errors::Cplex::Unbounded {
                code,
                message: "Unbounded problem".to_string(),
            }
            .into());
        }

        let mut objective_value: f64 = 0.0;
        macros::cpx_lp_result!(unsafe {
            CPXgetobjval(self.env.0, self.inner, &mut objective_value)
        })?;

        let mut variable_values = vec![0f64; self.variables.len()];
        macros::cpx_lp_result!(unsafe {
            CPXgetx(
                self.env.0,
                self.inner,
                variable_values.as_mut_ptr(),
                0,
                self.variables.len() as c_int - 1,
            )
        })?;

        Ok(Solution::new(variable_values, objective_value))
    }
}

impl Drop for Problem {
    fn drop(&mut self) {
        unsafe {
            assert_eq!(CPXfreeprob(self.env.0, &mut self.inner), 0);
        }
    }
}

#[cfg(test)]
mod test {
    use constants::INFINITY;
    use constraints::ConstraintType;

    use super::*;
    use variables::{Variable, VariableType};

    #[test]
    fn mipex1() {
        let env = Environment::new().unwrap();
        let mut problem = Problem::new(env, "mipex1").unwrap();

        let x0 = problem
            .add_variable(Variable::new(
                VariableType::Continuous,
                1.0,
                0.0,
                40.0,
                "x0",
            ))
            .unwrap();

        let x1 = problem
            .add_variable(Variable::new(
                VariableType::Continuous,
                2.0,
                0.0,
                INFINITY,
                "x1",
            ))
            .unwrap();

        let x2 = problem
            .add_variable(Variable::new(
                VariableType::Continuous,
                3.0,
                0.0,
                INFINITY,
                "x2",
            ))
            .unwrap();

        let x3 = problem
            .add_variable(Variable::new(VariableType::Integer, 1.0, 2.0, 3.0, "x3"))
            .unwrap();

        assert_eq!(x0, VariableId(0));
        assert_eq!(x1, VariableId(1));
        assert_eq!(x2, VariableId(2));
        assert_eq!(x3, VariableId(3));

        let c0 = problem
            .add_constraint(Constraint::new(
                ConstraintType::LessThanEq,
                20.0,
                None,
                vec![(x0, -1.0), (x1, 1.0), (x2, 1.0), (x3, 10.0)],
            ))
            .unwrap();

        let c1 = problem
            .add_constraint(Constraint::new(
                ConstraintType::LessThanEq,
                30.0,
                None,
                vec![(x0, 1.0), (x1, -3.0), (x2, 1.0)],
            ))
            .unwrap();

        let c2 = problem
            .add_constraint(Constraint::new(
                ConstraintType::Eq,
                0.0,
                None,
                vec![(x1, 1.0), (x3, -3.5)],
            ))
            .unwrap();

        assert_eq!(c0, ConstraintId(0));
        assert_eq!(c1, ConstraintId(1));
        assert_eq!(c2, ConstraintId(2));

        let problem = problem.set_objective_type(ObjectiveType::Maximize).unwrap();

        let solution = problem.solve_as(ProblemType::MixedInteger).unwrap();

        assert_eq!(solution.objective_value(), 122.5);
    }

    #[test]
    fn mipex1_batch() {
        let env = Environment::new().unwrap();
        let mut problem = Problem::new(env, "mipex1").unwrap();

        let vars = problem
            .add_variables(vec![
                Variable::new(VariableType::Continuous, 1.0, 0.0, 40.0, "x0"),
                Variable::new(VariableType::Continuous, 2.0, 0.0, INFINITY, "x1"),
                Variable::new(VariableType::Continuous, 3.0, 0.0, INFINITY, "x2"),
                Variable::new(VariableType::Integer, 1.0, 2.0, 3.0, "x3"),
            ])
            .unwrap();

        assert_eq!(
            vars,
            vec![VariableId(0), VariableId(1), VariableId(2), VariableId(3)]
        );

        let cons = problem
            .add_constraints(vec![
                Constraint::new(
                    ConstraintType::LessThanEq,
                    20.0,
                    None,
                    vec![
                        (vars[0], -1.0),
                        (vars[1], 1.0),
                        (vars[2], 1.0),
                        (vars[3], 10.0),
                    ],
                ),
                Constraint::new(
                    ConstraintType::LessThanEq,
                    30.0,
                    None,
                    vec![(vars[0], 1.0), (vars[1], -3.0), (vars[2], 1.0)],
                ),
                Constraint::new(
                    ConstraintType::Eq,
                    0.0,
                    None,
                    vec![(vars[1], 1.0), (vars[3], -3.5)],
                ),
            ])
            .unwrap();

        assert_eq!(
            cons,
            vec![ConstraintId(0), ConstraintId(1), ConstraintId(2)]
        );

        let problem = problem.set_objective_type(ObjectiveType::Maximize).unwrap();

        let solution = problem.solve_as(ProblemType::MixedInteger).unwrap();

        assert_eq!(solution.objective_value(), 122.5);
    }

    #[test]
    fn unfeasible() {
        let env = Environment::new().unwrap();
        let mut problem = Problem::new(env, "unfeasible").unwrap();

        let vars = problem
            .add_variables(vec![
                Variable::new(VariableType::Continuous, 1.0, 0.0, 1.0, "x0"),
                Variable::new(VariableType::Continuous, 1.0, 0.0, 1.0, "x1"),
            ])
            .unwrap();

        assert_eq!(vars, vec![VariableId(0), VariableId(1)]);

        let cons = problem
            .add_constraints(vec![
                Constraint::new(
                    ConstraintType::Eq,
                    0.0,
                    None,
                    vec![(vars[0], 1.0), (vars[1], 1.0)],
                ),
                Constraint::new(
                    ConstraintType::Eq,
                    1.0,
                    None,
                    vec![(vars[0], 1.0), (vars[1], 1.0)],
                ),
            ])
            .unwrap();

        assert_eq!(cons, vec![ConstraintId(0), ConstraintId(1)]);

        let problem = problem.set_objective_type(ObjectiveType::Maximize).unwrap();
        assert!(matches!(
            problem.solve_as(ProblemType::Linear),
            Err(errors::Error::Cplex(errors::Cplex::Unfeasible { .. }))
        ));
    }

    #[test]
    fn unbounded() {
        let env = Environment::new().unwrap();
        let mut problem = Problem::new(env, "unbounded").unwrap();

        problem
            .add_variable(Variable::new(
                VariableType::Integer,
                1.0,
                0.0,
                INFINITY,
                "x0",
            ))
            .unwrap();

        let problem = problem.set_objective_type(ObjectiveType::Maximize).unwrap();

        assert!(matches!(
            problem.solve_as(ProblemType::MixedInteger),
            Err(errors::Error::Cplex(errors::Cplex::Unbounded { .. }))
        ));
    }
}