mptensor v0.6.0
Parallel Library for Tensor Network Methods
Loading...
Searching...
No Matches
index.hpp
Go to the documentation of this file.
1/*
2 mptensor - Parallel Library for Tensor Network Methods
3
4 Copyright 2016 Satoshi Morita
5
6 mptensor is free software: you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation, either version 3 of the
9 License, or (at your option) any later version.
10
11 mptensor is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with mptensor. If not, see
18 <https://www.gnu.org/licenses/>.
19*/
20
29#ifndef _INDEX_HPP_
30#define _INDEX_HPP_
31
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <initializer_list>
36#include <iostream>
37#include <limits>
38#include <sstream>
39#include <stdexcept>
40#include <string>
41#include <type_traits>
42#include <utility>
43#include <vector>
44
45namespace mptensor {
46
48
53namespace internal {
56template <typename I, bool = std::is_enum_v<I>>
57struct is_unscoped_enum : std::false_type {};
58template <typename I>
60 : std::bool_constant<std::is_convertible_v<I, std::underlying_type_t<I>>> {};
61
64template <typename I>
65inline constexpr bool is_index_value_v =
66 std::is_integral_v<I> || is_unscoped_enum<I>::value;
67
70template <typename T, typename I>
72 static_assert(is_index_value_v<I>, "index values must be integers");
73 if constexpr (std::is_enum_v<I>) {
74 return checked_index_cast<T>(static_cast<std::underlying_type_t<I>>(value));
75 } else {
76 bool fits = true;
77 if constexpr (std::is_signed_v<I> && std::is_unsigned_v<T>) {
78 fits = (value >= 0);
79 } else if constexpr (std::is_unsigned_v<I> && std::is_signed_v<T>) {
81 std::numeric_limits<T>::max()));
82 }
83 if (!fits) {
84 std::ostringstream ss;
85 ss << "mptensor: index value " << +value << " is out of range for "
86 << (std::is_signed_v<T> ? "a signed" : "an unsigned") << " index";
87 throw std::out_of_range(ss.str());
88 }
89 return static_cast<T>(value);
90 }
91}
92} // namespace internal
93
96
101template <typename T>
103 public:
104 using value_type = T;
105 using index_t = std::vector<T>;
106
107 private:
108 // Declared before the public members: Doxygen 1.9.8 otherwise applies the
109 // trailing private access to entities in a later namespace block.
110 index_t idx;
111
112 public:
113
114 BasicIndex() = default;
115 BasicIndex(const index_t& index) : idx(index) {}
117 template <typename U,
118 typename = std::enable_if_t<internal::is_index_value_v<U> &&
119 !std::is_same_v<U, T>>>
120 BasicIndex(const std::vector<U>& index) {
121 idx.reserve(index.size());
122 for (const U& v : index) idx.push_back(internal::checked_index_cast<T>(v));
123 }
124 BasicIndex(std::initializer_list<T> list) : idx(list) {}
125
127
128 template <typename... Ints,
129 typename = std::enable_if_t<(sizeof...(Ints) > 0) &&
130 (internal::is_index_value_v<Ints> && ...)>>
131 BasicIndex(Ints... js) : idx{internal::checked_index_cast<T>(js)...} {}
132
133 const T& operator[](size_t i) const { return idx[i]; }
134 T& operator[](size_t i) { return idx[i]; }
135 size_t size() const { return idx.size(); }
136 void push(T i) { idx.push_back(i); }
137 void resize(size_t n) { idx.resize(n); }
138 void assign(size_t n, const T j[]) { idx.assign(j, j + n); }
139 void sort() { std::sort(idx.begin(), idx.end()); }
140
142
150 const size_t n = size();
152 inv.resize(n);
153 std::vector<bool> seen(n, false);
154 for (size_t i = 0; i < n; ++i) {
155 if (idx[i] < 0 || static_cast<size_t>(idx[i]) >= n) {
156 std::ostringstream ss;
157 ss << "mptensor: inverse_permutation() of " << *this << ": element "
158 << +idx[i]
159 << " at position " << i << " is out of range [0, " << n << ")";
160 throw std::out_of_range(ss.str());
161 }
162 const size_t j = static_cast<size_t>(idx[i]);
163 if (seen[j]) {
164 std::ostringstream ss;
165 ss << "mptensor: inverse_permutation() of " << *this << ": " << +idx[i]
166 << " appears more than once, so it is not a permutation";
167 throw std::invalid_argument(ss.str());
168 }
169 seen[j] = true;
170 inv[j] = static_cast<T>(i);
171 }
172 return inv;
173 }
174
176
177 [[deprecated("use inverse_permutation()")]] BasicIndex inverse() const {
178 return inverse_permutation();
179 }
180
181 bool operator==(const BasicIndex& rhs) const { return idx == rhs.idx; }
182
184 idx.insert(idx.end(), rhs.idx.begin(), rhs.idx.end());
185 return *this;
186 }
187};
188
190
191template <typename T>
192std::ostream& operator<<(std::ostream& os, const BasicIndex<T>& idx) {
193 os << "[";
194 if (idx.size() > 0) os << idx[0];
195 for (size_t i = 1; i < idx.size(); ++i) os << ", " << idx[i];
196 os << "]";
197 return os;
198}
199
202template <typename T>
206
212using Axes = Index;
215using Shape = Index;
216
217
218namespace internal {
224using UAxes = UIndex;
228
231
241inline size_t normalize_value(std::ptrdiff_t v, size_t n, bool end_inclusive,
242 const char* kind, std::ptrdiff_t position,
243 const char* position_name = "position") {
244 const std::ptrdiff_t sn = static_cast<std::ptrdiff_t>(n);
245 const bool ok = end_inclusive ? (v >= -sn && v <= sn) : (v >= -sn && v < sn);
246 if (!ok) {
247 std::ostringstream ss;
248 ss << "mptensor: " << kind << " " << v;
249 if (position >= 0) ss << " (" << position_name << " " << position << ")";
250 ss << " is out of range [" << -sn << ", " << sn
251 << (end_inclusive ? "]" : ")");
252 throw std::out_of_range(ss.str());
253 }
254 return static_cast<size_t>(v < 0 ? v + sn : v);
255}
256
259inline UAxes identity_axes(size_t n) {
260 UAxes axes;
261 axes.resize(n);
262 for (size_t i = 0; i < n; ++i) axes[i] = i;
263 return axes;
264}
265
268
269inline std::pair<size_t, size_t> normalize_slice_range(std::ptrdiff_t begin,
270 std::ptrdiff_t end,
271 size_t n, size_t axis) {
272 const std::ptrdiff_t pos = static_cast<std::ptrdiff_t>(axis);
273 const size_t b = normalize_value(begin, n, false, "slice begin", pos, "axis");
274 const size_t e = normalize_value(end, n, true, "slice end", pos, "axis");
275 if (b >= e) {
276 std::ostringstream ss;
277 ss << "mptensor: slice [" << begin << ", " << end << ") on axis " << axis
278 << " is empty (normalized to [" << b << ", " << e << "))";
279 throw std::out_of_range(ss.str());
280 }
281 return {b, e};
282}
283
286inline void normalize_slice_ranges(const Index& begin, const Index& end,
287 const UShape& shape, UIndex& ubegin,
288 UIndex& uend) {
289 const size_t rank = shape.size();
290 if (begin.size() != rank || end.size() != rank) {
291 std::ostringstream ss;
292 ss << "mptensor: slice bounds " << begin << " and " << end
293 << " do not match the tensor rank " << rank;
294 throw std::invalid_argument(ss.str());
295 }
296 ubegin.resize(rank);
297 uend.resize(rank);
298 for (size_t r = 0; r < rank; ++r) {
299 if (begin[r] == end[r]) {
300 // Full axis, but the bound itself must still be in [-n, n].
301 normalize_value(begin[r], shape[r], true, "slice bound",
302 static_cast<std::ptrdiff_t>(r), "axis");
303 ubegin[r] = 0;
304 uend[r] = shape[r];
305 } else {
306 const std::pair<size_t, size_t> be =
307 normalize_slice_range(begin[r], end[r], shape[r], r);
308 ubegin[r] = be.first;
309 uend[r] = be.second;
310 }
311 }
312}
313} // namespace internal
314
317inline size_t normalize_axis(std::ptrdiff_t a, size_t rank) {
318 return internal::normalize_value(a, rank, false, "axis", -1);
319}
320
323inline internal::UAxes normalize_axes(const Axes& axes, size_t rank) {
324 internal::UAxes result;
325 result.resize(axes.size());
326 for (size_t i = 0; i < axes.size(); ++i) {
327 result[i] = internal::normalize_value(axes[i], rank, false, "axis",
328 static_cast<std::ptrdiff_t>(i));
329 }
330 return result;
331}
332
335inline size_t normalize_index(std::ptrdiff_t i, size_t n) {
336 return internal::normalize_value(i, n, false, "index", -1);
337}
338
342 const internal::UShape& shape) {
343 if (idx.size() != shape.size()) {
344 std::ostringstream ss;
345 ss << "mptensor: index " << idx << " has " << idx.size()
346 << " elements, but the tensor has rank " << shape.size();
347 throw std::invalid_argument(ss.str());
348 }
349 internal::UIndex result;
350 result.resize(idx.size());
351 for (size_t k = 0; k < idx.size(); ++k) {
352 result[k] = internal::normalize_value(idx[k], shape[k], false, "index",
353 static_cast<std::ptrdiff_t>(k));
354 }
355 return result;
356}
357
360inline size_t normalize_slice_end(std::ptrdiff_t e, size_t n) {
361 return internal::normalize_value(e, n, true, "slice end", -1);
362}
363
367 internal::UShape result;
368 result.resize(s.size());
369 for (size_t k = 0; k < s.size(); ++k) {
370 if (s[k] < 0) {
371 std::ostringstream ss;
372 ss << "mptensor: shape " << s << " has a negative size at position " << k;
373 throw std::invalid_argument(ss.str());
374 }
375 result[k] = static_cast<size_t>(s[k]);
376 }
377 return result;
378}
379
383 Index result;
384 result.resize(u.size());
385 for (size_t k = 0; k < u.size(); ++k) {
386 result[k] = internal::checked_index_cast<std::ptrdiff_t>(u[k]);
387 }
388 return result;
389}
390
392
399
401inline Index range(const std::ptrdiff_t start, const std::ptrdiff_t stop,
402 const std::ptrdiff_t step) {
403 if (step == 0) {
404 throw std::invalid_argument("mptensor: range() step must not be zero");
405 }
406 // Number of elements, computed in unsigned arithmetic to avoid overflow.
407 size_t n = 0;
408 if (step > 0 && start < stop) {
409 const size_t diff = static_cast<size_t>(stop) - static_cast<size_t>(start);
410 n = (diff - 1) / static_cast<size_t>(step) + 1;
411 } else if (step < 0 && start > stop) {
412 const size_t diff = static_cast<size_t>(start) - static_cast<size_t>(stop);
413 const size_t ustep = size_t(0) - static_cast<size_t>(step);
414 n = (diff - 1) / ustep + 1;
415 }
416 Index index;
417 index.resize(n);
418 std::ptrdiff_t v = start;
419 for (size_t i = 0; i < n; ++i) {
420 index[i] = v;
421 if (i + 1 < n) v += step;
422 }
423 return index;
424}
425
428inline Index range(const std::ptrdiff_t start, const std::ptrdiff_t stop) {
429 return range(start, stop, 1);
430}
431
434inline Index range(const std::ptrdiff_t stop) { return range(0, stop, 1); }
435
436} // namespace mptensor
437
438#endif // _INDEX_HPP_
Definition index.hpp:102
BasicIndex & operator+=(const BasicIndex &rhs)
Definition index.hpp:183
BasicIndex inverse_permutation() const
Inverse of a permutation: inv[(*this)[i]] = i.
Definition index.hpp:149
BasicIndex inverse() const
Same as inverse_permutation().
Definition index.hpp:177
const T & operator[](size_t i) const
Definition index.hpp:133
BasicIndex(const std::vector< U > &index)
Converting constructor from a vector of another integer type.
Definition index.hpp:120
void resize(size_t n)
Definition index.hpp:137
BasicIndex(std::initializer_list< T > list)
Definition index.hpp:124
bool operator==(const BasicIndex &rhs) const
Definition index.hpp:181
void push(T i)
Definition index.hpp:136
T value_type
Definition index.hpp:104
BasicIndex(Ints... js)
Python-like list literal, e.g. Index(0, 1, -1).
Definition index.hpp:131
std::vector< T > index_t
Definition index.hpp:105
T & operator[](size_t i)
Definition index.hpp:134
void sort()
Definition index.hpp:139
BasicIndex(const index_t &index)
Definition index.hpp:115
void assign(size_t n, const T j[])
Definition index.hpp:138
size_t size() const
Definition index.hpp:135
std::complex< double > complex
Definition complex.hpp:38
internal::UShape to_internal_shape(const Shape &s)
Definition index.hpp:366
Index to_public(const internal::UIndex &u)
Definition index.hpp:382
Index range(const std::ptrdiff_t start, const std::ptrdiff_t stop, const std::ptrdiff_t step)
Arithmetic sequence start, start+step, ... up to (not including) stop.
Definition index.hpp:401
std::ostream & operator<<(std::ostream &os, const BasicIndex< T > &idx)
Definition index.hpp:192
internal::UAxes normalize_axes(const Axes &axes, size_t rank)
Definition index.hpp:323
size_t normalize_index(std::ptrdiff_t i, size_t n)
Definition index.hpp:335
size_t normalize_axis(std::ptrdiff_t a, size_t rank)
Definition index.hpp:317
size_t normalize_slice_end(std::ptrdiff_t e, size_t n)
Definition index.hpp:360
BasicIndex< T > operator+(const BasicIndex< T > &lhs, const BasicIndex< T > &rhs)
Definition index.hpp:203
BasicIndex< std::ptrdiff_t > Index
Definition index.hpp:209
size_t normalize_value(std::ptrdiff_t v, size_t n, bool end_inclusive, const char *kind, std::ptrdiff_t position, const char *position_name="position")
Definition index.hpp:241
void normalize_slice_ranges(const Index &begin, const Index &end, const UShape &shape, UIndex &ubegin, UIndex &uend)
Definition index.hpp:286
T checked_index_cast(I value)
Definition index.hpp:71
std::pair< size_t, size_t > normalize_slice_range(std::ptrdiff_t begin, std::ptrdiff_t end, size_t n, size_t axis)
Definition index.hpp:269
constexpr bool is_index_value_v
Definition index.hpp:65
BasicIndex< std::size_t > UIndex
Definition index.hpp:221
UAxes identity_axes(size_t n)
Definition index.hpp:259
Definition complex.hpp:34