use crate::backend_ops::BackendOps;
use crate::backend_ops::UnaryOp;
use coeus_core::{BackendError, Float};
use coeus_tensor::Tensor;
#[inline]
pub fn where_cond<T: Float, B: BackendOps<T> + Default>(
cond: &Tensor<T, B>,
on_true: &Tensor<T, B>,
on_false: &Tensor<T, B>,
backend: &B,
) -> Result<Tensor<T, B>, B::Error> {
if cond.shape() != on_true.shape() {
return Err(B::Error::from(BackendError::ShapeMismatch {
operation: "where_cond",
lhs: cond.shape().to_vec(),
rhs: on_true.shape().to_vec(),
}));
}
if cond.shape() != on_false.shape() {
return Err(B::Error::from(BackendError::ShapeMismatch {
operation: "where_cond",
lhs: cond.shape().to_vec(),
rhs: on_false.shape().to_vec(),
}));
}
let mask_pos = crate::unary::elementwise_unary(cond, backend, UnaryOp::ReluGrad)?;
let cond_neg = crate::unary::elementwise_unary(cond, backend, UnaryOp::Neg)?;
let mask_neg = crate::unary::elementwise_unary(&cond_neg, backend, UnaryOp::ReluGrad)?;
let any_mask = crate::binary::add(&mask_pos, &mask_neg, backend);
let one = Tensor::full_on(any_mask.shape(), T::from_f64(1.0), backend);
let inv_mask = crate::binary::sub(&one, &any_mask, backend);
let true_part = crate::binary::mul(on_true, &any_mask, backend);
let false_part = crate::binary::mul(on_false, &inv_mask, backend);
Ok(crate::binary::add(&true_part, &false_part, backend))
}