lp-ip-craft-native 0.34.0

Native Rust LP/MIP engine: dual revised simplex on a sparse LU factorization, presolve, cuts and branch-and-bound
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
//! Exact rational reconstruction of a nearby feasible point with fixed integers.
//! A rational witness may exist when no exactly feasible binary64 display point does.
//!
//! Effort is bounded by limb operations of the exact arithmetic (see
//! [`crate::rational::work`]), not by wall time, so whether a certificate is
//! found does not depend on machine speed or load.
use crate::{
    Budget,
    rational::{self, Rat},
};
use lp_ip_craft::{Model, Sense};
use std::cmp::Ordering;
pub(crate) struct Witness {
    pub upper: f64,
    pub point: Vec<f64>,
}
/// Limb operations allowed for one witness attempt (the largest public-model
/// attempt measured needs about 7e4).
pub(crate) const ATTEMPT_WORK: u64 = 8_000_000;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Outcome {
    #[default]
    NotAttempted,
    Dense,
    Sparse,
    ModelSize,
    WorkLimit,
    Interrupted,
    FreeColumns,
    InconsistentRows,
    Bound,
    Row,
    Arithmetic,
}

impl Outcome {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NotAttempted => "not_attempted",
            Self::Dense => "dense",
            Self::Sparse => "sparse",
            Self::ModelSize => "model_size",
            Self::WorkLimit => "work_limit",
            Self::Interrupted => "interrupted",
            Self::FreeColumns => "free_columns",
            Self::InconsistentRows => "inconsistent_rows",
            Self::Bound => "bound",
            Self::Row => "row",
            Self::Arithmetic => "arithmetic",
        }
    }
}

struct ExactWork<'a, 'b> {
    budget: &'a Budget<'b>,
    limit: u64,
    outcome: Outcome,
}

impl ExactWork<'_, '_> {
    fn stopped(&mut self) -> bool {
        self.outcome = if rational::work() >= self.limit {
            Outcome::WorkLimit
        } else if self.budget.stop().is_some() {
            Outcome::Interrupted
        } else {
            return false;
        };
        true
    }

    fn fail<T>(&mut self, outcome: Outcome) -> Option<T> {
        self.outcome = outcome;
        None
    }
}

/// Try an exactly feasible rational completion with the integer choices fixed.
pub(crate) fn upper(
    model: &Model,
    x: &[f64],
    budget: &Budget<'_>,
    limit: u64,
) -> (Option<Witness>, u64, Outcome) {
    rational::reset_work();
    let mut work = ExactWork {
        budget,
        limit,
        outcome: Outcome::Arithmetic,
    };
    let witness = reconstruct(model, x, &mut work);
    (witness, rational::work(), work.outcome)
}

fn reconstruct(model: &Model, x: &[f64], work: &mut ExactWork<'_, '_>) -> Option<Witness> {
    if model.n() > 8192 || model.m() > 4096 || model.nnz() > 100_000 {
        return work.fail(Outcome::ModelSize);
    }
    if work.stopped() {
        return None;
    }
    let mut point = Vec::with_capacity(model.n());
    let mut free = Vec::new();
    for (j, &value) in x.iter().enumerate() {
        let (l, u) = (model.variables().lower[j], model.variables().upper[j]);
        let v = if model.kinds()[j].is_integral() {
            value.round()
        } else if l.is_finite() && (value - l).abs() <= 1e-8 * (1. + l.abs()) {
            l
        } else if u.is_finite() && (value - u).abs() <= 1e-8 * (1. + u.abs()) {
            u
        } else {
            free.push(j);
            value
        };
        point.push(Rat::from(v)?);
    }
    if free.len() <= 64 && model.m() <= 1024 && model.nnz() <= 20000 {
        let rows = (0..model.m()).collect::<Vec<_>>();
        eliminate(model, x, &rows, &free, &mut point, work)?;
        return verify(model, &point, work, Outcome::Dense);
    }

    // The dense solver caps the dimension of its elimination. Time/flow
    // definitions often leave many continuous columns, but fixing the discrete
    // choices removes most of the dependencies before elimination.
    let (mut point, components) = singleton_intervals(model, x, work)?;
    for (columns, rows) in components {
        if columns.len() > 64 {
            return work.fail(Outcome::FreeColumns);
        }
        eliminate(model, x, &rows, &columns, &mut point, work)?;
    }
    verify(model, &point, work, Outcome::Sparse)
}

