ra-ra.texi 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626
  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 26
  13. @set UPDATED 2023 November 21
  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::} in order to override the default handler. 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 @ref{x-for_each,@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 non-pointer types for which @code{std::is_scalar_v} is true, like @code{char}, @code{int}, @code{double}, etc. as well as @code{std::complex<T>}. You can add your own types as scalar types with the following declaration:
  1008. @verbatim
  1009. namespace ra { template <> constexpr bool is_scalar_def<MYTYPE> = true; }
  1010. @end verbatim
  1011. Otherwise, you can bring a scalar object into @code{ra::} on the spot, with the function @ref{x-scalar,@code{scalar}}.
  1012. @subsection Using @code{ra::} types with the STL
  1013. General @code{ra::} @ref{Containers and views,views} provide STL compatible @code{std::input_iterator}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.
  1014. For @ref{Containers and views,containers} @code{begin()} provides @code{std::random_access_iterator}s, which is handy for certain functions such as @code{std::sort}. There's no reason why all views couldn't provide @code{std::random_access_iterator}, but these wouldn't be efficient for ranks above 1, and I haven't implemented them. The container @code{std::random_access_iterator}s that are provided are in fact raw pointers.
  1015. @example @c [ma106]
  1016. @verbatim
  1017. ra::Big<int> x {3, 2, 1}; // x is a Container
  1018. auto y = x(); // y is a View on x
  1019. // std::sort(y.begin(), y.end()); // error: y.begin() is not std::random_access_iterator
  1020. std::sort(x.begin(), x.end()); // ok, we know x is stored in row-major order
  1021. @end verbatim
  1022. @result{} x = @{1, 2, 3@}
  1023. @end example
  1024. @cindex other libraries, interfacing with
  1025. @subsection Using @code{ra::} types with other libraries
  1026. 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.
  1027. @subsubsection The good array citizen
  1028. @c FIXME Put these in examples/ and reference them here.
  1029. @cindex BLIS
  1030. 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}:
  1031. @quotation
  1032. @verbatim
  1033. #include <blis.h>
  1034. ra::Big<double, 2> A({M, K}, ...);
  1035. ra::Big<double, 2> B({K, N}, ...);
  1036. ra::Big<double, 2> C({M, N}, ...);
  1037. double alpha = ...;
  1038. double beta = ...;
  1039. // C := βC + αAB
  1040. bli_dgemm(BLIS_NO_TRANSPOSE, BLIS_NO_TRANSPOSE, M, N, K, &alpha,
  1041. A.data(), A.step(0), A.step(1),
  1042. B.data(), B.step(0), B.step(1),
  1043. &beta, C.data(), C.step(0), C.step(1));
  1044. @end verbatim
  1045. @end quotation
  1046. @cindex FFTW
  1047. Another good array citizen, @url{http://fftw.org, FFTW} handles arbitrary rank:
  1048. @quotation
  1049. @verbatim
  1050. #include <fftw3.h>
  1051. ...
  1052. using complex = std::complex<double>;
  1053. static_assert(sizeof(complex)==sizeof(fftw_complex));
  1054. // forward DFT over the last r axes of a -> b
  1055. void fftw(int r, ra::View<complex> const a, ra::View<complex> b)
  1056. {
  1057. int const rank = a.rank();
  1058. assert(r>0 && r<=rank);
  1059. assert(every(ra::start(shape(a))==shape(b)));
  1060. fftw_iodim dims[r];
  1061. fftw_iodim howmany_dims[rank-r];
  1062. for (int i=0; i!=rank; ++i) {
  1063. if (i>=rank-r) {
  1064. dims[i-rank+r].n = a.len(i);
  1065. dims[i-rank+r].is = a.step(i);
  1066. dims[i-rank+r].os = b.step(i);
  1067. } else {
  1068. howmany_dims[i].n = a.len(i);
  1069. howmany_dims[i].is = a.step(i);
  1070. howmany_dims[i].os = b.step(i);
  1071. }
  1072. }
  1073. fftw_plan p;
  1074. p = fftw_plan_guru_dft(r, dims, rank-r, howmany_dims,
  1075. (fftw_complex *)(a.data()), (fftw_complex *)(b.data()),
  1076. FFTW_FORWARD, FFTW_ESTIMATE);
  1077. fftw_execute(p);
  1078. fftw_destroy_plan(p);
  1079. }
  1080. @end verbatim
  1081. @end quotation
  1082. @cindex Guile
  1083. 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:
  1084. @quotation
  1085. @verbatim
  1086. SCM a; // say a is #nf64(...)
  1087. ...
  1088. scm_t_array_handle h;
  1089. scm_array_get_handle(a, &h);
  1090. scm_t_array_dim const * dims = scm_array_handle_dims(&h);
  1091. View<double> v(map([](int i) { return ra::Dim { dims[i].ubnd-dims[i].lbnd+1, dims[i].inc }; },
  1092. ra::iota(scm_array_handle_rank(&h))),
  1093. scm_array_handle_f64_writable_elements(&h));
  1094. ...
  1095. scm_array_handle_release(&h);
  1096. @end verbatim
  1097. @end quotation
  1098. @cindex Numpy
  1099. @cindex Python
  1100. 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.
  1101. 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}}).
  1102. @subsubsection The bad array citizen
  1103. 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.
  1104. 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.
  1105. @c FIXME using is_c_order, etc.
  1106. Other libraries do accept steps, but not arbitrary ones. For example @url{https://www.netlib.org/blas}' @code{cblas_dgemm} has this prototype:
  1107. @quotation
  1108. @verbatim
  1109. cblas_dgemm(order, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
  1110. @end verbatim
  1111. @end quotation
  1112. @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}.
  1113. 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.
  1114. @cindex OpenGL
  1115. OpenGL is another library that requires @url{https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVertexAttribPointer.xhtml,contortions:}
  1116. @quotation
  1117. @verbatim
  1118. void glVertexAttribPointer(GLuint index,
  1119. GLint size,
  1120. GLenum type,
  1121. GLboolean normalized,
  1122. GLsizei step,
  1123. const GLvoid * pointer);
  1124. @end verbatim
  1125. [...]
  1126. @emph{step}
  1127. @quotation
  1128. 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.
  1129. @end quotation
  1130. @end quotation
  1131. It isn't clear whether negative steps are legal, either. So just as with CBLAS, passing arbitrary array views may require copies.
  1132. @c ------------------------------------------------
  1133. @node Extension
  1134. @section Extension
  1135. @c ------------------------------------------------
  1136. @subsection New scalar types
  1137. @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}.
  1138. @example
  1139. @verbatim
  1140. struct W { int x; }
  1141. ra::Big<W, 2> w = {{ {4}, {2} }, { {1}, {3} }};
  1142. cout << W(1, 1).x << endl;
  1143. cout << amin(map([](auto && x) { return w.x; }, w)) << endl;
  1144. @end verbatim
  1145. @print{} 3
  1146. 1
  1147. @end example
  1148. 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.
  1149. @example
  1150. @verbatim
  1151. namespace ra { template <> constexpr bool is_scalar_def<W> = true; }
  1152. ...
  1153. W ww {11};
  1154. for_each([](auto && x, auto && y) { cout << (x.x + y.y) << " "; }, w, ww); // ok
  1155. @end verbatim
  1156. @print{} 15 13 12 14
  1157. @end example
  1158. but
  1159. @example
  1160. @verbatim
  1161. struct U { int x; }
  1162. U uu {11};
  1163. for_each([](auto && x, auto && y) { cout << (x.x + y.y) << " "; }, w, uu); // error: can't find ra::start(U)
  1164. @end verbatim
  1165. @end example
  1166. @anchor{x-new-array-operations}
  1167. @subsection New array operations
  1168. @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):
  1169. @example
  1170. @verbatim
  1171. return_type my_fun(...) { };
  1172. ...
  1173. namespace ra {
  1174. template <class ... A> inline auto
  1175. my_fun(A && ... a)
  1176. {
  1177. return map(::my_fun, std::forward<A>(a) ...);
  1178. }
  1179. } // namespace ra
  1180. @end verbatim
  1181. @end example
  1182. @cindex overload set
  1183. 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}.}
  1184. @example
  1185. @verbatim
  1186. namespace ra {
  1187. template <class ... A> inline auto
  1188. my_fun(A && ... a)
  1189. {
  1190. return map([](auto && ... a) { return ::my_fun(a ...); }, std::forward<A>(a) ...);
  1191. }
  1192. } // namespace ra
  1193. @end verbatim
  1194. @end example
  1195. @cindex error
  1196. @cindex assert
  1197. @c ------------------------------------------------
  1198. @node Error handling
  1199. @section Error handling
  1200. @c ------------------------------------------------
  1201. Error handling in @code{ra::} is controlled by two macros:
  1202. @itemize
  1203. @item @code{RA_DO_CHECK}
  1204. 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}.
  1205. @item @code{RA_ASSERT(cond, ...)}
  1206. 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.
  1207. @end itemize
  1208. @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}.
  1209. 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.
  1210. @c ------------------------------------------------
  1211. @node Extras
  1212. @chapter Extras
  1213. @c ------------------------------------------------
  1214. @c ------------------------------------------------
  1215. @node Hazards
  1216. @chapter Hazards
  1217. @c ------------------------------------------------
  1218. 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.
  1219. @section Reuse of expression objects
  1220. 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:
  1221. @example
  1222. @verbatim
  1223. ra::Big<int, 2> B({3, 3}, ra::_1 + ra::_0*3); // {{0 1 2} {3 4 5} {6 7 8}}
  1224. std::array<int, 2> l = { 1, 2 };
  1225. cout << B(ra::ptr(l), ra::ptr(l)) << endl; // ok => {{4 5} {7 8}}
  1226. auto ll = ra::ptr(l);
  1227. cout << B(ll, ll) << endl; // ??
  1228. @end verbatim
  1229. @end example
  1230. @section Assignment to views
  1231. FIXME
  1232. 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.
  1233. @section View of const vs const view
  1234. @c FIXME
  1235. FIXME
  1236. Passing view arguments by reference
  1237. @section Rank extension in assignments
  1238. 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.
  1239. @example @c [ma107]
  1240. @verbatim
  1241. int a = 0;
  1242. ra::scalar(a) = 3 + ra::Small<int, 3> {4, 5, 6}; // ?
  1243. @end verbatim
  1244. @result{} a = 9
  1245. @end example
  1246. Compare with
  1247. @example
  1248. @verbatim
  1249. int a = 0;
  1250. ra::scalar(a) += 3 + ra::Small<int, 3> {4, 5, 6}; // 0 + 3 + 4 + 5 + 6
  1251. @end verbatim
  1252. @result{} a = 18
  1253. @end example
  1254. @section Performance pitfalls of rank extension
  1255. 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.
  1256. @example
  1257. @verbatim
  1258. ra::Big<int, 2> a = {{1, 2, 3, 4}, {5, 6, 7, 8} {9, 10, 11, 12}};
  1259. ra::Big<int, 1> b = {1, 2, 3};
  1260. ra::Big<int, 2> c = map(f, b) + a;
  1261. @end verbatim
  1262. @end example
  1263. @section Chained assignment
  1264. FIXME
  1265. When @code{a=b=c} works, it operates as @code{b=c; a=b;} and not as an array expression.
  1266. @section Unregistered scalar types
  1267. FIXME
  1268. @code{View<T, N> x; x = T()} fails if @code{T} isn't registered as @code{is_scalar}.
  1269. @enumerate
  1270. @item
  1271. Item 0
  1272. @item
  1273. Item 1
  1274. @item
  1275. Item 2
  1276. @end enumerate
  1277. @c ------------------------------------------------
  1278. @node Internals
  1279. @chapter Internals
  1280. @c ------------------------------------------------
  1281. @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).
  1282. @menu
  1283. * Header structure::
  1284. * Type hierarchy::
  1285. * Term agreement::
  1286. * Loop types::
  1287. * Introspection::
  1288. * Building with @code{ra::}::
  1289. @end menu
  1290. @c ------------------------------------------------
  1291. @node Headers
  1292. @section Headers
  1293. @c ------------------------------------------------
  1294. The header structure of @code{ra::} is as follows.@footnote{Diagram generated using Graphviz and @url{https://www.flourish.org/cinclude2dot}.
  1295. @verbatim
  1296. cd ra && cinclude2dot.pl --include . > headers.dot
  1297. dot -Tpng headers.dot -Gdpi=100 > headers.png
  1298. @end verbatim
  1299. }
  1300. @itemize
  1301. @item @code{tuples.hh} -
  1302. Generic macros and tuple library.
  1303. @item @code{bootstrap.hh} -
  1304. Basic types, concepts, type predicates, introspection.
  1305. @item @code{expr.hh} -
  1306. Expression template nodes, prefix matching.
  1307. @item @code{ply.hh} -
  1308. Traversal, including I/O.
  1309. @item @code{small.hh} -
  1310. Array type with compile time dimensions.
  1311. @item @code{big.hh} -
  1312. Array type with run time dimensions.
  1313. @item @code{optimize.hh} -
  1314. Optimization templates.
  1315. @item @code{ra.hh} -
  1316. Functions and operators. Main header.
  1317. @item @code{test.hh} -
  1318. (accessory) Testing library.
  1319. @item @code{bench.hh} -
  1320. (accessory) Benchmarking library.
  1321. @item @code{dual.hh} -
  1322. (accessory) Dual number type and operations.
  1323. @end itemize
  1324. @image{headers,4cm}
  1325. @c ------------------------------------------------
  1326. @node Type hierarchy
  1327. @section Type hierarchy
  1328. @c ------------------------------------------------
  1329. Some of the categories below are C++20 ‘concepts’, some are still informal.
  1330. @itemize
  1331. @item @b{Container} --- @code{Big}, @code{Shared}, @code{Unique}, @code{Small}
  1332. These are array types that own their data in one way or another. Creating or destroying these objects may allocate or deallocate memory, respectively.
  1333. @item @b{View} --- @code{View}, @code{SmallView}
  1334. 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.
  1335. @item @b{Iterator} --- @code{CellBig}, @code{CellSmall}, @code{Iota}, @code{Ptr}, @code{Scalar}, @code{Expr}, @code{Pick}
  1336. 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.
  1337. @b{Iterator}s have two traversal functions: @code{.adv(k, d)}, moves the iterator along any dimension @var{k}, and @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.
  1338. @b{Iterator}s also provide an @code{at(i ...)} method for random access to any element.
  1339. @end itemize
  1340. @c ------------------------------------------------
  1341. @node Term agreement
  1342. @section Term agreement
  1343. @c ------------------------------------------------
  1344. 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 dimensions created with @code{insert}) are ignored. All the other terms must match.
  1345. 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.
  1346. 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.
  1347. @c ------------------------------------------------
  1348. @node Loop types
  1349. @section Loop types
  1350. @c ------------------------------------------------
  1351. TODO
  1352. @c ------------------------------------------------
  1353. @node Introspection
  1354. @section Introspection
  1355. @c ------------------------------------------------
  1356. The following functions are available to query the properties of @code{ra::} objects.
  1357. @cindex @code{rank}
  1358. @anchor{x-rank}
  1359. @deftypefn @w{Function} rank_t rank e
  1360. Return the rank of expression @var{e}.
  1361. @end deftypefn
  1362. @cindex @code{shape}
  1363. @anchor{x-shape}
  1364. @deftypefn @w{Function} array shape e
  1365. @deftypefnx @w{Function} dim_t shape e k
  1366. 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)}.
  1367. @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.
  1368. @end deftypefn
  1369. @c ------------------------------------------------
  1370. @node Building with @code{ra::}
  1371. @section Building with @code{ra::}
  1372. @c ------------------------------------------------
  1373. The following @code{#define}s affect the behavior of @code{ra::}.
  1374. @itemize
  1375. @c FIXME The flag should only apply to dynamic checks.
  1376. @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}.
  1377. @item @code{RA_DO_OPT} (default 1): Sets the default for all @code{RA_DO_OPT_XXX} flags.
  1378. @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.
  1379. @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.
  1380. @end itemize
  1381. @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}. @code{ra::} is highly dependent on optimization by the compiler and will be much slower with @option{-O0}.
  1382. The following environment variables affect the test suite under SCons:
  1383. @itemize
  1384. @item @code{RA_USE_BLAS} (default 0): Use BLAS for @code{gemm} and @code{gemv} benchmarks.
  1385. @end itemize
  1386. @c TODO Flags and notes about different compilers
  1387. @c ------------------------------------------------
  1388. @node The future
  1389. @chapter The future
  1390. @c ------------------------------------------------
  1391. @section Error messages
  1392. FIXME
  1393. @section Reductions
  1394. FIXME
  1395. @section Etc
  1396. FIXME
  1397. @c ------------------------------------------------
  1398. @node Reference
  1399. @chapter Reference
  1400. @c ------------------------------------------------
  1401. @cindex @code{agree}
  1402. @anchor{x-agree} @defun agree arg ...
  1403. Return true if the shapes of arguments @var{arg...} match (see @ref{Rank extension}), else return false.
  1404. This is useful when @ref{Error handling,error checking} is enabled and one wants to avoid the failure response.
  1405. @example
  1406. @verbatim
  1407. ra::Small<int, 2, 3> A;
  1408. ra::Small<int, 2> B;
  1409. ra::Small<int, 3> C;
  1410. agree(A, B); // -> true
  1411. static_assert(agree(A, B)); // ok for ct shapes
  1412. cout << (A+B) << endl; // ok
  1413. agree(A, C); // -> false
  1414. cout << (A+C) << endl; // error. Maybe abort, maybe throw - cf Error Handling
  1415. @end verbatim
  1416. @end example
  1417. @end defun
  1418. @cindex @code{agree_op}
  1419. @anchor{x-agree_op} @defun agree_op op arg ...
  1420. Return true if the shapes of arguments @var{arg...} match (see @ref{Rank extension}) relative to operator @var{op}, else return false.
  1421. This differs from @ref{x-agree,@code{agree}} when @var{op} has non-zero argument ranks. For example:
  1422. @example
  1423. @verbatim
  1424. ra::Big<real, 1> a({3}, 0.);
  1425. ra::Big<real, 2> b({2, 3}, 0.n);
  1426. agree(a, b); // -> false
  1427. cout << (a+b) << endl; // error
  1428. agree_op(ra::wrank<1, 1>(std::plus()), a, b); // -> true
  1429. cout << map(ra::wrank<1, 1>(std::plus()), a, b) << endl; // ok
  1430. @end verbatim
  1431. @end example
  1432. @end defun
  1433. @cindex @code{at}
  1434. @anchor{x-at} @defun at expr indices
  1435. Look up @var{expr} at each element of @var{indices}, which shall be a multi-index into @var{expr}.
  1436. This can be used for sparse subscripting. For example:
  1437. @example @c [ra30]
  1438. @verbatim
  1439. ra::Big<int, 2> A = {{100, 101}, {110, 111}, {120, 121}};
  1440. ra::Big<ra::Small<int, 2>, 2> i = {{{0, 1}, {2, 0}}, {{1, 0}, {2, 1}}};
  1441. ra::Big<int, 2> B = at(A, i);
  1442. @end verbatim
  1443. @result{} B = @{@{101, 120@}, @{110, 121@}@}
  1444. @end example
  1445. @end defun
  1446. @cindex @code{cast}
  1447. @anchor{x-cast} @defun cast <type> expr
  1448. Create an array expression that casts @var{expr} into @var{type}.
  1449. @end defun
  1450. @cindex @code{collapse}
  1451. @anchor{x-collapse} @defun collapse
  1452. TODO
  1453. See also @ref{x-explode,@code{explode}}.
  1454. @end defun
  1455. @cindex @code{concrete}
  1456. @anchor{x-concrete} @defun concrete a
  1457. Convert the argument to a container of the same shape as @var{a}.
  1458. 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.
  1459. @c FIXME example
  1460. @end defun
  1461. @cindex @code{diag}
  1462. @anchor{x-diag} @defun diag view
  1463. Equivalent to @code{transpose<0, 0>(view)}.
  1464. @end defun
  1465. @cindex @code{explode}
  1466. @anchor{x-explode} @defun explode
  1467. TODO
  1468. See also @ref{x-collapse,@code{collapse}}.
  1469. @end defun
  1470. @cindex @code{for_each}
  1471. @anchor{x-for_each} @defun for_each op expr ...
  1472. Create an array expression that applies @var{op} to @var{expr} ..., and traverse it. The return value of @var{op} is discarded.
  1473. For example:
  1474. @example
  1475. @verbatim
  1476. double s = 0.;
  1477. for_each([&s](auto && a) { s+=a; }, ra::Small<double, 1> {1., 2., 3})
  1478. @end verbatim
  1479. @result{} s = 6.
  1480. @end example
  1481. See also @ref{x-map,@code{map}}.
  1482. @end defun
  1483. @cindex @code{format_array}
  1484. @anchor{x-format_array} @defun format_array expr [last_axis_separator [second_last_axis_separator ...]]
  1485. Formats an array for character output.
  1486. For example:
  1487. @example
  1488. @verbatim
  1489. ra::Small<int, 2, 2> A = {{1, 2}, {3, 4}};
  1490. cout << "case a:\n" << A << endl;
  1491. cout << "case b:\n" << format_array(A) << endl;
  1492. cout << "case c:\n" << format_array(A, "|", "-") << endl;
  1493. @end verbatim
  1494. @print{} case a:
  1495. 1 2
  1496. 3 4
  1497. case b:
  1498. 1 2
  1499. 3 4
  1500. case c:
  1501. 1|2-3|4
  1502. @end example
  1503. The shape that might be printed before the expression itself (depending on its type) is not subject to these separators.
  1504. See also @ref{x-noshape,@code{noshape}}, @ref{x-withshape,@code{withshape}}.
  1505. @end defun
  1506. @cindex @code{from}
  1507. @anchor{x-from} @defun from op expr ...
  1508. Create outer product expression. This is defined as
  1509. @display
  1510. E = from(op, e₀, e₁ ...) ⇒ E(i₀₀, i₀₁ ..., i₁₀, i₁₁, ..., ...) = op[expr₀(i₀₀, i₀₁, ...), expr₁(i₁₀, i₁₁, ...), ...].
  1511. @end display
  1512. For example:
  1513. @example
  1514. @verbatim
  1515. ra::Big<double, 1> a {1, 2, 3};
  1516. ra::Big<double, 1> b {10, 20, 30};
  1517. ra::Big<double, 2> axb = from([](auto && a, auto && b) { return a*b; }, a, b)
  1518. @end verbatim
  1519. @result{} axb = @{@{10, 20, 30@}, @{20, 40, 60@}, @{30, 60, 90@}@}
  1520. @end example
  1521. @example
  1522. @verbatim
  1523. ra::Big<int, 1> i {2, 1};
  1524. ra::Big<int, 1> j {0, 1};
  1525. ra::Big<double, 2> A = {{1, 2}, {3, 4}, {5, 6}};
  1526. ra::Big<double, 2> Aij = from(A, i, j)
  1527. @end verbatim
  1528. @result{} Aij = @{@{6, 5@}, @{4, 3@}@}
  1529. @end example
  1530. The last example is more or less how @code{A(i, j)} is implemented for arbitrary subscripts (@pxref{The rank conjunction}).
  1531. @end defun
  1532. @cindex @code{imag_part}
  1533. @anchor{x-imag_part} @defun imag_part
  1534. Take imaginary part of a complex number. This can be used as reference.
  1535. For example: @c [ma115]
  1536. @example
  1537. @verbatim
  1538. ra::Small<std::complex<double>, 2, 2> A = {{1., 2.}, {3., 4.}};
  1539. imag_part(A) = -2*real_part(A);
  1540. cout << A << endl;
  1541. @end verbatim
  1542. @print{}
  1543. (1, -2) (2, -4)
  1544. (3, -6) (4, -8)
  1545. @end example
  1546. See also @ref{x-real_part,@code{real_part}}.
  1547. @end defun
  1548. @cindex @code{map}
  1549. @anchor{x-map} @defun map op expr ...
  1550. Create an array expression that applies callable @var{op} to @var{expr} ...
  1551. For example:
  1552. @example
  1553. @verbatim
  1554. ra::Big<double, 1> x = map(cos, std::array {0.});
  1555. @end verbatim
  1556. @result{} x = @{ 1. @}
  1557. @end example
  1558. @var{op} can return a reference. For example:
  1559. @example
  1560. @verbatim
  1561. ra::Big<int, 2> x = {{3, 3}, 0.};
  1562. ra::Big<int, 2> i = {0, 1, 1, 2};
  1563. ra::Big<int, 2> j = {1, 0, 2, 1};
  1564. map(x, i, j) = 1;
  1565. @end verbatim
  1566. @result{} x = @{@{0, 1, 0@}, @{1, 0, 1@}, @{0, 1, 0@}@}
  1567. @end example
  1568. Note that @code{map(x, i, j)} is @ref{x-subscript-outer-product,not the same} as @code{x(i, j)}.
  1569. @var{op} can be any callable. For example:
  1570. @example
  1571. @verbatim
  1572. struct A { int a, b; };
  1573. std::vector<A> v = {{1, 2}, {3, 4}};
  1574. ra::map(&A::a, v) = -ra::map(&A::b, v); // pointer to member
  1575. @end verbatim
  1576. @result{} v = @{@{-2, 2@}, @{-4, 4@}@}
  1577. @end example
  1578. See also @ref{x-for_each,@code{for_each}}.
  1579. @end defun
  1580. @cindex @code{pack}
  1581. @anchor{x-pack} @defun pack <type> expr ...
  1582. Create an array expression that brace-constructs @var{type} from @var{expr} ...
  1583. @end defun
  1584. @cindex @code{pick}
  1585. @anchor{x-pick} @defun pick select_expr expr ...
  1586. 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.
  1587. 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}.
  1588. For example:
  1589. @example @c cf examples/readme.cc [ma100].
  1590. @verbatim
  1591. ra::Small<int, 3> s {2, 1, 0};
  1592. ra::Small<double, 3> z = pick(s, s*s, s+s, sqrt(s));
  1593. @end verbatim
  1594. @result{} z = @{1.41421, 2, 0@}
  1595. @end example
  1596. @end defun
  1597. @cindex @code{ply}
  1598. @anchor{x-ply} @defun ply expr
  1599. Traverse @var{expr}. @code{ply} returns @code{void} so @var{expr} should be run for effect.
  1600. 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.
  1601. @example
  1602. @verbatim
  1603. double s = 0.;
  1604. ply(map([&s](auto && a) { s+=a; }, ra::Small<double, 1> {1., 2., 3})) // same as for_each
  1605. @end verbatim
  1606. @result{} s = 6.
  1607. @end example
  1608. @end defun
  1609. @cindex @code{real_part}
  1610. @anchor{x-real_part} @defun real_part
  1611. Take real part of a complex number. This can be used as reference.
  1612. See also @ref{x-imag_part,@code{imag_part}}.
  1613. @end defun
  1614. @cindex @code{reverse}
  1615. @anchor{x-reverse} @defun reverse view axis
  1616. Create a new view by reversing axis @var{k} of @var{view}.
  1617. This is equivalent to @code{view(ra::dots<k>, ra::iota(ra::len, ra::len-1, -1))}.
  1618. This operation does not work on arbitrary array expressions yet. TODO FILL
  1619. @end defun
  1620. @cindex @code{size}
  1621. @anchor{x-size} @defun size a
  1622. Get the total size of an @code{ra::} object: the product of all its lengths.
  1623. @end defun
  1624. @c FIXME example
  1625. @cindex @code{stencil}
  1626. @anchor{x-stencil} @defun stencil view lo hi
  1627. Create a stencil on @var{view} with lower bounds @var{lo} and higher bounds @var{hi}.
  1628. @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), ...)}.
  1629. This operation does not work on arbitrary array expressions yet. TODO FILL
  1630. @end defun
  1631. @cindex @code{swap}
  1632. @anchor{x-swap} @defun swap a b
  1633. Swap the contents of containers @var{a} and @var{b}.
  1634. 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.
  1635. 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)}).
  1636. @end defun
  1637. @example @c [ra30]
  1638. @verbatim
  1639. ra::Big<int> a ({2, 3}, 1 + ra::_0 - ra::_1); // (1)
  1640. ra::Big<int> b ({2, 3, 4}, 1 - ra::_0 + ra::_1 + ra::_2); // (2)
  1641. swap(a, b);
  1642. // as if (1) had b and (2) had a
  1643. @end verbatim
  1644. @end example
  1645. @cindex @code{transpose}
  1646. @anchor{x-transpose}
  1647. @defun transpose <axes ...> (view) | (axes, view)
  1648. Create a new view by transposing the axes of @var{view}. The number of @var{axes} must match the rank of @var{view}.
  1649. For example:
  1650. @example
  1651. @verbatim
  1652. ra::Unique<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  1653. cout << transpose<1, 0>(a) << endl;
  1654. @end verbatim
  1655. @print{}
  1656. 3 2
  1657. 1 4
  1658. 2 5
  1659. 3 6
  1660. @end example
  1661. 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:
  1662. @example
  1663. @verbatim
  1664. ra::Unique<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  1665. cout << transpose<0, 0>(a) << endl; // { a(0, 0), a(1, 1) }
  1666. @end verbatim
  1667. @print{}
  1668. 2
  1669. 1 5
  1670. @end example
  1671. 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:
  1672. @example
  1673. @verbatim
  1674. ra::Unique<double, 1> a = {1, 2, 3};
  1675. cout << ((a*10) + transpose<1>(a)) << endl;
  1676. @end verbatim
  1677. @print{}
  1678. 3 3
  1679. 11 21 31
  1680. 12 22 32
  1681. 13 23 33
  1682. @end example
  1683. 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]
  1684. @example
  1685. @verbatim
  1686. ra::Small<int, 2> axes = {0, 1};
  1687. ra::Unique<double, 2> a = {{1, 2, 3}, {4, 5, 6}};
  1688. cout << "A: " << transpose(axes, a) << endl;
  1689. axes = {1, 0};
  1690. cout << "B: " << transpose(axes, a) << endl;
  1691. @end verbatim
  1692. @print{}
  1693. A: 2
  1694. 2 3
  1695. 1 2 3
  1696. 4 5 6
  1697. B: 2
  1698. 3 2
  1699. 1 4
  1700. 2 5
  1701. 3 6
  1702. @end example
  1703. This operation does not work on arbitrary array expressions yet. TODO FILL
  1704. @end defun
  1705. @cindex @code{where}
  1706. @anchor{x-where} @defun where pred_expr true_expr false_expr
  1707. 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.
  1708. For example:
  1709. @example
  1710. @verbatim
  1711. ra::Big<double, 1> s {1, -1, 3, 2};
  1712. s = where(s>=2, 2, s); // saturate s
  1713. @end verbatim
  1714. @result{} s = @{1, -1, 2, 2@}
  1715. @end example
  1716. @end defun
  1717. @cindex @code{wrank}
  1718. @anchor{x-wrank} @defun wrank <input_rank ...> op
  1719. Wrap @var{op} using a rank conjunction (@pxref{The rank conjunction}).
  1720. For example: TODO
  1721. @example
  1722. @verbatim
  1723. @end verbatim
  1724. @result{} x = 0
  1725. @end example
  1726. @end defun
  1727. @c @anchor{x-reshape}
  1728. @c @defun reshape view shape
  1729. @c Create a new view with shape @var{shape} from the row-major ravel of @var{view}.
  1730. @c FIXME fill when the implementation is more mature...
  1731. @c @end defun
  1732. @c @anchor{x-ravel}
  1733. @c @defun ravel view
  1734. @c Return the ravel of @var{view} as a view on @var{view}.
  1735. @c FIXME fill when the implementation is more mature...
  1736. @c @end defun
  1737. @cindex @code{noshape}
  1738. @cindex @code{withshape}
  1739. @anchor{x-noshape}
  1740. @anchor{x-withshape}
  1741. @deffn @w{Special object} {withshape noshape}
  1742. 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.
  1743. 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.
  1744. For example:
  1745. @example
  1746. @verbatim
  1747. ra::Small<int, 2, 2> A = {77, 99};
  1748. cout << "case a:\n" << A << endl;
  1749. cout << "case b:\n" << ra::noshape << A << endl;
  1750. cout << "case c:\n" << ra::withshape << A << endl;
  1751. @end verbatim
  1752. @print{} case a:
  1753. 77 99
  1754. case b:
  1755. 77 99
  1756. case c:
  1757. 2
  1758. 77 99
  1759. @end example
  1760. but:
  1761. @example
  1762. @verbatim
  1763. ra::Big<int> A = {77, 99};
  1764. cout << "case a:\n" << A << endl;
  1765. cout << "case b:\n" << ra::noshape << A << endl;
  1766. cout << "case c:\n" << ra::withshape << A << endl;
  1767. @end verbatim
  1768. @print{} case a:
  1769. 1
  1770. 2
  1771. 77 99
  1772. case b:
  1773. 77 99
  1774. case c:
  1775. 1
  1776. 2
  1777. 77 99
  1778. @end example
  1779. 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}.
  1780. See also @ref{x-format_array,@code{format_array}}.
  1781. @end deffn
  1782. @cindex @code{ptr}
  1783. @anchor{x-ptr}
  1784. @deffn @w{Function} ptr bidirectional_iterator [len]
  1785. @deffnx @w{Function} ptr bidirectional_range
  1786. Create rank-1 expression from foreign object.
  1787. 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:
  1788. @example
  1789. @verbatim
  1790. int pp[] = {1, 2, 3};
  1791. int * p = pp; // erase length
  1792. ra::Big<int, 1> v3 {1, 2, 3};
  1793. ra::Big<int, 1> v4 {1, 2, 3, 4};
  1794. v3 += ra::ptr(p); // ok, shape (3): v3 = {2, 4, 6}
  1795. v4 += ra::ptr(p); // undefined, shape (4): bad access to p[3]
  1796. // cout << (ra::ptr(p)+ra::iota()) << endl; // ct error, expression has undefined shape
  1797. cout << (ra::ptr(p, 3)+ra::iota()) << endl; // ok, prints { 1, 3, 5 }
  1798. cout << (ra::ptr(p, 4)+ra::iota()) << endl; // undefined, bad access at p[4]
  1799. @end verbatim
  1800. @end example
  1801. 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.
  1802. @example
  1803. @verbatim
  1804. v3 += pp; // ok
  1805. v4 += pp; // error checked by ra::, shape clash (4) += (3)
  1806. cout << (p + ra::iota()) << endl; // ok
  1807. @end verbatim
  1808. @end example
  1809. 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}}.
  1810. @end deffn
  1811. @cindex @code{start}
  1812. @anchor{x-start} @defun start foreign_object
  1813. Create array expression from @var{foreign_object}.
  1814. @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.
  1815. 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.
  1816. @example
  1817. @verbatim
  1818. std::vector<int> x = {1, 2, 3};
  1819. ra::Big<int, 1> y = {10, 20, 30};
  1820. cout << (x+y) << endl; // same as ra::start(x)+y
  1821. // x += y; // error: no match for operator+=
  1822. ra::start(x) += y; // ok
  1823. @end verbatim
  1824. @print{} 3
  1825. 11 22 33
  1826. @result{} x = @{ 11, 22, 33 @}
  1827. @end example
  1828. @end defun
  1829. @cindex @code{scalar}
  1830. @anchor{x-scalar} @defun scalar expr
  1831. Create scalar expression from @var{expr}.
  1832. The primary use of this function is to bring a scalar object into the @code{ra::} namespace. A somewhat artificial example:
  1833. @example
  1834. @verbatim
  1835. struct W { int x; }
  1836. ra::Big<W, 1> w { {1}, {2}, {3} };
  1837. // error: no matching function for call to start(W)
  1838. // for_each([](auto && a, auto && b) { cout << (a.x + b.x) << endl; }, w, W {7});
  1839. // bring W into ra:: with ra::scalar
  1840. for_each([](auto && a, auto && b) { cout << (a.x + b.x) << endl; }, w, ra::scalar(W {7}));
  1841. @end verbatim
  1842. @print{} 8
  1843. 9
  1844. 10
  1845. @end example
  1846. See also @ref{x-scalar-char-star,@code{this example}}.
  1847. 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:
  1848. @example
  1849. @verbatim
  1850. using Vec2 = ra::Small<double, 2>;
  1851. Vec2 x {-1, 1};
  1852. ra::Big<Vec2, 1> c { {1, 2}, {2, 3}, {3, 4} };
  1853. // c += x // error: x has shape (2) and c has shape (3)
  1854. c += ra::scalar(x); // ok: scalar(x) has shape () and matches c.
  1855. @end verbatim
  1856. @result{} c = @{ @{0, 3@}, @{1, 4@}, @{2, 5@} @}
  1857. @end example
  1858. The result is @{c(0)+x, c(1)+x, c(2)+x@}. Compare this with
  1859. @example
  1860. @verbatim
  1861. c(ra::iota(2)) += x; // c(ra::iota(2)) with shape (2) matches x with shape (2)
  1862. @end verbatim
  1863. @result{} c = @{ @{-1, 2@}, @{2, 5@}, @{2, 5@} @}
  1864. @end example
  1865. where the result is @{c(0)+x(0), c(1)+x(1), c(2)@}.
  1866. @end defun
  1867. @cindex @code{iter}
  1868. @anchor{x-iter} @defun iter <k> (view)
  1869. 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.
  1870. @example
  1871. @verbatim
  1872. ra::Big<int, 2> c {{1, 3, 2}, {7, 1, 3}};
  1873. cout << "max of each row: " << map([](auto && a) { return amax(a); }, iter<1>(c)) << endl;
  1874. ra::Big<int, 1> m({3}, 0);
  1875. scalar(m) = max(scalar(m), iter<1>(c));
  1876. cout << "max of each column: " << m << endl;
  1877. m = 0;
  1878. for_each([&m](auto && a) { m = max(m, a); }, iter<1>(c));
  1879. cout << "max of each column again: " << m << endl;
  1880. @end verbatim
  1881. @print{} max of each row: 2
  1882. 3 7
  1883. max of each column: 3
  1884. 7 3 3
  1885. max of each column again: 3
  1886. 7 3 3
  1887. @end example
  1888. @c [ma113]
  1889. 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}.
  1890. @example
  1891. @verbatim
  1892. m = 0;
  1893. iter<1>(m) = max(iter<1>(m), iter<1>(c));
  1894. cout << "max of each column yet again: " << m << endl;
  1895. @end verbatim
  1896. @print{} max of each column again: 3
  1897. 7 3 3
  1898. @end example
  1899. The following example computes the trace of each of the items [(-1)-cells] of @code{c}. @c [ma104]
  1900. @example
  1901. @verbatim
  1902. ra::Small<int, 3, 2, 2> c = ra::_0 - ra::_1 - 2*ra::_2;
  1903. cout << "c: " << c << endl;
  1904. cout << "s: " << map([](auto && a) { return sum(diag(a)); }, iter<-1>(c)) << endl;
  1905. @end verbatim
  1906. @print{} c: 0 -2
  1907. -1 -3
  1908. 1 -1
  1909. 0 -2
  1910. 2 0
  1911. 1 -1
  1912. s: -3 -1 -1
  1913. @end example
  1914. @end defun
  1915. @cindex @code{sum}
  1916. @anchor{x-sum} @defun sum expr
  1917. Return the sum (+) of the elements of @var{expr}, or 0 if expr is empty. This sum is performed in unspecified order.
  1918. @end defun
  1919. @cindex @code{prod}
  1920. @anchor{x-prod} @defun prod expr
  1921. Return the product (*) of the elements of @var{expr}, or 1 if expr is empty. This product is performed in unspecified order.
  1922. @end defun
  1923. @cindex @code{amax}
  1924. @anchor{x-amax} @defun amax expr
  1925. 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}.
  1926. @end defun
  1927. @cindex @code{amin}
  1928. @anchor{x-amin} @defun amin expr
  1929. 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}.
  1930. @end defun
  1931. @cindex @code{early}
  1932. @anchor{x-early} @defun early expr default
  1933. @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
  1934. The following definition of elementwise @code{lexicographical_compare} relies on @code{early}.
  1935. @example @c [ma108]
  1936. @verbatim
  1937. template <class A, class B>
  1938. inline bool
  1939. lexicographical_compare(A && a, B && b)
  1940. {
  1941. return early(map([](auto && a, auto && b) { return a==b ? std::nullopt : std::make_optional(a<b); },
  1942. std::forward<A>(a), std::forward<B>(b)),
  1943. false);
  1944. }
  1945. @end verbatim
  1946. @end example
  1947. @end defun
  1948. @cindex @code{any}
  1949. @anchor{x-any} @defun any expr
  1950. 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.
  1951. @end defun
  1952. @cindex @code{every}
  1953. @anchor{x-every} @defun every expr
  1954. 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.
  1955. @end defun
  1956. @cindex @code{sqr}
  1957. @anchor{x-sqr} @defun sqr expr
  1958. Compute the square of @var{expr}.
  1959. @end defun
  1960. @cindex @code{sqrm}
  1961. @anchor{x-sqrm} @defun sqrm expr
  1962. Compute the square of the norm-2 of @var{expr}, that is, @code{conj(expr)*expr}.
  1963. @end defun
  1964. @cindex @code{conj}
  1965. @anchor{x-conj} @defun conj expr
  1966. Compute the complex conjugate of @var{expr}.
  1967. @end defun
  1968. @cindex @code{xI}
  1969. @anchor{x-xI} @defun xI expr
  1970. Compute @code{(0+1j)} times @var{expr}.
  1971. @end defun
  1972. @cindex @code{rel_error}
  1973. @anchor{x-rel-error} @defun rel_error a b
  1974. @var{a} and @var{b} are arbitrary array expressions. Compute the error of @var{a} relative to @var{b} as
  1975. @code{(a==0. && b==0.) ? 0. : 2.*abs(a, b)/(abs(a)+abs(b))}
  1976. @end defun
  1977. @cindex @code{none}
  1978. @anchor{x-none}
  1979. @deffn @w{Special object} {none}
  1980. 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:
  1981. @example
  1982. @verbatim
  1983. void old_style_initializer(int m, int n, double *);
  1984. ra::Big<double> b({2, 3}, ra::none);
  1985. old_style_initializer(2, 3, b.data());
  1986. @end verbatim
  1987. @end example
  1988. @end deffn
  1989. @c ------------------------------------------------
  1990. @node @mybibnode{}
  1991. @chapter Sources
  1992. @c ------------------------------------------------
  1993. @multitable @columnfractions .1 .9
  1994. @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.
  1995. @item @mybibitem{Ber87} @tab Robert Bernecky. An introduction to function rank. ACM SIGAPL APL Quote Quad, 18(2):39–43, December 1987.
  1996. @item @mybibitem{bli17} @tab The Blitz++ meta-template library. @url{http://blitz.sourceforge.net}, November 2017.
  1997. @item @mybibitem{Cha86} @tab Gregory J. Chaitin. Physics in APL2, June 1986.
  1998. @item @mybibitem{FI68} @tab Adin D. Falkoff and Kenneth Eugene Iverson. APL\360 User’s manual. IBM Thomas J. Watson Research Center, August 1968.
  1999. @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.
  2000. @item @mybibitem{FI78} @tab Adin D. Falkoff and Kenneth Eugene Iverson. The evolution of APL. ACM SIGAPL APL, 9(1):30– 44, 1978.
  2001. @item @mybibitem{J S} @tab J Primer. J Software, @url{https://www.jsoftware.com/help/primer/contents.htm}, November 2017.
  2002. @item @mybibitem{Mat} @tab MathWorks. MATLAB documentation, @url{https://www.mathworks.com/help/matlab/}, November 2017.
  2003. @item @mybibitem{num17} @tab NumPy. @url{http://www.numpy.org}, November 2017.
  2004. @item @mybibitem{Ric08} @tab Henry Rich. J for C programmers, February 2008.
  2005. @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.
  2006. @item @mybibitem{Vel01} @tab Todd Veldhuizen. Blitz++ user’s guide, February 2001.
  2007. @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}
  2008. @end multitable
  2009. @c ------------------------------------------------
  2010. @node Indices
  2011. @unnumbered Indices
  2012. @c ------------------------------------------------
  2013. @c @node Concept Index
  2014. @c @unnumbered Concept Index
  2015. @printindex cp
  2016. @c @node Function Index
  2017. @c @unnumbered Function Index
  2018. @c @printindex fn
  2019. @c \nocite{JLangReference,FalkoffIverson1968,Abrams1970,FalkoffIverson1973,FalkoffIverson1978,APLexamples1,ArraysCowan,KonaTheLanguage,blitz++2001}
  2020. @c ------------------------------------------------
  2021. @node Notes
  2022. @unnumbered Notes
  2023. @c ------------------------------------------------
  2024. @enumerate
  2025. @item
  2026. @code{ra::} uses the non standard @code{#pragma once} (supported on all major compilers).
  2027. @end enumerate
  2028. @bye