use torsh_core::device::DeviceType;
use torsh_core::{Result as TorshResult, TorshError};
use torsh_tensor::{creation::from_vec, Tensor};
use scirs2_core::ndarray::{Array1, Array2};
#[derive(Debug, Clone, Copy)]
pub enum NormOrd {
Fro,
Nuclear,
Inf,
NegInf,
P(f32),
}
pub fn tensor_to_array2(tensor: &Tensor) -> TorshResult<Array2<f32>> {
let shape = tensor.shape();
if shape.ndim() != 2 {
return Err(TorshError::invalid_argument_with_context(
"Expected 2D tensor",
"tensor_to_array2",
));
}
let data = tensor.data()?;
let dims = shape.dims();
Array2::from_shape_vec((dims[0], dims[1]), data.clone()).map_err(|e| {
TorshError::invalid_argument_with_context(
&format!("Failed to create Array2: {}", e),
"tensor_to_array2",
)
})
}
#[allow(dead_code)]
pub fn array2_to_tensor(array: Array2<f32>) -> TorshResult<Tensor> {
let shape = array.shape().to_vec();
let data = array.into_raw_vec();
Ok(from_vec(data, &[shape[0], shape[1]], DeviceType::Cpu)?)
}
#[allow(dead_code)]
pub fn tensor_to_array1(tensor: &Tensor) -> TorshResult<Array1<f32>> {
let shape = tensor.shape();
if shape.ndim() != 1 {
return Err(TorshError::invalid_argument_with_context(
"Expected 1D tensor",
"tensor_to_array1",
));
}
let data = tensor.data()?;
Ok(Array1::from_vec(data.clone()))
}
#[allow(dead_code)]
pub fn array1_to_tensor(array: Array1<f32>) -> TorshResult<Tensor> {
let length = array.len();
let data = array.into_raw_vec();
Ok(from_vec(data, &[length], DeviceType::Cpu)?)
}