Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions benchmarks/broadcast_small_inv.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#include "./bench_common.hpp"

template <int N, long dim>
static void inv(benchmark::State &state) {
nda::array<double, 3> W(dim, N, N), Wi(dim, N, N);
for (int k = 0; k < dim; ++k) {
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j) W(k, i, j) = (i > j ? 0.5 + i + 2.5 * j : i * 0.8 - j - 0.5);
}

while (state.KeepRunning()) {
Wi = inverse(W);
}
}

BENCHMARK_TEMPLATE(inv, 1, 100);
BENCHMARK_TEMPLATE(inv, 1, 10000);
BENCHMARK_TEMPLATE(inv, 1, 1000000);
BENCHMARK_TEMPLATE(inv, 2, 100);
BENCHMARK_TEMPLATE(inv, 2, 10000);
BENCHMARK_TEMPLATE(inv, 2, 1000000);
BENCHMARK_TEMPLATE(inv, 3, 100);
BENCHMARK_TEMPLATE(inv, 3, 10000);
BENCHMARK_TEMPLATE(inv, 3, 1000000);
8 changes: 8 additions & 0 deletions c++/nda/linalg/det_and_inverse.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,14 @@ namespace nda {
return r;
}

template <Array A>
auto inverse(A const &a) {
auto r = make_regular(a);
auto long_axis = stdutil::mpop<2>(r.indexmap().lengths());
for_each(long_axis, [&r, _ = range()](auto &&... i) {inverse_in_place(make_matrix_view(r(i..., _, _))); });
return r;
}

} // namespace nda

namespace nda::clef {
Expand Down
24 changes: 24 additions & 0 deletions test/c++/nda_linear_algebra.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,30 @@ TEST(Inverse, Small) { //NOLINT

// ==============================================================

TEST(Inverse, BroadcastInverse) { //NOLINT

for (auto N : {1, 2, 3, 4}) {

long dim = 100000;
nda::array<double, 3> W(dim, N, N);

for (int k = 0; k < dim; ++k) {
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j) W(k, i, j) = (i > j ? 0.5 + i + 2.5 * j : i * 0.8 - j - 0.5);
}

auto Wi = inverse(W);
auto Wii = inverse(Wi);
for ( int k = 0; k < dim; ++k) {
EXPECT_NEAR(determinant(make_matrix_view(Wi(k, range(), range()))), 1.0/determinant(make_matrix_view(W(k, range(), range()))), 1.e-12);
EXPECT_ARRAY_NEAR(make_matrix_view(W(k,range(),range())) * make_matrix_view(Wi(k, range(), range())), nda::eye<double>(N), 1.e-13);
EXPECT_ARRAY_NEAR(make_matrix_view(Wii(k,range(),range())), make_matrix_view(W(k, range(), range())), 1.e-12);
}
}
}

// ==============================================================

TEST(Matvecmul, Promotion) { //NOLINT

matrix<int> Ai = {{1, 2}, {3, 4}};
Expand Down