feat(math): add reshape operation

This commit is contained in:
2026-11-01 20:44:25 +01:00
parent 961067c28d
commit d23905c259
3 changed files with 35 additions and 14 deletions
+6
View File
@@ -44,6 +44,12 @@ struct ops_provider {
if (!ops::transpose::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self() };
}
template <typename S>
unary_expression<CRTP, ops::reshape<S>> reshape() {
if (!ops::reshape<S>::compatible(self())) throw std::runtime_error("tensor shape mismatch");
return { self() };
}
private:
decltype(auto) self() & { return reinterpret_cast<CRTP&>(*this); }
decltype(auto) self() && { return reinterpret_cast<CRTP&&>(*this); }
+26 -12
View File
@@ -146,18 +146,7 @@ struct apply {
template <typename L, typename R>
static constexpr auto shape(const L& lhs, const R& rhs) {
if (!compatible(lhs, rhs)) throw std::runtime_error("uncompatible operands");
using lhs_shape = remove_cvref_t<decltype(lhs.shape())>;
using rhs_shape = remove_cvref_t<decltype(rhs.shape())>;
constexpr std::size_t lhs_rows = lhs_shape::template sget<0>();
constexpr std::size_t rhs_cols = rhs_shape::template sget<1>();
if constexpr (lhs_rows == dynamic_extent || rhs_cols == dynamic_extent) {
return dynamic_shape<lhs_rows, rhs_cols>{};
} else {
return static_shape<lhs_rows, rhs_cols>{};
}
return lhs.shape();
}
template <typename E>
@@ -201,6 +190,31 @@ struct transpose {
}
};
// TODO: introduce dynamic reshape
template <typename S, typename = std::enable_if_t<::cenet::math::detail::is_static_shape_v<S>>>
struct reshape {
template <typename E>
static constexpr bool compatible(const E& expr) {
using shape_type = remove_cvref_t<decltype(expr.shape())>;
if constexpr (!::cenet::math::detail::is_static_shape<shape_type>::value) {
return false;
} else {
return shape_type::size == S::size;
}
}
template <typename E>
static constexpr auto shape(const E& expr) {
if (!compatible(expr)) throw std::runtime_error("uncompatible operands");
return S{};
}
template <typename E>
constexpr auto operator()(std::size_t index, const E& expr) const {
return expr.coeff(index);
}
};
} // namespace ops
} // namespace math
} // namespace cenet
+3 -2
View File
@@ -34,9 +34,10 @@ public:
m_items = nullptr;
m_shape = {};
} else if constexpr (traits::inline_storage) {
std::memset(m_items, 0, sizeof(m_items));
view().fill();
} else {
m_items = new value_type[traits::size];
view().fill();
}
}
@@ -261,7 +262,7 @@ private:
private:
template <std::size_t... Is>
void dyn_alloc(std::index_sequence<Is...>) {
if constexpr (traits::dynamic) {
if constexpr (!traits::inline_storage) {
m_items = new value_type[size()];
}
}