big.hh 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. // -*- mode: c++; coding: utf-8 -*-
  2. // ra-ra - Arrays with dynamic lengths/strides, cf small.hh.
  3. // (c) Daniel Llorens - 2013-2023
  4. // This library is free software; you can redistribute it and/or modify it under
  5. // the terms of the GNU Lesser General Public License as published by the Free
  6. // Software Foundation; either version 3 of the License, or (at your option) any
  7. // later version.
  8. #pragma once
  9. #include "small.hh"
  10. #include <memory>
  11. #include <complex> // for view ops
  12. namespace ra {
  13. // --------------------
  14. // nested braces for Container initializers, cf small_args in small.hh. FIXME Let any expr = braces.
  15. // --------------------
  16. template <class T, rank_t rank>
  17. struct braces_def { using type = noarg; };
  18. template <class T, rank_t rank>
  19. using braces = braces_def<T, rank>::type;
  20. template <class T, rank_t rank> requires (rank==1)
  21. struct braces_def<T, rank> { using type = std::initializer_list<T>; };
  22. template <class T, rank_t rank> requires (rank>1)
  23. struct braces_def<T, rank> { using type = std::initializer_list<braces<T, rank-1>>; };
  24. template <int i, class T, rank_t rank>
  25. constexpr dim_t
  26. braces_len(braces<T, rank> const & l)
  27. {
  28. if constexpr (i>=rank) {
  29. return 0;
  30. } else if constexpr (i==0) {
  31. return l.size();
  32. } else {
  33. return braces_len<i-1, T, rank-1>(*(l.begin()));
  34. }
  35. }
  36. template <class T, rank_t rank, class S = std::array<dim_t, rank>>
  37. constexpr S
  38. braces_shape(braces<T, rank> const & l)
  39. {
  40. return std::apply([&l](auto ... i) { return S { braces_len<i.value, T, rank>(l) ... }; }, mp::iota<rank> {});
  41. }
  42. // --------------------
  43. // ViewBig
  44. // --------------------
  45. // FIXME size is immutable so that it can be kept together with rank.
  46. // TODO Parameterize on Child having .data() so that there's only one pointer.
  47. // TODO Parameterize on iterator type not on value type.
  48. // TODO Constructor checks (nonnegative lens, steps inside, etc.).
  49. template <class T, rank_t RANK>
  50. struct ViewBig
  51. {
  52. using Dimv = std::conditional_t<ANY==RANK, vector_default_init<Dim>, Small<Dim, ANY==RANK ? 0 : RANK>>;
  53. Dimv dimv;
  54. T * cp;
  55. consteval static rank_t rank() requires (RANK!=ANY) { return RANK; }
  56. constexpr rank_t rank() const requires (RANK==ANY) { return rank_t(dimv.size()); }
  57. constexpr static dim_t len_s(int k) { return ANY; }
  58. constexpr dim_t len(int k) const { return dimv[k].len; }
  59. constexpr dim_t step(int k) const { return dimv[k].step; }
  60. constexpr auto data() const { return cp; }
  61. constexpr dim_t size() const { return prod(map(&Dim::len, dimv)); }
  62. constexpr bool empty() const { return any(0==map(&Dim::len, dimv)); }
  63. constexpr ViewBig(): cp() {} // FIXME used by Container constructors
  64. constexpr ViewBig(Dimv const & dimv_, T * cp_): dimv(dimv_), cp(cp_) {} // [ra36]
  65. constexpr ViewBig(auto && s, T * cp_): cp(cp_)
  66. {
  67. ra::resize(dimv, ra::size(s)); // [ra37]
  68. if constexpr (std::is_convertible_v<value_t<decltype(s)>, Dim>) {
  69. start(dimv) = s;
  70. } else {
  71. filldim(dimv, s);
  72. }
  73. }
  74. constexpr ViewBig(std::initializer_list<dim_t> s, T * cp_): ViewBig(start(s), cp_) {}
  75. // cf RA_ASSIGNOPS_SELF [ra38] [ra34]
  76. ViewBig const & operator=(ViewBig && x) const { start(*this) = x; return *this; }
  77. ViewBig const & operator=(ViewBig const & x) const { start(*this) = x; return *this; }
  78. constexpr ViewBig(ViewBig &&) = default;
  79. constexpr ViewBig(ViewBig const &) = default;
  80. #define ASSIGNOPS(OP) \
  81. ViewBig const & operator OP (auto && x) const { start(*this) OP x; return *this; }
  82. FOR_EACH(ASSIGNOPS, =, *=, +=, -=, /=)
  83. #undef ASSIGNOPS
  84. // braces row-major ravel for rank!=1. See Container::fill1
  85. using ravel_arg = std::conditional_t<RANK==1, noarg, std::initializer_list<T>>;
  86. ViewBig const & operator=(ravel_arg const x) const
  87. {
  88. auto xsize = ssize(x);
  89. RA_CHECK(size()==xsize, "Mismatched sizes ", ViewBig::size(), " ", xsize, ".");
  90. std::ranges::copy_n(x.begin(), xsize, begin());
  91. return *this;
  92. }
  93. constexpr ViewBig const & operator=(braces<T, RANK> x) const requires (RANK!=ANY) { ra::iter<-1>(*this) = x; return *this; }
  94. #define RA_BRACES_ANY(N) \
  95. constexpr ViewBig const & operator=(braces<T, N> x) const requires (RANK==ANY) { ra::iter<-1>(*this) = x; return *this; }
  96. FOR_EACH(RA_BRACES_ANY, 2, 3, 4);
  97. #undef RA_BRACES_ANY
  98. template <rank_t c=0> constexpr auto iter() const && { return Cell<T, Dimv, ic_t<c>>(cp, std::move(dimv)); }
  99. template <rank_t c=0> constexpr auto iter() const & { return Cell<T, Dimv const &, ic_t<c>>(cp, dimv); }
  100. constexpr auto iter(rank_t c) const && { return Cell<T, Dimv, dim_t>(cp, std::move(dimv), c); }
  101. constexpr auto iter(rank_t c) const & { return Cell<T, Dimv const &, dim_t>(cp, dimv, c); }
  102. constexpr auto begin() const { return STLIterator(iter<0>()); }
  103. constexpr decltype(auto) static end() { return std::default_sentinel; }
  104. constexpr dim_t
  105. select(Dim * dim, int k, dim_t i) const
  106. {
  107. RA_CHECK(inside(i, len(k)), "Bad index in len[", k, "]=", len(k), ": ", i, ".");
  108. return step(k)*i;
  109. }
  110. constexpr dim_t
  111. select(Dim * dim, int k, is_iota auto i) const
  112. {
  113. RA_CHECK(inside(i, len(k)), "Bad index in len[", k, "]=", len(k), ": iota [", i.n, " ", i.i, " ", i.s, "].");
  114. *dim = { .len = i.n, .step = step(k) * i.s };
  115. return 0==i.n ? 0 : step(k)*i.i;
  116. }
  117. template <class I0, class ... I>
  118. constexpr dim_t
  119. select_loop(Dim * dim, int k, I0 && i0, I && ... i) const
  120. {
  121. return select(dim, k, with_len(len(k), RA_FWD(i0)))
  122. + select_loop(dim + beatable<I0>.dst, k + beatable<I0>.src, RA_FWD(i) ...);
  123. }
  124. template <int n, class ... I>
  125. constexpr dim_t
  126. select_loop(Dim * dim, int k, dots_t<n> i0, I && ... i) const
  127. {
  128. int nn = (BAD==n) ? (rank() - k - (0 + ... + beatable<I>.src)) : n;
  129. for (Dim * end = dim+nn; dim!=end; ++dim, ++k) {
  130. *dim = dimv[k];
  131. }
  132. return select_loop(dim, k, RA_FWD(i) ...);
  133. }
  134. template <int n, class ... I>
  135. constexpr dim_t
  136. select_loop(Dim * dim, int k, insert_t<n> i0, I && ... i) const
  137. {
  138. for (Dim * end = dim+n; dim!=end; ++dim) {
  139. *dim = { .len = BAD, .step = 0 };
  140. }
  141. return select_loop(dim, k, RA_FWD(i) ...);
  142. }
  143. constexpr static dim_t
  144. select_loop(Dim * dim, int k) { return 0; }
  145. template <class ... I>
  146. constexpr decltype(auto)
  147. operator()(I && ... i) const
  148. {
  149. constexpr int stretch = (0 + ... + (beatable<I>.dst==BAD));
  150. static_assert(stretch<=1, "Cannot repeat stretch index.");
  151. if constexpr ((0 + ... + is_scalar_index<I>)==RANK) {
  152. return cp[select_loop(nullptr, 0, i ...)];
  153. } else if constexpr ((beatable<I>.rt && ...)) {
  154. constexpr rank_t extended = (0 + ... + beatable<I>.add);
  155. ViewBig<T, rank_sum(RANK, extended)> sub;
  156. rank_t subrank = rank()+extended;
  157. if constexpr (RANK==ANY) {
  158. RA_CHECK(subrank>=0, "Bad rank.");
  159. sub.dimv.resize(subrank);
  160. }
  161. sub.cp = cp + select_loop(sub.dimv.data(), 0, i ...);
  162. // fill the rest of dim, skipping over beatable subscripts.
  163. for (int k = (0==stretch ? (0 + ... + beatable<I>.dst) : subrank); k<subrank; ++k) {
  164. sub.dimv[k] = dimv[k-extended];
  165. }
  166. return sub;
  167. // TODO partial beating. FIXME should forward this; see unbeat, ViewSmall::operator()
  168. } else {
  169. return unbeat<sizeof...(I)>::op(*this, RA_FWD(i) ...);
  170. }
  171. }
  172. constexpr decltype(auto)
  173. operator[](auto && ... i) const { return (*this)(RA_FWD(i) ...); }
  174. template <class I>
  175. constexpr decltype(auto)
  176. at(I && i) const
  177. {
  178. // can't say 'frame rank 0' so -size wouldn't work. What about ra::len
  179. constexpr rank_t crank = rank_diff(RANK, ra::size_s<I>());
  180. if constexpr (ANY==crank) {
  181. return iter(rank()-ra::size(i)).at(RA_FWD(i));
  182. } else {
  183. return iter<crank>().at(RA_FWD(i));
  184. }
  185. }
  186. constexpr
  187. operator T & () const
  188. {
  189. if constexpr (0!=RANK) {
  190. RA_CHECK(1==size(), "Bad conversion to scalar from shape [", ra::noshape, ra::shape(this), "].");
  191. }
  192. return cp[0];
  193. }
  194. // FIXME necessary per [ra15], conflict with converting constructor? maybe gcc14 https://wg21.link/cwg976
  195. constexpr operator T & () { return std::as_const(*this); }
  196. // conversions from var rank to fixed rank
  197. template <rank_t R> requires (R==ANY && R!=RANK)
  198. constexpr ViewBig(ViewBig<T, R> const & x): dimv(x.dimv), cp(x.cp) {}
  199. template <rank_t R> requires (R==ANY && R!=RANK && std::is_const_v<T>)
  200. constexpr ViewBig(ViewBig<std::remove_const_t<T>, R> const & x): dimv(x.dimv), cp(x.cp) {}
  201. // conversion from fixed rank to var rank
  202. template <rank_t R> requires (R!=ANY && RANK==ANY)
  203. constexpr ViewBig(ViewBig<T, R> const & x): dimv(x.dimv.begin(), x.dimv.end()), cp(x.cp) {}
  204. template <rank_t R> requires (R!=ANY && RANK==ANY && std::is_const_v<T>)
  205. constexpr ViewBig(ViewBig<std::remove_const_t<T>, R> const & x): dimv(x.dimv.begin(), x.dimv.end()), cp(x.cp) {}
  206. // conversion to const. We rely on it for Container::view(). FIXME iffy? not constexpr, and doesn't work for Small.
  207. constexpr
  208. operator ViewBig<T const, RANK> const & () const requires (!std::is_const_v<T>)
  209. {
  210. return *reinterpret_cast<ViewBig<T const, RANK> const *>(this);
  211. }
  212. };
  213. // --------------------
  214. // Container types
  215. // --------------------
  216. template <class V>
  217. struct storage_traits
  218. {
  219. using T = V::value_type;
  220. static_assert(!std::is_same_v<std::remove_const_t<T>, bool>, "No pointers to bool in std::vector<bool>.");
  221. constexpr static auto create(dim_t n) { RA_CHECK(n>=0); return V(n); }
  222. template <class VV> constexpr static auto data(VV & v) { return v.data(); }
  223. };
  224. template <class P>
  225. struct storage_traits<std::unique_ptr<P>>
  226. {
  227. using V = std::unique_ptr<P>;
  228. using T = std::decay_t<decltype(*std::declval<V>().get())>;
  229. constexpr static auto create(dim_t n) { RA_CHECK(n>=0); return V(new T[n]); }
  230. template <class VV> constexpr static auto data(VV & v) { return v.get(); }
  231. };
  232. template <class P>
  233. struct storage_traits<std::shared_ptr<P>>
  234. {
  235. using V = std::shared_ptr<P>;
  236. using T = std::decay_t<decltype(*std::declval<V>().get())>;
  237. constexpr static auto create(dim_t n) { RA_CHECK(n>=0); return V(new T[n], std::default_delete<T[]>()); }
  238. template <class VV> constexpr static auto data(VV & v) { return v.get(); }
  239. };
  240. // FIXME avoid duplicating ViewBig::p. Avoid overhead with rank 1.
  241. template <class Store, rank_t RANK>
  242. struct Container: public ViewBig<typename storage_traits<Store>::T, RANK>
  243. {
  244. Store store;
  245. using T = typename storage_traits<Store>::T;
  246. using View = ra::ViewBig<T, RANK>;
  247. using ViewConst = ra::ViewBig<T const, RANK>;
  248. using View::size, View::rank;
  249. using shape_arg = decltype(shape(std::declval<View>().iter()));
  250. constexpr ViewConst const & view() const { return static_cast<View const &>(*this); }
  251. constexpr View & view() { return *this; }
  252. // Needed to set View::cp. FIXME Remove duplication as in SmallBase/SmallArray.
  253. Container(Container && w): store(std::move(w.store))
  254. {
  255. View::dimv = std::move(w.dimv);
  256. View::cp = storage_traits<Store>::data(store);
  257. }
  258. Container(Container const & w): store(w.store)
  259. {
  260. View::dimv = w.dimv;
  261. View::cp = storage_traits<Store>::data(store);
  262. }
  263. Container(Container & w): Container(std::as_const(w)) {}
  264. // A(shape 2 3) = A-type [1 2 3] initializes, so it doesn't behave as A(shape 2 3) = not-A-type [1 2 3] which uses View::operator=. This is used by operator>>(std::istream &, Container &). See test/ownership.cc [ra20].
  265. // TODO don't require copyable T in constructors, see fill1. That requires operator= to initialize, not update.
  266. Container & operator=(Container && w)
  267. {
  268. store = std::move(w.store);
  269. View::dimv = std::move(w.dimv);
  270. View::cp = storage_traits<Store>::data(store);
  271. return *this;
  272. }
  273. Container & operator=(Container const & w)
  274. {
  275. store = w.store;
  276. View::dimv = w.dimv;
  277. View::cp = storage_traits<Store>::data(store);
  278. return *this;
  279. }
  280. Container & operator=(Container & w) { return *this = std::as_const(w); }
  281. // const/nonconst shims over View's methods. FIXME > gcc13 ? __cpp_explicit_this_parameter
  282. #define RA_CONST_OR_NOT(CONST) \
  283. constexpr T CONST & back() CONST { RA_CHECK(1==rank() && size()>0); return store[size()-1]; } \
  284. constexpr auto data() CONST { return view().data(); } \
  285. constexpr decltype(auto) operator()(auto && ... a) CONST { return view()(RA_FWD(a) ...); } \
  286. constexpr decltype(auto) operator[](auto && ... a) CONST { return view()(RA_FWD(a) ...); } \
  287. constexpr decltype(auto) at(auto && i) CONST { return view().at(RA_FWD(i)); } \
  288. /* always compact/row-major, so STL-like iterators can be raw pointers. */ \
  289. constexpr auto begin() CONST { assert(is_c_order(view())); return view().data(); } \
  290. constexpr auto end() CONST { return view().data()+size(); } \
  291. template <rank_t c=0> constexpr auto iter() CONST { if constexpr (1==RANK && 0==c) { return ptr(data(), size()); } else { return view().template iter<c>(); } } \
  292. constexpr operator T CONST & () CONST { return view(); }
  293. FOR_EACH(RA_CONST_OR_NOT, /*not const*/, const)
  294. #undef RA_CONST_OR_NOT
  295. // non-copy assignment operators follow View, but cannot be just using'd because of constness.
  296. #define ASSIGNOPS(OP) \
  297. Container & operator OP (auto && x) { view() OP x; return *this; }
  298. FOR_EACH(ASSIGNOPS, =, *=, +=, -=, /=)
  299. #undef ASSIGNOPS
  300. using ravel_arg = std::conditional_t<RANK==1, noarg, std::initializer_list<T>>;
  301. Container & operator=(ravel_arg const x) { view() = x; return *this; }
  302. constexpr Container & operator=(braces<T, RANK> x) requires (RANK!=ANY) { view() = x; return *this; }
  303. #define RA_BRACES_ANY(N) \
  304. constexpr Container & operator=(braces<T, N> x) requires (RANK==ANY) { view() = x; return *this; }
  305. FOR_EACH(RA_BRACES_ANY, 2, 3, 4);
  306. #undef RA_BRACES_ANY
  307. template <class S> requires (1==rank_s<S>() || ANY==rank_s<S>())
  308. void
  309. init(S && s)
  310. {
  311. static_assert(!std::is_convertible_v<value_t<S>, Dim>);
  312. RA_CHECK(1==ra::rank(s), "Rank mismatch for init shape.");
  313. static_assert(ANY==RANK || ANY==size_s<S>() || RANK==size_s<S>() || BAD==size_s<S>(), "Bad shape for rank.");
  314. ra::resize(View::dimv, ra::size(s)); // [ra37]
  315. store = storage_traits<Store>::create(filldim(View::dimv, s));
  316. View::cp = storage_traits<Store>::data(store);
  317. }
  318. void init(dim_t s) { init(std::array {s}); } // scalar allowed as shape if rank is 1.
  319. // provided so that {} calls shape_arg constructor below.
  320. Container() requires (ANY==RANK): View({ Dim {0, 1} }, nullptr) {}
  321. Container() requires (ANY!=RANK && 0!=RANK): View(typename View::Dimv(Dim {0, 1}), nullptr) {}
  322. Container() requires (0==RANK): Container({}, none) {}
  323. // shape_arg overloads handle {...} arguments. Size check is at conversion (if shape_arg is Small) or init().
  324. Container(shape_arg const & s, none_t) { init(s); }
  325. Container(shape_arg const & s, auto && x): Container(s, none) { iter() = x; }
  326. Container(shape_arg const & s, braces<T, RANK> x) requires (RANK==1) : Container(s, none) { view() = x; }
  327. Container(auto && x): Container(ra::shape(x), none) { iter() = x; }
  328. Container(braces<T, RANK> x) requires (RANK!=ANY)
  329. : Container(braces_shape<T, RANK>(x), none) { view() = x; }
  330. #define RA_BRACES_ANY(N) \
  331. Container(braces<T, N> x) requires (RANK==ANY) \
  332. : Container(braces_shape<T, N>(x), none) { view() = x; }
  333. FOR_EACH(RA_BRACES_ANY, 1, 2, 3, 4)
  334. #undef RA_BRACES_ANY
  335. // FIXME requires T to be copiable, which conflicts with the semantics of view_.operator=. store(x) avoids it for Big, but doesn't work for Unique. Should construct in place like std::vector does.
  336. constexpr void
  337. fill1(auto && xbegin, dim_t xsize)
  338. {
  339. RA_CHECK(size()==xsize, "Mismatched sizes ", size(), " ", xsize, ".");
  340. std::ranges::copy_n(RA_FWD(xbegin), xsize, begin());
  341. }
  342. // shape + row-major ravel.
  343. // FIXME explicit it-is-ravel mark. Also iter<n> initializers.
  344. // FIXME regular (no need for fill1) for ANY if rank is 1.
  345. Container(shape_arg const & s, typename View::ravel_arg x)
  346. : Container(s, none) { fill1(x.begin(), x.size()); }
  347. // FIXME remove
  348. Container(shape_arg const & s, auto * p)
  349. : Container(s, none) { fill1(p, size()); } // FIXME fake check
  350. // FIXME remove
  351. Container(shape_arg const & s, auto && pbegin, dim_t psize)
  352. : Container(s, none) { fill1(RA_FWD(pbegin), psize); }
  353. // for shape arguments that doesn't convert implicitly to shape_arg
  354. Container(auto && s, none_t)
  355. { init(RA_FWD(s)); }
  356. Container(auto && s, auto && x)
  357. : Container(RA_FWD(s), none) { iter() = x; }
  358. Container(auto && s, std::initializer_list<T> x)
  359. : Container(RA_FWD(s), none) { fill1(x.begin(), x.size()); }
  360. // resize first axis or full shape. Only for some kinds of store.
  361. void resize(dim_t const s)
  362. {
  363. static_assert(RANK==ANY || RANK>0); RA_CHECK(0<rank());
  364. View::dimv[0].len = s;
  365. store.resize(size());
  366. View::cp = store.data();
  367. }
  368. void resize(dim_t const s, T const & t)
  369. {
  370. static_assert(RANK==ANY || RANK>0); RA_CHECK(0<rank());
  371. View::dimv[0].len = s;
  372. store.resize(size(), t);
  373. View::cp = store.data();
  374. }
  375. template <class S> requires (rank_s<S>() > 0)
  376. void resize(S const & s)
  377. {
  378. ra::resize(View::dimv, start(s).len(0)); // [ra37] FIXME is View constructor
  379. store.resize(filldim(View::dimv, s));
  380. View::cp = store.data();
  381. }
  382. // lets us move. A template + RA_FWD wouldn't work for push_back(brace-enclosed-list).
  383. void push_back(T && t)
  384. {
  385. static_assert(RANK==1 || RANK==ANY); RA_CHECK(1==rank());
  386. store.push_back(std::move(t));
  387. ++View::dimv[0].len;
  388. View::cp = store.data();
  389. }
  390. void push_back(T const & t)
  391. {
  392. static_assert(RANK==1 || RANK==ANY); RA_CHECK(1==rank());
  393. store.push_back(t);
  394. ++View::dimv[0].len;
  395. View::cp = store.data();
  396. }
  397. void emplace_back(auto && ... a)
  398. {
  399. static_assert(RANK==1 || RANK==ANY); RA_CHECK(1==rank());
  400. store.emplace_back(RA_FWD(a) ...);
  401. ++View::dimv[0].len;
  402. View::cp = store.data();
  403. }
  404. void pop_back()
  405. {
  406. static_assert(RANK==1 || RANK==ANY); RA_CHECK(1==rank());
  407. RA_CHECK(View::dimv[0].len>0);
  408. store.pop_back();
  409. --View::dimv[0].len;
  410. }
  411. };
  412. // rely on std::swap; else ambiguous
  413. template <class Store, rank_t RANKA, rank_t RANKB> requires (RANKA!=RANKB)
  414. void
  415. swap(Container<Store, RANKA> & a, Container<Store, RANKB> & b)
  416. {
  417. if constexpr (ANY==RANKA) {
  418. RA_CHECK(rank(a)==rank(b));
  419. decltype(b.dimv) c = a.dimv;
  420. start(a.dimv) = b.dimv;
  421. std::swap(b.dimv, c);
  422. } else if constexpr (ANY==RANKB) {
  423. RA_CHECK(rank(a)==rank(b));
  424. decltype(a.dimv) c = b.dimv;
  425. start(b.dimv) = a.dimv;
  426. std::swap(a.dimv, c);
  427. } else {
  428. static_assert(RANKA==RANKB);
  429. std::swap(a.dimv, b.dimv);
  430. }
  431. std::swap(a.store, b.store);
  432. std::swap(a.cp, b.cp);
  433. }
  434. template <class T, rank_t RANK=ANY> using Big = Container<vector_default_init<T>, RANK>;
  435. template <class T, rank_t RANK=ANY> using Unique = Container<std::unique_ptr<T []>, RANK>;
  436. template <class T, rank_t RANK=ANY> using Shared = Container<std::shared_ptr<T>, RANK>;
  437. // -------------
  438. // Used in Guile wrappers to let parameter either borrow from Guile storage or convert into new array (eg 'f32 into 'f64).
  439. // TODO Can use unique_ptr's deleter for this?
  440. // TODO Shared/Unique should maybe have constructors with unique_ptr/shared_ptr args
  441. // -------------
  442. template <rank_t RANK, class T>
  443. Shared<T, RANK>
  444. shared_borrowing(ViewBig<T, RANK> & raw)
  445. {
  446. Shared<T, RANK> a;
  447. a.dimv = raw.dimv;
  448. a.cp = raw.cp;
  449. a.store = std::shared_ptr<T>(raw.data(), [](T *) {});
  450. return a;
  451. }
  452. // --------------------
  453. // concrete (container) type from expression.
  454. // --------------------
  455. template <class E>
  456. struct concrete_type_def
  457. {
  458. using type = void;
  459. };
  460. template <class E> requires (size_s<E>()==ANY)
  461. struct concrete_type_def<E>
  462. {
  463. using type = Big<ncvalue_t<E>, rank_s<E>()>;
  464. };
  465. template <class E> requires (size_s<E>()!=ANY)
  466. struct concrete_type_def<E>
  467. {
  468. using type = decltype(std::apply([](auto ... i) { return Small<ncvalue_t<E>, E::len_s(i) ...> {}; },
  469. mp::iota<rank_s<E>()> {}));
  470. };
  471. // Scalars are their own concrete_type. Treat unregistered types as scalars.
  472. template <class E>
  473. using concrete_type = std::decay_t<
  474. std::conditional_t<(0==rank_s<E>() && !is_ra<E>) || is_scalar<E>,
  475. std::decay_t<E>,
  476. typename concrete_type_def<std::decay_t<decltype(start(std::declval<E>()))>>::type>>;
  477. template <class E>
  478. constexpr auto
  479. concrete(E && e)
  480. {
  481. // FIXME gcc 11.3 on GH workflows (?)
  482. #pragma GCC diagnostic push
  483. #pragma GCC diagnostic warning "-Wmaybe-uninitialized"
  484. return concrete_type<E>(RA_FWD(e));
  485. #pragma GCC diagnostic pop
  486. }
  487. template <class E>
  488. constexpr auto
  489. with_same_shape(E && e)
  490. {
  491. if constexpr (ANY!=size_s<concrete_type<E>>()) {
  492. return concrete_type<E>();
  493. } else {
  494. return concrete_type<E>(ra::shape(e), none);
  495. }
  496. }
  497. template <class E, class X>
  498. constexpr auto
  499. with_same_shape(E && e, X && x)
  500. {
  501. // FIXME gcc 11.3 on GH workflows (?)
  502. #pragma GCC diagnostic push
  503. #pragma GCC diagnostic warning "-Wmaybe-uninitialized"
  504. if constexpr (ANY!=size_s<concrete_type<E>>()) {
  505. return concrete_type<E>(RA_FWD(x));
  506. } else {
  507. return concrete_type<E>(ra::shape(e), RA_FWD(x));
  508. }
  509. #pragma GCC diagnostic pop
  510. }
  511. template <class E, class S, class X>
  512. constexpr auto
  513. with_shape(S && s, X && x)
  514. {
  515. if constexpr (ANY!=size_s<concrete_type<E>>()) {
  516. return concrete_type<E>(RA_FWD(x));
  517. } else {
  518. return concrete_type<E>(RA_FWD(s), RA_FWD(x));
  519. }
  520. }
  521. template <class E, class S, class X>
  522. constexpr auto
  523. with_shape(std::initializer_list<S> && s, X && x)
  524. {
  525. if constexpr (ANY!=size_s<concrete_type<E>>()) {
  526. return concrete_type<E>(RA_FWD(x));
  527. } else {
  528. return concrete_type<E>(s, RA_FWD(x));
  529. }
  530. }
  531. // --------------------
  532. // ViewBig ops
  533. // --------------------
  534. template <class T, rank_t RANK>
  535. inline ViewBig<T, RANK>
  536. reverse(ViewBig<T, RANK> const & view, int k=0)
  537. {
  538. RA_CHECK(inside(k, view.rank()), "Bad reverse axis ", k, " for view of rank ", view.rank(), ".");
  539. ViewBig<T, RANK> r = view;
  540. if (auto & dim=r.dimv[k]; dim.len!=0) {
  541. r.cp += dim.step*(dim.len-1);
  542. dim.step *= -1;
  543. }
  544. return r;
  545. }
  546. // static transposed axes list, output rank is static.
  547. template <int ... Iarg, class T, rank_t RANK>
  548. inline auto
  549. transpose(ViewBig<T, RANK> const & view)
  550. {
  551. static_assert(RANK==ANY || RANK==sizeof...(Iarg), "Bad output rank.");
  552. RA_CHECK(view.rank()==sizeof...(Iarg), "Bad output rank: ", view.rank(), "should be ", (sizeof...(Iarg)), ".");
  553. constexpr static std::array<dim_t, sizeof...(Iarg)> s = { Iarg ... };
  554. constexpr rank_t dstrank = (0==ra::size(s)) ? 0 : 1 + *std::ranges::max_element(s);
  555. ViewBig<T, dstrank> r;
  556. r.cp = view.data();
  557. transpose_filldim(s, view.dimv, r.dimv);
  558. return r;
  559. }
  560. // dynamic transposed axes list, output rank is dynamic. FIXME only some S are valid here.
  561. template <class T, rank_t RANK, class S>
  562. inline ViewBig<T, ANY>
  563. transpose_(S && s, ViewBig<T, RANK> const & view)
  564. {
  565. RA_CHECK(view.rank()==ra::size(s), "Bad size for transposed axes list.");
  566. rank_t dstrank = (0==ra::size(s)) ? 0 : 1 + *std::ranges::max_element(s);
  567. ViewBig<T, ANY> r { decltype(r.dimv)(dstrank), view.data() };
  568. transpose_filldim(s, view.dimv, r.dimv);
  569. return r;
  570. }
  571. template <class T, rank_t RANK, class S>
  572. inline ViewBig<T, ANY>
  573. transpose(S && s, ViewBig<T, RANK> const & view)
  574. {
  575. return transpose_(RA_FWD(s), view);
  576. }
  577. // Need compile time values and not sizes to deduce the output rank, so initializer_list suffices.
  578. template <class T, rank_t RANK>
  579. inline ViewBig<T, ANY>
  580. transpose(std::initializer_list<ra::rank_t> s, ViewBig<T, RANK> const & view)
  581. {
  582. return transpose_(s, view);
  583. }
  584. template <class T, rank_t RANK>
  585. inline auto
  586. diag(ViewBig<T, RANK> const & view)
  587. {
  588. return transpose<0, 0>(view);
  589. }
  590. template <class T, rank_t RANK>
  591. inline ViewBig<T, 1>
  592. ravel_free(ViewBig<T, RANK> const & a)
  593. {
  594. RA_CHECK(is_c_order(a, false));
  595. int r = a.rank()-1;
  596. for (; r>=0 && a.len(r)==1; --r) {}
  597. ra::dim_t s = r<0 ? 1 : a.step(r);
  598. return ra::ViewBig<T, 1>({{ra::size(a), s}}, a.cp);
  599. }
  600. template <class T, rank_t RANK, class S>
  601. inline auto
  602. reshape_(ViewBig<T, RANK> const & a, S && sb_)
  603. {
  604. auto sb = concrete(RA_FWD(sb_));
  605. // FIXME when we need to copy, accept/return Shared
  606. dim_t la = ra::size(a);
  607. dim_t lb = 1;
  608. for (int i=0; i<ra::size(sb); ++i) {
  609. if (sb[i]==-1) {
  610. dim_t quot = lb;
  611. for (int j=i+1; j<ra::size(sb); ++j) {
  612. quot *= sb[j];
  613. RA_CHECK(quot>0, "Cannot deduce dimensions.");
  614. }
  615. auto pv = la/quot;
  616. RA_CHECK((la%quot==0 && pv>=0), "Bad placeholder.");
  617. sb[i] = pv;
  618. lb = la;
  619. break;
  620. } else {
  621. lb *= sb[i];
  622. }
  623. }
  624. auto sa = shape(a);
  625. // FIXME should be able to reshape Scalar etc.
  626. ViewBig<T, ra::size_s(sb)> b(map([](auto i) { return Dim { BAD, 0 }; }, ra::iota(ra::size(sb))), a.data());
  627. rank_t i = 0;
  628. for (; i<a.rank() && i<b.rank(); ++i) {
  629. if (sa[a.rank()-i-1]!=sb[b.rank()-i-1]) {
  630. RA_CHECK(is_c_order(a, false), "Reshape with copy not implemented.");
  631. RA_CHECK(la>=lb, "Reshape with copy not implemented.");
  632. // FIXME ViewBig(SS const & s, T * p). Cf [ra37].
  633. filldim(b.dimv, sb);
  634. for (int j=0; j!=b.rank(); ++j) {
  635. b.dimv[j].step *= a.step(a.rank()-1);
  636. }
  637. return b;
  638. } else {
  639. // select
  640. b.dimv[b.rank()-i-1] = a.dimv[a.rank()-i-1];
  641. }
  642. }
  643. if (i==a.rank()) {
  644. // tile & return
  645. for (rank_t j=i; j<b.rank(); ++j) {
  646. b.dimv[b.rank()-j-1] = { sb[b.rank()-j-1], 0 };
  647. }
  648. }
  649. return b;
  650. }
  651. template <class T, rank_t RANK, class S>
  652. inline auto
  653. reshape(ViewBig<T, RANK> const & a, S && sb_)
  654. {
  655. return reshape_(a, RA_FWD(sb_));
  656. }
  657. // We need dimtype bc {1, ...} deduces to int and that fails to match ra::dim_t. initializer_list could handle the general case, but the result would have var rank and would override this one (?).
  658. template <class T, rank_t RANK, class dimtype, int N>
  659. inline auto
  660. reshape(ViewBig<T, RANK> const & a, dimtype const (&sb_)[N])
  661. {
  662. return reshape_(a, sb_);
  663. }
  664. // lo: lower bounds, hi: upper bounds. The stencil indices are in [0 lo+1+hi] = [-lo +hi].
  665. template <class LO, class HI, class T, rank_t N>
  666. inline ViewBig<T, rank_sum(N, N)>
  667. stencil(ViewBig<T, N> const & a, LO && lo, HI && hi)
  668. {
  669. ViewBig<T, rank_sum(N, N)> s;
  670. s.cp = a.data();
  671. ra::resize(s.dimv, 2*a.rank());
  672. RA_CHECK(every(lo>=0) && every(hi>=0), "Bad stencil bounds lo ", noshape, lo, " hi ", noshape, hi, ".");
  673. for_each([](auto & dims, auto && dima, auto && lo, auto && hi)
  674. {
  675. RA_CHECK(dima.len>=lo+hi, "Stencil is too large for array.");
  676. dims = {dima.len-lo-hi, dima.step};
  677. },
  678. ptr(s.dimv.data()), a.dimv, lo, hi);
  679. for_each([](auto & dims, auto && dima, auto && lo, auto && hi)
  680. { dims = {lo+hi+1, dima.step}; },
  681. ptr(s.dimv.data()+a.rank()), a.dimv, lo, hi);
  682. return s;
  683. }
  684. // Make last sizes of ViewBig<> be compile-time constants.
  685. template <class super_t, rank_t SUPERR, class T, rank_t RANK>
  686. inline auto
  687. explode_(ViewBig<T, RANK> const & a)
  688. {
  689. // TODO Reduce to single check, either the first or the second.
  690. static_assert(RANK>=SUPERR || RANK==ANY, "rank of a is too low");
  691. RA_CHECK(a.rank()>=SUPERR, "Rank of a ", a.rank(), " should be at least ", SUPERR, ".");
  692. ViewBig<super_t, rank_sum(RANK, -SUPERR)> b;
  693. ra::resize(b.dimv, a.rank()-SUPERR);
  694. dim_t r = 1;
  695. for (int i=0; i<SUPERR; ++i) {
  696. r *= a.len(i+b.rank());
  697. }
  698. RA_CHECK(r*sizeof(T)==sizeof(super_t), "Length of axes ", r*sizeof(T), " doesn't match type ", sizeof(super_t), ".");
  699. for (int i=0; i<b.rank(); ++i) {
  700. RA_CHECK(a.step(i) % r==0, "Step of axes ", a.step(i), " doesn't match type ", r, " on axis ", i, ".");
  701. b.dimv[i] = { .len = a.len(i), .step = a.step(i) / r };
  702. }
  703. RA_CHECK((b.rank()==0 || a.step(b.rank()-1)==r), "Super type is not compact in array.");
  704. b.cp = reinterpret_cast<super_t *>(a.data());
  705. return b;
  706. }
  707. template <class super_t, class T, rank_t RANK>
  708. inline auto
  709. explode(ViewBig<T, RANK> const & a)
  710. {
  711. return explode_<super_t, (std::is_same_v<super_t, std::complex<T>> ? 1 : rank_s<super_t>())>(a);
  712. }
  713. // FIXME Maybe namespace level generics
  714. template <class T> inline int gstep(int i) { if constexpr (is_scalar<T>) return 1; else return T::step(i); }
  715. template <class T> inline int glen(int i) { if constexpr (is_scalar<T>) return 1; else return T::len(i); }
  716. // TODO The ranks below SUBR must be compact, which is not checked.
  717. template <class sub_t, class super_t, rank_t RANK>
  718. inline auto
  719. collapse(ViewBig<super_t, RANK> const & a)
  720. {
  721. using super_v = value_t<super_t>;
  722. using sub_v = value_t<sub_t>;
  723. constexpr int subtype = sizeof(super_v)/sizeof(sub_t);
  724. constexpr int SUBR = rank_s<super_t>() - rank_s<sub_t>();
  725. ViewBig<sub_t, rank_sum(RANK, SUBR+int(subtype>1))> b;
  726. resize(b.dimv, a.rank()+SUBR+int(subtype>1));
  727. constexpr dim_t r = sizeof(super_t)/sizeof(sub_t);
  728. static_assert(sizeof(super_t)==r*sizeof(sub_t), "Cannot make axis of super_t from sub_t.");
  729. for (int i=0; i<a.rank(); ++i) {
  730. b.dimv[i] = { .len = a.len(i), .step = a.step(i) * r };
  731. }
  732. constexpr int t = sizeof(super_v)/sizeof(sub_v);
  733. constexpr int s = sizeof(sub_t)/sizeof(sub_v);
  734. static_assert(t*sizeof(sub_v)>=1, "Bad subtype.");
  735. for (int i=0; i<SUBR; ++i) {
  736. RA_CHECK(((gstep<super_t>(i)/s)*s==gstep<super_t>(i)), "Bad steps."); // TODO actually static
  737. b.dimv[a.rank()+i] = { .len = glen<super_t>(i), .step = gstep<super_t>(i) / s * t };
  738. }
  739. if (subtype>1) {
  740. b.dimv[a.rank()+SUBR] = { .len = t, .step = 1 };
  741. }
  742. b.cp = reinterpret_cast<sub_t *>(a.data());
  743. return b;
  744. }
  745. } // namespace ra