ra-ra.texi 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388
  1. @c -*- mode: texinfo; coding: utf-8 -*-
  2. @c %**start of header
  3. @setfilename ra-ra.info
  4. @documentencoding UTF-8
  5. @settitle ra:: —An array library for C++20
  6. @c %**end of header
  7. @c Keep track of
  8. @c http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0834r0.html
  9. @c http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0573r2.html
  10. @c http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0356r2.html
  11. @c References to source [ma··] or [ma···] current last is 117.
  12. @set VERSION 14
  13. @set UPDATED 2021 February 22
  14. @copying
  15. @code{ra::} (version @value{VERSION}, updated @value{UPDATED})
  16. (c) Daniel Llorens 2005--2020
  17. @smalldisplay
  18. Permission is granted to copy, distribute and/or modify this document
  19. under the terms of the GNU Free Documentation License, Version 1.3 or
  20. any later version published by the Free Software Foundation; with no
  21. Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
  22. @end smalldisplay
  23. @end copying
  24. @dircategory C++ libraries
  25. @direntry
  26. * ra-ra: (ra-ra.info). Expression template and multidimensional array library for C++.
  27. @end direntry
  28. @include my-bib-macros.texi
  29. @mybibuselist{Sources}
  30. @titlepage
  31. @title ra::
  32. @subtitle version @value{VERSION}, updated @value{UPDATED}
  33. @author Daniel Llorens
  34. @page
  35. @vskip 0pt plus 1filll
  36. @insertcopying
  37. @end titlepage
  38. @ifnottex
  39. @node Top
  40. @top @code{ra::}
  41. @insertcopying
  42. @code{ra::}@footnote{/ə'ɹ-eɪ/, I guess.} is a general purpose multidimensional array and expression template library for C++20. Please keep in mind that this manual is a work in progress. There are many errors and whole sections unwritten.
  43. @menu
  44. * Overview:: Array programming and C++.
  45. * Usage:: Everything you can do with @code{ra::}.
  46. * Extras:: Additional libraries provided with @code{ra::}.
  47. * Hazards:: User beware.
  48. * Internals:: For all the world to see.
  49. * The future:: Could be even better.
  50. * Reference:: Systematic list of types and functions.
  51. * @mybibnode{}:: It's been done before.
  52. * Indices:: Or try the search function.
  53. * Notes:: Technically...
  54. @end menu
  55. @end ifnottex
  56. @iftex
  57. @shortcontents
  58. @end iftex
  59. @c ------------------------------------------------
  60. @node Overview
  61. @chapter Overview
  62. @c ------------------------------------------------
  63. A multidimensional array is a container whose elements can be looked up using a multi-index (i₀, i₁, ...). Each of the indices i₀, i₁, ... has a constant range [0, n₀), [0, n₁), ... independent of the values of the other indices, so the array is ‘rectangular’. The number of indices in the multi-index is the @dfn{rank} of the array, and the list (n₀, n₁, ... nᵣ₋₁) is the @dfn{shape} of the array. We speak of a rank-@math{r} array or of an @math{r}-array.
  64. Often we deal with multidimensional @emph{expressions} where the elements aren't stored anywhere, but are computed on demand when the expression is looked up. In this general sense, an ‘array’ is just a function of integers with a rectangular domain.
  65. Arrays (in the form of @dfn{matrices}, @dfn{vectors}, or @dfn{tensors}) are very common objects in math and programming, and it is enormously useful to be able to manipulate arrays as individual entities rather than as aggregates. Not only is
  66. @verbatim
  67. A = B+C;
  68. @end verbatim
  69. much more compact and easier to read than
  70. @verbatim
  71. for (int i=0; i!=m; ++i)
  72. for (int j=0; j!=n; ++j)
  73. for (int k=0; k!=p; ++k)
  74. A(i, j, k) = B(i, j, k)+C(i, j, k);
  75. @end verbatim
  76. but it's also safer and less redundant. For example, the order of the loops may be something you don't really care about.
  77. However, if array operations are implemented naively, a piece of code such as @code{A=B+C} may result in the creation of a temporary to hold @code{B+C} which is then assigned to @code{A}. Needless to say this is very wasteful if the arrays involved are large.
  78. @cindex Blitz++
  79. Fortunately the problem is almost as old as aggregate data types, and other programming languages have addressed it with optimizations such as @url{https://en.wikipedia.org/wiki/Loop_fission_and_fusion, ‘loop fusion’}, ‘drag along’ @mybibcite{Abr70}, or ‘deforestation’ @mybibcite{Wad90}. In the C++ context the technique of ‘expression templates’ was pioneered in the late 90s by libraries such as Blitz++ @mybibcite{bli17}. It works by making @code{B+C} into an ‘expression object’ which holds references to its arguments and performs the sum only when its elements are looked up. The compiler removes the temporary expression objects during optimization, so that @code{A=B+C} results (in principle) in the same generated code as the complicated loop nest above.
  80. @menu
  81. * Rank polymorphism:: What makes arrays special.
  82. * Drag along and beating:: The basic array optimizations.
  83. * Why C++:: High level, low level.
  84. * Guidelines:: How @code{ra::} tries to do things.
  85. * Other libraries:: Inspiration and desperation.
  86. @end menu
  87. @c ------------------------------------------------
  88. @node Rank polymorphism
  89. @section Rank polymorphism
  90. @c ------------------------------------------------
  91. @dfn{Rank polymorphism} is the ability to treat an array of rank @math{r} as an array of lower rank where the elements are themselves arrays.
  92. @cindex cell
  93. @cindex frame
  94. For example, think of a matrix A, a 2-array with sizes (n₀, n₁) where the elements A(i₀, i₁) are numbers. If we consider the subarrays (rows) A(0, ...), A(1, ...), ..., A(n₀-1, ...) as individual elements, then we have a new view of A as a 1-array of size n₀ with those rows as elements. We say that the rows A(i₀)≡A(i₀, ...) are the 1-@dfn{cells} of A, and the numbers A(i₀, i₁) are 0-cells of A. For an array of arbitrary rank @math{r} the (@math{r}-1)-cells of A are called its @dfn{items}. The prefix of the shape (n₀, n₁, ... nₙ₋₁₋ₖ) that is not taken up by the k-cell is called the k-@dfn{frame}.
  95. An obvious way to store an array in linearly addressed memory is to place its items one after another. So we would store a 3-array as
  96. @quotation
  97. A: [A(0), A(1), ...]
  98. @end quotation
  99. and the items of A(i₀), etc. are in turn stored in the same way, so
  100. @quotation
  101. A: [A(0): [A(0, 0), A(0, 1) ...], ...]
  102. @end quotation
  103. and the same for the items of A(i₀, i₁), etc.
  104. @quotation
  105. A: [[A(0, 0): [A(0, 0, 0), A(0, 0, 1) ...], A(0, 1): [A(0, 1, 0), A(0, 1, 1) ...]], ...]
  106. @end quotation
  107. @cindex order, row-major
  108. This way to lay out an array in memory is called @dfn{row-major order} or @dfn{C-order}, since it's the default order for built-in arrays in C (@pxref{Other libraries}). A row-major array A with sizes (n₀, n₁, ... nᵣ₋₁) can be looked up like this:
  109. @anchor{x-strides}
  110. @quotation
  111. A(i₀, i₁, ...) = (storage-of-A) [(((i₀n₁ + i₁)n₂ + i₂)n₃ + ...)+iᵣ₋₁] = (storage-of-A) [o + s₀i₀ + s₁i₁ + ...]
  112. @end quotation
  113. where the numbers (s₀, s₁, ...) are called the @dfn{strides}@footnote{Cf. @url{https://en.wikipedia.org/wiki/Dope_vector, @dfn{dope vector}}}. Note that the ‘linear’ or ‘raveled’ address [o + s₀i₀ + s₁i₁ + ...] is an affine function of (i₀, i₁, ...). If we represent an array as a tuple
  114. @quotation
  115. A ≡ ((storage-of-A), o, (s₀, s₁, ...))
  116. @end quotation
  117. then any affine transformation of the indices can be achieved simply by modifying the numbers (o, (s₀, s₁, ...)), with no need to touch the storage. This includes very common operations such as: @ref{x-transpose,transposing} axes, @ref{x-reverse,reversing} the order along an axis, most cases of @ref{Slicing,slicing}, and sometimes even reshaping or tiling the array.
  118. A basic example is obtaining the i₀-th item of A:
  119. @quotation
  120. A(i₀) ≡ ((storage-of-A), o+s₀i₀, (s₁, ...))
  121. @end quotation
  122. Note that we can iterate over these items by simply bumping the pointer o+s₀i₀. This means that iterating over (k>0)-cells doesn't cost any more than iterating over 0-cells (@pxref{Cell iteration}).
  123. @c ------------------------------------------------
  124. @node Drag along and beating
  125. @section Drag along and beating
  126. @c ------------------------------------------------
  127. These two fundamental array optimizations are described in @mybibcite{Abr70}.
  128. @dfn{Drag-along} is the process that delays evaluation of array operations. Expression templates can be seen as an implementation of drag-along. Drag-along isn't an optimization in and of itself; it simply preserves the necessary information up to the point where the expression can be executed efficiently.
  129. @dfn{Beating} is the implementation of certain array operations on the array @ref{Containers and views,view} descriptor instead of on the array contents. For example, if @code{A} is a 1-array, one can implement @ref{x-reverse,@code{reverse(A, 0)}} by negating the @ref{x-strides,stride} and moving the offset to the other end of the array, without having to move any elements. More generally, beating applies to any function-of-indices (generator) that can take the place of an array in an array expression. For instance, an expression such as @ref{x-iota,@code{1+iota(3, 0)}} can be beaten into @code{iota(3, 1)}, and this can enable further optimizations.
  130. @c ------------------------------------------------
  131. @node Why C++
  132. @section Why C++
  133. @c ------------------------------------------------
  134. Of course the main reason is that (this being a personal project) I'm more familiar with C++ than with other languages to which the following might apply.
  135. C++ supports the low level control that is necessary for interoperation with external libraries and languages, but still has the abstraction power to create the features we want even though the language has no native support for most of them.
  136. @cindex APL
  137. @cindex J
  138. The classic array languages, APL @mybibcite{FI73} and J @mybibcite{Ric08}, have array support baked in. The same is true for other languages with array facilities such as Fortran or Octave/Matlab. Array libraries for general purpose languages usually depend heavily on C extensions. In Numpy's case @mybibcite{num17} this is both for reasons of flexibility (e.g. to obtain predictable memory layout and machine types) and of performance.
  139. On the other extreme, an array library for C would be hampered by the limited means of abstraction in the language (no polymorphism, no metaprogramming, etc.) so the natural choice of C programmers is to resort to code generators, which eventually turn into new languages.
  140. In C++, a library is enough.
  141. @c ------------------------------------------------
  142. @node Guidelines
  143. @section Guidelines
  144. @c ------------------------------------------------
  145. @code{ra::} attempts to be general, consistent, and transparent.
  146. @c @cindex J # TODO makeinfo can't handle an entry appearing more than once (it creates multiple entries in the index).
  147. Generality is achieved by removing arbitrary restrictions and by adopting the rank extension mechanism of J. @code{ra::} supports array operations with an arbitrary number of arguments. Any of the arguments in an array expression can be read from or written to. Arrays or array expressions can be of any rank. Slicing operations work for subscripts of any rank, as in APL. You can use your own types as array elements.
  148. Consistency is achieved by having a clear set of concepts and having the realizations of those concepts adhere to the concept as closely as possible. @code{ra::} offers a few different types of views and containers, but it should be possible to use them interchangeably whenever the properties that justify their existence are not involved. When this isn't possible, it's a bug. For example, it used to be the case that you couldn't create a higher rank iterator on a @code{SmallView}, even though you could do it on a @code{View}; this was a bug.
  149. Sometimes consistency requires a choice. For example, given array views A and B, @code{A=B} copies the contents of view B into view A. To change view A instead (to treat A as a pointer) would be the default meaning of A=B for C++ types, and result in better consistency with the rest of the language, but I have decided that having consistency between views and containers (which ‘are’ their contents in a sense that views aren't) is more important.
  150. Transparency is achieved by avoiding opaque types. An array view consists of a pointer and a list of strides and I see no point in hiding that. Manipulating the strides directly is often useful. A container consists of storage and a view and that isn't hidden either. Some of the types have an obscure implementation but I consider that a defect. Ideally you should be able to rewrite expressions on the fly, or plug in your own traversal methods or storage handling.
  151. That isn't to mean that you need to be in command of a lot of internal detail to be able to use the library. I hope to have provided a high level interface to most operations and a reasonably sweet syntax. However, transparency is critical to achieve interoperation with external libraries and languages. When you need to, you'll be able to guarantee that an array is stored by compact columns or that the real parts are interleaved with the imaginary parts.
  152. @c ------------------------------------------------
  153. @node Other libraries
  154. @section Other array libraries
  155. @c ------------------------------------------------
  156. Here I try to list the C++ array libraries that I know of, or libraries that I think deserve a mention for the way they deal with arrays. It is not an extensive review, since I have only used a few of these libraries myself. Please follow the links if you want to be properly informed.
  157. Since the C++ standard library doesn't offer a standard multidimensional array type, some libraries for specific tasks (linear algebra operations, finite elements, optimization) offer an accessory array library, which may be more or less general. Other libraries have generic array interfaces without needing to provide an array type. FFTW is a good example, maybe because it isn't C++!
  158. @subsection Standard C++
  159. The C++ language offers multidimensional arrays as a legacy feature from C, e.g. @code{int a[3][4]}. These decay to pointers when you do nearly anything with them, don't know their own sizes or rank at runtime, and are generally too limited.
  160. The C++ standard library also offers a number of contiguous storage containers that can be used as 1-arrays: @code{<array>}, @code{<vector>} and @code{<valarray>}. Neither supports higher ranks out of the box, but @code{<valarray>} offers array operations for 1-arrays. @code{ra::} makes use of @code{<array>} and @code{<vector>} for storage and bootstrapping.
  161. @code{ra::} accepts built-in arrays and standard library types as array objects (@pxref{Compatibility}).
  162. @subsection Blitz++
  163. @cindex Blitz++
  164. Blitz++ @mybibcite{bli17} pioneered the use of expression templates in C++. It supported higher rank arrays, as high as it was practical in C++98, but not dynamic rank. It also supported small arrays with compile time sizes (@code{Tiny}), and convenience features such as Fortran-order constructors and arbitrary lower bounds for the array indices (both of which @code{ra::} chooses not to support). It placed a strong emphasis on performance, with array traversal methods such as blocking, space filling curves, etc.
  165. To date it remains, I believe, one of the most general array libraries for C++. However, the implementation had to fight the limitations of C++98, and it offered no general rank extension mechanism.
  166. One important difference between Blitz++ and @code{ra::} is that Blitz++'s arrays were reference counted. @code{ra::} doesn't do any memory management on its own: the default container types are explicitly values (data-owning) or views. You can select your own storage for the data-owning objects, including reference-counted storage (@code{ra::} declares a type using @code{std::shared_ptr}), but this is not the default.
  167. @subsection Other C++ libraries
  168. I guess this is important enough!
  169. @subsection Other languages
  170. TODO Maybe review other languages, at least the big ones (Fortran/APL/J/Matlab/Numpy).
  171. @c ------------------------------------------------
  172. @node Usage
  173. @chapter Usage
  174. @c ------------------------------------------------
  175. This is an extended exposition of the features of @code{ra::} and is probably best read in order. For details on specific functions or types, please @pxref{Reference}.
  176. @menu
  177. * Using the library:: @code{ra::} is a header-only library.
  178. * Containers and views:: Data objects.
  179. * Array operations:: Building and traversing expressions.
  180. * Rank extension:: How array operands are matched.
  181. * Cell iteration:: At any rank.
  182. * Slicing:: Subscripting is a special operation.
  183. * Special objects:: Not arrays, yet arrays.
  184. * The rank conjunction:: J comes to C++.
  185. * Compatibility:: With the STL and other libraries.
  186. * Extension:: Using your own types and more.
  187. * Functions:: Ready to go.
  188. * Error handling:: What to check and what to do.
  189. @end menu
  190. @c ------------------------------------------------
  191. @node Using the library
  192. @section Using @code{ra::}
  193. @c ------------------------------------------------
  194. @code{ra::} is a header only library with no dependencies, so you just need to place the @samp{ra/} folder somewhere in your include path and add @code{#include "ra/ra.hh"} at the top of your sources.
  195. A compiler with C++20 support is required. At the time of writing this means @b{gcc 10.1} with @option{-std=c++20}. Check the top README.md for more up-to-date information.
  196. Here is a minimal program@footnote{Examples given without context assume that one has declared @code{using std::cout;}, etc.}:
  197. @example @c readme.cc [ma101]
  198. @verbatim
  199. #include "ra/ra.hh"
  200. #include <iostream>
  201. int main()
  202. {
  203. ra::Big<char, 2> A({2, 5}, "helloworld");
  204. std::cout << ra::noshape << format_array(transpose<1, 0>(A), "|") << std::endl;
  205. }
  206. @end verbatim
  207. @print{} h|w
  208. e|o
  209. l|r
  210. l|l
  211. d|d
  212. @end example
  213. You may want to @code{#include "ra/real.hh"} and @code{"ra/complex.hh"}. These put some functions in the global namespace that make it easier to work on built-in scalar types or array expressions indistinctly. They are not required for the rest of the library to function.
  214. @cindex container
  215. @c ------------------------------------------------
  216. @node Containers and views
  217. @section Containers and views
  218. @c ------------------------------------------------
  219. @code{ra::} offers two kinds of data objects. The first kind, the @dfn{container}, owns its data. Creating a container requires memory and destroying it causes that memory to be freed.
  220. There are three kinds of containers: static size, static rank/dynamic size, and dynamic rank. Here static means ‘compile time constant’ while dynamic means ‘run time constant’. Some dynamic size arrays can be resized but dynamic rank arrays cannot normally have their rank changed. Instead, you create a new container or view with the rank you want.
  221. For example:
  222. @example
  223. @verbatim
  224. {
  225. ra::Small<double, 2, 3> a(0.); // a static size 2x3 array
  226. ra::Big<double, 2> b({2, 3}, 0.); // a dynamic size 2x3 array
  227. ra::Big<double> c({2, 3}, 0.); // a dynamic rank 2x3 array
  228. // a, b, c destroyed at end of scope
  229. }
  230. @end verbatim
  231. @end example
  232. The main reason to have all these different types is performance; the compiler can do a better job when it knows the size or the rank of the array. Also, the sizes of a static size array do not need to be stored in memory, so when you have thousands of small arrays it pays off to use the static size types. Static size or static rank arrays are also safer to use; sometimes @code{ra::} will be able to detect errors in the sizes or ranks of array operands at compile time, if the appropriate types are used.
  233. Container constructors come in two forms. The first form takes a single argument which is copied into the new container. This argument provides shape information if the container type requires it.@footnote{The brace-list constructors of rank 2 and higher aren't supported on types of runtime rank, because in the C++ grammar, a nested initializer list doesn't always define a rank unambiguously.}
  234. @c [ma111]
  235. @example
  236. @verbatim
  237. using ra::Small, ra::Big;
  238. Small<int, 2, 2> a = {{1, 2}, {3, 4}}; // explicit contents
  239. Big<int, 2> a1 = {{1, 2}, {3, 4}}; // explicit contents
  240. Small<int, 2, 2> a2 = {{1, 2}}; // error: bad size
  241. Small<int, 2, 2> b = 7; // 7 is copied into b
  242. Small<int, 2, 2> c = a; // the contents of a are copied into c
  243. Big<int> d = a; // d takes the shape of a and a is copied into d
  244. Big<int> e = 0; // e is a 0-array with one element f()==0.
  245. @end verbatim
  246. @end example
  247. The second form takes two arguments, one giving the shape, the second the contents.
  248. @cindex @code{none}
  249. @cindex uninitialized container
  250. @example
  251. @verbatim
  252. ra::Big<double, 2> a({2, 3}, 1.); // a has size 2x3 and be filled with 1.
  253. ra::Big<double> b({2, 3}, ra::none); // b has size 2x3 and contents don't matter
  254. ra::Big<double> c({2, 3}, a); // c has size 2x3 and a is copied into c
  255. @end verbatim
  256. @end example
  257. The last example may result in an error if the shape of @code{a} and (2,@w{ }3) don't match. Here the shape of @code{1.} [which is ()] matches (2,@w{ }3) by a mechanism of rank extension (@pxref{Rank extension}). The special value @code{ra::none} can be used to request @url{https://en.cppreference.com/w/cpp/language/default_initialization, default initialization} of the container's elements.
  258. When the content argument is a pointer or a 1D brace list, it's handled especially, not for shape@footnote{You can still use pointers or @code{std::initializer_list}s for shape by wrapping them in the functions @code{ptr} or @code{vector}, respectively.}, but only as the (row-major) ravel of the content. The pointer constructor is unsafe —use at your own risk!@footnote{The brace-list constructors aren't rank extending, because giving the ravel is incompatible with rank extension. They are size-strict —you must give every element.}
  259. @cindex order, column-major
  260. @example
  261. @verbatim
  262. Small<int, 2, 2> aa = {1, 2, 3, 4}; // ravel of the content
  263. ra::Big<double, 2> a({2, 3}, {1, 2, 3, 4, 5, 6}); // same as a = {{1, 2, 3}, {4, 5, 6}}
  264. @end verbatim
  265. @end example
  266. @c [ma112]
  267. @example
  268. @verbatim
  269. double bx[6] = {1, 2, 3, 4, 5, 6}
  270. ra::Big<double, 2> b({3, 2}, bx); // {{1, 2}, {3, 4}, {5, 6}}
  271. double cx[4] = {1, 2, 3, 4}
  272. ra::Big<double, 2> c({3, 2}, cx); // *** WHO NOSE ***
  273. @end verbatim
  274. @end example
  275. @c [ma114]
  276. @example
  277. @verbatim
  278. using sizes = mp::int_list<2, 3>;
  279. using strides = mp::int_list<1, 2>;
  280. ra::SmallArray<double, sizes, strides> a {{1, 2, 3}, {4, 5, 6}}; // stored column-major: 1 4 2 5 3 6
  281. @end verbatim
  282. @end example
  283. These produce compile time errors:
  284. @example
  285. @verbatim
  286. Big<int, 2> b = {1, 2, 3, 4}; // error: shape cannot be deduced from ravel
  287. Small<int, 2, 2> b = {1, 2, 3, 4 5}; // error: bad size
  288. Small<int, 2, 2> b = {1, 2, 3}; // error: bad size
  289. @end verbatim
  290. @end example
  291. @anchor{x-scalar-char-star}
  292. Sometimes the pointer constructor gets in the way (see @ref{x-scalar,@code{scalar}}): @c [ma102]
  293. @example
  294. @verbatim
  295. ra::Big<char const *, 1> A({3}, "hello"); // error: try to convert char to char const *
  296. ra::Big<char const *, 1> A({3}, ra::scalar("hello")); // ok, "hello" is a single item
  297. cout << ra::noshape << format_array(A, "|") << endl;
  298. @end verbatim
  299. @print{} hello|hello|hello
  300. @end example
  301. @cindex view
  302. A @dfn{view} is similar to a container in that it points to actual data in memory. However, the view doesn't own that data and destroying the view won't affect it. For example:
  303. @example
  304. @verbatim
  305. ra::Big<double> c({2, 3}, 0.); // a dynamic rank 2x3 array
  306. {
  307. auto c1 = c(1); // the second row of array c
  308. // c1 is destroyed here
  309. }
  310. cout << c(1, 1) << endl; // ok
  311. @end verbatim
  312. @end example
  313. The data accessed through a view is the data of the ‘root’ container, so modifying the former will be reflected in the latter.
  314. @example
  315. @verbatim
  316. ra::Big<double> c({2, 3}, 0.);
  317. auto c1 = c(1);
  318. c1(2) = 9.; // c(1, 2) = 9.
  319. @end verbatim
  320. @end example
  321. Just as for containers, there are separate types of views depending on whether the size is known at compile time, the rank is known at compile time but the size is not, or neither the size nor the rank are known at compile time. @code{ra::} has functions to create the most common kinds of views:
  322. @example
  323. @verbatim
  324. ra::Big<double> c {{1, 2, 3}, {4, 5, 6}};
  325. auto ct = transpose<1, 0>(c); // {{1, 4}, {2, 5}, {3, 6}}
  326. auto cr = reverse(c, 0); // {{4, 5, 6}, {1, 2, 3}}
  327. @end verbatim
  328. @end example
  329. However, views can point to anywhere in memory and that memory doesn't have to belong to an @code{ra::} container. For example:
  330. @example
  331. @verbatim
  332. int raw[6] = {1, 2, 3, 4, 5, 6};
  333. ra::View<int> v1({{2, 3}, {3, 1}}, raw); // view with sizes {2, 3} strides {3, 1}
  334. ra::View<int> v2({2, 3}, raw); // same, default C (row-major) strides
  335. @end verbatim
  336. @end example
  337. Containers can be treated as views of the same ‘dynamicness’. If you declare a function
  338. @example
  339. @verbatim
  340. void f(ra::View<int, 3> & v);
  341. @end verbatim
  342. @end example
  343. you may pass it an object of type @code{ra::Big<int, 3>}.
  344. @c ------------------------------------------------
  345. @node Array operations
  346. @section Array operations
  347. @c ------------------------------------------------
  348. To apply an operation to each element of an array, use the function @code{for_each}. The array is traversed in an order that is decided by the library.
  349. @example
  350. @verbatim
  351. ra::Small<double, 2, 3> a = {{1, 2, 3}, {4, 5, 6}};
  352. double s = 0.;
  353. for_each([&s](auto && a) { s+=a; }, a);
  354. @end verbatim
  355. @result{} s = 21.
  356. @end example
  357. To construct an array expression but stop short of traversing it, use the function @code{map}. The expression will be traversed when it is assigned to a view, printed out, etc.
  358. @example
  359. @verbatim
  360. using T = ra::Small<double, 2, 2>;
  361. T a = {{1, 2}, {3, 4}};
  362. T b = {{10, 20}, {30, 40}};
  363. T c = map([](auto && a, auto && b) { return a+b; }, a, b); // (1)
  364. @end verbatim
  365. @result{} c = @{@{11, 22@}, @{33, 44@}@}
  366. @end example
  367. Expressions may take any number of arguments and be nested arbitrarily.
  368. @example
  369. @verbatim
  370. T d = 0;
  371. for_each([](auto && a, auto && b, auto && d) { d = a+b; },
  372. a, b, d); // same as (1)
  373. for_each([](auto && ab, auto && d) { d = ab; },
  374. map([](auto && a, auto && b) { return a+b; },
  375. a, b),
  376. d); // same as (1)
  377. @end verbatim
  378. @end example
  379. The operator of an expression may return a reference and you may assign to an expression in that case. @code{ra::} will complain if the expression is somehow not assignable.
  380. @example
  381. @verbatim
  382. T d = 0;
  383. map([](auto & d) -> decltype(auto) { return d; }, d) // just pass d along
  384. = map([](auto && a, auto && b) { return a+b; }, a, b); // same as (1)
  385. @end verbatim
  386. @end example
  387. @code{ra::} defines many shortcuts for common array operations. You can of course just do:
  388. @example
  389. @verbatim
  390. T c = a+b; // same as (1)
  391. @end verbatim
  392. @end example
  393. @c ------------------------------------------------
  394. @node Rank extension
  395. @section Rank extension
  396. @c ------------------------------------------------
  397. Rank extension is the mechanism that allows @code{R+S} to be defined even when @code{R}, @code{S} may have different ranks. The idea is an interpolation of the following basic cases.
  398. Suppose first that @code{R} and @code{S} have the same rank. We require that the shapes be the same. Then the shape of @code{R+S} will be the same as the shape of either @code{R} or @code{S} and the elements of @code{R+S} will be
  399. @quotation
  400. @code{(R+S)(i₀ i₁ ... i₍ᵣ₋₁₎) = R(i₀ i₁ ... i₍ᵣ₋₁₎) + S(i₀ i₁ ... i₍ᵣ₋₁₎)}
  401. @end quotation
  402. where @code{r} is the rank of @code{R}.
  403. Now suppose that @code{S} has rank 0. The shape of @code{R+S} is the same as the shape of @code{R} and the elements of @code{R+S} will be
  404. @quotation
  405. @code{(R+S)(i₀ i₁ ... i₍ᵣ₋₁₎) = R(i₀ i₁ ... i₍ᵣ₋₁₎) + S()}.
  406. @end quotation
  407. The two rules above are supported by all primitive array languages, e.g. Matlab @mybibcite{Mat}. But suppose that @code{S} has rank @code{s}, where @code{0<s<r}. Looking at the expressions above, it seems natural to define @code{R+S} by
  408. @quotation
  409. @code{(R+S)(i₀ i₁ ... i₍ₛ₋₁₎ ... i₍ᵣ₋₁₎) = R(i₀ i₁ ... i₍ₛ₋₁₎ ... i₍ᵣ₋₁₎) + S(i₀ i₁ ... i₍ₛ₋₁₎)}.
  410. @end quotation
  411. That is, after we run out of indices in @code{S}, we simply repeat the elements. We have aligned the shapes so:
  412. @quotation
  413. @verbatim
  414. [n₀ n₁ ... n₍ₛ₋₁₎ ... n₍ᵣ₋₁₎]
  415. [n₀ n₁ ... n₍ₛ₋₁₎]
  416. @end verbatim
  417. @end quotation
  418. @cindex shape agreement, prefix
  419. @cindex shape agreement, suffix
  420. @c @cindex J
  421. @cindex Numpy
  422. This rank extension rule is used by the J language @mybibcite{J S} and is known as @dfn{prefix agreement}. The opposite rule of @dfn{suffix agreement} is used, for example, in Numpy @mybibcite{num17}@footnote{Prefix agreement is chosen for @code{ra::} because of the availability of a @ref{The rank conjunction,rank conjunction} @mybibcite{Ber87} and @ref{Cell iteration, cell iterators of arbitrary rank}. This allows rank extension to be performed at multiple axes of an array expression.}.
  423. As you can verify, the prefix agreement rule is distributive. Therefore it can be applied to nested expressions or to expressions with any number of arguments. It is applied systematically throughout @code{ra::}, even in assignments. For example,
  424. @example
  425. @verbatim
  426. ra::Small<int, 3> x {3, 5, 9};
  427. ra::Small<int, 3, 2> a = x; // assign x(i) to each a(i, j)
  428. @end verbatim
  429. @result{} a = @{@{3, 3@}, @{5, 5@}, @{9, 9@}@}
  430. @end example
  431. @example
  432. @verbatim
  433. ra::Small<int, 3> x(0.);
  434. ra::Small<int, 3, 2> a = {{1, 2}, {3, 4}, {5, 6}};
  435. x += a; // sum the rows of a
  436. @end verbatim
  437. @result{} x = @{3, 7, 11@}
  438. @end example
  439. @example
  440. @verbatim
  441. ra::Big<double, 3> a({5, 3, 3}, ra::_0);
  442. ra::Big<double, 1> b({5}, 0.);
  443. b += transpose<0, 1, 1>(a); // b(i) = ∑ⱼ a(i, j, j)
  444. @end verbatim
  445. @result{} b = @{0, 3, 6, 9, 12@}
  446. @end example
  447. @cindex Numpy
  448. @cindex broadcasting, singleton, newaxis
  449. An weakness of prefix agreement is that the axes you want to match aren't always the prefix axes. Other array systems offer a feature similar to rank extension called ‘broadcasting’ that is a bit more flexible. For example, in the way it's implemented in Numpy @mybibcite{num17}, an array of shape [A B 1 D] will match an array of shape [A B C D]. The process of broadcasting consists in inserting so-called ‘singleton dimensions’ (axes with size one) to align the axes that one wishes to match. You can think of prefix agreement as a particular case of broadcasting where the singleton dimensions are added to the end of the shorter shapes automatically.
  450. A drawback of singleton broadcasting is that it muddles the distinction between a scalar and a vector of size 1. Sometimes, an axis of size 1 is no more than that, and if 2≠3 is a size error, it isn't obvious why 1≠2 shouldn't be. To avoid this problem, @code{ra::} supports broadcasting with undefined size axes (see @ref{x-insert,@code{insert}}).
  451. @example
  452. @verbatim
  453. ra::Big<double, 3> a({5, 3}, ra::_0);
  454. ra::Big<double, 1> b({3}, 0.);
  455. ra::Big<double, 3> c({1, 3}, ra::_0);
  456. // b(?, i) += a(j, i) → b(i) = ∑ⱼ a(j, i) (sum columns)
  457. b(ra::insert<1>) += a;
  458. c = a; // 1 ≠ 5, still an agreement error
  459. @end verbatim
  460. @end example
  461. Still another way to align array axes is provided by the @ref{The rank conjunction,rank conjunction}.
  462. Even with axis insertion, it is still necessary that the axes one wishes to match are in the same order in all the arguments.
  463. @ref{x-transpose,Transposing} the axes before extension is a possible workaround.
  464. @c ------------------------------------------------
  465. @node Cell iteration
  466. @section Cell iteration
  467. @c ------------------------------------------------
  468. @code{map} and @code{for_each} apply their operators to each element of their arguments; in other words, to the 0-cells of the arguments. But it is possible to specify directly the rank of the cells that one iterates over:
  469. @example
  470. @verbatim
  471. ra::Big<double, 3> a({5, 4, 3}, ra::_0);
  472. for_each([](auto && b) { /* b has shape (5 4 3) */ }, iter<3>(a));
  473. for_each([](auto && b) { /* b has shape (4 3) */ }, iter<2>(a));
  474. for_each([](auto && b) { /* b has shape (3) */ }, iter<1>(a));
  475. for_each([](auto && b) { /* b has shape () */ }, iter<0>(a)); // elements
  476. for_each([](auto && b) { /* b has shape () */ }, a); // same as iter<0>(a); default
  477. @end verbatim
  478. @end example
  479. One may specify the @emph{frame} rank instead:
  480. @example
  481. @verbatim
  482. for_each([](auto && b) { /* b has shape () */ }, iter<-3>(a)); // same as iter<0>(a)
  483. for_each([](auto && b) { /* b has shape (3) */ }, iter<-2>(a)); // same as iter<1>(a)
  484. for_each([](auto && b) { /* b has shape (4 3) */ }, iter<-1>(a)); // same as iter<2>(a)
  485. @end verbatim
  486. @end example
  487. In this way it is possible to match shapes in various ways. Compare
  488. @example
  489. @verbatim
  490. ra::Big<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  491. ra::Big<double, 1> b = {10, 20};
  492. ra::Big<double, 2> c = a * b; // multiply (each item of a) by (each item of b)
  493. @end verbatim
  494. @result{} a = @{@{10, 20, 30@}, @{80, 100, 120@}@}
  495. @end example
  496. with
  497. @example @c [ma105]
  498. @verbatim
  499. ra::Big<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  500. ra::Big<double, 1> b = {10, 20, 30};
  501. ra::Big<double, 2> c({2, 3}, 0.);
  502. iter<1>(c) = iter<1>(a) * iter<1>(b); // multiply (each item of a) by (b)
  503. @end verbatim
  504. @result{} a = @{@{10, 40, 90@}, @{40, 100, 180@}@}
  505. @end example
  506. Note that in this case we cannot construct @code{c} directly from @code{iter<1>(a) * iter<1>(b)}, since the constructor for @code{ra::Big} matches its argument using (the equivalent of) @code{iter<0>(*this)}. See @ref{x-iter,@code{iter}} for more examples.
  507. Cell iteration is appropriate when the operations take naturally operands of rank > 0; for instance, the operation ‘determinant of a matrix’ is naturally of rank 2. When the operation is of rank 0, such as @code{*} above, there may be faster ways to rearrange shapes for matching (@pxref{The rank conjunction}).
  508. FIXME More examples.
  509. @c ------------------------------------------------
  510. @node Slicing
  511. @section Slicing
  512. @c ------------------------------------------------
  513. Slicing is an array extension of the subscripting operation. However, tradition and convenience have given it a special status in most array languages, together with some peculiar semantics that @code{ra::} supports.
  514. The form of the scripting operator @code{A(i₀, i₁, ...)} makes it plain that @code{A} is a function of @code{rank(A)} integer arguments. An array extension is immediately available through @code{map}. For example:
  515. @example
  516. @verbatim
  517. ra::Big<double, 1> a = {1., 2., 3., 4.};
  518. ra::Big<int, 1> i = {1, 3};
  519. map(a, i) = 77.;
  520. @end verbatim
  521. @result{} a = @{1., 77., 3, 77.@}
  522. @end example
  523. Just as with any use of @code{map}, array arguments are subject to the prefix agreement rule.
  524. @example
  525. @verbatim
  526. ra::Big<double, 2> a({2, 2}, {1., 2., 3., 4.});
  527. ra::Big<int, 1> i = {1, 0};
  528. ra::Big<double, 1> b = map(a, i, 0);
  529. @end verbatim
  530. @result{} b = @{3., 1.@} // @{a(1, 0), a(0, 0)@}
  531. @end example
  532. @example
  533. @verbatim
  534. ra::Big<int, 1> j = {0, 1};
  535. b = map(a, i, j);
  536. @end verbatim
  537. @result{} b = @{3., 2.@} // @{a(1, 0), a(0, 1)@}
  538. @end example
  539. The latter is a form of sparse subscripting.
  540. Most array operations (e.g. @code{+}) are defined through @code{map} in this way. For example, @code{A+B+C} is defined as @code{map(+, A, B, C)} (or the equivalent @code{map(+, map(+, A, B), C)}). Not so for the subscripting operation:
  541. @example
  542. @verbatim
  543. ra::Big<double, 2> A {{1., 2.}, {3., 4.}};
  544. ra::Big<int, 1> i = {1, 0};
  545. ra::Big<int, 1> j = {0, 1};
  546. // {{A(i₀, j₀), A(i₀, j₁)}, {A(i₁, j₀), A(i₁, j₁)}}
  547. ra::Big<double, 2> b = A(i, j);
  548. @end verbatim
  549. @result{} b = @{@{3., 4.@}, @{1., 2.@}@}
  550. @end example
  551. @code{A(i, j, ...)} is defined as the @emph{outer product} of the indices @code{(i, j, ...)} with operator @code{A}, because this operation sees much more use in practice than @code{map(A, i, j ...)}.
  552. Besides, when the subscripts @code{i, j, ...} are scalars or @dfn{linear ranges} (integer sequences of the form @code{(o, o+s, ..., o+s*(n-1))}), the subscripting can be performed inmediately at constant cost and without needing to construct an expression object. This optimization is called @ref{Drag along and beating,@dfn{beating}}.
  553. @code{ra::} isn't smart enough to know when an arbitrary expression might be a linear range, so the following special objects are provided:
  554. @anchor{x-iota}
  555. @deffn @w{Special object} iota count [start:0 [step:1]]
  556. Create a linear range @code{start, start+step, ... start+step*(count-1)}.
  557. @end deffn
  558. This can used anywhere an array expression is expected.
  559. @example
  560. @verbatim
  561. ra::Big<int, 1> a = ra::iota(4, 3 -2);
  562. @end verbatim
  563. @result{} a = @{3, 1, -1, -3@}
  564. @end example
  565. Here, @code{b} and @code{c} are @code{View}s (@pxref{Containers and views}).
  566. @example
  567. @verbatim
  568. ra::Big<int, 1> a = {1, 2, 3, 4, 5, 6};
  569. auto b = a(iota(3));
  570. auto c = a(iota(3, 3));
  571. @end verbatim
  572. @result{} a = @{1, 2, 3@}
  573. @result{} a = @{4, 5, 6@}
  574. @end example
  575. @deffn @w{Special object} all
  576. Create a linear range @code{0, 1, ... (nᵢ-1)} when used as a subscript for the @code{i}-th argument of a subscripting expression.
  577. @end deffn
  578. This object cannot stand alone as an array expression. All the examples below result in @code{View} objects:
  579. @example
  580. @verbatim
  581. ra::Big<int, 2> a({3, 2}, {1, 2, 3, 4, 5, 6});
  582. auto b = a(ra::all, ra::all); // (1) a view of the whole of a
  583. auto c = a(iota(3), iota(2)); // same as (1)
  584. auto d = a(iota(3), ra::all); // same as (1)
  585. auto e = a(ra:all, iota(2)); // same as (1)
  586. auto f = a(0, ra::all); // first row of a
  587. auto g = a(ra::all, 1); // second column of a
  588. @end verbatim
  589. @end example
  590. @code{all} is a special case (@code{dots<1>}) of the more general object @code{dots}.
  591. @deffn @w{Special object} dots<n>
  592. Equivalent to as many instances of @code{ra::all} as indicated by @code{n}, which must not be negative. Each instance takes the place of one argument to the subscripting operation.
  593. @end deffn
  594. This object cannot stand alone as an array expression. All the examples below result in @code{View} objects:
  595. @example
  596. @verbatim
  597. auto h = a(ra::all, ra::all); // same as (1)
  598. auto i = a(ra::all, ra::dots<1>); // same as (1)
  599. auto j = a(ra::dots<2>); // same as (1)
  600. auto k = a(ra::dots<0>, ra::dots<2>); // same as (1)
  601. auto l = a(0, ra::dots<1>); // first row of a
  602. auto m = a(ra::dots<1>, 1); // second column of a
  603. @end verbatim
  604. @end example
  605. This is useful when writing rank-generic code, see @code{examples/maxwell.cc} in the distribution for an example.
  606. @anchor{x-insert}
  607. @deffn @w{Special object} insert<n>
  608. Inserts @code{n} new axes at the subscript position. @code{n} must not be negative.
  609. @end deffn
  610. The new axes have stride 0 and undefined size, so they will match any size on those axes by repeating items. @code{insert} objects cannot stand alone as an array expression. The examples below result in @code{View} objects:
  611. @example
  612. @verbatim
  613. auto h = a(insert<0>); // same as (1)
  614. auto k = a(insert<1>); // shape [undefined, 3, 2]
  615. @end verbatim
  616. @end example
  617. @cindex broadcasting, singleton, Numpy
  618. @code{insert<n>} main use is to prepare arguments for broadcasting. In other array systems (e.g. Numpy) broadcasting is done with singleton dimensions, that is, dimensions of size one match dimensions of any size. In @code{ra::} singleton dimensions aren't special, so broadcasting requires the use of @code{insert}. For example: @c [ma115]
  619. @example
  620. @verbatim
  621. ra::Big<int, 1> x = {1, 10};
  622. // match shapes [2, U, U] with [U, 3, 2] to produce [2, 3, 2]
  623. cout << x(ra::all, ra::insert<2>) * a(insert<1>) << endl;
  624. @end verbatim
  625. @print{} 2 3 2
  626. 1 2
  627. 3 4
  628. 5 6
  629. 10 20
  630. 30 40
  631. 50 60
  632. @end example
  633. Here's a way to perform the outer product of two @code{Views} of static rank (but see @ref{x-from,@code{from}} for a more general way):
  634. @example
  635. @verbatim
  636. cout << (a(ra::dots<a.rank()>, ra::insert<b.rank()>) * b(ra::insert<a.rank()>, ra::dots<b.rank()>)) << endl;
  637. // same thing by prefix matching
  638. cout << (a * b(ra::insert<a.rank()>)) << endl;
  639. @end verbatim
  640. @end example
  641. In addition to the special objects listed above, you can also omit any trailing @code{ra::all} subscripts. For example:
  642. @example
  643. @verbatim
  644. ra::Big<int, 3> a({2, 2, 2}, {1, 2, 3, 4, 5, 6, 7, 8});
  645. auto a0 = a(0); // same as a(0, ra::all, ra::all)
  646. auto a10 = a(1, 0); // same as a(1, 0, ra::all)
  647. @end verbatim
  648. @result{} a0 = @{@{1, 2@}, @{3, 4@}@}
  649. @result{} a10 = @{5, 6@}
  650. @end example
  651. This supports the notion (@pxref{Rank polymorphism}) that a 3-array is also an 2-array where the elements are 1-arrays themselves, or a 1-array where the elements are 2-arrays. This important property is directly related to the mechanism of rank extension (@pxref{Rank extension}).
  652. @subsection Subscripting and rank-0 views
  653. @cindex view, rank 0
  654. @cindex rank, dynamic
  655. @cindex rank, static
  656. When the result of the subscripting operation would have rank 0, the type returned is the type of the view @emph{element} and not a rank-0 view as long as the rank of the result can be determined at compile time. When that's not possible (for instance, the subscripted view has dynamic rank) then a rank-0 view is returned instead. An automatic conversion is defined for rank-0 views, but manual conversion may be needed in some contexts.
  657. @example
  658. @verbatim
  659. using T = std::complex<double>;
  660. int f(T &);
  661. Big<T, 2> a({2, 3}, 0); // static rank
  662. Big<T> b({2, 3}, 0); // dynamic rank
  663. cout << a(0, 0).real_part() << endl; // ok, a(0, 0) returns complex &
  664. // cout << b(0, 0).real_part() << endl; // error, View<T> has no member real_part
  665. cout << ((T &)(b(0, 0))).real_part() << endl; // ok, manual conversion to T &
  666. cout << f(b(0, 0)) << endl; // ok, automatic conversion from View<T> to T &
  667. // cout << f(a(0)) << endl; // compile time error, conversion failed since static rank of a(0) is not 0
  668. // cout << f(b(0)) << endl; // runtime error, conversion failed since dynamic rank of b(0) is not 0
  669. @end verbatim
  670. @end example
  671. @c ------------------------------------------------
  672. @node Special objects
  673. @section Special objects
  674. @c ------------------------------------------------
  675. @deffn @w{Special object} TensorIndex<n, integer_type=ra::dim_t>
  676. @code{TensorIndex<n>} represents the @code{n}-th index of an array expression. @code{TensorIndex<n>} is itself an array expression of rank @code{n}-1 and size undefined. It must be used with other terms whose dimensions are defined, so that the overall shape of the array expression can be determined.
  677. @code{ra::} offers the shortcut @code{ra::_0} for @code{ra::TensorIndex<0>@{@}}, etc.
  678. @end deffn
  679. @example
  680. @verbatim
  681. ra::Big<int, 1> v = {1, 2, 3};
  682. cout << (v - ra::_0) << endl; // { 1-0, 2-1, 3-2 }
  683. // cout << (ra::_0) << endl; // error: TensorIndex cannot drive array expression
  684. // cout << (v - ra::_1) << endl; // error: TensorIndex cannot drive array expression
  685. ra::Big<int, 2> a({3, 2}, 0);
  686. cout << (a + ra::_0 - ra::_1) << endl; // {{0, -1, -2}, {1, 0, -1}, {2, 1, 0}}
  687. @end verbatim
  688. @end example
  689. @c FIXME the rest
  690. @c ------------------------------------------------
  691. @node The rank conjunction
  692. @section The rank conjunction
  693. @c ------------------------------------------------
  694. We have seen in @ref{Cell iteration} that it is possible to treat an r-array as an array of lower rank with subarrays as its elements. With the @ref{x-iter,@code{iter<cell rank>}} construction, this ‘exploding’ is performed (notionally) on the argument; the operation of the array expression is applied blindly to these cells, whatever they turn out to be.
  695. @example
  696. @verbatim
  697. for_each(my_sort, iter<1>(A)); // (in ra::) my_sort is a regular function, cell rank must be given
  698. for_each(my_sort, iter<0>(A)); // (in ra::) error, bad cell rank
  699. @end verbatim
  700. @end example
  701. @c @cindex J
  702. The array language J has instead the concept of @dfn{verb rank}. Every function (or @dfn{verb}) has an associated cell rank for each of its arguments. Therefore @code{iter<cell rank>} is not needed.
  703. @example
  704. @verbatim
  705. for_each(sort_rows, A); // (not in ra::) will iterate over 1-cells of A, sort_rows knows
  706. @end verbatim
  707. @end example
  708. @c @cindex J
  709. @code{ra::} doesn't have ‘verb ranks’ yet. In practice one can think of @code{ra::}'s operations as having a verb rank of 0. However, @code{ra::} supports a limited form of J's @dfn{rank conjunction} with the function @ref{x-wrank,@code{wrank}}.
  710. @c @cindex J
  711. This is an operator that takes one verb (such operators are known as @dfn{adverbs} in J) and produces another verb with different ranks. These ranks are used for rank extension through prefix agreement, but then the original verb is used on the cells that result. The rank conjunction can be nested, and this allows repeated rank extension before the innermost operation is applied.
  712. A standard example is ‘outer product’.
  713. @example
  714. @verbatim
  715. ra::Big<int, 1> a = {1, 2, 3};
  716. ra::Big<int, 1> b = {40, 50};
  717. ra::Big<int, 2> axb = map(ra::wrank<0, 1>([](auto && a, auto && b) { return a*b; }),
  718. a, b)
  719. @end verbatim
  720. @result{} axb = @{@{40, 80, 120@}, @{50, 100, 150@}@}
  721. @end example
  722. It works like this. The verb @code{ra::wrank<0, 1>([](auto && a, auto && b) @{ return a*b; @})} has verb ranks (0, 1), so the 0-cells of @code{a} are paired with the 1-cells of @code{b}. In this case @code{b} has a single 1-cell. The frames and the cell shapes of each operand are:
  723. @example
  724. @verbatim
  725. a: 3 |
  726. b: | 2
  727. @end verbatim
  728. @end example
  729. Now the frames are rank-extended through prefix agreement.
  730. @example
  731. @verbatim
  732. a: 3 |
  733. b: 3 | 2
  734. @end verbatim
  735. @end example
  736. Now we need to perform the operation on each cell. The verb @code{[](auto && a, auto && b) @{ return a*b; @}} has verb ranks (0, 0). This results in the 0-cells of @code{a} (which have shape ()) being rank-extended to the shape of the 1-cells of @code{b} (which is (2)).
  737. @example
  738. @verbatim
  739. a: 3 | 2
  740. b: 3 | 2
  741. @end verbatim
  742. @end example
  743. This use of the rank conjunction is packaged in @code{ra::} as the @ref{x-from,@code{from}} operator. It supports any number of arguments, not only two.
  744. @example
  745. @verbatim
  746. ra::Big<int, 1> a = {1, 2, 3};
  747. ra::Big<int, 1> b = {40, 50};
  748. ra::Big<int, 2> axb = from([](auto && a, auto && b) { return a*b; }), a, b)
  749. @end verbatim
  750. @result{} axb = @{@{40, 80, 120@}, @{50, 100, 150@}@}
  751. @end example
  752. Another example is matrix multiplication. For 2-array arguments C, A and B with shapes C: (m, n) A: (m, p) and B: (p, n), we want to perform the operation C(i, j) += A(i, k)*B(k, j). The axis alignment gives us the ranks we need to use.
  753. @example
  754. @verbatim
  755. C: m | | n
  756. A: m | p |
  757. B: | p | n
  758. @end verbatim
  759. @end example
  760. First we'll align the first axes of C and A using the cell ranks (1, 1, 2). The cell shapes are:
  761. @example
  762. @verbatim
  763. C: m | n
  764. A: m | p
  765. B: | p n
  766. @end verbatim
  767. @end example
  768. Then we'll use the ranks (1, 0, 1) on the cells:
  769. @example
  770. @verbatim
  771. C: m | | n
  772. A: m | p |
  773. B: | p | n
  774. @end verbatim
  775. @end example
  776. The final operation is a standard operation on arrays of scalars. In actual @code{ra::} syntax:
  777. @example @c [ma103]
  778. @verbatim
  779. ra::Big A({3, 2}, {1, 2, 3, 4, 5, 6});
  780. ra::Big B({2, 3}, {7, 8, 9, 10, 11, 12});
  781. ra::Big C({3, 3}, 0.);
  782. for_each(ra::wrank<1, 1, 2>(ra::wrank<1, 0, 1>([](auto && c, auto && a, auto && b) { c += a*b; })), C, A, B);
  783. @end verbatim
  784. @result{} C = @{@{27, 30, 33@}, @{61, 68, 75@}, @{95, 106, 117@}@}
  785. @end example
  786. Note that @code{wrank} cannot be used to transpose axes in general.
  787. I hope that in the future something like @code{C(i, j) += A(i, k)*B(k, j)}, where @code{i, j, k} are special objects, can be automatically translated to the requisite combination of @code{wrank} and perhaps also @ref{x-transpose,@code{transpose}}. For the time being, you have to align or transpose the axes yourself.
  788. @c ------------------------------------------------
  789. @node Compatibility
  790. @section Compatibility
  791. @c ------------------------------------------------
  792. @subsection Using other C and C++ types with @code{ra::}
  793. @cindex foreign type
  794. @code{ra::} accepts certain types from outside @code{ra::} (@dfn{foreign types}) as array expressions. Generally it is enough to mix the foreign type with a type from @code{ra::} and let deduction work.
  795. @example
  796. @verbatim
  797. std::vector<int> x = {1, 2, 3};
  798. ra::Small<int, 3> y = {6, 5, 4};
  799. cout << (x-y) << endl;
  800. @end verbatim
  801. @print{} -5 -3 -1
  802. @end example
  803. @cindex @code{start}
  804. Foreign types can be brought into @code{ra::} explicitly with the function @ref{x-start,@code{start}}.
  805. @example
  806. @verbatim
  807. std::vector<int> x = {1, 2, 3};
  808. // cout << sum(x) << endl; // error, sum not found
  809. cout << sum(ra::start(x)) << endl;
  810. cout << ra::sum(x) << endl;
  811. @end verbatim
  812. @print{} 6
  813. 6
  814. @end example
  815. The following types are accepted as foreign types:
  816. @itemize
  817. @item @code{std::vector}
  818. produces an expression of rank 1 and dynamic size.
  819. @item @code{std::array}
  820. produces an expression of rank 1 and static size.
  821. @item Built-in arrays @cindex built-in array
  822. produce an expression of positive rank and static size.
  823. @item Raw pointers
  824. produce an expression of rank 1 and @emph{undefined} size. Raw pointers must be brought into @code{ra::} explicitly with the function @ref{x-ptr,@code{ptr}}.
  825. @end itemize
  826. Compare:
  827. @example @c [ma106]
  828. @verbatim
  829. int p[] = {1, 2, 3};
  830. int * z = p;
  831. ra::Big<int, 1> q {1, 2, 3};
  832. q += p; // ok, q is ra::, p is foreign object with size info
  833. ra::start(p) += q; // can't redefine operator+=(int[]), foreign needs ra::start()
  834. // z += q; // error: raw pointer needs ra::ptr()
  835. ra::ptr(z) += p; // ok, size is determined by foreign object p
  836. @end verbatim
  837. @end example
  838. @anchor{x-is-scalar}
  839. Some types are accepted automatically as scalars. These include:
  840. @itemize
  841. @item
  842. Any type @code{T} for which @code{std::is_scalar_v<T>} is true, @emph{except} pointers. These include @code{char}, @code{int}, @code{double}, etc.
  843. @item
  844. @code{std::complex<T>}, if you import @code{ra/complex.hh}.
  845. @end itemize
  846. You can add your own types as scalar types with the following declaration (see @code{ra/complex.hh}):
  847. @verbatim
  848. namespace ra { template <> constexpr bool is_scalar_def<MYTYPE> = true; }
  849. @end verbatim
  850. Otherwise, you can bring a scalar object into @code{ra::} on the spot, with the function @ref{x-scalar,@code{scalar}}.
  851. @subsection Using @code{ra::} types with the STL
  852. General @code{ra::} @ref{Containers and views,views} provide STL compatible @code{ForwardIterator}s through the members @code{begin()} and @code{end()}. These iterators traverse the elements of the array (0-cells) in row major order, regardless of the internal order of the view.
  853. For @ref{Containers and views,containers} @code{begin()} provides @code{RandomAccessIterator}s, which is handy for certain functions such as @code{sort}. There's no reason why all views couldn't provide @code{RandomAccessIterator}, but these wouldn't be efficient in general for ranks above 1, and I haven't implemented them. The container @code{RandomAccessIterator}s that are provided are in fact raw pointers.
  854. @example @c [ma106]
  855. @verbatim
  856. ra::Big<int> x {3, 2, 1}; // x is a Container
  857. auto y = x(); // y is a View on x
  858. // std::sort(y.begin(), y.end()); // error: y.begin() is not RandomAccessIterator
  859. std::sort(x.begin(), x.end()); // ok, we know x is stored in row-major order
  860. @end verbatim
  861. @result{} x = @{1, 2, 3@}
  862. @end example
  863. @cindex other libraries, interfacing with
  864. @subsection Using @code{ra::} types with other libraries
  865. When you have to pass arrays back and forth between your program and an external library, perhaps even another language, it is necessary for both sides to agree on a memory layout. @code{ra::} gives you access to its own memory layout and allows you to obtain an @code{ra::} view on any type of memory.
  866. @subsubsection The good array citizen
  867. FIXME Put these in examples/ and reference them here.
  868. @cindex BLIS
  869. The good array citizen describes its arrays with the same parameters as @code{ra::}, that is: a pointer, plus a size and a stride per dimension. You pass those and you're done; you don't have to worry about special cases. Say @url{https://github.com/flame/blis, BLIS}:
  870. @quotation
  871. @verbatim
  872. #include <blis.h>
  873. ra::Big<double, 2> A({M, K}, ...);
  874. ra::Big<double, 2> B({K, N}, ...);
  875. ra::Big<double, 2> C({M, N}, ...);
  876. double alpha = ...;
  877. double beta = ...;
  878. // C := βC + αAB
  879. bli_dgemm(BLIS_NO_TRANSPOSE, BLIS_NO_TRANSPOSE, M, N, K, &alpha,
  880. A.data(), A.stride(0), A.stride(1),
  881. B.data(), B.stride(0), B.stride(1),
  882. &beta, C.data(), C.stride(0), C.stride(1));
  883. @end verbatim
  884. @end quotation
  885. @cindex FFTW
  886. Another good array citizen, @url{http://fftw.org, FFTW} handles arbitrary rank:
  887. @quotation
  888. @verbatim
  889. #include <fftw3.h>
  890. ...
  891. using complex = std::complex<double>;
  892. static_assert(sizeof(complex)==sizeof(fftw_complex));
  893. // forward DFT over the last r axes of a -> b
  894. void fftw(int r, ra::View<complex> const a, ra::View<complex> b)
  895. {
  896. int const rank = a.rank();
  897. assert(r>0 && r<=rank);
  898. assert(every(shape(a)==shape(b)));
  899. fftw_iodim dims[r];
  900. fftw_iodim howmany_dims[rank-r];
  901. for (int i=0; i!=rank; ++i) {
  902. if (i>=rank-r) {
  903. dims[i-rank+r].n = a.size(i);
  904. dims[i-rank+r].is = a.stride(i);
  905. dims[i-rank+r].os = b.stride(i);
  906. } else {
  907. howmany_dims[i].n = a.size(i);
  908. howmany_dims[i].is = a.stride(i);
  909. howmany_dims[i].os = b.stride(i);
  910. }
  911. }
  912. fftw_plan p;
  913. p = fftw_plan_guru_dft(r, dims, rank-r, howmany_dims,
  914. (fftw_complex *)(a.data()), (fftw_complex *)(b.data()),
  915. FFTW_FORWARD, FFTW_ESTIMATE);
  916. fftw_execute(p);
  917. fftw_destroy_plan(p);
  918. }
  919. @end verbatim
  920. @end quotation
  921. @cindex Guile
  922. Translating array descriptors from a foreign language should be fairly simple. For example, this is how to convert a @url{https://www.gnu.org/software/guile/manual/html_node/Accessing-Arrays-from-C.html#Accessing-Arrays-from-C,Guile} array view into an @code{ra::} view:
  923. @quotation
  924. @verbatim
  925. SCM a; // say a is #nf64(...)
  926. ...
  927. scm_t_array_handle h;
  928. scm_array_get_handle(a, &h);
  929. scm_t_array_dim const * dims = scm_array_handle_dims(&h);
  930. View<double> v(map([](int i) { return ra::Dimv {dim[i].ubnd-dim[i].lbnd+1, dim[i].inc}; },
  931. ra::iota(scm_array_handle_rank(&h))),
  932. scm_array_handle_f64_writable_elements(&h));
  933. ...
  934. scm_array_handle_release(&h);
  935. @end verbatim
  936. @end quotation
  937. @cindex Numpy
  938. @cindex Python
  939. Numpy's C API has the type @url{https://docs.scipy.org/doc/numpy/reference/c-api.array.html,@code{PyArrayObject}} which can be used in the same way as Guile's @code{scm_t_array_handle} in the example above.
  940. Generally it is simpler to let the foreign language handle the memory, even though there should be ways to transfer ownership (e.g. Guile has @url{https://www.gnu.org/software/guile/manual/html_node/SRFI_002d4-API.html#index-scm_005ftake_005ff64vector,@code{scm_take_xxx}}).
  941. @subsubsection The bad array citizen
  942. Unfortunately there are many libraries that don't accept general array parameters, or that do strange things with particular values of sizes and/or strides.
  943. The most common case is that a library doesn't handle strides at all, and it only accepts unit stride for rank 1 arrays, or packed row-major or column-major storage for higher rank arrays. In that case, you might be forced to copy your array before passing it along.
  944. FIXME using is_c_order, etc.
  945. Other libraries do accept strides, but not general ones. For example @url{https://www.netlib.org/blas}' @code{cblas_dgemm} has this prototype:
  946. @quotation
  947. @verbatim
  948. cblas_dgemm(order, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
  949. @end verbatim
  950. @end quotation
  951. @code{A}, @code{B}, @code{C} are (pointers to) 2-arrays, but the routine accepts only one stride argument for each (@code{lda}, etc.). CBLAS also doesn't understand @code{lda} as a general stride, but rather as the dimension of a larger array that you're slicing @code{A} from, and some implementations will handle negative or zero @code{lda} in bizarre ways.
  952. Sometimes you can work around this by fiddling with @code{transA} and @code{transB}, but in general you need to check your array parameters and you may need to make copies.
  953. @cindex OpenGL
  954. OpenGL is another library that requires @url{https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVertexAttribPointer.xhtml,contortions:}
  955. @quotation
  956. @verbatim
  957. void glVertexAttribPointer(GLuint index,
  958. GLint size,
  959. GLenum type,
  960. GLboolean normalized,
  961. GLsizei stride,
  962. const GLvoid * pointer);
  963. @end verbatim
  964. [...]
  965. @emph{stride}
  966. @quotation
  967. Specifies the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in the array. The initial value is 0.
  968. @end quotation
  969. @end quotation
  970. It isn't clear whether negative strides are legal, either. So just as with CBLAS, passing general array views will require copies.
  971. @c ------------------------------------------------
  972. @node Extension
  973. @section Extension
  974. @c ------------------------------------------------
  975. @subsection New scalar types
  976. @code{ra::} will let you construct arrays of arbitrary types out of the box. This is the same functionality you get with e.g. @code{std::vector}.
  977. @example
  978. @verbatim
  979. struct W { int x; }
  980. ra::Big<W, 2> w = {{ {4}, {2} }, { {1}, {3} }};
  981. cout << W(1, 1).x << endl;
  982. cout << amin(map([](auto && x) { return w.x; }, w)) << endl;
  983. @end verbatim
  984. @print{} 3
  985. 1
  986. @end example
  987. However, if you want to mix arbitrary types in array operations, you'll need to tell @code{ra::} that that is actually what you want. This is to avoid conflicts with other libraries.
  988. @example
  989. @verbatim
  990. namespace ra { template <> constexpr bool is_scalar_def<W> = true; }
  991. ...
  992. W ww {11};
  993. for_each([](auto && x, auto && y) { cout << (x.x + y.y) << " "; }, w, ww); // ok
  994. @end verbatim
  995. @print{} 15 13 12 14
  996. @end example
  997. but
  998. @example
  999. @verbatim
  1000. struct U { int x; }
  1001. U uu {11};
  1002. for_each([](auto && x, auto && y) { cout << (x.x + y.y) << " "; }, w, uu); // error: can't find ra::start(U)
  1003. @end verbatim
  1004. @end example
  1005. @anchor{x-new-array-operations}
  1006. @subsection New array operations
  1007. @code{ra::} provides array extensions for standard operations such as @code{+}, @code{*}, @code{cos} @ref{x-scalar-ops,and so on}. You can add array extensions for your own operations in the obvious way, with @ref{x-map,@code{map}} (but note the namespace qualifiers):
  1008. @example
  1009. @verbatim
  1010. return_type my_fun(...) { };
  1011. ...
  1012. namespace ra {
  1013. template <class ... A> inline auto
  1014. my_fun(A && ... a)
  1015. {
  1016. return map(::my_fun, std::forward<A>(a) ...);
  1017. }
  1018. } // namespace ra
  1019. @end verbatim
  1020. @end example
  1021. @cindex Blitz++
  1022. If you compare this with what Blitz++ had to do, modern C++ sure has made our lives easier.
  1023. If @code{my_fun} is an overload set, you can use
  1024. @example
  1025. @verbatim
  1026. namespace ra {
  1027. template <class ... A> inline auto
  1028. my_fun(A && ... a)
  1029. {
  1030. return map([](auto && ... a) { return ::my_fun(a ...); }, std::forward<A>(a) ...);
  1031. }
  1032. } // namespace ra
  1033. @end verbatim
  1034. @end example
  1035. @c ------------------------------------------------
  1036. @node Functions
  1037. @section Functions
  1038. @c ------------------------------------------------
  1039. You don't need to use @ref{Array operations,@code{map}} every time you want to do something with arrays in @code{ra::}. A number of array functions are already defined.
  1040. @anchor{x-scalar-ops}
  1041. @subsection Standard scalar operations
  1042. @code{ra::} defines array extensions for @code{+}, @code{-} (both unary and binary), @code{*}, @code{/}, @code{!}, @code{&&}, @code{||}@footnote{@code{&&}, @code{||} are short-circuiting as array operations; the elements of the second operand won't be evaluated if the elements of the first one evaluate to @code{false} or @code{true}, respectively.
  1043. Note that if both operands are of rank 0 and at least one of them is an @code{ra::} object, they is no way to preserve the behavior of @code{&&} and @code{||} with built in types and avoid evaluating both, since the overloaded operators @url{http://en.cppreference.com/w/cpp/language/operators, are normal functions}.}, @code{>}, @code{<}, @code{>=}, @code{<=}, @code{<=>}, @code{==}, @code{!=}, @code{pow}, @code{sqr}, @code{abs}, @code{cos}, @code{sin}, @code{exp}, @code{expm1}, @code{sqrt}, @code{log}, @code{log1p}, @code{log10}, @code{isfinite}, @code{isnan}, @code{isinf}, @code{max}, @code{min}, @code{odd}, @code{asin}, @code{acos}, @code{atan}, @code{atan2}, @code{cosh}, @code{sinh}, and @code{tanh}.
  1044. Extending other scalar operations is straightforward; see @ref{x-new-array-operations,New array operations}. @code{ra::} also defines (and extends) the non-standard functions @ref{x-sqr,@code{sqr}}, @ref{x-sqrm,@code{sqrm}}, @ref{x-conj,@code{conj}}, @ref{x-rel-error,@code{rel_error}}, and @ref{x-xI,@code{xI}}.
  1045. For example:
  1046. @example @c [ma110]
  1047. @verbatim
  1048. cout << exp(ra::Small<double, 3> {4, 5, 6}) << endl;
  1049. @end verbatim
  1050. @print{} 54.5982 148.413 403.429
  1051. @end example
  1052. @subsection Conditional operations
  1053. @ref{x-map,@code{map}} evaluates all of its arguments before passing them along to its operator. This isn't always what you want. The simplest example is @code{where(condition, iftrue, iffalse)}, which returns an expression that will evaluate @code{iftrue} when @code{condition} is true and @code{iffalse} otherwise.
  1054. @example
  1055. @verbatim
  1056. ra::Big<double> x ...
  1057. ra::Big<double> y = where(x>0, expensive_expr_1(x), expensive_expr_2(x));
  1058. @end verbatim
  1059. @end example
  1060. Here @code{expensive_expr_1} and @code{expensive_expr_2} are array expressions. So the computation of the other arm would be wasted if one were to do instead
  1061. @example
  1062. @verbatim
  1063. ra::Big<double> y = map([](auto && w, auto && t, auto && f) -> decltype(auto) { return w ? t : f; }
  1064. x>0, expensive_expr_1(x), expensive_function_2(x));
  1065. @end verbatim
  1066. @end example
  1067. If the expressions have side effects, then @code{map} won't even give the right result.
  1068. @c [ma109]
  1069. @example
  1070. @verbatim
  1071. ra::Big<int, 1> o = {};
  1072. ra::Big<int, 1> e = {};
  1073. ra::Big<int, 1> n = {1, 2, 7, 9, 12};
  1074. ply(where(odd(n), map([&o](auto && x) { o.push_back(x); }, n), map([&e](auto && x) { e.push_back(x); }, n)));
  1075. cout << "o: " << ra::noshape << o << ", e: " << ra::noshape << e << endl;
  1076. @end verbatim
  1077. @print{} o: 1 7 9, e: 2 12
  1078. @end example
  1079. FIXME Very artificial example.
  1080. FIXME Do we want to expose ply(); this is the only example in the manual that uses it.
  1081. When the choice is between more than two expressions, there's @ref{x-pick,@code{pick}}, which operates similarly.
  1082. @subsection Special operations
  1083. Some operations are essentially scalar operations, but require special syntax and would need a lambda wrapper to be used with @code{map}. @code{ra::} comes with a few of these already defined.
  1084. FIXME
  1085. @subsection Elementwise reductions
  1086. @code{ra::} defines the whole-array one-argument reductions @code{any}, @code{every}, @code{amax}, @code{amin}, @code{sum}, @code{prod} and the two-argument reductions @code{dot} and @code{cdot}. Note that @code{max} and @code{min} are two-argument scalar operations with array extensions, while @code{amax} and @code{amin} are reductions. @code{any} and @code{every} are short-circuiting.
  1087. You can define similar reductions in the same way that @code{ra::} does it:
  1088. @example
  1089. @verbatim
  1090. template <class A>
  1091. inline auto op_reduce(A && a)
  1092. {
  1093. T c = op_default;
  1094. for_each([&c](auto && a) { c = op(c, a); }, a);
  1095. return c;
  1096. }
  1097. @end verbatim
  1098. @end example
  1099. Often enough you need to reduce over particular axes. This is possible by combining assignment operators with the @ref{Rank extension,rank extension} mechanism, or using the @ref{The rank conjunction,rank conjunction}, or iterating over @ref{Cell iteration, cells of higher rank}. For example:
  1100. @example
  1101. @verbatim
  1102. ra::Big<double, 2> a({m, n}, ...);
  1103. ra::Big<double, 1> sum_rows({n}, 0.);
  1104. iter<1>(sum_rows) += iter<1>(a);
  1105. // for_each(ra::wrank<1, 1>([](auto & c, auto && a) { c += a; }), sum_rows, a) // alternative
  1106. // sum_rows += transpose<1, 0>(a); // another
  1107. ra::Big<double, 1> sum_cols({m}, 0.);
  1108. sum_cols += a;
  1109. @end verbatim
  1110. @end example
  1111. FIXME example with assignment op
  1112. A few common operations of this type are already packaged in @code{ra::}.
  1113. @subsection Special reductions
  1114. @code{ra::} defines the following special reductions.
  1115. FIXME
  1116. @subsection Shortcut reductions
  1117. Some reductions do not need to traverse the whole array if a certain condition is encountered early. The most obvious ones are the reductions of @code{&&} and @code{||}, which @code{ra::} defines as @code{every} and @code{any}.
  1118. FIXME
  1119. These operations are defined on top of another function @code{early}.
  1120. FIXME early
  1121. The following is often useful.
  1122. FIXME lexicographical compare etc.
  1123. @cindex error
  1124. @cindex assert
  1125. @c ------------------------------------------------
  1126. @node Error handling
  1127. @section Error handling
  1128. @c ------------------------------------------------
  1129. Error handling in @code{ra::} is barebones. It is controlled by two macros:
  1130. @itemize
  1131. @item @code{RA_DO_CHECK}
  1132. is a binary flag that controls runtime checks. The default is 1. The checks themselves are done with @code{RA_ASSERT}.
  1133. @item @code{RA_ASSERT(cond, ...)}
  1134. is a function-like macro. @code{cond} an expression that evaluates to true (in the @code{ra::} namespace) if the check passes. The other arguments are informative and may or may not be used. The default defintion of @code{RA_ASSERT(cond, ...)} is @code{assert(cond)}, from @code{<cassert>}.
  1135. @end itemize
  1136. @code{ra::} contains uses of @code{assert} for checking invariants or for sanity checks that are separate from uses of @code{RA_ASSERT}. Those can be disabled in the usual way with @code{-DNDEBUG}. The use of @code{-DNDEBUG} is untested.
  1137. You can redefine @code{RA_ASSERT} to something that is more appropriate for your program. @code{examples/throw.cc} in the distribution shows how to throw an user-defined exception instead.
  1138. @c ------------------------------------------------
  1139. @node Extras
  1140. @chapter Extras
  1141. @c ------------------------------------------------
  1142. @c ------------------------------------------------
  1143. @node Hazards
  1144. @chapter Hazards
  1145. @c ------------------------------------------------
  1146. Some of these issues arise because @code{ra::} applies its principles systematically, which can have surprising results. Still others are the result of unfortunate compromises. And a few are just bugs.
  1147. @section Reuse of expression objects
  1148. Expression objects are meant to be used once. This applies to anything produced with @code{ra::map}, @code{ra::iter}, @code{ra::start}, @code{ra::vector}, or @code{ra::ptr}. Reuse errors are @emph{not} checked. For example:
  1149. @example
  1150. @verbatim
  1151. ra::Big<int, 2> B({3, 3}, ra::_1 + ra::_0*3); // {{0 1 2} {3 4 5} {6 7 8}}
  1152. std::array<int, 2> l = { 1, 2 };
  1153. cout << B(ra::vector(l), ra::vector(l)) << endl; // ok => {{4 5} {7 8}}
  1154. auto ll = ra::vector(l);
  1155. cout << B(ll, ll) << endl; // ??
  1156. @end verbatim
  1157. @end example
  1158. @section Assignment to views
  1159. FIXME
  1160. With dynamic-shape containers (e.g. @code{Big}), @code{operator=} replaces the left hand side instead of writing over its contents. This behavior is inconsistent with @code{View::operator=} and is there only so that istream >> container may work; do not rely on it.
  1161. @section View of const vs const view
  1162. @c See branches ra-viewconst / viewp [ra47]
  1163. FIXME
  1164. Passing view arguments by reference
  1165. @section Rank extension in assignments
  1166. Assignment of an expression onto another expression of lower rank may not do what you expect. This example matches @code{a} and 3 [both of shape ()] with a vector of shape (3). This is equivalent to @code{@{a=3+4; a=3+5; a=3+6;@}}. You may get a different result depending on traversal order.
  1167. @example @c [ma107]
  1168. @verbatim
  1169. int a = 0;
  1170. ra::scalar(a) = 3 + ra::Small<int, 3> {4, 5, 6}; // ?
  1171. @end verbatim
  1172. @result{} a = 9
  1173. @end example
  1174. Compare with
  1175. @example
  1176. @verbatim
  1177. int a = 0;
  1178. ra::scalar(a) += 3 + ra::Small<int, 3> {4, 5, 6}; // 0 + 3 + 4 + 5 + 6
  1179. @end verbatim
  1180. @result{} a = 18
  1181. @end example
  1182. @section Performance pitfalls of rank extension
  1183. In the following example where @code{b} has its shape extended from (3) to (3, 4), @code{f} is called 12 times, even though only 3 calls are needed if @code{f} doesn't have side effects. In such cases it might be preferrable to write the outer loop explicitly, or to do some precomputation.
  1184. @example
  1185. @verbatim
  1186. ra::Big<int, 2> a = {{1, 2, 3, 4}, {5, 6, 7, 8} {9, 10, 11, 12}};
  1187. ra::Big<int, 1> b = {1, 2, 3};
  1188. ra::Big<int, 2> c = map(f, b) + a;
  1189. @end verbatim
  1190. @end example
  1191. @section Chained assignment
  1192. FIXME
  1193. When @code{a=b=c} works, it operates as @code{b=c; a=b;} and not as an array expression.
  1194. @section Unregistered scalar types
  1195. FIXME
  1196. @code{View<T, N> x; x = T()} fails if @code{T} isn't registered as @code{is_scalar}.
  1197. @enumerate
  1198. @item
  1199. Item 0
  1200. @item
  1201. Item 1
  1202. @item
  1203. Item 2
  1204. @end enumerate
  1205. @c ------------------------------------------------
  1206. @node Internals
  1207. @chapter Internals
  1208. @c ------------------------------------------------
  1209. @code{ra::} has two main components: a set of container classes, and the expression template mechanism. The container classes provide leaves for the expression template trees, and the container classes also make some use of the expression template mechanism internally (e.g. in the selection operator, or for initialization).
  1210. @menu
  1211. * Type hierarchy:: From @code{Containers} to @code{Flat}.
  1212. * Term agreement:: Abstain or approve.
  1213. * Loop types:: Chosen for performance.
  1214. * Introspection:: Speaking to myself.
  1215. * Compiling and running:: Practical matters.
  1216. @end menu
  1217. @c ------------------------------------------------
  1218. @node Type hierarchy
  1219. @section Type hierarchy
  1220. @c ------------------------------------------------
  1221. This is a rough and possibly not very accurate summary. I'm hoping the planned feature of ‘C++ concepts’ will force me to be more systematic about it all.
  1222. @itemize
  1223. @item @b{Container} --- @code{Big} @code{Shared} @code{Unique} @code{Small}
  1224. These are array types that own their data in one way or another. Creating or destroying these objects may allocate or deallocate memory, respectively.
  1225. @item @b{View} --- @code{View} @code{SmallView}
  1226. These are array views into data in memory. Access to their contents doesn't involve computation and they may be writable. Any of the @b{Container} types can be treated as a @b{View}, but one may also create @b{View}s that aren't associated with any @b{Container}, for example into memory allocated by a different library. Creating and destroying @b{View}s doesn't allocate or deallocate memory for array elements.
  1227. @item @b{RaIterator} --- @code{Expr} @code{Pick} @code{cell_iterator} @code{cell_iterator_small} @code{Iota} @code{Vector} @code{Scalar}
  1228. This is a traversable object. @b{RaIterator}s are accepted by all the array functions such as @code{map}, @code{for_each}, etc. @code{map} produces an @b{RaIterator} itself, so most array expressions are @b{RaIterator}s. @b{RaIterator}s are created from @b{View}s and from certain foreign array-like types primarily through the function @code{start}. This is done automatically when those types are used in array expressions.
  1229. @item @b{Ravelable} --- @code{cell_iterator} @code{cell_iterator_small} @code{Iota} @code{Vector} @code{Scalar} @code{TensorIndex}
  1230. This is a kind of @b{RaIterator} that provides a @code{flat()} method to obtain a linearized view of a section of the array. Together with the methods @code{size()}, @code{stride()}, @code{keep_stride()} and @code{adv()}, a loop involving only @b{Ravelable}s can have its inner loop unfolded and traversed using @b{Flat} objects. This is faster than a multidimensional loop, especially if the inner dimensions of the loop are small.
  1231. @item @b{Indexable} @code{cell_iterator} @code{cell_iterator_small} @code{Iota} @code{Vector} @code{Scalar} @code{TensorIndex}
  1232. This is a kind of @b{RaIterator} that provides an @code{at(i ...)} method for random access to any element of the array. In the current version of @code{ra::}, every @b{RaIterator} is both @b{Ravelable} and @b{Indexable}.
  1233. @item @b{Flat} @code{Flat} @code{PickFlat} @code{CellFlat} @code{IotaFlat} @code{ScalarFlat}
  1234. These are types that support ‘forward iterator’ traversal. They have methods @code{operator+=} (to advance) and @code{operator*} (to derreference). @b{Flat} objects are obtained from @b{Ravelable} objects through a method @code{flat}.
  1235. @end itemize
  1236. @c ------------------------------------------------
  1237. @node Term agreement
  1238. @section Term agreement
  1239. @c ------------------------------------------------
  1240. The execution of an expression template begins with the determination of its shape — the size of each of its dimensions. This is done recursively by traversing the terms of the expression. For a given dimension @code{k}≥0, terms that have rank less or equal than @code{k} are ignored, following the prefix matching principle. Likewise terms where dimension @code{k} has undefined size (such as @code{TensorIndex} or view axes created with @code{insert}) are ignored. All the other terms must match.
  1241. Then we select a traversal method depending on the types of the arguments. @code{ra::} has two traversal methods, both based on pointer-like iterators. @code{ply_ravel} is used for dynamic-size expressions and @code{plyf} for static-size expressions.
  1242. Finally we select an order of traversal. @code{ra::} supports ‘array’ orders, meaning that the dimensions are sorted in a certain way from outermost to innermost and a full dimension is traversed before one advances on the dimension outside. However, currently (v14) there is no heuristic to choose a dimension order, so traversal always happens in row-major order (which shouldn't be relied upon). @code{ply_ravel} will unroll as many innermost dimensions as it can, and in some cases traversal will be executed as a single 1D loop.
  1243. @c ------------------------------------------------
  1244. @node Loop types
  1245. @section Loop types
  1246. @c ------------------------------------------------
  1247. TODO
  1248. @c ------------------------------------------------
  1249. @node Introspection
  1250. @section Introspection
  1251. @c ------------------------------------------------
  1252. @c ------------------------------------------------
  1253. @node Compiling and running
  1254. @section Compiling and running
  1255. @c ------------------------------------------------
  1256. The following boolean @code{#define}s affect the behavior of @code{ra::}.
  1257. @itemize
  1258. @item @code{RA_DO_CHECK} (default 1): Check bounds on dimension agreement (e.g. @code{Big<int, 1> @{2, 3@} + Big<int, 1> @{1, 2, 3@}}) and random array accesses (e.g. @code{Small<int, 2> a = 0; int i = 10; a[i] = 0;}).
  1259. @item @code{RA_USE_BLAS} (default 0): Try to use BLAS for certain rank 1 and rank 2 operations. Currently this is only used by some of the benchmarks and not by the library itself.
  1260. @item @code{RA_DO_OPT} (default 1): Replace certain expressions by others that are expected to perform better. This acts as a global mask on other @code{RA_DO_OPT_xxx} flags.
  1261. @item @code{RA_DO_OPT_IOTA} (default 1): Perform immediately (beat) certain operations on @code{ra::Iota} objects. For example, @code{ra::Iota(3, 0) + 1} becomes @code{ra::Iota(3, 1)} instead of a two-operand expression template.
  1262. @item @code{RA_DO_OPT_SMALLVECTOR} (default 0): Perform immediately certain operations on @code{ra::Small} objects, using small vector intrinsics. Currently this only works on @b{gcc} and doesn't necessarily result in improved performance.
  1263. @end itemize
  1264. @code{ra::} comes with three kinds of tests: examples, proper tests, and benchmarks. @code{ra::} uses its own crude test and benchmark suites. Run @code{CXXFLAGS=-O3 scons} from the top directory of the distribution to build and run them all. Alternatively, you can use @code{CXXFLAGS=-O3 cmake . && make && make test}.
  1265. TODO Flags and notes about different compilers
  1266. @c ------------------------------------------------
  1267. @node The future
  1268. @chapter The future
  1269. @c ------------------------------------------------
  1270. @section Error messages
  1271. FIXME
  1272. @section Reductions
  1273. FIXME
  1274. @section Etc
  1275. FIXME
  1276. @c ------------------------------------------------
  1277. @node Reference
  1278. @chapter Reference
  1279. @c ------------------------------------------------
  1280. @anchor{x-map} @defun map op expr ...
  1281. Create an array expression that applies @var{op} to @var{expr} ...
  1282. @end defun
  1283. For example:
  1284. @example
  1285. @verbatim
  1286. ra::Big<double, 1> x = map(cos, ra::Small<double, 1> {0.});
  1287. @end verbatim
  1288. @result{} x = @{ 1. @}
  1289. @end example
  1290. @var{op} can return a reference. A typical use is subscripting. For example (TODO better example, e.g. using STL types):
  1291. @example
  1292. @verbatim
  1293. ra::Big<int, 2> x = {{3, 3}, 0.};
  1294. map([](auto && i, auto && j) -> int & { return x(i, j); },
  1295. ra::Big<int, 1> {0, 1, 1, 2}, ra::Big<int, 1> {1, 0, 2, 1})
  1296. = 1;
  1297. @end verbatim
  1298. @result{} x = @{@{0, 1, 0@}, @{1, 0, 1@}, @{0, 1, 0@}@}
  1299. @end example
  1300. Here the anonymous function can be replaced by simply @code{x}. Remember that unspecified return type defaults to (value) @code{auto}, so either a explicit type or @code{decltype(auto)} should be used if you want to return a reference.
  1301. @cindex @code{for_each}
  1302. @anchor{x-for_each} @defun for_each op expr ...
  1303. Create an array expression that applies @var{op} to @var{expr} ..., and traverse it.
  1304. @end defun
  1305. @var{op} is run for effect; whatever it returns is discarded. For example:
  1306. @example
  1307. @verbatim
  1308. double s = 0.;
  1309. for_each([&s](auto && a) { s+=a; }, ra::Small<double, 1> {1., 2., 3})
  1310. @end verbatim
  1311. @result{} s = 6.
  1312. @end example
  1313. @cindex @code{ply}
  1314. @anchor{x-ply} @defun ply expr
  1315. Traverse @var{expr}. @code{ply} returns @code{void} so @var{expr} should be run for effect.
  1316. @end defun
  1317. It is rarely necessary to use @code{ply}. Expressions are traversed automatically when they are assigned to views, for example, or printed out. @ref{x-for_each,@code{for_each}}@code{(...)} (which is actually @code{ply(map(...))} should cover most other uses.
  1318. @example
  1319. @verbatim
  1320. double s = 0.;
  1321. ply(map([&s](auto && a) { s+=a; }, ra::Small<double, 1> {1., 2., 3})) // same as for_each
  1322. @end verbatim
  1323. @result{} s = 6.
  1324. @end example
  1325. @cindex @code{pack}
  1326. @anchor{x-pack} @defun pack <type> expr ...
  1327. Create an array expression that brace-constructs @var{type} from @var{expr} ...
  1328. @end defun
  1329. @cindex @code{cast}
  1330. @anchor{x-cast} @defun cast <type> expr
  1331. Create an array expression that casts @var{expr} into @var{type}.
  1332. @end defun
  1333. @cindex @code{pick}
  1334. @anchor{x-pick} @defun pick select_expr expr ...
  1335. Create an array expression that selects the first of @var{expr} ... if @var{select_expr} is 0, the second if @var{select_expr} is 1, and so on. The expressions that are not selected are not looked up.
  1336. @end defun
  1337. This function cannot be defined using @ref{x-map,@code{map}}, because @code{map} looks up each one of its argument expressions before calling @var{op}.
  1338. For example:
  1339. @example @c cf examples/readme.cc [ma100].
  1340. @verbatim
  1341. ra::Small<int, 3> s {2, 1, 0};
  1342. ra::Small<double, 3> z = pick(s, s*s, s+s, sqrt(s));
  1343. @end verbatim
  1344. @result{} z = @{1.41421, 2, 0@}
  1345. @end example
  1346. @cindex @code{where}
  1347. @anchor{x-where} @defun where pred_expr true_expr false_expr
  1348. Create an array expression that selects @var{true_expr} if @var{pred_expr} is @code{true}, and @var{false_expr} if @var{pred_expr} is @code{false}. The expression that is not selected is not looked up.
  1349. @end defun
  1350. For example:
  1351. @example
  1352. @verbatim
  1353. ra::Big<double, 1> s {1, -1, 3, 2};
  1354. s = where(s>=2, 2, s); // saturate s
  1355. @end verbatim
  1356. @result{} s = @{1, -1, 2, 2@}
  1357. @end example
  1358. @cindex @code{from}
  1359. @anchor{x-from} @defun from op ... expr
  1360. Create outer product expression. This is defined as @math{E = from(op, e₀, e₁ ...)} ⇒ @math{E(i₀₀, i₀₁ ..., i₁₀, i₁₁, ..., ...) = op[e₀(i₀₀, i₀₁, ...), e₁(i₁₀, i₁₁, ...), ...]}.
  1361. @end defun
  1362. For example:
  1363. @example
  1364. @verbatim
  1365. ra::Big<double, 1> a {1, 2, 3};
  1366. ra::Big<double, 1> b {10, 20, 30};
  1367. ra::Big<double, 2> axb = from([](auto && a, auto && b) { return a*b; }, a, b)
  1368. @end verbatim
  1369. @result{} axb = @{@{10, 20, 30@}, @{20, 40, 60@}, @{30, 60, 90@}@}
  1370. @end example
  1371. @example
  1372. @verbatim
  1373. ra::Big<int, 1> i {2, 1};
  1374. ra::Big<int, 1> j {0, 1};
  1375. ra::Big<double, 2> A = {{1, 2}, {3, 4}, {5, 6}};
  1376. ra::Big<double, 2> Aij = from(A, i, j)
  1377. @end verbatim
  1378. @result{} Aij = @{@{6, 5@}, @{4, 3@}@}
  1379. @end example
  1380. The last example is more or less how @code{A(i, j)} is actually implemented (@pxref{The rank conjunction}).
  1381. @cindex @code{at}
  1382. @anchor{x-at} @defun at expr indices
  1383. Look up @var{expr} at each element of @var{indices}, which shall be a multi-index into @var{expr}.
  1384. @end defun
  1385. This can be used for sparse subscripting. For example:
  1386. @example @c [ra30]
  1387. @verbatim
  1388. ra::Big<int, 2> A = {{100, 101}, {110, 111}, {120, 121}};
  1389. ra::Big<ra::Small<int, 2>, 2> i = {{{0, 1}, {2, 0}}, {{1, 0}, {2, 1}}};
  1390. ra::Big<int, 2> B = at(A, i);
  1391. @end verbatim
  1392. @result{} B = @{@{101, 120@}, @{110, 121@}@}
  1393. @end example
  1394. @cindex @code{shape}
  1395. @anchor{x-shape} @defun shape a
  1396. Get the shape of an @code{ra::} object.
  1397. @end defun
  1398. The shape of a dynamic rank array is a rank-1 object with dynamic size, and the shape of a static rank array is a rank-1 object with static size.
  1399. This function may return an expression object or an array object. If you need to operate on the result, it might be necessary to use @code{concrete}.
  1400. @c FIXME example
  1401. @cindex @code{size}
  1402. @anchor{x-size} @defun size a
  1403. Get the total size of an @code{ra::} object: the product of all its sizes.
  1404. @end defun
  1405. @c FIXME example
  1406. @cindex @code{concrete}
  1407. @anchor{x-concrete} @defun concrete a
  1408. Convert the argument to a container of the same rank and size as @code{a}.
  1409. @end defun
  1410. If the argument has dynamic or static shape, it is the same for the result. The main use of this function is to obtain modifiable copy of an array expression without having to prepare a container beforehand, or compute the appropiate type.
  1411. @c FIXME example
  1412. @cindex @code{wrank}
  1413. @anchor{x-wrank} @defun wrank <input_rank ...> op
  1414. Wrap op using a rank conjunction (@pxref{The rank conjunction}).
  1415. @end defun
  1416. For example: TODO
  1417. @example
  1418. @verbatim
  1419. @end verbatim
  1420. @result{} x = 0
  1421. @end example
  1422. @cindex @code{transpose}
  1423. @anchor{x-transpose}
  1424. @defun transpose <axes ...> (view) | (axes, view)
  1425. Create a new view by transposing the axes of @var{view}. The number of @var{axes} must match the rank of @var{view}.
  1426. @end defun
  1427. For example:
  1428. @example
  1429. @verbatim
  1430. ra::Unique<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  1431. cout << transpose<1, 0>(a) << endl;
  1432. @end verbatim
  1433. @print{}
  1434. 3 2
  1435. 1 4
  1436. 2 5
  1437. 3 6
  1438. @end example
  1439. The rank of the result is @code{maxᵢ(axesᵢ)+1} and it may be smaller or larger than that of @var{view}. If an axis is repeated, the smallest of the dimensions of @var{view} is used. For example:
  1440. @example
  1441. @verbatim
  1442. ra::Unique<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  1443. cout << transpose<0, 0>(a) << endl; // { a(0, 0), a(1, 1) }
  1444. @end verbatim
  1445. @print{}
  1446. 2
  1447. 1 5
  1448. @end example
  1449. If one of the destination axes isn't mentioned in @var{axes}, then is a ‘dead’ axis similar to those produced by @ref{x-insert,@code{insert}}. For example:
  1450. @example
  1451. @verbatim
  1452. ra::Unique<double, 1> a = {1, 2, 3};
  1453. cout << ((a*10) + transpose<1>(a)) << endl;
  1454. @end verbatim
  1455. @print{}
  1456. 3 3
  1457. 11 21 31
  1458. 12 22 32
  1459. 13 23 33
  1460. @end example
  1461. The two argument form lets you specify the axis list dynamically. In that case the result will have dynamic rank as well. For example: @c [ma117]
  1462. @example
  1463. @verbatim
  1464. ra::Small<int, 2> axes = {0, 1};
  1465. ra::Unique<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  1466. cout << "A: " << transpose(axes, a) << endl;
  1467. axes = {1, 0};
  1468. cout << "B: " << transpose(axes, a) << endl;
  1469. @end verbatim
  1470. @print{}
  1471. A: 2
  1472. 2 3
  1473. 1 2 3
  1474. 4 5 6
  1475. B: 2
  1476. 3 2
  1477. 1 4
  1478. 2 5
  1479. 3 6
  1480. @end example
  1481. This operation does not work on arbitrary array expressions yet. TODO FILL
  1482. @cindex @code{diag}
  1483. @anchor{x-diag} @defun diag view
  1484. Equivalent to @code{transpose<0, 0>(view)}.
  1485. @end defun
  1486. @cindex @code{reverse}
  1487. @anchor{x-reverse} @defun reverse view axis
  1488. Create a new view by reversing axis @var{k} of @var{view}.
  1489. @end defun
  1490. This is equivalent to @code{view(ra::dots<k>, ra::iota(view.size(k), view.size(k)-1, -1))}.
  1491. This operation does not work on arbitrary array expressions yet. TODO FILL
  1492. @c @anchor{x-reshape}
  1493. @c @defun reshape view shape
  1494. @c Create a new view with shape @var{shape} from the row-major ravel of @var{view}.
  1495. @c @end defun
  1496. @c FIXME fill when the implementation is more mature...
  1497. @c @anchor{x-ravel}
  1498. @c @defun ravel view
  1499. @c Return the ravel of @var{view} as a view on @var{view}.
  1500. @c @end defun
  1501. @c FIXME fill when the implementation is more mature...
  1502. @cindex @code{stencil}
  1503. @anchor{x-stencil} @defun stencil view lo hi
  1504. Create a stencil on @var{view} with lower bounds @var{lo} and higher bounds @var{hi}.
  1505. @end defun
  1506. @var{lo} and @var{hi} are expressions of rank 1 indicating the extent of the stencil on each dimension. Scalars are rank extended, that is, @var{lo}=0 is equivalent to @var{lo}=(0, 0, ..., 0) with length equal to the rank @code{r} of @var{view}. The stencil view has twice as many axes as @var{view}. The first @code{r} dimensions are the same as those of @var{view} except that they have their sizes reduced by @var{lo}+@var{hi}. The last @code{r} dimensions correspond to the stencil around each element of @var{view}; the center element is at @code{s(i0, i1, ..., lo(0), lo(1), ...)}.
  1507. This operation does not work on arbitrary array expressions yet. TODO FILL
  1508. @cindex @code{collapse}
  1509. @anchor{x-collapse} @defun collapse
  1510. TODO
  1511. @end defun
  1512. @cindex @code{explode}
  1513. @anchor{x-explode} @defun explode
  1514. TODO
  1515. @end defun
  1516. @cindex @code{real_part}
  1517. @anchor{x-real_part} @defun real_part
  1518. Take real part of a complex number. This can be used as reference.
  1519. See also @ref{x-imag_part,@code{imag_part}}.
  1520. @end defun
  1521. @cindex @code{imag_part}
  1522. @anchor{x-imag_part} @defun imag_part
  1523. Take imaginary part of a complex number. This can be used as reference.
  1524. For example: @c [ma115]
  1525. @example
  1526. @verbatim
  1527. ra::Small<std::complex<double>, 2, 2> A = {{1., 2.}, {3., 4.}};
  1528. imag_part(A) = -2*real_part(A);
  1529. cout << A << endl;
  1530. @end verbatim
  1531. @print{}
  1532. (1, -2) (2, -4)
  1533. (3, -6) (4, -8)
  1534. @end example
  1535. See also @ref{x-real_part,@code{real_part}}.
  1536. @end defun
  1537. @cindex @code{format_array}
  1538. @anchor{x-format_array} @defun format_array expr [last_axis_separator [second_last_axis_separator ...]]
  1539. Formats an array for character output.
  1540. For example:
  1541. @example
  1542. @verbatim
  1543. ra::Small<int, 2, 2> A = {{1, 2}, {3, 4}};
  1544. cout << "case a:\n" << A << endl;
  1545. cout << "case b:\n" << format_array(A) << endl;
  1546. cout << "case c:\n" << format_array(A, "|", "-") << endl;
  1547. @end verbatim
  1548. @print{} case a:
  1549. 1 2
  1550. 3 4
  1551. case b:
  1552. 1 2
  1553. 3 4
  1554. case c:
  1555. 1|2-3|4
  1556. @end example
  1557. @end defun
  1558. The shape that might be printed before the expression itself (depending on its type) is not subject to these separators. See @ref{x-noshape,@code{noshape}}, @ref{x-withshape,@code{withshape}}.
  1559. @cindex @code{noshape}
  1560. @cindex @code{withshape}
  1561. @anchor{x-noshape}
  1562. @anchor{x-withshape}
  1563. @deffn @w{Special object} {withshape noshape}
  1564. If either of these objects is sent to @code{std::ostream} before an expression object, the shape of that object will or won't be printed.
  1565. @end deffn
  1566. If the object has static (compile time) shape, the default is not to print the shape, so @code{noshape} isn't necessary, and conversely for @code{withshape} if the object has dynamic (runtime) shape. Note that the array readers [@code{operator>>(std::istream &, ...)}] expect the shape to be present or not according to the default.
  1567. For example:
  1568. @example
  1569. @verbatim
  1570. ra::Small<int, 2, 2> A = {77, 99};
  1571. cout << "case a:\n" << A << endl;
  1572. cout << "case b:\n" << ra::noshape << A << endl;
  1573. cout << "case c:\n" << ra::withshape << A << endl;
  1574. @end verbatim
  1575. @print{} case a:
  1576. 77 99
  1577. case b:
  1578. 77 99
  1579. case c:
  1580. 2
  1581. 77 99
  1582. @end example
  1583. but:
  1584. @example
  1585. @verbatim
  1586. ra::Big<int> A = {77, 99};
  1587. cout << "case a:\n" << A << endl;
  1588. cout << "case b:\n" << ra::noshape << A << endl;
  1589. cout << "case c:\n" << ra::withshape << A << endl;
  1590. @end verbatim
  1591. @print{} case a:
  1592. 1
  1593. 2
  1594. 77 99
  1595. case b:
  1596. 77 99
  1597. case c:
  1598. 1
  1599. 2
  1600. 77 99
  1601. @end example
  1602. Note that in the last example the very shape of @code{ra::Big<int>} has runtime size, so that size (the rank of @code{A}, that is 1) is printed as part of the shape of @code{A}.
  1603. See also @ref{x-format_array,@code{format_array}}.
  1604. @cindex @code{start}
  1605. @anchor{x-start} @defun start foreign_object
  1606. Create a array expression from @var{foreign_object}.
  1607. @end defun
  1608. @var{foreign_object} can be of type @code{std::vector} or @code{std::array}, a built-in array (@code{int[3]}, etc.) or an initializer list, or any object that @code{ra::} accepts as scalar (see @ref{x-is-scalar,@code{here}}). The resulting expresion has rank and size according to the original object. Compare this with @ref{x-scalar,@code{scalar}}, which will always produce an expression of rank 0.
  1609. Generally one can mix these types with @code{ra::} expressions without needing @code{ra::start}, but sometimes this isn't possible, for example for operators that must be class members.
  1610. @example
  1611. @verbatim
  1612. std::vector<int> x = {1, 2, 3};
  1613. ra::Big<int, 1> y = {10, 20, 30};
  1614. cout << (x+y) << endl; // same as ra::start(x)+y
  1615. // x += y; // error: no match for operator+=
  1616. ra::start(x) += y; // ok
  1617. @end verbatim
  1618. @print{} 3
  1619. 11 22 33
  1620. @result{} x = @{ 11, 22, 33 @}
  1621. @end example
  1622. @cindex @code{ptr}
  1623. @anchor{x-ptr} @defun ptr pointer [size]
  1624. Create vector expression from raw @var{pointer}.
  1625. @end defun
  1626. The resulting expression has rank 1 and the size given. If @code{size} is not given, the expression has undefined size, and it will need to be matched with other expressions whose size @emph{is} defined.
  1627. @code{ra::} doesn't know what is actually accessible through the pointer, so be careful. For instance:
  1628. @example
  1629. @verbatim
  1630. int p[] = {1, 2, 3};
  1631. ra::Big<int, 1> v3 {1, 2, 3};
  1632. ra::Big<int, 1> v4 {1, 2, 3, 4};
  1633. v3 += ra::ptr(p); // ok, shape (3): v3 = {2, 4, 6}
  1634. v4 += ra::ptr(p); // undefined, shape (4): bad access to p[3]
  1635. // cout << (ra::ptr(p)+ra::TensorIndex<0>{}) << endl; // ct error, expression has undefined shape
  1636. cout << (ra::ptr(p, 3)+ra::TensorIndex<0>{}) << endl; // ok, prints { 1, 3, 5 }
  1637. cout << (ra::ptr(p, 4)+ra::TensorIndex<0>{}) << endl; // undefined, bad access at p[4]
  1638. @end verbatim
  1639. @end example
  1640. Of course in this example one could simply have used @code{p} instead of @code{ra::ptr(p)}, since the array type retains size information.
  1641. @example
  1642. @verbatim
  1643. v3 += p; // ok
  1644. v4 += p; // error checked by ra::, shape clash (4) += (3)
  1645. cout << (p + ra::TensorIndex<0>{}) << endl; // ok
  1646. @end verbatim
  1647. @end example
  1648. @cindex @code{scalar}
  1649. @anchor{x-scalar} @defun scalar expr
  1650. Create scalar expression from @var{expr}.
  1651. @end defun
  1652. The primary use of this function is to bring a scalar object into the @code{ra::} namespace. A somewhat artificial example:
  1653. @example
  1654. @verbatim
  1655. struct W { int x; }
  1656. ra::Big<W, 1> w { {1}, {2}, {3} };
  1657. // error: no matching function for call to start(W)
  1658. // for_each([](auto && a, auto && b) { cout << (a.x + b.x) << endl; }, w, W {7});
  1659. // bring W into ra:: with ra::scalar
  1660. for_each([](auto && a, auto && b) { cout << (a.x + b.x) << endl; }, w, ra::scalar(W {7}));
  1661. @end verbatim
  1662. @print{} 8
  1663. 9
  1664. 10
  1665. @end example
  1666. See also @ref{x-scalar-char-star,@code{this example}}.
  1667. Since @code{scalar} produces an object with rank 0, it's also useful when dealing with nested arrays, even for objects that are already in @code{ra::}. Consider:
  1668. @example
  1669. @verbatim
  1670. using Vec2 = ra::Small<double, 2>;
  1671. Vec2 x {-1, 1};
  1672. ra::Big<Vec2, 1> c { {1, 2}, {2, 3}, {3, 4} };
  1673. // c += x // error: x has shape (2) and c has shape (3)
  1674. c += ra::scalar(x); // ok: scalar(x) has shape () and matches c.
  1675. @end verbatim
  1676. @result{} c = @{ @{0, 3@}, @{1, 4@}, @{2, 5@} @}
  1677. @end example
  1678. The result is @{c(0)+x, c(1)+x, c(2)+x@}. Compare this with
  1679. @example
  1680. @verbatim
  1681. c(ra::iota(2)) += x; // c(ra::iota(2)) with shape (2) matches x with shape (2)
  1682. @end verbatim
  1683. @result{} c = @{ @{-1, 2@}, @{2, 5@}, @{2, 5@} @}
  1684. @end example
  1685. where the result is @{c(0)+x(0), c(1)+x(1), c(2)@}.
  1686. @cindex @code{iter}
  1687. @anchor{x-iter} @defun iter <k> (view)
  1688. Create iterator over the @var{k}-cells of @var{view}. If @var{k} is negative, it is interpreted as the negative of the frame rank. In the current version of @code{ra::}, @var{view} may have dynamic or static shape.
  1689. @end defun
  1690. @example
  1691. @verbatim
  1692. ra::Big<int, 2> c {{1, 3, 2}, {7, 1, 3}};
  1693. cout << "max of each row: " << map([](auto && a) { return amax(a); }, iter<1>(c)) << endl;
  1694. ra::Big<int, 1> m({3}, 0);
  1695. scalar(m) = max(scalar(m), iter<1>(c));
  1696. cout << "max of each column: " << m << endl;
  1697. m = 0;
  1698. for_each([&m](auto && a) { m = max(m, a); }, iter<1>(c));
  1699. cout << "max of each column again: " << m << endl;
  1700. @end verbatim
  1701. @print{} max of each row: 2
  1702. 3 7
  1703. max of each column: 3
  1704. 7 3 3
  1705. max of each column again: 3
  1706. 7 3 3
  1707. @end example
  1708. @c [ma113]
  1709. In the following example, @code{iter} emulates @code{scalar}. Note that the shape () of @code{iter<1>(m)} matches the shape (3) of @code{iter<1>(c)}. Thus, each of the 1-cells of @code{c} matches against the single 1-cell of @code{m}.
  1710. @example
  1711. @verbatim
  1712. m = 0;
  1713. iter<1>(m) = max(iter<1>(m), iter<1>(c));
  1714. cout << "max of each column yet again: " << m << endl;
  1715. @end verbatim
  1716. @print{} max of each column again: 3
  1717. 7 3 3
  1718. @end example
  1719. The following example computes the trace of each of the items [(-1)-cells] of @code{c}. @c [ma104]
  1720. @example
  1721. @verbatim
  1722. ra::Small<int, 3, 2, 2> c = ra::_0 - ra::_1 - 2*ra::_2;
  1723. cout << "c: " << c << endl;
  1724. cout << "s: " << map([](auto && a) { return sum(diag(a)); }, iter<-1>(c)) << endl;
  1725. @end verbatim
  1726. @print{} c: 0 -2
  1727. -1 -3
  1728. 1 -1
  1729. 0 -2
  1730. 2 0
  1731. 1 -1
  1732. s: -3 -1 -1
  1733. @end example
  1734. @cindex @code{sum}
  1735. @anchor{x-sum} @defun sum expr
  1736. Return the sum (+) of the elements of @var{expr}, or 0 if expr is empty. This sum is performed in unspecified order.
  1737. @end defun
  1738. @cindex @code{prod}
  1739. @anchor{x-prod} @defun prod expr
  1740. Return the product (*) of the elements of @var{expr}, or 1 if expr is empty. This product is performed in unspecified order.
  1741. @end defun
  1742. @cindex @code{amax}
  1743. @anchor{x-amax} @defun amax expr
  1744. Return the maximum of the elements of @var{expr}. If @var{expr} is empty, return @code{-std::numeric_limits<T>::infinity()} if the type supports it, otherwise @code{std::numeric_limits<T>::lowest()}, where @code{T} is the value type of the elements of @var{expr}.
  1745. @end defun
  1746. @cindex @code{amin}
  1747. @anchor{x-amin} @defun amin expr
  1748. Return the minimum of the elements of @var{expr}. If @var{expr} is empty, return @code{+std::numeric_limits<T>::infinity()} if the type supports it, otherwise @code{std::numeric_limits<T>::max()}, where @code{T} is the value type of the elements of @var{expr}.
  1749. @end defun
  1750. @cindex @code{early}
  1751. @anchor{x-early} @defun early expr default
  1752. @var{expr} shall be an array expression that returns @code{std::tuple<bool, T>}. @var{expr} is traversed as by @code{for_each}; if the expression ever returns @code{true} in the first element of the tuple, traversal stops and the second element is returned. If this never happens, @var{default} is returned instead.
  1753. @end defun
  1754. The following definition of elementwise @code{lexicographical_compare} relies on @code{early}.
  1755. @example @c [ma108]
  1756. @verbatim
  1757. template <class A, class B>
  1758. inline bool lexicographical_compare(A && a, B && b)
  1759. {
  1760. return early(map([](auto && a, auto && b)
  1761. { return a==b ? std::make_tuple(false, true) : std::make_tuple(true, a<b); },
  1762. a, b),
  1763. false);
  1764. }
  1765. @end verbatim
  1766. @end example
  1767. @cindex @code{any}
  1768. @anchor{x-any} @defun any expr
  1769. Return @code{true} if any element of @var{expr} is true, @code{false} otherwise. The traversal of the array expression will stop as soon as possible, but the traversal order is not specified.
  1770. @end defun
  1771. @cindex @code{every}
  1772. @anchor{x-every} @defun every expr
  1773. Return @code{true} if every element of @var{expr} is true, @code{false} otherwise. The traversal of the array expression will stop as soon as possible, but the traversal order is not specified.
  1774. @end defun
  1775. @cindex @code{sqr}
  1776. @anchor{x-sqr} @defun sqr expr
  1777. Compute the square of @var{expr}.
  1778. @end defun
  1779. @cindex @code{sqrm}
  1780. @anchor{x-sqrm} @defun sqrm expr
  1781. Compute the square of the norm-2 of @var{expr}, that is, @code{conj(expr)*expr}.
  1782. @end defun
  1783. @cindex @code{conj}
  1784. @anchor{x-conj} @defun conj expr
  1785. Compute the complex conjugate of @var{expr}.
  1786. @end defun
  1787. @cindex @code{xI}
  1788. @anchor{x-xI} @defun xI expr
  1789. Compute @code{(0+1j)} times @var{expr}.
  1790. @end defun
  1791. @cindex @code{rel_error}
  1792. @anchor{x-rel-error} @defun rel_error a b
  1793. @var{a} and @var{b} are arbitrary array expressions. Compute the error of @var{a} relative to @var{b} as
  1794. @code{(a==0. && b==0.) ? 0. : 2.*abs(a, b)/(abs(a)+abs(b))}
  1795. @end defun
  1796. @cindex @code{none}
  1797. @anchor{x-none}
  1798. @deffn @w{Special object} {none}
  1799. Pass @code{none} to container constructors to indicate that the contents shouldn't be initialized. This is appropriate when the initialization you have in mind wouldn't fit in a constructor argument. For example:
  1800. @example
  1801. @verbatim
  1802. void old_style_initializer(int m, int n, double *);
  1803. ra::Big<double> b({2, 3}, ra::none);
  1804. old_style_initializer(2, 3, b.data());
  1805. @end verbatim
  1806. @end example
  1807. @end deffn
  1808. @c ------------------------------------------------
  1809. @node @mybibnode{}
  1810. @chapter Sources
  1811. @c ------------------------------------------------
  1812. @multitable @columnfractions .1 .9
  1813. @item @mybibitem{Abr70} @tab Philip S. Abrams. An APL machine. Technical report SLAC-114 UC-32 (MISC), Stanford Linear Accelerator Center, Stanford University, Stanford, CA, USA, February 1970.
  1814. @item @mybibitem{Ber87} @tab Robert Bernecky. An introduction to function rank. ACM SIGAPL APL Quote Quad, 18(2):39–43, December 1987.
  1815. @item @mybibitem{bli17} @tab The Blitz++ meta-template library. @url{http://blitz.sourceforge.net}, November 2017.
  1816. @item @mybibitem{Cha86} @tab Gregory J. Chaitin. Physics in APL2, June 1986.
  1817. @item @mybibitem{FI68} @tab Adin D. Falkoff and Kenneth Eugene Iverson. APL\360 User’s manual. IBM Thomas J. Watson Research Center, August 1968.
  1818. @item @mybibitem{FI73} @tab Adin D. Falkoff and Kenneth Eugene Iverson. The design of APL. IBM Journal of Research and Development, 17(4):5–14, July 1973.
  1819. @item @mybibitem{FI78} @tab Adin D. Falkoff and Kenneth Eugene Iverson. The evolution of APL. ACM SIGAPL APL, 9(1):30– 44, 1978.
  1820. @item @mybibitem{J S} @tab J Primer. J Software, @url{https://www.jsoftware.com/help/primer/contents.htm}, November 2017.
  1821. @item @mybibitem{Mat} @tab MathWorks. MATLAB documentation, @url{https://www.mathworks.com/help/matlab/}, November 2017.
  1822. @item @mybibitem{num17} @tab NumPy. @url{http://www.numpy.org}, November 2017.
  1823. @item @mybibitem{Ric08} @tab Henry Rich. J for C programmers, February 2008.
  1824. @item @mybibitem{SSM14} @tab Justin Slepak, Olin Shivers, and Panagiotis Manolios. An array-oriented language with static rank polymorphism. In Z. Shao, editor, ESOP 2014, LNCS 8410, pages 27–46, 2014.
  1825. @item @mybibitem{Vel01} @tab Todd Veldhuizen. Blitz++ user’s guide, February 2001.
  1826. @item @mybibitem{Wad90} @tab Philip Wadler. Deforestation: transforming programs to eliminate trees. Theoretical Computer Science, 73(2): 231--248, June 1990. @url{https://doi.org/10.1016/0304-3975%2890%2990147-A}
  1827. @end multitable
  1828. @c ------------------------------------------------
  1829. @node Indices
  1830. @unnumbered Indices
  1831. @c ------------------------------------------------
  1832. @c @node Concept Index
  1833. @c @unnumbered Concept Index
  1834. @printindex cp
  1835. @c @node Function Index
  1836. @c @unnumbered Function Index
  1837. @c @printindex fn
  1838. @c \nocite{JLangReference,FalkoffIverson1968,Abrams1970,FalkoffIverson1973,FalkoffIverson1978,APLexamples1,ArraysCowan,KonaTheLanguage,blitz++2001}
  1839. @c ------------------------------------------------
  1840. @node Notes
  1841. @unnumbered Notes
  1842. @c ------------------------------------------------
  1843. @enumerate
  1844. @item
  1845. @code{ra::} uses the following features that are not standard (but that all major compilers support): @code{#pragma once}, and @code{__COUNTER__}.
  1846. @end enumerate
  1847. @bye