use super::{ControlledPumpBatch, PumpResponseDefinition};
use crate::structures::{OperatingControlSnapshotData, StructureError, StructureInputErrorKind};
use hydr_core::contract::package_identity;
use numr::dtype::DType;
use numr::runtime::Runtime;
pub const CONTROLLED_PUMP_SNAPSHOT_SCHEMA: &str = "hydr-controlled-pump-checkpoint-1";
pub const CONTROLLED_PUMP_CONTRACT_VERSION: &str = "hydr-controlled-pump-numr-cpu-1";
#[derive(Clone, Debug, PartialEq)]
pub struct ControlledPumpSnapshotData {
pub schema: String,
pub contract: String,
pub definitions: Vec<PumpResponseDefinition>,
pub controls: OperatingControlSnapshotData,
}
#[derive(Clone, Debug)]
pub struct ControlledPumpSnapshot<R: Runtime<DType = DType>> {
batch: ControlledPumpBatch<R>,
}
impl<R: Runtime<DType = DType>> ControlledPumpSnapshot<R> {
pub fn time(&self) -> f64 {
self.batch.time()
}
pub fn data(&self) -> Result<ControlledPumpSnapshotData, StructureError> {
self.batch.snapshot_data()
}
}
fn require(condition: bool, message: &str) -> Result<(), StructureError> {
if condition {
Ok(())
} else {
Err(StructureError::input(
StructureInputErrorKind::Definition,
message,
))
}
}
impl<R: Runtime<DType = DType>> ControlledPumpBatch<R> {
pub fn snapshot(&self) -> ControlledPumpSnapshot<R> {
ControlledPumpSnapshot {
batch: self.clone(),
}
}
pub fn snapshot_data(&self) -> Result<ControlledPumpSnapshotData, StructureError> {
Ok(ControlledPumpSnapshotData {
schema: CONTROLLED_PUMP_SNAPSHOT_SCHEMA.into(),
contract: CONTROLLED_PUMP_CONTRACT_VERSION.into(),
definitions: self.definitions().to_vec(),
controls: self.controls.snapshot_data()?,
})
}
pub fn restore(&mut self, snapshot: &ControlledPumpSnapshot<R>) -> Result<(), StructureError> {
require(
super::compatibility::same_context(&self.context, &snapshot.batch.context),
"controlled pump snapshot response assumptions or immutable controller model differ",
)?;
let mut controls = self.controls.clone();
controls.restore(&snapshot.batch.controls.snapshot())?;
self.controls = controls;
Ok(())
}
pub fn restore_data(&mut self, data: &ControlledPumpSnapshotData) -> Result<(), StructureError>
where
R::Client: numr::ops::BinaryOps<R>
+ numr::ops::CompareOps<R>
+ numr::ops::ConditionalOps<R>
+ numr::ops::ReduceOps<R>
+ numr::ops::ScalarOps<R>
+ numr::ops::TwoSumOps<R>
+ numr::ops::TypeConversionOps<R>
+ numr::ops::UnaryOps<R>,
{
package_identity(
"controlled pump",
&data.schema,
CONTROLLED_PUMP_SNAPSHOT_SCHEMA,
&data.contract,
CONTROLLED_PUMP_CONTRACT_VERSION,
)
.map_err(StructureError::definition)?;
require(
self.definitions() == data.definitions.as_slice(),
"controlled pump snapshot original response assumptions differ",
)?;
let mut controls = self.controls.clone();
controls.restore_data(&data.controls)?;
self.controls = controls;
Ok(())
}
}