type Interval = (Option<Rat>, Option<Rat>);
type Component = (Vec<usize>, Vec<usize>);

fn interval_side(v: f64) -> Option<Rat> {
    v.is_finite().then(|| Rat::from(v)).flatten()
}

/// Eliminate fixed columns and propagate exact singleton row intervals.
/// Return residual row components for independent dense elimination.
fn singleton_intervals(
    model: &Model,
    x: &[f64],
    work: &mut ExactWork<'_, '_>,
) -> Option<(Vec<Rat>, Vec<Component>)> {
    let a = model.matrix();
    let range = |i| a.pattern.indptr[i]..a.pattern.indptr[i + 1];
    let mut bounds = Vec::with_capacity(model.n());
    let mut point = Vec::with_capacity(model.n());
    let mut fixed = Vec::with_capacity(model.n());
    for (j, &guess) in x.iter().enumerate() {
        let lo = model.variables().lower[j];
        let hi = model.variables().upper[j];
        let integer = model.kinds()[j].is_integral();
        let value = if integer {
            guess.round()
        } else {
            guess.clamp(lo, hi)
        };
        point.push(Rat::from(value)?);
        bounds.push((interval_side(lo), interval_side(hi)));
        fixed.push(integer || lo == hi);
    }

    let mut incidence = vec![Vec::new(); model.n()];
    let mut counts = vec![0; model.m()];
    let mut queue = std::collections::VecDeque::new();
    for (row, count) in counts.iter_mut().enumerate() {
        for k in range(row) {
            let j = a.pattern.indices[k];
            if !fixed[j] && a.values[k] != 0. {
                *count += 1;
                incidence[j].push(row);
            }
        }
        if *count == 1 {
            queue.push_back(row);
        }
    }
    while let Some(row) = queue.pop_front() {
        if work.stopped() {
            return None;
        }
        if counts[row] != 1 {
            continue;
        }
        let mut column = None;
        let mut offset = Rat::zero();
        for k in range(row) {
            let j = a.pattern.indices[k];
            let coef = Rat::from(a.values[k])?;
            if coef.is_zero() {
                continue;
            }
            if fixed[j] {
                offset = offset.add(&coef.mul(&point[j])?)?;
            } else {
                column = Some((j, coef, a.values[k] < 0.));
            }
        }
        let (j, coef, negative) = column?;
        let mut sides = [model.rows().lower[row], model.rows().upper[row]];
        if negative {
            sides.swap(0, 1);
        }
        let (lo, hi): &mut Interval = &mut bounds[j];
        for (side, edge, improves) in [
            (sides[0], &mut *lo, Ordering::Greater),
            (sides[1], &mut *hi, Ordering::Less),
        ] {
            if side.is_finite() {
                let implied = Rat::from(side)?.sub(&offset)?.div(&coef)?;
                if match edge {
                    Some(current) => implied.cmp(current)? == improves,
                    None => true,
                } {
                    *edge = Some(implied);
                }
            }
        }
        if let (Some(l), Some(u)) = (&*lo, &*hi) {
            match l.cmp(u)? {
                Ordering::Greater => return work.fail(Outcome::InconsistentRows),
                Ordering::Equal => {
                    point[j] = l.clone();
                    fixed[j] = true;
                    for &next in &incidence[j] {
                        counts[next] -= 1;
                        if counts[next] == 1 {
                            queue.push_back(next);
                        }
                    }
                }
                Ordering::Less => {}
            }
        }
    }

    // Clip box freedoms (for example a terminal departure) to the proved
    // intervals. Any coupling left after this pass is handled componentwise.
    for (j, (lo, hi)) in bounds.into_iter().enumerate() {
        if fixed[j] {
            continue;
        }
        if let Some(lo) = lo {
            if point[j].cmp(&lo)? == Ordering::Less {
                point[j] = lo;
            }
        }
        if let Some(hi) = hi {
            if point[j].cmp(&hi)? == Ordering::Greater {
                point[j] = hi;
            }
        }
    }
    let mut assigned = fixed;
    let mut visited = vec![false; model.m()];
    let mut components = Vec::new();
    for j in 0..model.n() {
        if assigned[j] || incidence[j].iter().all(|&r| counts[r] < 2) {
            continue;
        }
        assigned[j] = true;
        let mut columns = vec![j];
        let mut rows = Vec::new();
        let mut next = 0;
        while let Some(&column) = columns.get(next) {
            next += 1;
            for &row in &incidence[column] {
                if visited[row] {
                    continue;
                }
                visited[row] = true;
                rows.push(row);
                for k in range(row) {
                    let other = a.pattern.indices[k];
                    if a.values[k] != 0. && !assigned[other] {
                        assigned[other] = true;
                        columns.push(other);
                    }
                }
            }
        }
        components.push((columns, rows));
    }
    Some((point, components))
}

