use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyBool, PyDict, PyList, PyModule};
use pyo3::wrap_pyfunction;
use pyo3::Bound;
use pyo3::PyResult;
pub mod adam;
pub mod calibration;
pub mod callback;
pub mod circuit;
pub mod cmaes;
mod compatibility;
pub mod de;
pub mod expr;
pub mod external;
pub mod logging;
pub mod observable;
pub mod pso;
pub mod qml;
pub mod qng;
pub mod rotosolve;
pub mod spsa;
use adam::Adam;
use calibration::calibrate_parallel_threshold;
use callback::{validate_callback, PyTrainObserver, TrainProgress};
use circuit::{qft, shor_order_finding, statevector, Circuit, Param};
use cmaes::CMAES;
use compatibility::backend_compatibility;
use de::DE;
use external::External;
use logging::init_logger;
use observable::{CachedCost, Ising, Qubo, SampleCost};
use pso::PSO;
use qng::QNG;
use rotosolve::Rotosolve;
use spsa::Spsa;
use crate::evaluation::{
CircuitSource, CostObservable, Label, OracleErrorSlot, PyCallbackObservable, PyLabelledCost,
PySampleCost, PyVarianceOracle, QmlObjective, QmlOracleFactory, QmlSource, SupervisedObjective,
VqcOracleFactory,
};
use crate::infrastructure::execution_config::{random_id_bytes, random_seed};
use crate::infrastructure::{
merge_counts, validate_walltime, BackendConfig, BoundCircuit, Counts, EntropyError,
ExecutionConfig, Infrastructure, InfrastructureError, OptLevel, OptionValue, Planner,
ShotDistributingPlanner, DEFAULT_WALLTIME,
};
use crate::orchestration::{
AdamConfig, CmaesConfig, DeConfig, ExternalConfig, FinalEvaluation, Method, OracleError,
PsoConfig, QngConfig, Resources, RotosolveConfig, RunCircuitFlow, Scheduler, SpsaConfig,
TrainFlow, TrainObserver, TrainOutcome,
};
use polypus_optimizers::{OptimizationOutcome, VarianceOracle};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
struct SignalInterrupt;
impl crate::infrastructure::Interrupt for SignalInterrupt {
fn poll(&self) -> Result<(), crate::infrastructure::BackendError> {
crate::infrastructure::attach_or(
|| Err(crate::infrastructure::InterpreterUnavailable.into()),
|py| {
py.check_signals()
.map_err(crate::infrastructure::seam_error)
},
)
}
}
fn interruptible_token() -> crate::infrastructure::CancelToken {
crate::infrastructure::CancelToken::with_interrupt(Arc::new(SignalInterrupt))
}
#[pyclass(module = "polypus", frozen)]
pub struct RunResult {
#[pyo3(get)]
pub counts: Py<PyAny>,
#[pyo3(get)]
pub merged_counts: Py<PyAny>,
#[pyo3(get)]
pub id: String,
#[pyo3(get)]
pub seed: Option<u64>,
#[pyo3(get)]
pub backend: String,
#[pyo3(get)]
pub infrastructure: String,
}
#[pymethods]
impl RunResult {
fn __repr__(&self, py: Python<'_>) -> PyResult<String> {
let seed = self
.seed
.map_or_else(|| "None".to_string(), |s| s.to_string());
Ok(format!(
"RunResult(counts={}, merged_counts={}, id={:?}, seed={seed}, backend={:?}, \
infrastructure={:?})",
self.counts.bind(py).repr()?,
self.merged_counts.bind(py).repr()?,
self.id,
self.backend,
self.infrastructure
))
}
}
fn counts_to_pydict<'py>(py: Python<'py>, counts: &Counts) -> PyResult<Bound<'py, PyDict>> {
let mut outcomes: Vec<(&String, &u64)> = counts.iter().collect();
outcomes.sort_unstable_by(|a, b| a.0.cmp(b.0));
let dict = PyDict::new(py);
for (bitstring, n) in outcomes {
dict.set_item(bitstring, n)?;
}
Ok(dict)
}
fn counts_to_pylist<'py>(py: Python<'py>, counts: &[Counts]) -> PyResult<Bound<'py, PyList>> {
let list = PyList::empty(py);
for map in counts {
list.append(counts_to_pydict(py, map)?)?;
}
Ok(list)
}
#[pyclass(module = "polypus", frozen)]
pub struct TrainResult {
#[pyo3(get)]
pub best_params: Vec<f64>,
#[pyo3(get)]
pub best_fitness: f64,
#[pyo3(get)]
pub iterations_run: usize,
#[pyo3(get)]
pub converged: bool,
#[pyo3(get)]
pub fitness_history: Vec<f64>,
#[pyo3(get)]
pub final_params: Option<Vec<f64>>,
#[pyo3(get)]
pub final_fitness: Option<f64>,
#[pyo3(get)]
pub seed: u64,
#[pyo3(get)]
pub id: String,
}
#[pymethods]
impl TrainResult {
fn __repr__(&self) -> String {
let final_fitness = self
.final_fitness
.map_or(String::new(), |value| format!(", final_fitness={value}"));
let final_params = self
.final_params
.as_ref()
.map_or(String::new(), |params| format!(", final_params={params:?}"));
format!(
"TrainResult(id={:?}, best_fitness={}{final_fitness}, iterations_run={}, \
converged={}, seed={}, best_params={:?}{final_params})",
self.id,
self.best_fitness,
self.iterations_run,
self.converged,
self.seed,
self.best_params
)
}
}
fn outcome_to_train_result(
py: Python<'_>,
outcome: OptimizationOutcome,
final_evaluation: Option<FinalEvaluation>,
seed: u64,
id: String,
) -> PyResult<Py<PyAny>> {
let (final_params, final_fitness) = match final_evaluation {
Some(evaluation) => (Some(evaluation.params), Some(evaluation.fitness)),
None => (None, None),
};
Py::new(
py,
TrainResult {
best_params: outcome.best_params,
best_fitness: outcome.best_fitness,
iterations_run: outcome.iterations_run,
converged: outcome.converged,
fitness_history: outcome.fitness_history,
final_params,
final_fitness,
seed,
id,
},
)
.map(|result| result.into_any())
}
fn resolve_optimizer_seed(
kwarg_seed: Option<u64>,
method_seed: Option<u64>,
draw: impl FnOnce() -> Result<u64, EntropyError>,
) -> PyResult<u64> {
seed_or_entropy(kwarg_seed.or(method_seed), draw)
}
fn seed_or_entropy(
seed: Option<u64>,
draw: impl FnOnce() -> Result<u64, EntropyError>,
) -> PyResult<u64> {
match seed {
Some(seed) => Ok(seed),
None => draw().map_err(|e| {
crate::exceptions::backend_error_to_pyerr(crate::infrastructure::BackendError::from(e))
}),
}
}
fn unique_id(base: &str) -> PyResult<String> {
unique_id_from(base, random_id_bytes)
}
fn unique_id_from(
base: &str,
draw: impl FnOnce() -> Result<[u8; 16], EntropyError>,
) -> PyResult<String> {
let bytes = draw().map_err(|e| {
crate::exceptions::backend_error_to_pyerr(crate::infrastructure::BackendError::from(e))
})?;
Ok(format!(
"{}_{}",
base,
uuid::Builder::from_random_bytes(bytes).into_uuid()
))
}
fn log_training_start(
id: &str,
infrastructure: &str,
backend: &str,
n_qpus: u32,
shots: u32,
seed: u64,
) {
log::info!(
"training run {id} starting: infrastructure={infrastructure}, backend={backend}, \
n_qpus={n_qpus}, shots={shots}, seed={seed}"
);
}
fn method_seed(method: &Bound<'_, PyAny>) -> Option<u64> {
if let Ok(de) = method.extract::<PyRef<DE>>() {
return de.seed;
}
if let Ok(pso) = method.extract::<PyRef<PSO>>() {
return pso.seed;
}
if let Ok(qng) = method.extract::<PyRef<QNG>>() {
return qng.seed;
}
if let Ok(cmaes) = method.extract::<PyRef<CMAES>>() {
return cmaes.seed;
}
if let Ok(adam) = method.extract::<PyRef<Adam>>() {
return adam.seed;
}
if let Ok(spsa) = method.extract::<PyRef<Spsa>>() {
return spsa.seed;
}
if let Ok(rotosolve) = method.extract::<PyRef<Rotosolve>>() {
return rotosolve.seed;
}
None
}
fn check_external_initial_point(
method: &Bound<'_, PyAny>,
initial_point: Option<&[f64]>,
) -> PyResult<()> {
if initial_point.is_none() || method.extract::<PyRef<External>>().is_err() {
return Ok(());
}
Err(crate::exceptions::configuration_error(
"polypus.External takes no initial_point: the external optimizer chooses its own \
start. Give the starting point to the library, or to the initial_point of the \
polypus.ask_tell adapter (from_optuna, from_nevergrad); for pycma it is the x0 of \
cma.CMAEvolutionStrategy",
))
}
fn is_rotosolve(method: &Bound<'_, PyAny>) -> bool {
method.extract::<PyRef<Rotosolve>>().is_ok()
}
fn rotosolve_circuit_error(reason: &str) -> PyErr {
crate::exceptions::configuration_error(format!(
"polypus.Rotosolve cannot train this circuit: {reason}. Rotosolve needs every \
trainable parameter to be exactly one angle of an rx, ry, rz, rxx, rzz, p, u1, u, \
u2 or u3 gate (also ryy, rzx, or the θ of an r, in a Qiskit circuit), as ±θ + c, \
so that the fitness is a sinusoid of each parameter; train this circuit with \
another optimizer"
))
}
fn check_rotosolve_circuit(
circuit: &Bound<'_, PyAny>,
source: Option<&CircuitSource>,
trainable: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
if let Some(CircuitSource::Native(native)) = source {
return native
.check_single_frequency()
.map_err(|problem| rotosolve_circuit_error(&problem.to_string()));
}
let py = circuit.py();
let problem = PyModule::import(py, "polypus_python.rotosolve")?
.getattr("single_frequency_problem")?
.call1((circuit, trainable))?;
if problem.is_none() {
return Ok(());
}
Err(rotosolve_circuit_error(&problem.extract::<String>()?))
}
fn validate_method(
method: &Bound<'_, PyAny>,
dimensions: u32,
initial_point: Option<&[f64]>,
) -> PyResult<()> {
let parsed = method_from_pyclass(method, dimensions, &OracleErrorSlot::new(), "")?;
let point = match parsed {
Method::External(..) => None,
_ => initial_point,
};
parsed
.check_preconditions(dimensions, point)
.map_err(|e| crate::exceptions::configuration_error(e.to_string()))?;
check_external_initial_point(method, initial_point)
}
fn validate_final_shots(final_shots: Option<&Bound<'_, PyAny>>) -> PyResult<Option<u32>> {
let Some(value) = final_shots.filter(|value| !value.is_none()) else {
return Ok(None);
};
let index = positive_index(value, "final_shots")?;
match index.extract::<u32>() {
Ok(shots) => Ok(Some(shots)),
Err(_) => Err(too_large(value, "final_shots", u32::MAX)),
}
}
pub(crate) fn training_observer(
callback: Option<Py<PyAny>>,
errors: &OracleErrorSlot,
run_id: &str,
) -> Option<Box<dyn TrainObserver>> {
callback.map(|callback| -> Box<dyn TrainObserver> {
Box::new(PyTrainObserver::new(callback, errors, run_id))
})
}
fn positive_index<'py>(value: &Bound<'py, PyAny>, name: &str) -> PyResult<Bound<'py, PyAny>> {
let message = || format!("{name} must be an integer >= 1, got {}", shown_repr(value));
let not_an_integer = || pyo3::exceptions::PyTypeError::new_err(message());
if value.is_instance_of::<PyBool>() {
return Err(not_an_integer());
}
let py = value.py();
let index = match PyModule::import(py, "operator")?.call_method1("index", (value,)) {
Ok(index) => index,
Err(err) if err.is_instance_of::<pyo3::exceptions::PyTypeError>(py) => {
return Err(not_an_integer());
}
Err(err) => return Err(err),
};
if index.lt(1)? {
return Err(crate::exceptions::configuration_error(message()));
}
Ok(index)
}
fn too_large(value: &Bound<'_, PyAny>, name: &str, max: impl std::fmt::Display) -> PyErr {
crate::exceptions::configuration_error(format!(
"{name} must be at most {max}, got {}",
shown_repr(value)
))
}
fn shown_repr(value: &Bound<'_, PyAny>) -> String {
value
.repr()
.map_or_else(|_| "an unprintable value".to_string(), |r| r.to_string())
}
fn finish_optimization(
py: Python<'_>,
result: Result<TrainOutcome, OracleError>,
seed: u64,
id: String,
start: Instant,
) -> PyResult<Py<PyAny>> {
let (outcome, final_evaluation) = match result {
Ok(outcome) => (outcome.optimization, outcome.final_evaluation),
Err(OracleError::Evaluation(boxed)) => {
return Err(
match boxed.downcast::<crate::evaluation::EvaluationError>() {
Ok(eval_err) => crate::exceptions::evaluation_error_to_pyerr(*eval_err),
Err(other) => crate::exceptions::EvaluationError::new_err(other.to_string()),
},
);
}
Err(OracleError::Config(
oracle_err @ (polypus_optimizers::OptimizerError::OracleLengthMismatch { .. }
| polypus_optimizers::OptimizerError::NonFiniteGradient { .. }),
)) => {
log::error!("run {id}: evaluation failed: {oracle_err}");
return Err(crate::exceptions::EvaluationError::new_err(
oracle_err.to_string(),
));
}
Err(OracleError::Config(config_err)) => {
log::error!("run {id}: optimizer rejected the configuration: {config_err}");
return Err(crate::exceptions::configuration_error(
config_err.to_string(),
));
}
};
let final_fitness = final_evaluation
.as_ref()
.map_or(String::new(), |evaluation| {
format!(", final_fitness={}", evaluation.fitness)
});
log::info!(
"training run {id} completed: iterations_run={}, converged={}{final_fitness}, duration={:?}",
outcome.iterations_run,
outcome.converged,
start.elapsed()
);
outcome_to_train_result(py, outcome, final_evaluation, seed, id)
}
fn method_from_pyclass(
method: &Bound<'_, PyAny>,
dimensions: u32,
errors: &OracleErrorSlot,
run_id: &str,
) -> PyResult<Method> {
if let Ok(de) = method.extract::<PyRef<DE>>() {
return Ok(Method::De(DeConfig {
generations: de.generations,
population_size: de.population_size,
tolerance: de.tolerance,
patience: de.patience,
strategy: de.strategy,
mutation_factor: de.mutation_factor,
crossover_rate: de.crossover_rate,
}));
}
if let Ok(pso) = method.extract::<PyRef<PSO>>() {
return Ok(Method::Pso(PsoConfig {
generations: pso.generations,
population_size: pso.population_size,
bounds: pso.bounds,
inertia_weight: pso.inertia_weight,
cognitive_weight: pso.cognitive_weight,
social_weight: pso.social_weight,
tolerance: pso.tolerance,
}));
}
if let Ok(qng) = method.extract::<PyRef<QNG>>() {
let variance_oracle: Box<dyn VarianceOracle> = Box::new(PyVarianceOracle {
variance_function: qng.variance_function.clone_ref(method.py()),
errors: errors.clone(),
run_id: run_id.to_string(),
});
return Ok(Method::Qng(
QngConfig {
max_iters: qng.max_iters,
learning_rate: qng.learning_rate,
finite_difference_step: qng.finite_difference_step,
bounds: qng.bounds,
tikhonov_reg: qng.tikhonov_reg,
},
variance_oracle,
));
}
if let Ok(cmaes) = method.extract::<PyRef<CMAES>>() {
return Ok(Method::Cmaes(CmaesConfig {
generations: cmaes.generations,
population_size: cmaes.population_size,
sigma0: cmaes.sigma0,
tolerance: cmaes.tolerance,
patience: cmaes.patience,
restarts: cmaes.restarts,
}));
}
if let Ok(adam) = method.extract::<PyRef<Adam>>() {
return Ok(Method::Adam(AdamConfig {
max_iters: adam.max_iters,
learning_rate: adam.learning_rate,
beta1: adam.beta1,
beta2: adam.beta2,
epsilon: adam.epsilon,
bounds: adam.bounds,
tolerance: adam.tolerance,
patience: adam.patience,
finite_difference_step: adam.finite_difference_step,
rule: adam.rule,
}));
}
if let Ok(spsa) = method.extract::<PyRef<Spsa>>() {
return Ok(Method::Spsa(SpsaConfig {
max_iters: spsa.max_iters,
resamplings: spsa.resamplings,
perturbation: spsa.perturbation,
target_step: spsa.target_step,
alpha: spsa.alpha,
gamma: spsa.gamma,
stability_constant: spsa.stability_constant,
eval_interval: spsa.eval_interval,
}));
}
if let Ok(rotosolve) = method.extract::<PyRef<Rotosolve>>() {
return Ok(Method::Rotosolve(RotosolveConfig {
sweeps: rotosolve.sweeps,
reevaluate_every: rotosolve.reevaluate_every,
tolerance: rotosolve.tolerance,
patience: rotosolve.patience,
}));
}
if let Ok(external) = method.extract::<PyRef<External>>() {
let (max_evaluations, optimizer) =
external.for_run(method.py(), dimensions, errors, run_id);
return Ok(Method::External(
ExternalConfig { max_evaluations },
Box::new(optimizer),
));
}
Err(pyo3::exceptions::PyTypeError::new_err(
"method must be an instance of polypus.DE, polypus.PSO, polypus.QNG, polypus.CMAES, \
polypus.Adam, polypus.SPSA, polypus.Rotosolve, or polypus.External",
))
}
pub(crate) struct OptionsArg(HashMap<String, OptionValue>);
impl OptionsArg {
fn into_inner(self) -> HashMap<String, OptionValue> {
self.0
}
}
impl<'a, 'py> FromPyObject<'a, 'py> for OptionsArg {
type Error = PyErr;
fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
use pyo3::exceptions::PyTypeError;
use pyo3::types::{PyString, PyTuple};
let type_name = |item: &Bound<'_, PyAny>| {
item.get_type()
.name()
.map_or_else(|_| "an unknown type".to_string(), |name| name.to_string())
};
let dict = ob.cast::<PyDict>().map_err(|_| {
PyTypeError::new_err(format!(
"options must be a dict of str keys to str or list[str] values, got {}",
type_name(&ob)
))
})?;
let mut options = HashMap::with_capacity(dict.len());
for item in dict.items().iter() {
let (key, value) = item.extract::<(Bound<'py, PyAny>, Bound<'py, PyAny>)>()?;
let key = match key.cast::<PyString>() {
Ok(key) => key.to_str()?.to_owned(),
Err(_) => {
return Err(PyTypeError::new_err(format!(
"options keys must be str, got {}",
type_name(&key)
)))
}
};
let value = if let Ok(text) = value.cast::<PyString>() {
OptionValue::Str(text.to_str()?.to_owned())
} else if value.is_instance_of::<PyList>() || value.is_instance_of::<PyTuple>() {
let elements: Vec<Bound<'py, PyAny>> = match value.cast::<PyList>() {
Ok(list) => list.iter().collect(),
Err(_) => value.cast::<PyTuple>()?.iter().collect(),
};
let mut items = Vec::with_capacity(elements.len());
for (idx, item) in elements.into_iter().enumerate() {
match item.cast::<PyString>() {
Ok(text) => items.push(text.to_str()?.to_owned()),
Err(_) => {
return Err(PyTypeError::new_err(format!(
"options['{key}'][{idx}] must be a str, got {}",
type_name(&item)
)))
}
}
}
OptionValue::List(items)
} else {
return Err(PyTypeError::new_err(format!(
"options['{key}'] must be a str or a list of str, got {}",
type_name(&value)
)));
};
options.insert(key, value);
}
Ok(OptionsArg(options))
}
}
fn build_backend_config(
infrastructure: &str,
backend: &str,
sim_method: &str,
noise_model: Option<Py<PyAny>>,
nodes: u32,
cores_per_qpu: u32,
walltime: Option<&str>,
fusion: Option<bool>,
options: Option<HashMap<String, OptionValue>>,
) -> PyResult<BackendConfig> {
let is_native = infrastructure == "local"
&& matches!(backend, "polypus" | "statevector" | "polypus_statevector");
if fusion == Some(true) && !is_native {
return Err(crate::exceptions::configuration_error(format!(
"fusion=True applies only to the native backend=\"polypus\"; backend \"{backend}\" \
on infrastructure \"{infrastructure}\" cannot fuse gates. Omit fusion, or pass \
fusion=False for a gate-by-gate run."
)));
}
if matches!(infrastructure, "local" | "cunqa") {
if let Some(opts) = &options {
if !opts.is_empty() {
return Err(crate::exceptions::configuration_error(format!(
"the '{infrastructure}' infrastructure does not accept 'options' ({} given); \
the 'options' dict applies only to registry-backed backends (\"qmio\", \
\"subprocess\", or a registered third-party backend)",
opts.len()
)));
}
}
}
if infrastructure == "cunqa" {
if !matches!(backend, "aer" | "AerSimulator") {
return Err(crate::exceptions::configuration_error(format!(
"unknown cunqa backend '{backend}'; CUNQA's QPUs run Aer, expected \"aer\""
)));
}
if noise_model.is_some() {
return Err(crate::exceptions::configuration_error(
"the 'cunqa' infrastructure does not accept a noise_model: its simulated QPUs \
are configured when they are raised, not per run; omit it, or use \
infrastructure=\"local\" with backend=\"aer\"",
));
}
}
match infrastructure {
"local" => match backend {
"aer" | "AerSimulator" => Ok(BackendConfig::Local {
sim_method: sim_method.to_string(),
noise_model,
}),
"polypus" | "statevector" | "polypus_statevector" => {
if noise_model.is_some() {
return Err(crate::exceptions::configuration_error(
"the native 'polypus' backend is a noiseless statevector simulator \
and does not accept a noise_model; use backend=\"aer\"",
));
}
if sim_method != "automatic" {
return Err(crate::exceptions::configuration_error(format!(
"the native 'polypus' backend is a statevector simulator and does \
not accept sim_method=\"{sim_method}\"; omit it, or use \
backend=\"aer\""
)));
}
Ok(BackendConfig::LocalNative {
fusion: fusion.unwrap_or(true),
})
}
other => Err(crate::exceptions::configuration_error(format!(
"unknown local backend '{other}'; expected \"aer\" or \"polypus\""
))),
},
"cunqa" => Ok(BackendConfig::Cunqa {
sim_method: sim_method.to_string(),
nodes,
cores_per_qpu,
walltime: walltime.unwrap_or(DEFAULT_WALLTIME).to_string(),
}),
"qmio" => {
let config = build_qmio_registered(backend, options)?;
reject_aer_only_args(infrastructure, sim_method, noise_model.as_ref())?;
Ok(config)
}
other => {
crate::infrastructure::register_builtin_backends();
if crate::infrastructure::is_registered(other) {
reject_aer_only_args(other, sim_method, noise_model.as_ref())?;
if backend != "aer" {
return Err(crate::exceptions::configuration_error(format!(
"the registered backend '{other}' does not accept backend=\"{backend}\"; \
omit it and pass backend-specific settings through 'options'"
)));
}
Ok(BackendConfig::Registered {
name: other.to_string(),
options: options.unwrap_or_default(),
})
} else {
Err(crate::exceptions::configuration_error(format!(
"unknown infrastructure '{other}'; expected \"local\", \"cunqa\", \"qmio\", \
or a registered backend name (see docs/backends.md)"
)))
}
}
}
}
fn reject_aer_only_args(
infrastructure: &str,
sim_method: &str,
noise_model: Option<&Py<PyAny>>,
) -> PyResult<()> {
if noise_model.is_some() {
return Err(crate::exceptions::configuration_error(format!(
"the '{infrastructure}' infrastructure does not accept a noise_model; it applies \
only to Aer (infrastructure=\"local\" with backend=\"aer\")"
)));
}
if sim_method != "automatic" {
return Err(crate::exceptions::configuration_error(format!(
"the '{infrastructure}' infrastructure does not accept sim_method=\"{sim_method}\"; \
it applies only to Aer (infrastructure=\"local\" or \"cunqa\")"
)));
}
Ok(())
}
#[cfg(feature = "qmio")]
fn build_qmio_registered(
backend: &str,
options: Option<HashMap<String, OptionValue>>,
) -> PyResult<BackendConfig> {
qmio_registered_config(backend, std::env::var("ZMQ_SERVER").ok(), options)
}
#[cfg(feature = "qmio")]
fn qmio_registered_config(
backend: &str,
zmq_server: Option<String>,
options: Option<HashMap<String, OptionValue>>,
) -> PyResult<BackendConfig> {
let program_format = match backend {
"aer" | "qmio" | "openqasm" | "qasm" => "openqasm",
"qir" | "qir_text" => "qir_text",
"qir_bitcode" | "qir_compiled" => "qir_bitcode",
other => {
return Err(crate::exceptions::configuration_error(format!(
"unknown qmio program format '{other}'; expected \"openqasm\", \"qir\", or \"qir_bitcode\""
)))
}
};
let mut opts: HashMap<String, OptionValue> = HashMap::new();
if let Some(endpoint) = zmq_server {
opts.insert("endpoint".to_string(), OptionValue::from(endpoint));
}
opts.insert(
"program_format".to_string(),
OptionValue::from(program_format),
);
opts.insert("optimization".to_string(), OptionValue::from("0"));
opts.insert("res_format".to_string(), OptionValue::from("binary_count"));
if let Some(user) = options {
opts.extend(user);
}
Ok(BackendConfig::Registered {
name: "qmio".to_string(),
options: opts,
})
}
#[cfg(not(feature = "qmio"))]
fn build_qmio_registered(
_backend: &str,
_options: Option<HashMap<String, OptionValue>>,
) -> PyResult<BackendConfig> {
Err(crate::exceptions::configuration_error(QMIO_NOT_COMPILED))
}
#[cfg(not(feature = "qmio"))]
const QMIO_NOT_COMPILED: &str =
"the 'qmio' infrastructure requires compiling polypus with --features qmio";
const QMIO_REJECTS_QISKIT: &str =
"the 'qmio' infrastructure runs entirely in Rust (GIL-free) and cannot \
serialize a Qiskit QuantumCircuit; pass a polypus.Circuit or an OpenQASM \
2.0 string";
const QMIO_REJECTS_QML: &str =
"the 'qmio' infrastructure runs entirely in Rust (GIL-free) and cannot \
serialize the Qiskit circuits of a QML model";
const NATIVE_REJECTS_QISKIT: &str =
"the native 'polypus' backend cannot execute a Qiskit QuantumCircuit; \
pass a polypus.Circuit or an OpenQASM 2.0 string, or use backend=\"aer\"";
fn is_native_backend(backend: &str) -> bool {
matches!(backend, "polypus" | "statevector" | "polypus_statevector")
}
fn validate_shots_and_qpus(shots: u32, n_qpus: u32) -> PyResult<()> {
if shots < 1 {
return Err(crate::exceptions::configuration_error(format!(
"shots must be >= 1, got {shots}"
)));
}
if n_qpus < 1 {
return Err(crate::exceptions::configuration_error(format!(
"n_qpus must be >= 1, got {n_qpus}"
)));
}
Ok(())
}
fn validate_cunqa_allocation(
infrastructure: &str,
nodes: u32,
cores_per_qpu: u32,
walltime: Option<&str>,
) -> PyResult<()> {
if infrastructure != "cunqa" {
return Ok(());
}
if nodes < 1 {
return Err(crate::exceptions::configuration_error(format!(
"nodes must be >= 1 for the 'cunqa' infrastructure, got {nodes}"
)));
}
if cores_per_qpu < 1 {
return Err(crate::exceptions::configuration_error(format!(
"cores_per_qpu must be >= 1 for the 'cunqa' infrastructure, got {cores_per_qpu}"
)));
}
if let Some(walltime) = walltime {
validate_walltime(walltime)
.map_err(|e| crate::exceptions::configuration_error(e.to_string()))?;
}
Ok(())
}
const MAX_ID_LEN: usize = 64;
fn validate_id(id: &str) -> PyResult<()> {
if id.is_empty() {
return Err(crate::exceptions::configuration_error(
"id must not be empty",
));
}
if let Some(c) = id
.chars()
.find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')))
{
return Err(crate::exceptions::configuration_error(format!(
"id contains invalid character {c:?}; only ASCII letters, digits, \
'.', '_' and '-' are allowed (got {id:?})"
)));
}
if id.len() > MAX_ID_LEN {
return Err(crate::exceptions::configuration_error(format!(
"id must be at most {MAX_ID_LEN} characters, got {} ({id:?})",
id.len()
)));
}
Ok(())
}
fn extract_circuit_source(qc: &Bound<'_, PyAny>) -> CircuitSource {
if let Ok(native) = qc.extract::<PyRef<'_, Circuit>>() {
CircuitSource::Native(native.native().clone())
} else {
CircuitSource::Qiskit(qc.clone().unbind())
}
}
const UNBOUND_PARAMETERS: &str = "circuit has unbound parameters and cannot be executed directly";
fn extract_bound_circuit(qc: &Bound<'_, PyAny>) -> PyResult<BoundCircuit> {
if let Ok(native) = qc.extract::<PyRef<'_, Circuit>>() {
let concrete = native.native().assign_parameters(&[]).map_err(|e| {
crate::exceptions::configuration_error(format!(
"{UNBOUND_PARAMETERS}: {e}. \
Bind values first via to_qasm2(params) or use polypus.train"
))
})?;
return Ok(BoundCircuit::Native(concrete));
}
if let Ok(qasm) = qc.extract::<String>() {
return Ok(BoundCircuit::Qasm2(qasm));
}
let free = free_parameter_names(qc)?;
if !free.is_empty() {
return Err(crate::exceptions::configuration_error(format!(
"{UNBOUND_PARAMETERS}: {}. \
Bind values first via QuantumCircuit.assign_parameters or use polypus.train",
free.join(", ")
)));
}
Ok(crate::infrastructure::QiskitCircuit::into_bound(
qc.clone().unbind(),
))
}
fn free_parameter_names(qc: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
let Ok(parameters) = qc.getattr(pyo3::intern!(qc.py(), "parameters")) else {
return Ok(Vec::new());
};
parameters
.try_iter()?
.map(|parameter| Ok(parameter?.str()?.to_string()))
.collect()
}
fn extract_cost_observable(obj: &Bound<'_, PyAny>) -> PyResult<Arc<dyn CostObservable>> {
if let Ok(q) = obj.extract::<PyRef<'_, Qubo>>() {
let concrete = Arc::clone(&q.inner);
let obs: Arc<dyn CostObservable> = concrete;
return Ok(obs);
}
if let Ok(i) = obj.extract::<PyRef<'_, Ising>>() {
let concrete = Arc::clone(&i.inner);
let obs: Arc<dyn CostObservable> = concrete;
return Ok(obs);
}
if let Ok(cached) = obj.extract::<PyRef<'_, CachedCost>>() {
let obs: Arc<dyn CostObservable> = Arc::new(PyCallbackObservable::new(
cached.cost_fn.clone_ref(obj.py()),
true,
));
return Ok(obs);
}
if obj.is_callable() {
let obs: Arc<dyn CostObservable> =
Arc::new(PyCallbackObservable::new(obj.clone().unbind(), false));
return Ok(obs);
}
if obj.extract::<PyRef<'_, SampleCost>>().is_ok() {
return Err(pyo3::exceptions::PyTypeError::new_err(
"polypus.SampleCost scores each training sample against its label, so it needs \
labels: use it with polypus.qml.train(..., y_train=...). Without labels, pass a \
callable (bitstring -> float)",
));
}
Err(pyo3::exceptions::PyTypeError::new_err(
"expectation_function must be a callable (bitstring -> float), a \
polypus.CachedCost(callable), or a polypus.Qubo / polypus.Ising observable",
))
}
fn extract_supervised_objective(obj: &Bound<'_, PyAny>) -> PyResult<Arc<dyn SupervisedObjective>> {
if let Ok(sample) = obj.extract::<PyRef<'_, SampleCost>>() {
let objective: Arc<dyn SupervisedObjective> =
Arc::new(PySampleCost::new(sample.cost_fn.clone_ref(obj.py())));
return Ok(objective);
}
if let Ok(cached) = obj.extract::<PyRef<'_, CachedCost>>() {
let objective: Arc<dyn SupervisedObjective> = Arc::new(PyLabelledCost::new(
cached.cost_fn.clone_ref(obj.py()),
true,
));
return Ok(objective);
}
if obj.extract::<PyRef<'_, Qubo>>().is_ok() || obj.extract::<PyRef<'_, Ising>>().is_ok() {
return Err(pyo3::exceptions::PyTypeError::new_err(
"a polypus.Qubo / polypus.Ising observable cannot read labels; with y_train, \
expectation_function must be a callable (bitstring, label) -> float, a \
polypus.CachedCost(callable) or a polypus.SampleCost(callable)",
));
}
if obj.is_callable() {
let objective: Arc<dyn SupervisedObjective> =
Arc::new(PyLabelledCost::new(obj.clone().unbind(), false));
return Ok(objective);
}
Err(pyo3::exceptions::PyTypeError::new_err(
"with y_train, expectation_function must be a callable (bitstring, label) -> float, \
a polypus.CachedCost(callable) or a polypus.SampleCost((counts, label) -> float)",
))
}
fn extract_labels(y_train: &Bound<'_, PyAny>) -> PyResult<Vec<Label>> {
use pyo3::exceptions::PyTypeError;
use pyo3::types::PyString;
enum Raw {
Int(i64),
Float(f64),
}
let type_name = |item: &Bound<'_, PyAny>| {
item.get_type()
.name()
.map_or_else(|_| "an unknown type".to_string(), |name| name.to_string())
};
let mut raw = Vec::new();
for (idx, item) in y_train.try_iter()?.enumerate() {
let item = item?;
if item.is_instance_of::<PyString>() {
return Err(PyTypeError::new_err(format!(
"y_train[{idx}] is a str; labels must be numbers (int class labels or float \
targets) — encode class names as integers first"
)));
}
if let Ok(len) = item.len() {
return Err(PyTypeError::new_err(format!(
"y_train[{idx}] is a sequence ({} of length {len}), not a single label; pass \
one number per x_train row (class indices rather than one-hot rows; \
y.ravel() for a column vector)",
type_name(&item)
)));
}
if let Ok(value) = item.extract::<i64>() {
raw.push(Raw::Int(value));
continue;
}
let is_numpy_bool = item
.getattr("dtype")
.and_then(|dtype| dtype.getattr("kind"))
.and_then(|kind| kind.extract::<String>())
.is_ok_and(|kind| kind == "b");
if is_numpy_bool {
raw.push(Raw::Int(i64::from(item.is_truthy()?)));
continue;
}
match item.extract::<f64>() {
Ok(value) if value.is_finite() => raw.push(Raw::Float(value)),
Ok(value) => {
return Err(crate::exceptions::configuration_error(format!(
"y_train[{idx}] is {value}; labels must be finite numbers"
)));
}
Err(_) => {
return Err(PyTypeError::new_err(format!(
"y_train[{idx}] has type {}; labels must be numbers (int class labels or \
float targets)",
type_name(&item)
)));
}
}
}
let all_integers = raw.iter().all(|r| matches!(r, Raw::Int(_)));
Ok(raw
.into_iter()
.map(|r| match r {
Raw::Int(value) if all_integers => Label::Class(value),
Raw::Int(value) => Label::Real(value as f64),
Raw::Float(value) => Label::Real(value),
})
.collect())
}
#[pyfunction(signature=(qc, shots, infrastructure, n_qpus=1, nodes=1, cores_per_qpu=2, sim_method="automatic", noise_model=None, backend="aer", seed=None, fusion=None, options=None, walltime=None))]
pub fn run_quantum_circuit<'py>(
qc: Bound<'py, PyAny>,
shots: u32,
infrastructure: String,
n_qpus: u32,
nodes: u32,
cores_per_qpu: u32,
sim_method: &str,
noise_model: Option<Bound<'py, PyAny>>,
backend: &str,
seed: Option<u64>,
fusion: Option<bool>,
options: Option<OptionsArg>,
walltime: Option<String>,
) -> PyResult<Py<PyAny>> {
let start = Instant::now();
log::debug!(
"run_quantum_circuit called with qc: {qc:?}, shots: {shots}, \
infrastructure: {infrastructure}, n_qpus: {n_qpus}, backend: {backend}, seed: {seed:?}"
);
validate_shots_and_qpus(shots, n_qpus)?;
validate_cunqa_allocation(&infrastructure, nodes, cores_per_qpu, walltime.as_deref())?;
let bound_qc = extract_bound_circuit(&qc)?;
if is_native_backend(backend) && bound_qc.is_foreign() {
return Err(crate::exceptions::configuration_error(
NATIVE_REJECTS_QISKIT,
));
}
if infrastructure == "qmio" && bound_qc.is_foreign() {
return Err(crate::exceptions::configuration_error(QMIO_REJECTS_QISKIT));
}
let effective_seed: Option<u64> = if infrastructure == "qmio" {
if seed.is_some() {
return Err(crate::exceptions::configuration_error(
"seed is not supported for the 'qmio' infrastructure (real quantum hardware)",
));
}
None
} else {
Some(seed_or_entropy(seed, random_seed)?)
};
let id = unique_id(&format!("run_{}_{}", n_qpus, infrastructure))?;
let backend_config = build_backend_config(
&infrastructure,
backend,
sim_method,
noise_model.map(|nm| nm.unbind()),
nodes,
cores_per_qpu,
walltime.as_deref(),
fusion,
options.map(OptionsArg::into_inner),
)?;
if matches!(backend_config, BackendConfig::LocalNative { .. }) {
calibration::prepare_native_threshold(qc.py())?;
}
let config = ExecutionConfig {
id: id.clone(),
shots,
n_qpus,
infrastructure: infrastructure.clone(),
backend_config,
opt_level: OptLevel::default(),
seed: effective_seed,
};
log::info!(
"run {id} starting: infrastructure={infrastructure}, backend={backend}, \
n_qpus={n_qpus}, shots={shots}, seed={effective_seed:?}"
);
let counts_result = qc
.py()
.detach(move || -> Result<Vec<Counts>, InfrastructureError> {
let backend =
Infrastructure::create_backend(&config).map_err(InfrastructureError::Backend)?;
let planner: Option<Arc<dyn Planner>> = if n_qpus == 1 {
None
} else {
Some(Arc::new(ShotDistributingPlanner::new(n_qpus)))
};
let resources = Resources::new(backend, planner, Arc::new(config.run_params()))?;
let scheduler = Scheduler::ephemeral(resources);
let out = scheduler.run_cancellable(
RunCircuitFlow {
circuits: vec![bound_qc],
shots,
},
&interruptible_token(),
);
scheduler.close();
out
});
let counts_vec = counts_result.map_err(crate::exceptions::infrastructure_error_to_pyerr)?;
log::info!("run {id} completed: duration={:?}", start.elapsed());
let merged = merge_counts(&counts_vec);
Python::attach(|py| {
let counts = counts_to_pylist(py, &counts_vec)?.into_any().unbind();
let merged_counts = counts_to_pydict(py, &merged)?.into_any().unbind();
Py::new(
py,
RunResult {
counts,
merged_counts,
id,
seed: effective_seed,
backend: backend.to_string(),
infrastructure,
},
)
.map(|result| result.into_any())
})
}
#[pyfunction(signature = (qc, method, shots, n_qpus, dimensions, expectation_function, infrastructure, nodes, cores_per_qpu, id, sim_method="automatic", noise_model=None, backend="aer", seed=None, fusion=None, options=None, walltime=None, initial_point=None, final_shots=None, *, callback=None))]
pub fn train<'py>(
qc: Bound<'py, PyAny>,
method: Bound<'py, PyAny>,
shots: u32,
n_qpus: u32,
dimensions: u32,
expectation_function: Bound<'py, PyAny>,
infrastructure: String,
nodes: u32,
cores_per_qpu: u32,
id: String,
sim_method: &str,
noise_model: Option<Bound<'py, PyAny>>,
backend: &str,
seed: Option<u64>,
fusion: Option<bool>,
options: Option<OptionsArg>,
walltime: Option<String>,
initial_point: Option<Vec<f64>>,
final_shots: Option<Bound<'py, PyAny>>,
callback: Option<Bound<'py, PyAny>>,
) -> PyResult<Py<PyAny>> {
let start = Instant::now();
validate_shots_and_qpus(shots, n_qpus)?;
validate_cunqa_allocation(&infrastructure, nodes, cores_per_qpu, walltime.as_deref())?;
validate_id(&id)?;
let effective_seed = resolve_optimizer_seed(seed, method_seed(&method), random_seed)?;
let circuit_source = extract_circuit_source(&qc);
if let Some(num_params) = circuit_source.num_params() {
if num_params != dimensions as usize {
return Err(crate::exceptions::configuration_error(format!(
"dimensions ({dimensions}) does not match the circuit's free parameters ({num_params})"
)));
}
}
validate_method(&method, dimensions, initial_point.as_deref())?;
let final_shots = validate_final_shots(final_shots.as_ref())?;
let callback = validate_callback(callback.as_ref())?;
if is_native_backend(backend) {
if let CircuitSource::Qiskit(_) = &circuit_source {
return Err(crate::exceptions::configuration_error(
"the native 'polypus' backend requires a native polypus.Circuit; \
got a Qiskit circuit. Build it with polypus.Circuit or use backend=\"aer\"",
));
}
}
if infrastructure == "qmio" {
if let CircuitSource::Qiskit(_) = &circuit_source {
return Err(crate::exceptions::configuration_error(
"the 'qmio' infrastructure requires a native polypus.Circuit (GIL-free \
serialization); got a Qiskit circuit. Build it with polypus.Circuit",
));
}
}
if is_rotosolve(&method) {
check_rotosolve_circuit(&qc, Some(&circuit_source), None)?;
}
let backend_config = build_backend_config(
&infrastructure,
backend,
sim_method,
noise_model.map(|nm| nm.unbind()),
nodes,
cores_per_qpu,
walltime.as_deref(),
fusion,
options.map(OptionsArg::into_inner),
)?;
if matches!(backend_config, BackendConfig::LocalNative { .. }) {
calibration::prepare_native_threshold(qc.py())?;
}
let effective_id = unique_id(&id)?;
let config = Arc::new(ExecutionConfig {
id: effective_id.clone(),
shots,
n_qpus,
infrastructure: infrastructure.clone(),
backend_config,
opt_level: OptLevel::default(),
seed: Some(effective_seed),
});
let errors = OracleErrorSlot::new();
let observable = extract_cost_observable(&expectation_function)?;
let method_enum = method_from_pyclass(&method, dimensions, &errors, &effective_id)?;
log_training_start(
&effective_id,
&infrastructure,
backend,
n_qpus,
shots,
effective_seed,
);
let backend = Infrastructure::create_backend(&config)
.map_err(crate::exceptions::backend_error_to_pyerr)?;
let resources = Resources::new(backend, None, Arc::new(config.run_params()))
.map_err(crate::exceptions::infrastructure_error_to_pyerr)?;
let scheduler = Scheduler::ephemeral(resources);
let flow = TrainFlow {
factory: VqcOracleFactory {
circuit: circuit_source,
observable,
},
method: method_enum,
dimensions,
seed: effective_seed,
initial_point,
final_shots,
observer: training_observer(callback, &errors, &effective_id),
errors: errors.clone(),
};
let token = interruptible_token();
let result = method
.py()
.detach(|| scheduler.run_cancellable(flow, &token));
scheduler.close();
finish_optimization(method.py(), result, effective_seed, effective_id, start)
}
fn compose_qml_template<'py>(
feature_map: &Bound<'py, PyAny>,
ansatz: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
let qiskit = crate::exceptions::qiskit_error_to_evaluation_error;
let composed = feature_map
.call_method1("compose", (ansatz,))
.map_err(qiskit)?;
let num_clbits: usize = composed.getattr("num_clbits")?.extract()?;
if num_clbits == 0 {
composed.call_method0("measure_all").map_err(qiskit)?;
}
Ok(composed)
}
fn bind_feature_rows<'py>(
template: &Bound<'py, PyAny>,
feature_map: &Bound<'py, PyAny>,
rows: &Bound<'py, PyAny>,
rows_name: &str,
) -> PyResult<Vec<Py<PyAny>>> {
let py = template.py();
let fm_params = feature_map.getattr("parameters")?;
let builtins = PyModule::import(py, "builtins")?;
let fm_params_list = builtins.call_method1("list", (&fm_params,))?;
let kwargs_assign = [("inplace", false)].into_py_dict(py)?;
let fm_len = fm_params_list.len()?;
let mut circuits: Vec<Py<PyAny>> = Vec::new();
for (row_idx, row_result) in rows.try_iter()?.enumerate() {
let row = row_result?;
let row_len = row.len()?;
if row_len != fm_len {
return Err(crate::exceptions::configuration_error(format!(
"{rows_name} row {row_idx} has {row_len} features, but feature_map expects \
{fm_len} (len(feature_map.parameters))"
)));
}
let param_dict = PyDict::new(py);
for (param, val) in fm_params_list.try_iter()?.zip(row.try_iter()?) {
param_dict.set_item(param?, val?)?;
}
circuits.push(
template
.call_method("assign_parameters", (¶m_dict,), Some(&kwargs_assign))
.map_err(crate::exceptions::qiskit_error_to_evaluation_error)?
.unbind(),
);
}
Ok(circuits)
}
#[pyfunction(name = "train", signature = (feature_map, ansatz, x_train, method, shots, n_qpus, dimensions, expectation_function, infrastructure, nodes, cores_per_qpu, id, sim_method="automatic", noise_model=None, backend="aer", seed=None, options=None, walltime=None, *, y_train=None, initial_point=None, final_shots=None, callback=None))]
pub fn qml_train<'py>(
feature_map: Bound<'py, PyAny>,
ansatz: Bound<'py, PyAny>,
x_train: Bound<'py, PyAny>,
method: Bound<'py, PyAny>,
shots: u32,
n_qpus: u32,
dimensions: u32,
expectation_function: Bound<'py, PyAny>,
infrastructure: String,
nodes: u32,
cores_per_qpu: u32,
id: String,
sim_method: &str,
noise_model: Option<Bound<'py, PyAny>>,
backend: &str,
seed: Option<u64>,
options: Option<OptionsArg>,
walltime: Option<String>,
y_train: Option<Bound<'py, PyAny>>,
initial_point: Option<Vec<f64>>,
final_shots: Option<Bound<'py, PyAny>>,
callback: Option<Bound<'py, PyAny>>,
) -> PyResult<Py<PyAny>> {
let start = Instant::now();
validate_shots_and_qpus(shots, n_qpus)?;
validate_cunqa_allocation(&infrastructure, nodes, cores_per_qpu, walltime.as_deref())?;
validate_id(&id)?;
qml::reject_native_pieces("train", &feature_map, &ansatz)?;
let effective_seed = resolve_optimizer_seed(seed, method_seed(&method), random_seed)?;
if is_native_backend(backend) {
return Err(crate::exceptions::configuration_error(
"the native 'polypus' backend is not supported for qml.train (feature maps \
and ansätze are Qiskit circuits); use backend=\"aer\"",
));
}
if infrastructure == "qmio" {
return Err(crate::exceptions::configuration_error(QMIO_REJECTS_QML));
}
let num_ansatz_params = ansatz.getattr("parameters")?.len()?;
if num_ansatz_params != dimensions as usize {
return Err(crate::exceptions::configuration_error(format!(
"dimensions ({dimensions}) does not match the ansatz's free parameters ({num_ansatz_params})"
)));
}
validate_method(&method, dimensions, initial_point.as_deref())?;
let final_shots = validate_final_shots(final_shots.as_ref())?;
let callback = validate_callback(callback.as_ref())?;
let labels = y_train.as_ref().map(extract_labels).transpose()?;
let py = feature_map.py();
let rotosolve = is_rotosolve(&method);
if rotosolve
&& expectation_function
.extract::<PyRef<'_, SampleCost>>()
.is_ok()
{
return Err(crate::exceptions::configuration_error(
"polypus.Rotosolve cannot train with a polypus.SampleCost: Rotosolve needs a \
fitness that averages a cost per bitstring over the shots, so that it is a \
sinusoid of each parameter, and a SampleCost scores each sample's whole \
distribution. Use a callable (bitstring, label) -> float or a \
polypus.CachedCost, or another optimizer",
));
}
let composed = compose_qml_template(&feature_map, &ansatz)?;
if rotosolve {
check_rotosolve_circuit(&composed, None, Some(&ansatz.getattr("parameters")?))?;
}
let qcs = bind_feature_rows(&composed, &feature_map, &x_train, "x_train")?;
if qcs.is_empty() {
return Err(crate::exceptions::configuration_error(
"x_train must contain at least one training sample",
));
}
let supervised = match labels {
Some(labels) => {
if labels.len() != qcs.len() {
return Err(crate::exceptions::configuration_error(format!(
"y_train has {} labels, but x_train has {} rows; qml.train needs exactly \
one label per training sample",
labels.len(),
qcs.len()
)));
}
Some((extract_supervised_objective(&expectation_function)?, labels))
}
None => None,
};
let backend_config = build_backend_config(
&infrastructure,
backend,
sim_method,
noise_model.map(|nm| nm.unbind()),
nodes,
cores_per_qpu,
walltime.as_deref(),
None,
options.map(OptionsArg::into_inner),
)?;
let effective_id = unique_id(&id)?;
let config = Arc::new(ExecutionConfig {
id: effective_id.clone(),
shots,
n_qpus,
infrastructure: infrastructure.clone(),
backend_config,
opt_level: OptLevel::default(),
seed: Some(effective_seed),
});
let errors = OracleErrorSlot::new();
let objective = match supervised {
Some((objective, labels)) => QmlObjective::Supervised { objective, labels },
None => QmlObjective::Unsupervised(extract_cost_observable(&expectation_function)?),
};
let method_enum = method_from_pyclass(&method, dimensions, &errors, &effective_id)?;
log_training_start(
&effective_id,
&infrastructure,
backend,
n_qpus,
shots,
effective_seed,
);
let backend = Infrastructure::create_backend(&config)
.map_err(crate::exceptions::backend_error_to_pyerr)?;
let resources = Resources::new(backend, None, Arc::new(config.run_params()))
.map_err(crate::exceptions::infrastructure_error_to_pyerr)?;
let scheduler = Scheduler::ephemeral(resources);
let flow = TrainFlow {
factory: QmlOracleFactory {
source: QmlSource::Qiskit {
training_circuits: qcs,
objective,
},
minibatch: None,
},
method: method_enum,
dimensions,
seed: effective_seed,
initial_point,
final_shots,
observer: training_observer(callback, &errors, &effective_id),
errors: errors.clone(),
};
let token = interruptible_token();
let result = py.detach(|| scheduler.run_cancellable(flow, &token));
scheduler.close();
finish_optimization(py, result, effective_seed, effective_id, start)
}
#[pyfunction(name = "predict", signature = (feature_map, ansatz, x, params, shots, infrastructure, n_qpus=1, nodes=1, cores_per_qpu=2, sim_method="automatic", noise_model=None, backend="aer", seed=None, walltime=None))]
pub fn qml_predict<'py>(
feature_map: Bound<'py, PyAny>,
ansatz: Bound<'py, PyAny>,
x: Bound<'py, PyAny>,
params: Vec<f64>,
shots: u32,
infrastructure: String,
n_qpus: u32,
nodes: u32,
cores_per_qpu: u32,
sim_method: &str,
noise_model: Option<Bound<'py, PyAny>>,
backend: &str,
seed: Option<u64>,
walltime: Option<String>,
) -> PyResult<Py<PyAny>> {
let start = Instant::now();
validate_shots_and_qpus(shots, n_qpus)?;
validate_cunqa_allocation(&infrastructure, nodes, cores_per_qpu, walltime.as_deref())?;
qml::reject_native_pieces("predict", &feature_map, &ansatz)?;
if is_native_backend(backend) {
return Err(crate::exceptions::configuration_error(
"the native 'polypus' backend is not supported for qml.predict (feature maps \
and ansätze are Qiskit circuits); use backend=\"aer\"",
));
}
if infrastructure == "qmio" {
return Err(crate::exceptions::configuration_error(QMIO_REJECTS_QML));
}
let num_ansatz_params = ansatz.getattr("parameters")?.len()?;
if params.len() != num_ansatz_params {
return Err(crate::exceptions::configuration_error(format!(
"params has {} values, but the ansatz has {num_ansatz_params} free parameters",
params.len()
)));
}
if let Some((index, value)) = params.iter().enumerate().find(|(_, v)| !v.is_finite()) {
return Err(crate::exceptions::configuration_error(format!(
"params[{index}] is {value}; every weight must be a finite number"
)));
}
let py = feature_map.py();
let composed = compose_qml_template(&feature_map, &ansatz)?;
let rows = bind_feature_rows(&composed, &feature_map, &x, "x")?;
if rows.is_empty() {
return Err(crate::exceptions::configuration_error(
"x must contain at least one sample",
));
}
let kwargs_assign = [("inplace", false)].into_py_dict(py)?;
let circuits: Vec<BoundCircuit> = rows
.iter()
.map(|row| {
let circuit = row
.bind(py)
.call_method("assign_parameters", (params.clone(),), Some(&kwargs_assign))
.map_err(crate::exceptions::qiskit_error_to_evaluation_error)?
.unbind();
Ok(crate::infrastructure::QiskitCircuit::into_bound(circuit))
})
.collect::<PyResult<_>>()?;
let effective_seed = seed_or_entropy(seed, random_seed)?;
let id = unique_id(&format!("predict_{}_{}", n_qpus, infrastructure))?;
let backend_config = build_backend_config(
&infrastructure,
backend,
sim_method,
noise_model.map(|nm| nm.unbind()),
nodes,
cores_per_qpu,
walltime.as_deref(),
None,
None,
)?;
let config = ExecutionConfig {
id: id.clone(),
shots,
n_qpus,
infrastructure: infrastructure.clone(),
backend_config,
opt_level: OptLevel::default(),
seed: Some(effective_seed),
};
let n_rows = circuits.len();
log::info!(
"qml.predict {id} starting: rows={n_rows}, infrastructure={infrastructure}, \
backend={backend}, n_qpus={n_qpus}, shots={shots}, seed={effective_seed}"
);
let counts_result = py.detach(move || -> Result<Vec<Counts>, InfrastructureError> {
let backend =
Infrastructure::create_backend(&config).map_err(InfrastructureError::Backend)?;
let resources = Resources::new(backend, None, Arc::new(config.run_params()))?;
let scheduler = Scheduler::ephemeral(resources);
let out =
scheduler.run_cancellable(RunCircuitFlow { circuits, shots }, &interruptible_token());
scheduler.close();
out
});
let counts_vec = counts_result.map_err(crate::exceptions::infrastructure_error_to_pyerr)?;
log::info!("qml.predict {id} completed: duration={:?}", start.elapsed());
let counts = counts_to_pylist(py, &counts_vec)?.into_any().unbind();
Py::new(
py,
RunResult {
counts,
merged_counts: py.None(),
id,
seed: Some(effective_seed),
backend: backend.to_string(),
infrastructure,
},
)
.map(|result| result.into_any())
}
#[pyfunction]
fn backend_cleanup_failures() -> u64 {
crate::infrastructure::cleanup_failure_count()
}
fn python_version(cargo_version: &str) -> String {
match cargo_version.strip_suffix("-dev") {
Some(release) => format!("{release}.dev0"),
None => cargo_version.to_owned(),
}
}
#[pymodule]
pub fn polypus(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add("__version__", python_version(env!("CARGO_PKG_VERSION")))?;
crate::exceptions::register(m)?;
m.add_class::<DE>()?;
m.add_class::<PSO>()?;
m.add_class::<QNG>()?;
m.add_class::<CMAES>()?;
m.add_class::<Adam>()?;
m.add_class::<Spsa>()?;
m.add_class::<Rotosolve>()?;
m.add_class::<External>()?;
m.add_class::<Circuit>()?;
m.add_class::<Param>()?;
expr::register(m)?;
m.add_class::<RunResult>()?;
m.add_class::<TrainResult>()?;
m.add_class::<TrainProgress>()?;
m.add_class::<Qubo>()?;
m.add_class::<Ising>()?;
m.add_class::<CachedCost>()?;
m.add_class::<SampleCost>()?;
m.add_function(wrap_pyfunction!(train, m)?)?;
m.add_function(wrap_pyfunction!(run_quantum_circuit, m)?)?;
m.add_function(wrap_pyfunction!(statevector, m)?)?;
m.add_function(wrap_pyfunction!(init_logger, m)?)?;
m.add_function(wrap_pyfunction!(calibrate_parallel_threshold, m)?)?;
m.add_function(wrap_pyfunction!(backend_cleanup_failures, m)?)?;
m.add_function(wrap_pyfunction!(backend_compatibility, m)?)?;
let py = m.py();
let qml = PyModule::new(py, "polypus.qml")?;
qml.add_function(wrap_pyfunction!(qml_train, &qml)?)?;
qml.add_function(wrap_pyfunction!(qml_predict, &qml)?)?;
qml::register(&qml)?;
m.add("qml", &qml)?;
let sys = PyModule::import(py, "sys")?;
sys.getattr("modules")?.set_item("polypus.qml", &qml)?;
let circuits = PyModule::new(py, "polypus.circuits")?;
let templates = PyModule::new(py, "polypus.circuits.templates")?;
templates.add_function(wrap_pyfunction!(qft, &templates)?)?;
templates.add_function(wrap_pyfunction!(shor_order_finding, &templates)?)?;
circuits.add("templates", &templates)?;
m.add("circuits", &circuits)?;
let modules = sys.getattr("modules")?;
modules.set_item("polypus.circuits", &circuits)?;
modules.set_item("polypus.circuits.templates", &templates)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
const FRESH_PROCESS_ENV: &str = "POLYPUS_FRESH_PROCESS_CHILD";
fn run_in_fresh_process(name: &str) {
let exe = std::env::current_exe().expect("the test binary path is available");
let output = std::process::Command::new(exe)
.args(["--exact", name, "--test-threads=1", "--nocapture"])
.env(FRESH_PROCESS_ENV, "1")
.output()
.expect("the test binary can be re-executed");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success(),
"child run failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(
stdout.contains("1 passed"),
"the child must actually run the test, not filter it out:\n{stdout}"
);
}
#[test]
fn signal_polling_cancels_when_the_interpreter_is_unavailable() {
if std::env::var_os(FRESH_PROCESS_ENV).is_none() {
run_in_fresh_process(
"bindings::tests::signal_polling_cancels_when_the_interpreter_is_unavailable",
);
return;
}
use crate::infrastructure::{BackendError, InterpreterUnavailable, Interrupt};
match SignalInterrupt.poll() {
Err(BackendError::External(boxed)) => assert!(
boxed.is::<InterpreterUnavailable>(),
"an unreachable interpreter must abort the run with InterpreterUnavailable: {boxed}"
),
other => panic!("an unreachable interpreter must abort the run, got {other:?}"),
}
let mut pending = None;
assert!(
circuit::poll_for_cancellation(&mut pending),
"an unreachable interpreter must cancel the simulation"
);
assert!(
pending.is_none(),
"no exception can be recorded without an interpreter"
);
}
#[test]
fn statevector_simulation_cancels_when_the_interpreter_is_unavailable() {
if std::env::var_os(FRESH_PROCESS_ENV).is_none() {
run_in_fresh_process(
"bindings::tests::statevector_simulation_cancels_when_the_interpreter_is_unavailable",
);
return;
}
use polypus_circuit::{ConcreteCircuit, GateInstruction as G, GateParam::Fixed};
const N: usize = 14;
let mut gates = Vec::new();
for i in 0..60_000 {
gates.push(G::Rx {
qubit: i % N,
theta: Fixed(0.1),
});
gates.push(G::Barrier(Vec::new()));
}
gates.push(G::Rx {
qubit: 0,
theta: Fixed(f64::NAN),
});
let circuit = ConcreteCircuit::new_unchecked(N, gates);
let mut pending = None;
let outcome = circuit::simulate_cancellable(&circuit, true, &mut pending);
assert!(
matches!(outcome, Err(polypus_sim::SimError::Cancelled)),
"an unreachable interpreter must cancel the simulation mid-run, got {:?}",
outcome.map(|_| "a completed run")
);
assert!(
pending.is_none(),
"no exception can be recorded without an interpreter"
);
}
#[test]
fn statevector_cancellation_raises_keyboard_interrupt() {
Python::initialize();
Python::attach(|py| {
let unreachable = circuit::cancellation_error(None);
assert!(unreachable.is_instance_of::<pyo3::exceptions::PyKeyboardInterrupt>(py));
assert_eq!(
unreachable.value(py).to_string(),
format!(
"the run was aborted: {}",
crate::infrastructure::InterpreterUnavailable
)
);
let signal = pyo3::exceptions::PyKeyboardInterrupt::new_err("Ctrl+C");
let signal_value = signal.value(py).clone();
let raised = circuit::cancellation_error(Some(signal));
assert!(
raised.value(py).is(&signal_value),
"the pending exception must be re-raised verbatim"
);
});
}
use pyo3::types::PyString;
use std::collections::HashMap;
fn uniform3_qasm() -> String {
polypus_circuit::ParameterizedCircuit::new(3)
.h(0)
.h(1)
.h(2)
.measure_all()
.assign_parameters(&[])
.expect("no free parameters")
.try_to_qasm2()
.unwrap()
}
fn native_run(
py: Python<'_>,
qasm: &str,
seed: Option<u64>,
) -> (Option<u64>, Vec<HashMap<String, u64>>) {
let qc = PyString::new(py, qasm).into_any();
let result = run_quantum_circuit(
qc,
500,
"local".to_string(),
1,
1,
2,
"automatic",
None,
"polypus",
seed,
None,
None,
None,
)
.expect("native run_quantum_circuit succeeds");
let bound = result.bind(py);
let reported = bound
.getattr("seed")
.unwrap()
.extract::<Option<u64>>()
.unwrap();
let counts = bound
.getattr("counts")
.unwrap()
.extract::<Vec<HashMap<String, u64>>>()
.unwrap();
(reported, counts)
}
#[test]
fn native_seed_round_trips_and_reproduces_counts() {
pyo3::Python::initialize();
Python::attach(|py| {
let qasm = uniform3_qasm();
let (s1, c1) = native_run(py, &qasm, Some(42));
let (s2, c2) = native_run(py, &qasm, Some(42));
assert_eq!(s1, Some(42));
assert_eq!(s2, Some(42));
assert_eq!(c1, c2, "same seed must reproduce counts");
});
}
#[test]
fn native_omitted_seed_is_entropy_and_differs() {
pyo3::Python::initialize();
Python::attach(|py| {
let qasm = uniform3_qasm();
let (s1, c1) = native_run(py, &qasm, None);
let (s2, c2) = native_run(py, &qasm, None);
assert!(
s1.is_some() && s2.is_some(),
"an entropy seed must be reported"
);
assert_ne!(s1, s2, "each unseeded run must draw a fresh seed");
assert_ne!(c1, c2, "unseeded runs must produce independent noise");
});
}
#[test]
fn native_manifest_reports_run_metadata() {
pyo3::Python::initialize();
Python::attach(|py| {
let qc = PyString::new(py, &uniform3_qasm()).into_any();
let result = run_quantum_circuit(
qc,
100,
"local".to_string(),
1,
1,
2,
"automatic",
None,
"polypus",
Some(7),
None,
None,
None,
)
.expect("native run succeeds");
let bound = result.bind(py);
let get = |name: &str| bound.getattr(name).unwrap().extract::<String>().unwrap();
assert_eq!(get("backend"), "polypus");
assert_eq!(get("infrastructure"), "local");
assert!(
get("id").starts_with("run_1_local_"),
"id must keep the run_{{n}}_{{infra}}_ prefix, got {}",
get("id")
);
assert_eq!(
bound
.getattr("seed")
.unwrap()
.extract::<Option<u64>>()
.unwrap(),
Some(7)
);
});
}
#[test]
fn auto_generated_id_is_unique_per_call() {
pyo3::Python::initialize();
Python::attach(|py| {
let qasm = uniform3_qasm();
let id_of = || {
let qc = PyString::new(py, &qasm).into_any();
let result = run_quantum_circuit(
qc,
100,
"local".to_string(),
1,
1,
2,
"automatic",
None,
"polypus",
Some(7),
None,
None,
None,
)
.expect("native run succeeds");
result
.bind(py)
.getattr("id")
.unwrap()
.extract::<String>()
.unwrap()
};
let id1 = id_of();
let id2 = id_of();
assert!(id1.starts_with("run_1_local_") && id2.starts_with("run_1_local_"));
assert_ne!(
id1, id2,
"ids from identical calls must differ (unique per run)"
);
});
}
#[test]
fn unique_id_keeps_prefix_and_is_unique_per_call() {
for base in ["run1", "qml_run", "run_1_local"] {
let id1 = unique_id(base).unwrap();
let id2 = unique_id(base).unwrap();
let prefix = format!("{base}_");
assert!(
id1.starts_with(&prefix) && id2.starts_with(&prefix),
"the caller-supplied id must survive as a prefix, got {id1} / {id2}"
);
assert_ne!(
id1, id2,
"ids built from an identical base must differ (unique per call)"
);
}
}
#[test]
fn seed_rejected_for_qmio_hardware() {
pyo3::Python::initialize();
Python::attach(|py| {
let qasm = uniform3_qasm();
let qc = pyo3::types::PyString::new(py, &qasm).into_any();
let result = run_quantum_circuit(
qc,
100,
"qmio".to_string(),
1,
1,
2,
"automatic",
None,
"aer",
Some(3),
None,
None,
None,
);
assert!(
result.is_err(),
"an explicit seed must be rejected for infrastructure=qmio"
);
});
}
#[test]
fn resolve_optimizer_seed_follows_precedence() {
assert_eq!(
resolve_optimizer_seed(Some(7), Some(9), random_seed).unwrap(),
7
);
assert_eq!(
resolve_optimizer_seed(None, Some(9), random_seed).unwrap(),
9
);
assert_ne!(
resolve_optimizer_seed(None, None, random_seed).unwrap(),
resolve_optimizer_seed(None, None, random_seed).unwrap()
);
}
fn failing_draw() -> Result<u64, EntropyError> {
Err(EntropyError::new(std::io::Error::other(
"getrandom: device not available",
)))
}
fn forbidden_draw() -> Result<u64, EntropyError> {
panic!("an explicit seed must not draw from the OS entropy source")
}
fn assert_entropy_failure(err: &PyErr) {
pyo3::Python::initialize();
Python::attach(|py| {
assert!(
err.is_instance_of::<crate::exceptions::BackendError>(py),
"wrong exception class: {err}"
);
assert!(
!err.is_instance_of::<pyo3::panic::PanicException>(py),
"an entropy failure must not cross as a PanicException: {err}"
);
assert!(
err.to_string().contains("OS entropy source unavailable"),
"message lost: {err}"
);
});
}
#[test]
fn seed_or_entropy_uses_an_explicit_seed_without_drawing() {
assert_eq!(seed_or_entropy(Some(11), forbidden_draw).unwrap(), 11);
}
#[test]
fn seed_or_entropy_returns_the_drawn_value() {
assert_eq!(seed_or_entropy(None, || Ok(31)).unwrap(), 31);
}
#[test]
fn seed_or_entropy_raises_backend_error_when_the_draw_fails() {
let err = seed_or_entropy(None, failing_draw).expect_err("a failed draw must be an Err");
assert_entropy_failure(&err);
}
#[test]
fn resolve_optimizer_seed_propagates_a_failed_draw() {
assert_eq!(
resolve_optimizer_seed(Some(7), None, forbidden_draw).unwrap(),
7
);
assert_eq!(
resolve_optimizer_seed(None, Some(9), forbidden_draw).unwrap(),
9
);
let err = resolve_optimizer_seed(None, None, failing_draw)
.expect_err("a failed draw must be an Err");
assert_entropy_failure(&err);
}
#[test]
fn unique_id_from_builds_a_v4_uuid_from_the_drawn_bytes() {
let id = unique_id_from("run1", || Ok(std::array::from_fn(|i| i as u8))).unwrap();
assert_eq!(id, "run1_00010203-0405-4607-8809-0a0b0c0d0e0f");
let suffix = uuid::Uuid::parse_str(id.strip_prefix("run1_").unwrap()).unwrap();
assert_eq!(suffix.get_version(), Some(uuid::Version::Random));
assert_eq!(suffix.get_variant(), uuid::Variant::RFC4122);
}
#[test]
fn unique_id_from_raises_backend_error_when_the_draw_fails() {
let err = unique_id_from("run1", || {
Err(EntropyError::for_run_id(std::io::Error::other(
"getrandom: device not available",
)))
})
.expect_err("a failed draw must be an Err");
assert_entropy_failure(&err);
Python::attach(|py| {
assert!(
err.is_instance_of::<pyo3::exceptions::PyException>(py),
"must be catchable as Exception: {err}"
);
assert!(
err.to_string().contains("run id"),
"message must say the run id draw failed: {err}"
);
});
}
#[test]
fn resolved_seed_drives_the_optimizer_deterministically() {
use polypus_optimizers::{
AlgorithmDifferentialEvolution, AlgorithmDifferentialEvolutionArgs, EvaluationOracle,
Optimizer,
};
struct Quadratic;
impl EvaluationOracle for Quadratic {
fn evaluate_batch(&self, candidates: &[Vec<f64>]) -> Vec<f64> {
candidates
.iter()
.map(|c| -c.iter().map(|x| (x - 0.7).powi(2)).sum::<f64>())
.collect()
}
}
let run = |kwarg: Option<u64>, field: Option<u64>| {
let seed = resolve_optimizer_seed(kwarg, field, random_seed).unwrap();
AlgorithmDifferentialEvolution
.optimize(AlgorithmDifferentialEvolutionArgs {
oracle: Box::new(Quadratic),
population_size: 20,
generations: 40,
dimensions: 3,
tolerance: 1e-9,
patience: 20,
seed: Some(seed),
initial_point: None,
mutation_factor: None,
crossover_rate: None,
})
.expect("valid DE args optimize successfully")
};
assert_eq!(run(Some(123), None), run(Some(123), None));
assert_eq!(run(None, Some(55)), run(None, Some(55)));
assert_ne!(run(None, None), run(None, None));
}
#[test]
fn de_strategy_is_validated_and_reaches_the_method() {
use polypus_optimizers::DeStrategy;
Python::initialize();
Python::attach(|py| {
let err = DE::new(100, 50, 0.01, 20, None, "LSHADE", None, None)
.err()
.expect("an unknown strategy is rejected");
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(err.to_string().contains("\"lshade\""), "{err}");
let de = Py::new(
py,
DE::new(100, 50, 0.01, 20, None, "shade", None, None).unwrap(),
)
.unwrap();
let bound = de.bind(py);
assert!(bound.setattr("strategy", "jade").is_err());
assert_eq!(
bound
.getattr("strategy")
.unwrap()
.extract::<String>()
.unwrap(),
"shade",
"a rejected name leaves the strategy unchanged"
);
bound.setattr("strategy", "lshade").unwrap();
match method_from_pyclass(bound.as_any(), 1, &OracleErrorSlot::new(), "run") {
Ok(Method::De(cfg)) => assert_eq!(cfg.strategy, DeStrategy::LShade),
_ => panic!("a polypus.DE parses into Method::De"),
}
});
}
#[test]
fn adam_rule_is_validated_when_passed_or_set() {
Python::initialize();
Python::attach(|py| {
let new = |rule| {
Adam::new(
100,
0.05,
0.9,
0.999,
1e-8,
(-1.0, 1.0),
0.01,
20,
0.1,
rule,
None,
)
};
let err = new("Momentum").err().expect("an unknown rule is rejected");
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("\"adam\" or \"momentum\""),
"{err}"
);
let adam = Py::new(py, new("adam").unwrap()).unwrap();
let bound = adam.bind(py);
let err = bound
.setattr("rule", "nesterov")
.expect_err("an unknown rule is rejected when set");
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("\"adam\" or \"momentum\""),
"{err}"
);
assert_eq!(
bound.getattr("rule").unwrap().extract::<String>().unwrap(),
"adam",
"a rejected name leaves the rule unchanged"
);
bound.setattr("rule", "momentum").unwrap();
assert_eq!(
bound.getattr("rule").unwrap().extract::<String>().unwrap(),
"momentum"
);
});
}
#[test]
fn validate_shots_and_qpus_accepts_the_minimum() {
assert!(validate_shots_and_qpus(1, 1).is_ok());
assert!(validate_shots_and_qpus(1024, 8).is_ok());
}
#[test]
fn validate_shots_and_qpus_rejects_zero() {
assert!(validate_shots_and_qpus(0, 1).is_err());
assert!(validate_shots_and_qpus(1, 0).is_err());
assert!(validate_shots_and_qpus(0, 0).is_err());
}
#[test]
fn build_backend_config_selects_the_local_variants() {
let aer = build_backend_config("local", "aer", "automatic", None, 1, 2, None, None, None)
.expect("aer is a valid local backend");
assert!(matches!(
aer,
BackendConfig::Local {
ref sim_method,
noise_model: None,
} if sim_method == "automatic"
));
for name in ["polypus", "statevector", "polypus_statevector"] {
let native = build_backend_config(
"local",
name,
"automatic",
None,
1,
2,
None,
Some(true),
None,
)
.unwrap_or_else(|_| panic!("'{name}' selects the native backend"));
assert!(matches!(
native,
BackendConfig::LocalNative { fusion: true }
));
}
}
#[test]
fn build_backend_config_forwards_fusion_for_the_native_backend() {
let with_fusion = build_backend_config(
"local",
"polypus",
"automatic",
None,
1,
2,
None,
Some(true),
None,
)
.expect("polypus is a valid local backend");
assert!(matches!(
with_fusion,
BackendConfig::LocalNative { fusion: true }
));
let without_fusion = build_backend_config(
"local",
"polypus",
"automatic",
None,
1,
2,
None,
Some(false),
None,
)
.expect("polypus is a valid local backend");
assert!(matches!(
without_fusion,
BackendConfig::LocalNative { fusion: false }
));
}
#[test]
fn build_backend_config_defaults_fusion_to_enabled_when_omitted() {
let native = build_backend_config(
"local",
"polypus",
"automatic",
None,
1,
2,
None,
None,
None,
)
.expect("polypus is a valid local backend");
assert!(matches!(
native,
BackendConfig::LocalNative { fusion: true }
));
}
#[test]
fn build_backend_config_rejects_fusion_true_on_non_fusing_backends() {
pyo3::Python::initialize();
for (infra, backend) in [("local", "aer"), ("cunqa", "aer")] {
let err = build_backend_config(
infra,
backend,
"automatic",
None,
1,
2,
None,
Some(true),
None,
)
.expect_err("fusion=True on a non-fusing backend must be rejected");
Python::attach(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("fusion=True applies only to"),
"unexpected error: {err}"
);
});
build_backend_config(
infra,
backend,
"automatic",
None,
1,
2,
None,
Some(false),
None,
)
.expect("fusion=False is accepted everywhere");
build_backend_config(infra, backend, "automatic", None, 1, 2, None, None, None)
.expect("omitted fusion is accepted everywhere");
}
}
#[test]
fn build_backend_config_rejects_an_unknown_local_backend() {
let err = build_backend_config(
"local",
"does-not-exist",
"automatic",
None,
1,
2,
None,
None,
None,
)
.expect_err("an unknown local backend must be rejected");
pyo3::Python::initialize();
Python::attach(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(err.to_string().contains("unknown local backend"));
});
}
#[test]
fn build_backend_config_rejects_an_unknown_cunqa_backend() {
pyo3::Python::initialize();
for backend in ["polypus", "statevector", "polypus_statevector", "foo"] {
let err =
build_backend_config("cunqa", backend, "automatic", None, 1, 2, None, None, None)
.expect_err("a non-Aer cunqa backend must be rejected");
Python::attach(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("unknown cunqa backend"),
"unexpected error for {backend}: {err}"
);
});
}
for backend in ["aer", "AerSimulator"] {
let config =
build_backend_config("cunqa", backend, "automatic", None, 1, 2, None, None, None)
.expect("cunqa accepts the Aer backend names");
assert!(matches!(config, BackendConfig::Cunqa { .. }));
}
}
#[test]
fn build_backend_config_rejects_a_noise_model_on_cunqa() {
pyo3::Python::initialize();
let noise_model = Python::attach(|py| py.None());
let err = build_backend_config(
"cunqa",
"aer",
"automatic",
Some(noise_model),
1,
2,
None,
None,
None,
)
.expect_err("a noise model on cunqa must be rejected");
Python::attach(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("noise_model"),
"the message must name the offending kwarg: {err}"
);
});
assert!(matches!(
build_backend_config("cunqa", "aer", "automatic", None, 1, 2, None, None, None),
Ok(BackendConfig::Cunqa { .. })
));
}
#[test]
fn build_backend_config_rejects_aer_only_args_on_a_registered_backend() {
pyo3::Python::initialize();
let build = |backend: &str, sim_method: &str, noise: bool| {
let noise_model = noise.then(|| Python::attach(|py| py.None()));
build_backend_config(
"subprocess",
backend,
sim_method,
noise_model,
1,
2,
None,
None,
None,
)
};
assert!(build("aer", "automatic", false).is_ok());
for (backend, sim_method, noise, kwarg) in [
("aer", "automatic", true, "noise_model"),
("aer", "statevector", false, "sim_method"),
("polypus", "automatic", false, "backend"),
] {
let err = build(backend, sim_method, noise)
.expect_err("an argument the backend cannot honour must be rejected");
Python::attach(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(err.to_string().contains(kwarg), "{kwarg}: {err}");
});
}
}
#[cfg(feature = "qmio")]
#[test]
fn build_backend_config_rejects_a_noise_model_and_sim_method_on_qmio() {
pyo3::Python::initialize();
let build = |sim_method: &str, noise: bool| {
let noise_model = noise.then(|| Python::attach(|py| py.None()));
build_backend_config(
"qmio",
"qir",
sim_method,
noise_model,
1,
2,
None,
None,
None,
)
};
assert!(build("automatic", false).is_ok());
for (sim_method, noise, kwarg) in [
("automatic", true, "noise_model"),
("density_matrix", false, "sim_method"),
] {
let err = build(sim_method, noise).expect_err("must be rejected on qmio");
Python::attach(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(err.to_string().contains(kwarg), "{kwarg}: {err}");
});
}
}
#[test]
fn build_backend_config_rejects_a_noise_model_on_the_native_backend() {
pyo3::Python::initialize();
let noise_model = Python::attach(|py| py.None());
let err = build_backend_config(
"local",
"polypus",
"automatic",
Some(noise_model),
1,
2,
None,
None,
None,
)
.expect_err("a noise model on the native backend must be rejected");
Python::attach(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("noise_model"),
"the message must name the offending kwarg: {err}"
);
});
}
#[test]
fn build_backend_config_rejects_a_sim_method_on_the_native_backend() {
pyo3::Python::initialize();
for backend in ["polypus", "statevector", "polypus_statevector"] {
let err = build_backend_config(
"local",
backend,
"statevector",
None,
1,
2,
None,
None,
None,
)
.expect_err("a sim_method on the native backend must be rejected");
Python::attach(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("sim_method"),
"the message must name the offending kwarg: {err}"
);
});
}
}
#[test]
fn build_backend_config_keeps_a_noise_model_for_aer() {
pyo3::Python::initialize();
let noise_model = Python::attach(|py| py.None());
let config = build_backend_config(
"local",
"aer",
"density_matrix",
Some(noise_model),
1,
2,
None,
None,
None,
)
.expect("aer accepts a noise model");
assert!(matches!(
config,
BackendConfig::Local {
noise_model: Some(_),
ref sim_method,
..
} if sim_method == "density_matrix"
));
}
#[test]
fn build_backend_config_forwards_the_cunqa_allocation() {
let config =
build_backend_config("cunqa", "aer", "statevector", None, 3, 4, None, None, None)
.expect("cunqa is a valid infrastructure");
assert!(matches!(
config,
BackendConfig::Cunqa {
nodes: 3,
cores_per_qpu: 4,
ref sim_method,
ref walltime,
..
} if sim_method == "statevector" && walltime == DEFAULT_WALLTIME
));
}
#[test]
fn build_backend_config_forwards_an_explicit_cunqa_walltime() {
let config = build_backend_config(
"cunqa",
"aer",
"statevector",
None,
1,
2,
Some("48:00:00"),
None,
None,
)
.expect("cunqa is a valid infrastructure");
assert!(matches!(
config,
BackendConfig::Cunqa { ref walltime, .. } if walltime == "48:00:00"
));
}
#[test]
fn validate_cunqa_allocation_checks_the_walltime_only_for_cunqa() {
let msg = |r: PyResult<()>| r.expect_err("must be rejected").to_string();
assert!(
msg(validate_cunqa_allocation("cunqa", 1, 2, Some("1-00:00:00"))).contains("HH:MM:SS")
);
assert!(validate_cunqa_allocation("cunqa", 1, 2, Some("48:00:00")).is_ok());
assert!(validate_cunqa_allocation("cunqa", 1, 2, None).is_ok());
for infra in ["local", "qmio"] {
assert!(validate_cunqa_allocation(infra, 1, 2, Some("garbage")).is_ok());
}
}
#[test]
fn build_backend_config_rejects_an_unknown_infrastructure() {
let err = build_backend_config(
"quantum-cloud",
"aer",
"automatic",
None,
1,
2,
None,
None,
None,
)
.expect_err("an unknown infrastructure must be rejected");
pyo3::Python::initialize();
Python::attach(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(err.to_string().contains("unknown infrastructure"));
});
}
#[test]
fn build_backend_config_routes_a_registered_name_to_registered() {
crate::infrastructure::register_backend(
"edge-registered-test",
|_ctx: &crate::infrastructure::BackendBuildContext| {
Err(crate::infrastructure::BackendError::Conversion(
"unused".to_string(),
))
},
);
let opts = HashMap::from([
("endpoint".to_string(), OptionValue::from("tcp://x:1")),
(
"command".to_string(),
OptionValue::from(vec!["python3".to_string(), "/a b/w.py".to_string()]),
),
]);
let config = build_backend_config(
"edge-registered-test",
"aer",
"automatic",
None,
1,
2,
None,
None,
Some(opts),
)
.expect("a registered name builds a Registered config");
match config {
BackendConfig::Registered { name, options } => {
assert_eq!(name, "edge-registered-test");
assert_eq!(
options.get("endpoint"),
Some(&OptionValue::from("tcp://x:1"))
);
assert_eq!(
options.get("command"),
Some(&OptionValue::from(vec![
"python3".to_string(),
"/a b/w.py".to_string()
]))
);
}
other => panic!("expected BackendConfig::Registered, got {other:?}"),
}
}
#[test]
fn build_backend_config_rejects_options_on_a_typed_builtin() {
pyo3::Python::initialize();
let str_opts = HashMap::from([("command".to_string(), OptionValue::from("x"))]);
let list_opts = HashMap::from([(
"command".to_string(),
OptionValue::from(vec!["x".to_string()]),
)]);
for (infra, opts) in [
("local", &str_opts),
("cunqa", &str_opts),
("local", &list_opts),
("cunqa", &list_opts),
] {
let err = build_backend_config(
infra,
"aer",
"automatic",
None,
1,
2,
None,
None,
Some(opts.clone()),
)
.expect_err("options on a typed built-in must be rejected");
Python::attach(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("does not accept 'options'"),
"unexpected message: {err}"
);
});
}
assert!(build_backend_config(
"local",
"aer",
"automatic",
None,
1,
2,
None,
None,
Some(HashMap::new()),
)
.is_ok());
}
#[cfg(feature = "qmio")]
#[test]
fn build_qmio_registered_merges_user_options_over_the_defaults() {
let user = HashMap::from([
("optimization".to_string(), OptionValue::from("2")),
(
"res_format".to_string(),
OptionValue::from(vec!["raw".to_string()]),
),
(
"custom".to_string(),
OptionValue::from(vec!["a b".to_string()]),
),
]);
let config = qmio_registered_config(
"qir",
Some("tcp://qmio.example:5556".to_string()),
Some(user),
)
.expect("qir is a qmio format");
let BackendConfig::Registered { name, options } = config else {
panic!("qmio must build a Registered config");
};
assert_eq!(name, "qmio");
assert_eq!(
options.get("endpoint"),
Some(&OptionValue::from("tcp://qmio.example:5556"))
);
assert_eq!(
options.get("program_format"),
Some(&OptionValue::from("qir_text"))
);
assert_eq!(options.get("optimization"), Some(&OptionValue::from("2")));
assert_eq!(
options.get("res_format"),
Some(&OptionValue::from(vec!["raw".to_string()]))
);
assert_eq!(
options.get("custom"),
Some(&OptionValue::from(vec!["a b".to_string()]))
);
assert_eq!(options.len(), 5);
}
#[cfg(feature = "qmio")]
#[test]
fn qmio_registered_config_has_no_default_endpoint() {
let BackendConfig::Registered { options, .. } =
qmio_registered_config("qmio", None, None).expect("qmio is a qmio format")
else {
panic!("qmio must build a Registered config");
};
assert_eq!(options.get("endpoint"), None);
let user = HashMap::from([(
"endpoint".to_string(),
OptionValue::from("tcp://qmio.example:5556"),
)]);
let BackendConfig::Registered { options, .. } =
qmio_registered_config("qmio", None, Some(user)).expect("qmio is a qmio format")
else {
panic!("qmio must build a Registered config");
};
assert_eq!(
options.get("endpoint"),
Some(&OptionValue::from("tcp://qmio.example:5556"))
);
}
fn extract_options(expr: &str) -> PyResult<HashMap<String, OptionValue>> {
pyo3::Python::initialize();
Python::attach(|py| {
let code = std::ffi::CString::new(expr).expect("no NUL in the test expression");
py.eval(&code, None, None)?
.extract::<OptionsArg>()
.map(OptionsArg::into_inner)
})
}
#[test]
fn options_arg_accepts_str_list_and_tuple_values() {
let options = extract_options(
"{'endpoint': 'tcp://x:1', 'command': ['python3', '/a b/w.py'], \
'argv': ('a', 'b c'), 'empty': []}",
)
.expect("str, list[str] and tuple[str] values convert");
assert_eq!(options.len(), 4);
assert_eq!(options["endpoint"], OptionValue::from("tcp://x:1"));
assert_eq!(
options["command"],
OptionValue::from(vec!["python3".to_string(), "/a b/w.py".to_string()])
);
assert_eq!(
options["argv"],
OptionValue::from(vec!["a".to_string(), "b c".to_string()])
);
assert_eq!(options["empty"], OptionValue::from(Vec::new()));
}
#[test]
fn options_arg_does_not_run_user_iterators_while_walking_the_dict() {
pyo3::Python::initialize();
Python::attach(|py| {
let globals = PyDict::new(py);
let code = std::ffi::CString::new(
"opts = {}\n\
class L(list):\n\
\x20 def __iter__(self):\n\
\x20 opts['injected-by-list'] = 'x'\n\
\x20 return super().__iter__()\n\
class T(tuple):\n\
\x20 def __iter__(self):\n\
\x20 opts['injected-by-tuple'] = 'x'\n\
\x20 return super().__iter__()\n\
opts['a'] = L(['python3', '/a b/w.py'])\n\
opts['b'] = 'y'\n\
opts['c'] = T(('t',))\n",
)
.expect("no NUL in the test program");
py.run(&code, Some(&globals), None)
.expect("the test program runs");
let opts = globals
.get_item("opts")
.expect("globals lookup")
.expect("the test program defines opts");
let options = opts
.extract::<OptionsArg>()
.map(OptionsArg::into_inner)
.expect("list/tuple subclasses of str convert");
assert_eq!(
options["a"],
OptionValue::from(vec!["python3".to_string(), "/a b/w.py".to_string()])
);
assert_eq!(options["b"], OptionValue::from("y"));
assert_eq!(options["c"], OptionValue::from(vec!["t".to_string()]));
assert_eq!(options.len(), 3);
assert_eq!(opts.len().expect("opts is a dict"), 3, "{opts}");
});
}
#[test]
fn options_arg_rejects_unsupported_values_with_a_type_error_naming_the_key() {
for (expr, needle) in [
(
"{'k': 1}",
"options['k'] must be a str or a list of str, got int",
),
(
"{'k': True}",
"options['k'] must be a str or a list of str, got bool",
),
(
"{'k': 1.5}",
"options['k'] must be a str or a list of str, got float",
),
(
"{'k': None}",
"options['k'] must be a str or a list of str, got NoneType",
),
(
"{'k': {'a': 'b'}}",
"options['k'] must be a str or a list of str, got dict",
),
("{'k': ['a', 1]}", "options['k'][1] must be a str, got int"),
("{'k': [['a']]}", "options['k'][0] must be a str, got list"),
(
"{'k': ('a', None)}",
"options['k'][1] must be a str, got NoneType",
),
("{1: 'a'}", "options keys must be str, got int"),
("['a']", "options must be a dict"),
] {
let err = extract_options(expr)
.map(|_| ())
.expect_err(&format!("{expr} must be rejected"));
Python::attach(|py| {
assert!(
err.is_instance_of::<pyo3::exceptions::PyTypeError>(py),
"{expr}: expected TypeError, got {err}"
);
});
assert!(
err.to_string().contains(needle),
"{expr}: message {err} should contain {needle:?}"
);
}
}
#[test]
fn extract_bound_circuit_reads_a_qasm_string() {
pyo3::Python::initialize();
Python::attach(|py| {
let qasm = uniform3_qasm();
let bound = extract_bound_circuit(&PyString::new(py, &qasm).into_any())
.expect("a str is an OpenQASM 2.0 program");
match bound {
BoundCircuit::Qasm2(text) => assert_eq!(text, qasm),
_ => panic!("a str must become BoundCircuit::Qasm2"),
}
});
}
#[test]
fn extract_bound_circuit_treats_anything_else_as_a_qiskit_circuit() {
pyo3::Python::initialize();
Python::attach(|py| {
let bound = extract_bound_circuit(py.None().bind(py))
.expect("a non-Circuit, non-str object is assumed to be a Qiskit circuit");
assert!(bound.is_foreign());
});
}
#[test]
fn extract_bound_circuit_rejects_a_qiskit_circuit_with_free_parameters() {
pyo3::Python::initialize();
Python::attach(|py| {
let qc = py
.eval(
c"type('QC', (), {'parameters': ['t', 'theta[0]']})()",
None,
None,
)
.expect("the stand-in builds");
let err = match extract_bound_circuit(&qc) {
Err(err) => err,
Ok(_) => panic!("a circuit with free parameters cannot be executed directly"),
};
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
let message = err.to_string();
assert!(message.contains("unbound parameters"), "{message}");
assert!(message.contains("directly: t, theta[0]."), "{message}");
let unbound = py
.eval(c"type('QC', (), {'parameters': []})()", None, None)
.expect("the stand-in builds");
assert!(extract_bound_circuit(&unbound).is_ok_and(|b| b.is_foreign()));
});
}
#[test]
fn extract_bound_circuit_reads_a_fully_bound_native_circuit() {
pyo3::Python::initialize();
Python::attach(|py| {
let circuit = Py::new(
py,
Circuit {
inner: polypus_circuit::ParameterizedCircuit::new(1)
.x(0)
.measure_all(),
},
)
.expect("the pyclass instantiates");
let bound = extract_bound_circuit(circuit.bind(py).as_any())
.expect("a parameter-free polypus.Circuit is executable as-is");
assert!(matches!(bound, BoundCircuit::Native(_)));
});
}
#[test]
fn extract_bound_circuit_rejects_a_native_circuit_with_free_parameters() {
pyo3::Python::initialize();
Python::attach(|py| {
let circuit = Py::new(
py,
Circuit {
inner: polypus_circuit::ParameterizedCircuit::new(1)
.ry(0, polypus_circuit::GateParam::Param(0))
.measure_all(),
},
)
.expect("the pyclass instantiates");
let err = match extract_bound_circuit(circuit.bind(py).as_any()) {
Err(err) => err,
Ok(_) => panic!("an unbound template cannot be executed directly"),
};
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("unbound parameters"),
"the message must explain what to do instead: {err}"
);
});
}
fn labels_of(py: Python<'_>, expr: &std::ffi::CStr) -> PyResult<Vec<Label>> {
let y_train = py
.eval(expr, None, None)
.expect("the test expression evaluates");
extract_labels(&y_train)
}
fn label_error(py: Python<'_>, expr: &std::ffi::CStr) -> (String, String) {
let err = labels_of(py, expr).expect_err("these labels must be rejected");
let class = err
.get_type(py)
.name()
.expect("an exception type has a name")
.to_string();
(class, err.to_string())
}
#[test]
fn extract_labels_keeps_all_integer_labels_as_classes() {
pyo3::Python::initialize();
Python::attach(|py| {
assert_eq!(
labels_of(py, c"[0, 2, -1, True]").expect("integers are labels"),
[0, 2, -1, 1].map(Label::Class),
"ints and bools stay class labels"
);
assert_eq!(
labels_of(py, c"(k % 2 for k in range(3))").expect("a generator is iterable"),
[0, 1, 0].map(Label::Class)
);
});
}
#[test]
fn extract_labels_makes_every_label_a_float_when_any_is_not_an_integer() {
pyo3::Python::initialize();
Python::attach(|py| {
assert_eq!(
labels_of(py, c"[0, 1.5, 2]").expect("mixed numbers are labels"),
[0.0, 1.5, 2.0].map(Label::Real),
"one float makes every label a float"
);
assert_eq!(
labels_of(py, c"[1.0, 0.0]").expect("floats are labels"),
[1.0, 0.0].map(Label::Real)
);
});
}
#[test]
fn extract_labels_rejects_non_numbers_and_nested_rows_naming_the_index() {
pyo3::Python::initialize();
Python::attach(|py| {
let (class, msg) = label_error(py, c"[0, 'cat']");
assert_eq!(class, "TypeError");
assert!(msg.contains("y_train[1] is a str"), "{msg}");
let (class, msg) = label_error(py, c"[0, [1, 0]]");
assert_eq!(class, "TypeError");
assert!(
msg.contains("y_train[1] is a sequence (list of length 2)"),
"a one-hot row is not a label: {msg}"
);
let (class, msg) = label_error(py, c"[None]");
assert_eq!(class, "TypeError");
assert!(msg.contains("y_train[0] has type NoneType"), "{msg}");
});
}
#[test]
fn extract_labels_rejects_non_finite_values_naming_the_index() {
pyo3::Python::initialize();
Python::attach(|py| {
let (class, msg) = label_error(py, c"[0.5, float('nan')]");
assert_eq!(class, "ConfigurationError");
assert!(msg.contains("y_train[1] is NaN"), "{msg}");
let (class, msg) = label_error(py, c"[float('-inf')]");
assert_eq!(class, "ConfigurationError");
assert!(msg.contains("y_train[0] is -inf"), "{msg}");
});
}
#[test]
fn extract_supervised_objective_accepts_callables_and_the_two_wrappers() {
pyo3::Python::initialize();
Python::attach(|py| {
let callable = py
.eval(c"lambda bitstring, label: 0.0", None, None)
.expect("a lambda evaluates");
let cached = Py::new(
py,
CachedCost {
cost_fn: callable.clone().unbind(),
},
)
.expect("the pyclass instantiates");
let sample = Py::new(
py,
SampleCost {
cost_fn: callable.clone().unbind(),
},
)
.expect("the pyclass instantiates");
for accepted in [
callable,
cached.into_bound(py).into_any(),
sample.into_bound(py).into_any(),
] {
assert!(
extract_supervised_objective(&accepted).is_ok(),
"{accepted:?} is a valid supervised objective"
);
}
});
}
#[test]
fn extract_supervised_objective_rejects_observables_that_cannot_read_labels() {
pyo3::Python::initialize();
Python::attach(|py| {
let qubo = Py::new(
py,
Qubo {
inner: Arc::new(
polypus_observable::QuboObservable::new(
1,
vec![(0, 1.0)],
vec![],
0.0,
1.0,
)
.expect("a one-variable QUBO is valid"),
),
},
)
.expect("the pyclass instantiates");
let err = extract_supervised_objective(qubo.bind(py).as_any())
.err()
.expect("a Qubo cannot read labels");
assert!(err.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
assert!(err.to_string().contains("cannot read labels"), "{err}");
let not_callable = 42i64.into_pyobject(py).expect("an int converts").into_any();
let err = extract_supervised_objective(¬_callable)
.err()
.expect("a non-callable is not an objective");
assert!(err.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
assert!(err.to_string().contains("with y_train"), "{err}");
});
}
#[test]
fn extract_cost_observable_rejects_a_sample_cost_without_labels() {
pyo3::Python::initialize();
Python::attach(|py| {
let sample = Py::new(
py,
SampleCost {
cost_fn: py
.eval(c"lambda counts, label: 0.0", None, None)
.expect("a lambda evaluates")
.unbind(),
},
)
.expect("the pyclass instantiates");
let err = extract_cost_observable(sample.bind(py).as_any())
.err()
.expect("a SampleCost needs labels");
assert!(err.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
assert!(err.to_string().contains("y_train"), "{err}");
});
}
#[test]
fn cmaes_reaches_the_method_and_its_seed_is_read() {
Python::initialize();
Python::attach(|py| {
let cmaes = Py::new(py, CMAES::new(40, Some(12), 0.75, 0.5, 7, 3, Some(99)))
.expect("the pyclass instantiates");
let bound = cmaes.bind(py);
assert_eq!(method_seed(bound.as_any()), Some(99));
match method_from_pyclass(bound.as_any(), 1, &OracleErrorSlot::new(), "run") {
Ok(Method::Cmaes(cfg)) => {
assert_eq!(cfg.generations, 40);
assert_eq!(cfg.population_size, Some(12));
assert_eq!(cfg.sigma0, 0.75);
assert_eq!(cfg.tolerance, 0.5);
assert_eq!(cfg.patience, 7);
assert_eq!(cfg.restarts, 3);
}
_ => panic!("a polypus.CMAES parses into Method::Cmaes"),
}
bound.setattr("population_size", py.None()).unwrap();
match method_from_pyclass(bound.as_any(), 1, &OracleErrorSlot::new(), "run") {
Ok(Method::Cmaes(cfg)) => assert_eq!(cfg.population_size, None),
_ => panic!("a polypus.CMAES parses into Method::Cmaes"),
}
let not_a_method = 3_i32.into_pyobject(py).unwrap();
assert_eq!(method_seed(not_a_method.as_any()), None);
let err = method_from_pyclass(not_a_method.as_any(), 1, &OracleErrorSlot::new(), "run")
.err()
.expect("an int is not a method");
assert!(err.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
assert!(err.to_string().contains("polypus.CMAES"), "{err}");
});
}
#[test]
fn adam_reaches_the_method_and_its_seed_is_read() {
use polypus_optimizers::AdamRule;
Python::initialize();
Python::attach(|py| {
let adam = Py::new(
py,
Adam::new(
40,
0.2,
0.8,
0.99,
1e-6,
(-1.0, 2.0),
0.5,
7,
0.05,
"momentum",
Some(99),
)
.expect("a valid rule"),
)
.expect("the pyclass instantiates");
let bound = adam.bind(py);
assert_eq!(method_seed(bound.as_any()), Some(99));
match method_from_pyclass(bound.as_any(), 1, &OracleErrorSlot::new(), "run") {
Ok(Method::Adam(cfg)) => {
assert_eq!(cfg.max_iters, 40);
assert_eq!(cfg.learning_rate, 0.2);
assert_eq!(cfg.beta1, 0.8);
assert_eq!(cfg.beta2, 0.99);
assert_eq!(cfg.epsilon, 1e-6);
assert_eq!(cfg.bounds, (-1.0, 2.0));
assert_eq!(cfg.tolerance, 0.5);
assert_eq!(cfg.patience, 7);
assert_eq!(cfg.finite_difference_step, 0.05);
assert_eq!(cfg.rule, AdamRule::Momentum);
}
_ => panic!("a polypus.Adam parses into Method::Adam"),
}
let not_a_method = 3_i32.into_pyobject(py).unwrap();
let err = method_from_pyclass(not_a_method.as_any(), 1, &OracleErrorSlot::new(), "run")
.err()
.expect("an int is not a method");
assert!(err.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
assert!(err.to_string().contains("polypus.Adam"), "{err}");
});
}
#[test]
fn spsa_reaches_the_method_and_its_seed_is_read() {
Python::initialize();
Python::attach(|py| {
let spsa = Py::new(py, Spsa::new(40, 8, 0.2, 1.2, 1.0, 0.25, 5, Some(99), 4.0))
.expect("the pyclass instantiates");
let bound = spsa.bind(py);
assert_eq!(method_seed(bound.as_any()), Some(99));
match method_from_pyclass(bound.as_any(), 1, &OracleErrorSlot::new(), "run") {
Ok(Method::Spsa(cfg)) => {
assert_eq!(cfg.max_iters, 40);
assert_eq!(cfg.resamplings, 8);
assert_eq!(cfg.perturbation, 0.2);
assert_eq!(cfg.target_step, 1.2);
assert_eq!(cfg.alpha, 1.0);
assert_eq!(cfg.gamma, 0.25);
assert_eq!(cfg.stability_constant, 4.0);
assert_eq!(cfg.eval_interval, 5);
}
_ => panic!("a polypus.SPSA parses into Method::Spsa"),
}
let not_a_method = 3_i32.into_pyobject(py).unwrap();
let err = method_from_pyclass(not_a_method.as_any(), 1, &OracleErrorSlot::new(), "run")
.err()
.expect("an int is not a method");
assert!(err.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
assert!(err.to_string().contains("polypus.SPSA"), "{err}");
});
}
#[test]
fn rotosolve_reaches_the_method_and_its_seed_is_read() {
Python::initialize();
Python::attach(|py| {
let rotosolve = Py::new(py, Rotosolve::new(7, 3, 0.25, 4, Some(99)))
.expect("the pyclass instantiates");
let bound = rotosolve.bind(py);
assert!(is_rotosolve(bound.as_any()));
assert_eq!(method_seed(bound.as_any()), Some(99));
match method_from_pyclass(bound.as_any(), 1, &OracleErrorSlot::new(), "run") {
Ok(Method::Rotosolve(cfg)) => {
assert_eq!(cfg.sweeps, 7);
assert_eq!(cfg.reevaluate_every, 3);
assert_eq!(cfg.tolerance, 0.25);
assert_eq!(cfg.patience, 4);
}
_ => panic!("a polypus.Rotosolve parses into Method::Rotosolve"),
}
let not_a_method = 3_i32.into_pyobject(py).unwrap();
assert!(!is_rotosolve(not_a_method.as_any()));
let err = method_from_pyclass(not_a_method.as_any(), 1, &OracleErrorSlot::new(), "run")
.err()
.expect("an int is not a method");
assert!(err.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
assert!(err.to_string().contains("polypus.Rotosolve"), "{err}");
});
}
#[test]
fn external_reaches_the_method_without_a_seed() {
Python::initialize();
Python::attach(|py| {
let optimizer = PyModule::from_code(
py,
c"class Done:\n def ask(self):\n return None\n def tell(self, c, v):\n pass\n",
c"external_done.py",
c"external_done",
)
.and_then(|module| module.getattr("Done")?.call0())
.expect("the optimizer instantiates");
let external = Bound::new(
py,
External::new(optimizer, 12_i32.into_pyobject(py).unwrap().into_any())
.expect("a valid External"),
)
.expect("the pyclass instantiates");
assert_eq!(method_seed(external.as_any()), None);
match method_from_pyclass(external.as_any(), 1, &OracleErrorSlot::new(), "run") {
Ok(Method::External(cfg, _)) => assert_eq!(cfg.max_evaluations, 12),
_ => panic!("a polypus.External parses into Method::External"),
}
assert!(check_external_initial_point(external.as_any(), None).is_ok());
let err = check_external_initial_point(external.as_any(), Some(&[0.5]))
.expect_err("External refuses a point");
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.value(py)
.to_string()
.starts_with("polypus.External takes no initial_point"),
"{err}"
);
let rotosolve = Py::new(py, Rotosolve::new(7, 3, 0.25, 4, None)).unwrap();
assert!(
check_external_initial_point(rotosolve.bind(py).as_any(), Some(&[0.5])).is_ok()
);
let not_a_method = 3_i32.into_pyobject(py).unwrap();
let err = method_from_pyclass(not_a_method.as_any(), 1, &OracleErrorSlot::new(), "run")
.err()
.expect("an int is not a method");
assert!(err.to_string().contains("or polypus.External"), "{err}");
});
}
#[test]
fn a_native_circuit_is_checked_for_rotosolve_in_rust() {
use crate::circuit::{Param, ParameterizedCircuit};
Python::initialize();
Python::attach(|py| {
let unused = 0_i32.into_pyobject(py).unwrap();
let good = CircuitSource::Native(
ParameterizedCircuit::new(2)
.ry(0, Param(0))
.cx(0, 1)
.rz(1, Param(1)),
);
assert!(check_rotosolve_circuit(unused.as_any(), Some(&good), None).is_ok());
let bad = CircuitSource::Native(ParameterizedCircuit::new(2).ry(0, Param(0)).crx(
0,
1,
Param(1),
));
let err = check_rotosolve_circuit(unused.as_any(), Some(&bad), None)
.expect_err("a controlled rotation does not qualify");
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
let message = err.value(py).to_string();
assert!(
message.starts_with(
"polypus.Rotosolve cannot train this circuit: parameter 1 ('theta_1') is \
an angle of 'crx' (instruction 1), which is not a rotation generated by a \
single Pauli operator. Rotosolve needs"
),
"{message}"
);
});
}
#[test]
fn a_rejected_optimizer_configuration_is_a_configuration_error() {
Python::initialize();
let err = Python::attach(|py| {
finish_optimization(
py,
Err(OracleError::Config(
polypus_optimizers::OptimizerError::InvalidConfig {
parameter: "population_size",
reason: "must be at least 4, got 3".to_string(),
},
)),
0,
"run".to_string(),
Instant::now(),
)
.expect_err("a rejected configuration is an error")
});
crate::exceptions::tests::assert_configuration_error(&err, "must be at least 4, got 3");
}
#[test]
fn an_oracle_failure_reported_by_the_optimizer_is_an_evaluation_error() {
Python::initialize();
for (failure, message) in [
(
polypus_optimizers::OptimizerError::OracleLengthMismatch {
expected: 3,
got: 2,
},
"returned 2 fitness value(s) for 3 candidate(s)",
),
(
polypus_optimizers::OptimizerError::NonFiniteGradient {
index: 1,
value: f64::NAN,
},
"gradient oracle returned NaN for parameter 1",
),
] {
Python::attach(|py| {
let err = finish_optimization(
py,
Err(OracleError::Config(failure)),
0,
"run".to_string(),
Instant::now(),
)
.expect_err("an oracle failure is an error");
assert!(
err.is_instance_of::<crate::exceptions::EvaluationError>(py),
"{err}"
);
assert!(
!err.is_instance_of::<pyo3::exceptions::PyValueError>(py),
"{err}"
);
assert!(err.value(py).to_string().contains(message), "{err}");
});
}
}
fn register_sentinel_backend(name: &str, builds: &'static std::sync::atomic::AtomicUsize) {
crate::infrastructure::register_backend(
name,
move |_ctx: &crate::infrastructure::BackendBuildContext| {
builds.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Err(crate::infrastructure::BackendError::Conversion(
"the sentinel backend was created".to_string(),
))
},
);
}
fn de<'py>(py: Python<'py>, population_size: u32) -> Bound<'py, PyAny> {
let kwargs = [("generations", 1), ("population_size", population_size)]
.into_py_dict(py)
.expect("the kwargs build");
py.get_type::<DE>()
.call((), Some(&kwargs))
.expect("the pyclass instantiates")
}
fn train_on<'py>(
py: Python<'py>,
infrastructure: &str,
method: Bound<'py, PyAny>,
expectation_function: Bound<'py, PyAny>,
) -> PyResult<Py<PyAny>> {
train_with(py, infrastructure, method, expectation_function, None, None)
}
fn train_with<'py>(
py: Python<'py>,
infrastructure: &str,
method: Bound<'py, PyAny>,
expectation_function: Bound<'py, PyAny>,
final_shots: Option<Bound<'py, PyAny>>,
callback: Option<Bound<'py, PyAny>>,
) -> PyResult<Py<PyAny>> {
train(
py.None().into_bound(py),
method,
16,
1,
1,
expectation_function,
infrastructure.to_string(),
1,
1,
"edge".to_string(),
"automatic",
None,
"aer",
Some(3),
None,
None,
None,
None,
final_shots,
callback,
)
}
fn fake_qml_circuits(py: Python<'_>) -> (Bound<'_, PyAny>, Bound<'_, PyAny>) {
let module = PyModule::from_code(
py,
c"class Circuit:
num_clbits = 1
def __init__(self, *parameters):
self.parameters = list(parameters)
def compose(self, other):
return Circuit(*self.parameters, *other.parameters)
def assign_parameters(self, values, inplace=False):
return self
",
c"fake_qml_circuits.py",
c"fake_qml_circuits",
)
.expect("the module compiles");
let circuit = module.getattr("Circuit").expect("the class exists");
(
circuit.call1(("x",)).expect("a feature map"),
circuit.call1(("w",)).expect("an ansatz"),
)
}
fn qml_train_on<'py>(
py: Python<'py>,
infrastructure: &str,
method: Bound<'py, PyAny>,
expectation_function: Bound<'py, PyAny>,
) -> PyResult<Py<PyAny>> {
qml_train_with(py, infrastructure, method, expectation_function, None, None)
}
fn qml_train_with<'py>(
py: Python<'py>,
infrastructure: &str,
method: Bound<'py, PyAny>,
expectation_function: Bound<'py, PyAny>,
final_shots: Option<Bound<'py, PyAny>>,
callback: Option<Bound<'py, PyAny>>,
) -> PyResult<Py<PyAny>> {
let (feature_map, ansatz) = fake_qml_circuits(py);
let rows = py.eval(c"[[0.1], [0.2]]", None, None).expect("the rows");
qml_train(
feature_map,
ansatz,
rows,
method,
16,
1,
1,
expectation_function,
infrastructure.to_string(),
1,
1,
"edge".to_string(),
"automatic",
None,
"aer",
Some(3),
None,
None,
None,
None,
final_shots,
callback,
)
}
#[test]
fn a_callback_is_checked_after_final_shots_and_before_the_backend() {
use std::sync::atomic::{AtomicUsize, Ordering};
static TRAIN_BUILDS: AtomicUsize = AtomicUsize::new(0);
static QML_BUILDS: AtomicUsize = AtomicUsize::new(0);
register_sentinel_backend("sentinel-train-500", &TRAIN_BUILDS);
register_sentinel_backend("sentinel-qml-train-500", &QML_BUILDS);
Python::initialize();
Python::attach(|py| {
let cost = py.eval(c"lambda bits: 0.0", None, None).unwrap();
let not_callable = py.eval(c"'checkpoint.json'", None, None).unwrap();
let callable = py.eval(c"lambda progress: None", None, None).unwrap();
let zero = 0_i32.into_pyobject(py).unwrap().into_any();
type Run = for<'py> fn(
Python<'py>,
&str,
Bound<'py, PyAny>,
Bound<'py, PyAny>,
Option<Bound<'py, PyAny>>,
Option<Bound<'py, PyAny>>,
) -> PyResult<Py<PyAny>>;
let entry_points: [(&str, &str, &AtomicUsize, Run); 2] = [
("train", "sentinel-train-500", &TRAIN_BUILDS, train_with),
(
"qml.train",
"sentinel-qml-train-500",
&QML_BUILDS,
qml_train_with,
),
];
for (name, infrastructure, builds, run) in entry_points {
let err = run(
py,
infrastructure,
de(py, 4),
cost.clone(),
None,
Some(not_callable.clone()),
)
.expect_err("a callback that is not callable is rejected");
assert!(
err.is_instance_of::<pyo3::exceptions::PyTypeError>(py),
"{name}: {err}"
);
assert!(
err.to_string()
.contains("callback must be a callable or None, got 'checkpoint.json'"),
"{name}: {err}"
);
let err = run(
py,
infrastructure,
de(py, 4),
cost.clone(),
Some(zero.clone()),
Some(not_callable.clone()),
)
.expect_err("final_shots=0 is rejected");
crate::exceptions::tests::assert_configuration_error(&err, "final_shots");
assert_eq!(
builds.load(Ordering::SeqCst),
0,
"{name} created the backend"
);
let err = run(
py,
infrastructure,
de(py, 4),
cost.clone(),
None,
Some(callable.clone()),
)
.expect_err("the sentinel backend fails");
assert!(
err.to_string().contains("sentinel backend was created"),
"{name}: {err}"
);
assert_eq!(builds.load(Ordering::SeqCst), 1, "{name}");
}
});
}
#[test]
fn training_checks_the_configuration_before_creating_the_backend() {
use std::sync::atomic::{AtomicUsize, Ordering};
static TRAIN_BUILDS: AtomicUsize = AtomicUsize::new(0);
static QML_BUILDS: AtomicUsize = AtomicUsize::new(0);
register_sentinel_backend("sentinel-train-418", &TRAIN_BUILDS);
register_sentinel_backend("sentinel-qml-train-418", &QML_BUILDS);
Python::initialize();
Python::attach(|py| {
let not_an_observable = 42_i32.into_pyobject(py).unwrap().into_any();
let cost = py.eval(c"lambda bits: 0.0", None, None).unwrap();
type Run = for<'py> fn(
Python<'py>,
&str,
Bound<'py, PyAny>,
Bound<'py, PyAny>,
) -> PyResult<Py<PyAny>>;
let entry_points: [(&str, &str, &AtomicUsize, Run); 2] = [
("train", "sentinel-train-418", &TRAIN_BUILDS, train_on),
(
"qml.train",
"sentinel-qml-train-418",
&QML_BUILDS,
qml_train_on,
),
];
for (name, infrastructure, builds, run) in entry_points {
let err = run(py, infrastructure, de(py, 4), not_an_observable.clone())
.expect_err("an invalid observable is rejected");
assert!(
err.is_instance_of::<pyo3::exceptions::PyTypeError>(py),
"{name}: {err}"
);
assert!(
err.to_string().contains("expectation_function"),
"{name}: {err}"
);
let err = run(py, infrastructure, de(py, 3), cost.clone())
.expect_err("a population too small is rejected");
crate::exceptions::tests::assert_configuration_error(&err, "population_size");
assert_eq!(
builds.load(Ordering::SeqCst),
0,
"{name} created the backend"
);
let err = run(py, infrastructure, de(py, 4), cost.clone())
.expect_err("the sentinel backend fails");
assert!(
err.to_string().contains("sentinel backend was created"),
"{name}: {err}"
);
assert_eq!(builds.load(Ordering::SeqCst), 1, "{name}");
}
});
}
#[test]
fn qml_rejects_qmio_before_reading_the_model() {
Python::initialize();
Python::attach(|py| {
let none = || py.None().into_bound(py);
let cost = py.eval(c"lambda bits: 0.0", None, None).unwrap();
let train_err = qml_train(
none(),
none(),
none(),
de(py, 4),
16,
1,
1,
cost,
"qmio".to_string(),
1,
1,
"edge".to_string(),
"automatic",
None,
"aer",
None,
None,
None,
None,
None,
None,
None,
)
.expect_err("qmio is rejected");
let predict_err = qml_predict(
none(),
none(),
none(),
vec![0.0],
16,
"qmio".to_string(),
1,
1,
1,
"automatic",
None,
"aer",
None,
None,
)
.expect_err("qmio is rejected");
for err in [train_err, predict_err] {
crate::exceptions::tests::assert_configuration_error(
&err,
"cannot serialize the Qiskit circuits of a QML model",
);
}
});
}
#[test]
fn argument_checks_raise_configuration_error() {
Python::initialize();
let cases: [(PyResult<()>, &str); 6] = [
(validate_id(""), "id must not be empty"),
(validate_id("a b"), "' '"),
(validate_id(&"a".repeat(65)), "64"),
(validate_cunqa_allocation("cunqa", 0, 1, None), "nodes"),
(
validate_cunqa_allocation("cunqa", 1, 0, None),
"cores_per_qpu",
),
(
validate_cunqa_allocation("cunqa", 1, 1, Some("1-00:00:00")),
"walltime",
),
];
for (result, message) in cases {
let err = result.expect_err("the argument is rejected");
crate::exceptions::tests::assert_configuration_error(&err, message);
}
}
#[test]
fn python_version_keeps_a_release_version() {
assert_eq!(python_version("0.8.0"), "0.8.0");
}
#[test]
fn python_version_maps_a_dev_version_as_maturin_does() {
assert_eq!(python_version("0.8.1-dev"), "0.8.1.dev0");
}
}