use std::sync::Arc;
use num_bigint::BigUint;
use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;
use crate::mdd::heuristics::*;
use crate::mdd::*;
use crate::modelling::*;
use super::heuristics::{PyMergeHeuristic, PyOrderingHeuristic, PySelectHeuristic};
use super::problem::PyProblem;
#[pyclass(name = "Compiler")]
pub struct PyCompiler {
problem: Arc<Problem>,
}
#[pymethods]
impl PyCompiler {
#[new]
fn new(problem: &PyProblem) -> Self {
PyCompiler {
problem: problem.arc(),
}
}
#[pyo3(signature = (constraints=None, max_width=None,
pyordering=PyOrderingHeuristic::MinDomMaxLinked(),
pymerge=PyMergeHeuristic::StateSimilarity,
pyselect=PySelectHeuristic::Greedy))]
fn compile(
&self,
constraints: Option<Vec<usize>>,
max_width: Option<usize>,
pyordering: PyOrderingHeuristic,
pymerge: PyMergeHeuristic,
pyselect: PySelectHeuristic,
) -> PyMdd {
let ordering: OrderingHeuristic = pyordering.into();
let merge = pymerge.into_heuristic(&self.problem);
let select: SelectHeuristic = pyselect.into();
let constraints: Vec<ConstraintIndex> = match constraints {
Some(cs) => cs.into_iter().map(ConstraintIndex).collect(),
None => self.problem.iter_constraints().collect(),
};
let mut compiler = Compiler::new(
Arc::clone(&self.problem),
CompilationHeuristic {
ordering,
merge,
selection: select,
},
&constraints,
);
if let Some(width) = max_width {
compiler.refine(width);
}
PyMdd {
held: Held::Compiling(Box::new(compiler)),
}
}
fn number_variables(&self) -> usize {
self.problem.number_variables()
}
fn number_constraints(&self) -> usize {
self.problem.number_constraints()
}
fn constraint_scope(&self, constraint: usize) -> Vec<usize> {
self.problem[ConstraintIndex(constraint)]
.iter_scope()
.map(|v| v.0)
.collect()
}
fn variable_domain_size(&self, variable: usize) -> usize {
self.problem[VariableIndex(variable)].domain_size()
}
fn variable_domain(&self, variable: usize) -> Vec<isize> {
self.problem[VariableIndex(variable)]
.iter_domain()
.collect()
}
}
enum Held {
Compiling(Box<Compiler>),
Frozen(Mdd),
Moving,
}
#[pyclass]
pub struct PyMdd {
held: Held,
}
impl PyMdd {
fn mdd(&self) -> &Mdd {
match &self.held {
Held::Compiling(compiler) => compiler.mdd(),
Held::Frozen(mdd) => mdd,
Held::Moving => unreachable!("freeze leaves the diagram in place"),
}
}
}
#[pymethods]
impl PyMdd {
fn refine(&mut self, max_width: usize) -> PyResult<()> {
match &mut self.held {
Held::Compiling(compiler) => {
compiler.refine(max_width);
Ok(())
}
_ => Err(PyRuntimeError::new_err(
"this diagram is frozen: it was released from its compiler and cannot be refined",
)),
}
}
fn freeze(&mut self) {
self.held = match std::mem::replace(&mut self.held, Held::Moving) {
Held::Compiling(compiler) => Held::Frozen(compiler.into_mdd()),
other => other,
};
}
fn is_frozen(&self) -> bool {
matches!(self.held, Held::Frozen(_))
}
fn is_unsat(&self) -> bool {
self.mdd().is_unsat()
}
#[pyo3(signature = (sample=false))]
fn get_solution(&self, sample: bool) -> Option<(Vec<isize>, Vec<usize>)> {
let mdd = self.mdd();
if mdd.is_unsat() {
return None;
}
let (values, variables) = if sample {
let weights = crate::sampling::uniform_weights(mdd);
let path = crate::sampling::sample_solution(mdd, &weights);
mdd.solution_from_path(&path)
} else {
mdd.get_solution()?
};
let mut assignment: Vec<(usize, isize)> = variables
.into_iter()
.map(|variable| variable.0)
.zip(values)
.collect();
assignment.sort_unstable();
Some(assignment.into_iter().map(|(v, value)| (value, v)).unzip())
}
fn scope(&self) -> Vec<usize> {
let mdd = self.mdd();
let mut scope: Vec<usize> = (0..mdd.number_decisions())
.map(|layer| mdd.decision_at_layer(layer).0)
.collect();
scope.sort_unstable();
scope
}
fn is_solution(&self, solution: Vec<isize>) -> bool {
self.mdd().problem().is_solution(&solution)
}
fn count_solutions(&self) -> BigUint {
self.mdd().count_solutions()
}
fn number_layers(&self) -> usize {
self.mdd().number_layers()
}
fn number_nodes_in_layer(&self, layer: usize) -> usize {
self.mdd().number_nodes_in_layer(layer)
}
fn number_variables(&self) -> usize {
self.mdd().problem().number_variables()
}
fn number_constraints(&self) -> usize {
self.mdd().problem().number_constraints()
}
fn constraint_scope(&self, constraint: usize) -> Vec<usize> {
self.mdd().problem()[ConstraintIndex(constraint)]
.iter_scope()
.map(|v| v.0)
.collect()
}
fn variable_domain_size(&self, variable: usize) -> usize {
self.mdd().problem()[VariableIndex(variable)].domain_size()
}
fn variable_domain(&self, variable: usize) -> Vec<isize> {
self.mdd().problem()[VariableIndex(variable)]
.iter_domain()
.collect()
}
fn as_graphviz(&self) -> String {
self.mdd().as_graphviz()
}
fn show_memory_info(&self) {
self.mdd().show_memory_footprint();
}
}