ra-ra.texi 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609
  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 25
  13. @set UPDATED 2023 November 1
  14. @copying
  15. @code{ra::} (version @value{VERSION}, updated @value{UPDATED})
  16. (c) Daniel Llorens 2005--2023
  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. @cindex length
  64. @cindex rank
  65. @cindex shape
  66. 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 of all the @dfn{lengths} (n₀, n₁, ... nᵣ₋₁) is the @dfn{shape} of the array. We speak of a rank-@math{r} array or of an @math{r}-array.
  67. 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.
  68. Arrays (as a representation of @dfn{matrices}, @dfn{vectors}, or @dfn{tensors}) are common objects in math and programming, and it is very useful to be able to manipulate arrays as individual entities rather than as aggregates. Not only is
  69. @verbatim
  70. A = B+C;
  71. @end verbatim
  72. much more compact and easier to read than
  73. @verbatim
  74. for (int i=0; i!=m; ++i)
  75. for (int j=0; j!=n; ++j)
  76. for (int k=0; k!=p; ++k)
  77. A(i, j, k) = B(i, j, k)+C(i, j, k);
  78. @end verbatim
  79. but it's also safer and less redundant. For example, the order of the loops may be something you don't really care about.
  80. 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}. This is wasteful if the arrays involved are large.
  81. @cindex Blitz++
  82. 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.
  83. @menu
  84. * Rank polymorphism:: What makes arrays special.
  85. * Drag along and beating:: The basic array optimizations.
  86. * Why C++:: High level, low level.
  87. * Guidelines:: How @code{ra::} tries to do things.
  88. * Other libraries:: Inspiration and desperation.
  89. @end menu
  90. @c ------------------------------------------------
  91. @node Rank polymorphism
  92. @section Rank polymorphism
  93. @c ------------------------------------------------
  94. @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.
  95. @cindex cell
  96. @cindex frame
  97. For example, think of a matrix A, a 2-array with shape (n₀, n₁) where the elements A(i₀, i₁) are numbers. If we consider the subarrays A(0, ...), A(1, ...), ..., A(n₀-1, ...) as individual elements, then we have a new view of A as a 1-array of length 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}.
  98. 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
  99. @quotation
  100. A: [A(0), A(1), ...]
  101. @end quotation
  102. and the items of A(i₀), etc. are in turn stored in the same way, so
  103. @quotation
  104. A: [A(0): [A(0, 0), A(0, 1) ...], ...]
  105. @end quotation
  106. and the same for the items of A(i₀, i₁), etc.
  107. @quotation
  108. A: [[A(0, 0): [A(0, 0, 0), A(0, 0, 1) ...], A(0, 1): [A(0, 1, 0), A(0, 1, 1) ...]], ...]
  109. @end quotation
  110. @cindex order, row-major
  111. 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 shape (n₀, n₁, ... nᵣ₋₁) can be looked up like this:
  112. @anchor{x-steps}
  113. @quotation
  114. A(i₀, i₁, ...) = (storage-of-A) [(((i₀n₁ + i₁)n₂ + i₂)n₃ + ...)+iᵣ₋₁] = (storage-of-A) [o + s₀i₀ + s₁i₁ + ...]
  115. @end quotation
  116. @cindex step
  117. @cindex stride
  118. where the numbers (s₀, s₁, ...) are called the @dfn{steps}@footnote{Sometimes `strides'. 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
  119. @quotation
  120. A ≡ ((storage-of-A), o, (s₀, s₁, ...))
  121. @end quotation
  122. 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 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.
  123. A basic example is obtaining the i₀-th item of A:
  124. @quotation
  125. A(i₀) ≡ ((storage-of-A), o+s₀i₀, (s₁, ...))
  126. @end quotation
  127. 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}).
  128. @c ------------------------------------------------
  129. @node Drag along and beating
  130. @section Drag along and beating
  131. @c ------------------------------------------------
  132. These two fundamental array optimizations are described in @mybibcite{Abr70}.
  133. @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.
  134. @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-steps,step} 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.
  135. @c ------------------------------------------------
  136. @node Why C++
  137. @section Why C++
  138. @c ------------------------------------------------
  139. 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.
  140. 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.
  141. @cindex APL
  142. @cindex J
  143. 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.
  144. 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.
  145. In C++, a library is enough.
  146. @c ------------------------------------------------
  147. @node Guidelines
  148. @section Guidelines
  149. @c ------------------------------------------------
  150. @code{ra::} attempts to be general, consistent, and transparent.
  151. @c @cindex J # TODO makeinfo can't handle an entry appearing more than once (it creates multiple entries in the index).
  152. 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.
  153. 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 it makes sense. 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.
  154. Sometimes consistency requires a choice. For example, given array views A and B, @code{A=B} copies the contents of view @code{B} into view @code{A}. To change view @code{A} instead (to treat @code{A} as a pointer) would be the default meaning of @code{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.
  155. Transparency is achieved by avoiding unnecessary abstraction. An array view consists of a pointer and a list of steps and I see no point in hiding it. Manipulating the steps 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.
  156. 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 usable 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 in compact columns, or that the real parts are interleaved with the imaginary parts.
  157. @c ------------------------------------------------
  158. @node Other libraries
  159. @section Other array libraries
  160. @c ------------------------------------------------
  161. 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.
  162. 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++!
  163. @subsection Standard C++
  164. 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 shape or rank at runtime, and are generally too limited.
  165. 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.
  166. @code{ra::} accepts built-in arrays and standard library types as array objects (@pxref{Compatibility}).
  167. @subsection Blitz++
  168. @cindex Blitz++
  169. 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 runtime rank. It also supported small arrays with compile time shape (@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.
  170. However, the implementation had to fight the limitations of C++98, and it offered no general rank extension mechanism.
  171. 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 (data-owning) types are values, and views are distinct types. 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.
  172. @subsection Other C++ libraries
  173. TODO
  174. @subsection Other languages
  175. TODO Maybe review other languages, at least the big ones (Fortran / APL / J / Matlab / Python-Numpy).
  176. @c ------------------------------------------------
  177. @node Usage
  178. @chapter Usage
  179. @c ------------------------------------------------
  180. 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}.
  181. @menu
  182. * Using the library:: @code{ra::} is a header-only library.
  183. * Containers and views:: Data objects.
  184. * Array operations:: Building and traversing expressions.
  185. * Rank extension:: How array operands are matched.
  186. * Cell iteration:: At any rank.
  187. * Slicing:: Subscripting is a special operation.
  188. * Special objects:: Not arrays, yet arrays.
  189. * Functions:: Ready to go.
  190. * The rank conjunction:: J comes to C++.
  191. * Compatibility:: With the STL and other libraries.
  192. * Extension:: Using your own types and more.
  193. * Error handling:: What to check and what to do.
  194. @end menu
  195. @c ------------------------------------------------
  196. @node Using the library
  197. @section Using @code{ra::}
  198. @c ------------------------------------------------
  199. @code{ra::} is a header only library with no dependencies other than the standard library, 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.
  200. A compiler with C++20 support is required. For the current version this means at least @b{gcc 11} with @option{-std=c++20}. Some C++23 features are available with @option{-std=c++2b}. Check the top @code{README.md} for more up-to-date information.
  201. Here is a minimal program@footnote{Examples given without context assume that one has declared @code{using std::cout;}, etc.}:
  202. @example @c readme.cc [ma101]
  203. @verbatim
  204. #include "ra/ra.hh"
  205. #include <iostream>
  206. int main()
  207. {
  208. ra::Big<char, 2> A({2, 5}, "helloworld");
  209. std::cout << ra::noshape << format_array(transpose<1, 0>(A), "|") << std::endl;
  210. }
  211. @end verbatim
  212. @print{} h|w
  213. e|o
  214. l|r
  215. l|l
  216. d|d
  217. @end example
  218. The following headers are @emph{not} included by default:
  219. @itemize
  220. @item @code{"ra/dual.hh"}: A dual number type for simple uses of automatic differentiation.
  221. @item @code{"ra/test.hh"}, @code{"ra/bench.hh"}: Used by the test and benchmark suites.
  222. @end itemize
  223. The header @code{"ra/bootstrap.hh"} can be used to configure @ref{Error handling}. You don't need to modify the header, but the configuration depends on including @code{"ra/bootstrap.hh"} before the rest of @code{ra::}. All other headers are for internal use by @code{ra::}.
  224. @cindex container
  225. @c ------------------------------------------------
  226. @node Containers and views
  227. @section Containers and views
  228. @c ------------------------------------------------
  229. @code{ra::} offers two kinds of data objects. The first kind, the @dfn{container}, owns its data. Creating a container uses up memory and destroying it causes that memory to be freed.
  230. @cindex compile-time
  231. @cindex ct
  232. @cindex runtime
  233. @cindex rt
  234. There are three kinds of containers (ct: compile-time, rt: runtime): 1) ct size, 2) ct rank/rt shape, and 3) rt rank; rt rank implies rt shape. Some rt size arrays can be resized but rt rank arrays cannot normally have their rank changed. Instead, you create a new container or view with the rank you want.
  235. For example:
  236. @example
  237. @verbatim
  238. {
  239. ra::Small<double, 2, 3> a(0.); // a ct size 2x3 array
  240. ra::Big<double, 2> b({2, 3}, 0.); // a rt size 2x3 array
  241. ra::Big<double> c({2, 3}, 0.); // a rt rank 2x3 array
  242. // a, b, c destroyed at end of scope
  243. }
  244. @end verbatim
  245. @end example
  246. Using the right kind of container can result in better performance. Ct shapes do not need to be stored in memory, which matters when you have many small arrays. Ct shape or ct rank arrays are also safer to use; sometimes @code{ra::} will be able to detect errors in the shapes or ranks of array operands at compile time, if the appropriate types are used.
  247. 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 rt rank, because in the C++ grammar, a nested initializer list doesn't always define a rank unambiguously.}
  248. @c [ma111]
  249. @example
  250. @verbatim
  251. using ra::Small, ra::Big;
  252. Small<int, 2, 2> a = {{1, 2}, {3, 4}}; // explicit contents
  253. Big<int, 2> a1 = {{1, 2}, {3, 4}}; // explicit contents
  254. Small<int, 2, 2> a2 = {{1, 2}}; // error: bad shape
  255. Small<int, 2, 2> b = 7; // 7 is copied into b
  256. Small<int, 2, 2> c = a; // the contents of a are copied into c
  257. Big<int> d = a; // d takes the shape of a and a is copied into d
  258. Big<int> e = 0; // e is a 0-array with one element f()==0.
  259. @end verbatim
  260. @end example
  261. The second form takes two arguments, one giving the shape, the second the contents.
  262. @cindex @code{none}
  263. @cindex uninitialized container
  264. @example
  265. @verbatim
  266. ra::Big<double, 2> a({2, 3}, 1.); // a has shape [2 3], filled with 1.
  267. ra::Big<double> b({2, 3}, ra::none); // b has shape [2 3], default initialized
  268. ra::Big<double> c({2, 3}, a); // c has shape [2 3], a is copied into c
  269. @end verbatim
  270. @end example
  271. 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.
  272. The shape argument can have rank 0 only for rank 1 arrays.
  273. @cindex @code{none}
  274. @cindex uninitialized container
  275. @example
  276. @verbatim
  277. ra::Big<int> c(3, 0); // ok {0, 0, 0}, same as ra::Big<int> c({3}, 0)
  278. ra::Big<int, 1> c(3, 0); // ok {0, 0, 0}, same as ra::Big<int, 1> c({3}, 0)
  279. ra::Big<int, 2> c({3}, 0); // error: bad length for shape
  280. ra::Big<int, 2> c(3, 0); // error: bad length for shape
  281. @end verbatim
  282. @end example
  283. 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 shape-strict —you must give every element.}
  284. @cindex order, column-major
  285. @example
  286. @verbatim
  287. Small<int, 2, 2> aa = {1, 2, 3, 4}; // ravel of the content
  288. ra::Big<double, 2> a({2, 3}, {1, 2, 3, 4, 5, 6}); // same as a = {{1, 2, 3}, {4, 5, 6}}
  289. @end verbatim
  290. @end example
  291. @c [ma112]
  292. @example
  293. @verbatim
  294. double bx[6] = {1, 2, 3, 4, 5, 6}
  295. ra::Big<double, 2> b({3, 2}, bx); // {{1, 2}, {3, 4}, {5, 6}}
  296. double cx[4] = {1, 2, 3, 4}
  297. ra::Big<double, 2> c({3, 2}, cx); // *** WHO NOSE ***
  298. @end verbatim
  299. @end example
  300. @c [ma114]
  301. @example
  302. @verbatim
  303. using lens = mp::int_list<2, 3>;
  304. using steps = mp::int_list<1, 2>;
  305. ra::SmallArray<double, lens, steps> a {{1, 2, 3}, {4, 5, 6}}; // stored column-major: 1 4 2 5 3 6
  306. @end verbatim
  307. @end example
  308. These produce compile time errors:
  309. @example
  310. @verbatim
  311. Big<int, 2> b = {1, 2, 3, 4}; // error: shape cannot be deduced from ravel
  312. Small<int, 2, 2> b = {1, 2, 3, 4 5}; // error: bad size
  313. Small<int, 2, 2> b = {1, 2, 3}; // error: bad size
  314. @end verbatim
  315. @end example
  316. @anchor{x-scalar-char-star}
  317. Sometimes the pointer constructor gets in the way (see @ref{x-scalar,@code{scalar}}): @c [ma102]
  318. @example
  319. @verbatim
  320. ra::Big<char const *, 1> A({3}, "hello"); // error: try to convert char to char const *
  321. ra::Big<char const *, 1> A({3}, ra::scalar("hello")); // ok, "hello" is a single item
  322. cout << ra::noshape << format_array(A, "|") << endl;
  323. @end verbatim
  324. @print{} hello|hello|hello
  325. @end example
  326. @cindex view
  327. 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:
  328. @example
  329. @verbatim
  330. ra::Big<double> c({2, 3}, 0.); // a rt rank 2x3 array
  331. {
  332. auto c1 = c(1); // the second row of array c
  333. // c1 is destroyed here
  334. }
  335. cout << c(1, 1) << endl; // ok
  336. @end verbatim
  337. @end example
  338. The data accessed through a view is the data of the ‘root’ container, so modifying the former will be reflected in the latter.
  339. @example
  340. @verbatim
  341. ra::Big<double> c({2, 3}, 0.);
  342. auto c1 = c(1);
  343. c1(2) = 9.; // c(1, 2) = 9.
  344. @end verbatim
  345. @end example
  346. Just as for containers, there are separate types of views depending on whether the shape is known at compile time, the rank is known at compile time but the shape is not, or neither the shape nor the rank are known at compile time. @code{ra::} has functions to create the most common kinds of views:
  347. @example
  348. @verbatim
  349. ra::Big<double> c {{1, 2, 3}, {4, 5, 6}};
  350. auto ct = transpose<1, 0>(c); // {{1, 4}, {2, 5}, {3, 6}}
  351. auto cr = reverse(c, 0); // {{4, 5, 6}, {1, 2, 3}}
  352. @end verbatim
  353. @end example
  354. However, views can point to anywhere in memory and that memory doesn't have to belong to an @code{ra::} container. For example:
  355. @example
  356. @verbatim
  357. int raw[6] = {1, 2, 3, 4, 5, 6};
  358. ra::View<int> v1({{2, 3}, {3, 1}}, raw); // view with shape [2, 3] steps [3, 1]
  359. ra::View<int> v2({2, 3}, raw); // same, default C (row-major) steps
  360. @end verbatim
  361. @end example
  362. Containers can be treated as views of the same kind (rt or ct) . If you declare a function
  363. @example
  364. @verbatim
  365. void f(ra::View<int, 3> & v);
  366. @end verbatim
  367. @end example
  368. you may pass it an object of type @code{ra::Big<int, 3>}.
  369. @c ------------------------------------------------
  370. @node Array operations
  371. @section Array operations
  372. @c ------------------------------------------------
  373. 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.
  374. @example
  375. @verbatim
  376. ra::Small<double, 2, 3> a = {{1, 2, 3}, {4, 5, 6}};
  377. double s = 0.;
  378. for_each([&s](auto && a) { s+=a; }, a);
  379. @end verbatim
  380. @result{} s = 21.
  381. @end example
  382. 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.
  383. @example
  384. @verbatim
  385. using T = ra::Small<double, 2, 2>;
  386. T a = {{1, 2}, {3, 4}};
  387. T b = {{10, 20}, {30, 40}};
  388. T c = map([](auto && a, auto && b) { return a+b; }, a, b); // (1)
  389. @end verbatim
  390. @result{} c = @{@{11, 22@}, @{33, 44@}@}
  391. @end example
  392. Expressions may take any number of arguments and be nested arbitrarily.
  393. @example
  394. @verbatim
  395. T d = 0;
  396. for_each([](auto && a, auto && b, auto && d) { d = a+b; },
  397. a, b, d); // same as (1)
  398. for_each([](auto && ab, auto && d) { d = ab; },
  399. map([](auto && a, auto && b) { return a+b; },
  400. a, b),
  401. d); // same as (1)
  402. @end verbatim
  403. @end example
  404. 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.
  405. @example
  406. @verbatim
  407. T d = 0;
  408. map([](auto & d) -> decltype(auto) { return d; }, d) // just pass d along
  409. = map([](auto && a, auto && b) { return a+b; }, a, b); // same as (1)
  410. @end verbatim
  411. @end example
  412. @code{ra::} defines many shortcuts for common array operations. You can of course just do:
  413. @example
  414. @verbatim
  415. T c = a+b; // same as (1)
  416. @end verbatim
  417. @end example
  418. @c ------------------------------------------------
  419. @node Rank extension
  420. @section Rank extension
  421. @c ------------------------------------------------
  422. 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.
  423. 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
  424. @quotation
  425. @code{(R+S)(i₀ i₁ ... i₍ᵣ₋₁₎) = R(i₀ i₁ ... i₍ᵣ₋₁₎) + S(i₀ i₁ ... i₍ᵣ₋₁₎)}
  426. @end quotation
  427. where @code{r} is the rank of @code{R}.
  428. 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
  429. @quotation
  430. @code{(R+S)(i₀ i₁ ... i₍ᵣ₋₁₎) = R(i₀ i₁ ... i₍ᵣ₋₁₎) + S()}.
  431. @end quotation
  432. 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
  433. @quotation
  434. @code{(R+S)(i₀ i₁ ... i₍ₛ₋₁₎ ... i₍ᵣ₋₁₎) = R(i₀ i₁ ... i₍ₛ₋₁₎ ... i₍ᵣ₋₁₎) + S(i₀ i₁ ... i₍ₛ₋₁₎)}.
  435. @end quotation
  436. That is, after we run out of indices in @code{S}, we simply repeat the elements. We have aligned the shapes so:
  437. @quotation
  438. @verbatim
  439. [n₀ n₁ ... n₍ₛ₋₁₎ ... n₍ᵣ₋₁₎]
  440. [n₀ n₁ ... n₍ₛ₋₁₎]
  441. @end verbatim
  442. @end quotation
  443. @cindex shape agreement, prefix
  444. @cindex shape agreement, suffix
  445. @c @cindex J
  446. @cindex Numpy
  447. 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.}.
  448. 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,
  449. @example
  450. @verbatim
  451. ra::Small<int, 3> x {3, 5, 9};
  452. ra::Small<int, 3, 2> a = x; // assign x(i) to each a(i, j)
  453. @end verbatim
  454. @result{} a = @{@{3, 3@}, @{5, 5@}, @{9, 9@}@}
  455. @end example
  456. @example
  457. @verbatim
  458. ra::Small<int, 3> x(0.);
  459. ra::Small<int, 3, 2> a = {{1, 2}, {3, 4}, {5, 6}};
  460. x += a; // sum the rows of a
  461. @end verbatim
  462. @result{} x = @{3, 7, 11@}
  463. @end example
  464. @example
  465. @verbatim
  466. ra::Big<double, 3> a({5, 3, 3}, ra::_0);
  467. ra::Big<double, 1> b({5}, 0.);
  468. b += transpose<0, 1, 1>(a); // b(i) = ∑ⱼ a(i, j, j)
  469. @end verbatim
  470. @result{} b = @{0, 3, 6, 9, 12@}
  471. @end example
  472. @cindex Numpy
  473. @cindex broadcasting, singleton, newaxis
  474. 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 length 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.
  475. A drawback of singleton broadcasting is that it muddles the distinction between a scalar and a vector of length 1. Sometimes, an axis of length 1 is no more than that, and if 2≠3 is a size mismatch, it isn't obvious why 1≠2 shouldn't be. To avoid this problem, @code{ra::} supports broadcasting with undefined length axes (see @ref{x-insert,@code{insert}}).
  476. @example
  477. @verbatim
  478. ra::Big<double, 3> a({5, 3}, ra::_0);
  479. ra::Big<double, 1> b({3}, 0.);
  480. ra::Big<double, 3> c({1, 3}, ra::_0);
  481. // b(?, i) += a(j, i) → b(i) = ∑ⱼ a(j, i) (sum columns)
  482. b(ra::insert<1>) += a;
  483. c = a; // 1 ≠ 5, still an agreement error
  484. @end verbatim
  485. @end example
  486. Still another way to align array axes is provided by the @ref{The rank conjunction,rank conjunction}.
  487. Even with axis insertion, it is still necessary that the axes one wishes to match are in the same order in all the arguments.
  488. @ref{x-transpose,Transposing} the axes before extension is a possible workaround.
  489. @c ------------------------------------------------
  490. @node Cell iteration
  491. @section Cell iteration
  492. @c ------------------------------------------------
  493. @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:
  494. @example
  495. @verbatim
  496. ra::Big<double, 3> a({5, 4, 3}, ra::_0);
  497. for_each([](auto && b) { /* b has shape (5 4 3) */ }, iter<3>(a));
  498. for_each([](auto && b) { /* b has shape (4 3) */ }, iter<2>(a));
  499. for_each([](auto && b) { /* b has shape (3) */ }, iter<1>(a));
  500. for_each([](auto && b) { /* b has shape () */ }, iter<0>(a)); // elements
  501. for_each([](auto && b) { /* b has shape () */ }, a); // same as iter<0>(a); default
  502. @end verbatim
  503. @end example
  504. One may specify the @emph{frame} rank instead:
  505. @example
  506. @verbatim
  507. for_each([](auto && b) { /* b has shape () */ }, iter<-3>(a)); // same as iter<0>(a)
  508. for_each([](auto && b) { /* b has shape (3) */ }, iter<-2>(a)); // same as iter<1>(a)
  509. for_each([](auto && b) { /* b has shape (4 3) */ }, iter<-1>(a)); // same as iter<2>(a)
  510. @end verbatim
  511. @end example
  512. In this way it is possible to match shapes in various ways. Compare
  513. @example
  514. @verbatim
  515. ra::Big<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  516. ra::Big<double, 1> b = {10, 20};
  517. ra::Big<double, 2> c = a * b; // multiply (each item of a) by (each item of b)
  518. @end verbatim
  519. @result{} a = @{@{10, 20, 30@}, @{80, 100, 120@}@}
  520. @end example
  521. with
  522. @example @c [ma105]
  523. @verbatim
  524. ra::Big<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  525. ra::Big<double, 1> b = {10, 20, 30};
  526. ra::Big<double, 2> c({2, 3}, 0.);
  527. iter<1>(c) = iter<1>(a) * iter<1>(b); // multiply (each item of a) by (b)
  528. @end verbatim
  529. @result{} a = @{@{10, 40, 90@}, @{40, 100, 180@}@}
  530. @end example
  531. 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.
  532. 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}).
  533. FIXME More examples.
  534. @c ------------------------------------------------
  535. @node Slicing
  536. @section Slicing
  537. @c ------------------------------------------------
  538. 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.
  539. 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@footnote{The multi-argument square bracket form @code{A[i₀, i₁, ...]} is supported under C++23 compilers (e.g. gcc ≥ 12 with @code{-std=c++2b}), with the same meaning as @code{A(i₀, i₁, ...)}. Under C++20 only a single-argument square bracket form @code{A[i₀]} is available.}. An array extension is immediately available through @code{map}. For example:
  540. @example
  541. @verbatim
  542. ra::Big<double, 1> a = {1., 2., 3., 4.};
  543. ra::Big<int, 1> i = {1, 3};
  544. map(a, i) = 77.;
  545. @end verbatim
  546. @result{} a = @{1., 77., 3, 77.@}
  547. @end example
  548. Just as with any use of @code{map}, array arguments are subject to the prefix agreement rule.
  549. @example
  550. @verbatim
  551. ra::Big<double, 2> a({2, 2}, {1., 2., 3., 4.});
  552. ra::Big<int, 1> i = {1, 0};
  553. ra::Big<double, 1> b = map(a, i, 0);
  554. @end verbatim
  555. @result{} b = @{3., 1.@} // @{a(1, 0), a(0, 0)@}
  556. @end example
  557. @example
  558. @verbatim
  559. ra::Big<int, 1> j = {0, 1};
  560. b = map(a, i, j);
  561. @end verbatim
  562. @result{} b = @{3., 2.@} // @{a(1, 0), a(0, 1)@}
  563. @end example
  564. The latter is a form of sparse subscripting.
  565. 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:
  566. @example
  567. @verbatim
  568. ra::Big<double, 2> A {{1., 2.}, {3., 4.}};
  569. ra::Big<int, 1> i = {1, 0};
  570. ra::Big<int, 1> j = {0, 1};
  571. // {{A(i₀, j₀), A(i₀, j₁)}, {A(i₁, j₀), A(i₁, j₁)}}
  572. ra::Big<double, 2> b = A(i, j);
  573. @end verbatim
  574. @result{} b = @{@{3., 4.@}, @{1., 2.@}@}
  575. @end example
  576. @anchor{x-subscript-outer-product}
  577. @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 ...)}.
  578. @cindex elision, index
  579. You may give fewer subscripts than the rank of the array. The full extent is assumed for the missing subscripts (cf @ref{x-all,@code{all}} below):
  580. @example
  581. @verbatim
  582. ra::Big<int, 3> a({2, 2, 2}, {1, 2, 3, 4, 5, 6, 7, 8});
  583. auto a0 = a(0); // same as a(0, ra::all, ra::all)
  584. auto a10 = a(1, 0); // same as a(1, 0, ra::all)
  585. @end verbatim
  586. @result{} a0 = @{@{1, 2@}, @{3, 4@}@}
  587. @result{} a10 = @{5, 6@}
  588. @end example
  589. 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}).
  590. Besides, when the subscripts @code{i, j, ...} are scalars or integer sequences of the form @code{(o, o+s, ..., o+s*(n-1))} (@dfn{linear ranges}), 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}}.
  591. @code{ra::} isn't smart enough to know when an arbitrary expression might be a linear range, so the following special objects are provided:
  592. @anchor{x-iota}
  593. @deffn @w{Special object} iota count [start:0 [step:1]]
  594. Create a linear range @code{start, start+step, ... start+step*(count-1)}.
  595. This can used anywhere an array expression is expected.
  596. @example
  597. @verbatim
  598. ra::Big<int, 1> a = ra::iota(4, 3 -2);
  599. @end verbatim
  600. @result{} a = @{3, 1, -1, -3@}
  601. @end example
  602. Here, @code{b} and @code{c} are @code{View}s (@pxref{Containers and views}).
  603. @example
  604. @verbatim
  605. ra::Big<int, 1> a = {1, 2, 3, 4, 5, 6};
  606. auto b = a(iota(3));
  607. auto c = a(iota(3, 3));
  608. @end verbatim
  609. @result{} a = @{1, 2, 3@}
  610. @result{} a = @{4, 5, 6@}
  611. @end example
  612. @cindex TensorIndex
  613. @code{iota()} by itself is an expression of rank 1 and undefined length. It must be used with other terms whose lengths are defined, so that the overall shape of the array expression can be determined. In general, @code{iota<n>()} is an array expression of rank @code{n}+1 that represents the @code{n}-th index of an array expression. This is similar to Blitz++'s @code{TensorIndex}.
  614. @code{ra::} offers the shortcut @code{ra::_0} for @code{ra::iota<0>()}, etc.
  615. @example
  616. @verbatim
  617. ra::Big<int, 1> v = {1, 2, 3};
  618. cout << (v - ra::_0) << endl; // { 1-0, 2-1, 3-2 }
  619. // cout << (ra::_0) << endl; // error: undefined length
  620. // cout << (v - ra::_1) << endl; // error: undefined length on axis 1
  621. ra::Big<int, 2> a({3, 2}, 0);
  622. cout << (a + ra::_0 - ra::_1) << endl; // {{0, -1, -2}, {1, 0, -1}, {2, 1, 0}}
  623. @end verbatim
  624. @end example
  625. When undefined length @code{iota()} is used as a subscript by itself, the result isn't a @code{View}. This allows @code{view(iota())} to match with expressions of different lengths, as in the following example.
  626. @example
  627. @verbatim
  628. ra::Big<int, 1> a = {1, 2, 3, 4, 5, 6};
  629. ra::Big<int, 1> b = {1, 2, 3};
  630. cout << (b + a(iota())) << endl; // a(iota()) is not a View
  631. @end verbatim
  632. @print{} 3
  633. 2 4 6
  634. @end example
  635. Note the difference between
  636. @itemize
  637. @item @code{ra::iota<3>()} —
  638. an expression of rank 4 and undefined length, representing a linear sequence over the tensor index of axis 3
  639. @item @code{ra::iota(3)} ≡ @code{ra::iota<0>(3)} —
  640. an expression of rank 1, representing the sequence @code{0, 1, 2}.
  641. @end itemize
  642. @end deffn
  643. @anchor{x-all}
  644. @deffn @w{Special object} all
  645. Create a linear range @code{0, 1, ... (nᵢ-1)} when used as a subscript at the @var{i}-th place of a subscripting expression. This might not be the @var{i}-th argument; see @ref{x-insert,@code{insert}}, @ref{x-dots,@code{dots}}.
  646. This object cannot stand alone as an array expression. All the examples below result in @code{View} objects:
  647. @example
  648. @verbatim
  649. ra::Big<int, 2> a({3, 2}, {1, 2, 3, 4, 5, 6});
  650. auto b = a(ra::all, ra::all); // (1) a view of the whole of a
  651. auto c = a(iota(3), iota(2)); // same as (1)
  652. auto d = a(iota(3), ra::all); // same as (1)
  653. auto e = a(ra:all, iota(2)); // same as (1)
  654. auto f = a(0, ra::all); // first row of a
  655. auto g = a(ra::all, 1); // second column of a
  656. auto g = a(ra::all, ra::dots<0>, 1); // same
  657. @end verbatim
  658. @end example
  659. @code{all} is a special case (@code{dots<1>}) of the more general object @code{dots}.
  660. @end deffn
  661. @anchor{x-dots}
  662. @deffn @w{Special object} dots<n>
  663. 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.
  664. If @var{n} is defaulted (@code{dots<>}), all available places will be used; this can only be done once in a given subscript list.
  665. This object cannot stand alone as an array expression. All the examples below result in @code{View} objects:
  666. @example
  667. @verbatim
  668. ra::Big<int, 3> a({3, 2, 4}, ...);
  669. auto h = a(); // all of a
  670. auto b = a(ra::all, ra::all, ra::all); // (1) all of a
  671. auto c = a(ra::dots<3>); // same as (1)
  672. auto d = a(ra::all, ra::dots<2>); // same as (1)
  673. auto e = a(ra::dots<2>, ra::all); // same as (1)
  674. auto f = a(ra::dots<>); // same as (1)
  675. auto j0 = a(0, ra::dots<2>); // first page of a
  676. auto j1 = a(0); // same
  677. auto j2 = a(0, ra::dots<>); // same
  678. auto k0 = a(ra::all, 0); // first row of a
  679. auto k1 = a(ra::all, 0, ra::all); // same
  680. auto k2 = a(ra::all, 0, ra::dots<>); // same
  681. auto k3 = a(ra::dots<>, 0, ra::all); // same
  682. // auto k = a(ra::dots<>, 0, ra::dots<>); // error
  683. auto l0 = a(ra::all, ra::all, 0); // first column of a
  684. auto l1 = a(ra::dots<2>, 0); // same
  685. auto l2 = a(ra::dots<>, 0); // same
  686. @end verbatim
  687. @end example
  688. This is useful when writing rank-generic code, see @code{examples/maxwell.cc} in the distribution for an example.
  689. @end deffn
  690. The following special objects aren't related to linear ranges, but they are meant to be used in a subscript context. Using them in other contexts will result in a compile time error.
  691. @cindex @code{len}
  692. @cindex @code{end}, Octave/Matlab
  693. @anchor{x-len}
  694. @deffn @w{Special object} len
  695. Represents the length of the @var{i}-th axis of a subscripted expression, when used at the @var{i}-th place of a subscripting expression.
  696. This works like @code{end} in Octave/Matlab, but note that @code{ra::} indices begin at 0, so the last element of a vector @code{a} is @code{a(ra::len-1)}.
  697. @example
  698. @verbatim
  699. ra::Big<int, 2> a({10, 10}, 100 + ra::_0 - ra::_1);
  700. auto a0 = a(ra::len-1); // last row of a; ra::len is a.len(0)
  701. auto a1 = a(ra::all, ra::len-1); // last column a; ra::len is a.len(1)
  702. auto a2 = a(ra::len-1, ra::len-1); // last element of last row; the first ra::len is a.len(0) and the second one is a.len(1)
  703. auto a3 = a(ra::all, ra::iota(2, ra::len-2)); // last two columns of a
  704. auto a4 = a(ra::iota(ra::len/2, 1, 2)); // odd rows of a
  705. a(ra::len - std::array {1, 3, 4}) = 0; // set to 0 the 1st, 3rd and 4th rows of a, counting from the end
  706. @end verbatim
  707. @end example
  708. @example
  709. @verbatim
  710. ra::Big<int, 3> b({2, 3, 4}, ...);
  711. auto b0 = b(ra::dots<2>, ra::len-1); // ra::len is a.len(2)
  712. auto b1 = b(ra::insert<1>, ra::len-1); // ra::len is a.len(0)
  713. @end verbatim
  714. @end example
  715. @end deffn
  716. @cindex @code{insert}
  717. @anchor{x-insert}
  718. @deffn @w{Special object} insert<n>
  719. Inserts @code{n} new axes at the subscript position. @code{n} must not be negative.
  720. The new axes have step 0 and undefined length, so they will match any length on those axes by repeating items. @code{insert} objects cannot stand alone as an array expression. The examples below result in @code{View} objects:
  721. @example
  722. @verbatim
  723. auto h = a(insert<0>); // same as (1)
  724. auto k = a(insert<1>); // shape [undefined, 3, 2]
  725. @end verbatim
  726. @end example
  727. @cindex broadcasting, singleton, Numpy
  728. @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 length one match dimensions of any length. In @code{ra::} singleton dimensions aren't special, so broadcasting requires the use of @code{insert}. For example: @c [ma115]
  729. @example
  730. @verbatim
  731. ra::Big<int, 1> x = {1, 10};
  732. // match shapes [2, U, U] with [U, 3, 2] to produce [2, 3, 2]
  733. cout << x(ra::all, ra::insert<2>) * a(insert<1>) << endl;
  734. @end verbatim
  735. @print{} 2 3 2
  736. 1 2
  737. 3 4
  738. 5 6
  739. 10 20
  740. 30 40
  741. 50 60
  742. @end example
  743. @end deffn
  744. We were speaking earlier of the outer product of the subscripts with operator @code{A}. Here's a way to perform the actual outer product (with operator @code{*}) of two @code{Views}, through broadcasting. All three lines are equivalent. See @ref{x-from,@code{from}} for a more general way to compute outer products.
  745. @example
  746. @verbatim
  747. cout << (A(ra::dots<A.rank()>, ra::insert<B.rank()>) * B(ra::insert<A.rank()>, ra::dots<B.rank()>)) << endl;
  748. cout << (A(ra::dots<>, ra::insert<B.rank()>) * B(ra::insert<A.rank()>, ra::dots<>)) << endl; // default dots<>
  749. cout << (A * B(ra::insert<A.rank()>)) << endl; // index elision + prefix matching
  750. @end verbatim
  751. @end example
  752. @subsection Subscripting and rank-0 views
  753. @cindex view, rank 0
  754. @cindex rank, runtime
  755. @cindex rank, compile-time
  756. 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 rt 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.
  757. @example
  758. @verbatim
  759. using T = std::complex<double>;
  760. int f(T &);
  761. Big<T, 2> a({2, 3}, 0); // ct rank
  762. Big<T> b({2, 3}, 0); // rt rank
  763. cout << a(0, 0).real_part() << endl; // ok, a(0, 0) returns complex &
  764. // cout << b(0, 0).real_part() << endl; // error, View<T> has no member real_part
  765. cout << ((T &)(b(0, 0))).real_part() << endl; // ok, manual conversion to T &
  766. cout << f(b(0, 0)) << endl; // ok, automatic conversion from View<T> to T &
  767. // cout << f(a(0)) << endl; // compile time error, conversion failed since ct rank of a(0) is not 0
  768. // cout << f(b(0)) << endl; // runtime error, conversion failed since rt rank of b(0) is not 0
  769. @end verbatim
  770. @end example
  771. @c ------------------------------------------------
  772. @node Functions
  773. @section Functions
  774. @c ------------------------------------------------
  775. 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.
  776. @anchor{x-scalar-ops}
  777. @subsection Standard scalar operations
  778. @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.
  779. 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{asin}, @code{acos}, @code{atan}, @code{atan2}, @code{cosh}, @code{sinh}, @code{tanh}, and @code{lerp}.
  780. 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 @code{odd}, @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}}.
  781. For example:
  782. @example @c [ma110]
  783. @verbatim
  784. cout << exp(ra::Small<double, 3> {4, 5, 6}) << endl;
  785. @end verbatim
  786. @print{} 54.5982 148.413 403.429
  787. @end example
  788. @subsection Conditional operations
  789. @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.
  790. @example
  791. @verbatim
  792. ra::Big<double> x ...
  793. ra::Big<double> y = where(x>0, expensive_expr_1(x), expensive_expr_2(x));
  794. @end verbatim
  795. @end example
  796. 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
  797. @example
  798. @verbatim
  799. ra::Big<double> y = map([](auto && w, auto && t, auto && f) -> decltype(auto) { return w ? t : f; }
  800. x>0, expensive_expr_1(x), expensive_function_2(x));
  801. @end verbatim
  802. @end example
  803. If the expressions have side effects, then @code{map} won't even give the right result.
  804. @c [ma109]
  805. @example
  806. @verbatim
  807. ra::Big<int, 1> o = {};
  808. ra::Big<int, 1> e = {};
  809. ra::Big<int, 1> n = {1, 2, 7, 9, 12};
  810. ply(where(odd(n), map([&o](auto && x) { o.push_back(x); }, n), map([&e](auto && x) { e.push_back(x); }, n)));
  811. cout << "o: " << ra::noshape << o << ", e: " << ra::noshape << e << endl;
  812. @end verbatim
  813. @print{} o: 1 7 9, e: 2 12
  814. @end example
  815. FIXME Artificial example.
  816. FIXME Do we want to expose ply(); this is the only example in the manual that uses it.
  817. When the choice is between more than two expressions, there's @ref{x-pick,@code{pick}}, which operates similarly, but accepts an integer instead of a boolean selector.
  818. @subsection Special operations
  819. 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.
  820. FIXME
  821. @subsection Elementwise reductions
  822. @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.
  823. You can define reductions the same way @code{ra::} does:
  824. @example
  825. @verbatim
  826. template <class A>
  827. inline auto op_reduce(A && a)
  828. {
  829. T c = op_default;
  830. for_each([&c](auto && a) { c = op(c, a); }, a);
  831. return c;
  832. }
  833. @end verbatim
  834. @end example
  835. 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:
  836. @example
  837. @verbatim
  838. ra::Big<double, 2> a({m, n}, ...);
  839. ra::Big<double, 1> sum_rows({n}, 0.);
  840. iter<1>(sum_rows) += iter<1>(a);
  841. // for_each(ra::wrank<1, 1>([](auto & c, auto && a) { c += a; }), sum_rows, a) // alternative
  842. // sum_rows += transpose<1, 0>(a); // another
  843. ra::Big<double, 1> sum_cols({m}, 0.);
  844. sum_cols += a;
  845. @end verbatim
  846. @end example
  847. FIXME example with assignment op
  848. A few common operations of this type are already packaged in @code{ra::}.
  849. @subsection Special reductions
  850. @code{ra::} defines the following special reductions.
  851. FIXME
  852. @subsection Shortcut reductions
  853. 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}.
  854. FIXME
  855. These operations are defined on top of another function @code{early}.
  856. FIXME early
  857. The following is often useful.
  858. FIXME lexicographical compare etc.
  859. @c ------------------------------------------------
  860. @node The rank conjunction
  861. @section The rank conjunction
  862. @c ------------------------------------------------
  863. 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.
  864. @example
  865. @verbatim
  866. for_each(my_sort, iter<1>(A)); // (in ra::) my_sort is a regular function, cell rank must be given
  867. for_each(my_sort, iter<0>(A)); // (in ra::) error, bad cell rank
  868. @end verbatim
  869. @end example
  870. @c @cindex J
  871. 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.
  872. @example
  873. @verbatim
  874. for_each(sort_rows, A); // (not in ra::) will iterate over 1-cells of A, sort_rows knows
  875. @end verbatim
  876. @end example
  877. @c @cindex J
  878. @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}}.
  879. @c @cindex J
  880. 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.
  881. A standard example is ‘outer product’.
  882. @example
  883. @verbatim
  884. ra::Big<int, 1> a = {1, 2, 3};
  885. ra::Big<int, 1> b = {40, 50};
  886. ra::Big<int, 2> axb = map(ra::wrank<0, 1>([](auto && a, auto && b) { return a*b; }),
  887. a, b)
  888. @end verbatim
  889. @result{} axb = @{@{40, 80, 120@}, @{50, 100, 150@}@}
  890. @end example
  891. 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:
  892. @example
  893. @verbatim
  894. a: 3 |
  895. b: | 2
  896. @end verbatim
  897. @end example
  898. Now the frames are rank-extended through prefix agreement.
  899. @example
  900. @verbatim
  901. a: 3 |
  902. b: 3 | 2
  903. @end verbatim
  904. @end example
  905. 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)).
  906. @example
  907. @verbatim
  908. a: 3 | 2
  909. b: 3 | 2
  910. @end verbatim
  911. @end example
  912. 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.
  913. @example
  914. @verbatim
  915. ra::Big<int, 1> a = {1, 2, 3};
  916. ra::Big<int, 1> b = {40, 50};
  917. ra::Big<int, 2> axb = from([](auto && a, auto && b) { return a*b; }), a, b)
  918. @end verbatim
  919. @result{} axb = @{@{40, 80, 120@}, @{50, 100, 150@}@}
  920. @end example
  921. 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.
  922. @example
  923. @verbatim
  924. C: m | | n
  925. A: m | p |
  926. B: | p | n
  927. @end verbatim
  928. @end example
  929. First we'll align the first axes of C and A using the cell ranks (1, 1, 2). The cell shapes are:
  930. @example
  931. @verbatim
  932. C: m | n
  933. A: m | p
  934. B: | p n
  935. @end verbatim
  936. @end example
  937. Then we'll use the ranks (1, 0, 1) on the cells:
  938. @example
  939. @verbatim
  940. C: m | | n
  941. A: m | p |
  942. B: | p | n
  943. @end verbatim
  944. @end example
  945. The final operation is a standard operation on arrays of scalars. In actual @code{ra::} syntax:
  946. @example @c [ma103]
  947. @verbatim
  948. ra::Big A({3, 2}, {1, 2, 3, 4, 5, 6});
  949. ra::Big B({2, 3}, {7, 8, 9, 10, 11, 12});
  950. ra::Big C({3, 3}, 0.);
  951. for_each(ra::wrank<1, 1, 2>(ra::wrank<1, 0, 1>([](auto && c, auto && a, auto && b) { c += a*b; })), C, A, B);
  952. @end verbatim
  953. @result{} C = @{@{27, 30, 33@}, @{61, 68, 75@}, @{95, 106, 117@}@}
  954. @end example
  955. Note that @code{wrank} cannot be used to transpose axes in general.
  956. 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.
  957. @c ------------------------------------------------
  958. @node Compatibility
  959. @section Compatibility
  960. @c ------------------------------------------------
  961. @subsection Using other C and C++ types with @code{ra::}
  962. @cindex foreign type
  963. @anchor{x-foreign-type}
  964. @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.
  965. @example
  966. @verbatim
  967. std::vector<int> x = {1, 2, 3};
  968. ra::Small<int, 3> y = {6, 5, 4};
  969. cout << (x-y) << endl;
  970. @end verbatim
  971. @print{} -5 -3 -1
  972. @end example
  973. @cindex @code{start}
  974. Foreign types can be brought into @code{ra::} explicitly with the function @ref{x-start,@code{start}}.
  975. @example
  976. @verbatim
  977. std::vector<int> x = {1, 2, 3};
  978. // cout << sum(x) << endl; // error, sum not found
  979. cout << sum(ra::start(x)) << endl;
  980. cout << ra::sum(x) << endl;
  981. @end verbatim
  982. @print{} 6
  983. @end example
  984. The following types are accepted as foreign types:
  985. @itemize
  986. @item Built-in arrays @cindex built-in array
  987. produce an expression of positive rank and ct size.
  988. @item @code{std::array}
  989. produces an expression of rank 1 and ct size.
  990. @item Other types conforming to @code{std::ranges::random_access_range}, including @code{std::vector}, @code{std::string}, etc.
  991. produce an expression of rank 1 and rt size.
  992. @end itemize
  993. Raw pointers must be brought into @code{ra::} explicitly using the function @ref{x-ptr,@code{ptr}}, which produces an expression of rank 1 and @emph{undefined} size.
  994. Compare:
  995. @example @c [ma106]
  996. @verbatim
  997. int p[] = {1, 2, 3};
  998. int * z = p;
  999. ra::Big<int, 1> q {1, 2, 3};
  1000. q += p; // ok, q is ra::, p is foreign object with shape info
  1001. ra::start(p) += q; // can't redefine operator+=(int[]), foreign needs ra::start()
  1002. // z += q; // error: raw pointer needs ra::ptr()
  1003. ra::ptr(z) += p; // ok, shape is determined by foreign object p
  1004. @end verbatim
  1005. @end example
  1006. @anchor{x-is-scalar}
  1007. Some types are accepted automatically as scalars. These include:
  1008. @itemize
  1009. @item
  1010. 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.
  1011. @item
  1012. @code{std::complex<T>}, if you import @code{ra/complex.hh}.
  1013. @end itemize
  1014. You can add your own types as scalar types with the following declaration (see @code{ra/complex.hh}):
  1015. @verbatim
  1016. namespace ra { template <> constexpr bool is_scalar_def<MYTYPE> = true; }
  1017. @end verbatim
  1018. Otherwise, you can bring a scalar object into @code{ra::} on the spot, with the function @ref{x-scalar,@code{scalar}}.
  1019. @subsection Using @code{ra::} types with the STL
  1020. 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 storage order of the view.
  1021. 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 for ranks above 1, and I haven't implemented them. The container @code{RandomAccessIterator}s that are provided are in fact raw pointers.
  1022. @example @c [ma106]
  1023. @verbatim
  1024. ra::Big<int> x {3, 2, 1}; // x is a Container
  1025. auto y = x(); // y is a View on x
  1026. // std::sort(y.begin(), y.end()); // error: y.begin() is not RandomAccessIterator
  1027. std::sort(x.begin(), x.end()); // ok, we know x is stored in row-major order
  1028. @end verbatim
  1029. @result{} x = @{1, 2, 3@}
  1030. @end example
  1031. @cindex other libraries, interfacing with
  1032. @subsection Using @code{ra::} types with other libraries
  1033. 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 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.
  1034. @subsubsection The good array citizen
  1035. @c FIXME Put these in examples/ and reference them here.
  1036. @cindex BLIS
  1037. The good array citizen describes its arrays with the same parameters as @code{ra::}: a pointer, plus a length and a step per dimension. You don't have to worry about special cases. Say @url{https://github.com/flame/blis, BLIS}:
  1038. @quotation
  1039. @verbatim
  1040. #include <blis.h>
  1041. ra::Big<double, 2> A({M, K}, ...);
  1042. ra::Big<double, 2> B({K, N}, ...);
  1043. ra::Big<double, 2> C({M, N}, ...);
  1044. double alpha = ...;
  1045. double beta = ...;
  1046. // C := βC + αAB
  1047. bli_dgemm(BLIS_NO_TRANSPOSE, BLIS_NO_TRANSPOSE, M, N, K, &alpha,
  1048. A.data(), A.step(0), A.step(1),
  1049. B.data(), B.step(0), B.step(1),
  1050. &beta, C.data(), C.step(0), C.step(1));
  1051. @end verbatim
  1052. @end quotation
  1053. @cindex FFTW
  1054. Another good array citizen, @url{http://fftw.org, FFTW} handles arbitrary rank:
  1055. @quotation
  1056. @verbatim
  1057. #include <fftw3.h>
  1058. ...
  1059. using complex = std::complex<double>;
  1060. static_assert(sizeof(complex)==sizeof(fftw_complex));
  1061. // forward DFT over the last r axes of a -> b
  1062. void fftw(int r, ra::View<complex> const a, ra::View<complex> b)
  1063. {
  1064. int const rank = a.rank();
  1065. assert(r>0 && r<=rank);
  1066. assert(every(ra::start(shape(a))==shape(b)));
  1067. fftw_iodim dims[r];
  1068. fftw_iodim howmany_dims[rank-r];
  1069. for (int i=0; i!=rank; ++i) {
  1070. if (i>=rank-r) {
  1071. dims[i-rank+r].n = a.len(i);
  1072. dims[i-rank+r].is = a.step(i);
  1073. dims[i-rank+r].os = b.step(i);
  1074. } else {
  1075. howmany_dims[i].n = a.len(i);
  1076. howmany_dims[i].is = a.step(i);
  1077. howmany_dims[i].os = b.step(i);
  1078. }
  1079. }
  1080. fftw_plan p;
  1081. p = fftw_plan_guru_dft(r, dims, rank-r, howmany_dims,
  1082. (fftw_complex *)(a.data()), (fftw_complex *)(b.data()),
  1083. FFTW_FORWARD, FFTW_ESTIMATE);
  1084. fftw_execute(p);
  1085. fftw_destroy_plan(p);
  1086. }
  1087. @end verbatim
  1088. @end quotation
  1089. @cindex Guile
  1090. 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:
  1091. @quotation
  1092. @verbatim
  1093. SCM a; // say a is #nf64(...)
  1094. ...
  1095. scm_t_array_handle h;
  1096. scm_array_get_handle(a, &h);
  1097. scm_t_array_dim const * dims = scm_array_handle_dims(&h);
  1098. View<double> v(map([](int i) { return ra::Dim { dims[i].ubnd-dims[i].lbnd+1, dims[i].inc }; },
  1099. ra::iota(scm_array_handle_rank(&h))),
  1100. scm_array_handle_f64_writable_elements(&h));
  1101. ...
  1102. scm_array_handle_release(&h);
  1103. @end verbatim
  1104. @end quotation
  1105. @cindex Numpy
  1106. @cindex Python
  1107. 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.
  1108. It is usually 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}}).
  1109. @subsubsection The bad array citizen
  1110. Unfortunately there are many libraries that don't accept arbitrary array parameters, or that do strange things with particular values of lengths and/or steps.
  1111. The most common case is that a library doesn't handle steps at all, and it only accepts unit step 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.
  1112. @c FIXME using is_c_order, etc.
  1113. Other libraries do accept steps, but not arbitrary ones. For example @url{https://www.netlib.org/blas}' @code{cblas_dgemm} has this prototype:
  1114. @quotation
  1115. @verbatim
  1116. cblas_dgemm(order, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
  1117. @end verbatim
  1118. @end quotation
  1119. @code{A}, @code{B}, @code{C} are (pointers to) 2-arrays, but the routine accepts only one step argument for each (@code{lda}, etc.). CBLAS also doesn't understand @code{lda} as a arbitrary step, but rather as the dimension of a larger array that you're slicing @code{A} from, and some implementations will mishandle negative or zero @code{lda}.
  1120. 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.
  1121. @cindex OpenGL
  1122. OpenGL is another library that requires @url{https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVertexAttribPointer.xhtml,contortions:}
  1123. @quotation
  1124. @verbatim
  1125. void glVertexAttribPointer(GLuint index,
  1126. GLint size,
  1127. GLenum type,
  1128. GLboolean normalized,
  1129. GLsizei step,
  1130. const GLvoid * pointer);
  1131. @end verbatim
  1132. [...]
  1133. @emph{step}
  1134. @quotation
  1135. Specifies the byte offset between consecutive generic vertex attributes. If step is 0, the generic vertex attributes are understood to be tightly packed in the array. The initial value is 0.
  1136. @end quotation
  1137. @end quotation
  1138. It isn't clear whether negative steps are legal, either. So just as with CBLAS, passing arbitrary array views may require copies.
  1139. @c ------------------------------------------------
  1140. @node Extension
  1141. @section Extension
  1142. @c ------------------------------------------------
  1143. @subsection New scalar types
  1144. @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}.
  1145. @example
  1146. @verbatim
  1147. struct W { int x; }
  1148. ra::Big<W, 2> w = {{ {4}, {2} }, { {1}, {3} }};
  1149. cout << W(1, 1).x << endl;
  1150. cout << amin(map([](auto && x) { return w.x; }, w)) << endl;
  1151. @end verbatim
  1152. @print{} 3
  1153. 1
  1154. @end example
  1155. 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.
  1156. @example
  1157. @verbatim
  1158. namespace ra { template <> constexpr bool is_scalar_def<W> = true; }
  1159. ...
  1160. W ww {11};
  1161. for_each([](auto && x, auto && y) { cout << (x.x + y.y) << " "; }, w, ww); // ok
  1162. @end verbatim
  1163. @print{} 15 13 12 14
  1164. @end example
  1165. but
  1166. @example
  1167. @verbatim
  1168. struct U { int x; }
  1169. U uu {11};
  1170. for_each([](auto && x, auto && y) { cout << (x.x + y.y) << " "; }, w, uu); // error: can't find ra::start(U)
  1171. @end verbatim
  1172. @end example
  1173. @anchor{x-new-array-operations}
  1174. @subsection New array operations
  1175. @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):
  1176. @example
  1177. @verbatim
  1178. return_type my_fun(...) { };
  1179. ...
  1180. namespace ra {
  1181. template <class ... A> inline auto
  1182. my_fun(A && ... a)
  1183. {
  1184. return map(::my_fun, std::forward<A>(a) ...);
  1185. }
  1186. } // namespace ra
  1187. @end verbatim
  1188. @end example
  1189. @cindex overload set
  1190. If @code{my_fun} is an overload set, you can use@footnote{Simplified; see the references in @url{http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1170r0.html}.}
  1191. @example
  1192. @verbatim
  1193. namespace ra {
  1194. template <class ... A> inline auto
  1195. my_fun(A && ... a)
  1196. {
  1197. return map([](auto && ... a) { return ::my_fun(a ...); }, std::forward<A>(a) ...);
  1198. }
  1199. } // namespace ra
  1200. @end verbatim
  1201. @end example
  1202. @cindex error
  1203. @cindex assert
  1204. @c ------------------------------------------------
  1205. @node Error handling
  1206. @section Error handling
  1207. @c ------------------------------------------------
  1208. Error handling in @code{ra::} is controlled by two macros:
  1209. @itemize
  1210. @item @code{RA_DO_CHECK}
  1211. is a binary flag that controls runtime checks. The default is 1 which means to check for errors. 0 means not to check. The checks themselves are done with @code{RA_ASSERT}.
  1212. @item @code{RA_ASSERT(cond, ...)}
  1213. is a function-like macro. @code{cond} is an expression that evaluates to true (in the @code{ra::} namespace) if the assertion is satisfied. The other arguments are informative and do not need to be used. If the assertion fails, the default definition of @code{RA_ASSERT(cond, ...)} prints those arguments to @code{std::cerr} and aborts.
  1214. @end itemize
  1215. @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 @option{-DNDEBUG}.
  1216. 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 a user-defined exception instead.
  1217. @c ------------------------------------------------
  1218. @node Extras
  1219. @chapter Extras
  1220. @c ------------------------------------------------
  1221. @c ------------------------------------------------
  1222. @node Hazards
  1223. @chapter Hazards
  1224. @c ------------------------------------------------
  1225. 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.
  1226. @section Reuse of expression objects
  1227. Expression objects are meant to be used once. This applies to anything produced with @code{ra::map}, @code{ra::iter}, @code{ra::start}, or @code{ra::ptr}. Reuse errors are @emph{not} checked. For example:
  1228. @example
  1229. @verbatim
  1230. ra::Big<int, 2> B({3, 3}, ra::_1 + ra::_0*3); // {{0 1 2} {3 4 5} {6 7 8}}
  1231. std::array<int, 2> l = { 1, 2 };
  1232. cout << B(ra::ptr(l), ra::ptr(l)) << endl; // ok => {{4 5} {7 8}}
  1233. auto ll = ra::ptr(l);
  1234. cout << B(ll, ll) << endl; // ??
  1235. @end verbatim
  1236. @end example
  1237. @section Assignment to views
  1238. FIXME
  1239. With rt-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 @code{>>} container may work; do not rely on it.
  1240. @section View of const vs const view
  1241. @c FIXME
  1242. FIXME
  1243. Passing view arguments by reference
  1244. @section Rank extension in assignments
  1245. 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.
  1246. @example @c [ma107]
  1247. @verbatim
  1248. int a = 0;
  1249. ra::scalar(a) = 3 + ra::Small<int, 3> {4, 5, 6}; // ?
  1250. @end verbatim
  1251. @result{} a = 9
  1252. @end example
  1253. Compare with
  1254. @example
  1255. @verbatim
  1256. int a = 0;
  1257. ra::scalar(a) += 3 + ra::Small<int, 3> {4, 5, 6}; // 0 + 3 + 4 + 5 + 6
  1258. @end verbatim
  1259. @result{} a = 18
  1260. @end example
  1261. @section Performance pitfalls of rank extension
  1262. 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.
  1263. @example
  1264. @verbatim
  1265. ra::Big<int, 2> a = {{1, 2, 3, 4}, {5, 6, 7, 8} {9, 10, 11, 12}};
  1266. ra::Big<int, 1> b = {1, 2, 3};
  1267. ra::Big<int, 2> c = map(f, b) + a;
  1268. @end verbatim
  1269. @end example
  1270. @section Chained assignment
  1271. FIXME
  1272. When @code{a=b=c} works, it operates as @code{b=c; a=b;} and not as an array expression.
  1273. @section Unregistered scalar types
  1274. FIXME
  1275. @code{View<T, N> x; x = T()} fails if @code{T} isn't registered as @code{is_scalar}.
  1276. @enumerate
  1277. @item
  1278. Item 0
  1279. @item
  1280. Item 1
  1281. @item
  1282. Item 2
  1283. @end enumerate
  1284. @c ------------------------------------------------
  1285. @node Internals
  1286. @chapter Internals
  1287. @c ------------------------------------------------
  1288. @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).
  1289. @menu
  1290. * Header structure::
  1291. * Type hierarchy::
  1292. * Term agreement::
  1293. * Loop types::
  1294. * Introspection::
  1295. * Compiling and running::
  1296. @end menu
  1297. @c ------------------------------------------------
  1298. @node Headers
  1299. @section Headers
  1300. @c ------------------------------------------------
  1301. The header structure of @code{ra::} is as follows.@footnote{Diagram generated using Graphviz and @url{https://www.flourish.org/cinclude2dot}.
  1302. @verbatim
  1303. cd ra && cinclude2dot.pl --include . > headers.dot
  1304. dot -Tpng headers.dot -Gdpi=100 > headers.png
  1305. @end verbatim
  1306. }
  1307. @image{headers,4cm}
  1308. @c ------------------------------------------------
  1309. @node Type hierarchy
  1310. @section Type hierarchy
  1311. @c ------------------------------------------------
  1312. Some of the categories below are C++20 ‘concepts’, some are still informal.
  1313. @itemize
  1314. @item @b{Container} --- @code{Big}, @code{Shared}, @code{Unique}, @code{Small}
  1315. These are array types that own their data in one way or another. Creating or destroying these objects may allocate or deallocate memory, respectively.
  1316. @item @b{View} --- @code{View}, @code{SmallView}
  1317. These are array views into data in memory, which 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.
  1318. @item @b{Iterator} --- @code{CellBig}, @code{CellSmall}, @code{Iota}, @code{Ptr}, @code{Scalar}, @code{Expr}, @code{Pick}
  1319. This is a traversable object. @b{Iterator}s are accepted by all the array functions such as @code{map}, @code{for_each}, etc. @code{map} produces an @b{Iterator} itself, so most array expressions are @b{Iterator}s. @b{Iterator}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.
  1320. @b{Iterator}s have two traversal functions. The first one, @code{.adv(k, d)}, moves the iterator along any axis @var{k}. The other one, @code{.mov(d)}, is used on linearized views of the array. The methods @code{len()}, @code{step()}, @code{keep_step()} are used to determine the extent of these linearized views. In this way, a loop involving @b{Iterator}s can have its inner loop unfolded, which is faster than a multidimensional loop, especially if the inner dimensions of the loop are small.
  1321. @b{Iterator}s also provide an @code{at(i ...)} method for random access to any element of the expression.
  1322. @end itemize
  1323. @c ------------------------------------------------
  1324. @node Term agreement
  1325. @section Term agreement
  1326. @c ------------------------------------------------
  1327. The execution of an expression template begins with the determination of its shape — the length 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 length (such as @code{iota()} or view axes created with @code{insert}) are ignored. All the other terms must match.
  1328. Then we select a 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 (v@value{VERSION}) 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 flat loop.
  1329. Finally we select a traversal method. @code{ra::} has two traversal methods: @code{ply_fixed} can be used when the rank and the traversal order are known at compile time, and @code{ply_ravel} can be used in the general case.
  1330. @c ------------------------------------------------
  1331. @node Loop types
  1332. @section Loop types
  1333. @c ------------------------------------------------
  1334. TODO
  1335. @c ------------------------------------------------
  1336. @node Introspection
  1337. @section Introspection
  1338. @c ------------------------------------------------
  1339. The following functions are available to query the properties of @code{ra::} objects.
  1340. @cindex @code{rank}
  1341. @anchor{x-rank}
  1342. @deftypefn @w{Function} rank_t rank e
  1343. Return the rank of expression @var{e}.
  1344. @end deftypefn
  1345. @cindex @code{shape}
  1346. @anchor{x-shape}
  1347. @deftypefn @w{Function} array shape e
  1348. @deftypefnx @w{Function} dim_t shape e k
  1349. The first form returns the shape of expression @var{e} as an array. The second form returns the length of axis @var{k}, i.e. @code{shape(e)[k]} ≡ @code{shape(e, k)}.
  1350. @var{array} might be a @ref{x-foreign-type,@code{foreign type}} (such as @code{std::array} or @code{std::vector}) instead of a @code{ra-ra} type.
  1351. @end deftypefn
  1352. @c ------------------------------------------------
  1353. @node Compiling and running
  1354. @section Compiling and running
  1355. @c ------------------------------------------------
  1356. The following @code{#define}s affect the behavior of @code{ra::}.
  1357. @itemize
  1358. @c FIXME The flag should only apply to dynamic checks.
  1359. @item @code{RA_DO_CHECK} (default 1): Check shape 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;}). See @ref{Error handling}.
  1360. @item @code{RA_DO_OPT} (default 1): Sets the default for all @code{RA_DO_OPT_XXX} flags.
  1361. @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.
  1362. @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.
  1363. @end itemize
  1364. @code{ra::} comes with three kinds of tests: examples, proper tests, and benchmarks. @code{ra::} uses its own 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}. Like most expression template libraries, @code{ra::} is highly dependent on optimization by the compiler and will be orders of magnitude slower with @option{-O0} compared to @option{-O2}.
  1365. The following environment variables affect the test suite under SCons:
  1366. @itemize
  1367. @item @code{RA_USE_BLAS} (default 0): Use BLAS for @code{gemm} and @code{gemv} benchmarks.
  1368. @end itemize
  1369. @c TODO Flags and notes about different compilers
  1370. @c ------------------------------------------------
  1371. @node The future
  1372. @chapter The future
  1373. @c ------------------------------------------------
  1374. @section Error messages
  1375. FIXME
  1376. @section Reductions
  1377. FIXME
  1378. @section Etc
  1379. FIXME
  1380. @c ------------------------------------------------
  1381. @node Reference
  1382. @chapter Reference
  1383. @c ------------------------------------------------
  1384. @cindex @code{agree}
  1385. @anchor{x-agree} @defun agree arg ...
  1386. Return true if the shapes of arguments @var{arg...} match (see @ref{Rank extension}), else return false.
  1387. This is useful when @ref{Error handling,error checking} is enabled and one wants to avoid the failure response.
  1388. @example
  1389. @verbatim
  1390. ra::Small<int, 2, 3> A;
  1391. ra::Small<int, 2> B;
  1392. ra::Small<int, 3> C;
  1393. agree(A, B); // -> true
  1394. static_assert(agree(A, B)); // ok for ct shapes
  1395. cout << (A+B) << endl; // ok
  1396. agree(A, C); // -> false
  1397. cout << (A+C) << endl; // error. Maybe abort, maybe throw - cf Error Handling
  1398. @end verbatim
  1399. @end example
  1400. @end defun
  1401. @cindex @code{agree_op}
  1402. @anchor{x-agree_op} @defun agree_op op arg ...
  1403. Return true if the shapes of arguments @var{arg...} match (see @ref{Rank extension}) relative to operator @var{op}, else return false.
  1404. This differs from @ref{x-agree,@code{agree}} when @var{op} has non-zero argument ranks. For example:
  1405. @example
  1406. @verbatim
  1407. ra::Big<real, 1> a({3}, 0.);
  1408. ra::Big<real, 2> b({2, 3}, 0.n);
  1409. agree(a, b); // -> false
  1410. cout << (a+b) << endl; // error
  1411. agree_op(ra::wrank<1, 1>(std::plus()), a, b); // -> true
  1412. cout << map(ra::wrank<1, 1>(std::plus()), a, b) << endl; // ok
  1413. @end verbatim
  1414. @end example
  1415. @end defun
  1416. @cindex @code{at}
  1417. @anchor{x-at} @defun at expr indices
  1418. Look up @var{expr} at each element of @var{indices}, which shall be a multi-index into @var{expr}.
  1419. This can be used for sparse subscripting. For example:
  1420. @example @c [ra30]
  1421. @verbatim
  1422. ra::Big<int, 2> A = {{100, 101}, {110, 111}, {120, 121}};
  1423. ra::Big<ra::Small<int, 2>, 2> i = {{{0, 1}, {2, 0}}, {{1, 0}, {2, 1}}};
  1424. ra::Big<int, 2> B = at(A, i);
  1425. @end verbatim
  1426. @result{} B = @{@{101, 120@}, @{110, 121@}@}
  1427. @end example
  1428. @end defun
  1429. @cindex @code{cast}
  1430. @anchor{x-cast} @defun cast <type> expr
  1431. Create an array expression that casts @var{expr} into @var{type}.
  1432. @end defun
  1433. @cindex @code{collapse}
  1434. @anchor{x-collapse} @defun collapse
  1435. TODO
  1436. See also @ref{x-explode,@code{explode}}.
  1437. @end defun
  1438. @cindex @code{concrete}
  1439. @anchor{x-concrete} @defun concrete a
  1440. Convert the argument to a container of the same shape as @var{a}.
  1441. If the argument has rt or ct 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.
  1442. @c FIXME example
  1443. @end defun
  1444. @cindex @code{diag}
  1445. @anchor{x-diag} @defun diag view
  1446. Equivalent to @code{transpose<0, 0>(view)}.
  1447. @end defun
  1448. @cindex @code{explode}
  1449. @anchor{x-explode} @defun explode
  1450. TODO
  1451. See also @ref{x-collapse,@code{collapse}}.
  1452. @end defun
  1453. @cindex @code{for_each}
  1454. @anchor{x-for_each} @defun for_each op expr ...
  1455. Create an array expression that applies @var{op} to @var{expr} ..., and traverse it.
  1456. @var{op} is run for effect; whatever it returns is discarded. For example:
  1457. @example
  1458. @verbatim
  1459. double s = 0.;
  1460. for_each([&s](auto && a) { s+=a; }, ra::Small<double, 1> {1., 2., 3})
  1461. @end verbatim
  1462. @result{} s = 6.
  1463. @end example
  1464. See also @ref{x-map,@code{map}}.
  1465. @end defun
  1466. @cindex @code{format_array}
  1467. @anchor{x-format_array} @defun format_array expr [last_axis_separator [second_last_axis_separator ...]]
  1468. Formats an array for character output.
  1469. For example:
  1470. @example
  1471. @verbatim
  1472. ra::Small<int, 2, 2> A = {{1, 2}, {3, 4}};
  1473. cout << "case a:\n" << A << endl;
  1474. cout << "case b:\n" << format_array(A) << endl;
  1475. cout << "case c:\n" << format_array(A, "|", "-") << endl;
  1476. @end verbatim
  1477. @print{} case a:
  1478. 1 2
  1479. 3 4
  1480. case b:
  1481. 1 2
  1482. 3 4
  1483. case c:
  1484. 1|2-3|4
  1485. @end example
  1486. The shape that might be printed before the expression itself (depending on its type) is not subject to these separators.
  1487. See also @ref{x-noshape,@code{noshape}}, @ref{x-withshape,@code{withshape}}.
  1488. @end defun
  1489. @cindex @code{from}
  1490. @anchor{x-from} @defun from op expr ...
  1491. Create outer product expression. This is defined as
  1492. @display
  1493. E = from(op, e₀, e₁ ...) ⇒ E(i₀₀, i₀₁ ..., i₁₀, i₁₁, ..., ...) = op[expr₀(i₀₀, i₀₁, ...), expr₁(i₁₀, i₁₁, ...), ...].
  1494. @end display
  1495. For example:
  1496. @example
  1497. @verbatim
  1498. ra::Big<double, 1> a {1, 2, 3};
  1499. ra::Big<double, 1> b {10, 20, 30};
  1500. ra::Big<double, 2> axb = from([](auto && a, auto && b) { return a*b; }, a, b)
  1501. @end verbatim
  1502. @result{} axb = @{@{10, 20, 30@}, @{20, 40, 60@}, @{30, 60, 90@}@}
  1503. @end example
  1504. @example
  1505. @verbatim
  1506. ra::Big<int, 1> i {2, 1};
  1507. ra::Big<int, 1> j {0, 1};
  1508. ra::Big<double, 2> A = {{1, 2}, {3, 4}, {5, 6}};
  1509. ra::Big<double, 2> Aij = from(A, i, j)
  1510. @end verbatim
  1511. @result{} Aij = @{@{6, 5@}, @{4, 3@}@}
  1512. @end example
  1513. The last example is more or less how @code{A(i, j)} is implemented for arbitrary subscripts (@pxref{The rank conjunction}).
  1514. @end defun
  1515. @cindex @code{imag_part}
  1516. @anchor{x-imag_part} @defun imag_part
  1517. Take imaginary part of a complex number. This can be used as reference.
  1518. For example: @c [ma115]
  1519. @example
  1520. @verbatim
  1521. ra::Small<std::complex<double>, 2, 2> A = {{1., 2.}, {3., 4.}};
  1522. imag_part(A) = -2*real_part(A);
  1523. cout << A << endl;
  1524. @end verbatim
  1525. @print{}
  1526. (1, -2) (2, -4)
  1527. (3, -6) (4, -8)
  1528. @end example
  1529. See also @ref{x-real_part,@code{real_part}}.
  1530. @end defun
  1531. @cindex @code{map}
  1532. @anchor{x-map} @defun map op expr ...
  1533. Create an array expression that applies callable @var{op} to @var{expr} ...
  1534. For example:
  1535. @example
  1536. @verbatim
  1537. ra::Big<double, 1> x = map(cos, std::array {0.});
  1538. @end verbatim
  1539. @result{} x = @{ 1. @}
  1540. @end example
  1541. @var{op} can return a reference. For example:
  1542. @example
  1543. @verbatim
  1544. ra::Big<int, 2> x = {{3, 3}, 0.};
  1545. ra::Big<int, 2> i = {0, 1, 1, 2};
  1546. ra::Big<int, 2> j = {1, 0, 2, 1};
  1547. map(x, i, j) = 1;
  1548. @end verbatim
  1549. @result{} x = @{@{0, 1, 0@}, @{1, 0, 1@}, @{0, 1, 0@}@}
  1550. @end example
  1551. Note that @code{map(x, i, j)} is @ref{x-subscript-outer-product,not the same} as @code{x(i, j)}.
  1552. @var{op} can be any callable. For example:
  1553. @example
  1554. @verbatim
  1555. struct A { int a, b; };
  1556. std::vector<A> v = {{1, 2}, {3, 4}};
  1557. ra::map(&A::a, v) = -ra::map(&A::b, v); // pointer to member
  1558. @end verbatim
  1559. @result{} v = @{@{-2, 2@}, @{-4, 4@}@}
  1560. @end example
  1561. See also @ref{x-for_each,@code{for_each}}.
  1562. @end defun
  1563. @cindex @code{pack}
  1564. @anchor{x-pack} @defun pack <type> expr ...
  1565. Create an array expression that brace-constructs @var{type} from @var{expr} ...
  1566. @end defun
  1567. @cindex @code{pick}
  1568. @anchor{x-pick} @defun pick select_expr expr ...
  1569. 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.
  1570. 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}.
  1571. For example:
  1572. @example @c cf examples/readme.cc [ma100].
  1573. @verbatim
  1574. ra::Small<int, 3> s {2, 1, 0};
  1575. ra::Small<double, 3> z = pick(s, s*s, s+s, sqrt(s));
  1576. @end verbatim
  1577. @result{} z = @{1.41421, 2, 0@}
  1578. @end example
  1579. @end defun
  1580. @cindex @code{ply}
  1581. @anchor{x-ply} @defun ply expr
  1582. Traverse @var{expr}. @code{ply} returns @code{void} so @var{expr} should be run for effect.
  1583. 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 equivalent to @code{ply(map(...))}, should cover most other uses.
  1584. @example
  1585. @verbatim
  1586. double s = 0.;
  1587. ply(map([&s](auto && a) { s+=a; }, ra::Small<double, 1> {1., 2., 3})) // same as for_each
  1588. @end verbatim
  1589. @result{} s = 6.
  1590. @end example
  1591. @end defun
  1592. @cindex @code{real_part}
  1593. @anchor{x-real_part} @defun real_part
  1594. Take real part of a complex number. This can be used as reference.
  1595. See also @ref{x-imag_part,@code{imag_part}}.
  1596. @end defun
  1597. @cindex @code{reverse}
  1598. @anchor{x-reverse} @defun reverse view axis
  1599. Create a new view by reversing axis @var{k} of @var{view}.
  1600. This is equivalent to @code{view(ra::dots<k>, ra::iota(ra::len, ra::len-1, -1))}.
  1601. This operation does not work on arbitrary array expressions yet. TODO FILL
  1602. @end defun
  1603. @cindex @code{size}
  1604. @anchor{x-size} @defun size a
  1605. Get the total size of an @code{ra::} object: the product of all its lengths.
  1606. @end defun
  1607. @c FIXME example
  1608. @cindex @code{stencil}
  1609. @anchor{x-stencil} @defun stencil view lo hi
  1610. Create a stencil on @var{view} with lower bounds @var{lo} and higher bounds @var{hi}.
  1611. @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 lengths 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), ...)}.
  1612. This operation does not work on arbitrary array expressions yet. TODO FILL
  1613. @end defun
  1614. @cindex @code{swap}
  1615. @anchor{x-swap} @defun swap a b
  1616. Swap the contents of containers @var{a} and @var{b}.
  1617. Both containers must be of the same storage type. The containers may have different shapes, but if at least one of them is of ct rank, then both of them must have the same rank.
  1618. This function reuses @code{std::swap} for same-rank overloads, so it must not be qualified (i.e. use @code{swap(a, b)}, not @code{ra::swap(a, b)}).
  1619. @end defun
  1620. @example @c [ra30]
  1621. @verbatim
  1622. ra::Big<int> a ({2, 3}, 1 + ra::_0 - ra::_1); // (1)
  1623. ra::Big<int> b ({2, 3, 4}, 1 - ra::_0 + ra::_1 + ra::_2); // (2)
  1624. swap(a, b);
  1625. // as if (1) had b and (2) had a
  1626. @end verbatim
  1627. @end example
  1628. @cindex @code{transpose}
  1629. @anchor{x-transpose}
  1630. @defun transpose <axes ...> (view) | (axes, view)
  1631. Create a new view by transposing the axes of @var{view}. The number of @var{axes} must match the rank of @var{view}.
  1632. For example:
  1633. @example
  1634. @verbatim
  1635. ra::Unique<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  1636. cout << transpose<1, 0>(a) << endl;
  1637. @end verbatim
  1638. @print{}
  1639. 3 2
  1640. 1 4
  1641. 2 5
  1642. 3 6
  1643. @end example
  1644. 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:
  1645. @example
  1646. @verbatim
  1647. ra::Unique<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  1648. cout << transpose<0, 0>(a) << endl; // { a(0, 0), a(1, 1) }
  1649. @end verbatim
  1650. @print{}
  1651. 2
  1652. 1 5
  1653. @end example
  1654. If one of the destination axes isn't mentioned in @var{axes}, then it becomes a ‘dead’ axis similar to those produced by @ref{x-insert,@code{insert}}. For example:
  1655. @example
  1656. @verbatim
  1657. ra::Unique<double, 1> a = {1, 2, 3};
  1658. cout << ((a*10) + transpose<1>(a)) << endl;
  1659. @end verbatim
  1660. @print{}
  1661. 3 3
  1662. 11 21 31
  1663. 12 22 32
  1664. 13 23 33
  1665. @end example
  1666. The two argument form lets you specify the axis list at runtime. In that case the result will have rt rank as well. For example: @c [ma117]
  1667. @example
  1668. @verbatim
  1669. ra::Small<int, 2> axes = {0, 1};
  1670. ra::Unique<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  1671. cout << "A: " << transpose(axes, a) << endl;
  1672. axes = {1, 0};
  1673. cout << "B: " << transpose(axes, a) << endl;
  1674. @end verbatim
  1675. @print{}
  1676. A: 2
  1677. 2 3
  1678. 1 2 3
  1679. 4 5 6
  1680. B: 2
  1681. 3 2
  1682. 1 4
  1683. 2 5
  1684. 3 6
  1685. @end example
  1686. This operation does not work on arbitrary array expressions yet. TODO FILL
  1687. @end defun
  1688. @cindex @code{where}
  1689. @anchor{x-where} @defun where pred_expr true_expr false_expr
  1690. 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.
  1691. For example:
  1692. @example
  1693. @verbatim
  1694. ra::Big<double, 1> s {1, -1, 3, 2};
  1695. s = where(s>=2, 2, s); // saturate s
  1696. @end verbatim
  1697. @result{} s = @{1, -1, 2, 2@}
  1698. @end example
  1699. @end defun
  1700. @cindex @code{wrank}
  1701. @anchor{x-wrank} @defun wrank <input_rank ...> op
  1702. Wrap @var{op} using a rank conjunction (@pxref{The rank conjunction}).
  1703. For example: TODO
  1704. @example
  1705. @verbatim
  1706. @end verbatim
  1707. @result{} x = 0
  1708. @end example
  1709. @end defun
  1710. @c @anchor{x-reshape}
  1711. @c @defun reshape view shape
  1712. @c Create a new view with shape @var{shape} from the row-major ravel of @var{view}.
  1713. @c FIXME fill when the implementation is more mature...
  1714. @c @end defun
  1715. @c @anchor{x-ravel}
  1716. @c @defun ravel view
  1717. @c Return the ravel of @var{view} as a view on @var{view}.
  1718. @c FIXME fill when the implementation is more mature...
  1719. @c @end defun
  1720. @cindex @code{noshape}
  1721. @cindex @code{withshape}
  1722. @anchor{x-noshape}
  1723. @anchor{x-withshape}
  1724. @deffn @w{Special object} {withshape noshape}
  1725. If either of these objects is sent to @code{std::ostream} before an expression object, the shape of that object will or will not be printed.
  1726. If the object has ct shape, the default is not to print the shape, so @code{noshape} isn't necessary, and conversely for @code{withshape} if the object has rt shape. Note that the array readers [@code{operator>>(std::istream &, ...)}] expect the shape to be present or not according to the default.
  1727. For example:
  1728. @example
  1729. @verbatim
  1730. ra::Small<int, 2, 2> A = {77, 99};
  1731. cout << "case a:\n" << A << endl;
  1732. cout << "case b:\n" << ra::noshape << A << endl;
  1733. cout << "case c:\n" << ra::withshape << A << endl;
  1734. @end verbatim
  1735. @print{} case a:
  1736. 77 99
  1737. case b:
  1738. 77 99
  1739. case c:
  1740. 2
  1741. 77 99
  1742. @end example
  1743. but:
  1744. @example
  1745. @verbatim
  1746. ra::Big<int> A = {77, 99};
  1747. cout << "case a:\n" << A << endl;
  1748. cout << "case b:\n" << ra::noshape << A << endl;
  1749. cout << "case c:\n" << ra::withshape << A << endl;
  1750. @end verbatim
  1751. @print{} case a:
  1752. 1
  1753. 2
  1754. 77 99
  1755. case b:
  1756. 77 99
  1757. case c:
  1758. 1
  1759. 2
  1760. 77 99
  1761. @end example
  1762. Note that in the last example the very shape of @code{ra::Big<int>} has rt length, so that length (the rank of @code{A}, that is 1) is printed as part of the shape of @code{A}.
  1763. See also @ref{x-format_array,@code{format_array}}.
  1764. @end deffn
  1765. @cindex @code{ptr}
  1766. @anchor{x-ptr}
  1767. @deffn @w{Function} ptr bidirectional_iterator [len]
  1768. @deffnx @w{Function} ptr bidirectional_range
  1769. Create rank-1 expression from foreign object.
  1770. If @code{len} is not given for @var{bidirectional_iterator}, the expression has undefined length, and it will need to be matched with other expressions whose length is defined. @code{ra::} doesn't know what is actually accessible through the iterator, so be careful. For instance:
  1771. @example
  1772. @verbatim
  1773. int pp[] = {1, 2, 3};
  1774. int * p = pp; // erase length
  1775. ra::Big<int, 1> v3 {1, 2, 3};
  1776. ra::Big<int, 1> v4 {1, 2, 3, 4};
  1777. v3 += ra::ptr(p); // ok, shape (3): v3 = {2, 4, 6}
  1778. v4 += ra::ptr(p); // undefined, shape (4): bad access to p[3]
  1779. // cout << (ra::ptr(p)+ra::iota()) << endl; // ct error, expression has undefined shape
  1780. cout << (ra::ptr(p, 3)+ra::iota()) << endl; // ok, prints { 1, 3, 5 }
  1781. cout << (ra::ptr(p, 4)+ra::iota()) << endl; // undefined, bad access at p[4]
  1782. @end verbatim
  1783. @end example
  1784. Of course in this example one could simply have used @code{pp} instead of @code{ra::ptr(p)}, since the array type retains shape information.
  1785. @example
  1786. @verbatim
  1787. v3 += pp; // ok
  1788. v4 += pp; // error checked by ra::, shape clash (4) += (3)
  1789. cout << (p + ra::iota()) << endl; // ok
  1790. @end verbatim
  1791. @end example
  1792. You don't need to use @code{ra::ptr} on STL containers and built in arrays, which are converted to rank-1 expressions of the right size automatically. See also @ref{x-start,@code{start}}.
  1793. @end deffn
  1794. @cindex @code{start}
  1795. @anchor{x-start} @defun start foreign_object
  1796. Create array expression from @var{foreign_object}.
  1797. @var{foreign_object} can be a built-in array (e.g. @code{int[3][2]}), a @code{std::random_access_range} type (including @code{std::vector} or @code{std::array}, @pxref{Compatibility}), an initializer list, or any object that @code{ra::} accepts as scalar (see @ref{x-is-scalar,@code{here}}). The resulting expresion has shape according to the original object. Compare this with @ref{x-scalar,@code{scalar}}, which will always produce an expression of rank 0.
  1798. 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.
  1799. @example
  1800. @verbatim
  1801. std::vector<int> x = {1, 2, 3};
  1802. ra::Big<int, 1> y = {10, 20, 30};
  1803. cout << (x+y) << endl; // same as ra::start(x)+y
  1804. // x += y; // error: no match for operator+=
  1805. ra::start(x) += y; // ok
  1806. @end verbatim
  1807. @print{} 3
  1808. 11 22 33
  1809. @result{} x = @{ 11, 22, 33 @}
  1810. @end example
  1811. @end defun
  1812. @cindex @code{scalar}
  1813. @anchor{x-scalar} @defun scalar expr
  1814. Create scalar expression from @var{expr}.
  1815. The primary use of this function is to bring a scalar object into the @code{ra::} namespace. A somewhat artificial example:
  1816. @example
  1817. @verbatim
  1818. struct W { int x; }
  1819. ra::Big<W, 1> w { {1}, {2}, {3} };
  1820. // error: no matching function for call to start(W)
  1821. // for_each([](auto && a, auto && b) { cout << (a.x + b.x) << endl; }, w, W {7});
  1822. // bring W into ra:: with ra::scalar
  1823. for_each([](auto && a, auto && b) { cout << (a.x + b.x) << endl; }, w, ra::scalar(W {7}));
  1824. @end verbatim
  1825. @print{} 8
  1826. 9
  1827. 10
  1828. @end example
  1829. See also @ref{x-scalar-char-star,@code{this example}}.
  1830. 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:
  1831. @example
  1832. @verbatim
  1833. using Vec2 = ra::Small<double, 2>;
  1834. Vec2 x {-1, 1};
  1835. ra::Big<Vec2, 1> c { {1, 2}, {2, 3}, {3, 4} };
  1836. // c += x // error: x has shape (2) and c has shape (3)
  1837. c += ra::scalar(x); // ok: scalar(x) has shape () and matches c.
  1838. @end verbatim
  1839. @result{} c = @{ @{0, 3@}, @{1, 4@}, @{2, 5@} @}
  1840. @end example
  1841. The result is @{c(0)+x, c(1)+x, c(2)+x@}. Compare this with
  1842. @example
  1843. @verbatim
  1844. c(ra::iota(2)) += x; // c(ra::iota(2)) with shape (2) matches x with shape (2)
  1845. @end verbatim
  1846. @result{} c = @{ @{-1, 2@}, @{2, 5@}, @{2, 5@} @}
  1847. @end example
  1848. where the result is @{c(0)+x(0), c(1)+x(1), c(2)@}.
  1849. @end defun
  1850. @cindex @code{iter}
  1851. @anchor{x-iter} @defun iter <k> (view)
  1852. 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 rt or ct shape.
  1853. @example
  1854. @verbatim
  1855. ra::Big<int, 2> c {{1, 3, 2}, {7, 1, 3}};
  1856. cout << "max of each row: " << map([](auto && a) { return amax(a); }, iter<1>(c)) << endl;
  1857. ra::Big<int, 1> m({3}, 0);
  1858. scalar(m) = max(scalar(m), iter<1>(c));
  1859. cout << "max of each column: " << m << endl;
  1860. m = 0;
  1861. for_each([&m](auto && a) { m = max(m, a); }, iter<1>(c));
  1862. cout << "max of each column again: " << m << endl;
  1863. @end verbatim
  1864. @print{} max of each row: 2
  1865. 3 7
  1866. max of each column: 3
  1867. 7 3 3
  1868. max of each column again: 3
  1869. 7 3 3
  1870. @end example
  1871. @c [ma113]
  1872. 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}.
  1873. @example
  1874. @verbatim
  1875. m = 0;
  1876. iter<1>(m) = max(iter<1>(m), iter<1>(c));
  1877. cout << "max of each column yet again: " << m << endl;
  1878. @end verbatim
  1879. @print{} max of each column again: 3
  1880. 7 3 3
  1881. @end example
  1882. The following example computes the trace of each of the items [(-1)-cells] of @code{c}. @c [ma104]
  1883. @example
  1884. @verbatim
  1885. ra::Small<int, 3, 2, 2> c = ra::_0 - ra::_1 - 2*ra::_2;
  1886. cout << "c: " << c << endl;
  1887. cout << "s: " << map([](auto && a) { return sum(diag(a)); }, iter<-1>(c)) << endl;
  1888. @end verbatim
  1889. @print{} c: 0 -2
  1890. -1 -3
  1891. 1 -1
  1892. 0 -2
  1893. 2 0
  1894. 1 -1
  1895. s: -3 -1 -1
  1896. @end example
  1897. @end defun
  1898. @cindex @code{sum}
  1899. @anchor{x-sum} @defun sum expr
  1900. Return the sum (+) of the elements of @var{expr}, or 0 if expr is empty. This sum is performed in unspecified order.
  1901. @end defun
  1902. @cindex @code{prod}
  1903. @anchor{x-prod} @defun prod expr
  1904. Return the product (*) of the elements of @var{expr}, or 1 if expr is empty. This product is performed in unspecified order.
  1905. @end defun
  1906. @cindex @code{amax}
  1907. @anchor{x-amax} @defun amax expr
  1908. 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}.
  1909. @end defun
  1910. @cindex @code{amin}
  1911. @anchor{x-amin} @defun amin expr
  1912. 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}.
  1913. @end defun
  1914. @cindex @code{early}
  1915. @anchor{x-early} @defun early expr default
  1916. @var{expr} is an array expression that returns @code{std::optional<T>}. @var{expr} is traversed as by @code{for_each}. If the optional ever contains a value, traversal stops and that value is returned. If traversal ends, @var{default} is returned instead. If @code{default} is a reference, @code{early} will return its value. @c FIXME
  1917. The following definition of elementwise @code{lexicographical_compare} relies on @code{early}.
  1918. @example @c [ma108]
  1919. @verbatim
  1920. template <class A, class B>
  1921. inline bool
  1922. lexicographical_compare(A && a, B && b)
  1923. {
  1924. return early(map([](auto && a, auto && b) { return a==b ? std::nullopt : std::make_optional(a<b); },
  1925. std::forward<A>(a), std::forward<B>(b)),
  1926. false);
  1927. }
  1928. @end verbatim
  1929. @end example
  1930. @end defun
  1931. @cindex @code{any}
  1932. @anchor{x-any} @defun any expr
  1933. 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.
  1934. @end defun
  1935. @cindex @code{every}
  1936. @anchor{x-every} @defun every expr
  1937. 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.
  1938. @end defun
  1939. @cindex @code{sqr}
  1940. @anchor{x-sqr} @defun sqr expr
  1941. Compute the square of @var{expr}.
  1942. @end defun
  1943. @cindex @code{sqrm}
  1944. @anchor{x-sqrm} @defun sqrm expr
  1945. Compute the square of the norm-2 of @var{expr}, that is, @code{conj(expr)*expr}.
  1946. @end defun
  1947. @cindex @code{conj}
  1948. @anchor{x-conj} @defun conj expr
  1949. Compute the complex conjugate of @var{expr}.
  1950. @end defun
  1951. @cindex @code{xI}
  1952. @anchor{x-xI} @defun xI expr
  1953. Compute @code{(0+1j)} times @var{expr}.
  1954. @end defun
  1955. @cindex @code{rel_error}
  1956. @anchor{x-rel-error} @defun rel_error a b
  1957. @var{a} and @var{b} are arbitrary array expressions. Compute the error of @var{a} relative to @var{b} as
  1958. @code{(a==0. && b==0.) ? 0. : 2.*abs(a, b)/(abs(a)+abs(b))}
  1959. @end defun
  1960. @cindex @code{none}
  1961. @anchor{x-none}
  1962. @deffn @w{Special object} {none}
  1963. 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:
  1964. @example
  1965. @verbatim
  1966. void old_style_initializer(int m, int n, double *);
  1967. ra::Big<double> b({2, 3}, ra::none);
  1968. old_style_initializer(2, 3, b.data());
  1969. @end verbatim
  1970. @end example
  1971. @end deffn
  1972. @c ------------------------------------------------
  1973. @node @mybibnode{}
  1974. @chapter Sources
  1975. @c ------------------------------------------------
  1976. @multitable @columnfractions .1 .9
  1977. @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.
  1978. @item @mybibitem{Ber87} @tab Robert Bernecky. An introduction to function rank. ACM SIGAPL APL Quote Quad, 18(2):39–43, December 1987.
  1979. @item @mybibitem{bli17} @tab The Blitz++ meta-template library. @url{http://blitz.sourceforge.net}, November 2017.
  1980. @item @mybibitem{Cha86} @tab Gregory J. Chaitin. Physics in APL2, June 1986.
  1981. @item @mybibitem{FI68} @tab Adin D. Falkoff and Kenneth Eugene Iverson. APL\360 User’s manual. IBM Thomas J. Watson Research Center, August 1968.
  1982. @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.
  1983. @item @mybibitem{FI78} @tab Adin D. Falkoff and Kenneth Eugene Iverson. The evolution of APL. ACM SIGAPL APL, 9(1):30– 44, 1978.
  1984. @item @mybibitem{J S} @tab J Primer. J Software, @url{https://www.jsoftware.com/help/primer/contents.htm}, November 2017.
  1985. @item @mybibitem{Mat} @tab MathWorks. MATLAB documentation, @url{https://www.mathworks.com/help/matlab/}, November 2017.
  1986. @item @mybibitem{num17} @tab NumPy. @url{http://www.numpy.org}, November 2017.
  1987. @item @mybibitem{Ric08} @tab Henry Rich. J for C programmers, February 2008.
  1988. @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.
  1989. @item @mybibitem{Vel01} @tab Todd Veldhuizen. Blitz++ user’s guide, February 2001.
  1990. @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}
  1991. @end multitable
  1992. @c ------------------------------------------------
  1993. @node Indices
  1994. @unnumbered Indices
  1995. @c ------------------------------------------------
  1996. @c @node Concept Index
  1997. @c @unnumbered Concept Index
  1998. @printindex cp
  1999. @c @node Function Index
  2000. @c @unnumbered Function Index
  2001. @c @printindex fn
  2002. @c \nocite{JLangReference,FalkoffIverson1968,Abrams1970,FalkoffIverson1973,FalkoffIverson1978,APLexamples1,ArraysCowan,KonaTheLanguage,blitz++2001}
  2003. @c ------------------------------------------------
  2004. @node Notes
  2005. @unnumbered Notes
  2006. @c ------------------------------------------------
  2007. @enumerate
  2008. @item
  2009. @code{ra::} uses the non standard @code{#pragma once} (supported on all major compilers).
  2010. @end enumerate
  2011. @bye