TRIQS/nda 1.3.0
Multi-dimensional array library for C++
Loading...
Searching...
No Matches
slice_static.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 "./range.hpp"
14#include "../macros.hpp"
15#include "../stdutil/array.hpp"
16#include "../traits.hpp"
17
18#include <array>
19#include <cstdint>
20#include <cstddef>
21#include <tuple>
22#include <type_traits>
23#include <utility>
24
25#ifdef NDA_ENFORCE_BOUNDCHECK
27#endif
28
29namespace nda {
30
32 // Forward declarations.
33 template <int Rank, uint64_t StaticExtents, uint64_t StrideOrder, layout_prop_e LayoutProp>
34 class idx_map;
36
37} // namespace nda
38
39namespace nda::slice_static {
40
45
46 // Notations for this file
47 //
48 // N: rank of the original idx_map
49 // P: rank of the resulting idx_map
50 // Q: number of arguments given when creating the slice
51 //
52 // n: 0, ..., N - 1: indexes the dimensions of the original idx_map
53 // p: 0, ..., P - 1: indexes the dimensions of the resulting idx_map
54 // q: 0, ..., Q - 1: indexes the arguments
55 //
56 // p are the indices of the non-long arguments (after ellipsis expansion)
57 //
58 // N - Q + e is the length of the ellipsis, i.e. the number of the dimensions covered by the
59 // ellipsis, where e = +1 if there is an ellipsis and e = 0 otherwise.
60 //
61 // Let's assume the original idx_map is of rank N = 6 and the following slice arguments are given:
62 //
63 // Given args = long, long , ellipsis, long, range
64 // q 0 1 2 3 4
65 //
66 // Here the position of the ellipsis is 2 and its length is N - Q + 1 = 6 - 5 + 1 = 2.
67 // After expanding the ellipsis, the arguments are:
68 //
69 // Expanded args = long, long, range::all, range::all, long, range
70 // q 0 1 2 2 3 4
71 // n 0 1 2 3 4 5
72 // p - - 0 1 - 2
73 //
74 // Now we can define the following (compile-time) maps:
75 //
76 // - q(n): n -> q
77 // - n(p): p -> n
78 // - q(p): p -> q
79
80 namespace detail {
81
82 // Helper function to get the position of an nda::ellipsis object in a given parameter pack.
83 template <typename... Args, size_t... Is>
84 constexpr int ellipsis_position_impl(std::index_sequence<Is...>) {
85 // we know that there is at most one ellipsis
86 int r = ((std::is_same_v<Args, ellipsis> ? int(Is) + 1 : 0) + ...);
87 return (r == 0 ? 128 : r - 1);
88 }
89
90 // Get the position of an nda::ellipsis object in a given parameter pack (returns 128 if there is no nda::ellipsis).
91 template <typename... Args>
92 constexpr int ellipsis_position() {
93 return detail::ellipsis_position_impl<Args...>(std::make_index_sequence<sizeof...(Args)>{});
94 }
95
96 // Map the original dimension n to the argument index q after ellipsis expansion.
97 constexpr int q_of_n(int n, int e_pos, int e_len) {
98 // n appears before the ellipsis or no ellipsis is present
99 if (n < e_pos) return n;
100
101 // n is covered by the ellipsis
102 if (n < (e_pos + e_len)) return e_pos;
103
104 // n appears after the ellipsis
105 return n - (e_len - 1);
106 }
107
108 // Determine how the dimensions of the sliced index map are mapped to the dimensions of the original index map.
109 template <int N, int P, size_t Q>
110 constexpr std::array<int, P> n_of_p_map(std::array<bool, Q> const &args_is_range, int e_pos, int e_len) {
111 auto result = stdutil::make_initialized_array<P>(0);
112 // loop over all dimensions of the original index map
113 for (int n = 0, p = 0; n < N; ++n) {
114 // for each dimension n, determine the corresponding argument index q after ellipsis expansion
115 int q = q_of_n(n, e_pos, e_len);
116 // if q is a range, map the current p to the current n and increment p
117 if (args_is_range[q]) result[p++] = n;
118 }
119 return result;
120 }
121
122 // Determine how the dimensions of the sliced index map are mapped to the arguments after ellipsis expansion.
123 template <int N, int P, size_t Q>
124 constexpr std::array<int, P> q_of_p_map(std::array<bool, Q> const &args_is_range, int e_pos, int e_len) {
125 auto result = stdutil::make_initialized_array<P>(0);
126 // loop over all dimensions of the original index map
127 int p = 0;
128 for (int n = 0; n < N; ++n) {
129 // for each dimension n, determine the corresponding argument index q after ellipsis expansion
130 int q = q_of_n(n, e_pos, e_len);
131 // if q is a range, map the current p to the current q and increment p
132 if (args_is_range[q]) result[p++] = q;
133 }
134 return result;
135 }
136
137 // Determine the pseudo inverse map p(n): n -> p. If an n has no corresponding p, the value is -1.
138 template <size_t N, size_t P>
139 constexpr std::array<int, N> p_of_n_map(std::array<int, P> const &n_of_p) {
140 auto result = stdutil::make_initialized_array<N>(-1);
141 for (size_t p = 0; p < P; ++p) result[n_of_p[p]] = p;
142 return result;
143 }
144
145 // Determine the stride order of the sliced index map.
146 template <size_t P, size_t N>
147 constexpr std::array<int, P> slice_stride_order(std::array<int, N> const &orig_stride_order, std::array<int, P> const &n_of_p) {
148 auto result = stdutil::make_initialized_array<P>(0);
149 auto p_of_n = p_of_n_map<N>(n_of_p);
150 for (int i = 0, ip = 0; i < N; ++i) {
151 // n traverses the original stride order, slowest first
152 int n = orig_stride_order[i];
153 // get the corresponding dimension in the sliced index map
154 int p = p_of_n[n];
155 // if n maps to a p, add p to the stride order of the sliced index map
156 if (p != -1) result[ip++] = p;
157 }
158 return result;
159 }
160
161 // Determine the compile-time layout properties of the sliced index map.
162 template <size_t Q, size_t N>
163 constexpr layout_prop_e slice_layout_prop(int P, bool has_only_rangeall_and_long, std::array<bool, Q> const &args_is_rangeall,
164 std::array<int, N> const &orig_stride_order, layout_prop_e orig_layout_prop, int e_pos, int e_len) {
165 // if there are ranges in the arguments
166 if (not has_only_rangeall_and_long) {
167 if (P == 1)
168 // rank one is always at least strided_1d
169 return layout_prop_e::strided_1d;
170 else
171 // otherwise we don't know
172 return layout_prop_e::none;
173 }
174
175 // count the number of nda::range::all_t blocks in the argument list, e.g. long, range::all, range::all, long,
176 // range::all -> 2 blocks
177 int n_rangeall_blocks = 0;
178 bool previous_arg_is_rangeall = false;
179 for (int i = 0; i < N; ++i) {
180 int q = q_of_n(orig_stride_order[i], e_pos, e_len);
181 bool arg_is_rangeall = args_is_rangeall[q];
182 if (arg_is_rangeall and (not previous_arg_is_rangeall)) ++n_rangeall_blocks;
183 previous_arg_is_rangeall = arg_is_rangeall;
184 }
185 bool rangeall_are_grouped_in_memory = (n_rangeall_blocks <= 1);
186 bool last_is_rangeall = previous_arg_is_rangeall;
187
188 // return the proper layout_prop_e
189 if (has_contiguous(orig_layout_prop) and rangeall_are_grouped_in_memory and last_is_rangeall) return layout_prop_e::contiguous;
190 if (has_strided_1d(orig_layout_prop) and rangeall_are_grouped_in_memory) return layout_prop_e::strided_1d;
191 if (has_smallest_stride_is_one(orig_layout_prop) and last_is_rangeall) return layout_prop_e::smallest_stride_is_one;
192
193 return layout_prop_e::none;
194 }
195
196 // Get the contribution to the flat index of the first element of the slice from a single dimension if the argument
197 // is a long.
198 FORCEINLINE long get_offset(long idx, long stride) { return idx * stride; }
199
200 // Get the contribution to the flat index of the first element of the slice from a single dimension if the argument
201 // is a range.
202 FORCEINLINE long get_offset(range const &rg, long stride) { return rg.first() * stride; }
203
204 // Get the contribution to the flat index of the first element of the slice from a single dimension if the argument
205 // is a range::all_t or covered by an nda::ellipsis.
206 FORCEINLINE long get_offset(range::all_t, long) { return 0; }
207
208 // Get the length of the slice for a single dimension if the argument is a range.
209 FORCEINLINE long get_length(range const &rg, long original_len) {
210 auto last = (rg.last() == -1 and rg.step() > 0) ? original_len : rg.last();
211 return range(rg.first(), last, rg.step()).size();
212 }
213
214 // Get the length of the slice for a single dimension if the argument is a range::all_t or covered by an
215 // nda::ellipsis.
216 FORCEINLINE long get_length(range::all_t, long original_len) { return original_len; }
217
218 // Get the stride of the slice for a single dimension if the argument is a range.
219 FORCEINLINE long get_stride(range const &rg, long original_str) { return original_str * rg.step(); }
220
221 // Get the stride of the slice for a single dimension if the argument is a range::all_t or covered by an
222 // nda::ellipsis..
223 FORCEINLINE long get_stride(range::all_t, long original_str) { return original_str; }
224
225 // Helper function to determine the resulting index map when taking a slice of a given index map.
226 template <size_t... Ps, size_t... Ns, typename IdxMap, typename... Args>
227 FORCEINLINE auto slice_idx_map_impl(std::index_sequence<Ps...>, std::index_sequence<Ns...>, IdxMap const &idxm, Args const &...args) {
228 // optional bounds check
229#ifdef NDA_ENFORCE_BOUNDCHECK
230 nda::assert_in_bounds(idxm.rank(), idxm.lengths().data(), args...);
231#endif
232 // compile time check
233 static_assert(IdxMap::rank() == sizeof...(Ns), "Internal error in slice_idx_map_impl: Rank and length of index sequence do not match");
234
235 // rank of original and resulting idx_map, number of arguments, length of ellipsis, position of ellipsis in the
236 // argument list
237 static constexpr int N = sizeof...(Ns);
238 static constexpr int P = sizeof...(Ps);
239 static constexpr int Q = sizeof...(Args);
240 static constexpr int e_len = N - Q + 1;
241 static constexpr int e_pos = ellipsis_position<Args...>();
242
243 // is i-th argument a range/range::all_t/ellipsis?
244 static constexpr std::array<bool, Q> args_is_range{(std::is_same_v<Args, range> or std::is_base_of_v<range::all_t, Args>)...};
245
246 // is i-th argument a range::all_t/ellipsis?
247 static constexpr std::array<bool, Q> args_is_rangeall{(std::is_base_of_v<range::all_t, Args>)...};
248
249 // mapping between the dimensions of the resulting index map and the dimensions of the original index map
250 static constexpr std::array<int, P> n_of_p = n_of_p_map<N, P>(args_is_range, e_pos, e_len);
251
252 // mapping between the dimensions of the resulting index map and the given arguments
253 static constexpr std::array<int, P> q_of_p = q_of_p_map<N, P>(args_is_range, e_pos, e_len);
254
255 // more compile time checks
256 static_assert(n_of_p.size() == P, "Internal error in slice_idx_map_impl: Size of the mapping n_of_p and P do not match");
257 static_assert(q_of_p.size() == P, "Internal error in slice_idx_map_impl: Size of the mapping q_of_p and P do not match");
258
259 // create tuple of arguments
260 auto argstie = std::tie(args...);
261
262 // flat index of the first element of the slice
263 long offset = (get_offset(std::get<q_of_n(Ns, e_pos, e_len)>(argstie), std::get<Ns>(idxm.strides())) + ... + 0);
264
265 // shape and strides of the resulting index map
266 std::array<long, P> len{get_length(std::get<q_of_p[Ps]>(argstie), std::get<n_of_p[Ps]>(idxm.lengths()))...};
267 std::array<long, P> str{get_stride(std::get<q_of_p[Ps]>(argstie), std::get<n_of_p[Ps]>(idxm.strides()))...};
268
269 // static extents of the resulting index map: 0 (= dynamic extent) if the corresponding argument is not a
270 // range/range::all_t/ellipsis
271 static constexpr std::array<int, P> new_static_extents{(args_is_rangeall[q_of_p[Ps]] ? IdxMap::static_extents[n_of_p[Ps]] : 0)...};
272
273 // stride order of the resulting index map
274 static constexpr std::array<int, P> new_stride_order = slice_stride_order(IdxMap::stride_order, n_of_p);
275
276 // compile-time layout properties of the resulting index map
277 static constexpr bool has_only_rangeall_and_long = ((std::is_constructible_v<long, Args> or std::is_base_of_v<range::all_t, Args>)and...);
278 static constexpr layout_prop_e li =
279 slice_layout_prop(P, has_only_rangeall_and_long, args_is_rangeall, IdxMap::stride_order, IdxMap::layout_prop, e_pos, e_len);
280
281 // return the resulting index map
282 static constexpr uint64_t new_static_extents_encoded = encode(new_static_extents);
283 static constexpr uint64_t new_stride_order_encoded = encode(new_stride_order);
284 return std::make_pair(offset, idx_map<P, new_static_extents_encoded, new_stride_order_encoded, li>{len, str});
285 }
286
287 } // namespace detail
288
313 template <int R, uint64_t SE, uint64_t SO, layout_prop_e LP, typename... Args>
314 FORCEINLINE decltype(auto) slice_idx_map(idx_map<R, SE, SO, LP> const &idxm, Args const &...args) {
315 // number of ellipsis and long arguments
316 static constexpr int n_args_ellipsis = ((std::is_same_v<Args, ellipsis>)+...);
317 static constexpr int n_args_long = (std::is_constructible_v<long, Args> + ...);
318
319 // compile time checks
320 static_assert(n_args_ellipsis <= 1, "Error in nda::slice_static::slice_idx_map: At most one ellipsis argument is allowed");
321 static_assert((sizeof...(Args) <= R + 1), "Error in nda::slice_static::slice_idx_map: Incorrect number of arguments");
322 static_assert((n_args_ellipsis == 1) or (sizeof...(Args) == R), "Error in nda::slice_static::slice_idx_map: Incorrect number of arguments");
323
324 return detail::slice_idx_map_impl(std::make_index_sequence<R - n_args_long>{}, std::make_index_sequence<R>{}, idxm, args...);
325 }
326
328
329} // namespace nda::slice_static
Provides utility functions for std::array.
Provides a way to check the bounds when accessing elements/slices of an array or a view.
Layout that specifies how to map multi-dimensional indices to a linear/flat index.
Definition idx_map.hpp:90
__inline__ decltype(auto) slice_idx_map(idx_map< R, SE, SO, LP > const &idxm, Args const &...args)
Determine the resulting nda::idx_map when taking a slice of a given nda::idx_map.
constexpr bool has_contiguous(layout_prop_e lp)
Checks if a layout property has the contiguous property.
Definition traits.hpp:271
constexpr bool has_strided_1d(layout_prop_e lp)
Checks if a layout property has the strided_1d property.
Definition traits.hpp:255
void assert_in_bounds(int rank, long const *lengths, Args const &...args)
Check if the given indices/arguments are within the bounds of an array/view.
constexpr bool has_smallest_stride_is_one(layout_prop_e lp)
Checks if a layout property has the smallest_stride_is_one property.
Definition traits.hpp:263
layout_prop_e
Compile-time guarantees of the memory layout of an array/view.
Definition traits.hpp:211
constexpr uint64_t encode(std::array< int, N > const &a)
Encode a std::array<int, N> in a uint64_t.
constexpr std::array< T, R > make_initialized_array(T v)
Create a new std::array object initialized with a specific value.
Definition array.hpp:155
Macros used in the nda library.
Includes the itertools header and provides some additional utilities.
Provides type traits for the nda library.