fn eliminate(
    model: &Model,
    x: &[f64],
    rows: &[usize],
    free: &[usize],
    point: &mut [Rat],
    work: &mut ExactWork<'_, '_>,
) -> Option<()> {
    let n = free.len();
    let mut positions = vec![None; model.n()];
    for (k, &j) in free.iter().enumerate() {
        positions[j] = Some(k);
    }
    let a = model.matrix();
    let mut equations = Vec::new();
    for &i in rows {
        let activity: f64 = (a.pattern.indptr[i]..a.pattern.indptr[i + 1])
            .map(|k| a.values[k] * x[a.pattern.indices[k]])
            .sum();
        let (l, u) = (model.rows().lower[i], model.rows().upper[i]);
        let side =
            if l == u || (l.is_finite() && (activity - l).abs() <= 1e-6 * (1. + activity.abs())) {
                Some(l)
            } else if u.is_finite() && (activity - u).abs() <= 1e-6 * (1. + activity.abs()) {
                Some(u)
            } else {
                None
            };
        if let Some(rhs) = side {
            equations.push((l != u, i, rhs));
        }
    }
    equations.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    let mut basis: Vec<Option<Vec<Rat>>> = vec![None; n];
    let mut rank = 0;
    for (_, i, rhs) in equations {
        if rank == n {
            break;
        }
        if work.stopped() {
            return None;
        }
        let mut row = vec![Rat::zero(); n + 1];
        row[n] = Rat::from(rhs)?;
        for k in a.pattern.indptr[i]..a.pattern.indptr[i + 1] {
            let j = a.pattern.indices[k];
            let coefficient = Rat::from(a.values[k])?;
            if let Some(p) = positions[j] {
                row[p] = coefficient;
            } else {
                row[n] = row[n].sub(&coefficient.mul(&point[j])?)?;
            }
        }
        for p in 0..n {
            if row[p].is_zero() {
                continue;
            }
            if let Some(old) = &basis[p] {
                let v = row[p].clone();
                for k in p..=n {
                    row[k] = row[k].sub(&v.mul(&old[k])?)?;
                }
            } else {
                let v = row[p].clone();
                for value in row.iter_mut().skip(p) {
                    *value = value.div(&v)?;
                }
                basis[p] = Some(row);
                rank += 1;
                break;
            }
        }
    }
    for p in (0..n).rev() {
        if let Some(row) = &basis[p] {
            let mut v = row[n].clone();
            for k in p + 1..n {
                v = v.sub(&row[k].mul(&point[free[k]])?)?;
            }
            point[free[p]] = v;
        }
    }
    Some(())
}

