TRIQS/nda 1.3.0
Multi-dimensional array library for C++
Loading...
Searching...
No Matches
basic_array_view.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 "./clef.hpp"
15#include "./concepts.hpp"
16#include "./declarations.hpp"
17#include "./exceptions.hpp"
18#include "./iterators.hpp"
20#include "./layout/for_each.hpp"
21#include "./layout/idx_map.hpp"
23#include "./layout/range.hpp"
24#include "./macros.hpp"
26#include "./mem/memcpy.hpp"
27#include "./mem/memset.hpp"
28#include "./mem/fill.hpp"
29#include "./mem/policies.hpp"
30#include "./traits.hpp"
31
32#include <itertools/itertools.hpp>
33
34#include <algorithm>
35#include <array>
36#include <cstring>
37#include <memory>
38#include <ranges>
39#include <type_traits>
40#include <utility>
41
42#ifdef NDA_ENFORCE_BOUNDCHECK
43#include <exception>
44#include <iostream>
45#endif // NDA_ENFORCE_BOUNDCHECK
46
47namespace std {
48
54 template <typename V1, int R1, typename LP1, char A1, typename AP1, typename OP1, typename V2, int R2, typename LP2, char A2, typename AP2,
55 typename OP2>
57
58} // namespace std
59
60namespace nda {
61
118 template <typename ValueType, int Rank, typename LayoutPolicy, char Algebra, typename AccessorPolicy, typename OwningPolicy>
119 class basic_array_view {
120 // Compile-time checks.
121 static_assert((Algebra != 'N'), "Internal error in nda::basic_array_view: Algebra 'N' not supported");
122 static_assert((Algebra != 'M') or (Rank == 2), "Internal error in nda::basic_array_view: Algebra 'M' requires a rank 2 view");
123 static_assert((Algebra != 'V') or (Rank == 1), "Internal error in nda::basic_array_view: Algebra 'V' requires a rank 1 view");
124
125 public:
127 using value_type = ValueType;
128
130 using layout_policy_t = LayoutPolicy;
131
133 using layout_t = typename LayoutPolicy::template mapping<Rank>;
134
136 using accessor_policy_t = AccessorPolicy;
137
139 using owning_policy_t = OwningPolicy;
140
142 using storage_t = typename OwningPolicy::template handle<ValueType>;
143
145 using regular_type = basic_array<std::remove_const_t<ValueType>, Rank, C_layout, Algebra, heap<mem::get_addr_space<storage_t>>>;
146
148 static constexpr int rank = Rank;
149
150 private:
151 // Type of the view itself.
152 using self_t = basic_array_view;
153
154 // Constexpr variable that is true if the view is a view (always for basic_array_view).
155 static constexpr bool is_view = true;
156
157 // Constexpr variable that is true if the value_type is const.
158 static constexpr bool is_const = std::is_const_v<ValueType>;
159
160 // Memory layout of the view, i.e. the nda::idx_map.
161 layout_t lay;
162
163 // Memory handle of the view.
164 storage_t sto;
165
166 // Declare any nda::basic_array as a friend.
167 template <typename T, int R, typename L, char A, typename CP>
168 friend class basic_array;
169
170 // Declare any other nda::basic_array_view as a friend.
171 template <typename T, int R, typename L, char A, typename AP, typename OP>
172 friend class basic_array_view;
173
174 // Check the layout compatibility of this view with another layout.
175 template <typename L>
176 static constexpr bool requires_runtime_check = not layout_property_compatible(L::template mapping<Rank>::layout_prop, layout_t::layout_prop);
177
178 public:
179 // FIXME : TRIQS PORTING
180 // private constructor for the previous friend
189 basic_array_view(layout_t const &idxm, storage_t st) : lay(idxm), sto(std::move(st)) {}
190
191 public:
192 // backward : FIXME : temporary to be removed
194 [[deprecated]] auto as_array_view() { return basic_array_view<ValueType, Rank, LayoutPolicy, 'A', AccessorPolicy, OwningPolicy>{*this}; };
195
197 [[deprecated]] auto as_array_view() const {
198 return basic_array_view<const ValueType, Rank, LayoutPolicy, 'A', AccessorPolicy, OwningPolicy>{*this};
199 };
200
202 basic_array_view() = default;
203
205 basic_array_view(basic_array_view &&) = default;
206
208 basic_array_view(basic_array_view const &) = default;
209
219 template <MemoryArrayOfRank<Rank> A>
220 requires((get_layout_info<A>.stride_order == layout_t::stride_order_encoded)
221 and (std::is_same_v<std::remove_const_t<ValueType>, get_value_t<A>>)
222 and (std::is_const_v<ValueType> or !std::is_const_v<typename std::decay_t<A>::value_type>))
223 explicit(requires_runtime_check<typename std::decay_t<A>::layout_policy_t>)
224 basic_array_view(A &&a) noexcept // NOLINT (should we forward the reference?)
225 : lay(a.indexmap()), sto(a.storage()) {}
226
236 basic_array_view(std::array<long, Rank> const &shape, ValueType *p) noexcept : basic_array_view(layout_t{shape}, p) {}
237
247 basic_array_view(layout_t const &idxm, ValueType *p) noexcept : lay(idxm), sto{p} {}
248
255 template <size_t N>
256 requires(Rank == 1)
257 explicit basic_array_view(std::array<ValueType, N> &a) noexcept : basic_array_view{{long(N)}, a.data()} {}
258
265 template <size_t N>
266 requires(Rank == 1 and std::is_const_v<ValueType>)
267 explicit basic_array_view(std::array<std::remove_const_t<ValueType>, N> const &a) noexcept : basic_array_view{{long(N)}, a.data()} {}
268
275 template <std::ranges::contiguous_range R>
276 requires(Rank == 1 and not MemoryArray<R>
277 and (std::is_same_v<std::ranges::range_value_t<R>, ValueType> or std::is_same_v<const std::ranges::range_value_t<R>, ValueType>))
278 explicit basic_array_view(R &rg) noexcept : basic_array_view{{long(std::ranges::size(rg))}, std::to_address(std::begin(rg))} {}
279
288 basic_array_view &operator=(basic_array_view const &rhs) noexcept {
289 assign_from_ndarray(rhs);
290 return *this;
291 }
292
302 template <ArrayOfRank<Rank> RHS>
303 basic_array_view &operator=(RHS const &rhs) noexcept {
304 static_assert(!is_const, "Cannot assign to an nda::basic_array_view with const value_type");
305 assign_from_ndarray(rhs);
306 return *this;
307 }
308
319 template <typename RHS>
320 basic_array_view &operator=(RHS const &rhs) noexcept
322 {
323 static_assert(!is_const, "Cannot assign to an nda::basic_array_view with const value_type");
324 assign_from_scalar(rhs);
325 return *this;
326 }
327
336 template <ArrayInitializer<basic_array_view> Initializer>
337 basic_array_view &operator=(Initializer const &initializer) noexcept {
338 EXPECTS(shape() == initializer.shape());
339 initializer.invoke(*this);
340 return *this;
341 }
342
357 template <typename T, int R, typename LP, char A, typename AP, typename OP>
358 void rebind(basic_array_view<T, R, LP, A, AP, OP> v) noexcept {
359 static_assert(R == Rank, "Cannot rebind a view to another view of a different rank");
360 static_assert(std::is_same_v<std::remove_const_t<T>, std::remove_const_t<ValueType>>,
361 "Cannot rebind a view to another view with a different value_type (except for const)");
362 static constexpr bool same_type = std::is_same_v<T, ValueType>;
363 static_assert(same_type or is_const, "Cannot rebind a view with non-const value_type to another view with const value_type");
364 if constexpr (same_type) {
365 // FIXME Error message in layout error !
366 lay = v.lay;
367 sto = v.sto;
368 } else if constexpr (is_const) {
369 // the last if is always trivially true but in case of an error in the static_assert above,
370 // it improves the error message by not compiling the = afterwards
371 lay = layout_t{v.indexmap()};
372 sto = storage_t{v.storage()};
373 }
374 }
375
384 friend void swap(basic_array_view &a, basic_array_view &b) noexcept {
385 std::swap(a.lay, b.lay);
386 std::swap(a.sto, b.sto);
387 }
388
397 friend void deep_swap(basic_array_view a, basic_array_view b) noexcept {
398 auto tmp = make_regular(a);
399 a = b;
400 b = tmp;
401 }
402
403// include common functionality of arrays and views
404// Copyright (c) 2019--present, The Simons Foundation
405// This file is part of TRIQS/nda and is licensed under the Apache License, Version 2.0.
406// SPDX-License-Identifier: Apache-2.0
407// See LICENSE in the root of this distribution for details.
408
413[[nodiscard]] constexpr auto const &indexmap() const noexcept { return lay; }
414
419[[nodiscard]] storage_t const &storage() const & noexcept { return sto; }
420
425[[nodiscard]] storage_t &storage() & noexcept { return sto; }
426
431[[nodiscard]] storage_t storage() && noexcept { return std::move(sto); }
432
439[[nodiscard]] constexpr auto stride_order() const noexcept { return lay.stride_order; }
440
445[[nodiscard]] ValueType const *data() const noexcept { return sto.data(); }
446
451[[nodiscard]] ValueType *data() noexcept { return sto.data(); }
452
457[[nodiscard]] auto const &shape() const noexcept { return lay.lengths(); }
458
463[[nodiscard]] auto const &strides() const noexcept { return lay.strides(); }
464
469[[nodiscard]] long size() const noexcept { return lay.size(); }
470
475[[nodiscard]] long is_contiguous() const noexcept { return lay.is_contiguous(); }
476
481[[nodiscard]] long has_positive_strides() const noexcept { return lay.has_positive_strides(); }
482
487[[nodiscard]] bool empty() const { return sto.is_null(); }
488
490[[nodiscard]] bool is_empty() const noexcept { return sto.is_null(); }
491
496[[nodiscard]] long extent(int i) const noexcept {
497#ifdef NDA_ENFORCE_BOUNDCHECK
498 if (i < 0 || i >= rank) {
499 std::cerr << "Error in extent: Dimension " << i << " is incompatible with array of rank " << rank << std::endl;
500 std::terminate();
501 }
502#endif
503 return lay.lengths()[i];
504}
505
507[[nodiscard]] long shape(int i) const noexcept { return extent(i); }
508
513[[nodiscard]] auto indices() const noexcept { return itertools::product_range(shape()); }
514
519static constexpr bool is_stride_order_C() noexcept { return layout_t::is_stride_order_C(); }
520
525static constexpr bool is_stride_order_Fortran() noexcept { return layout_t::is_stride_order_Fortran(); }
526
536decltype(auto) operator()(_linear_index_t idx) const noexcept {
537 if constexpr (layout_t::layout_prop == layout_prop_e::strided_1d)
538 return sto[idx.value * lay.min_stride()];
539 else if constexpr (layout_t::layout_prop == layout_prop_e::contiguous)
540 return sto[idx.value];
541 else
542 static_assert(always_false<layout_t>, "Internal error in array/view: Calling this type with a _linear_index_t is not allowed");
543}
544
546decltype(auto) operator()(_linear_index_t idx) noexcept {
547 if constexpr (layout_t::layout_prop == layout_prop_e::strided_1d)
548 return sto[idx.value * lay.min_stride()];
549 else if constexpr (layout_t::layout_prop == layout_prop_e::contiguous)
550 return sto[idx.value];
551 else
552 static_assert(always_false<layout_t>, "Internal error in array/view: Calling this type with a _linear_index_t is not allowed");
553}
554
555private:
556// Constexpr variable that is true if bounds checking is disabled.
557#ifdef NDA_ENFORCE_BOUNDCHECK
558static constexpr bool has_no_boundcheck = false;
559#else
560static constexpr bool has_no_boundcheck = true;
561#endif
562
563public:
580template <char ResultAlgebra, bool SelfIsRvalue, typename Self, typename... Ts>
581FORCEINLINE static decltype(auto) call(Self &&self, Ts const &...idxs) noexcept(has_no_boundcheck) {
582 // resulting value type
583 using r_v_t = std::conditional_t<std::is_const_v<std::remove_reference_t<Self>>, ValueType const, ValueType>;
584
585 // behavior depends on the given arguments
586 if constexpr (clef::is_any_lazy<Ts...>) {
587 // if there are lazy arguments, e.g. as in A(i_) << i_, a lazy expression is returned
588 return clef::make_expr_call(std::forward<Self>(self), idxs...);
589 } else if constexpr (sizeof...(Ts) == 0) {
590 // if no arguments are given, a full view is returned
591 return basic_array_view<r_v_t, Rank, LayoutPolicy, Algebra, AccessorPolicy, OwningPolicy>{self.lay, self.sto};
592 } else {
593 // otherwise we check the arguments and either access a single element or make a slice
594 static_assert(((layout_t::template argument_is_allowed_for_call_or_slice<Ts> + ...) > 0),
595 "Error in array/view: Slice arguments must be convertible to range, ellipsis, or long (or string if the layout permits it)");
596
597 // number of arguments convertible to long
598 static constexpr int n_args_long = (layout_t::template argument_is_allowed_for_call<Ts> + ...);
599
600 if constexpr (n_args_long == rank) {
601 // access a single element
602 long offset = self.lay(idxs...);
603 if constexpr (is_view or not SelfIsRvalue) {
604 // if the calling object is a view or an lvalue, we return a reference
605 return AccessorPolicy::template accessor<r_v_t>::access(self.sto.data(), offset);
606 } else {
607 // otherwise, we return a copy of the value
608 return ValueType{self.sto[offset]};
609 }
610 } else {
611 // access a slice of the view/array
612 auto const [offset, idxm] = self.lay.slice(idxs...);
613 static constexpr auto res_rank = decltype(idxm)::rank();
614 // resulting algebra
615 static constexpr char newAlgebra = (ResultAlgebra == 'M' and (res_rank == 1) ? 'V' : ResultAlgebra);
616 // resulting layout policy
617 using r_layout_p = typename detail::layout_to_policy<std::decay_t<decltype(idxm)>>::type;
618 return basic_array_view<r_v_t, res_rank, r_layout_p, newAlgebra, AccessorPolicy, OwningPolicy>{std::move(idxm), {self.sto, offset}};
619 }
620 }
621}
622
623public:
645template <typename... Ts>
646FORCEINLINE decltype(auto) operator()(Ts const &...idxs) const & noexcept(has_no_boundcheck) {
647 static_assert((rank == -1) or (sizeof...(Ts) == rank) or (sizeof...(Ts) == 0) or (ellipsis_is_present<Ts...> and (sizeof...(Ts) <= rank + 1)),
648 "Error in array/view: Incorrect number of parameters in call operator");
649 return call<Algebra, false>(*this, idxs...);
650}
651
653template <typename... Ts>
654FORCEINLINE decltype(auto) operator()(Ts const &...idxs) & noexcept(has_no_boundcheck) {
655 static_assert((rank == -1) or (sizeof...(Ts) == rank) or (sizeof...(Ts) == 0) or (ellipsis_is_present<Ts...> and (sizeof...(Ts) <= rank + 1)),
656 "Error in array/view: Incorrect number of parameters in call operator");
657 return call<Algebra, false>(*this, idxs...);
658}
659
661template <typename... Ts>
662FORCEINLINE decltype(auto) operator()(Ts const &...idxs) && noexcept(has_no_boundcheck) {
663 static_assert((rank == -1) or (sizeof...(Ts) == rank) or (sizeof...(Ts) == 0) or (ellipsis_is_present<Ts...> and (sizeof...(Ts) <= rank + 1)),
664 "Error in array/view: Incorrect number of parameters in call operator");
665 return call<Algebra, true>(*this, idxs...);
666}
667
685template <typename T>
686decltype(auto) operator[](T const &idx) const & noexcept(has_no_boundcheck) {
687 static_assert((rank == 1), "Error in array/view: Subscript operator is only available for rank 1 views/arrays in C++17/20");
688 return call<Algebra, false>(*this, idx);
689}
690
692template <typename T>
693decltype(auto) operator[](T const &x) & noexcept(has_no_boundcheck) {
694 static_assert((rank == 1), "Error in array/view: Subscript operator is only available for rank 1 views/arrays in C++17/20");
695 return call<Algebra, false>(*this, x);
696}
697
699template <typename T>
700decltype(auto) operator[](T const &x) && noexcept(has_no_boundcheck) {
701 static_assert((rank == 1), "Error in array/view: Subscript operator is only available for rank 1 views/arrays in C++17/20");
702 return call<Algebra, true>(*this, x);
703}
704
706static constexpr int iterator_rank = (has_strided_1d(layout_t::layout_prop) ? 1 : Rank);
707
710
713
714private:
715// Make an iterator for the view/array depending on its type.
716template <typename Iterator>
717[[nodiscard]] auto make_iterator(bool at_end) const noexcept {
718 if constexpr (iterator_rank == Rank) {
719 // multi-dimensional iterator
720 if constexpr (layout_t::is_stride_order_C()) {
721 // C-order case (array_iterator already traverses the data in C-order)
722 return Iterator{indexmap().lengths(), indexmap().strides(), sto.data(), at_end};
723 } else {
724 // general case (we need to permute the shape and the strides according to the stride order of the layout)
725 return Iterator{nda::permutations::apply(layout_t::stride_order, indexmap().lengths()),
726 nda::permutations::apply(layout_t::stride_order, indexmap().strides()), sto.data(), at_end};
727 }
728 } else {
729 // 1-dimensional iterator
730 return Iterator{std::array<long, 1>{size()}, std::array<long, 1>{indexmap().min_stride()}, sto.data(), at_end};
731 }
732}
733
734public:
736[[nodiscard]] const_iterator begin() const noexcept { return make_iterator<const_iterator>(false); }
737
739[[nodiscard]] const_iterator cbegin() const noexcept { return make_iterator<const_iterator>(false); }
740
742iterator begin() noexcept { return make_iterator<iterator>(false); }
743
745[[nodiscard]] const_iterator end() const noexcept { return make_iterator<const_iterator>(true); }
746
748[[nodiscard]] const_iterator cend() const noexcept { return make_iterator<const_iterator>(true); }
749
751iterator end() noexcept { return make_iterator<iterator>(true); }
752
765template <typename RHS>
766auto &operator+=(RHS const &rhs) noexcept {
767 static_assert(not is_const, "Error in array/view: Can not assign to a const view");
768 return operator=(*this + rhs);
769}
770
783template <typename RHS>
784auto &operator-=(RHS const &rhs) noexcept {
785 static_assert(not is_const, "Error in array/view: Can not assign to a const view");
786 return operator=(*this - rhs);
787}
788
801template <typename RHS>
802auto &operator*=(RHS const &rhs) noexcept {
803 static_assert(not is_const, "Error in array/view: Can not assign to a const view");
804 return operator=((*this) * rhs);
805}
806
819template <typename RHS>
820auto &operator/=(RHS const &rhs) noexcept {
821 static_assert(not is_const, "Error in array/view: Can not assign to a const view");
822 return operator=(*this / rhs);
823}
824
833template <std::ranges::contiguous_range R>
834auto &operator=(R const &rhs) noexcept
835 requires(Rank == 1 and not MemoryArray<R> and not is_scalar_for_v<R, self_t>)
836{
838 return *this;
839}
840
841private:
842// Implementation of the assignment from an n-dimensional array type.
843template <typename RHS>
844void assign_from_ndarray(RHS const &rhs) { // FIXME noexcept {
845#ifdef NDA_ENFORCE_BOUNDCHECK
846 if (this->shape() != rhs.shape())
847 NDA_RUNTIME_ERROR << "Error in assign_from_ndarray: Size mismatch:"
848 << "\n LHS.shape() = " << this->shape() << "\n RHS.shape() = " << rhs.shape();
849#endif
850 // compile-time check if assignment is possible
851 static_assert(std::is_assignable_v<value_type &, get_value_t<RHS>>, "Error in assign_from_ndarray: Incompatible value types");
852
853 // are both operands nda::MemoryArray types?
854 static constexpr bool both_in_memory = MemoryArray<self_t> and MemoryArray<RHS>;
855
856 // do both operands have the same stride order?
857 static constexpr bool same_stride_order = get_layout_info<self_t>.stride_order == get_layout_info<RHS>.stride_order;
858
859 // prefer optimized options if possible
860 if constexpr (both_in_memory and same_stride_order) {
861 if (rhs.empty()) return;
862 // are both operands strided in 1d?
863 static constexpr bool both_1d_strided = has_layout_strided_1d<self_t> and has_layout_strided_1d<RHS>;
864 if constexpr (mem::on_host<self_t, RHS> and both_1d_strided) {
865 // vectorizable copy on host
866 for (long i = 0; i < size(); ++i) (*this)(_linear_index_t{i}) = rhs(_linear_index_t{i});
867 return;
869 // check for block-layout and use mem::memcpy2D if possible
870 auto bl_layout_dst = get_block_layout(*this);
871 auto bl_layout_src = get_block_layout(rhs);
872 if (bl_layout_dst && bl_layout_src) {
873 auto [n_bl_dst, bl_size_dst, bl_str_dst] = *bl_layout_dst;
874 auto [n_bl_src, bl_size_src, bl_str_src] = *bl_layout_src;
875 // check that the total memory size is the same
876 if (n_bl_dst * bl_size_dst != n_bl_src * bl_size_src) NDA_RUNTIME_ERROR << "Error in assign_from_ndarray: Incompatible block sizes";
877 // if either destination or source consists of a single block, we can chunk it up to make the layouts compatible
878 if (n_bl_dst == 1 && n_bl_src > 1) {
879 n_bl_dst = n_bl_src;
880 bl_size_dst /= n_bl_src;
881 bl_str_dst = bl_size_dst;
882 }
883 if (n_bl_src == 1 && n_bl_dst > 1) {
884 n_bl_src = n_bl_dst;
885 bl_size_src /= n_bl_dst;
886 bl_str_src = bl_size_src;
887 }
888 // copy only if block-layouts are compatible, otherwise continue to fallback
889 if (n_bl_dst == n_bl_src && bl_size_dst == bl_size_src) {
890 mem::memcpy2D<mem::get_addr_space<self_t>, mem::get_addr_space<RHS>>((void *)data(), bl_str_dst * sizeof(value_type), (void *)rhs.data(),
891 bl_str_src * sizeof(value_type), bl_size_src * sizeof(value_type),
892 n_bl_src);
893 return;
894 }
895 }
896 }
897 }
898 // otherwise fallback to elementwise assignment
900 NDA_RUNTIME_ERROR << "Error in assign_from_ndarray: Fallback to elementwise assignment not implemented for arrays/views on the GPU";
901 }
902 nda::for_each(shape(), [this, &rhs](auto const &...args) { (*this)(args...) = rhs(args...); });
903}
904
905// Implementation to fill a view/array with a constant scalar value.
906template <typename Scalar>
907void fill_with_scalar(Scalar const &scalar) noexcept {
908 // we make a special implementation if the array is strided in 1d or contiguous
909 if constexpr (mem::on_host<self_t>) {
910 if constexpr (has_layout_strided_1d<self_t>) {
911 const long L = size();
912 auto *__restrict const p = data(); // no alias possible here!
913 if constexpr (has_contiguous_layout<self_t>) {
914 for (long i = 0; i < L; ++i) p[i] = scalar;
915 } else {
916 const long stri = indexmap().min_stride();
917 const long Lstri = L * stri;
918 for (long i = 0; i != Lstri; i += stri) p[i] = scalar;
919 }
920 } else {
921 for (auto &x : *this) x = scalar;
922 }
923 } else if constexpr (mem::on_device<self_t> or mem::on_unified<self_t>) { // on device
924 if constexpr (has_layout_strided_1d<self_t>) { // possibly contiguous
925 if constexpr (has_contiguous_layout<self_t>) {
926 mem::fill_n<mem::get_addr_space<self_t>>(data(), size(), value_type(scalar));
927 } else {
928 const long stri = indexmap().min_stride();
929 mem::fill2D_n<mem::get_addr_space<self_t>>(data(), stri, 1, size(), value_type(scalar));
930 }
931 } else {
932 // check for 2D layout
933 auto bl_layout = get_block_layout(*this);
934 if (bl_layout) {
935 auto [n_bl, bl_size, bl_str] = *bl_layout;
936 mem::fill2D_n<mem::get_addr_space<self_t>>(data(), bl_str, bl_size, n_bl, value_type(scalar));
937 } else {
938 // MAM: implement recursive call to fill_with_scalar on (i,nda::ellipsis{})
939 NDA_RUNTIME_ERROR << "fill_with_scalar: Not implemented yet for general layout. ";
940 }
941 }
942 }
943}
944
945// Implementation of the assignment from a scalar value.
946template <typename Scalar>
947void assign_from_scalar(Scalar const &scalar) noexcept {
948 static_assert(!is_const, "Error in assign_from_ndarray: Cannot assign to a const view");
949 if constexpr (Algebra != 'M') {
950 // element-wise assignment for non-matrix algebras
951 fill_with_scalar(scalar);
952 } else {
953 // a scalar has to be interpreted as a unit matrix for matrix algebras (the scalar in the shortest diagonal)
954 // FIXME : A priori faster to put 0 everywhere and then change the diag to avoid the if.
955 // FIXME : Benchmark and confirm.
957 fill_with_scalar(0);
958 else
959 fill_with_scalar(Scalar{0 * scalar}); // FIXME : improve this
960 diagonal(*this).fill_with_scalar(scalar);
961 }
962}
963 };
964
965 // Class template argument deduction guides.
966 template <MemoryArray A>
967 basic_array_view(A &&a)
968 -> basic_array_view<std::conditional_t<std::is_const_v<std::remove_reference_t<A>>, const typename std::decay_t<A>::value_type,
969 typename std::decay_t<A>::value_type>,
970 get_rank<A>, typename std::decay_t<A>::layout_policy_t, get_algebra<A>, default_accessor, borrowed<mem::get_addr_space<A>>>;
971
972 template <typename V, size_t R>
973 basic_array_view(std::array<V, R> &a)
974 -> basic_array_view<V, 1, nda::basic_layout<nda::static_extents(R), nda::C_stride_order<1>, nda::layout_prop_e::contiguous>, 'V',
976
977 template <typename V, size_t R>
978 basic_array_view(std::array<V, R> const &a)
979 -> basic_array_view<const V, 1, nda::basic_layout<nda::static_extents(R), nda::C_stride_order<1>, nda::layout_prop_e::contiguous>, 'V',
981
982 template <std::ranges::contiguous_range R>
983 basic_array_view(R &r) -> basic_array_view<std::conditional_t<std::is_const_v<R>, const typename R::value_type, typename R::value_type>, 1,
985
986} // namespace nda
Provides definitions and type traits involving the different memory address spaces supported by nda.
void swap(nda::basic_array_view< V1, R1, LP1, A1, AP1, OP1 > &a, nda::basic_array_view< V2, R2, LP2, A2, AP2, OP2 > &b)=delete
std::swap is deleted for nda::basic_array_view.
Provides basic functions to create and manipulate arrays and views.
Iterator for nda::basic_array and nda::basic_array_view types.
A generic view of a multi-dimensional array.
auto & operator=(R const &rhs) noexcept
Assignment operator makes a deep copy of a general contiguous range and assigns it to the 1-dimension...
const_iterator end() const noexcept
Get a const iterator to the end of the view/array.
ValueType const * data() const noexcept
Get a pointer to the actual data (in general this is not the beginning of the memory block for a view...
static constexpr bool is_stride_order_C() noexcept
Is the stride order of the view/array in C-order?
iterator begin() noexcept
Get an iterator to the beginning of the view/array.
ValueType * data() noexcept
Get a pointer to the actual data (in general this is not the beginning of thr memory block for a view...
basic_array_view & operator=(RHS const &rhs) noexcept
Assignment operator makes a deep copy of the contents of an nda::ArrayOfRank object.
long has_positive_strides() const noexcept
Are all the strides of the memory layout of the view/array positive?
typename OwningPolicy::template handle< ValueType > storage_t
Type of the memory handle (see Handles).
auto & operator/=(RHS const &rhs) noexcept
Division assignment operator.
static __inline__ decltype(auto) call(Self &&self, Ts const &...idxs) noexcept(has_no_boundcheck)
Implementation of the function call operator.
basic_array_view(layout_t const &idxm, ValueType *p) noexcept
Construct a view from a bare pointer to some contiguous data and a memory layout.
basic_array_view(R &rg) noexcept
Construct a 1-dimensional view of a general contiguous range.
basic_array_view & operator=(basic_array_view const &rhs) noexcept
Copy assignment operator makes a deep copy of the contents of the view.
basic_array_view(std::array< ValueType, N > &a) noexcept
Construct a 1-dimensional view of a std::array.
basic_array_view & operator=(Initializer const &initializer) noexcept
Assignment operator uses an nda::ArrayInitializer to assign to the view.
auto const & strides() const noexcept
Get the strides of the view/array (see nda::idx_map for more details on how we define strides).
long shape(int i) const noexcept
storage_t storage() &&noexcept
Get the data storage of the view/array.
typename LayoutPolicy::template mapping< Rank > layout_t
Type of the memory layout (an nda::idx_map).
basic_array< std::remove_const_t< ValueType >, Rank, C_layout, Algebra, heap< mem::get_addr_space< storage_t > > > regular_type
The associated regular (nda::basic_array) type.
array_iterator< iterator_rank, ValueType, typename AccessorPolicy::template accessor< ValueType >::pointer > iterator
Iterator type of the view/array.
auto & operator+=(RHS const &rhs) noexcept
Addition assignment operator.
auto indices() const noexcept
Get a range that generates all valid index tuples.
basic_array_view()=default
Default constructor constructs an empty view with a default constructed memory handle and layout.
long is_contiguous() const noexcept
Is the memory layout of the view/array contiguous?
storage_t & storage() &noexcept
Get the data storage of the view/array.
static constexpr bool is_stride_order_Fortran() noexcept
Is the stride order of the view/array in Fortran-order?
auto & operator*=(RHS const &rhs) noexcept
Multiplication assignment operator.
basic_array_view(std::array< std::remove_const_t< ValueType >, N > const &a) noexcept
Construct a 1-dimensional view of a std::array.
friend void deep_swap(basic_array_view a, basic_array_view b) noexcept
Swap two views by swapping their data.
iterator end() noexcept
Get an iterator to the end of the view/array.
ValueType value_type
Type of the values in the view (might be const).
long size() const noexcept
Get the total size of the view/array.
auto & operator-=(RHS const &rhs) noexcept
Subtraction assignment operator.
bool empty() const
Is the view/array empty?
basic_array_view & operator=(RHS const &rhs) noexcept
Assignment operator assigns a scalar to the view.
basic_array_view(std::array< long, Rank > const &shape, ValueType *p) noexcept
Construct a view from a bare pointer to some contiguous data and a shape.
OwningPolicy owning_policy_t
Type of the owning policy (see Memory policies).
LayoutPolicy layout_policy_t
Type of the memory layout policy (see Layout policies).
array_iterator< iterator_rank, ValueType const, typename AccessorPolicy::template accessor< ValueType >::pointer > const_iterator
Const iterator type of the view/array.
bool is_empty() const noexcept
friend void swap(basic_array_view &a, basic_array_view &b) noexcept
Swap two views by swapping their memory handles and layouts.
constexpr auto stride_order() const noexcept
Get the stride order of the memory layout of the view/array (see nda::idx_map for more details on how...
const_iterator cbegin() const noexcept
Get a const iterator to the beginning of the view/array.
basic_array_view(layout_t const &idxm, storage_t st)
Construct a view from a given layout and memory handle.
AccessorPolicy accessor_policy_t
Type of the accessor policy (see e.g. nda::default_accessor).
basic_array_view(basic_array_view &&)=default
Default move constructor moves the memory handle and layout.
void rebind(basic_array_view< T, R, LP, A, AP, OP > v) noexcept
Rebind the current view to another view.
basic_array_view(basic_array_view const &)=default
Default copy constructor copies the memory handle and layout.
long extent(int i) const noexcept
Get the extent of the ith dimension.
const_iterator begin() const noexcept
Get a const iterator to the beginning of the view/array.
const_iterator cend() const noexcept
Get a const iterator to the end of the view/array.
Includes all clef relevant headers.
Check if a given type satisfies the memory array concept.
Definition concepts.hpp:248
Provides concepts for the nda library.
Provides various convenient aliases and helper functions for nda::basic_array and nda::basic_array_vi...
Provides a custom runtime error class and macros to assert conditions and throw exceptions.
Provides for_each functions for multi-dimensional arrays/views.
decltype(auto) make_regular(A &&a)
Make a given object regular.
ArrayOfRank< 1 > auto diagonal(M &&m)
Get a view of the diagonal of a 2-dimensional array/view.
basic_array_view< ValueType const, Rank, Layout, 'A', default_accessor, borrowed<> > array_const_view
Same as nda::array_view except for const value types.
constexpr char get_algebra
Constexpr variable that specifies the algebra of a type.
Definition traits.hpp:116
constexpr uint64_t static_extents(int i0, Is... is)
Encode the given shape into a single integer using the nda::encode function.
constexpr bool have_same_value_type_v
Constexpr variable that is true if all types in As have the same value type as A0.
Definition traits.hpp:186
constexpr int get_rank
Constexpr variable that specifies the rank of an nda::Array or of a contiguous 1-dimensional range.
Definition traits.hpp:126
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:182
auto make_expr_call(F &&f, Args &&...args)
Create a function call expression from a callable object and a list of arguments.
Definition make_lazy.hpp:63
constexpr bool is_any_lazy
Constexpr variable that is true if any of the given types is lazy.
Definition utils.hpp:145
constexpr uint64_t C_stride_order
C/Row-major stride order.
Definition idx_map.hpp:52
constexpr bool layout_property_compatible(layout_prop_e from, layout_prop_e to)
Checks if two layout properties are compatible with each other.
Definition traits.hpp:227
constexpr bool ellipsis_is_present
Constexpr variable that is true if the parameter pack Args contains an nda::ellipsis.
Definition range.hpp:56
constexpr bool has_strided_1d(layout_prop_e lp)
Checks if a layout property has the strided_1d property.
Definition traits.hpp:256
__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
constexpr bool has_layout_strided_1d
Constexpr variable that is true if type A has the strided_1d nda::layout_prop_e guarantee.
Definition traits.hpp:324
auto get_block_layout(A const &a)
Check if a given nda::MemoryArray has a block-strided layout.
constexpr layout_info_t get_layout_info
Constexpr variable that specifies the nda::layout_info_t of type A.
Definition traits.hpp:311
constexpr bool has_contiguous_layout
Constexpr variable that is true if type A has the contiguous nda::layout_prop_e guarantee.
Definition traits.hpp:320
static constexpr bool on_device
Constexpr variable that is true if all given types have a Device address space.
static constexpr bool on_unified
Constexpr variable that is true if all given types have a Unified address space.
static constexpr AddressSpace get_addr_space
Variable template providing the address space for different types.
static constexpr bool on_host
Constexpr variable that is true if all given types have a Host address space.
heap_basic< mem::mallocator< AdrSp > > heap
Alias template of the nda::heap_basic policy using an nda::mem::mallocator.
Definition policies.hpp:52
void memcpy2D(void *dest, size_t dpitch, const void *src, size_t spitch, size_t width, size_t height)
Call CUDA's cudaMemcpy2D function or simulate its behavior on the Host based on the given address spa...
Definition memcpy.hpp:73
constexpr std::array< T, N > apply(std::array< Int, N > const &p, std::array< T, N > const &a)
Apply a permutation to a std::array.
static constexpr bool always_false
Constexpr variable that is always false regardless of the types in Ts (used to trigger static_assert)...
Definition traits.hpp:61
constexpr bool is_scalar_for_v
Constexpr variable used to check requirements when initializing an nda::basic_array or nda::basic_arr...
Definition traits.hpp:83
constexpr bool is_scalar_or_convertible_v
Constexpr variable that is true if type S is a scalar type (see nda::is_scalar_v) or if a std::comple...
Definition traits.hpp:76
Provides a class that maps multi-dimensional indices to a linear index and vice versa.
Provides an iterator for nda::basic_array and nda::basic_array_view types.
Macros used in the nda library.
Defines various memory handling policies.
Provides a generic memcpy and memcpy2D function for different address spaces.
Provides a generic memset and memset2D function for different address spaces.
Provides utilities to work with permutations and to compactly encode/decode std::array objects.
Includes the itertools header and provides some additional utilities.
Provides utilities that determine the resulting nda::idx_map when taking a slice of an nda::idx_map.
A small wrapper around a single long integer to be used as a linear index.
Definition traits.hpp:333
Contiguous layout policy with C-order (row-major order).
Definition policies.hpp:36
Memory policy using an nda::mem::handle_borrowed.
Definition policies.hpp:97
Default accessor for various array and view types.
Definition accessors.hpp:25
Provides type traits for the nda library.