big.hh 30 KB

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