fn verify(
    model: &Model,
    point: &[Rat],
    work: &mut ExactWork<'_, '_>,
    method: Outcome,
) -> Option<Witness> {
    if work.stopped() {
        return None;
    }
    let a = model.matrix();
    for (j, v) in point.iter().enumerate() {
        for (b, lower) in [
            (model.variables().lower[j], true),
            (model.variables().upper[j], false),
        ] {
            if b.is_finite() {
                let c = v.cmp(&Rat::from(b)?)?;
                if (lower && c == Ordering::Less) || (!lower && c == Ordering::Greater) {
                    return work.fail(Outcome::Bound);
                }
            }
        }
    }
    for i in 0..model.m() {
        if i % 16 == 0 && work.stopped() {
            return None;
        }
        let mut sum = Rat::zero();
        for k in a.pattern.indptr[i]..a.pattern.indptr[i + 1] {
            sum = sum.add(&Rat::from(a.values[k])?.mul(&point[a.pattern.indices[k]])?)?;
        }
        for (b, lower) in [
            (model.rows().lower[i], true),
            (model.rows().upper[i], false),
        ] {
            if b.is_finite() {
                let c = sum.cmp(&Rat::from(b)?)?;
                if (lower && c == Ordering::Less) || (!lower && c == Ordering::Greater) {
                    return work.fail(Outcome::Row);
                }
            }
        }
    }
    let sign = if model.sense() == Sense::Minimize {
        1.
    } else {
        -1.
    };
    let mut value = Rat::from(sign * model.objective_offset())?;
    for (j, v) in point.iter().enumerate() {
        value = value.add(&Rat::from(sign * model.objective()[j])?.mul(v)?)?;
    }
    let witness = Witness {
        upper: value.upper()?,
        point: point.iter().map(Rat::upper).collect::<Option<_>>()?,
    };
    if work.stopped() {
        return None;
    }
    work.outcome = method;
    Some(witness)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::NativeOptions;
    use lp_ip_craft::*;
    #[test]
    fn rational_boundary_witness_and_false_candidate() {
        let make = |upper| {
            Model::new(ModelData {
                sense: Sense::Minimize,
                objective: vec![0., 1.],
                objective_offset: 2.,
                variables: Bounds::new(vec![0., 0.], vec![1., upper]),
                kinds: vec![VariableKind::Binary, VariableKind::Continuous],
                matrix: CsrMatrix::from_dense(1, 2, &[0., 3.]).unwrap(),
                rows: Bounds::fixed(vec![1.]),
            })
            .unwrap()
        };
        let settings = NativeOptions::default();
        let cancel = CancellationToken::default();
        let budget = Budget {
            start: std::time::Instant::now(),
            settings: &settings,
            cancel: &cancel,
            pivots: 0,
        };
        let m = make(1.);
        let u = upper(&m, &[0., 1. / 3.], &budget, ATTEMPT_WORK)
            .0
            .unwrap()
            .upper;
        assert!((2. + 1. / 3. ..2. + 1. / 3. + 1e-14).contains(&u));
        assert!(crate::incumbent::upper(&m, &[0., 1. / 3.]).is_none());
        assert!(
            upper(&make(1. / 3.), &[0., 1. / 3.], &budget, ATTEMPT_WORK)
                .0
                .is_none()
        );
        assert!(
            upper(&m, &[0., 1. / 3.], &budget, 1).0.is_none(),
            "work cap"
        );
        cancel.cancel();
        assert!(upper(&m, &[0., 1. / 3.], &budget, ATTEMPT_WORK).0.is_none());
    }
}

