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
//! Root LP separation stage: checked solves, exact cuts and retained bases.
use crate::*;
#[derive(Default)]
pub(crate) struct Stats {
    pub pivots: u64,
    pub nodes: u64,
    pub gmi: u64,
    pub small_gap_skips: u64,
    pub mir: u64,
    pub choice_mass: u64,
    pub choice_precedence_rows: u64,
    pub choice_precedence_signs: u64,
    pub route_improvements: u64,
    pub route_work: usize,
    pub mixed_root: root_fix::Stats,
    pub root_probe: root_fix::ProbeStats,
    pub covers: u64,
    pub lifted: u64,
    pub exact_work: u64,
    pub gmi_work: u64,
    pub candidates: u64,
    pub rejected: u64,
    pub vubs: u64,
    pub basis_reuses: u64,
    /// Cut rows slack at the final root LP optimum, removed before search.
    pub pruned: u64,
    /// RENS sub-MIP nodes, and whether it improved the root seed.
    pub rens_nodes: u64,
    pub rens_found: u64,
    pub grouped: grouped::Stats,
    pub bound: Option<f64>,
    pub initial_objective: Option<f64>,
    pub stages: Vec<String>,
    pub seed: Option<Vec<f64>>,
    pub primal: primal::Stats,
    pub stop: &'static str,
}
fn number(v: Option<f64>) -> String {
    v.filter(|v| v.is_finite())
        .map_or_else(|| "null".into(), |v| v.to_string())
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn run(
    model: &mut Model,
    original: &Model,
    options: &Options,
    settings: &NativeOptions,
    start: Option<&WarmStart>,
    cancel: &CancellationToken,
    began: Instant,
    policy: Option<&root_policy::Policy>,
    mut pilot: Option<&mut local_mip_bench::Trace<'_>>,
) -> Result<Stats> {
    let mut stats = Stats {
        seed: start.map(|s| s.primal.clone()),
        ..Default::default()
    };
    let root_budget = policy.map(|_| root_policy::Policy::budget(settings));
    let mut budget = Budget {
        start: began,
        settings: root_budget.as_ref().unwrap_or(settings),
        cancel,
        pivots: 0,
    };
    if policy.is_some() && budget.stop().is_some() {
        stats.stop = "root_budget";
        return Ok(stats);
    }
    let mut choice_mass = (settings.choice_mass_rounds > 0
        || settings.choice_route_passes > 0
        || settings.choice_order_presolve)
        .then(|| choice_mass::Separator::new(model, &budget))
        .filter(|s| !s.is_empty());
    if let Some(separator) = choice_mass
        .as_ref()
        .filter(|_| settings.choice_order_presolve)
    {
        let (cuts, signs) = separator.precedence(model, &budget)?;
        stats.choice_precedence_rows = cuts as u64;
        stats.choice_precedence_signs = signs as u64;
    }
    if let Some(s) = choice_mass
        .as_ref()
        .filter(|_| settings.choice_route_passes > 0)
    {
        (stats.route_improvements, stats.route_work) =
            choice_route::improve(model, &s.pairs, options, &budget, &mut stats.seed)?;
    }
    let mut lp = match Lp::new(
        model,
        &vec![true; model.m()],
        &presolve::kept_columns(model, model.variables(), settings),
        controls(model, options, settings),
    ) {
        Ok(lp) => lp,
        Err(_) if policy.is_some() => {
            stats.stop = "lp_setup";
            return Ok(stats);
        }
        Err(e) => return Err(e),
    };
    let generic_rounds = policy.map_or_else(
        || {
            if settings.gmi_cuts || settings.mir_cuts {
                settings.mip_cut_rounds
            } else {
                0
            }
        },
        |p| p.rounds,
    );
    let delay = if choice_mass.is_some() && generic_rounds > 0 {
        settings.root_cut_delay.min(settings.choice_mass_rounds)
    } else {
        0
    };
    let cut_upper = (settings.root_cut_gap > 0.)
        .then(|| {
            stats
                .seed
                .as_deref()
                .and_then(|seed| certified_start(original, seed, &budget))
        })
        .flatten();
    let rounds = (generic_rounds + delay).max(if choice_mass.is_some() {
        settings.choice_mass_rounds
    } else {
        0
    });
    let mut stagnant = 0;
    let mut previous: Option<f64> = None;
    let mut families = policy.map_or([settings.gmi_cuts, settings.mir_cuts], |p| p.families);
    let initial_nnz = model.nnz();
    const POLICY_EXACT_WORK: u64 = 4_000_000;
    stats.stop = "round_limit";
    // Rows from here on are root cuts; `last` is the latest accepted optimum
    // and the row count it belongs to.
    let cuts_from = model.m();
    let mut last: Option<(usize, Vec<f64>)> = None;
    for round in 0..=rounds {
        if budget.stop().is_some() || budget.settings.node_limit.is_some_and(|n| stats.nodes >= n) {
            stats.stop = "root_budget";
            break;
        }
        let before = (stats.nodes, budget.pivots);
        stats.nodes += 1;
        let t = Instant::now();
        let status = lp
            .solve(&mut budget, round == 0)
            .unwrap_or(Status::NumericalFailure);
        if let Some(trace) = &mut pilot {
            trace.stage("presolve_root_lp", (stats.nodes, budget.pivots), before, t);
        }
        if status != Status::Optimal {
            stats.stop = "lp_status";
            stats.stages.push(format!("{{\"round\":{round},\"status\":\"{}\",\"bound\":null,\"objective\":null,\"seconds\":{}}}",status.as_str(),t.elapsed().as_secs_f64()));
            break;
        }
        let x = lp.point();
        let duals = lp.duals(model);
        if !accepted(model, model.variables(), &x, &duals, options, settings) {
            stats.stop = "lp_check";
            break;
        }
        let objective = check::evaluate(model, &x, &options.tolerances)?.objective;
        last = Some((model.m(), x.clone()));
        let bound = safe_dual_bound_with_bounds(model, model.variables(), &duals.row_duals)?.bound;
        if let Some(b) = bound {
            stats.bound = Some(stats.bound.map_or(b, |old| {
                if model.sense() == Sense::Minimize {
                    old.max(b)
                } else {
                    old.min(b)
                }
            }));
        }
        if round == 0 {
            stats.initial_objective = Some(objective);
        }
        stats.stages.push(format!("{{\"round\":{round},\"status\":\"optimal\",\"bound\":{},\"objective\":{objective},\"seconds\":{},\"elapsed_seconds\":{},\"rows\":{},\"pivots\":{}}}",number(bound),t.elapsed().as_secs_f64(),began.elapsed().as_secs_f64(),model.m(),budget.pivots));
        if let Some(old) = previous {
            let improvement = (objective - old).abs();
            if improvement < settings.root_cut_progress * (1.0f64 + f64::abs(old)) {
                stagnant += 1;
            } else {
                stagnant = 0;
            }
        }
        previous = Some(objective);
        if round == 0 && settings.root_heuristics && budget.stop().is_none() {
            stats.primal = primal::run(
                model,
                &mut lp,
                options,
                &mut budget,
                &mut stats.nodes,
                &mut stats.seed,
                pilot.as_deref_mut(),
            )?;
            if budget.stop().is_some() || settings.node_limit.is_some_and(|n| stats.nodes >= n) {
                break;
            }
            let before = (stats.nodes, budget.pivots);
            let started = pilot.as_ref().map(|_| Instant::now());
            stats.nodes += 1;
            let status = lp
                .solve(&mut budget, false)
                .unwrap_or(Status::NumericalFailure);
            if let Some((trace, started)) = pilot.as_deref_mut().zip(started) {
                trace.stage(
                    "root_lp_restore",
                    (stats.nodes, budget.pivots),
                    before,
                    started,
                );
            }
            if status != Status::Optimal
                || !accepted(
                    model,
                    model.variables(),
                    &lp.point(),
                    &lp.duals(model),
                    options,
                    settings,
                )
            {
                break;
            }
        }
        if policy.is_some() {
            if !root_policy::Policy::can_improve(model, &x, bound, start, options) {
                stats.stop = "integral_or_closed";
                break;
            }
            if stats.exact_work >= POLICY_EXACT_WORK
                || model.nnz() > initial_nnz.saturating_mul(12).saturating_add(128)
            {
                stats.stop = "separation_work";
                break;
            }
        }
        if stagnant >= 3 {
            stats.stop = "low_progress";
            break;
        }
        if round == rounds {
            break;
        }
        // While both families keep contributing after the first round,
        // dense cuts are dropped (support above max(50, n/4), like SCIP's
        // relative support limit). Combined rounds otherwise accumulate
        // dense rank-2 cuts whose exact derivations dominate root time on
        // assignment models. Single-family policies, and combined once a
        // family has stopped, keep every cut.
        let max_terms = if round >= 1 && families == [true, true] {
            50.max(model.n() / 4)
        } else {
            usize::MAX
        };
        let work = if policy.is_some() {
            settings
                .cut_exact_work
                .min(POLICY_EXACT_WORK.saturating_sub(stats.exact_work))
        } else {
            settings.cut_exact_work
        };
        let generic = round >= delay && round - delay < generic_rounds;
        if generic
            && cut_upper.zip(bound).is_some_and(|(upper, bound)| {
                (upper - oriented(model, bound)).max(0.) <= settings.root_cut_gap
            })
            && families.iter().any(|&x| x)
        {
            families.fill(false);
            stats.small_gap_skips += 1;
        }
        let (mut selected, cuts) = if generic {
            certified_cuts::separate(model, &mut lp, &x, &budget, families, max_terms, work)
        } else {
            (Vec::new(), certified_cuts::Stats::default())
        };
        if let Some(separator) = choice_mass
            .as_mut()
            .filter(|_| round < settings.choice_mass_rounds)
        {
            let additional = separator.separate(&x, &budget);
            stats.choice_mass += additional.len() as u64;
            selected.extend(additional);
        }
        // A family whose cuts were not selected this round is not separated
        // again; the other family then gets the whole work budget.
        if generic {
            for (active, family) in families.iter_mut().zip(["gmi", "mir"]) {
                *active &= selected.iter().any(|c| c.family == family);
            }
        }
        stats.exact_work += cuts.work;
        stats.gmi_work += cuts.gmi_work;
        stats.candidates += cuts.candidates;
        stats.rejected += cuts.rejected;
        stats.vubs = stats.vubs.max(cuts.vubs);
        let old_rows = model.m();
        stats.gmi += selected.iter().filter(|c| c.family == "gmi").count() as u64;
        stats.mir += selected.iter().filter(|c| c.family == "mir").count() as u64;
        certified_cuts::append(model, &selected)?;
        if settings.root_separation && (round < generic_rounds || choice_mass.is_none()) {
            let c = cuts::separate(model, &x, settings.cover_lifting, cancel)?;
            stats.covers += c.added as u64;
            stats.lifted += c.lifted as u64;
        }
        if model.m() == old_rows {
            if round < delay {
                continue;
            }
            stats.stop = "no_selected_cut";
            break;
        }
        match lp.extend_rows(model, old_rows) {
            Ok(extended) => lp = extended,
            Err(_) if policy.is_some() => {
                // Any appended inequalities passed the same validity checks
                // as manual separation. The tree can rebuild on that model.
                stats.stop = "basis_extension";
                break;
            }
            Err(e) => return Err(e),
        }
        stats.basis_reuses += 1;
    }
    if let Some((rows, x)) = last {
        if rows == model.m() && settings.mixed_root_rounds > 0 && budget.stop().is_none() {
            if let Some(seed) = stats.seed.as_ref() {
                if let Some(upper) = certified_start(original, seed, &budget) {
                    for _ in 0..settings.mixed_root_rounds.min(6) {
                        if budget.stop().is_some()
                            || settings.node_limit.is_some_and(|n| stats.nodes >= n)
                        {
                            break;
                        }
                        let duals = lp.duals(model);
                        let Some(bounds) = root_fix::narrow(
                            model,
                            seed,
                            upper,
                            &duals,
                            &budget,
                            &mut stats.mixed_root,
                        )?
                        else {
                            break;
                        };
                        if seed
                            .iter()
                            .enumerate()
                            .any(|(j, &v)| v < bounds.lower[j] || v > bounds.upper[j])
                        {
                            break;
                        }
                        let mut data = model.data().clone();
                        data.variables = bounds;
                        let next = Model::new(data)?;
                        lp.set_bounds(&next.variables().lower, &next.variables().upper)?;
                        *model = next;
                        stats.mixed_root.applied += 1;
                        stats.nodes += 1;
                        let started = Instant::now();
                        if lp.solve(&mut budget, false)? != Status::Optimal {
                            break;
                        }
                        let duals = lp.duals(model);
                        let bound = safe_dual_bound_with_bounds(
                            model,
                            model.variables(),
                            &duals.row_duals,
                        )?
                        .bound;
                        if let Some(b) = bound {
                            let clipped = oriented(model, oriented(model, b).min(upper));
                            stats.bound = Some(stats.bound.map_or(clipped, |old| {
                                oriented(model, oriented(model, old).max(oriented(model, clipped)))
                            }));
                        }
                        stats.stages.push(format!(
                            "{{\"stage\":\"mixed_root_fix\",\"bound\":{},\"elapsed_seconds\":{},\"seconds\":{},\"pivots\":{}}}",
                            number(bound), began.elapsed().as_secs_f64(),
                            started.elapsed().as_secs_f64(), budget.pivots
                        ));
                    }
                }
            }
        }
        // Incumbent-opposite root probes need a certified start; Rust 1.85
        // has no let chains, hence the nested matches.
        let probe_seed = stats.seed.as_ref().filter(|_| {
            rows == model.m() && settings.root_probe_limit > 0 && budget.stop().is_none()
        });
        if let Some(seed) = probe_seed {
            if let Some(upper) = certified_start(original, seed, &budget) {
                if let Some(bounds) = root_fix::probe(
                    model,
                    &mut lp,
                    seed,
                    upper,
                    &mut stats.nodes,
                    &mut budget,
                    &mut stats.root_probe,
                )? {
                    let mut data = model.data().clone();
                    data.variables = bounds;
                    *model = Model::new(data)?;
                    stats.mixed_root.applied += 1;
                }
            }
        }
        if rows == model.m() && rows > cuts_from && choice_mass.is_none() {
            stats.pruned = prune_slack(model, cuts_from, &x)?;
        }
        if settings.root_heuristics && budget.stop().is_none() {
            rens(model, &x, options, &mut budget, began, &mut stats, pilot)?;
        }
        if settings.grouped_heuristics {
            stats.grouped = grouped::improve(
                model,
                &x,
                options,
                &mut budget,
                began,
                &mut stats.nodes,
                &mut stats.seed,
            )?;
        }
    }
    stats.pivots = budget.pivots;
    Ok(stats)
}
fn certified_start(model: &Model, seed: &[f64], budget: &Budget<'_>) -> Option<f64> {
    incumbent::upper(model, seed).or_else(|| {
        budget
            .settings
            .rational_certification
            .then(|| {
                witness::upper(model, seed, budget, witness::ATTEMPT_WORK)
                    .0
                    .map(|w| w.upper)
            })
            .flatten()
    })
}
/// RENS: the sub-MIP of `model` in which every integer column that is
/// integral at the root optimum `x` is fixed and every other one is
/// restricted to its two neighbouring integers, when at least half of the
/// integer columns are fixed. It is solved with a node budget of 50 per
/// heuristic LP call. Its incumbents are feasible for
/// `model`, and only those are kept, as the search's start; its status and
/// bound say nothing about `model` and are discarded.
fn rens(
    model: &Model,
    x: &[f64],
    options: &Options,
    budget: &mut Budget<'_>,
    began: Instant,
    stats: &mut Stats,
    mut pilot: Option<&mut local_mip_bench::Trace<'_>>,
) -> Result<()> {
    let settings = budget.settings;
    let started = pilot.as_ref().map(|_| Instant::now());
    let before = (stats.nodes, budget.pivots);
    let mut data = model.data().clone();
    let (mut open, mut fixed) = (0, 0);
    for (j, &v) in x.iter().enumerate() {
        if !model.kinds()[j].is_integral() {
            continue;
        }
        let (lo, hi) = (
            data.variables.lower[j].ceil(),
            data.variables.upper[j].floor(),
        );
        if (v - v.round()).abs() <= 1e-6 {
            fixed += 1;
            let r = v.round().clamp(lo, hi);
            data.variables.lower[j] = r;
            data.variables.upper[j] = r;
        } else {
            data.variables.lower[j] = lo.max(v.floor());
            data.variables.upper[j] = hi.min(v.ceil());
            open += 1;
        }
    }
    let nodes = 50 * settings.heuristic_lp_calls as u64;
    let nodes = settings
        .node_limit
        .map_or(nodes, |n| n.saturating_sub(stats.nodes).min(nodes));
    // Like SCIP's minimum fixing rate: with fewer than half the integer
    // columns fixed, the sub-MIP is nearly the whole problem.
    if open == 0 || nodes == 0 || fixed < open {
        return Ok(());
    }
    let mut s = packing::child_settings(settings, began);
    s.node_limit = Some(nodes);
    s.iteration_limit = settings
        .iteration_limit
        .map(|p| p.saturating_sub(budget.pivots));
    s.mip_trace_limit = 0;
    s.branch_trace_limit = 0;
    let Ok(sub) = Model::new(data) else {
        return Ok(());
    };
    // A failed heuristic solve is not an error of the main search.
    let Ok(r) = NativeSolver::new(s).solve(&sub, options, None, budget.cancel) else {
        return Ok(());
    };
    stats.nodes += r.nodes;
    stats.rens_nodes += r.nodes;
    budget.pivots += r.iterations;
    if let Some(c) = r.candidate {
        if primal::candidate(
            model,
            c,
            options,
            &mut stats.seed,
            pilot
                .as_deref_mut()
                .map(|p| (p, "rens", (stats.nodes, budget.pivots))),
        )? {
            stats.rens_found += 1;
        }
    }
    if let Some((trace, started)) = pilot.zip(started) {
        trace.stage("rens", (stats.nodes, budget.pivots), before, started);
    }
    Ok(())
}
/// Removes cut rows (index `from` on) that are strictly slack at the root LP
/// optimum `x`. Each has a zero dual there, so `x` and its duals stay
/// optimal for the smaller LP and the root relaxation value is unchanged;
/// dropping valid inequalities never removes a feasible point.
fn prune_slack(model: &mut Model, from: usize, x: &[f64]) -> Result<u64> {
    let a = model.matrix();
    let rows = model.rows();
    let slack = |i: usize| {
        let activity: f64 = (a.pattern.indptr[i]..a.pattern.indptr[i + 1])
            .map(|k| a.values[k] * x[a.pattern.indices[k]])
            .sum();
        let margin = |b: f64| 1e-6 * (1. + b.abs());
        (!rows.lower[i].is_finite() || activity > rows.lower[i] + margin(rows.lower[i]))
            && (!rows.upper[i].is_finite() || activity < rows.upper[i] - margin(rows.upper[i]))
    };
    let keep: Vec<bool> = (0..model.m()).map(|i| i < from || !slack(i)).collect();
    let removed = keep.iter().filter(|k| !**k).count() as u64;
    if removed == 0 {
        return Ok(0);
    }
    let mut data = model.data().clone();
    let (mut indptr, mut indices, mut values) = (vec![0], Vec::new(), Vec::new());
    let (mut lower, mut upper) = (Vec::new(), Vec::new());
    for i in (0..model.m()).filter(|&i| keep[i]) {
        let range = a.pattern.indptr[i]..a.pattern.indptr[i + 1];
        indices.extend_from_slice(&a.pattern.indices[range.clone()]);
        values.extend_from_slice(&a.values[range]);
        indptr.push(values.len());
        lower.push(rows.lower[i]);
        upper.push(rows.upper[i]);
    }
    data.matrix.pattern.rows = lower.len();
    data.matrix.pattern.indptr = indptr;
    data.matrix.pattern.indices = indices;
    data.matrix.values = values;
    data.rows.lower = lower;
    data.rows.upper = upper;
    *model = Model::new(data)?;
    Ok(removed)
}