TRIQS/nda 2.0.0
Multi-dimensional array library for C++
Loading...
Searching...
No Matches
algorithms.hpp
Go to the documentation of this file.
1// Copyright (c) 2019--present, The Simons Foundation
2// This file is part of TRIQS/nda and is licensed under the Apache License, Version 2.0.
3// SPDX-License-Identifier: Apache-2.0
4// See LICENSE in the root of this distribution for details.
5
10
11#pragma once
12
13#include "./basic_functions.hpp"
14#include "./concepts.hpp"
15#include "./layout/for_each.hpp"
16#include "./layout/range.hpp"
17#include "./macros.hpp"
18#include "./map.hpp"
20#include "./traits.hpp"
21
22#include <algorithm>
23#include <array>
24#include <cmath>
25#include <concepts>
26#include <cstdlib>
27#include <functional>
28#include <type_traits>
29#include <utility>
30#include <vector>
31
32namespace nda {
33
38
39 // FIXME : CHECK ORDER of the LOOP !
59 template <Array A, typename F, typename R>
60 auto fold(F f, A const &a, R r) {
61 // cast the initial value to the return type of f to avoid narrowing
62 using res_t = std::decay_t<decltype(make_regular(f(r, get_value_t<A>{})))>;
63 auto res = res_t{r};
64 nda::for_each(a.shape(), [&a, &res, &f](auto &&...args) { res = f(res, a(args...)); });
65 return res;
66 }
67
69 template <Array A, typename F>
70 auto fold(F f, A const &a) {
71 return fold(std::move(f), a, get_value_t<A>{});
72 }
73
89 template <Array A>
90 bool any(A const &a) {
91 static_assert(std::is_same_v<get_value_t<A>, bool>, "Error in nda::any: Value type of the array must be bool");
92 return fold([](bool r, auto const &x) -> bool { return r or bool(x); }, a, false);
93 }
94
110 template <Array A>
111 bool all(A const &a) {
112 static_assert(std::is_same_v<get_value_t<A>, bool>, "Error in nda::all: Value type of the array must be bool");
113 return fold([](bool r, auto const &x) -> bool { return r and bool(x); }, a, true);
114 }
115
125 template <Array A>
126 auto max_element(A const &a) {
127 return fold(
128 [](auto const &x, auto const &y) {
129 using std::max;
130 return max(x, y);
131 },
132 a, get_first_element(a));
133 }
134
144 template <Array A>
145 auto min_element(A const &a) {
146 return fold(
147 [](auto const &x, auto const &y) {
148 using std::min;
149 return min(x, y);
150 },
151 a, get_first_element(a));
152 }
153
161 template <Array A, typename Value = get_value_t<A>>
162 auto sum(A const &a)
164 {
165 if constexpr (nda::Scalar<Value>) {
166 return fold(std::plus<>{}, a);
167 } else { // Array<Value>
168 return fold(std::plus<>{}, a, Value::zeros(get_first_element(a).shape()));
169 }
170 }
171
183 template <ArrayOfRank<2> A>
184 auto frobenius_norm(A const &a) {
185 return std::sqrt(sum(abs2(a)));
186 }
187
207 template <Array A, std::integral I, size_t N>
208 requires(get_rank<A> >= N and nda::Scalar<get_value_t<A>>)
209 auto sum(A const &a, std::array<I, N> axes) {
210 // if no axes are specified, return a copy of the input
211 if constexpr (N == 0) {
212 return make_regular(a);
213 } else {
214 // sort axes and check validity
215 std::ranges::sort(axes);
216 EXPECTS(std::ranges::adjacent_find(axes) == axes.end());
217 EXPECTS(axes.front() >= 0 and axes.back() < get_rank<A>);
218
219 constexpr int res_rank = get_rank<A> - static_cast<int>(N);
220
221 if constexpr (res_rank == 0) {
222 return sum(a);
223 } else {
224 // get the result shape and the axes that we keep (are not summed over)
225 std::array<long, res_rank> keep_axes, res_shape;
226 for (int i = 0; auto ax : nda::range(get_rank<A>)) {
227 if (!std::ranges::binary_search(axes, ax)) {
228 keep_axes[i] = ax;
229 res_shape[i++] = a.shape()[ax];
230 }
231 }
232
233 // create the result array initialized to zero
234 auto res = array<get_value_t<A>, res_rank>::zeros(res_shape);
235
236 // loop over all indices of the input array and sum over the specified axes
237 nda::for_each(a.shape(), [&](auto... idxs) {
238 auto idx_arr = std::array{idxs...};
239 std::apply([&](auto... keep) { res(idx_arr[keep]...) += a(idxs...); }, keep_axes);
240 });
241
242 return res;
243 }
244 }
245 }
246
257 template <Array A>
258 requires(get_rank<A> >= 1 and nda::Scalar<get_value_t<A>>)
259 auto sum(A const &a, int axis) {
260 return sum(a, std::array{axis});
261 }
262
270 template <Array A, typename Value = get_value_t<A>>
271 auto product(A const &a)
273 {
274 if constexpr (nda::Scalar<Value>) {
275 return fold(std::multiplies<>{}, a, get_value_t<A>{1});
276 } else { // Array<Value>
277 return fold(std::multiplies<>{}, a, Value::ones(get_first_element(a).shape()));
278 }
279 }
280
290 template <Array A, Array B>
292 [[nodiscard]] constexpr auto hadamard(A &&a, B &&b) {
293 return nda::map([](auto const &x, auto const &y) { return x * y; })(std::forward<A>(a), std::forward<B>(b));
294 }
295
306 template <typename T, typename U, size_t R>
307 [[nodiscard]] constexpr auto hadamard(std::array<T, R> const &a, std::array<U, R> const &b) {
308 return a * b;
309 }
310
320 template <typename T, typename U>
321 [[nodiscard]] constexpr auto hadamard(std::vector<T> const &a, std::vector<U> const &b) {
322 using TU = decltype(std::declval<T>() * std::declval<U>());
323 EXPECTS(a.size() == b.size());
324
325 std::vector<TU> c(a.size());
326 for (auto i : range(c.size())) c[i] = a[i] * b[i];
327 return c;
328 }
329
339 constexpr auto hadamard(nda::Scalar auto a, nda::Scalar auto b) { return a * b; }
340
342
343} // namespace nda
Provides basic functions to create and manipulate arrays and views.
Check if a given type satisfies the array concept.
Definition concepts.hpp:212
Check if a given type is either an arithmetic or complex type.
Definition concepts.hpp:83
Provides concepts for the nda library.
Provides for_each functions for multi-dimensional arrays/views.
auto max_element(A const &a)
Find the maximum element of an array.
auto fold(F f, A const &a, R r)
Perform a fold operation on the given nda::Array object.
auto sum(A const &a)
Sum all the elements of an nda::Array object.
bool any(A const &a)
Does any of the elements of the array evaluate to true?
auto product(A const &a)
Multiply all the elements of an nda::Array object.
auto min_element(A const &a)
Find the minimum element of an array.
constexpr auto hadamard(A &&a, B &&b)
Hadamard product of two nda::Array objects.
bool all(A const &a)
Do all elements of the array evaluate to true?
decltype(auto) make_regular(A &&a)
Make a given object regular.
auto zeros(std::array< Int, Rank > const &shape)
Make an array of the given shape on the given address space and zero-initialize it.
auto min(A &&a, B &&b)
Function min for nda::ArrayOrScalar types (lazy and coefficient-wise for nda::Array types).
auto abs2(A &&a)
Function abs2 for nda::ArrayOrScalar types (lazy and coefficient-wise for nda::Array types).
auto frobenius_norm(A const &a)
Calculate the Frobenius norm of a 2-dimensional array.
auto max(A &&a, B &&b)
Function max for nda::ArrayOrScalar types (lazy and coefficient-wise for nda::Array types).
mapped< F > map(F f)
Create a lazy function call expression on arrays/views.
Definition map.hpp:235
basic_array< ValueType, Rank, Layout, 'A', ContainerPolicy > array
Alias template of an nda::basic_array with an 'A' algebra.
decltype(auto) get_first_element(A &&a)
Get the first element of an array/view or simply return the scalar if a scalar is given.
Definition traits.hpp:210
constexpr int get_rank
Constexpr variable that specifies the rank of an nda::Array or of a contiguous 1-dimensional range.
Definition traits.hpp:159
std::decay_t< decltype(get_first_element(std::declval< A const >()))> get_value_t
Get the value type of an array/view or a scalar type.
Definition traits.hpp:225
__inline__ void for_each(std::array< Int, R > const &shape, F &&f)
Loop over all possible index values of a given shape and apply a function to them.
Definition for_each.hpp:116
Macros used in the nda library.
Provides lazy function calls on arrays/views.
Provides some custom implementations of standard mathematical functions used for lazy,...
Includes the itertools header and provides some additional utilities.
Provides type traits for the nda library.