ra-ra.texi 112 KB

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