Skip to main content

NativeSolver

Struct NativeSolver 

Source
pub struct NativeSolver {
    pub settings: NativeOptions,
}
Expand description

Solver with a single-thread simplex kernel and optional parallel components. Independent instances can share immutable input models.

Fields§

§settings: NativeOptions

Engine controls.

Implementations§

Source§

impl NativeSolver

Source

pub fn solve_batch( &self, models: &[&Model], options: &Options, workers: usize, cancel: &CancellationToken, ) -> Result<Vec<Result<SolveResult>>>

Solve independent models in input order using 1..=16 workers. Each job has its own limits and result/error. A shared cancellation token affects running and queued jobs. Nested component, residual and tree workers are disabled inside the pool. No warm starts are supplied by this API. Models are borrowed, not copied.

Examples found in repository?
examples/performance_parallel.rs (lines 281-286)
206fn main() {
207    let args: Vec<_> = std::env::args().collect();
208    let family = args.get(1).map(String::as_str).unwrap_or("packing");
209    let n = args.get(2).map(|v| v.parse().unwrap()).unwrap_or(128);
210    let mode = args.get(3).map(String::as_str).unwrap_or("single");
211    let inner = args.get(4).map(|v| v.parse().unwrap()).unwrap_or(1);
212    let workers = args.get(5).map(|v| v.parse().unwrap()).unwrap_or(1);
213    let jobs = args.get(6).map(|v| v.parse().unwrap()).unwrap_or(1);
214    assert!(inner * workers <= 8 && inner > 0 && workers > 0 && jobs > 0);
215    #[cfg(feature = "parallel-bench")]
216    if family == "factor" {
217        assert_eq!(workers, 1);
218        assert_eq!(jobs, 3);
219        let q = lp_ip_craft_native::parallel_bench::run(n, inner).unwrap();
220        println!(
221            "{{\"kernel_profile\":{},\"version\":\"{}\",\"family\":\"factor\",\"size\":{n},\"mode\":\"{mode}\",\"inner\":{inner},\"workers\":1,\"jobs\":3,\"completed\":3,\"seconds\":{},\"workflow_seconds\":{},\"resource_seconds\":{},\"objective\":0.0,\"residual\":{},\"checksum\":{},\"pivots\":0,\"nodes\":0,\"status\":\"checked\"}}",
222            cfg!(feature = "kernel-profile"),
223            env!("CARGO_PKG_VERSION"),
224            q.seconds,
225            q.workflow_seconds,
226            q.resource_seconds,
227            q.error,
228            q.checksum
229        );
230        return;
231    }
232    let mut settings = NativeOptions {
233        decompose: false,
234        component_threads: 1,
235        packing_workers: 1,
236        tree_threads: 1,
237        time_limit_seconds: Some(20.),
238        ..Default::default()
239    };
240    if mode.contains("components") {
241        settings.decompose = true;
242        settings.component_threads = workers;
243        settings.component_parallel_min_entries = 0;
244    }
245    if mode == "tree" {
246        settings.tree_threads = workers;
247        settings.tree_split_depth = 3;
248    }
249    if mode == "residual" {
250        settings.packing_workers = workers;
251        settings.packing_root = true;
252        settings.packing_neighborhoods = 16;
253        settings.packing_neighborhood_size = 24;
254        settings.packing_rounds = 2;
255    }
256    let models: Vec<_> = (0..jobs)
257        .map(|i| {
258            if mode.contains("components") {
259                blocks(n, mode == "skewcomponents")
260            } else {
261                fixture(
262                    family,
263                    if mode == "skewbatch" && i >= jobs * 3 / 4 {
264                        n * 4
265                    } else {
266                        n
267                    },
268                )
269            }
270        })
271        .collect();
272    let options = Options {
273        threads: inner,
274        ..Default::default()
275    };
276    let token = CancellationToken::default();
277    let solver = NativeSolver::new(settings);
278    let t = Instant::now();
279    let result = if mode.contains("batch") {
280        solver
281            .solve_batch(
282                &models.iter().map(|p| &p.0).collect::<Vec<_>>(),
283                &options,
284                workers,
285                &token,
286            )
287            .unwrap()
288    } else {
289        assert_eq!(jobs, 1);
290        vec![NativeSolver::new(solver.settings.clone()).solve(&models[0].0, &options, None, &token)]
291    };
292    let seconds = t.elapsed().as_secs_f64();
293    assert_eq!(result.len(), jobs);
294    let (mut objective, mut residual, mut pivots, mut nodes) = (0_f64, 0_f64, 0_u64, 0_u64);
295    for ((m, e), r) in models.iter().zip(result) {
296        let r = r.unwrap();
297        let (c, k) = check_result(m, *e, &r);
298        objective += c;
299        residual = residual.max(k);
300        pivots += r.iterations;
301        nodes += r.nodes;
302    }
303    println!(
304        "{{\"kernel_profile\":{},\"version\":\"{}\",\"family\":\"{family}\",\"size\":{n},\"mode\":\"{mode}\",\"inner\":{inner},\"workers\":{workers},\"jobs\":{jobs},\"completed\":{jobs},\"seconds\":{seconds},\"objective\":{objective},\"residual\":{residual},\"pivots\":{pivots},\"nodes\":{nodes},\"status\":\"optimal\"}}",
305        cfg!(feature = "kernel-profile"),
306        env!("CARGO_PKG_VERSION")
307    );
308}
Source§

