use crate::structures::StructureError;
use crate::structures::numerics::culvert::BarrelDepths;
use crate::structures::tensor::codes;
use numr::dtype::DType;
use numr::runtime::Runtime;
use numr::tensor::Tensor;
use std::fmt::Debug;
use std::marker::PhantomData;
mod sealed {
pub trait Sealed: Sized {
fn from_code(code: f64) -> Option<Self>;
}
}
pub trait BarrelDepthStatus: sealed::Sealed + Copy + Debug + PartialEq {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CriticalDepthStatus {
Dry,
Solved,
BelowFloor,
AtCrown,
AboveCrown,
}
impl sealed::Sealed for CriticalDepthStatus {
fn from_code(code: f64) -> Option<Self> {
[
(codes::CRITICAL_DRY, Self::Dry),
(codes::CRITICAL_SOLVED, Self::Solved),
(codes::CRITICAL_BELOW_FLOOR, Self::BelowFloor),
(codes::CRITICAL_AT_CROWN, Self::AtCrown),
(codes::CRITICAL_ABOVE_CROWN, Self::AboveCrown),
]
.into_iter()
.find_map(|(value, status)| (value == code).then_some(status))
}
}
impl BarrelDepthStatus for CriticalDepthStatus {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NormalDepthStatus {
Dry,
Solved,
BelowFloor,
NearCapacity,
AboveCapacity,
NonPositiveSlope,
}
impl sealed::Sealed for NormalDepthStatus {
fn from_code(code: f64) -> Option<Self> {
[
(codes::NORMAL_DRY, Self::Dry),
(codes::NORMAL_SOLVED, Self::Solved),
(codes::NORMAL_BELOW_FLOOR, Self::BelowFloor),
(codes::NORMAL_NEAR_CAPACITY, Self::NearCapacity),
(codes::NORMAL_ABOVE_CAPACITY, Self::AboveCapacity),
(codes::NORMAL_NON_POSITIVE_SLOPE, Self::NonPositiveSlope),
]
.into_iter()
.find_map(|(value, status)| (value == code).then_some(status))
}
}
impl BarrelDepthStatus for NormalDepthStatus {}
pub struct CulvertBarrelDepth<R: Runtime<DType = DType>, S: BarrelDepthStatus> {
status: Tensor<R>,
lower: Tensor<R>,
upper: Tensor<R>,
marker: PhantomData<S>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CulvertBarrelDepthRow<S: BarrelDepthStatus> {
pub status: S,
pub depth_m: Option<(f64, f64)>,
}
impl<R: Runtime<DType = DType>, S: BarrelDepthStatus> CulvertBarrelDepth<R, S> {
pub(crate) fn from_depths(depths: BarrelDepths<R>) -> Self {
Self {
status: depths.status,
lower: depths.lower,
upper: depths.upper,
marker: PhantomData,
}
}
pub fn depth_m(&self) -> (&Tensor<R>, &Tensor<R>) {
(&self.lower, &self.upper)
}
pub fn project(&self) -> Result<Vec<CulvertBarrelDepthRow<S>>, StructureError> {
let status = self.status.try_to_vec::<f64>()?;
let lower = self.lower.try_to_vec::<f64>()?;
let upper = self.upper.try_to_vec::<f64>()?;
status
.iter()
.zip(lower.iter().zip(&upper))
.enumerate()
.map(|(row, (&code, (&low, &high)))| {
let status = <S as sealed::Sealed>::from_code(code).ok_or_else(|| {
StructureError::numerical(format!(
"depth status code={code}: report this row, the code is not a depth status"
))
.at(row)
})?;
let depth_m = (!low.is_nan()).then_some((low, high));
Ok(CulvertBarrelDepthRow { status, depth_m })
})
.collect()
}
}