use crate::convert::flatten_rectangular;
use crate::error::MattenError;
use crate::shape;
use std::fmt;
use crate::limits::MattenLimits;
#[derive(Clone)]
pub struct Tensor {
pub(crate) data: Vec<f64>,
pub(crate) shape: Vec<usize>,
#[cfg(feature = "dynamic")]
pub(crate) dynamic: Option<Box<crate::dynamic::storage::DynamicTensor>>,
}
impl PartialEq for Tensor {
fn eq(&self, other: &Self) -> bool {
if self.shape != other.shape {
return false;
}
#[cfg(feature = "dynamic")]
{
match (&self.dynamic, &other.dynamic) {
(Some(a), Some(b)) => return a.to_vec() == b.to_vec(),
(None, None) => {}
_ => return false,
}
}
self.data == other.data
}
}
#[allow(clippy::len_without_is_empty)]
impl Tensor {
#[cfg(feature = "dynamic")]
#[inline(always)]
pub(crate) fn panic_if_dynamic(&self, operation: &'static str) {
if self.is_dynamic() {
panic!(
"matten unsupported error in {operation}: this numeric API is not supported on dynamic tensors; use to_elements() or try_numeric() first"
);
}
}
#[must_use]
pub fn new(data: Vec<f64>, shape: &[usize]) -> Tensor {
Self::try_new(data, shape).unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_new(data: Vec<f64>, shape: &[usize]) -> Result<Tensor, MattenError> {
let expected = shape::validate_shape(shape, "try_new")?;
if data.len() != expected {
return Err(MattenError::Shape {
operation: "try_new",
message: format!(
"data length {} does not match shape {shape:?}, which requires {expected} elements",
data.len()
),
});
}
Ok(Tensor {
data,
shape: shape.to_vec(),
#[cfg(feature = "dynamic")]
dynamic: None,
})
}
#[must_use]
pub fn scalar(value: f64) -> Tensor {
Tensor {
data: vec![value],
shape: Vec::new(),
#[cfg(feature = "dynamic")]
dynamic: None,
}
}
#[must_use]
pub fn zeros(shape: &[usize]) -> Tensor {
Self::try_zeros(shape).unwrap_or_else(|e| panic!("{e}"))
}
#[must_use]
pub fn ones(shape: &[usize]) -> Tensor {
Self::try_ones(shape).unwrap_or_else(|e| panic!("{e}"))
}
#[must_use]
pub fn full(shape: &[usize], value: f64) -> Tensor {
Self::try_full(shape, value).unwrap_or_else(|e| panic!("{e}"))
}
#[must_use]
pub fn from_vec(data: Vec<f64>) -> Tensor {
let len = data.len();
Tensor::new(data, &[len])
}
#[must_use]
pub fn arange(start: f64, end: f64, step: f64) -> Tensor {
arange_impl(start, end, step, "arange").unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_arange(start: f64, end: f64, step: f64) -> Result<Tensor, MattenError> {
arange_impl(start, end, step, "try_arange")
}
pub fn try_from_rows(rows: Vec<Vec<f64>>) -> Result<Tensor, MattenError> {
let (data, shape) = flatten_rectangular(rows, "try_from_rows")?;
Ok(Tensor {
data,
shape,
#[cfg(feature = "dynamic")]
dynamic: None,
})
}
#[must_use]
pub fn shape(&self) -> &[usize] {
&self.shape
}
#[must_use]
pub fn ndim(&self) -> usize {
self.shape.len()
}
#[must_use]
pub fn len(&self) -> usize {
#[cfg(feature = "dynamic")]
if let Some(dyn_t) = &self.dynamic {
return dyn_t.len;
}
self.data.len()
}
#[must_use]
pub fn is_scalar(&self) -> bool {
self.ndim() == 0
}
#[must_use]
pub fn is_vector(&self) -> bool {
self.ndim() == 1
}
#[must_use]
pub fn is_matrix(&self) -> bool {
self.ndim() == 2
}
#[must_use]
pub fn as_slice(&self) -> &[f64] {
#[cfg(feature = "dynamic")]
self.panic_if_dynamic("as_slice");
&self.data
}
#[must_use]
pub fn to_vec(&self) -> Vec<f64> {
#[cfg(feature = "dynamic")]
self.panic_if_dynamic("to_vec");
self.data.clone()
}
#[must_use]
pub fn into_vec(self) -> Vec<f64> {
#[cfg(feature = "dynamic")]
self.panic_if_dynamic("into_vec");
self.data
}
}
impl fmt::Debug for Tensor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
const MAX: usize = 8;
#[cfg(feature = "dynamic")]
if let Some(dyn_t) = &self.dynamic {
write!(f, "Tensor(shape={:?}, dynamic=[", self.shape)?;
for i in 0..dyn_t.len.min(MAX) {
if i > 0 {
f.write_str(", ")?;
}
if let Some(e) = dyn_t.get_flat(i) {
write!(f, "{e:?}")?;
}
}
if dyn_t.len > MAX {
write!(f, ", ... ({} more)", dyn_t.len - MAX)?;
}
return f.write_str("])");
}
write!(f, "Tensor(shape={:?}, data=[", self.shape)?;
for (i, v) in self.data.iter().take(MAX).enumerate() {
if i > 0 {
f.write_str(", ")?;
}
write!(f, "{v:?}")?;
}
if self.data.len() > MAX {
write!(f, ", ... ({} more)", self.data.len() - MAX)?;
}
f.write_str("])")
}
}
fn arange_impl(
start: f64,
end: f64,
step: f64,
operation: &'static str,
) -> Result<Tensor, MattenError> {
if !start.is_finite() || !end.is_finite() {
return Err(MattenError::Shape {
operation,
message: format!("start and end must be finite (got start={start}, end={end})"),
});
}
if step == 0.0 || !step.is_finite() {
return Err(MattenError::Shape {
operation,
message: format!("step must be a non-zero finite value (got {step})"),
});
}
let raw_count = ((end - start) / step).ceil();
let count: usize = if raw_count <= 0.0 {
0
} else if raw_count > MattenLimits::default().max_elements as f64 {
return Err(MattenError::Allocation {
requested_elements: raw_count as usize,
message: format!(
"arange would produce ~{} elements, exceeding the limit of {}",
raw_count as usize,
MattenLimits::default().max_elements
),
});
} else {
raw_count as usize
};
let mut data = Vec::with_capacity(count);
let mut i: usize = 0;
loop {
let v = start + step * i as f64;
if (step > 0.0 && v >= end) || (step < 0.0 && v <= end) {
break;
}
data.push(v);
i += 1;
if i > MattenLimits::default().max_elements {
return Err(MattenError::Allocation {
requested_elements: i,
message: format!(
"arange exceeded the element limit of {}",
MattenLimits::default().max_elements
),
});
}
}
let len = data.len();
if len == 0 {
return Err(MattenError::Shape {
operation,
message: format!("arange(start={start}, end={end}, step={step}) produces no elements"),
});
}
Ok(Tensor {
data,
shape: vec![len],
#[cfg(feature = "dynamic")]
dynamic: None,
})
}
mod ops;