#[cfg(test)]
mod incompatible_decimal_test {
    use super::*;
    use crate::NativeOptions;
    use lp_ip_craft::*;
    #[test]
    fn numerical_decimal_equality_is_not_an_exact_integer_certificate() {
        let model = Model::new(ModelData {
            sense: Sense::Minimize,
            objective: vec![0.; 3],
            objective_offset: 0.,
            variables: Bounds::new(vec![60., 0., 0.], vec![60., 100., 100.]),
            kinds: vec![
                VariableKind::Continuous,
                VariableKind::Integer,
                VariableKind::Integer,
            ],
            matrix: CsrMatrix::from_dense(1, 3, &[0.9, 1., -1.]).unwrap(),
            rows: Bounds::fixed(vec![0.]),
        })
        .unwrap();
        let x = [60., 0., 54.];
        assert!(
            check::evaluate(&model, &x, &Tolerances::default())
                .unwrap()
                .feasible_candidate
        );
        let s = NativeOptions::default();
        let c = CancellationToken::default();
        let b = Budget {
            start: std::time::Instant::now(),
            settings: &s,
            cancel: &c,
            pivots: 0,
        };
        assert!(upper(&model, &x, &b, ATTEMPT_WORK).0.is_none());
    }
}

#[cfg(test)]
mod sparse_tests {
    use super::*;
    use crate::NativeOptions;
    use lp_ip_craft::*;

    #[test]
    fn fixed_choices_leave_small_rational_components() {
        // One singleton definition and an independent 2x2 mixed block per
        // copy. None of the continuous coordinates sits on its box bounds.
        let copies = 30;
        let n = copies * 3 + 1;
        let mut coefficients = vec![0.; 3 * copies * n];
        let mut rhs = Vec::new();
        for i in 0..copies {
            let j = 1 + 3 * i;
            coefficients[3 * i * n] = -1.;
            coefficients[3 * i * n + j] = 3.;
            coefficients[(3 * i + 1) * n + j + 1] = 1.;
            coefficients[(3 * i + 1) * n + j + 2] = 1.;
            coefficients[(3 * i + 2) * n + j + 1] = 2.;
            coefficients[(3 * i + 2) * n + j + 2] = -1.;
            rhs.extend([0., 1., 0.]);
        }
        let model = |corrupt| {
            let mut vars = Bounds::new(vec![0.; n], vec![1.; n]);
            if corrupt {
                // Exact 1/3 exceeds this binary64 upper endpoint.
                vars.upper[1] = 1. / 3.;
            }
            let mut kinds = vec![VariableKind::Continuous; n];
            kinds[0] = VariableKind::Binary;
            let mut objective = vec![0.; n];
            objective[1] = 1.;
            Model::new(ModelData {
                sense: Sense::Minimize,
                objective,
                objective_offset: 2.,
                variables: vars,
                kinds,
                rows: Bounds::fixed(rhs.clone()),
                matrix: CsrMatrix::from_dense(rhs.len(), n, &coefficients).unwrap(),
            })
            .unwrap()
        };
        let mut x = vec![1.; n];
        for block in x[1..].chunks_mut(3) {
            block.copy_from_slice(&[1. / 3., 1. / 3., 2. / 3.]);
        }
        let settings = NativeOptions::default();
        let cancel = CancellationToken::default();
        let budget = Budget {
            start: std::time::Instant::now(),
            settings: &settings,
            cancel: &cancel,
            pivots: 0,
        };
        let (witness, _, outcome) = upper(&model(false), &x, &budget, ATTEMPT_WORK);
        assert_eq!(outcome, Outcome::Sparse);
        assert!((2. + 1. / 3. ..2. + 1. / 3. + 1e-14).contains(&witness.unwrap().upper));
        let (witness, _, outcome) = upper(&model(true), &x, &budget, ATTEMPT_WORK);
        assert!(witness.is_none());
        assert_eq!(outcome, Outcome::InconsistentRows);
        assert_eq!(upper(&model(false), &x, &budget, 1).2, Outcome::WorkLimit);
    }
}