use crate::{MattenError, Tensor};
impl Tensor {
#[must_use]
pub fn reshape(&self, new_shape: &[usize]) -> Tensor {
crate::reshape::try_reshape_impl(self, new_shape).unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_reshape(&self, new_shape: &[usize]) -> Result<Tensor, MattenError> {
crate::reshape::try_reshape_impl(self, new_shape)
}
#[must_use]
pub fn flatten(&self) -> Tensor {
#[cfg(feature = "dynamic")]
if self.is_dynamic() {
panic!(
"matten unsupported error in flatten: dynamic tensors do not support flatten; call try_numeric() first to convert to a numeric tensor"
);
}
let len = self.data.len();
Tensor {
data: self.data.clone(),
shape: vec![len],
#[cfg(feature = "dynamic")]
dynamic: None,
}
}
#[must_use]
pub fn transpose(&self) -> Tensor {
let ndim = self.ndim();
if ndim == 0 {
panic!("matten shape error in transpose: cannot transpose a scalar (rank 0)");
}
let perm: Vec<usize> = (0..ndim).rev().collect();
crate::reshape::permute_axes(self, &perm)
}
#[must_use]
pub fn t(&self) -> Tensor {
self.transpose()
}
#[must_use]
pub fn swap_axes(&self, axis1: usize, axis2: usize) -> Tensor {
crate::reshape::validate_axes(axis1, axis2, self.ndim(), "swap_axes")
.unwrap_or_else(|e| panic!("{e}"));
let mut perm: Vec<usize> = (0..self.ndim()).collect();
perm.swap(axis1, axis2);
crate::reshape::permute_axes(self, &perm)
}
pub fn get(&self, coord: &[usize]) -> Option<f64> {
#[cfg(feature = "dynamic")]
self.panic_if_dynamic("get");
let flat = crate::shape::coord_to_flat(coord, &self.shape)?;
self.data.get(flat).copied()
}
pub fn get_flat(&self, index: usize) -> Option<f64> {
#[cfg(feature = "dynamic")]
self.panic_if_dynamic("get_flat");
self.data.get(index).copied()
}
pub fn slice(&self) -> crate::slice::SliceBuilder<'_> {
crate::slice::SliceBuilder::new(self)
}
pub fn slice_str(&self, spec: &str) -> Result<Tensor, MattenError> {
let specs = crate::slice::parse_slice_str(spec)?;
crate::slice::execute_slice(self, &specs, "slice_str")
}
}
impl Tensor {
#[cfg(feature = "json")]
pub fn from_json(input: &str) -> Result<Tensor, MattenError> {
crate::parse::json::from_json_str(input)
}
#[cfg(feature = "csv")]
pub fn from_csv(input: &str) -> Result<Tensor, MattenError> {
crate::parse::csv::from_csv_str(input)
}
#[cfg(feature = "json")]
pub fn load_json(path: impl AsRef<std::path::Path>) -> Result<Tensor, MattenError> {
let path = path.as_ref();
let content = std::fs::read_to_string(path).map_err(|e| MattenError::Io {
path: path.to_path_buf(),
source: e,
})?;
crate::parse::json::from_json_str(&content)
}
#[cfg(feature = "csv")]
pub fn load_csv(path: impl AsRef<std::path::Path>) -> Result<Tensor, MattenError> {
let path = path.as_ref();
let content = std::fs::read_to_string(path).map_err(|e| MattenError::Io {
path: path.to_path_buf(),
source: e,
})?;
crate::parse::csv::from_csv_str(&content)
}
}