impl NativeSolver

Source

pub fn new(settings: NativeOptions) -> Self

Construct a solver with explicit controls.

Examples found in repository?
examples/benchmark.rs (line 93)
68fn main() {
69    let repeats: usize = std::env::args()
70        .nth(1)
71        .unwrap_or("7".into())
72        .parse()
73        .unwrap();
74    let component_threads = std::env::args().nth(2).map(|s| s.parse::<usize>().unwrap());
75    println!("[");
76    let mut first = true;
77    for name in [
78        "fixed",
79        "pivot",
80        "knapsack",
81        "partition",
82        "nodecopy",
83        "redundant",
84        "blocks",
85    ] {
86        let model = fixture(name);
87        for run in 0..=repeats {
88            let t = Instant::now();
89            let mut settings = NativeOptions::default();
90            if let Some(t) = component_threads {
91                settings.component_threads = t;
92            }
93            let r = NativeSolver::new(settings)
94                .solve(
95                    &model,
96                    &Options::default(),
97                    None,
98                    &CancellationToken::default(),
99                )
100                .unwrap();
101            let seconds = t.elapsed().as_secs_f64();
102            assert_eq!(r.status, Status::Optimal, "{name}: {r:?}");
103            if run > 0 {
104                if !first {
105                    println!(",");
106                }
107                first = false;
108                print!(
109                    "{{\"fixture\":\"{name}\",\"run\":{run},\"seconds\":{seconds},\"nodes\":{},\"pivots\":{},\"objective\":{},\"components\":{},\"workers\":{}}}",
110                    r.nodes,
111                    r.iterations,
112                    r.evaluation.unwrap().objective,
113                    r.backend
114                        .effective_options
115                        .iter()
116                        .find(|(k, _)| k == "diagnostics.component_count")
117                        .map(|(_, v)| v.as_str())
118                        .unwrap_or("1"),
119                    r.backend
120                        .effective_options
121                        .iter()
122                        .find(|(k, _)| k == "diagnostics.component_workers")
123                        .map(|(_, v)| v.as_str())
124                        .unwrap_or("1")
125                );
126            }
127        }
128    }
129    println!("\n]");
130}
More examples
Hide additional examples
examples/family_benchmark.rs (line 183)
161fn main() {
162    let args: Vec<_> = std::env::args().collect();
163    let family = args.get(1).map(String::as_str).unwrap_or("packing");
164    let size = args.get(2).map(|s| s.parse().unwrap()).unwrap_or(128);
165    let warm = args.get(3).is_none_or(|s| s != "cold");
166    let steepest_edge = args.get(4).is_none_or(|s| s != "dantzig");
167    let (model, expected) = match family {
168        "packing" => packing(size),
169        "irregular" => irregular(size),
170        "network" => network(size),
171        "selection" => selection(size),
172        _ => panic!("unknown family"),
173    };
174    let settings = NativeOptions {
175        decompose: false,
176        component_threads: 1,
177        node_reoptimization: warm,
178        steepest_edge,
179        time_limit_seconds: Some(30.),
180        ..Default::default()
181    };
182    let t = Instant::now();
183    let r = NativeSolver::new(settings)
184        .solve(
185            &model,
186            &Options::default(),
187            None,
188            &CancellationToken::default(),
189        )
190        .unwrap();
191    let seconds = t.elapsed().as_secs_f64();
192    let peak_rss_kib = std::fs::read_to_string("/proc/self/status")
193        .ok()
194        .and_then(|text| {
195            text.lines()
196                .find(|l| l.starts_with("VmHWM:"))
197                .and_then(|l| l.split_whitespace().nth(1))
198                .and_then(|s| s.parse::<u64>().ok())
199        })
200        .unwrap_or(0);
201    let status = r.status.as_str();
202    if r.status == Status::Optimal {
203        let objective = r.evaluation.as_ref().unwrap().objective;
204        assert!(
205            (objective - expected).abs() < 1e-6 * (1. + expected.abs()),
206            "{objective} != {expected}"
207        );
208    }
209    let objective = r
210        .evaluation
211        .as_ref()
212        .map(|e| e.objective.to_string())
213        .unwrap_or("null".into());
214    let d = |key: &str| {
215        r.backend
216            .effective_options
217            .iter()
218            .find(|(k, _)| k == &format!("diagnostics.{key}"))
219            .map(|(_, v)| v.as_str())
220            .unwrap_or("0")
221    };
222    println!(
223        "{{\"family\":\"{family}\",\"size\":{size},\"warm\":{warm},\"steepest_edge\":{steepest_edge},\"n\":{},\"m\":{},\"nnz\":{},\"peak_rss_kib\":{peak_rss_kib},\"seconds\":{seconds},\"status\":\"{status}\",\"objective\":{objective},\"expected\":{expected},\"iterations\":{},\"nodes\":{},\"factor_peak_entries\":{},\"refactorizations\":{},\"bound_flips\":{},\"warm_nodes\":{},\"cold_fallbacks\":{}}}",
224        model.n(),
225        model.m(),
226        model.nnz(),
227        r.iterations,
228        r.nodes,
229        d("factor_peak_entries"),
230        d("refactorizations"),
231        d("bound_flips"),
232        d("reoptimized_nodes"),
233        d("cold_fallbacks")
234    );
235}
examples/spoc4_profile.rs (lines 77-82)
9fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
10    let args: Vec<_> = std::env::args().collect();
11    let text = std::fs::read_to_string(args.get(1).ok_or("matching table path required")?)?;
12    let mut transfers = Vec::new();
13    let mut keys = BTreeSet::new();
14    let mut weights = Vec::new();
15    for line in text.lines().filter(|s| !s.trim().is_empty()) {
16        let fields: Vec<_> = line.split_whitespace().collect();
17        if fields.len() != 4 {
18            return Err("four fields required".into());
19        }
20        let mut t = [0u64; 3];
21        for k in 0..3 {
22            t[k] = fields[k].parse()?;
23            keys.insert((k, t[k]));
24        }
25        let (whole, fraction) = fields[3].split_once('.').unwrap_or((fields[3], ""));
26        if fraction.len() > 3 {
27            return Err("at most three decimal digits required".into());
28        }
29        weights.push(
30            (whole.parse::<u64>()? * 1000 + format!("{fraction:0<3}").parse::<u64>()?) as f64,
31        );
32        transfers.push(t);
33    }
34    let map: BTreeMap<_, _> = keys
35        .into_iter()
36        .enumerate()
37        .map(|(i, key)| (key, i))
38        .collect();
39    let mut rows = vec![Vec::new(); map.len()];
40    for (j, t) in transfers.iter().enumerate() {
41        for k in 0..3 {
42            rows[map[&(k, t[k])]].push(j);
43        }
44    }
45    rows.retain(|r| r.len() > 1);
46    let n = weights.len();
47    let m = rows.len();
48    let mut indptr = vec![0];
49    let mut indices = Vec::new();
50    for row in rows {
51        indices.extend(row);
52        indptr.push(indices.len());
53    }
54    let values = vec![1.; indices.len()];
55    let model = Model::new(ModelData {
56        objective: weights,
57        objective_offset: 0.,
58        sense: Sense::Maximize,
59        variables: Bounds::new(vec![0.; n], vec![1.; n]),
60        kinds: vec![VariableKind::Binary; n],
61        matrix: CsrMatrix {
62            pattern: CsrPattern {
63                rows: m,
64                cols: n,
65                indptr,
66                indices,
67            },
68            values,
69        },
70        rows: Bounds::new(vec![f64::NEG_INFINITY; m], vec![1.; m]),
71    })?;
72    let seconds = args.get(2).map(|v| v.parse()).transpose()?.unwrap_or(5.);
73    let packing = args.get(3).is_some_and(|s| s == "packing");
74    #[cfg(feature = "kernel-profile")]
75    profile::reset();
76    let start = Instant::now();
77    let r = NativeSolver::new(NativeOptions {
78        time_limit_seconds: Some(seconds),
79        component_threads: 1,
80        packing_root: packing,
81        ..Default::default()
82    })
83    .solve(
84        &model,
85        &Options::default(),
86        None,
87        &CancellationToken::default(),
88    )?;
89    println!(
90        "{{\"status\":{:?},\"seconds\":{},\"pivots\":{},\"profile\":[",
91        r.status.as_str(),
92        start.elapsed().as_secs_f64(),
93        r.iterations
94    );
95    #[cfg(feature = "kernel-profile")]
96    for (index, (name, ns, count)) in profile::snapshot().iter().enumerate() {
97        if index > 0 {
98            println!(",");
99        }
100        print!("{{\"operation\":{name:?},\"exclusive_nanoseconds\":{ns},\"count\":{count}}}");
101    }
102    println!("]}}");
103    Ok(())
104}
examples/performance_parallel.rs (line 277)
206fn main() {
207    let args: Vec<_> = std::env::args().collect();
208    let family = args.get(1).map(String::as_str).unwrap_or("packing");
209    let n = args.get(2).map(|v| v.parse().unwrap()).unwrap_or(128);
210    let mode = args.get(3).map(String::as_str).unwrap_or("single");
211    let inner = args.get(4).map(|v| v.parse().unwrap()).unwrap_or(1);
212    let workers = args.get(5).map(|v| v.parse().unwrap()).unwrap_or(1);
213    let jobs = args.get(6).map(|v| v.parse().unwrap()).unwrap_or(1);
214    assert!(inner * workers <= 8 && inner > 0 && workers > 0 && jobs > 0);
215    #[cfg(feature = "parallel-bench")]
216    if family == "factor" {
217        assert_eq!(workers, 1);
218        assert_eq!(jobs, 3);
219        let q = lp_ip_craft_native::parallel_bench::run(n, inner).unwrap();
220        println!(
221            "{{\"kernel_profile\":{},\"version\":\"{}\",\"family\":\"factor\",\"size\":{n},\"mode\":\"{mode}\",\"inner\":{inner},\"workers\":1,\"jobs\":3,\"completed\":3,\"seconds\":{},\"workflow_seconds\":{},\"resource_seconds\":{},\"objective\":0.0,\"residual\":{},\"checksum\":{},\"pivots\":0,\"nodes\":0,\"status\":\"checked\"}}",
222            cfg!(feature = "kernel-profile"),
223            env!("CARGO_PKG_VERSION"),
224            q.seconds,
225            q.workflow_seconds,
226            q.resource_seconds,
227            q.error,
228            q.checksum
229        );
230        return;
231    }
232    let mut settings = NativeOptions {
233        decompose: false,
234        component_threads: 1,
235        packing_workers: 1,
236        tree_threads: 1,
237        time_limit_seconds: Some(20.),
238        ..Default::default()
239    };
240    if mode.contains("components") {
241        settings.decompose = true;
242        settings.component_threads = workers;
243        settings.component_parallel_min_entries = 0;
244    }
245    if mode == "tree" {
246        settings.tree_threads = workers;
247        settings.tree_split_depth = 3;
248    }
249    if mode == "residual" {
250        settings.packing_workers = workers;
251        settings.packing_root = true;
252        settings.packing_neighborhoods = 16;
253        settings.packing_neighborhood_size = 24;
254        settings.packing_rounds = 2;
255    }
256    let models: Vec<_> = (0..jobs)
257        .map(|i| {
258            if mode.contains("components") {
259                blocks(n, mode == "skewcomponents")
260            } else {
261                fixture(
262                    family,
263                    if mode == "skewbatch" && i >= jobs * 3 / 4 {
264                        n * 4
265                    } else {
266                        n
267                    },
268                )
269            }
270        })
271        .collect();
272    let options = Options {
273        threads: inner,
274        ..Default::default()
275    };
276    let token = CancellationToken::default();
277    let solver = NativeSolver::new(settings);
278    let t = Instant::now();
279    let result = if mode.contains("batch") {
280        solver
281            .solve_batch(
282                &models.iter().map(|p| &p.0).collect::<Vec<_>>(),
283                &options,
284                workers,
285                &token,
286            )
287            .unwrap()
288    } else {
289        assert_eq!(jobs, 1);
290        vec![NativeSolver::new(solver.settings.clone()).solve(&models[0].0, &options, None, &token)]
291    };
292    let seconds = t.elapsed().as_secs_f64();
293    assert_eq!(result.len(), jobs);
294    let (mut objective, mut residual, mut pivots, mut nodes) = (0_f64, 0_f64, 0_u64, 0_u64);
295    for ((m, e), r) in models.iter().zip(result) {
296        let r = r.unwrap();
297        let (c, k) = check_result(m, *e, &r);
298        objective += c;
299        residual = residual.max(k);
300        pivots += r.iterations;
301        nodes += r.nodes;
302    }
303    println!(
304        "{{\"kernel_profile\":{},\"version\":\"{}\",\"family\":\"{family}\",\"size\":{n},\"mode\":\"{mode}\",\"inner\":{inner},\"workers\":{workers},\"jobs\":{jobs},\"completed\":{jobs},\"seconds\":{seconds},\"objective\":{objective},\"residual\":{residual},\"pivots\":{pivots},\"nodes\":{nodes},\"status\":\"optimal\"}}",
305        cfg!(feature = "kernel-profile"),
306        env!("CARGO_PKG_VERSION")
307    );
308}

Trait Implementations§

Source§

impl Clone for NativeSolver

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for NativeSolver

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for NativeSolver

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl LpIpSolver for NativeSolver

Source§

fn solve( &mut self, model: &Model, options: &Options, start: Option<&WarmStart>, cancel: &CancellationToken, ) -> Result<SolveResult>

Solves model, optionally from start. Read more

Auto Trait Implementations§

§

impl Forget for NativeSolver

§

impl Freeze for NativeSolver
where *const u8 is !null: Freeze, PhantomData<u8>: Freeze,

§

impl Move for NativeSolver

§

impl RefUnwindSafe for NativeSolver

§

impl Send for NativeSolver
where RawVecInner: Send,

§

impl Sync for NativeSolver
where RawVecInner: Sync,

§

impl Unpin for NativeSolver
where *const u8 is !null: Unpin,

§

impl UnsafeUnpin for NativeSolver

§

impl UnwindSafe for NativeSolver
where RawVecInner: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.