use std::sync::Arc;
use polypus_observable::{IsingObservable, QuboObservable};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
#[pyclass(module = "polypus", name = "Qubo", frozen)]
pub struct Qubo {
pub(crate) inner: Arc<QuboObservable>,
}
#[pymethods]
impl Qubo {
#[new]
#[pyo3(signature = (num_vars, linear=None, quadratic=None, constant=0.0, scale=1.0))]
fn new(
num_vars: usize,
linear: Option<Vec<(usize, f64)>>,
quadratic: Option<Vec<(usize, usize, f64)>>,
constant: f64,
scale: f64,
) -> PyResult<Self> {
let inner = QuboObservable::new(
num_vars,
linear.unwrap_or_default(),
quadratic.unwrap_or_default(),
constant,
scale,
)
.map_err(|e| PyValueError::new_err(e.to_string()))?;
Ok(Self {
inner: Arc::new(inner),
})
}
#[staticmethod]
#[pyo3(signature = (matrix, scale=1.0))]
fn from_matrix(matrix: Vec<Vec<f64>>, scale: f64) -> PyResult<Self> {
let inner = QuboObservable::from_matrix(&matrix, scale)
.map_err(|e| PyValueError::new_err(e.to_string()))?;
Ok(Self {
inner: Arc::new(inner),
})
}
#[getter]
fn num_vars(&self) -> usize {
self.inner.num_vars()
}
fn __repr__(&self) -> String {
format!("Qubo(num_vars={})", self.inner.num_vars())
}
}
#[pyclass(module = "polypus", name = "Ising", frozen)]
pub struct Ising {
pub(crate) inner: Arc<IsingObservable>,
}
#[pymethods]
impl Ising {
#[new]
#[pyo3(signature = (num_vars, fields=None, couplings=None, constant=0.0, scale=1.0))]
fn new(
num_vars: usize,
fields: Option<Vec<(usize, f64)>>,
couplings: Option<Vec<(usize, usize, f64)>>,
constant: f64,
scale: f64,
) -> PyResult<Self> {
let inner = IsingObservable::new(
num_vars,
fields.unwrap_or_default(),
couplings.unwrap_or_default(),
constant,
scale,
)
.map_err(|e| PyValueError::new_err(e.to_string()))?;
Ok(Self {
inner: Arc::new(inner),
})
}
#[getter]
fn num_vars(&self) -> usize {
self.inner.num_vars()
}
fn __repr__(&self) -> String {
format!("Ising(num_vars={})", self.inner.num_vars())
}
}
#[pyclass(module = "polypus", name = "CachedCost", frozen)]
pub struct CachedCost {
pub(crate) cost_fn: Py<PyAny>,
}
#[pymethods]
impl CachedCost {
#[new]
fn new(cost_fn: Bound<'_, PyAny>) -> PyResult<Self> {
if !cost_fn.is_callable() {
return Err(pyo3::exceptions::PyTypeError::new_err(
"CachedCost expects a callable (bitstring -> float)",
));
}
Ok(Self {
cost_fn: cost_fn.unbind(),
})
}
fn __repr__(&self) -> String {
"CachedCost(<callable>)".to_string()
}
}
#[pyclass(module = "polypus", name = "SampleCost", frozen)]
pub struct SampleCost {
pub(crate) cost_fn: Py<PyAny>,
}
#[pymethods]
impl SampleCost {
#[new]
fn new(cost_fn: Bound<'_, PyAny>) -> PyResult<Self> {
if !cost_fn.is_callable() {
return Err(pyo3::exceptions::PyTypeError::new_err(
"SampleCost expects a callable ((counts, label) -> float)",
));
}
Ok(Self {
cost_fn: cost_fn.unbind(),
})
}
fn __repr__(&self) -> String {
"SampleCost(<callable>)".to_string()
}
}