//////////////////////////// GATEWAY HEADER //////////////////////////// // // _| _| _|_|_| _|_|_| _|_| _|_|_| _|_| // _|_| _|_| _| _| _| _| _| _| _| _| // _| _| _| _| _| _| _|_|_|_| _| _| _| // _| _| _| _| _| _| _| _| _| _| // _| _| _|_|_| _|_|_| _| _| _|_|_| _|_| // // Version 7 // //////////////////////////////////////////////////////////////////////// // // See the MIDACO user manual for detailed information // //////////////////////////////////////////////////////////////////////// // // THE RUST GATEWAY // ---------------- // // let solution = midaco::run( problem_function, &problem, &option, key ); // // problem_function(f, g, x) evaluates the objectives f[0..o] and // the constraints g[0..m] at x[0..n] // problem midaco::Problem dimensions, bounds, starting point // option midaco::Options stopping criteria, printing, PARAM, // parallelization // key &str the MIDACO license key // solution midaco::Solution f, g, x, iflag and the pareto front // // PARALLELIZATION: with option.parallel = P > 1 the P points of a // cycle are evaluated on several threads (std::thread::scope, no // extra crate). problem_function is then called from several threads // at once - Rust checks at compile time that it may be (it has to be // 'Sync', i.e. it must not change shared data without a lock). // // THE LIBRARY: libmidacors.a lies next to Cargo.toml and build.rs // links it. // //////////////////////////////////////////////////////////////////////// use std::ffi::{CStr, CString}; use std::io::Write; use std::os::raw::{c_char, c_int}; //////////////////////////////////////////////////////////////////////// // The problem definition, the options and the solution //////////////////////////////////////////////////////////////////////// /// Problem dimensions, bounds 'xl' & 'xu' and the starting point 'x' #[derive(Clone, Debug)] pub struct Problem { pub o: usize, // Number of objectives pub n: usize, // Number of variables (in total) pub ni: usize, // Number of integer variables (0 <= ni <= n) pub m: usize, // Number of constraints (in total) pub me: usize, // Number of equality constraints (0 <= me <= m) pub xl: Vec, // Lower bounds (n entries) pub xu: Vec, // Upper bounds (n entries) pub x: Vec, // Starting point (n entries) } /// MIDACO options. Options::default() is the MIDACO default for each. #[derive(Clone, Debug)] pub struct Options { pub maxeval: i64, // Maximum evaluation budget pub maxtime: i64, // Maximum time limit in seconds pub printeval: i64, // Print-Frequency for current best solution pub save2file: i64, // Save SCREEN and SOLUTION to TXT-files [0=NO/1=YES/>1=HISTORY] pub resumable: i64, // Resumable mode [0=NO/1=YES] pub param: [f64; 15], // MIDACO parameters PARAM(1...15) pub parallel: i64, // Serial: 0 or 1, Parallel: 2,3,4,... } impl Default for Options { fn default() -> Self { Options { maxeval: 10000, maxtime: 60 * 60 * 24, printeval: 1000, save2file: 1, resumable: 0, param: [0.0; 15], parallel: 0, } } } /// The solution found by MIDACO #[derive(Clone, Debug)] #[allow(dead_code)] pub struct Solution { pub f: Vec, // Objectives F(X) pub g: Vec, // Constraints G(X) pub x: Vec, // Solution X pub iflag: i32, // MIDACO information flag pub psize: usize, // Number of pareto points pub paretofront: Vec, // The full pareto front array (pf) } //////////////////////////////////////////////////////////////////////// // midaco::run - the reverse communication loop //////////////////////////////////////////////////////////////////////// pub fn run(problem_function: F, problem: &Problem, option: &Options, key: &str) -> Solution where F: Fn(&mut [f64], &mut [f64], &[f64]) + Sync, { let (o, n, m) = (problem.o, problem.n, problem.m); assert!(o >= 1 && n >= 1, "MIDACO: problem.o and problem.n must be >= 1"); for (v, name) in [(&problem.xl, "xl"), (&problem.xu, "xu"), (&problem.x, "x")] { assert!(v.len() == n, "MIDACO: problem.{} has {} entries, but n = {}", name, v.len(), n); } let mut p_: c_int = if option.parallel >= 2 { to_int(option.parallel) } else { 1 }; let mut o_: c_int = to_int(o as i64); let mut n_: c_int = to_int(n as i64); let mut ni_: c_int = to_int(problem.ni as i64); let mut m_: c_int = to_int(m as i64); let mut me_: c_int = to_int(problem.me as i64); let p = p_ as usize; let printeval = to_int(option.printeval); let save2file = to_int(option.save2file); let resumable = to_int(option.resumable); let maxeval = to_int(option.maxeval); let mut maxeval_: c_int = maxeval; // the solver takes it by reference let maxtime = to_int(option.maxtime); let mut param = option.param; let key_ = CString::new(key).expect("MIDACO: the key must not contain a NUL character"); // Workspace lengths let (mut lrw, mut liw): (c_int, c_int) = (0, 0); unsafe { midaco_ws(&mut p_, &mut o_, &mut n_, &mut ni_, &mut m_, &mut lrw, &mut liw) }; assert!(lrw > 0 && liw > 0, "MIDACO cannot split parallel = {}", p); let mut lpf: c_int = 1; if o > 1 { let s = (o + m + n) as c_int; lpf = 1000 * s + 1 + 100; if param[9] >= 1.0 { lpf = (param[9] as c_int) * s + 1; } if param[9] <= -1.0 { lpf = (-param[9] as c_int) * s + 1; } } let mg = m.max(1); // m = 0: g is a one entry dummy per point let mut xl = problem.xl.clone(); let mut xu = problem.xu.clone(); let mut x0 = problem.x.clone(); // Re-scale Infinity values: MIDACO needs finite bounds if xl.iter().chain(xu.iter()).chain(x0.iter()).any(|v| v.is_infinite()) { for i in 0..n { if xl[i].is_infinite() { xl[i] = -1.0e+6; } if xu[i].is_infinite() { xu[i] = 1.0e+6; } if x0[i].is_infinite() { x0[i] = xl[i]; } } println!("\n NOTE: Infinity Values have been rescaled to 1.0E+6 \n"); } // The P points of a cycle, one after another let mut x: Vec = x0.iter().cloned().cycle().take(p * n).collect(); let mut f = vec![0.0f64; p * o]; let mut g = vec![0.0f64; p * mg]; let mut rw = vec![0.0f64; lrw as usize]; let mut iw = vec![0 as c_int; liw as usize]; let mut pf = vec![0.0f64; lpf as usize]; let (mut iflag, mut istop): (c_int, c_int) = (0, 0); // The threads for P > 1: never more than points or processors let threads = std::thread::available_parallelism().map(|t| t.get()).unwrap_or(1).min(p); let per = (p + threads - 1) / threads; // points per thread unsafe { midaco_screen(Some(screen)) }; // MIDACO's screen output goes to screen() // Print MIDACO head information unsafe { midaco_print(1, printeval, save2file, resumable, &mut iflag, &mut istop, f.as_mut_ptr(), g.as_mut_ptr(), x.as_mut_ptr(), xl.as_mut_ptr(), xu.as_mut_ptr(), o_, n_, ni_, m_, me_, rw.as_mut_ptr(), lrw, iw.as_mut_ptr(), liw, pf.as_mut_ptr(), maxeval, maxtime, param.as_mut_ptr(), p_, key_.as_ptr()) }; flush_screen(); while istop == 0 // Call MIDACO by reverse communication loop { // Evaluate F(X) and G(X) of the P points if p == 1 { problem_function(&mut f[..o], &mut g[..m], &x[..n]); } else { let func = &problem_function; std::thread::scope(|s| { for ((fb, gb), xb) in f.chunks_mut(per * o).zip(g.chunks_mut(per * mg)).zip(x.chunks(per * n)) { s.spawn(move || { for ((fc, gc), xc) in fb.chunks_mut(o).zip(gb.chunks_mut(mg)).zip(xb.chunks(n)) { func(fc, &mut gc[..m], xc); } }); } }); } // Check and repair NaN and Inf for v in f.iter_mut() { if v.is_nan() { *v = 1.0e+33; } else if v.is_infinite() { *v = 1.0e+32; } } if m > 0 { for v in g.iter_mut() { if v.is_nan() { *v = -1.0e+33; } else if v.is_infinite() { *v = -1.0e+32; } } } unsafe { midaco(&mut p_, &mut o_, &mut n_, &mut ni_, &mut m_, &mut me_, x.as_mut_ptr(), f.as_mut_ptr(), g.as_mut_ptr(), xl.as_mut_ptr(), xu.as_mut_ptr(), &mut iflag, &mut istop, param.as_mut_ptr(), rw.as_mut_ptr(), &mut lrw, iw.as_mut_ptr(), &mut liw, pf.as_mut_ptr(), &mut lpf, &mut maxeval_, key_.as_ptr()); midaco_print(2, printeval, save2file, resumable, &mut iflag, &mut istop, f.as_mut_ptr(), g.as_mut_ptr(), x.as_mut_ptr(), xl.as_mut_ptr(), xu.as_mut_ptr(), o_, n_, ni_, m_, me_, rw.as_mut_ptr(), lrw, iw.as_mut_ptr(), liw, pf.as_mut_ptr(), maxeval, maxtime, param.as_mut_ptr(), p_, key_.as_ptr()); } flush_screen(); } unsafe { midaco_screen(None) }; // The solution is the first point of the arrays Solution { f: f[..o].to_vec(), g: g[..m].to_vec(), x: x[..n].to_vec(), iflag: iflag as i32, psize: pf[0] as usize, paretofront: pf, } } //////////////////////////////////////////////////////////////////////// // MIDACO's screen output: every piece of text the library prints //////////////////////////////////////////////////////////////////////// extern "C" fn screen(text: *const c_char) { if text.is_null() { return; } let text = unsafe { CStr::from_ptr(text) }; let _ = std::io::stdout().write_all(text.to_bytes()); } fn flush_screen() { let _ = std::io::stdout().flush(); } // MIDACO's integers are 4-byte 'int' on every platform: clipped, so // that e.g. maxeval = 10000000000 cannot wrap around fn to_int(v: i64) -> c_int { v.clamp(c_int::MIN as i64, c_int::MAX as i64) as c_int } //////////////////////////////////////////////////////////////////////// // The MIDACO library (libmidacors.a, linked by build.rs) //////////////////////////////////////////////////////////////////////// extern "C" { fn midaco(p: *mut c_int, o: *mut c_int, n: *mut c_int, ni: *mut c_int, m: *mut c_int, me: *mut c_int, x: *mut f64, f: *mut f64, g: *mut f64, xl: *mut f64, xu: *mut f64, iflag: *mut c_int, istop: *mut c_int, param: *mut f64, rw: *mut f64, lrw: *mut c_int, iw: *mut c_int, liw: *mut c_int, pf: *mut f64, lpf: *mut c_int, maxeval: *mut c_int, key: *const c_char) -> c_int; fn midaco_print(c: c_int, printeval: c_int, save2file: c_int, resumable: c_int, iflag: *mut c_int, istop: *mut c_int, f: *mut f64, g: *mut f64, x: *mut f64, xl: *mut f64, xu: *mut f64, o: c_int, n: c_int, ni: c_int, m: c_int, me: c_int, rw: *mut f64, lrw: c_int, iw: *mut c_int, liw: c_int, pf: *mut f64, maxeval: c_int, maxtime: c_int, param: *mut f64, p: c_int, key: *const c_char) -> c_int; fn midaco_ws(p: *mut c_int, o: *mut c_int, n: *mut c_int, ni: *mut c_int, m: *mut c_int, lrw: *mut c_int, liw: *mut c_int) -> c_int; fn midaco_screen(receiver: Option); } //////////////////////////////////////////////////////////////////////// ////////////////////////////// END OF FILE ///////////////////////////// ////////////////////////////////////////////////////////////////////////