use crate::{MattenError, Tensor};
impl From<Vec<f64>> for Tensor {
fn from(data: Vec<f64>) -> Self {
let len = data.len();
Tensor::new(data, &[len])
}
}
impl From<Vec<Vec<f64>>> for Tensor {
fn from(rows: Vec<Vec<f64>>) -> Self {
Tensor::try_from_rows(rows).unwrap_or_else(|e| panic!("{e}"))
}
}
impl From<Tensor> for Vec<f64> {
fn from(t: Tensor) -> Vec<f64> {
#[cfg(feature = "dynamic")]
t.panic_if_dynamic("From<Tensor> for Vec<f64>");
t.data
}
}
impl From<&Tensor> for Vec<f64> {
fn from(t: &Tensor) -> Vec<f64> {
#[cfg(feature = "dynamic")]
t.panic_if_dynamic("From<&Tensor> for Vec<f64>");
t.data.clone()
}
}
impl TryFrom<Tensor> for Vec<Vec<f64>> {
type Error = MattenError;
fn try_from(t: Tensor) -> Result<Vec<Vec<f64>>, MattenError> {
#[cfg(feature = "dynamic")]
if t.is_dynamic() {
return Err(MattenError::Unsupported {
operation: "TryFrom<Tensor> for Vec<Vec<f64>>",
message: "dynamic tensors cannot be converted to Vec<Vec<f64>>; ".to_string()
+ "call try_numeric() first",
});
}
if t.ndim() != 2 {
return Err(MattenError::Shape {
operation: "TryFrom<Tensor> for Vec<Vec<f64>>",
message: format!(
"expected a rank-2 tensor but found rank {} (shape {:?})",
t.ndim(),
t.shape()
),
});
}
let rows = t.shape[0];
let cols = t.shape[1];
let mut data = t.data.into_iter();
Ok((0..rows)
.map(|_| (0..cols).map(|_| data.next().unwrap()).collect())
.collect())
}
}
pub(crate) fn flatten_rectangular(
rows: Vec<Vec<f64>>,
operation: &'static str,
) -> Result<(Vec<f64>, Vec<usize>), MattenError> {
let row_count = rows.len();
if row_count == 0 {
return Err(MattenError::Shape {
operation,
message: "cannot create a tensor from an empty row list (zero-sized dimensions are not supported in matten 0.1)".into(),
});
}
let col_count = rows[0].len();
if col_count == 0 {
return Err(MattenError::Shape {
operation,
message: "rows must have at least one column (zero-sized dimensions are not supported in matten 0.1)".into(),
});
}
let mut flat = Vec::with_capacity(row_count * col_count);
for (i, row) in rows.into_iter().enumerate() {
if row.len() != col_count {
return Err(MattenError::Shape {
operation,
message: format!(
"ragged rows: row 0 has {col_count} columns but row {i} has {} columns",
row.len()
),
});
}
flat.extend(row);
}
Ok((flat, vec![row_count, col_count]))
}