use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::error::{Error, Result, ensure};
use crate::model::{Model, Sense};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Status {
Stub,
Cancelled,
Optimal,
Infeasible,
Unbounded,
InfeasibleOrUnbounded,
TimeLimit,
NodeLimit,
GapLimit,
IterationLimit,
SolutionLimit,
ObjectiveLimit,
MemoryLimit,
NumericalFailure,
Unknown,
}
impl Status {
pub fn as_str(self) -> &'static str {
match self {
Status::Stub => "stub",
Status::Cancelled => "cancelled",
Status::Optimal => "optimal",
Status::Infeasible => "infeasible",
Status::Unbounded => "unbounded",
Status::InfeasibleOrUnbounded => "infeasible_or_unbounded",
Status::TimeLimit => "time_limit",
Status::NodeLimit => "node_limit",
Status::GapLimit => "gap_limit",
Status::IterationLimit => "iteration_limit",
Status::SolutionLimit => "solution_limit",
Status::ObjectiveLimit => "objective_limit",
Status::MemoryLimit => "memory_limit",
Status::NumericalFailure => "numerical_failure",
Status::Unknown => "unknown",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Tolerances {
pub feasibility: f64,
pub integrality: f64,
}
impl Default for Tolerances {
fn default() -> Self {
Self {
feasibility: 1e-7,
integrality: 1e-7,
}
}
}
impl Tolerances {
pub fn validate(&self) -> Result<()> {
ensure(
self.feasibility.is_finite() && self.feasibility > 0.0,
|| {
format!(
"feasibility tolerance must be positive and finite, got {}",
self.feasibility
)
},
)?;
ensure(
self.integrality.is_finite() && self.integrality > 0.0 && self.integrality < 0.5,
|| {
format!(
"integrality tolerance must lie in (0, 0.5), got {}",
self.integrality
)
},
)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Options {
pub tolerances: Tolerances,
pub threads: usize,
}
impl Default for Options {
fn default() -> Self {
Self {
tolerances: Tolerances::default(),
threads: 1,
}
}
}
impl Options {
pub fn validate(&self) -> Result<()> {
self.tolerances.validate()?;
ensure(self.threads > 0, || "threads must be at least 1".into())?;
if self.threads > 8 {
return Err(Error::Unsupported(format!(
"threads = {}: maximum numerical budget is 8",
self.threads
)));
}
Ok(())
}
}
#[derive(Clone, Debug, Default)]
pub struct CancellationToken(Arc<AtomicBool>);
impl CancellationToken {
pub fn cancel(&self) {
self.0.store(true, Ordering::Relaxed);
}
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct WarmStart {
pub primal: Vec<f64>,
}
impl WarmStart {
pub fn from_primal(primal: Vec<f64>) -> Self {
Self { primal }
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Evaluation {
pub objective: f64,
pub row_activity: Vec<f64>,
pub primal_violation: f64,
pub integrality_violation: f64,
pub feasible_candidate: bool,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Duals {
pub row_duals: Vec<f64>,
pub reduced_costs: Vec<f64>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Gap {
pub absolute: f64,
pub relative: f64,
}
impl Gap {
pub fn new(sense: Sense, objective: f64, bound: f64) -> Self {
let absolute = match sense {
Sense::Minimize => objective - bound,
Sense::Maximize => bound - objective,
};
let relative = if objective != 0.0 {
absolute / objective.abs()
} else if absolute == 0.0 {
0.0
} else {
f64::INFINITY.copysign(absolute)
};
Self { absolute, relative }
}
pub fn try_new(sense: Sense, objective: f64, bound: f64) -> Result<Self> {
crate::error::finite(objective, "gap objective")?;
crate::error::finite(bound, "gap bound")?;
let gap = Self::new(sense, objective, bound);
crate::error::finite(gap.absolute, "absolute gap")?;
if objective != 0.0 {
crate::error::finite(gap.relative, "relative gap")?;
}
Ok(gap)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct SolveResult {
pub status: Status,
pub candidate: Option<Vec<f64>>,
pub evaluation: Option<Evaluation>,
pub duals: Option<Duals>,
pub best_bound: Option<f64>,
pub nodes: u64,
pub iterations: u64,
pub message: String,
pub backend: BackendReport,
}
impl SolveResult {
pub fn empty(status: Status, message: impl Into<String>, backend: BackendReport) -> Self {
Self {
status,
candidate: None,
evaluation: None,
duals: None,
best_bound: None,
nodes: 0,
iterations: 0,
message: message.into(),
backend,
}
}
pub fn gap(&self, sense: Sense) -> Result<Option<Gap>> {
match (&self.evaluation, self.best_bound) {
(Some(e), Some(bound)) if e.feasible_candidate => {
Gap::try_new(sense, e.objective, bound).map(Some)
}
_ => Ok(None),
}
}
}
pub trait LpIpSolver {
fn solve(
&mut self,
model: &Model,
options: &Options,
start: Option<&WarmStart>,
cancel: &CancellationToken,
) -> Result<SolveResult>;
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StartStatus {
#[default]
NotProvided,
Submitted,
Rejected,
Evaluated,
}
impl StartStatus {
pub fn as_str(self) -> &'static str {
match self {
StartStatus::NotProvided => "not_provided",
StartStatus::Submitted => "submitted",
StartStatus::Rejected => "rejected",
StartStatus::Evaluated => "evaluated",
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BackendReport {
pub name: String,
pub version: Option<String>,
pub raw_status: Option<String>,
pub start_status: StartStatus,
pub effective_options: Vec<(String, String)>,
pub total_seconds: f64,
pub conversion_seconds: f64,
pub solve_seconds: f64,
pub check_seconds: f64,
pub time_budget_exceeded: bool,
}
impl BackendReport {
pub fn new(name: &str) -> Self {
Self {
name: name.into(),
..Self::default()
}
}
}