use super::super::super::CpuRuntime;
use crate::dtype::Element;
use crate::error::{Error, Result};
use crate::tensor::Tensor;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum MergeStrategy {
Union,
Intersection,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum OperationSemantics {
Add,
Subtract,
Multiply,
Divide,
}
#[allow(clippy::too_many_arguments)]
pub(super) fn handle_empty_compressed<T: Element>(
a_nnz: usize,
b_nnz: usize,
shape: [usize; 2],
device: &<CpuRuntime as crate::runtime::Runtime>::Device,
a_ptrs: &Tensor<CpuRuntime>,
a_indices: &Tensor<CpuRuntime>,
a_values: &Tensor<CpuRuntime>,
b_ptrs: &Tensor<CpuRuntime>,
b_indices: &Tensor<CpuRuntime>,
b_values: &Tensor<CpuRuntime>,
semantics: OperationSemantics,
format_is_csr: bool,
) -> Option<Result<(Tensor<CpuRuntime>, Tensor<CpuRuntime>, Tensor<CpuRuntime>)>> {
let ptr_dim = if format_is_csr { shape[0] } else { shape[1] };
let empty_result =
|| -> Result<(Tensor<CpuRuntime>, Tensor<CpuRuntime>, Tensor<CpuRuntime>)> {
let empty_ptrs = Tensor::from_slice(&vec![0i64; ptr_dim + 1], &[ptr_dim + 1], device)?;
let empty_indices = Tensor::from_slice(&Vec::<i64>::new(), &[0], device)?;
let empty_vals = Tensor::from_slice(&Vec::<T>::new(), &[0], device)?;
Ok((empty_ptrs, empty_indices, empty_vals))
};
match (a_nnz, b_nnz, semantics) {
(0, 0, _) => Some(empty_result()),
(0, _, OperationSemantics::Add) => {
Some(Ok((b_ptrs.clone(), b_indices.clone(), b_values.clone())))
}
(0, _, OperationSemantics::Subtract) => {
let b_vals: Vec<T> = b_values.to_vec();
let negated_vals: Vec<T> = b_vals.iter().map(|&v| T::from_f64(-v.to_f64())).collect();
Some(
Tensor::from_slice(&negated_vals, &[negated_vals.len()], device)
.map(|out_vals| (b_ptrs.clone(), b_indices.clone(), out_vals)),
)
}
(0, _, OperationSemantics::Multiply) => {
Some(empty_result())
}
(0, _, OperationSemantics::Divide) => {
Some(empty_result())
}
(_, 0, OperationSemantics::Add) => {
Some(Ok((a_ptrs.clone(), a_indices.clone(), a_values.clone())))
}
(_, 0, OperationSemantics::Subtract) => {
Some(Ok((a_ptrs.clone(), a_indices.clone(), a_values.clone())))
}
(_, 0, OperationSemantics::Multiply) => {
Some(empty_result())
}
(_, 0, OperationSemantics::Divide) => {
Some(Err(Error::Internal(
"Division by zero - B matrix is empty".to_string(),
)))
}
(_, _, _) => None,
}
}