mod ends;
mod residual;
use super::constants::CRITICAL_FLOOR;
use super::roots::{self, BarrelDepths};
use super::{BarrelClient, RowNames};
use crate::structures::StructureError;
use crate::structures::tensor::culvert::TensorBarrelContext;
use numr::dtype::DType;
use numr::runtime::Runtime;
use numr::tensor::Tensor;
use solvr::common::arithmetic::with_interval_arithmetic;
use solvr::optimize::CertifiedBisectionAlgorithms;
pub(crate) fn solve<R>(
names: RowNames<'_, R>,
barrel: &TensorBarrelContext<R>,
unit: &TensorBarrelContext<R>,
discharge: &Tensor<R>,
roughness: &Tensor<R>,
slope: &Tensor<R>,
) -> Result<BarrelDepths<R>, StructureError>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R> + CertifiedBisectionAlgorithms<R>,
{
solve_to(
names,
barrel,
unit,
[discharge, roughness, slope],
roots::RELATIVE_TOLERANCE,
)
}
pub(crate) fn solve_to<R>(
names: RowNames<'_, R>,
barrel: &TensorBarrelContext<R>,
unit: &TensorBarrelContext<R>,
[discharge, roughness, slope]: [&Tensor<R>; 3],
rtol: f64,
) -> Result<BarrelDepths<R>, StructureError>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R> + CertifiedBisectionAlgorithms<R>,
{
let c = &barrel.client;
let (ends, floors) =
with_interval_arithmetic(c, DType::F64, "culvert normal depth ends", |a| {
ends::classify(a, barrel, unit, discharge, roughness, slope)
})?;
roots::solve(
barrel,
unit,
ends,
roots::Stopping {
slope: &floors,
rtol,
stage: "culvert normal residual",
},
residual::residual,
|row| {
describe(
names,
[discharge, roughness, slope, &barrel.normal_top],
row,
)
},
)
}
fn describe<R>(
names: RowNames<'_, R>,
inputs: [&Tensor<R>; 4],
row: usize,
) -> Result<String, StructureError>
where
R: Runtime<DType = DType>,
{
let mut values = [f64::NAN; 4];
for (value, input) in values.iter_mut().zip(inputs) {
if let Some(read) = input.try_to_vec::<f64>()?.get(row) {
*value = *read;
}
}
let [discharge, roughness, slope, fraction] = values;
let Some(entry) = names.barrel(row)? else {
return Err(StructureError::numerical(format!(
"normal depth row={row}: the solver named a row past the barrel list. Report this runtime"
)));
};
let rise = entry.open_rise_m();
let top = rise * fraction;
Ok(format!(
"normal depth shape={:?},rise_m={:?},open_rise_m={rise:?},span_m={:?},discharge_m3_per_s={discharge:?},manning_n={roughness:?},slope={slope:?},bracket_m=[{:?}, {top:?}]",
entry.shape(),
entry.rise_m(),
entry.span_m(),
rise * CRITICAL_FLOOR,
))
}