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
//! Conservative integer-domain propagation with incremental exact activities.
use crate::diagnostics::PropagationStats;
use crate::{Budget, integer_equality};
use lp_ip_craft::{Bounds, Model, Tolerances};
use std::collections::VecDeque;

struct Row {
    terms: Vec<(usize, i128)>,
    residues: Vec<Option<integer_equality::Residue>>,
    lower: Option<i128>,
    upper: Option<i128>,
    min: i128,
    max: i128,
    max_width: i128,
}
pub(crate) struct Domain {
    integers: Vec<usize>,
    rows: Vec<Row>,
    incident: Vec<Vec<(usize, i128)>>,
    lower: Vec<i128>,
    upper: Vec<i128>,
    pending: VecDeque<usize>,
    queued: Vec<bool>,
    last_changed: Vec<usize>,
    touched: Vec<usize>,
    marked: Vec<bool>,
    first: bool,
    work_limit: usize,
    statistics: Option<PropagationStats>,
}
fn floor_div(a: i128, b: i128) -> i128 {
    debug_assert!(b > 0);
    a.div_euclid(b)
}
fn ceil_div(a: i128, b: i128) -> i128 {
    -floor_div(-a, b)
}
impl Domain {
    pub fn new(model: &Model, enabled: bool, feasibility: f64) -> Self {
        Self::with_equalities(model, enabled, feasibility, None)
    }

