use nalgebra::{DMatrix, DVector};
#[cfg(feature = "friedrich_ndarray")]
use ndarray::{Array1, ArrayBase, Data, Ix1, Ix2};
pub trait Input: Sized
{
type InVector: Sized;
type OutVector;
fn to_dmatrix(m: &Self) -> DMatrix<f64>;
fn into_dmatrix(m: Self) -> DMatrix<f64>
{
Self::to_dmatrix(&m)
}
fn to_dvector(v: &Self::InVector) -> DVector<f64>;
fn into_dvector(v: Self::InVector) -> DVector<f64>
{
Self::to_dvector(&v)
}
fn from_dvector(v: &DVector<f64>) -> Self::OutVector;
}
impl Input for DMatrix<f64>
{
type InVector = DVector<f64>;
type OutVector = DVector<f64>;
fn to_dmatrix(m: &Self) -> DMatrix<f64>
{
m.clone()
}
fn to_dvector(v: &Self::InVector) -> DVector<f64>
{
v.clone()
}
fn into_dmatrix(m: Self) -> DMatrix<f64>
{
m
}
fn into_dvector(v: Self::InVector) -> DVector<f64>
{
v
}
fn from_dvector(v: &DVector<f64>) -> Self::OutVector
{
v.clone()
}
}
impl Input for Vec<f64>
{
type InVector = f64;
type OutVector = f64;
fn to_dmatrix(m: &Self) -> DMatrix<f64>
{
DMatrix::from_row_slice(1, m.len(), m)
}
fn to_dvector(v: &Self::InVector) -> DVector<f64>
{
DVector::from_element(1, *v)
}
fn from_dvector(v: &DVector<f64>) -> Self::OutVector
{
assert_eq!(v.nrows(), 1);
v[0]
}
}
impl Input for Vec<Vec<f64>>
{
type InVector = Vec<f64>;
type OutVector = Vec<f64>;
fn to_dmatrix(m: &Self) -> DMatrix<f64>
{
let nb_rows = m.len();
assert_ne!(nb_rows, 0);
let nb_cols = m[0].len();
DMatrix::from_fn(nb_rows, nb_cols, |r, c| m[r][c])
}
fn to_dvector(v: &Self::InVector) -> DVector<f64>
{
DVector::from_column_slice(v)
}
fn from_dvector(v: &DVector<f64>) -> Self::OutVector
{
v.iter().cloned().collect()
}
}
#[cfg(feature = "friedrich_ndarray")]
impl<D: Data<Elem = f64>> Input for ArrayBase<D, Ix2>
{
type InVector = ArrayBase<D, Ix1>;
type OutVector = Array1<f64>;
fn to_dmatrix(m: &Self) -> DMatrix<f64>
{
assert_ne!(m.nrows(), 0);
DMatrix::from_iterator(m.nrows(), m.ncols(), m.t().iter().cloned())
}
fn to_dvector(v: &Self::InVector) -> DVector<f64>
{
DVector::from_iterator(v.len(), v.iter().cloned())
}
fn from_dvector(v: &DVector<f64>) -> Self::OutVector
{
v.iter().cloned().collect()
}
}
#[cfg(feature = "friedrich_ndarray")]
impl<D: Data<Elem = f64>> Input for ArrayBase<D, Ix1>
{
type InVector = f64;
type OutVector = f64;
fn to_dmatrix(m: &Self) -> DMatrix<f64>
{
DMatrix::from_iterator(1, m.len(), m.iter().cloned())
}
fn to_dvector(v: &Self::InVector) -> DVector<f64>
{
DVector::from_element(1, *v)
}
fn from_dvector(v: &DVector<f64>) -> Self::OutVector
{
assert_eq!(v.nrows(), 1);
v[0]
}
}