    /// `feasibility` is the accepted row violation: an integer activity may
    /// miss a row limit by that much, so limits are rounded after widening.
    /// A right-hand side computed as `3.0000000000000004` then still admits
    /// activity 3. `tolerances` enables the residue rule on short equalities.
    pub fn with_equalities(
        model: &Model,
        enabled: bool,
        feasibility: f64,
        tolerances: Option<&Tolerances>,
    ) -> Self {
        let n = if enabled && model.is_mip() {
            model.n()
        } else {
            0
        };
        let mut domain = Self {
            integers: Vec::new(),
            rows: Vec::new(),
            incident: vec![Vec::new(); n],
            lower: model
                .variables()
                .lower
                .iter()
                .take(n)
                .map(|v| v.ceil() as i128)
                .collect(),
            upper: model
                .variables()
                .upper
                .iter()
                .take(n)
                .map(|v| v.floor() as i128)
                .collect(),
            pending: VecDeque::new(),
            queued: Vec::new(),
            last_changed: Vec::new(),
            touched: Vec::new(),
            marked: vec![false; n],
            first: true,
            work_limit: 4096,
            statistics: None,
        };
        if !enabled || !model.is_mip() {
            return domain;
        }
        domain.integers = (0..n)
            .filter(|&j| {
                model.kinds()[j].is_integral()
                    && (model.variables().lower[j].fract() != 0.
                        || model.variables().upper[j].fract() != 0.)
            })
            .collect();
        let a = model.matrix();
        for i in 0..model.m() {
            let range = a.pattern.indptr[i]..a.pattern.indptr[i + 1];
            // Each product is at most 2^62; at most usize::MAX terms means
            // every activity and activity difference fits signed i128.
            let basic = range.clone().all(|k| {
                let (j, v) = (a.pattern.indices[k], a.values[k]);
                v == 0.
                    || (model.kinds()[j].is_integral()
                        && v.fract() == 0.
                        && v.abs() <= 2_147_483_648.
                        && model.variables().lower[j].abs() <= 2_147_483_648.
                        && model.variables().upper[j].abs() <= 2_147_483_648.)
            });
            let endpoint =
                |v: f64| (v.is_finite() && v.abs() <= 1_125_899_906_842_624.).then_some(v as i128);
            let (terms, lower, upper, residues) = if basic {
                let lower = endpoint((model.rows().lower[i] - feasibility).ceil());
                let upper = endpoint((model.rows().upper[i] + feasibility).floor());
                if lower.is_none() && upper.is_none() {
                    continue;
                }
                let terms: Vec<_> = range
                    .filter(|&k| a.values[k] != 0.)
                    .map(|k| (a.pattern.indices[k], a.values[k] as i128))
                    .collect();
                let residues = match (tolerances, lower, upper) {
                    (Some(tol), Some(l), Some(u))
                        if l == u
                            && (2..=12).contains(&terms.len())
                            && model.rows().lower[i] == model.rows().upper[i]
                            && integer_equality::normalized(model, i, tol).is_some() =>
                    {
                        integer_equality::residues(&terms, l)
                    }
                    _ => Vec::new(),
                };
                (terms, lower, upper, residues)
            } else if let Some((terms, rhs)) =
                tolerances.and_then(|t| integer_equality::normalized(model, i, t))
            {
                let residues = integer_equality::residues(&terms, rhs);
                (terms, Some(rhs), Some(rhs), residues)
            } else {
                continue;
            };
            let (mut min, mut max) = (0, 0);
            let mut max_width = 0;
            for &(j, v) in &terms {
                let (l, u) = (domain.lower[j], domain.upper[j]);
                max_width = max_width.max(v.abs() * (u - l));
                min += v * if v > 0 { l } else { u };
                max += v * if v > 0 { u } else { l };
                domain.incident[j].push((domain.rows.len(), v));
            }
            domain.rows.push(Row {
                terms,
                residues,
                lower,
                upper,
                min,
                max,
                max_width,
            });
        }
        domain.queued = vec![false; domain.rows.len()];
        let nnz = domain.rows.iter().map(|r| r.terms.len()).sum::<usize>();
        domain.work_limit = nnz
            .saturating_mul(16)
            .saturating_add(domain.rows.len().saturating_mul(64))
            .max(4096);
        domain
    }
    pub fn enable_statistics(&mut self) {
        self.statistics = Some(PropagationStats {
            eligible_rows: self.rows.len(),
            eligible_terms: self.rows.iter().map(|r| r.terms.len()).sum(),
            ..Default::default()
        });
    }
    pub fn statistics(&self) -> Option<PropagationStats> {
        self.statistics
    }
    fn enqueue(&mut self, row: usize) {
        if !self.queued[row] {
            self.queued[row] = true;
            self.pending.push_back(row);
        }
    }
    /// Undoes a trial [`Self::apply`]: resets `columns` to `bounds` without
    /// propagating and drops every pending row (probing).
    pub(crate) fn reset(&mut self, bounds: &Bounds, columns: &[usize]) {
        for &j in columns {
            self.synchronize(
                j,
                bounds.lower[j].ceil() as i128,
                bounds.upper[j].floor() as i128,
            );
        }
        while let Some(i) = self.pending.pop_front() {
            self.queued[i] = false;
        }
        self.last_changed.clear();
    }
    fn synchronize(&mut self, j: usize, l: i128, u: i128) {
        let (old_l, old_u) = (self.lower[j], self.upper[j]);
        if l == old_l && u == old_u {
            return;
        }
        self.lower[j] = l;
        self.upper[j] = u;
        for k in 0..self.incident[j].len() {
            let (i, a) = self.incident[j][k];
            let row = &mut self.rows[i];
            row.min += a * if a > 0 { l - old_l } else { u - old_u };
            row.max += a * if a > 0 { u - old_u } else { l - old_l };
            self.enqueue(i);
        }
    }
    /// Appended columns, including every implication, must be restored on exit.
    /// Across nodes synchronize both the preceding and current changed lists:
    /// this accounts for bounds restored by NodeBox before entering a sibling.
    pub fn apply(
        &mut self,
        bounds: &mut Bounds,
        changed: &mut Vec<usize>,
        budget: &Budget<'_>,
    ) -> bool {
        for &j in &self.integers {
            let (l, u) = (bounds.lower[j].ceil(), bounds.upper[j].floor());
            if l > u {
                if let Some(stats) = &mut self.statistics {
                    stats.infeasibilities += 1;
                }
                return false;
            }
            if l != bounds.lower[j] || u != bounds.upper[j] {
                bounds.lower[j] = l;
                bounds.upper[j] = u;
                changed.push(j);
                if let Some(stats) = &mut self.statistics {
                    stats.bound_changes += 1;
                }
            }
        }
        if self.rows.is_empty() {
            return true;
        }
        while let Some(i) = self.pending.pop_front() {
            self.queued[i] = false;
        }
        self.touched.clear();
        for &j in self.last_changed.iter().chain(changed.iter()) {
            if !self.marked[j] {
                self.marked[j] = true;
                self.touched.push(j);
            }
        }
        for k in 0..self.touched.len() {
            let j = self.touched[k];
            self.marked[j] = false;
            self.synchronize(j, bounds.lower[j] as i128, bounds.upper[j] as i128);
        }
        self.last_changed.clear();
        self.last_changed.extend_from_slice(changed);
        if self.first {
            for i in 0..self.rows.len() {
                self.enqueue(i);
            }
            self.first = false;
        }
        let mut work = 0usize;
        while let Some(i) = self.pending.pop_front() {
            self.queued[i] = false;
            if work >= self.work_limit || budget.stop().is_some() {
                if let Some(stats) = &mut self.statistics {
                    stats.work_limit_exits += u64::from(work >= self.work_limit);
                }
                return true;
            }
            if let Some(stats) = &mut self.statistics {
                stats.rows_dequeued += 1;
            }
            let row = &self.rows[i];
            if row.lower.is_some_and(|l| row.max < l) || row.upper.is_some_and(|u| row.min > u) {
                if let Some(stats) = &mut self.statistics {
                    stats.infeasibilities += 1;
                }
                return false;
            }
            // Root domain widths are conservative upper bounds at every child.
            // If neither side can tighten even the widest term, skip the row.
            if row.residues.is_empty()
                && row.upper.is_none_or(|b| b - row.min >= row.max_width)
                && row.lower.is_none_or(|b| row.max - b >= row.max_width)
            {
                if let Some(stats) = &mut self.statistics {
                    stats.slack_skips += 1;
                }
                continue;
            }
            for k in 0..self.rows[i].terms.len() {
                work = work.saturating_add(1);
                if let Some(stats) = &mut self.statistics {
                    stats.terms_examined += 1;
                }
                if work % 1024 == 0 && (work >= self.work_limit || budget.stop().is_some()) {
                    if let Some(stats) = &mut self.statistics {
                        stats.work_limit_exits += u64::from(work >= self.work_limit);
                    }
                    return true;
                }
                let row = &self.rows[i];
                let (j, a) = row.terms[k];
                let (l, u) = (self.lower[j], self.upper[j]);
                let width = a.abs() * (u - l);
                let amin = a * if a > 0 { l } else { u };
                let amax = a * if a > 0 { u } else { l };
                let (mut lo, mut hi) = (l, u);
                if a > 0 {
                    if let Some(b) = row.upper.filter(|&b| b - row.min < width) {
                        hi = hi.min(floor_div(b - (row.min - amin), a));
                    }
                    if let Some(b) = row.lower.filter(|&b| row.max - b < width) {
                        lo = lo.max(ceil_div(b - (row.max - amax), a));
                    }
                } else {
                    if let Some(b) = row.upper.filter(|&b| b - row.min < width) {
                        lo = lo.max(ceil_div((row.min - amin) - b, -a));
                    }
                    if let Some(b) = row.lower.filter(|&b| row.max - b < width) {
                        hi = hi.min(floor_div((row.max - amax) - b, -a));
                    }
                }
                if let Some(&(r, step)) = row.residues.get(k).and_then(Option::as_ref) {
                    lo += (r - lo).rem_euclid(step);
                    hi -= (hi - r).rem_euclid(step);
                }
                if lo > hi {
                    if let Some(stats) = &mut self.statistics {
                        stats.infeasibilities += 1;
                    }
                    return false;
                }
                if lo != l || hi != u {
                    bounds.lower[j] = lo as f64;
                    bounds.upper[j] = hi as f64;
                    changed.push(j);
                    if let Some(stats) = &mut self.statistics {
                        stats.bound_changes += 1;
                    }
                    self.last_changed.push(j);
                    self.synchronize(j, lo, hi);
                }
            }
        }
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::NativeOptions;
    use lp_ip_craft::*;
    fn apply(domain: &mut Domain, bounds: &mut Bounds, changed: &mut Vec<usize>) -> bool {
        let settings = NativeOptions::default();
        let cancel = CancellationToken::default();
        let budget = Budget {
            start: std::time::Instant::now(),
            settings: &settings,
            cancel: &cancel,
            pivots: 0,
        };
        domain.apply(bounds, changed, &budget)
    }
    #[test]
    fn row_limits_are_rounded_with_the_feasibility_tolerance() {
        // 3x - 2y = 2.0000000000001: (2, 2) misses the row by 1e-13.
        let model = Model::new(ModelData {
            sense: Sense::Minimize,
            objective: vec![4., 0.],
            objective_offset: 0.,
            variables: Bounds::new(vec![1., -1.], vec![3., 2.]),
            kinds: vec![VariableKind::Integer; 2],
            matrix: CsrMatrix::from_dense(1, 2, &[3., -2.]).unwrap(),
            rows: Bounds::new(vec![2.0000000000001], vec![2.0000000000001]),
        })
        .unwrap();
        let mut b = model.variables().clone();
        assert!(apply(
            &mut Domain::new(&model, true, 1e-7),
            &mut b,
            &mut Vec::new()
        ));
        assert_eq!(
            (b.lower.clone(), b.upper.clone()),
            (vec![2., 2.], vec![2., 2.])
        );
        // Read exactly, the limits round to the empty range [3, 2].
        let mut exact = model.variables().clone();
        assert!(!apply(
            &mut Domain::new(&model, true, 0.),
            &mut exact,
            &mut Vec::new()
        ));
    }
    #[test]
    fn long_rows_root_implications_and_sibling_restoration() {
        let n = 40;
        let mut values = vec![0.; n * n];
        let mut lo = vec![f64::NEG_INFINITY; n];
        let mut hi = vec![0.; n];
        // Reverse chain order requires more than the old three full scans.
        for i in 0..n - 1 {
            let j = n - 2 - i;
            values[i * n + j] = 1.;
            values[i * n + j + 1] = -1.;
        }
        for j in 0..n {
            values[(n - 1) * n + j] = 1.;
        }
        lo[n - 1] = 20.;
        hi[n - 1] = 40.;
        let model = Model::new(ModelData {
            sense: Sense::Minimize,
            objective: vec![0.; n],
            objective_offset: 0.,
            variables: Bounds::new(vec![0.; n], vec![1.; n]),
            kinds: vec![VariableKind::Binary; n],
            matrix: CsrMatrix::from_dense(n, n, &values).unwrap(),
            rows: Bounds::new(lo, hi),
        })
        .unwrap();
        let mut d = Domain::new(&model, true, 1e-7);
        let mut b = model.variables().clone();
        let mut c = vec![0];
        b.lower[0] = 1.;
        assert!(apply(&mut d, &mut b, &mut c));
        assert!(b.lower.iter().all(|&v| v == 1.));
        // NodeBox restores every implication before moving to the sibling.
        b = model.variables().clone();
        b.upper[n - 1] = 0.;
        c = vec![n - 1];
        assert!(!apply(&mut d, &mut b, &mut c));
        b = model.variables().clone();
        c.clear();
        assert!(apply(&mut d, &mut b, &mut c));
        assert_eq!(b.lower[0], 0.);
        assert_eq!(b.upper[n - 1], 1.);
    }
    #[test]
    fn propagation_never_removes_an_enumerated_integer_point() {
        let n = 10;
        let mut seed = 38471u64;
        for trial in 0..80 {
            let mut next = || {
                seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
                ((seed >> 32) % 7) as i32 - 3
            };
            let data: Vec<f64> = (0..4 * n).map(|_| next() as f64).collect();
            let witness: Vec<f64> = (0..n).map(|_| f64::from(next() > 0)).collect();
            let center: Vec<f64> = data
                .chunks(n)
                .map(|r| r.iter().zip(&witness).map(|(a, x)| a * x).sum())
                .collect();
            let m = Model::new(ModelData {
                sense: Sense::Minimize,
                objective: vec![0.; n],
                objective_offset: 0.,
                variables: Bounds::new(vec![0.; n], vec![1.; n]),
                kinds: vec![VariableKind::Binary; n],
                matrix: CsrMatrix::from_dense(4, n, &data).unwrap(),
                rows: Bounds::new(
                    center.iter().map(|v| v - 1.3).collect(),
                    center.iter().map(|v| v + 1.8).collect(),
                ),
            })
            .unwrap();
            let mut domain = Domain::new(&m, true, 1e-7);
            for branch in 0..5 {
                let mut b = m.variables().clone();
                let j = (trial + branch) % n;
                let v = f64::from(branch % 2 == 0);
                b.lower[j] = v;
                b.upper[j] = v;
                let before = b.clone();
                let mut changed = vec![j];
                let ok = apply(&mut domain, &mut b, &mut changed);
                for mask in 0..1usize << n {
                    let x: Vec<f64> = (0..n).map(|j| ((mask >> j) & 1) as f64).collect();
                    if x.iter()
                        .enumerate()
                        .any(|(j, &v)| v < before.lower[j] || v > before.upper[j])
                    {
                        continue;
                    }
                    if !check::evaluate(&m, &x, &Tolerances::default())
                        .unwrap()
                        .feasible_candidate
                    {
                        continue;
                    }
                    assert!(ok, "trial {trial} branch {branch}");
                    assert!(
                        x.iter()
                            .enumerate()
                            .all(|(j, &v)| v >= b.lower[j] && v <= b.upper[j])
                    );
                }
            }
        }
    }
}