xmath.hpp 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329
  1. /***************************************************************************
  2. * Copyright (c) Johan Mabille, Sylvain Corlay and Wolf Vollprecht *
  3. * Copyright (c) QuantStack *
  4. * *
  5. * Distributed under the terms of the BSD 3-Clause License. *
  6. * *
  7. * The full license is in the file LICENSE, distributed with this software. *
  8. ****************************************************************************/
  9. /**
  10. * @brief standard mathematical functions for xexpressions
  11. */
  12. #ifndef XTENSOR_MATH_HPP
  13. #define XTENSOR_MATH_HPP
  14. #include <algorithm>
  15. #include <array>
  16. #include <cmath>
  17. #include <complex>
  18. #include <type_traits>
  19. #include <xtl/xcomplex.hpp>
  20. #include <xtl/xsequence.hpp>
  21. #include <xtl/xtype_traits.hpp>
  22. #include "xaccumulator.hpp"
  23. #include "xeval.hpp"
  24. #include "xmanipulation.hpp"
  25. #include "xoperation.hpp"
  26. #include "xreducer.hpp"
  27. #include "xslice.hpp"
  28. #include "xstrided_view.hpp"
  29. #include "xtensor_config.hpp"
  30. namespace xt
  31. {
  32. template <class T = double>
  33. struct numeric_constants
  34. {
  35. static constexpr T PI = 3.141592653589793238463;
  36. static constexpr T PI_2 = 1.57079632679489661923;
  37. static constexpr T PI_4 = 0.785398163397448309616;
  38. static constexpr T D_1_PI = 0.318309886183790671538;
  39. static constexpr T D_2_PI = 0.636619772367581343076;
  40. static constexpr T D_2_SQRTPI = 1.12837916709551257390;
  41. static constexpr T SQRT2 = 1.41421356237309504880;
  42. static constexpr T SQRT1_2 = 0.707106781186547524401;
  43. static constexpr T E = 2.71828182845904523536;
  44. static constexpr T LOG2E = 1.44269504088896340736;
  45. static constexpr T LOG10E = 0.434294481903251827651;
  46. static constexpr T LN2 = 0.693147180559945309417;
  47. };
  48. /***********
  49. * Helpers *
  50. ***********/
  51. #define XTENSOR_UNSIGNED_ABS_FUNC(T) \
  52. constexpr inline T abs(const T& x) \
  53. { \
  54. return x; \
  55. }
  56. #define XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, T) \
  57. constexpr inline bool FUNC_NAME(const T& /*x*/) noexcept \
  58. { \
  59. return RETURN_VAL; \
  60. }
  61. #define XTENSOR_INT_SPECIALIZATION(FUNC_NAME, RETURN_VAL) \
  62. XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, char); \
  63. XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, short); \
  64. XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, int); \
  65. XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, long); \
  66. XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, long long); \
  67. XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, unsigned char); \
  68. XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, unsigned short); \
  69. XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, unsigned int); \
  70. XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, unsigned long); \
  71. XTENSOR_INT_SPECIALIZATION_IMPL(FUNC_NAME, RETURN_VAL, unsigned long long);
  72. #define XTENSOR_UNARY_MATH_FUNCTOR(NAME) \
  73. struct NAME##_fun \
  74. { \
  75. template <class T> \
  76. constexpr auto operator()(const T& arg) const \
  77. { \
  78. using math::NAME; \
  79. return NAME(arg); \
  80. } \
  81. template <class B> \
  82. constexpr auto simd_apply(const B& arg) const \
  83. { \
  84. using math::NAME; \
  85. return NAME(arg); \
  86. } \
  87. }
  88. #define XTENSOR_UNARY_MATH_FUNCTOR_COMPLEX_REDUCING(NAME) \
  89. struct NAME##_fun \
  90. { \
  91. template <class T> \
  92. constexpr auto operator()(const T& arg) const \
  93. { \
  94. using math::NAME; \
  95. return NAME(arg); \
  96. } \
  97. template <class B> \
  98. constexpr auto simd_apply(const B& arg) const \
  99. { \
  100. using math::NAME; \
  101. return NAME(arg); \
  102. } \
  103. }
  104. #define XTENSOR_BINARY_MATH_FUNCTOR(NAME) \
  105. struct NAME##_fun \
  106. { \
  107. template <class T1, class T2> \
  108. constexpr auto operator()(const T1& arg1, const T2& arg2) const \
  109. { \
  110. using math::NAME; \
  111. return NAME(arg1, arg2); \
  112. } \
  113. template <class B> \
  114. constexpr auto simd_apply(const B& arg1, const B& arg2) const \
  115. { \
  116. using math::NAME; \
  117. return NAME(arg1, arg2); \
  118. } \
  119. }
  120. #define XTENSOR_TERNARY_MATH_FUNCTOR(NAME) \
  121. struct NAME##_fun \
  122. { \
  123. template <class T1, class T2, class T3> \
  124. constexpr auto operator()(const T1& arg1, const T2& arg2, const T3& arg3) const \
  125. { \
  126. using math::NAME; \
  127. return NAME(arg1, arg2, arg3); \
  128. } \
  129. template <class B> \
  130. auto simd_apply(const B& arg1, const B& arg2, const B& arg3) const \
  131. { \
  132. using math::NAME; \
  133. return NAME(arg1, arg2, arg3); \
  134. } \
  135. }
  136. namespace math
  137. {
  138. using std::abs;
  139. using std::fabs;
  140. using std::acos;
  141. using std::asin;
  142. using std::atan;
  143. using std::cos;
  144. using std::sin;
  145. using std::tan;
  146. using std::acosh;
  147. using std::asinh;
  148. using std::atanh;
  149. using std::cosh;
  150. using std::sinh;
  151. using std::tanh;
  152. using std::cbrt;
  153. using std::sqrt;
  154. using std::exp;
  155. using std::exp2;
  156. using std::expm1;
  157. using std::ilogb;
  158. using std::log;
  159. using std::log10;
  160. using std::log1p;
  161. using std::log2;
  162. using std::logb;
  163. using std::ceil;
  164. using std::floor;
  165. using std::llround;
  166. using std::lround;
  167. using std::nearbyint;
  168. using std::remainder;
  169. using std::rint;
  170. using std::round;
  171. using std::trunc;
  172. using std::erf;
  173. using std::erfc;
  174. using std::lgamma;
  175. using std::tgamma;
  176. using std::arg;
  177. using std::conj;
  178. using std::imag;
  179. using std::real;
  180. using std::atan2;
  181. // copysign is not in the std namespace for MSVC
  182. #if !defined(_MSC_VER)
  183. using std::copysign;
  184. #endif
  185. using std::fdim;
  186. using std::fmax;
  187. using std::fmin;
  188. using std::fmod;
  189. using std::hypot;
  190. using std::pow;
  191. using std::fma;
  192. using std::fpclassify;
  193. // Overload isinf, isnan and isfinite because glibc implementation
  194. // might return int instead of bool and the SIMD detection requires
  195. // bool return type.
  196. template <class T>
  197. inline std::enable_if_t<xtl::is_arithmetic<T>::value, bool> isinf(const T& t)
  198. {
  199. return bool(std::isinf(t));
  200. }
  201. template <class T>
  202. inline std::enable_if_t<xtl::is_arithmetic<T>::value, bool> isnan(const T& t)
  203. {
  204. return bool(std::isnan(t));
  205. }
  206. template <class T>
  207. inline std::enable_if_t<xtl::is_arithmetic<T>::value, bool> isfinite(const T& t)
  208. {
  209. return bool(std::isfinite(t));
  210. }
  211. // Overload isinf, isnan and isfinite for complex datatypes,
  212. // following the Python specification:
  213. template <class T>
  214. inline bool isinf(const std::complex<T>& c)
  215. {
  216. return std::isinf(std::real(c)) || std::isinf(std::imag(c));
  217. }
  218. template <class T>
  219. inline bool isnan(const std::complex<T>& c)
  220. {
  221. return std::isnan(std::real(c)) || std::isnan(std::imag(c));
  222. }
  223. template <class T>
  224. inline bool isfinite(const std::complex<T>& c)
  225. {
  226. return !isinf(c) && !isnan(c);
  227. }
  228. // VS2015 STL defines isnan, isinf and isfinite as template
  229. // functions, breaking ADL.
  230. #if defined(_WIN32) && defined(XTENSOR_USE_XSIMD)
  231. /*template <class T, class A>
  232. inline xsimd::batch_bool<T, A> isinf(const xsimd::batch<T, A>& b)
  233. {
  234. return xsimd::isinf(b);
  235. }
  236. template <class T, class A>
  237. inline xsimd::batch_bool<T, A> isnan(const xsimd::batch<T, A>& b)
  238. {
  239. return xsimd::isnan(b);
  240. }
  241. template <class T, class A>
  242. inline xsimd::batch_bool<T, A> isfinite(const xsimd::batch<T, A>& b)
  243. {
  244. return xsimd::isfinite(b);
  245. }*/
  246. #endif
  247. // The following specializations are needed to avoid 'ambiguous overload' errors,
  248. // whereas 'unsigned char' and 'unsigned short' are automatically converted to 'int'.
  249. // we're still adding those functions to silence warnings
  250. XTENSOR_UNSIGNED_ABS_FUNC(unsigned char)
  251. XTENSOR_UNSIGNED_ABS_FUNC(unsigned short)
  252. XTENSOR_UNSIGNED_ABS_FUNC(unsigned int)
  253. XTENSOR_UNSIGNED_ABS_FUNC(unsigned long)
  254. XTENSOR_UNSIGNED_ABS_FUNC(unsigned long long)
  255. #ifdef _WIN32
  256. XTENSOR_INT_SPECIALIZATION(isinf, false);
  257. XTENSOR_INT_SPECIALIZATION(isnan, false);
  258. XTENSOR_INT_SPECIALIZATION(isfinite, true);
  259. #endif
  260. XTENSOR_UNARY_MATH_FUNCTOR_COMPLEX_REDUCING(abs);
  261. XTENSOR_UNARY_MATH_FUNCTOR(fabs);
  262. XTENSOR_BINARY_MATH_FUNCTOR(fmod);
  263. XTENSOR_BINARY_MATH_FUNCTOR(remainder);
  264. XTENSOR_TERNARY_MATH_FUNCTOR(fma);
  265. XTENSOR_BINARY_MATH_FUNCTOR(fmax);
  266. XTENSOR_BINARY_MATH_FUNCTOR(fmin);
  267. XTENSOR_BINARY_MATH_FUNCTOR(fdim);
  268. XTENSOR_UNARY_MATH_FUNCTOR(exp);
  269. XTENSOR_UNARY_MATH_FUNCTOR(exp2);
  270. XTENSOR_UNARY_MATH_FUNCTOR(expm1);
  271. XTENSOR_UNARY_MATH_FUNCTOR(log);
  272. XTENSOR_UNARY_MATH_FUNCTOR(log10);
  273. XTENSOR_UNARY_MATH_FUNCTOR(log2);
  274. XTENSOR_UNARY_MATH_FUNCTOR(log1p);
  275. XTENSOR_BINARY_MATH_FUNCTOR(pow);
  276. XTENSOR_UNARY_MATH_FUNCTOR(sqrt);
  277. XTENSOR_UNARY_MATH_FUNCTOR(cbrt);
  278. XTENSOR_BINARY_MATH_FUNCTOR(hypot);
  279. XTENSOR_UNARY_MATH_FUNCTOR(sin);
  280. XTENSOR_UNARY_MATH_FUNCTOR(cos);
  281. XTENSOR_UNARY_MATH_FUNCTOR(tan);
  282. XTENSOR_UNARY_MATH_FUNCTOR(asin);
  283. XTENSOR_UNARY_MATH_FUNCTOR(acos);
  284. XTENSOR_UNARY_MATH_FUNCTOR(atan);
  285. XTENSOR_BINARY_MATH_FUNCTOR(atan2);
  286. XTENSOR_UNARY_MATH_FUNCTOR(sinh);
  287. XTENSOR_UNARY_MATH_FUNCTOR(cosh);
  288. XTENSOR_UNARY_MATH_FUNCTOR(tanh);
  289. XTENSOR_UNARY_MATH_FUNCTOR(asinh);
  290. XTENSOR_UNARY_MATH_FUNCTOR(acosh);
  291. XTENSOR_UNARY_MATH_FUNCTOR(atanh);
  292. XTENSOR_UNARY_MATH_FUNCTOR(erf);
  293. XTENSOR_UNARY_MATH_FUNCTOR(erfc);
  294. XTENSOR_UNARY_MATH_FUNCTOR(tgamma);
  295. XTENSOR_UNARY_MATH_FUNCTOR(lgamma);
  296. XTENSOR_UNARY_MATH_FUNCTOR(ceil);
  297. XTENSOR_UNARY_MATH_FUNCTOR(floor);
  298. XTENSOR_UNARY_MATH_FUNCTOR(trunc);
  299. XTENSOR_UNARY_MATH_FUNCTOR(round);
  300. XTENSOR_UNARY_MATH_FUNCTOR(nearbyint);
  301. XTENSOR_UNARY_MATH_FUNCTOR(rint);
  302. XTENSOR_UNARY_MATH_FUNCTOR(isfinite);
  303. XTENSOR_UNARY_MATH_FUNCTOR(isinf);
  304. XTENSOR_UNARY_MATH_FUNCTOR(isnan);
  305. }
  306. #undef XTENSOR_UNARY_MATH_FUNCTOR
  307. #undef XTENSOR_BINARY_MATH_FUNCTOR
  308. #undef XTENSOR_TERNARY_MATH_FUNCTOR
  309. #undef XTENSOR_UNARY_MATH_FUNCTOR_COMPLEX_REDUCING
  310. #undef XTENSOR_UNSIGNED_ABS_FUNC
  311. namespace detail
  312. {
  313. template <class R, class T>
  314. std::enable_if_t<!has_iterator_interface<R>::value, R> fill_init(T init)
  315. {
  316. return R(init);
  317. }
  318. template <class R, class T>
  319. std::enable_if_t<has_iterator_interface<R>::value, R> fill_init(T init)
  320. {
  321. R result;
  322. std::fill(std::begin(result), std::end(result), init);
  323. return result;
  324. }
  325. }
  326. #define XTENSOR_REDUCER_FUNCTION(NAME, FUNCTOR, INIT_VALUE_TYPE, INIT) \
  327. template < \
  328. class T = void, \
  329. class E, \
  330. class X, \
  331. class EVS = DEFAULT_STRATEGY_REDUCERS, \
  332. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::negation<xtl::is_integral<std::decay_t<X>>>)> \
  333. inline auto NAME(E&& e, X&& axes, EVS es = EVS()) \
  334. { \
  335. using init_value_type = std::conditional_t<std::is_same<T, void>::value, INIT_VALUE_TYPE, T>; \
  336. using functor_type = FUNCTOR; \
  337. using init_value_fct = xt::const_value<init_value_type>; \
  338. return xt::reduce( \
  339. make_xreducer_functor(functor_type(), init_value_fct(detail::fill_init<init_value_type>(INIT))), \
  340. std::forward<E>(e), \
  341. std::forward<X>(axes), \
  342. es \
  343. ); \
  344. } \
  345. \
  346. template < \
  347. class T = void, \
  348. class E, \
  349. class X, \
  350. class EVS = DEFAULT_STRATEGY_REDUCERS, \
  351. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::is_integral<std::decay_t<X>>)> \
  352. inline auto NAME(E&& e, X axis, EVS es = EVS()) \
  353. { \
  354. return NAME(std::forward<E>(e), {axis}, es); \
  355. } \
  356. \
  357. template <class T = void, class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)> \
  358. inline auto NAME(E&& e, EVS es = EVS()) \
  359. { \
  360. using init_value_type = std::conditional_t<std::is_same<T, void>::value, INIT_VALUE_TYPE, T>; \
  361. using functor_type = FUNCTOR; \
  362. using init_value_fct = xt::const_value<init_value_type>; \
  363. return xt::reduce( \
  364. make_xreducer_functor(functor_type(), init_value_fct(detail::fill_init<init_value_type>(INIT))), \
  365. std::forward<E>(e), \
  366. es \
  367. ); \
  368. } \
  369. \
  370. template <class T = void, class E, class I, std::size_t N, class EVS = DEFAULT_STRATEGY_REDUCERS> \
  371. inline auto NAME(E&& e, const I(&axes)[N], EVS es = EVS()) \
  372. { \
  373. using init_value_type = std::conditional_t<std::is_same<T, void>::value, INIT_VALUE_TYPE, T>; \
  374. using functor_type = FUNCTOR; \
  375. using init_value_fct = xt::const_value<init_value_type>; \
  376. return xt::reduce( \
  377. make_xreducer_functor(functor_type(), init_value_fct(detail::fill_init<init_value_type>(INIT))), \
  378. std::forward<E>(e), \
  379. axes, \
  380. es \
  381. ); \
  382. }
  383. /*******************
  384. * basic functions *
  385. *******************/
  386. /**
  387. * @defgroup basic_functions Basic functions
  388. */
  389. /**
  390. * @ingroup basic_functions
  391. * @brief Absolute value function.
  392. *
  393. * Returns an \ref xfunction for the element-wise absolute value
  394. * of \em e.
  395. * @param e an \ref xexpression
  396. * @return an \ref xfunction
  397. */
  398. template <class E>
  399. inline auto abs(E&& e) noexcept -> detail::xfunction_type_t<math::abs_fun, E>
  400. {
  401. return detail::make_xfunction<math::abs_fun>(std::forward<E>(e));
  402. }
  403. /**
  404. * @ingroup basic_functions
  405. * @brief Absolute value function.
  406. *
  407. * Returns an \ref xfunction for the element-wise absolute value
  408. * of \em e.
  409. * @param e an \ref xexpression
  410. * @return an \ref xfunction
  411. */
  412. template <class E>
  413. inline auto fabs(E&& e) noexcept -> detail::xfunction_type_t<math::fabs_fun, E>
  414. {
  415. return detail::make_xfunction<math::fabs_fun>(std::forward<E>(e));
  416. }
  417. /**
  418. * @ingroup basic_functions
  419. * @brief Remainder of the floating point division operation.
  420. *
  421. * Returns an \ref xfunction for the element-wise remainder of
  422. * the floating point division operation <em>e1 / e2</em>.
  423. * @param e1 an \ref xexpression or a scalar
  424. * @param e2 an \ref xexpression or a scalar
  425. * @return an \ref xfunction
  426. * @note e1 and e2 can't be both scalars.
  427. */
  428. template <class E1, class E2>
  429. inline auto fmod(E1&& e1, E2&& e2) noexcept -> detail::xfunction_type_t<math::fmod_fun, E1, E2>
  430. {
  431. return detail::make_xfunction<math::fmod_fun>(std::forward<E1>(e1), std::forward<E2>(e2));
  432. }
  433. /**
  434. * @ingroup basic_functions
  435. * @brief Signed remainder of the division operation.
  436. *
  437. * Returns an \ref xfunction for the element-wise signed remainder
  438. * of the floating point division operation <em>e1 / e2</em>.
  439. * @param e1 an \ref xexpression or a scalar
  440. * @param e2 an \ref xexpression or a scalar
  441. * @return an \ref xfunction
  442. * @note e1 and e2 can't be both scalars.
  443. */
  444. template <class E1, class E2>
  445. inline auto remainder(E1&& e1, E2&& e2) noexcept -> detail::xfunction_type_t<math::remainder_fun, E1, E2>
  446. {
  447. return detail::make_xfunction<math::remainder_fun>(std::forward<E1>(e1), std::forward<E2>(e2));
  448. }
  449. /**
  450. * @ingroup basic_functions
  451. * @brief Fused multiply-add operation.
  452. *
  453. * Returns an \ref xfunction for <em>e1 * e2 + e3</em> as if
  454. * to infinite precision and rounded only once to fit the result type.
  455. * @param e1 an \ref xfunction or a scalar
  456. * @param e2 an \ref xfunction or a scalar
  457. * @param e3 an \ref xfunction or a scalar
  458. * @return an \ref xfunction
  459. * @note e1, e2 and e3 can't be scalars every three.
  460. */
  461. template <class E1, class E2, class E3>
  462. inline auto fma(E1&& e1, E2&& e2, E3&& e3) noexcept -> detail::xfunction_type_t<math::fma_fun, E1, E2, E3>
  463. {
  464. return detail::make_xfunction<math::fma_fun>(
  465. std::forward<E1>(e1),
  466. std::forward<E2>(e2),
  467. std::forward<E3>(e3)
  468. );
  469. }
  470. /**
  471. * @ingroup basic_functions
  472. * @brief Maximum function.
  473. *
  474. * Returns an \ref xfunction for the element-wise maximum
  475. * of \a e1 and \a e2.
  476. * @param e1 an \ref xexpression or a scalar
  477. * @param e2 an \ref xexpression or a scalar
  478. * @return an \ref xfunction
  479. * @note e1 and e2 can't be both scalars.
  480. */
  481. template <class E1, class E2>
  482. inline auto fmax(E1&& e1, E2&& e2) noexcept -> detail::xfunction_type_t<math::fmax_fun, E1, E2>
  483. {
  484. return detail::make_xfunction<math::fmax_fun>(std::forward<E1>(e1), std::forward<E2>(e2));
  485. }
  486. /**
  487. * @ingroup basic_functions
  488. * @brief Minimum function.
  489. *
  490. * Returns an \ref xfunction for the element-wise minimum
  491. * of \a e1 and \a e2.
  492. * @param e1 an \ref xexpression or a scalar
  493. * @param e2 an \ref xexpression or a scalar
  494. * @return an \ref xfunction
  495. * @note e1 and e2 can't be both scalars.
  496. */
  497. template <class E1, class E2>
  498. inline auto fmin(E1&& e1, E2&& e2) noexcept -> detail::xfunction_type_t<math::fmin_fun, E1, E2>
  499. {
  500. return detail::make_xfunction<math::fmin_fun>(std::forward<E1>(e1), std::forward<E2>(e2));
  501. }
  502. /**
  503. * @ingroup basic_functions
  504. * @brief Positive difference function.
  505. *
  506. * Returns an \ref xfunction for the element-wise positive
  507. * difference of \a e1 and \a e2.
  508. * @param e1 an \ref xexpression or a scalar
  509. * @param e2 an \ref xexpression or a scalar
  510. * @return an \ref xfunction
  511. * @note e1 and e2 can't be both scalars.
  512. */
  513. template <class E1, class E2>
  514. inline auto fdim(E1&& e1, E2&& e2) noexcept -> detail::xfunction_type_t<math::fdim_fun, E1, E2>
  515. {
  516. return detail::make_xfunction<math::fdim_fun>(std::forward<E1>(e1), std::forward<E2>(e2));
  517. }
  518. namespace math
  519. {
  520. template <class T = void>
  521. struct minimum
  522. {
  523. template <class A1, class A2>
  524. constexpr auto operator()(const A1& t1, const A2& t2) const noexcept
  525. {
  526. return xtl::select(t1 < t2, t1, t2);
  527. }
  528. template <class A1, class A2>
  529. constexpr auto simd_apply(const A1& t1, const A2& t2) const noexcept
  530. {
  531. return xt_simd::select(t1 < t2, t1, t2);
  532. }
  533. };
  534. template <class T = void>
  535. struct maximum
  536. {
  537. template <class A1, class A2>
  538. constexpr auto operator()(const A1& t1, const A2& t2) const noexcept
  539. {
  540. return xtl::select(t1 > t2, t1, t2);
  541. }
  542. template <class A1, class A2>
  543. constexpr auto simd_apply(const A1& t1, const A2& t2) const noexcept
  544. {
  545. return xt_simd::select(t1 > t2, t1, t2);
  546. }
  547. };
  548. struct clamp_fun
  549. {
  550. template <class A1, class A2, class A3>
  551. constexpr auto operator()(const A1& v, const A2& lo, const A3& hi) const
  552. {
  553. return xtl::select(v < lo, lo, xtl::select(hi < v, hi, v));
  554. }
  555. template <class A1, class A2, class A3>
  556. constexpr auto simd_apply(const A1& v, const A2& lo, const A3& hi) const
  557. {
  558. return xt_simd::select(v < lo, lo, xt_simd::select(hi < v, hi, v));
  559. }
  560. };
  561. struct deg2rad
  562. {
  563. template <class A, std::enable_if_t<xtl::is_integral<A>::value, int> = 0>
  564. constexpr double operator()(const A& a) const noexcept
  565. {
  566. return a * xt::numeric_constants<double>::PI / 180.0;
  567. }
  568. template <class A, std::enable_if_t<std::is_floating_point<A>::value, int> = 0>
  569. constexpr auto operator()(const A& a) const noexcept
  570. {
  571. return a * xt::numeric_constants<A>::PI / A(180.0);
  572. }
  573. template <class A, std::enable_if_t<xtl::is_integral<A>::value, int> = 0>
  574. constexpr double simd_apply(const A& a) const noexcept
  575. {
  576. return a * xt::numeric_constants<double>::PI / 180.0;
  577. }
  578. template <class A, std::enable_if_t<std::is_floating_point<A>::value, int> = 0>
  579. constexpr auto simd_apply(const A& a) const noexcept
  580. {
  581. return a * xt::numeric_constants<A>::PI / A(180.0);
  582. }
  583. };
  584. struct rad2deg
  585. {
  586. template <class A, std::enable_if_t<xtl::is_integral<A>::value, int> = 0>
  587. constexpr double operator()(const A& a) const noexcept
  588. {
  589. return a * 180.0 / xt::numeric_constants<double>::PI;
  590. }
  591. template <class A, std::enable_if_t<std::is_floating_point<A>::value, int> = 0>
  592. constexpr auto operator()(const A& a) const noexcept
  593. {
  594. return a * A(180.0) / xt::numeric_constants<A>::PI;
  595. }
  596. template <class A, std::enable_if_t<xtl::is_integral<A>::value, int> = 0>
  597. constexpr double simd_apply(const A& a) const noexcept
  598. {
  599. return a * 180.0 / xt::numeric_constants<double>::PI;
  600. }
  601. template <class A, std::enable_if_t<std::is_floating_point<A>::value, int> = 0>
  602. constexpr auto simd_apply(const A& a) const noexcept
  603. {
  604. return a * A(180.0) / xt::numeric_constants<A>::PI;
  605. }
  606. };
  607. }
  608. /**
  609. * @ingroup basic_functions
  610. * @brief Convert angles from degrees to radians.
  611. *
  612. * Returns an \ref xfunction for the element-wise corresponding
  613. * angle in radians of \em e.
  614. * @param e an \ref xexpression
  615. * @return an \ref xfunction
  616. */
  617. template <class E>
  618. inline auto deg2rad(E&& e) noexcept -> detail::xfunction_type_t<math::deg2rad, E>
  619. {
  620. return detail::make_xfunction<math::deg2rad>(std::forward<E>(e));
  621. }
  622. /**
  623. * @ingroup basic_functions
  624. * @brief Convert angles from degrees to radians.
  625. *
  626. * Returns an \ref xfunction for the element-wise corresponding
  627. * angle in radians of \em e.
  628. * @param e an \ref xexpression
  629. * @return an \ref xfunction
  630. */
  631. template <class E>
  632. inline auto radians(E&& e) noexcept -> detail::xfunction_type_t<math::deg2rad, E>
  633. {
  634. return detail::make_xfunction<math::deg2rad>(std::forward<E>(e));
  635. }
  636. /**
  637. * @ingroup basic_functions
  638. * @brief Convert angles from radians to degrees.
  639. *
  640. * Returns an \ref xfunction for the element-wise corresponding
  641. * angle in degrees of \em e.
  642. * @param e an \ref xexpression
  643. * @return an \ref xfunction
  644. */
  645. template <class E>
  646. inline auto rad2deg(E&& e) noexcept -> detail::xfunction_type_t<math::rad2deg, E>
  647. {
  648. return detail::make_xfunction<math::rad2deg>(std::forward<E>(e));
  649. }
  650. /**
  651. * @ingroup basic_functions
  652. * @brief Convert angles from radians to degrees.
  653. *
  654. * Returns an \ref xfunction for the element-wise corresponding
  655. * angle in degrees of \em e.
  656. * @param e an \ref xexpression
  657. * @return an \ref xfunction
  658. */
  659. template <class E>
  660. inline auto degrees(E&& e) noexcept -> detail::xfunction_type_t<math::rad2deg, E>
  661. {
  662. return detail::make_xfunction<math::rad2deg>(std::forward<E>(e));
  663. }
  664. /**
  665. * @ingroup basic_functions
  666. * @brief Elementwise maximum
  667. *
  668. * Returns an \ref xfunction for the element-wise
  669. * maximum between e1 and e2.
  670. * @param e1 an \ref xexpression
  671. * @param e2 an \ref xexpression
  672. * @return an \ref xfunction
  673. */
  674. template <class E1, class E2>
  675. inline auto maximum(E1&& e1, E2&& e2) noexcept -> detail::xfunction_type_t<math::maximum<void>, E1, E2>
  676. {
  677. return detail::make_xfunction<math::maximum<void>>(std::forward<E1>(e1), std::forward<E2>(e2));
  678. }
  679. /**
  680. * @ingroup basic_functions
  681. * @brief Elementwise minimum
  682. *
  683. * Returns an \ref xfunction for the element-wise
  684. * minimum between e1 and e2.
  685. * @param e1 an \ref xexpression
  686. * @param e2 an \ref xexpression
  687. * @return an \ref xfunction
  688. */
  689. template <class E1, class E2>
  690. inline auto minimum(E1&& e1, E2&& e2) noexcept -> detail::xfunction_type_t<math::minimum<void>, E1, E2>
  691. {
  692. return detail::make_xfunction<math::minimum<void>>(std::forward<E1>(e1), std::forward<E2>(e2));
  693. }
  694. /**
  695. * @ingroup basic_functions
  696. * @brief Maximum element along given axis.
  697. *
  698. * Returns an \ref xreducer for the maximum of elements over given
  699. * \em axes.
  700. * @param e an \ref xexpression
  701. * @param axes the axes along which the maximum is found (optional)
  702. * @param es evaluation strategy of the reducer
  703. * @return an \ref xreducer
  704. */
  705. XTENSOR_REDUCER_FUNCTION(
  706. amax,
  707. math::maximum<void>,
  708. typename std::decay_t<E>::value_type,
  709. std::numeric_limits<xvalue_type_t<std::decay_t<E>>>::lowest()
  710. )
  711. /**
  712. * @ingroup basic_functions
  713. * @brief Minimum element along given axis.
  714. *
  715. * Returns an \ref xreducer for the minimum of elements over given
  716. * \em axes.
  717. * @param e an \ref xexpression
  718. * @param axes the axes along which the minimum is found (optional)
  719. * @param es evaluation strategy of the reducer
  720. * @return an \ref xreducer
  721. */
  722. XTENSOR_REDUCER_FUNCTION(
  723. amin,
  724. math::minimum<void>,
  725. typename std::decay_t<E>::value_type,
  726. std::numeric_limits<xvalue_type_t<std::decay_t<E>>>::max()
  727. )
  728. /**
  729. * @ingroup basic_functions
  730. * @brief Clip values between hi and lo
  731. *
  732. * Returns an \ref xfunction for the element-wise clipped
  733. * values between lo and hi
  734. * @param e1 an \ref xexpression or a scalar
  735. * @param lo a scalar
  736. * @param hi a scalar
  737. *
  738. * @return a \ref xfunction
  739. */
  740. template <class E1, class E2, class E3>
  741. inline auto clip(E1&& e1, E2&& lo, E3&& hi) noexcept
  742. -> detail::xfunction_type_t<math::clamp_fun, E1, E2, E3>
  743. {
  744. return detail::make_xfunction<math::clamp_fun>(
  745. std::forward<E1>(e1),
  746. std::forward<E2>(lo),
  747. std::forward<E3>(hi)
  748. );
  749. }
  750. namespace math
  751. {
  752. template <class T>
  753. struct sign_impl
  754. {
  755. template <class XT = T>
  756. static constexpr std::enable_if_t<xtl::is_signed<XT>::value, T> run(T x)
  757. {
  758. return std::isnan(x) ? std::numeric_limits<T>::quiet_NaN()
  759. : x == 0 ? T(copysign(T(0), x))
  760. : T(copysign(T(1), x));
  761. }
  762. template <class XT = T>
  763. static constexpr std::enable_if_t<xtl::is_complex<XT>::value, T> run(T x)
  764. {
  765. return T(
  766. sign_impl<typename T::value_type>::run(
  767. (x.real() != typename T::value_type(0)) ? x.real() : x.imag()
  768. ),
  769. 0
  770. );
  771. }
  772. template <class XT = T>
  773. static constexpr std::enable_if_t<std::is_unsigned<XT>::value, T> run(T x)
  774. {
  775. return T(x > T(0));
  776. }
  777. };
  778. struct sign_fun
  779. {
  780. template <class T>
  781. constexpr auto operator()(const T& x) const
  782. {
  783. return sign_impl<T>::run(x);
  784. }
  785. };
  786. }
  787. /**
  788. * @ingroup basic_functions
  789. * @brief Returns an element-wise indication of the sign of a number
  790. *
  791. * If the number is positive, returns +1. If negative, -1. If the number
  792. * is zero, returns 0.
  793. *
  794. * @param e an \ref xexpression
  795. * @return an \ref xfunction
  796. */
  797. template <class E>
  798. inline auto sign(E&& e) noexcept -> detail::xfunction_type_t<math::sign_fun, E>
  799. {
  800. return detail::make_xfunction<math::sign_fun>(std::forward<E>(e));
  801. }
  802. /*************************
  803. * exponential functions *
  804. *************************/
  805. /**
  806. * @defgroup exp_functions Exponential functions
  807. */
  808. /**
  809. * @ingroup exp_functions
  810. * @brief Natural exponential function.
  811. *
  812. * Returns an \ref xfunction for the element-wise natural
  813. * exponential of \em e.
  814. * @param e an \ref xexpression
  815. * @return an \ref xfunction
  816. */
  817. template <class E>
  818. inline auto exp(E&& e) noexcept -> detail::xfunction_type_t<math::exp_fun, E>
  819. {
  820. return detail::make_xfunction<math::exp_fun>(std::forward<E>(e));
  821. }
  822. /**
  823. * @ingroup exp_functions
  824. * @brief Base 2 exponential function.
  825. *
  826. * Returns an \ref xfunction for the element-wise base 2
  827. * exponential of \em e.
  828. * @param e an \ref xexpression
  829. * @return an \ref xfunction
  830. */
  831. template <class E>
  832. inline auto exp2(E&& e) noexcept -> detail::xfunction_type_t<math::exp2_fun, E>
  833. {
  834. return detail::make_xfunction<math::exp2_fun>(std::forward<E>(e));
  835. }
  836. /**
  837. * @ingroup exp_functions
  838. * @brief Natural exponential minus one function.
  839. *
  840. * Returns an \ref xfunction for the element-wise natural
  841. * exponential of \em e, minus 1.
  842. * @param e an \ref xexpression
  843. * @return an \ref xfunction
  844. */
  845. template <class E>
  846. inline auto expm1(E&& e) noexcept -> detail::xfunction_type_t<math::expm1_fun, E>
  847. {
  848. return detail::make_xfunction<math::expm1_fun>(std::forward<E>(e));
  849. }
  850. /**
  851. * @ingroup exp_functions
  852. * @brief Natural logarithm function.
  853. *
  854. * Returns an \ref xfunction for the element-wise natural
  855. * logarithm of \em e.
  856. * @param e an \ref xexpression
  857. * @return an \ref xfunction
  858. */
  859. template <class E>
  860. inline auto log(E&& e) noexcept -> detail::xfunction_type_t<math::log_fun, E>
  861. {
  862. return detail::make_xfunction<math::log_fun>(std::forward<E>(e));
  863. }
  864. /**
  865. * @ingroup exp_functions
  866. * @brief Base 10 logarithm function.
  867. *
  868. * Returns an \ref xfunction for the element-wise base 10
  869. * logarithm of \em e.
  870. * @param e an \ref xexpression
  871. * @return an \ref xfunction
  872. */
  873. template <class E>
  874. inline auto log10(E&& e) noexcept -> detail::xfunction_type_t<math::log10_fun, E>
  875. {
  876. return detail::make_xfunction<math::log10_fun>(std::forward<E>(e));
  877. }
  878. /**
  879. * @ingroup exp_functions
  880. * @brief Base 2 logarithm function.
  881. *
  882. * Returns an \ref xfunction for the element-wise base 2
  883. * logarithm of \em e.
  884. * @param e an \ref xexpression
  885. * @return an \ref xfunction
  886. */
  887. template <class E>
  888. inline auto log2(E&& e) noexcept -> detail::xfunction_type_t<math::log2_fun, E>
  889. {
  890. return detail::make_xfunction<math::log2_fun>(std::forward<E>(e));
  891. }
  892. /**
  893. * @ingroup exp_functions
  894. * @brief Natural logarithm of one plus function.
  895. *
  896. * Returns an \ref xfunction for the element-wise natural
  897. * logarithm of \em e, plus 1.
  898. * @param e an \ref xexpression
  899. * @return an \ref xfunction
  900. */
  901. template <class E>
  902. inline auto log1p(E&& e) noexcept -> detail::xfunction_type_t<math::log1p_fun, E>
  903. {
  904. return detail::make_xfunction<math::log1p_fun>(std::forward<E>(e));
  905. }
  906. /*******************
  907. * power functions *
  908. *******************/
  909. /**
  910. * @defgroup pow_functions Power functions
  911. */
  912. /**
  913. * @ingroup pow_functions
  914. * @brief Power function.
  915. *
  916. * Returns an \ref xfunction for the element-wise value of
  917. * of \em e1 raised to the power \em e2.
  918. * @param e1 an \ref xexpression or a scalar
  919. * @param e2 an \ref xexpression or a scalar
  920. * @return an \ref xfunction
  921. * @note e1 and e2 can't be both scalars.
  922. */
  923. template <class E1, class E2>
  924. inline auto pow(E1&& e1, E2&& e2) noexcept -> detail::xfunction_type_t<math::pow_fun, E1, E2>
  925. {
  926. return detail::make_xfunction<math::pow_fun>(std::forward<E1>(e1), std::forward<E2>(e2));
  927. }
  928. namespace detail
  929. {
  930. template <class F, class... T, typename = decltype(std::declval<F>()(std::declval<T>()...))>
  931. std::true_type supports_test(const F&, const T&...);
  932. std::false_type supports_test(...);
  933. template <class... T>
  934. struct supports;
  935. template <class F, class... T>
  936. struct supports<F(T...)> : decltype(supports_test(std::declval<F>(), std::declval<T>()...))
  937. {
  938. };
  939. template <class F>
  940. struct lambda_adapt
  941. {
  942. explicit lambda_adapt(F&& lmbd)
  943. : m_lambda(std::move(lmbd))
  944. {
  945. }
  946. template <class... T>
  947. auto operator()(T... args) const
  948. {
  949. return m_lambda(args...);
  950. }
  951. template <class... T, XTL_REQUIRES(detail::supports<F(T...)>)>
  952. auto simd_apply(T... args) const
  953. {
  954. return m_lambda(args...);
  955. }
  956. F m_lambda;
  957. };
  958. }
  959. /**
  960. * Create a xfunction from a lambda
  961. *
  962. * This function can be used to easily create performant xfunctions from lambdas:
  963. *
  964. * @code{cpp}
  965. * template <class E1>
  966. * inline auto square(E1&& e1) noexcept
  967. * {
  968. * auto fnct = [](auto x) -> decltype(x * x) {
  969. * return x * x;
  970. * };
  971. * return make_lambda_xfunction(std::move(fnct), std::forward<E1>(e1));
  972. * }
  973. * @endcode
  974. *
  975. * Lambda function allow the reusal of a single arguments in multiple places (otherwise
  976. * only correctly possible when using xshared_expressions). ``auto`` lambda functions are
  977. * automatically vectorized with ``xsimd`` if possible (note that the trailing
  978. * ``-> decltype(...)`` is mandatory for the feature detection to work).
  979. *
  980. * @param lambda the lambda to be vectorized
  981. * @param args forwarded arguments
  982. *
  983. * @return lazy xfunction
  984. */
  985. template <class F, class... E>
  986. inline auto make_lambda_xfunction(F&& lambda, E&&... args)
  987. {
  988. using xfunction_type = typename detail::xfunction_type<detail::lambda_adapt<F>, E...>::type;
  989. return xfunction_type(detail::lambda_adapt<F>(std::forward<F>(lambda)), std::forward<E>(args)...);
  990. }
  991. #define XTENSOR_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  992. // Workaround for MSVC 2015 & GCC 4.9
  993. #if (defined(_MSC_VER) && _MSC_VER < 1910) || (defined(__GNUC__) && GCC_VERSION < 49999)
  994. #define XTENSOR_DISABLE_LAMBDA_FCT
  995. #endif
  996. #ifdef XTENSOR_DISABLE_LAMBDA_FCT
  997. struct square_fct
  998. {
  999. template <class T>
  1000. auto operator()(T x) const -> decltype(x * x)
  1001. {
  1002. return x * x;
  1003. }
  1004. };
  1005. struct cube_fct
  1006. {
  1007. template <class T>
  1008. auto operator()(T x) const -> decltype(x * x * x)
  1009. {
  1010. return x * x * x;
  1011. }
  1012. };
  1013. #endif
  1014. /**
  1015. * @ingroup pow_functions
  1016. * @brief Square power function, equivalent to e1 * e1.
  1017. *
  1018. * Returns an \ref xfunction for the element-wise value of
  1019. * of \em e1 * \em e1.
  1020. * @param e1 an \ref xexpression or a scalar
  1021. * @return an \ref xfunction
  1022. */
  1023. template <class E1>
  1024. inline auto square(E1&& e1) noexcept
  1025. {
  1026. #ifdef XTENSOR_DISABLE_LAMBDA_FCT
  1027. return make_lambda_xfunction(square_fct{}, std::forward<E1>(e1));
  1028. #else
  1029. auto fnct = [](auto x) -> decltype(x * x)
  1030. {
  1031. return x * x;
  1032. };
  1033. return make_lambda_xfunction(std::move(fnct), std::forward<E1>(e1));
  1034. #endif
  1035. }
  1036. /**
  1037. * @ingroup pow_functions
  1038. * @brief Cube power function, equivalent to e1 * e1 * e1.
  1039. *
  1040. * Returns an \ref xfunction for the element-wise value of
  1041. * of \em e1 * \em e1.
  1042. * @param e1 an \ref xexpression or a scalar
  1043. * @return an \ref xfunction
  1044. */
  1045. template <class E1>
  1046. inline auto cube(E1&& e1) noexcept
  1047. {
  1048. #ifdef XTENSOR_DISABLE_LAMBDA_FCT
  1049. return make_lambda_xfunction(cube_fct{}, std::forward<E1>(e1));
  1050. #else
  1051. auto fnct = [](auto x) -> decltype(x * x * x)
  1052. {
  1053. return x * x * x;
  1054. };
  1055. return make_lambda_xfunction(std::move(fnct), std::forward<E1>(e1));
  1056. #endif
  1057. }
  1058. #undef XTENSOR_GCC_VERSION
  1059. #undef XTENSOR_DISABLE_LAMBDA_FCT
  1060. namespace detail
  1061. {
  1062. // Thanks to Matt Pharr in http://pbrt.org/hair.pdf
  1063. template <std::size_t N>
  1064. struct pow_impl;
  1065. template <std::size_t N>
  1066. struct pow_impl
  1067. {
  1068. template <class T>
  1069. auto operator()(T v) const -> decltype(v * v)
  1070. {
  1071. T temp = pow_impl<N / 2>{}(v);
  1072. return temp * temp * pow_impl<N & 1>{}(v);
  1073. }
  1074. };
  1075. template <>
  1076. struct pow_impl<1>
  1077. {
  1078. template <class T>
  1079. auto operator()(T v) const -> T
  1080. {
  1081. return v;
  1082. }
  1083. };
  1084. template <>
  1085. struct pow_impl<0>
  1086. {
  1087. template <class T>
  1088. auto operator()(T /*v*/) const -> T
  1089. {
  1090. return T(1);
  1091. }
  1092. };
  1093. }
  1094. /**
  1095. * @ingroup pow_functions
  1096. * @brief Integer power function.
  1097. *
  1098. * Returns an \ref xfunction for the element-wise power of e1 to
  1099. * an integral constant.
  1100. *
  1101. * Instead of computing the power by using the (expensive) logarithm, this function
  1102. * computes the power in a number of straight-forward multiplication steps. This function
  1103. * is therefore much faster (even for high N) than the generic pow-function.
  1104. *
  1105. * For example, `e1^20` can be expressed as `(((e1^2)^2)^2)^2*(e1^2)^2`, which is just 5 multiplications.
  1106. *
  1107. * @param e an \ref xexpression
  1108. * @tparam N the exponent (has to be positive integer)
  1109. * @return an \ref xfunction
  1110. */
  1111. template <std::size_t N, class E>
  1112. inline auto pow(E&& e) noexcept
  1113. {
  1114. static_assert(N > 0, "integer power cannot be negative");
  1115. return make_lambda_xfunction(detail::pow_impl<N>{}, std::forward<E>(e));
  1116. }
  1117. /**
  1118. * @ingroup pow_functions
  1119. * @brief Square root function.
  1120. *
  1121. * Returns an \ref xfunction for the element-wise square
  1122. * root of \em e.
  1123. * @param e an \ref xexpression
  1124. * @return an \ref xfunction
  1125. */
  1126. template <class E>
  1127. inline auto sqrt(E&& e) noexcept -> detail::xfunction_type_t<math::sqrt_fun, E>
  1128. {
  1129. return detail::make_xfunction<math::sqrt_fun>(std::forward<E>(e));
  1130. }
  1131. /**
  1132. * @ingroup pow_functions
  1133. * @brief Cubic root function.
  1134. *
  1135. * Returns an \ref xfunction for the element-wise cubic
  1136. * root of \em e.
  1137. * @param e an \ref xexpression
  1138. * @return an \ref xfunction
  1139. */
  1140. template <class E>
  1141. inline auto cbrt(E&& e) noexcept -> detail::xfunction_type_t<math::cbrt_fun, E>
  1142. {
  1143. return detail::make_xfunction<math::cbrt_fun>(std::forward<E>(e));
  1144. }
  1145. /**
  1146. * @ingroup pow_functions
  1147. * @brief Hypotenuse function.
  1148. *
  1149. * Returns an \ref xfunction for the element-wise square
  1150. * root of the sum of the square of \em e1 and \em e2, avoiding
  1151. * overflow and underflow at intermediate stages of computation.
  1152. * @param e1 an \ref xexpression or a scalar
  1153. * @param e2 an \ref xexpression or a scalar
  1154. * @return an \ref xfunction
  1155. * @note e1 and e2 can't be both scalars.
  1156. */
  1157. template <class E1, class E2>
  1158. inline auto hypot(E1&& e1, E2&& e2) noexcept -> detail::xfunction_type_t<math::hypot_fun, E1, E2>
  1159. {
  1160. return detail::make_xfunction<math::hypot_fun>(std::forward<E1>(e1), std::forward<E2>(e2));
  1161. }
  1162. /***************************
  1163. * trigonometric functions *
  1164. ***************************/
  1165. /**
  1166. * @defgroup trigo_functions Trigonometric function
  1167. */
  1168. /**
  1169. * @ingroup trigo_functions
  1170. * @brief Sine function.
  1171. *
  1172. * Returns an \ref xfunction for the element-wise sine
  1173. * of \em e (measured in radians).
  1174. * @param e an \ref xexpression
  1175. * @return an \ref xfunction
  1176. */
  1177. template <class E>
  1178. inline auto sin(E&& e) noexcept -> detail::xfunction_type_t<math::sin_fun, E>
  1179. {
  1180. return detail::make_xfunction<math::sin_fun>(std::forward<E>(e));
  1181. }
  1182. /**
  1183. * @ingroup trigo_functions
  1184. * @brief Cosine function.
  1185. *
  1186. * Returns an \ref xfunction for the element-wise cosine
  1187. * of \em e (measured in radians).
  1188. * @param e an \ref xexpression
  1189. * @return an \ref xfunction
  1190. */
  1191. template <class E>
  1192. inline auto cos(E&& e) noexcept -> detail::xfunction_type_t<math::cos_fun, E>
  1193. {
  1194. return detail::make_xfunction<math::cos_fun>(std::forward<E>(e));
  1195. }
  1196. /**
  1197. * @ingroup trigo_functions
  1198. * @brief Tangent function.
  1199. *
  1200. * Returns an \ref xfunction for the element-wise tangent
  1201. * of \em e (measured in radians).
  1202. * @param e an \ref xexpression
  1203. * @return an \ref xfunction
  1204. */
  1205. template <class E>
  1206. inline auto tan(E&& e) noexcept -> detail::xfunction_type_t<math::tan_fun, E>
  1207. {
  1208. return detail::make_xfunction<math::tan_fun>(std::forward<E>(e));
  1209. }
  1210. /**
  1211. * @ingroup trigo_functions
  1212. * @brief Arcsine function.
  1213. *
  1214. * Returns an \ref xfunction for the element-wise arcsine
  1215. * of \em e.
  1216. * @param e an \ref xexpression
  1217. * @return an \ref xfunction
  1218. */
  1219. template <class E>
  1220. inline auto asin(E&& e) noexcept -> detail::xfunction_type_t<math::asin_fun, E>
  1221. {
  1222. return detail::make_xfunction<math::asin_fun>(std::forward<E>(e));
  1223. }
  1224. /**
  1225. * @ingroup trigo_functions
  1226. * @brief Arccosine function.
  1227. *
  1228. * Returns an \ref xfunction for the element-wise arccosine
  1229. * of \em e.
  1230. * @param e an \ref xexpression
  1231. * @return an \ref xfunction
  1232. */
  1233. template <class E>
  1234. inline auto acos(E&& e) noexcept -> detail::xfunction_type_t<math::acos_fun, E>
  1235. {
  1236. return detail::make_xfunction<math::acos_fun>(std::forward<E>(e));
  1237. }
  1238. /**
  1239. * @ingroup trigo_functions
  1240. * @brief Arctangent function.
  1241. *
  1242. * Returns an \ref xfunction for the element-wise arctangent
  1243. * of \em e.
  1244. * @param e an \ref xexpression
  1245. * @return an \ref xfunction
  1246. */
  1247. template <class E>
  1248. inline auto atan(E&& e) noexcept -> detail::xfunction_type_t<math::atan_fun, E>
  1249. {
  1250. return detail::make_xfunction<math::atan_fun>(std::forward<E>(e));
  1251. }
  1252. /**
  1253. * @ingroup trigo_functions
  1254. * @brief Artangent function, using signs to determine quadrants.
  1255. *
  1256. * Returns an \ref xfunction for the element-wise arctangent
  1257. * of <em>e1 / e2</em>, using the signs of arguments to determine the
  1258. * correct quadrant.
  1259. * @param e1 an \ref xexpression or a scalar
  1260. * @param e2 an \ref xexpression or a scalar
  1261. * @return an \ref xfunction
  1262. * @note e1 and e2 can't be both scalars.
  1263. */
  1264. template <class E1, class E2>
  1265. inline auto atan2(E1&& e1, E2&& e2) noexcept -> detail::xfunction_type_t<math::atan2_fun, E1, E2>
  1266. {
  1267. return detail::make_xfunction<math::atan2_fun>(std::forward<E1>(e1), std::forward<E2>(e2));
  1268. }
  1269. /************************
  1270. * hyperbolic functions *
  1271. ************************/
  1272. /**
  1273. * @defgroup hyper_functions Hyperbolic functions
  1274. */
  1275. /**
  1276. * @ingroup hyper_functions
  1277. * @brief Hyperbolic sine function.
  1278. *
  1279. * Returns an \ref xfunction for the element-wise hyperbolic
  1280. * sine of \em e.
  1281. * @param e an \ref xexpression
  1282. * @return an \ref xfunction
  1283. */
  1284. template <class E>
  1285. inline auto sinh(E&& e) noexcept -> detail::xfunction_type_t<math::sinh_fun, E>
  1286. {
  1287. return detail::make_xfunction<math::sinh_fun>(std::forward<E>(e));
  1288. }
  1289. /**
  1290. * @ingroup hyper_functions
  1291. * @brief Hyperbolic cosine function.
  1292. *
  1293. * Returns an \ref xfunction for the element-wise hyperbolic
  1294. * cosine of \em e.
  1295. * @param e an \ref xexpression
  1296. * @return an \ref xfunction
  1297. */
  1298. template <class E>
  1299. inline auto cosh(E&& e) noexcept -> detail::xfunction_type_t<math::cosh_fun, E>
  1300. {
  1301. return detail::make_xfunction<math::cosh_fun>(std::forward<E>(e));
  1302. }
  1303. /**
  1304. * @ingroup hyper_functions
  1305. * @brief Hyperbolic tangent function.
  1306. *
  1307. * Returns an \ref xfunction for the element-wise hyperbolic
  1308. * tangent of \em e.
  1309. * @param e an \ref xexpression
  1310. * @return an \ref xfunction
  1311. */
  1312. template <class E>
  1313. inline auto tanh(E&& e) noexcept -> detail::xfunction_type_t<math::tanh_fun, E>
  1314. {
  1315. return detail::make_xfunction<math::tanh_fun>(std::forward<E>(e));
  1316. }
  1317. /**
  1318. * @ingroup hyper_functions
  1319. * @brief Inverse hyperbolic sine function.
  1320. *
  1321. * Returns an \ref xfunction for the element-wise inverse hyperbolic
  1322. * sine of \em e.
  1323. * @param e an \ref xexpression
  1324. * @return an \ref xfunction
  1325. */
  1326. template <class E>
  1327. inline auto asinh(E&& e) noexcept -> detail::xfunction_type_t<math::asinh_fun, E>
  1328. {
  1329. return detail::make_xfunction<math::asinh_fun>(std::forward<E>(e));
  1330. }
  1331. /**
  1332. * @ingroup hyper_functions
  1333. * @brief Inverse hyperbolic cosine function.
  1334. *
  1335. * Returns an \ref xfunction for the element-wise inverse hyperbolic
  1336. * cosine of \em e.
  1337. * @param e an \ref xexpression
  1338. * @return an \ref xfunction
  1339. */
  1340. template <class E>
  1341. inline auto acosh(E&& e) noexcept -> detail::xfunction_type_t<math::acosh_fun, E>
  1342. {
  1343. return detail::make_xfunction<math::acosh_fun>(std::forward<E>(e));
  1344. }
  1345. /**
  1346. * @ingroup hyper_functions
  1347. * @brief Inverse hyperbolic tangent function.
  1348. *
  1349. * Returns an \ref xfunction for the element-wise inverse hyperbolic
  1350. * tangent of \em e.
  1351. * @param e an \ref xexpression
  1352. * @return an \ref xfunction
  1353. */
  1354. template <class E>
  1355. inline auto atanh(E&& e) noexcept -> detail::xfunction_type_t<math::atanh_fun, E>
  1356. {
  1357. return detail::make_xfunction<math::atanh_fun>(std::forward<E>(e));
  1358. }
  1359. /*****************************
  1360. * error and gamma functions *
  1361. *****************************/
  1362. /**
  1363. * @defgroup err_functions Error and gamma functions
  1364. */
  1365. /**
  1366. * @ingroup err_functions
  1367. * @brief Error function.
  1368. *
  1369. * Returns an \ref xfunction for the element-wise error function
  1370. * of \em e.
  1371. * @param e an \ref xexpression
  1372. * @return an \ref xfunction
  1373. */
  1374. template <class E>
  1375. inline auto erf(E&& e) noexcept -> detail::xfunction_type_t<math::erf_fun, E>
  1376. {
  1377. return detail::make_xfunction<math::erf_fun>(std::forward<E>(e));
  1378. }
  1379. /**
  1380. * @ingroup err_functions
  1381. * @brief Complementary error function.
  1382. *
  1383. * Returns an \ref xfunction for the element-wise complementary
  1384. * error function of \em e, whithout loss of precision for large argument.
  1385. * @param e an \ref xexpression
  1386. * @return an \ref xfunction
  1387. */
  1388. template <class E>
  1389. inline auto erfc(E&& e) noexcept -> detail::xfunction_type_t<math::erfc_fun, E>
  1390. {
  1391. return detail::make_xfunction<math::erfc_fun>(std::forward<E>(e));
  1392. }
  1393. /**
  1394. * @ingroup err_functions
  1395. * @brief Gamma function.
  1396. *
  1397. * Returns an \ref xfunction for the element-wise gamma function
  1398. * of \em e.
  1399. * @param e an \ref xexpression
  1400. * @return an \ref xfunction
  1401. */
  1402. template <class E>
  1403. inline auto tgamma(E&& e) noexcept -> detail::xfunction_type_t<math::tgamma_fun, E>
  1404. {
  1405. return detail::make_xfunction<math::tgamma_fun>(std::forward<E>(e));
  1406. }
  1407. /**
  1408. * @ingroup err_functions
  1409. * @brief Natural logarithm of the gamma function.
  1410. *
  1411. * Returns an \ref xfunction for the element-wise logarithm of
  1412. * the asbolute value fo the gamma function of \em e.
  1413. * @param e an \ref xexpression
  1414. * @return an \ref xfunction
  1415. */
  1416. template <class E>
  1417. inline auto lgamma(E&& e) noexcept -> detail::xfunction_type_t<math::lgamma_fun, E>
  1418. {
  1419. return detail::make_xfunction<math::lgamma_fun>(std::forward<E>(e));
  1420. }
  1421. /*********************************************
  1422. * nearest integer floating point operations *
  1423. *********************************************/
  1424. /**
  1425. * @defgroup nearint_functions Nearest integer floating point operations
  1426. */
  1427. /**
  1428. * @ingroup nearint_functions
  1429. * @brief ceil function.
  1430. *
  1431. * Returns an \ref xfunction for the element-wise smallest integer value
  1432. * not less than \em e.
  1433. * @param e an \ref xexpression
  1434. * @return an \ref xfunction
  1435. */
  1436. template <class E>
  1437. inline auto ceil(E&& e) noexcept -> detail::xfunction_type_t<math::ceil_fun, E>
  1438. {
  1439. return detail::make_xfunction<math::ceil_fun>(std::forward<E>(e));
  1440. }
  1441. /**
  1442. * @ingroup nearint_functions
  1443. * @brief floor function.
  1444. *
  1445. * Returns an \ref xfunction for the element-wise smallest integer value
  1446. * not greater than \em e.
  1447. * @param e an \ref xexpression
  1448. * @return an \ref xfunction
  1449. */
  1450. template <class E>
  1451. inline auto floor(E&& e) noexcept -> detail::xfunction_type_t<math::floor_fun, E>
  1452. {
  1453. return detail::make_xfunction<math::floor_fun>(std::forward<E>(e));
  1454. }
  1455. /**
  1456. * @ingroup nearint_functions
  1457. * @brief trunc function.
  1458. *
  1459. * Returns an \ref xfunction for the element-wise nearest integer not greater
  1460. * in magnitude than \em e.
  1461. * @param e an \ref xexpression
  1462. * @return an \ref xfunction
  1463. */
  1464. template <class E>
  1465. inline auto trunc(E&& e) noexcept -> detail::xfunction_type_t<math::trunc_fun, E>
  1466. {
  1467. return detail::make_xfunction<math::trunc_fun>(std::forward<E>(e));
  1468. }
  1469. /**
  1470. * @ingroup nearint_functions
  1471. * @brief round function.
  1472. *
  1473. * Returns an \ref xfunction for the element-wise nearest integer value
  1474. * to \em e, rounding halfway cases away from zero, regardless of the
  1475. * current rounding mode.
  1476. * @param e an \ref xexpression
  1477. * @return an \ref xfunction
  1478. */
  1479. template <class E>
  1480. inline auto round(E&& e) noexcept -> detail::xfunction_type_t<math::round_fun, E>
  1481. {
  1482. return detail::make_xfunction<math::round_fun>(std::forward<E>(e));
  1483. }
  1484. /**
  1485. * @ingroup nearint_functions
  1486. * @brief nearbyint function.
  1487. *
  1488. * Returns an \ref xfunction for the element-wise rounding of \em e to integer
  1489. * values in floating point format, using the current rounding mode. nearbyint
  1490. * never raises FE_INEXACT error.
  1491. * @param e an \ref xexpression
  1492. * @return an \ref xfunction
  1493. */
  1494. template <class E>
  1495. inline auto nearbyint(E&& e) noexcept -> detail::xfunction_type_t<math::nearbyint_fun, E>
  1496. {
  1497. return detail::make_xfunction<math::nearbyint_fun>(std::forward<E>(e));
  1498. }
  1499. /**
  1500. * @ingroup nearint_functions
  1501. * @brief rint function.
  1502. *
  1503. * Returns an \ref xfunction for the element-wise rounding of \em e to integer
  1504. * values in floating point format, using the current rounding mode. Contrary
  1505. * to nearbyint, rint may raise FE_INEXACT error.
  1506. * @param e an \ref xexpression
  1507. * @return an \ref xfunction
  1508. */
  1509. template <class E>
  1510. inline auto rint(E&& e) noexcept -> detail::xfunction_type_t<math::rint_fun, E>
  1511. {
  1512. return detail::make_xfunction<math::rint_fun>(std::forward<E>(e));
  1513. }
  1514. /****************************
  1515. * classification functions *
  1516. ****************************/
  1517. /**
  1518. * @defgroup classif_functions Classification functions
  1519. */
  1520. /**
  1521. * @ingroup classif_functions
  1522. * @brief finite value check
  1523. *
  1524. * Returns an \ref xfunction for the element-wise finite value check
  1525. * tangent of \em e.
  1526. * @param e an \ref xexpression
  1527. * @return an \ref xfunction
  1528. */
  1529. template <class E>
  1530. inline auto isfinite(E&& e) noexcept -> detail::xfunction_type_t<math::isfinite_fun, E>
  1531. {
  1532. return detail::make_xfunction<math::isfinite_fun>(std::forward<E>(e));
  1533. }
  1534. /**
  1535. * @ingroup classif_functions
  1536. * @brief infinity check
  1537. *
  1538. * Returns an \ref xfunction for the element-wise infinity check
  1539. * tangent of \em e.
  1540. * @param e an \ref xexpression
  1541. * @return an \ref xfunction
  1542. */
  1543. template <class E>
  1544. inline auto isinf(E&& e) noexcept -> detail::xfunction_type_t<math::isinf_fun, E>
  1545. {
  1546. return detail::make_xfunction<math::isinf_fun>(std::forward<E>(e));
  1547. }
  1548. /**
  1549. * @ingroup classif_functions
  1550. * @brief NaN check
  1551. *
  1552. * Returns an \ref xfunction for the element-wise NaN check
  1553. * tangent of \em e.
  1554. * @param e an \ref xexpression
  1555. * @return an \ref xfunction
  1556. */
  1557. template <class E>
  1558. inline auto isnan(E&& e) noexcept -> detail::xfunction_type_t<math::isnan_fun, E>
  1559. {
  1560. return detail::make_xfunction<math::isnan_fun>(std::forward<E>(e));
  1561. }
  1562. namespace detail
  1563. {
  1564. template <class FUNCTOR, class T, std::size_t... Is>
  1565. inline auto get_functor(T&& args, std::index_sequence<Is...>)
  1566. {
  1567. return FUNCTOR(std::get<Is>(args)...);
  1568. }
  1569. template <class F, class... A, class... E>
  1570. inline auto make_xfunction(std::tuple<A...>&& f_args, E&&... e) noexcept
  1571. {
  1572. using functor_type = F;
  1573. using expression_tag = xexpression_tag_t<E...>;
  1574. using type = select_xfunction_expression_t<expression_tag, functor_type, const_xclosure_t<E>...>;
  1575. auto functor = get_functor<functor_type>(
  1576. std::forward<std::tuple<A...>>(f_args),
  1577. std::make_index_sequence<sizeof...(A)>{}
  1578. );
  1579. return type(std::move(functor), std::forward<E>(e)...);
  1580. }
  1581. struct isclose
  1582. {
  1583. using result_type = bool;
  1584. isclose(double rtol, double atol, bool equal_nan)
  1585. : m_rtol(rtol)
  1586. , m_atol(atol)
  1587. , m_equal_nan(equal_nan)
  1588. {
  1589. }
  1590. template <class A1, class A2>
  1591. bool operator()(const A1& a, const A2& b) const
  1592. {
  1593. using internal_type = xtl::promote_type_t<A1, A2, double>;
  1594. if (math::isnan(a) && math::isnan(b))
  1595. {
  1596. return m_equal_nan;
  1597. }
  1598. if (math::isinf(a) && math::isinf(b))
  1599. {
  1600. // check for both infinity signs equal
  1601. return a == b;
  1602. }
  1603. auto d = math::abs(internal_type(a) - internal_type(b));
  1604. return d <= m_atol
  1605. || d <= m_rtol
  1606. * double((std::max)(math::abs(internal_type(a)), math::abs(internal_type(b)))
  1607. );
  1608. }
  1609. private:
  1610. double m_rtol;
  1611. double m_atol;
  1612. bool m_equal_nan;
  1613. };
  1614. }
  1615. /**
  1616. * @ingroup classif_functions
  1617. * @brief Element-wise closeness detection
  1618. *
  1619. * Returns an \ref xfunction that evaluates to
  1620. * true if the elements in ``e1`` and ``e2`` are close to each other
  1621. * according to parameters ``atol`` and ``rtol``.
  1622. * The equation is: ``std::abs(a - b) <= (m_atol + m_rtol * std::abs(b))``.
  1623. * @param e1 input array to compare
  1624. * @param e2 input array to compare
  1625. * @param rtol the relative tolerance parameter (default 1e-05)
  1626. * @param atol the absolute tolerance parameter (default 1e-08)
  1627. * @param equal_nan if true, isclose returns true if both elements of e1 and e2 are NaN
  1628. * @return an \ref xfunction
  1629. */
  1630. template <class E1, class E2>
  1631. inline auto
  1632. isclose(E1&& e1, E2&& e2, double rtol = 1e-05, double atol = 1e-08, bool equal_nan = false) noexcept
  1633. {
  1634. return detail::make_xfunction<detail::isclose>(
  1635. std::make_tuple(rtol, atol, equal_nan),
  1636. std::forward<E1>(e1),
  1637. std::forward<E2>(e2)
  1638. );
  1639. }
  1640. /**
  1641. * @ingroup classif_functions
  1642. * @brief Check if all elements in \em e1 are close to the
  1643. * corresponding elements in \em e2.
  1644. *
  1645. * Returns true if all elements in ``e1`` and ``e2`` are close to each other
  1646. * according to parameters ``atol`` and ``rtol``.
  1647. * @param e1 input array to compare
  1648. * @param e2 input arrays to compare
  1649. * @param rtol the relative tolerance parameter (default 1e-05)
  1650. * @param atol the absolute tolerance parameter (default 1e-08)
  1651. * @return a boolean
  1652. */
  1653. template <class E1, class E2>
  1654. inline auto allclose(E1&& e1, E2&& e2, double rtol = 1e-05, double atol = 1e-08) noexcept
  1655. {
  1656. return xt::all(isclose(std::forward<E1>(e1), std::forward<E2>(e2), rtol, atol));
  1657. }
  1658. /**********************
  1659. * Reducing functions *
  1660. **********************/
  1661. /**
  1662. * @defgroup red_functions reducing functions
  1663. */
  1664. /**
  1665. * @ingroup red_functions
  1666. * @brief Sum of elements over given axes.
  1667. *
  1668. * Returns an \ref xreducer for the sum of elements over given
  1669. * \em axes.
  1670. * @param e an \ref xexpression
  1671. * @param axes the axes along which the sum is performed (optional)
  1672. * @param es evaluation strategy of the reducer
  1673. * @tparam T the value type used for internal computation. The default is
  1674. * `E::value_type`. `T` is also used for determining the value type
  1675. * of the result, which is the type of `T() + E::value_type()`.
  1676. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  1677. * @return an \ref xreducer
  1678. */
  1679. XTENSOR_REDUCER_FUNCTION(sum, detail::plus, typename std::decay_t<E>::value_type, 0)
  1680. /**
  1681. * @ingroup red_functions
  1682. * @brief Product of elements over given axes.
  1683. *
  1684. * Returns an \ref xreducer for the product of elements over given
  1685. * \em axes.
  1686. * @param e an \ref xexpression
  1687. * @param axes the axes along which the product is computed (optional)
  1688. * @param ddof delta degrees of freedom (optional).
  1689. * The divisor used in calculations is N - ddof, where N represents the number of
  1690. * elements. By default ddof is zero.
  1691. * @param es evaluation strategy of the reducer
  1692. * @tparam T the value type used for internal computation. The default is `E::value_type`.
  1693. * `T` is also used for determining the value type of the result, which is the type
  1694. * of `T() * E::value_type()`.
  1695. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  1696. * @return an \ref xreducer
  1697. */
  1698. XTENSOR_REDUCER_FUNCTION(prod, detail::multiplies, typename std::decay_t<E>::value_type, 1)
  1699. namespace detail
  1700. {
  1701. template <class T, class S, class ST>
  1702. inline auto mean_division(S&& s, ST e_size)
  1703. {
  1704. using value_type = typename std::conditional_t<std::is_same<T, void>::value, double, T>;
  1705. // Avoids floating point exception when s.size is 0
  1706. value_type div = s.size() != ST(0) ? static_cast<value_type>(e_size / s.size()) : value_type(0);
  1707. return std::move(s) / std::move(div);
  1708. }
  1709. template <
  1710. class T,
  1711. class E,
  1712. class X,
  1713. class D,
  1714. class EVS,
  1715. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::is_integral<D>)>
  1716. inline auto mean(E&& e, X&& axes, const D& ddof, EVS es)
  1717. {
  1718. // sum cannot always be a double. It could be a complex number which cannot operate on
  1719. // std::plus<double>.
  1720. using size_type = typename std::decay_t<E>::size_type;
  1721. const size_type size = e.size();
  1722. XTENSOR_ASSERT(static_cast<size_type>(ddof) <= size);
  1723. auto s = sum<T>(std::forward<E>(e), std::forward<X>(axes), es);
  1724. return mean_division<T>(std::move(s), size - static_cast<size_type>(ddof));
  1725. }
  1726. template <class T, class E, class I, std::size_t N, class D, class EVS>
  1727. inline auto mean(E&& e, const I (&axes)[N], const D& ddof, EVS es)
  1728. {
  1729. using size_type = typename std::decay_t<E>::size_type;
  1730. const size_type size = e.size();
  1731. XTENSOR_ASSERT(static_cast<size_type>(ddof) <= size);
  1732. auto s = sum<T>(std::forward<E>(e), axes, es);
  1733. return mean_division<T>(std::move(s), size - static_cast<size_type>(ddof));
  1734. }
  1735. template <class T, class E, class D, class EVS, XTL_REQUIRES(is_reducer_options<EVS>, xtl::is_integral<D>)>
  1736. inline auto mean_noaxis(E&& e, const D& ddof, EVS es)
  1737. {
  1738. using value_type = typename std::conditional_t<std::is_same<T, void>::value, double, T>;
  1739. using size_type = typename std::decay_t<E>::size_type;
  1740. const size_type size = e.size();
  1741. XTENSOR_ASSERT(static_cast<size_type>(ddof) <= size);
  1742. auto s = sum<T>(std::forward<E>(e), es);
  1743. return std::move(s) / static_cast<value_type>((size - static_cast<size_type>(ddof)));
  1744. }
  1745. }
  1746. /**
  1747. * @ingroup red_functions
  1748. * @brief Mean of elements over given axes.
  1749. *
  1750. * Returns an \ref xreducer for the mean of elements over given
  1751. * \em axes.
  1752. * @param e an \ref xexpression
  1753. * @param axes the axes along which the mean is computed (optional)
  1754. * @param es the evaluation strategy (optional)
  1755. * @tparam T the value type used for internal computation. The default is
  1756. * `E::value_type`. `T` is also used for determining the value type
  1757. * of the result, which is the type of `T() + E::value_type()`.
  1758. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  1759. * @return an \ref xexpression
  1760. */
  1761. template <
  1762. class T = void,
  1763. class E,
  1764. class X,
  1765. class EVS = DEFAULT_STRATEGY_REDUCERS,
  1766. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>)>
  1767. inline auto mean(E&& e, X&& axes, EVS es = EVS())
  1768. {
  1769. return detail::mean<T>(std::forward<E>(e), std::forward<X>(axes), 0u, es);
  1770. }
  1771. template <class T = void, class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  1772. inline auto mean(E&& e, EVS es = EVS())
  1773. {
  1774. return detail::mean_noaxis<T>(std::forward<E>(e), 0u, es);
  1775. }
  1776. template <class T = void, class E, class I, std::size_t N, class EVS = DEFAULT_STRATEGY_REDUCERS>
  1777. inline auto mean(E&& e, const I (&axes)[N], EVS es = EVS())
  1778. {
  1779. return detail::mean<T>(std::forward<E>(e), axes, 0u, es);
  1780. }
  1781. /**
  1782. * @ingroup red_functions
  1783. * @brief Average of elements over given axes using weights.
  1784. *
  1785. * Returns an \ref xreducer for the mean of elements over given
  1786. * \em axes.
  1787. * @param e an \ref xexpression
  1788. * @param weights \ref xexpression containing weights associated with the values in \ref e
  1789. * @param axes the axes along which the mean is computed (optional)
  1790. * @tparam T the value type used for internal computation. The default is
  1791. * `E::value_type`. `T`is also used for determining the value type of the result,
  1792. * which is the type of `T() + E::value_type().
  1793. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  1794. * @return an \ref xexpression
  1795. *
  1796. * @sa mean
  1797. */
  1798. template <
  1799. class T = void,
  1800. class E,
  1801. class W,
  1802. class X,
  1803. class EVS = DEFAULT_STRATEGY_REDUCERS,
  1804. XTL_REQUIRES(is_reducer_options<EVS>, xtl::negation<xtl::is_integral<X>>)>
  1805. inline auto average(E&& e, W&& weights, X&& axes, EVS ev = EVS())
  1806. {
  1807. xindex_type_t<typename std::decay_t<E>::shape_type> broadcast_shape;
  1808. xt::resize_container(broadcast_shape, e.dimension());
  1809. auto ax = normalize_axis(e, axes);
  1810. if (weights.dimension() == 1)
  1811. {
  1812. if (weights.size() != e.shape()[ax[0]])
  1813. {
  1814. XTENSOR_THROW(std::runtime_error, "Weights need to have the same shape as expression at axes.");
  1815. }
  1816. std::fill(broadcast_shape.begin(), broadcast_shape.end(), std::size_t(1));
  1817. broadcast_shape[ax[0]] = weights.size();
  1818. }
  1819. else
  1820. {
  1821. if (!same_shape(e.shape(), weights.shape()))
  1822. {
  1823. XTENSOR_THROW(
  1824. std::runtime_error,
  1825. "Weights with dim > 1 need to have the same shape as expression."
  1826. );
  1827. }
  1828. std::copy(e.shape().begin(), e.shape().end(), broadcast_shape.begin());
  1829. }
  1830. constexpr layout_type L = default_assignable_layout(std::decay_t<W>::static_layout);
  1831. auto weights_view = reshape_view<L>(std::forward<W>(weights), std::move(broadcast_shape));
  1832. auto scl = sum<T>(weights_view, ax, xt::evaluation_strategy::immediate);
  1833. return sum<T>(std::forward<E>(e) * std::move(weights_view), std::move(ax), ev) / std::move(scl);
  1834. }
  1835. template <
  1836. class T = void,
  1837. class E,
  1838. class W,
  1839. class X,
  1840. class EVS = DEFAULT_STRATEGY_REDUCERS,
  1841. XTL_REQUIRES(is_reducer_options<EVS>, xtl::is_integral<X>)>
  1842. inline auto average(E&& e, W&& weights, X axis, EVS ev = EVS())
  1843. {
  1844. return average(std::forward<E>(e), std::forward<W>(weights), {axis}, std::forward<EVS>(ev));
  1845. }
  1846. template <class T = void, class E, class W, class X, std::size_t N, class EVS = DEFAULT_STRATEGY_REDUCERS>
  1847. inline auto average(E&& e, W&& weights, const X (&axes)[N], EVS ev = EVS())
  1848. {
  1849. // need to select the X&& overload and forward to different type
  1850. using ax_t = std::array<std::size_t, N>;
  1851. return average<T>(std::forward<E>(e), std::forward<W>(weights), xt::forward_normalize<ax_t>(e, axes), ev);
  1852. }
  1853. template <class T = void, class E, class W, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  1854. inline auto average(E&& e, W&& weights, EVS ev = EVS())
  1855. {
  1856. if (weights.dimension() != e.dimension()
  1857. || !std::equal(weights.shape().begin(), weights.shape().end(), e.shape().begin()))
  1858. {
  1859. XTENSOR_THROW(std::runtime_error, "Weights need to have the same shape as expression.");
  1860. }
  1861. auto div = sum<T>(weights, evaluation_strategy::immediate)();
  1862. auto s = sum<T>(std::forward<E>(e) * std::forward<W>(weights), ev) / std::move(div);
  1863. return s;
  1864. }
  1865. template <class T = void, class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  1866. inline auto average(E&& e, EVS ev = EVS())
  1867. {
  1868. return mean<T>(e, ev);
  1869. }
  1870. namespace detail
  1871. {
  1872. template <typename E>
  1873. std::enable_if_t<std::is_lvalue_reference<E>::value, E> shared_forward(E e) noexcept
  1874. {
  1875. return e;
  1876. }
  1877. template <typename E>
  1878. std::enable_if_t<!std::is_lvalue_reference<E>::value, xshared_expression<E>> shared_forward(E e) noexcept
  1879. {
  1880. return make_xshared(std::move(e));
  1881. }
  1882. }
  1883. template <
  1884. class T = void,
  1885. class E,
  1886. class D,
  1887. class EVS = DEFAULT_STRATEGY_REDUCERS,
  1888. XTL_REQUIRES(is_reducer_options<EVS>, xtl::is_integral<D>)>
  1889. inline auto variance(E&& e, const D& ddof, EVS es = EVS())
  1890. {
  1891. auto cached_mean = mean<T>(e, es)();
  1892. return detail::mean_noaxis<T>(square(std::forward<E>(e) - std::move(cached_mean)), ddof, es);
  1893. }
  1894. template <class T = void, class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  1895. inline auto variance(E&& e, EVS es = EVS())
  1896. {
  1897. return variance<T>(std::forward<E>(e), 0u, es);
  1898. }
  1899. template <class T = void, class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  1900. inline auto stddev(E&& e, EVS es = EVS())
  1901. {
  1902. return sqrt(variance<T>(std::forward<E>(e), es));
  1903. }
  1904. /**
  1905. * @ingroup red_functions
  1906. * @brief Compute the variance along the specified axes
  1907. *
  1908. * Returns the variance of the array elements, a measure of the spread of a
  1909. * distribution. The variance is computed for the flattened array by default,
  1910. * otherwise over the specified axes.
  1911. *
  1912. * Note: this function is not yet specialized for complex numbers.
  1913. *
  1914. * @param e an \ref xexpression
  1915. * @param axes the axes along which the variance is computed (optional)
  1916. * @param ddof delta degrees of freedom (optional).
  1917. * The divisor used in calculations is N - ddof, where N represents the number of
  1918. * elements. By default ddof is zero.
  1919. * @param es evaluation strategy to use (lazy (default), or immediate)
  1920. * @tparam T the value type used for internal computation. The default is
  1921. * `E::value_type`. `T`is also used for determining the value type of the result,
  1922. * which is the type of `T() + E::value_type()`.
  1923. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  1924. * @return an \ref xexpression
  1925. *
  1926. * @sa stddev, mean
  1927. */
  1928. template <
  1929. class T = void,
  1930. class E,
  1931. class X,
  1932. class D,
  1933. class EVS = DEFAULT_STRATEGY_REDUCERS,
  1934. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::is_integral<D>)>
  1935. inline auto variance(E&& e, X&& axes, const D& ddof, EVS es = EVS())
  1936. {
  1937. decltype(auto) sc = detail::shared_forward<E>(e);
  1938. // note: forcing copy of first axes argument -- is there a better solution?
  1939. auto axes_copy = axes;
  1940. // always eval to prevent repeated evaluations in the next calls
  1941. auto inner_mean = eval(mean<T>(sc, std::move(axes_copy), evaluation_strategy::immediate));
  1942. // fake keep_dims = 1
  1943. // Since the inner_shape might have a reference semantic (e.g. xbuffer_adaptor in bindings)
  1944. // We need to map it to another type before modifying it.
  1945. // We pragmatically abuse `get_strides_t`
  1946. using tmp_shape_t = get_strides_t<typename std::decay_t<E>::shape_type>;
  1947. tmp_shape_t keep_dim_shape = xtl::forward_sequence<tmp_shape_t, decltype(e.shape())>(e.shape());
  1948. for (const auto& el : axes)
  1949. {
  1950. keep_dim_shape[el] = 1u;
  1951. }
  1952. auto mrv = reshape_view<XTENSOR_DEFAULT_LAYOUT>(std::move(inner_mean), std::move(keep_dim_shape));
  1953. return detail::mean<T>(square(sc - std::move(mrv)), std::forward<X>(axes), ddof, es);
  1954. }
  1955. template <
  1956. class T = void,
  1957. class E,
  1958. class X,
  1959. class EVS = DEFAULT_STRATEGY_REDUCERS,
  1960. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::negation<xtl::is_integral<std::decay_t<X>>>, is_reducer_options<EVS>)>
  1961. inline auto variance(E&& e, X&& axes, EVS es = EVS())
  1962. {
  1963. return variance<T>(std::forward<E>(e), std::forward<X>(axes), 0u, es);
  1964. }
  1965. /**
  1966. * @ingroup red_functions
  1967. * @brief Compute the standard deviation along the specified axis.
  1968. *
  1969. * Returns the standard deviation, a measure of the spread of a distribution,
  1970. * of the array elements. The standard deviation is computed for the flattened
  1971. * array by default, otherwise over the specified axis.
  1972. *
  1973. * Note: this function is not yet specialized for complex numbers.
  1974. *
  1975. * @param e an \ref xexpression
  1976. * @param axes the axes along which the standard deviation is computed (optional)
  1977. * @param es evaluation strategy to use (lazy (default), or immediate)
  1978. * @tparam T the value type used for internal computation. The default is
  1979. * `E::value_type`. `T`is also used for determining the value type of the result,
  1980. * which is the type of `T() + E::value_type()`.
  1981. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  1982. * @return an \ref xexpression
  1983. *
  1984. * @sa variance, mean
  1985. */
  1986. template <
  1987. class T = void,
  1988. class E,
  1989. class X,
  1990. class EVS = DEFAULT_STRATEGY_REDUCERS,
  1991. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>)>
  1992. inline auto stddev(E&& e, X&& axes, EVS es = EVS())
  1993. {
  1994. return sqrt(variance<T>(std::forward<E>(e), std::forward<X>(axes), es));
  1995. }
  1996. template <class T = void, class E, class A, std::size_t N, class EVS = DEFAULT_STRATEGY_REDUCERS>
  1997. inline auto stddev(E&& e, const A (&axes)[N], EVS es = EVS())
  1998. {
  1999. return stddev<T>(
  2000. std::forward<E>(e),
  2001. xtl::forward_sequence<std::array<std::size_t, N>, decltype(axes)>(axes),
  2002. es
  2003. );
  2004. }
  2005. template <
  2006. class T = void,
  2007. class E,
  2008. class A,
  2009. std::size_t N,
  2010. class EVS = DEFAULT_STRATEGY_REDUCERS,
  2011. XTL_REQUIRES(is_reducer_options<EVS>)>
  2012. inline auto variance(E&& e, const A (&axes)[N], EVS es = EVS())
  2013. {
  2014. return variance<T>(
  2015. std::forward<E>(e),
  2016. xtl::forward_sequence<std::array<std::size_t, N>, decltype(axes)>(axes),
  2017. es
  2018. );
  2019. }
  2020. template <class T = void, class E, class A, std::size_t N, class D, class EVS = DEFAULT_STRATEGY_REDUCERS>
  2021. inline auto variance(E&& e, const A (&axes)[N], const D& ddof, EVS es = EVS())
  2022. {
  2023. return variance<T>(
  2024. std::forward<E>(e),
  2025. xtl::forward_sequence<std::array<std::size_t, N>, decltype(axes)>(axes),
  2026. ddof,
  2027. es
  2028. );
  2029. }
  2030. /**
  2031. * @ingroup red_functions
  2032. * @brief Minimum and maximum among the elements of an array or expression.
  2033. *
  2034. * Returns an \ref xreducer for the minimum and maximum of an expression's elements.
  2035. * @param e an \ref xexpression
  2036. * @param es evaluation strategy to use (lazy (default), or immediate)
  2037. * @return an \ref xexpression of type ``std::array<value_type, 2>``, whose first
  2038. * and second element represent the minimum and maximum respectively
  2039. */
  2040. template <class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  2041. inline auto minmax(E&& e, EVS es = EVS())
  2042. {
  2043. using std::max;
  2044. using std::min;
  2045. using value_type = typename std::decay_t<E>::value_type;
  2046. using result_type = std::array<value_type, 2>;
  2047. using init_value_fct = xt::const_value<result_type>;
  2048. auto reduce_func = [](auto r, const auto& v)
  2049. {
  2050. r[0] = (min) (r[0], v);
  2051. r[1] = (max) (r[1], v);
  2052. return r;
  2053. };
  2054. auto init_func = init_value_fct(
  2055. result_type{std::numeric_limits<value_type>::max(), std::numeric_limits<value_type>::lowest()}
  2056. );
  2057. auto merge_func = [](auto r, const auto& s)
  2058. {
  2059. r[0] = (min) (r[0], s[0]);
  2060. r[1] = (max) (r[1], s[1]);
  2061. return r;
  2062. };
  2063. return xt::reduce(
  2064. make_xreducer_functor(std::move(reduce_func), std::move(init_func), std::move(merge_func)),
  2065. std::forward<E>(e),
  2066. arange(e.dimension()),
  2067. es
  2068. );
  2069. }
  2070. /**
  2071. * @defgroup acc_functions accumulating functions
  2072. */
  2073. /**
  2074. * @ingroup acc_functions
  2075. * @brief Cumulative sum.
  2076. *
  2077. * Returns the accumulated sum for the elements over given
  2078. * \em axis (or flattened).
  2079. * @param e an \ref xexpression
  2080. * @param axis the axes along which the cumulative sum is computed (optional)
  2081. * @tparam T the value type used for internal computation. The default is
  2082. * `E::value_type`. `T`is also used for determining the value type of the result,
  2083. * which is the type of `T() + E::value_type()`.
  2084. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  2085. * @return an \ref xarray<T>
  2086. */
  2087. template <class T = void, class E>
  2088. inline auto cumsum(E&& e, std::ptrdiff_t axis)
  2089. {
  2090. using init_value_type = std::conditional_t<std::is_same<T, void>::value, typename std::decay_t<E>::value_type, T>;
  2091. return accumulate(
  2092. make_xaccumulator_functor(detail::plus(), detail::accumulator_identity<init_value_type>()),
  2093. std::forward<E>(e),
  2094. axis
  2095. );
  2096. }
  2097. template <class T = void, class E>
  2098. inline auto cumsum(E&& e)
  2099. {
  2100. using init_value_type = std::conditional_t<std::is_same<T, void>::value, typename std::decay_t<E>::value_type, T>;
  2101. return accumulate(
  2102. make_xaccumulator_functor(detail::plus(), detail::accumulator_identity<init_value_type>()),
  2103. std::forward<E>(e)
  2104. );
  2105. }
  2106. /**
  2107. * @ingroup acc_functions
  2108. * @brief Cumulative product.
  2109. *
  2110. * Returns the accumulated product for the elements over given
  2111. * \em axis (or flattened).
  2112. * @param e an \ref xexpression
  2113. * @param axis the axes along which the cumulative product is computed (optional)
  2114. * @tparam T the value type used for internal computation. The default is
  2115. * `E::value_type`. `T`is also used for determining the value type of the result,
  2116. * which is the type of `T() * E::value_type()`.
  2117. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  2118. * @return an \ref xarray<T>
  2119. */
  2120. template <class T = void, class E>
  2121. inline auto cumprod(E&& e, std::ptrdiff_t axis)
  2122. {
  2123. using init_value_type = std::conditional_t<std::is_same<T, void>::value, typename std::decay_t<E>::value_type, T>;
  2124. return accumulate(
  2125. make_xaccumulator_functor(detail::multiplies(), detail::accumulator_identity<init_value_type>()),
  2126. std::forward<E>(e),
  2127. axis
  2128. );
  2129. }
  2130. template <class T = void, class E>
  2131. inline auto cumprod(E&& e)
  2132. {
  2133. using init_value_type = std::conditional_t<std::is_same<T, void>::value, typename std::decay_t<E>::value_type, T>;
  2134. return accumulate(
  2135. make_xaccumulator_functor(detail::multiplies(), detail::accumulator_identity<init_value_type>()),
  2136. std::forward<E>(e)
  2137. );
  2138. }
  2139. /*****************
  2140. * nan functions *
  2141. *****************/
  2142. namespace detail
  2143. {
  2144. struct nan_to_num_functor
  2145. {
  2146. template <class A>
  2147. inline auto operator()(const A& a) const
  2148. {
  2149. if (math::isnan(a))
  2150. {
  2151. return A(0);
  2152. }
  2153. if (math::isinf(a))
  2154. {
  2155. if (a < 0)
  2156. {
  2157. return std::numeric_limits<A>::lowest();
  2158. }
  2159. else
  2160. {
  2161. return (std::numeric_limits<A>::max)();
  2162. }
  2163. }
  2164. return a;
  2165. }
  2166. };
  2167. struct nan_min
  2168. {
  2169. template <class T, class U>
  2170. constexpr auto operator()(const T lhs, const U rhs) const
  2171. {
  2172. // Clunky expression for working with GCC 4.9
  2173. return math::isnan(lhs)
  2174. ? rhs
  2175. : (math::isnan(rhs) ? lhs
  2176. : std::common_type_t<T, U>(
  2177. detail::make_xfunction<math::minimum<void>>(lhs, rhs)
  2178. ));
  2179. }
  2180. };
  2181. struct nan_max
  2182. {
  2183. template <class T, class U>
  2184. constexpr auto operator()(const T lhs, const U rhs) const
  2185. {
  2186. // Clunky expression for working with GCC 4.9
  2187. return math::isnan(lhs)
  2188. ? rhs
  2189. : (math::isnan(rhs) ? lhs
  2190. : std::common_type_t<T, U>(
  2191. detail::make_xfunction<math::maximum<void>>(lhs, rhs)
  2192. ));
  2193. }
  2194. };
  2195. struct nan_plus
  2196. {
  2197. template <class T, class U>
  2198. constexpr auto operator()(const T lhs, const U rhs) const
  2199. {
  2200. return !math::isnan(rhs) ? lhs + rhs : lhs;
  2201. }
  2202. };
  2203. struct nan_multiplies
  2204. {
  2205. template <class T, class U>
  2206. constexpr auto operator()(const T lhs, const U rhs) const
  2207. {
  2208. return !math::isnan(rhs) ? lhs * rhs : lhs;
  2209. }
  2210. };
  2211. template <class T, int V>
  2212. struct nan_init
  2213. {
  2214. using value_type = T;
  2215. using result_type = T;
  2216. constexpr result_type operator()(const value_type lhs) const
  2217. {
  2218. return math::isnan(lhs) ? result_type(V) : lhs;
  2219. }
  2220. };
  2221. }
  2222. /**
  2223. * @defgroup nan_functions nan functions
  2224. */
  2225. /**
  2226. * @ingroup nan_functions
  2227. * @brief Convert nan or +/- inf to numbers
  2228. *
  2229. * This functions converts NaN to 0, and +inf to the highest, -inf to the lowest
  2230. * floating point value of the same type.
  2231. *
  2232. * @param e input \ref xexpression
  2233. * @return an \ref xexpression
  2234. */
  2235. template <class E>
  2236. inline auto nan_to_num(E&& e)
  2237. {
  2238. return detail::make_xfunction<detail::nan_to_num_functor>(std::forward<E>(e));
  2239. }
  2240. /**
  2241. * @ingroup nan_functions
  2242. * @brief Minimum element over given axes, ignoring NaNs.
  2243. *
  2244. * Returns an \ref xreducer for the minimum of elements over given
  2245. * @p axes, ignoring NaNs.
  2246. * @warning Casting the result to an integer type can cause undefined behavior.
  2247. * @param e an \ref xexpression
  2248. * @param axes the axes along which the minimum is found (optional)
  2249. * @param es evaluation strategy of the reducer (optional)
  2250. * @tparam T the result type. The default is `E::value_type`.
  2251. * @return an \ref xreducer
  2252. */
  2253. XTENSOR_REDUCER_FUNCTION(nanmin, detail::nan_min, typename std::decay_t<E>::value_type, std::nan("0"))
  2254. /**
  2255. * @ingroup nan_functions
  2256. * @brief Maximum element along given axes, ignoring NaNs.
  2257. *
  2258. * Returns an \ref xreducer for the sum of elements over given
  2259. * @p axes, ignoring NaN.
  2260. * @warning Casting the result to an integer type can cause undefined behavior.
  2261. * @param e an \ref xexpression
  2262. * @param axes the axes along which the sum is performed (optional)
  2263. * @param es evaluation strategy of the reducer (optional)
  2264. * @tparam T the result type. The default is `E::value_type`.
  2265. * @return an \ref xreducer
  2266. */
  2267. XTENSOR_REDUCER_FUNCTION(nanmax, detail::nan_max, typename std::decay_t<E>::value_type, std::nan("0"))
  2268. /**
  2269. * @ingroup nan_functions
  2270. * @brief Sum of elements over given axes, replacing NaN with 0.
  2271. *
  2272. * Returns an \ref xreducer for the sum of elements over given
  2273. * @p axes, ignoring NaN.
  2274. * @param e an \ref xexpression
  2275. * @param axes the axes along which the sum is performed (optional)
  2276. * @param es evaluation strategy of the reducer (optional)
  2277. * @tparam T the value type used for internal computation. The default is
  2278. * `E::value_type`. `T` is also used for determining the value type
  2279. * of the result, which is the type of `T() + E::value_type()`.
  2280. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  2281. * @return an \ref xreducer
  2282. */
  2283. XTENSOR_REDUCER_FUNCTION(nansum, detail::nan_plus, typename std::decay_t<E>::value_type, 0)
  2284. /**
  2285. * @ingroup nan_functions
  2286. * @brief Product of elements over given axes, replacing NaN with 1.
  2287. *
  2288. * Returns an \ref xreducer for the sum of elements over given
  2289. * @p axes, replacing nan with 1.
  2290. * @param e an \ref xexpression
  2291. * @param axes the axes along which the sum is performed (optional)
  2292. * @param es evaluation strategy of the reducer (optional)
  2293. * @tparam T the value type used for internal computation. The default is
  2294. * `E::value_type`. `T` is also used for determining the value type
  2295. * of the result, which is the type of `T() * E::value_type()`.
  2296. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  2297. * @return an \ref xreducer
  2298. */
  2299. XTENSOR_REDUCER_FUNCTION(nanprod, detail::nan_multiplies, typename std::decay_t<E>::value_type, 1)
  2300. #define COUNT_NON_ZEROS_CONTENT \
  2301. using value_type = typename std::decay_t<E>::value_type; \
  2302. using result_type = xt::detail::xreducer_size_type_t<value_type>; \
  2303. using init_value_fct = xt::const_value<result_type>; \
  2304. \
  2305. auto init_fct = init_value_fct(0); \
  2306. \
  2307. auto reduce_fct = [](const auto& lhs, const auto& rhs) \
  2308. { \
  2309. using value_t = xt::detail::xreducer_temporary_type_t<std::decay_t<decltype(rhs)>>; \
  2310. using result_t = std::decay_t<decltype(lhs)>; \
  2311. \
  2312. return (rhs != value_t(0)) ? lhs + result_t(1) : lhs; \
  2313. }; \
  2314. auto merge_func = detail::plus();
  2315. template <class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  2316. inline auto count_nonzero(E&& e, EVS es = EVS())
  2317. {
  2318. COUNT_NON_ZEROS_CONTENT;
  2319. return xt::reduce(
  2320. make_xreducer_functor(std::move(reduce_fct), std::move(init_fct), std::move(merge_func)),
  2321. std::forward<E>(e),
  2322. es
  2323. );
  2324. }
  2325. template <
  2326. class E,
  2327. class X,
  2328. class EVS = DEFAULT_STRATEGY_REDUCERS,
  2329. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::negation<xtl::is_integral<X>>)>
  2330. inline auto count_nonzero(E&& e, X&& axes, EVS es = EVS())
  2331. {
  2332. COUNT_NON_ZEROS_CONTENT;
  2333. return xt::reduce(
  2334. make_xreducer_functor(std::move(reduce_fct), std::move(init_fct), std::move(merge_func)),
  2335. std::forward<E>(e),
  2336. std::forward<X>(axes),
  2337. es
  2338. );
  2339. }
  2340. template <
  2341. class E,
  2342. class X,
  2343. class EVS = DEFAULT_STRATEGY_REDUCERS,
  2344. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::is_integral<X>)>
  2345. inline auto count_nonzero(E&& e, X axis, EVS es = EVS())
  2346. {
  2347. return count_nonzero(std::forward<E>(e), {axis}, es);
  2348. }
  2349. template <class E, class I, std::size_t N, class EVS = DEFAULT_STRATEGY_REDUCERS>
  2350. inline auto count_nonzero(E&& e, const I (&axes)[N], EVS es = EVS())
  2351. {
  2352. COUNT_NON_ZEROS_CONTENT;
  2353. return xt::reduce(
  2354. make_xreducer_functor(std::move(reduce_fct), std::move(init_fct), std::move(merge_func)),
  2355. std::forward<E>(e),
  2356. axes,
  2357. es
  2358. );
  2359. }
  2360. #undef COUNT_NON_ZEROS_CONTENT
  2361. template <class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  2362. inline auto count_nonnan(E&& e, EVS es = EVS())
  2363. {
  2364. return xt::count_nonzero(!xt::isnan(std::forward<E>(e)), es);
  2365. }
  2366. template <
  2367. class E,
  2368. class X,
  2369. class EVS = DEFAULT_STRATEGY_REDUCERS,
  2370. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::negation<xtl::is_integral<X>>)>
  2371. inline auto count_nonnan(E&& e, X&& axes, EVS es = EVS())
  2372. {
  2373. return xt::count_nonzero(!xt::isnan(std::forward<E>(e)), std::forward<X>(axes), es);
  2374. }
  2375. template <
  2376. class E,
  2377. class X,
  2378. class EVS = DEFAULT_STRATEGY_REDUCERS,
  2379. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::is_integral<X>)>
  2380. inline auto count_nonnan(E&& e, X&& axes, EVS es = EVS())
  2381. {
  2382. return xt::count_nonzero(!xt::isnan(std::forward<E>(e)), {axes}, es);
  2383. }
  2384. template <class E, class I, std::size_t N, class EVS = DEFAULT_STRATEGY_REDUCERS>
  2385. inline auto count_nonnan(E&& e, const I (&axes)[N], EVS es = EVS())
  2386. {
  2387. return xt::count_nonzero(!xt::isnan(std::forward<E>(e)), axes, es);
  2388. }
  2389. /**
  2390. * @ingroup nan_functions
  2391. * @brief Cumulative sum, replacing nan with 0.
  2392. *
  2393. * Returns an xaccumulator for the sum of elements over given
  2394. * \em axis, replacing nan with 0.
  2395. * @param e an \ref xexpression
  2396. * @param axis the axis along which the elements are accumulated (optional)
  2397. * @tparam T the value type used for internal computation. The default is
  2398. * `E::value_type`. `T` is also used for determining the value type
  2399. * of the result, which is the type of `T() + E::value_type()`.
  2400. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  2401. * @return an xaccumulator
  2402. */
  2403. template <class T = void, class E>
  2404. inline auto nancumsum(E&& e, std::ptrdiff_t axis)
  2405. {
  2406. using init_value_type = std::conditional_t<std::is_same<T, void>::value, typename std::decay_t<E>::value_type, T>;
  2407. return accumulate(
  2408. make_xaccumulator_functor(detail::nan_plus(), detail::nan_init<init_value_type, 0>()),
  2409. std::forward<E>(e),
  2410. axis
  2411. );
  2412. }
  2413. template <class T = void, class E>
  2414. inline auto nancumsum(E&& e)
  2415. {
  2416. using init_value_type = std::conditional_t<std::is_same<T, void>::value, typename std::decay_t<E>::value_type, T>;
  2417. return accumulate(
  2418. make_xaccumulator_functor(detail::nan_plus(), detail::nan_init<init_value_type, 0>()),
  2419. std::forward<E>(e)
  2420. );
  2421. }
  2422. /**
  2423. * @ingroup nan_functions
  2424. * @brief Cumulative product, replacing nan with 1.
  2425. *
  2426. * Returns an xaccumulator for the product of elements over given
  2427. * \em axis, replacing nan with 1.
  2428. * @param e an \ref xexpression
  2429. * @param axis the axis along which the elements are accumulated (optional)
  2430. * @tparam T the value type used for internal computation. The default is
  2431. * `E::value_type`. `T` is also used for determining the value type
  2432. * of the result, which is the type of `T() * E::value_type()`.
  2433. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  2434. * @return an xaccumulator
  2435. */
  2436. template <class T = void, class E>
  2437. inline auto nancumprod(E&& e, std::ptrdiff_t axis)
  2438. {
  2439. using init_value_type = std::conditional_t<std::is_same<T, void>::value, typename std::decay_t<E>::value_type, T>;
  2440. return accumulate(
  2441. make_xaccumulator_functor(detail::nan_multiplies(), detail::nan_init<init_value_type, 1>()),
  2442. std::forward<E>(e),
  2443. axis
  2444. );
  2445. }
  2446. template <class T = void, class E>
  2447. inline auto nancumprod(E&& e)
  2448. {
  2449. using init_value_type = std::conditional_t<std::is_same<T, void>::value, typename std::decay_t<E>::value_type, T>;
  2450. return accumulate(
  2451. make_xaccumulator_functor(detail::nan_multiplies(), detail::nan_init<init_value_type, 1>()),
  2452. std::forward<E>(e)
  2453. );
  2454. }
  2455. namespace detail
  2456. {
  2457. template <class T>
  2458. struct diff_impl
  2459. {
  2460. template <class Arg>
  2461. inline void operator()(
  2462. Arg& ad,
  2463. const std::size_t& n,
  2464. xstrided_slice_vector& slice1,
  2465. xstrided_slice_vector& slice2,
  2466. std::size_t saxis
  2467. )
  2468. {
  2469. for (std::size_t i = 0; i < n; ++i)
  2470. {
  2471. slice2[saxis] = range(xnone(), ad.shape()[saxis] - 1);
  2472. ad = strided_view(ad, slice1) - strided_view(ad, slice2);
  2473. }
  2474. }
  2475. };
  2476. template <>
  2477. struct diff_impl<bool>
  2478. {
  2479. template <class Arg>
  2480. inline void operator()(
  2481. Arg& ad,
  2482. const std::size_t& n,
  2483. xstrided_slice_vector& slice1,
  2484. xstrided_slice_vector& slice2,
  2485. std::size_t saxis
  2486. )
  2487. {
  2488. for (std::size_t i = 0; i < n; ++i)
  2489. {
  2490. slice2[saxis] = range(xnone(), ad.shape()[saxis] - 1);
  2491. ad = not_equal(strided_view(ad, slice1), strided_view(ad, slice2));
  2492. }
  2493. }
  2494. };
  2495. }
  2496. /**
  2497. * @ingroup nan_functions
  2498. * @brief Mean of elements over given axes, excluding NaNs.
  2499. *
  2500. * Returns an \ref xreducer for the mean of elements over given
  2501. * \em axes, excluding NaNs.
  2502. * This is not the same as counting NaNs as zero, since excluding NaNs changes the number
  2503. * of elements considered in the statistic.
  2504. * @param e an \ref xexpression
  2505. * @param axes the axes along which the mean is computed (optional)
  2506. * @param es the evaluation strategy (optional)
  2507. * @tparam T the result type. The default is `E::value_type`.
  2508. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  2509. * @return an \ref xexpression
  2510. */
  2511. template <
  2512. class T = void,
  2513. class E,
  2514. class X,
  2515. class EVS = DEFAULT_STRATEGY_REDUCERS,
  2516. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>)>
  2517. inline auto nanmean(E&& e, X&& axes, EVS es = EVS())
  2518. {
  2519. decltype(auto) sc = detail::shared_forward<E>(e);
  2520. // note: forcing copy of first axes argument -- is there a better solution?
  2521. auto axes_copy = axes;
  2522. using value_type = typename std::conditional_t<std::is_same<T, void>::value, double, T>;
  2523. using sum_type = typename std::conditional_t<
  2524. std::is_same<T, void>::value,
  2525. typename std::common_type_t<typename std::decay_t<E>::value_type, value_type>,
  2526. T>;
  2527. // sum cannot always be a double. It could be a complex number which cannot operate on
  2528. // std::plus<double>.
  2529. return nansum<sum_type>(sc, std::forward<X>(axes), es)
  2530. / xt::cast<value_type>(count_nonnan(sc, std::move(axes_copy), es));
  2531. }
  2532. template <class T = void, class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  2533. inline auto nanmean(E&& e, EVS es = EVS())
  2534. {
  2535. decltype(auto) sc = detail::shared_forward<E>(e);
  2536. using value_type = typename std::conditional_t<std::is_same<T, void>::value, double, T>;
  2537. using sum_type = typename std::conditional_t<
  2538. std::is_same<T, void>::value,
  2539. typename std::common_type_t<typename std::decay_t<E>::value_type, value_type>,
  2540. T>;
  2541. return nansum<sum_type>(sc, es) / xt::cast<value_type>(count_nonnan(sc, es));
  2542. }
  2543. template <class T = void, class E, class I, std::size_t N, class EVS = DEFAULT_STRATEGY_REDUCERS>
  2544. inline auto nanmean(E&& e, const I (&axes)[N], EVS es = EVS())
  2545. {
  2546. return nanmean<T>(
  2547. std::forward<E>(e),
  2548. xtl::forward_sequence<std::array<std::size_t, N>, decltype(axes)>(axes),
  2549. es
  2550. );
  2551. }
  2552. template <class T = void, class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  2553. inline auto nanvar(E&& e, EVS es = EVS())
  2554. {
  2555. decltype(auto) sc = detail::shared_forward<E>(e);
  2556. return nanmean<T>(square(sc - nanmean<T>(sc)), es);
  2557. }
  2558. template <class T = void, class E, class EVS = DEFAULT_STRATEGY_REDUCERS, XTL_REQUIRES(is_reducer_options<EVS>)>
  2559. inline auto nanstd(E&& e, EVS es = EVS())
  2560. {
  2561. return sqrt(nanvar<T>(std::forward<E>(e), es));
  2562. }
  2563. /**
  2564. * @ingroup nan_functions
  2565. * @brief Compute the variance along the specified axes, excluding NaNs
  2566. *
  2567. * Returns the variance of the array elements, a measure of the spread of a
  2568. * distribution. The variance is computed for the flattened array by default,
  2569. * otherwise over the specified axes.
  2570. * Excluding NaNs changes the number of elements considered in the statistic.
  2571. *
  2572. * Note: this function is not yet specialized for complex numbers.
  2573. *
  2574. * @param e an \ref xexpression
  2575. * @param axes the axes along which the variance is computed (optional)
  2576. * @param es evaluation strategy to use (lazy (default), or immediate)
  2577. * @tparam T the result type. The default is `E::value_type`.
  2578. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  2579. * @return an \ref xexpression
  2580. *
  2581. * @sa nanstd, nanmean
  2582. */
  2583. template <
  2584. class T = void,
  2585. class E,
  2586. class X,
  2587. class EVS = DEFAULT_STRATEGY_REDUCERS,
  2588. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>)>
  2589. inline auto nanvar(E&& e, X&& axes, EVS es = EVS())
  2590. {
  2591. decltype(auto) sc = detail::shared_forward<E>(e);
  2592. // note: forcing copy of first axes argument -- is there a better solution?
  2593. auto axes_copy = axes;
  2594. using result_type = typename std::conditional_t<std::is_same<T, void>::value, double, T>;
  2595. auto inner_mean = nanmean<result_type>(sc, std::move(axes_copy));
  2596. // fake keep_dims = 1
  2597. // Since the inner_shape might have a reference semantic (e.g. xbuffer_adaptor in bindings)
  2598. // We need to map it to another type before modifying it.
  2599. // We pragmatically abuse `get_strides_t`
  2600. using tmp_shape_t = get_strides_t<typename std::decay_t<E>::shape_type>;
  2601. tmp_shape_t keep_dim_shape = xtl::forward_sequence<tmp_shape_t, decltype(e.shape())>(e.shape());
  2602. for (const auto& el : axes)
  2603. {
  2604. keep_dim_shape[el] = 1;
  2605. }
  2606. auto mrv = reshape_view<XTENSOR_DEFAULT_LAYOUT>(std::move(inner_mean), std::move(keep_dim_shape));
  2607. return nanmean<result_type>(square(cast<result_type>(sc) - std::move(mrv)), std::forward<X>(axes), es);
  2608. }
  2609. /**
  2610. * @ingroup nan_functions
  2611. * @brief Compute the standard deviation along the specified axis, excluding nans.
  2612. *
  2613. * Returns the standard deviation, a measure of the spread of a distribution,
  2614. * of the array elements. The standard deviation is computed for the flattened
  2615. * array by default, otherwise over the specified axis.
  2616. * Excluding NaNs changes the number of elements considered in the statistic.
  2617. *
  2618. * Note: this function is not yet specialized for complex numbers.
  2619. *
  2620. * @param e an \ref xexpression
  2621. * @param axes the axes along which the standard deviation is computed (optional)
  2622. * @param es evaluation strategy to use (lazy (default), or immediate)
  2623. * @tparam T the result type. The default is `E::value_type`.
  2624. * You can pass `big_promote_value_type_t<E>` to avoid overflow in computation.
  2625. * @return an \ref xexpression
  2626. *
  2627. * @sa nanvar, nanmean
  2628. */
  2629. template <
  2630. class T = void,
  2631. class E,
  2632. class X,
  2633. class EVS = DEFAULT_STRATEGY_REDUCERS,
  2634. XTL_REQUIRES(xtl::negation<is_reducer_options<X>>)>
  2635. inline auto nanstd(E&& e, X&& axes, EVS es = EVS())
  2636. {
  2637. return sqrt(nanvar<T>(std::forward<E>(e), std::forward<X>(axes), es));
  2638. }
  2639. template <class T = void, class E, class A, std::size_t N, class EVS = DEFAULT_STRATEGY_REDUCERS>
  2640. inline auto nanstd(E&& e, const A (&axes)[N], EVS es = EVS())
  2641. {
  2642. return nanstd<T>(
  2643. std::forward<E>(e),
  2644. xtl::forward_sequence<std::array<std::size_t, N>, decltype(axes)>(axes),
  2645. es
  2646. );
  2647. }
  2648. template <class T = void, class E, class A, std::size_t N, class EVS = DEFAULT_STRATEGY_REDUCERS>
  2649. inline auto nanvar(E&& e, const A (&axes)[N], EVS es = EVS())
  2650. {
  2651. return nanvar<T>(
  2652. std::forward<E>(e),
  2653. xtl::forward_sequence<std::array<std::size_t, N>, decltype(axes)>(axes),
  2654. es
  2655. );
  2656. }
  2657. /**
  2658. * @ingroup red_functions
  2659. * @brief Calculate the n-th discrete difference along the given axis.
  2660. *
  2661. * Calculate the n-th discrete difference along the given axis. This function is not lazy (might change in
  2662. * the future).
  2663. * @param a an \ref xexpression
  2664. * @param n The number of times values are differenced. If zero, the input is returned as-is. (optional)
  2665. * @param axis The axis along which the difference is taken, default is the last axis.
  2666. * @return an xarray
  2667. */
  2668. template <class T>
  2669. auto diff(const xexpression<T>& a, std::size_t n = 1, std::ptrdiff_t axis = -1)
  2670. {
  2671. typename std::decay_t<T>::temporary_type ad = a.derived_cast();
  2672. std::size_t saxis = normalize_axis(ad.dimension(), axis);
  2673. if (n <= ad.size())
  2674. {
  2675. if (n != std::size_t(0))
  2676. {
  2677. xstrided_slice_vector slice1(ad.dimension(), all());
  2678. xstrided_slice_vector slice2(ad.dimension(), all());
  2679. slice1[saxis] = range(1, xnone());
  2680. detail::diff_impl<typename T::value_type> impl;
  2681. impl(ad, n, slice1, slice2, saxis);
  2682. }
  2683. }
  2684. else
  2685. {
  2686. auto shape = ad.shape();
  2687. shape[saxis] = std::size_t(0);
  2688. ad.resize(shape);
  2689. }
  2690. return ad;
  2691. }
  2692. /**
  2693. * @ingroup red_functions
  2694. * @brief Integrate along the given axis using the composite trapezoidal rule.
  2695. *
  2696. * Returns definite integral as approximated by trapezoidal rule. This function is not lazy (might change
  2697. * in the future).
  2698. * @param y an \ref xexpression
  2699. * @param dx the spacing between sample points (optional)
  2700. * @param axis the axis along which to integrate.
  2701. * @return an xarray
  2702. */
  2703. template <class T>
  2704. auto trapz(const xexpression<T>& y, double dx = 1.0, std::ptrdiff_t axis = -1)
  2705. {
  2706. auto& yd = y.derived_cast();
  2707. std::size_t saxis = normalize_axis(yd.dimension(), axis);
  2708. xstrided_slice_vector slice1(yd.dimension(), all());
  2709. xstrided_slice_vector slice2(yd.dimension(), all());
  2710. slice1[saxis] = range(1, xnone());
  2711. slice2[saxis] = range(xnone(), yd.shape()[saxis] - 1);
  2712. auto trap = dx * (strided_view(yd, slice1) + strided_view(yd, slice2)) * 0.5;
  2713. return eval(sum(trap, {saxis}));
  2714. }
  2715. /**
  2716. * @ingroup red_functions
  2717. * @brief Integrate along the given axis using the composite trapezoidal rule.
  2718. *
  2719. * Returns definite integral as approximated by trapezoidal rule. This function is not lazy (might change
  2720. * in the future).
  2721. * @param y an \ref xexpression
  2722. * @param x an \ref xexpression representing the sample points corresponding to the y values.
  2723. * @param axis the axis along which to integrate.
  2724. * @return an xarray
  2725. */
  2726. template <class T, class E>
  2727. auto trapz(const xexpression<T>& y, const xexpression<E>& x, std::ptrdiff_t axis = -1)
  2728. {
  2729. auto& yd = y.derived_cast();
  2730. auto& xd = x.derived_cast();
  2731. decltype(diff(x)) dx;
  2732. std::size_t saxis = normalize_axis(yd.dimension(), axis);
  2733. if (xd.dimension() == 1)
  2734. {
  2735. dx = diff(x);
  2736. typename std::decay_t<decltype(yd)>::shape_type shape;
  2737. resize_container(shape, yd.dimension());
  2738. std::fill(shape.begin(), shape.end(), 1);
  2739. shape[saxis] = dx.shape()[0];
  2740. dx.reshape(shape);
  2741. }
  2742. else
  2743. {
  2744. dx = diff(x, 1, axis);
  2745. }
  2746. xstrided_slice_vector slice1(yd.dimension(), all());
  2747. xstrided_slice_vector slice2(yd.dimension(), all());
  2748. slice1[saxis] = range(1, xnone());
  2749. slice2[saxis] = range(xnone(), yd.shape()[saxis] - 1);
  2750. auto trap = dx * (strided_view(yd, slice1) + strided_view(yd, slice2)) * 0.5;
  2751. return eval(sum(trap, {saxis}));
  2752. }
  2753. /**
  2754. * @ingroup basic_functions
  2755. * @brief Returns the one-dimensional piecewise linear interpolant to a function with given discrete data
  2756. * points (xp, fp), evaluated at x.
  2757. *
  2758. * @param x The x-coordinates at which to evaluate the interpolated values (sorted).
  2759. * @param xp The x-coordinates of the data points (sorted).
  2760. * @param fp The y-coordinates of the data points, same length as xp.
  2761. * @param left Value to return for x < xp[0].
  2762. * @param right Value to return for x > xp[-1]
  2763. * @return an one-dimensional xarray, same length as x.
  2764. */
  2765. template <class E1, class E2, class E3, typename T>
  2766. inline auto interp(const E1& x, const E2& xp, const E3& fp, T left, T right)
  2767. {
  2768. using size_type = common_size_type_t<E1, E2, E3>;
  2769. using value_type = typename E3::value_type;
  2770. // basic checks
  2771. XTENSOR_ASSERT(xp.dimension() == 1);
  2772. XTENSOR_ASSERT(std::is_sorted(x.cbegin(), x.cend()));
  2773. XTENSOR_ASSERT(std::is_sorted(xp.cbegin(), xp.cend()));
  2774. // allocate output
  2775. auto f = xtensor<value_type, 1>::from_shape(x.shape());
  2776. // counter in "x": from left
  2777. size_type i = 0;
  2778. // fill f[i] for x[i] <= xp[0]
  2779. for (; i < x.size(); ++i)
  2780. {
  2781. if (x[i] > xp[0])
  2782. {
  2783. break;
  2784. }
  2785. f[i] = static_cast<value_type>(left);
  2786. }
  2787. // counter in "x": from right
  2788. // (index counts one right, to terminate the reverse loop, without risking being negative)
  2789. size_type imax = x.size();
  2790. // fill f[i] for x[-1] >= xp[-1]
  2791. for (; imax > 0; --imax)
  2792. {
  2793. if (x[imax - 1] < xp[xp.size() - 1])
  2794. {
  2795. break;
  2796. }
  2797. f[imax - 1] = static_cast<value_type>(right);
  2798. }
  2799. // catch edge case: all entries are "right"
  2800. if (imax == 0)
  2801. {
  2802. return f;
  2803. }
  2804. // set "imax" as actual index
  2805. // (counted one right, see above)
  2806. --imax;
  2807. // counter in "xp"
  2808. size_type ip = 1;
  2809. // fill f[i] for the interior
  2810. for (; i <= imax; ++i)
  2811. {
  2812. // - search next value in "xp"
  2813. while (x[i] > xp[ip])
  2814. {
  2815. ++ip;
  2816. }
  2817. // - distances as doubles
  2818. double dfp = static_cast<double>(fp[ip] - fp[ip - 1]);
  2819. double dxp = static_cast<double>(xp[ip] - xp[ip - 1]);
  2820. double dx = static_cast<double>(x[i] - xp[ip - 1]);
  2821. // - interpolate
  2822. f[i] = fp[ip - 1] + static_cast<value_type>(dfp / dxp * dx);
  2823. }
  2824. return f;
  2825. }
  2826. namespace detail
  2827. {
  2828. template <class E1, class E2>
  2829. auto calculate_discontinuity(E1&& discontinuity, E2&&)
  2830. {
  2831. return discontinuity;
  2832. }
  2833. template <class E2>
  2834. auto calculate_discontinuity(xt::placeholders::xtuph, E2&& period)
  2835. {
  2836. return 0.5 * period;
  2837. }
  2838. template <class E1, class E2>
  2839. auto
  2840. calculate_interval(E2&& period, typename std::enable_if<std::is_integral<E1>::value, E1>::type* = 0)
  2841. {
  2842. auto interval_high = 0.5 * period;
  2843. uint64_t remainder = static_cast<uint64_t>(period) % 2;
  2844. auto boundary_ambiguous = (remainder == 0);
  2845. return std::make_tuple(interval_high, boundary_ambiguous);
  2846. }
  2847. template <class E1, class E2>
  2848. auto
  2849. calculate_interval(E2&& period, typename std::enable_if<std::is_floating_point<E1>::value, E1>::type* = 0)
  2850. {
  2851. auto interval_high = 0.5 * period;
  2852. auto boundary_ambiguous = true;
  2853. return std::make_tuple(interval_high, boundary_ambiguous);
  2854. }
  2855. }
  2856. /**
  2857. * @ingroup basic_functions
  2858. * @brief Unwrap by taking the complement of large deltas with respect to the period
  2859. * @details https://numpy.org/doc/stable/reference/generated/numpy.unwrap.html
  2860. * @param p Input array.
  2861. * @param discontinuity
  2862. * Maximum discontinuity between values, default is `period / 2`.
  2863. * Values below `period / 2` are treated as if they were `period / 2`.
  2864. * To have an effect different from the default, use `discontinuity > period / 2`.
  2865. * @param axis Axis along which unwrap will operate, default: the last axis.
  2866. * @param period Size of the range over which the input wraps. Default: \f$ 2 \pi \f$.
  2867. */
  2868. template <class E1, class E2 = xt::placeholders::xtuph, class E3 = double>
  2869. inline auto unwrap(
  2870. E1&& p,
  2871. E2 discontinuity = xnone(),
  2872. std::ptrdiff_t axis = -1,
  2873. E3 period = 2.0 * xt::numeric_constants<double>::PI
  2874. )
  2875. {
  2876. auto discont = detail::calculate_discontinuity(discontinuity, period);
  2877. using value_type = typename std::decay_t<E1>::value_type;
  2878. std::size_t saxis = normalize_axis(p.dimension(), axis);
  2879. auto dd = diff(p, 1, axis);
  2880. xstrided_slice_vector slice(p.dimension(), all());
  2881. slice[saxis] = range(1, xnone());
  2882. auto interval_tuple = detail::calculate_interval<value_type>(period);
  2883. auto interval_high = std::get<0>(interval_tuple);
  2884. auto boundary_ambiguous = std::get<1>(interval_tuple);
  2885. auto interval_low = -interval_high;
  2886. auto ddmod = xt::eval(xt::fmod(xt::fmod(dd - interval_low, period) + period, period) + interval_low);
  2887. if (boundary_ambiguous)
  2888. {
  2889. // for `mask = (abs(dd) == period/2)`, the above line made
  2890. //`ddmod[mask] == -period/2`. correct these such that
  2891. //`ddmod[mask] == sign(dd[mask])*period/2`.
  2892. auto boolmap = xt::equal(ddmod, interval_low) && (xt::greater(dd, 0.0));
  2893. ddmod = xt::where(boolmap, interval_high, ddmod);
  2894. }
  2895. auto ph_correct = xt::eval(ddmod - dd);
  2896. ph_correct = xt::where(xt::abs(dd) < discont, 0.0, ph_correct);
  2897. E1 up(p);
  2898. strided_view(up, slice) = strided_view(p, slice)
  2899. + xt::cumsum(ph_correct, static_cast<std::ptrdiff_t>(saxis));
  2900. return up;
  2901. }
  2902. /**
  2903. * @ingroup basic_functions
  2904. * @brief Returns the one-dimensional piecewise linear interpolant to a function with given discrete data
  2905. * points (xp, fp), evaluated at x.
  2906. *
  2907. * @param x The x-coordinates at which to evaluate the interpolated values (sorted).
  2908. * @param xp The x-coordinates of the data points (sorted).
  2909. * @param fp The y-coordinates of the data points, same length as xp.
  2910. * @return an one-dimensional xarray, same length as x.
  2911. */
  2912. template <class E1, class E2, class E3>
  2913. inline auto interp(const E1& x, const E2& xp, const E3& fp)
  2914. {
  2915. return interp(x, xp, fp, fp[0], fp[fp.size() - 1]);
  2916. }
  2917. /**
  2918. * @brief Returns the covariance matrix
  2919. *
  2920. * @param x one or two dimensional array
  2921. * @param y optional one-dimensional array to build covariance to x
  2922. */
  2923. template <class E1>
  2924. inline auto cov(const E1& x, const E1& y = E1())
  2925. {
  2926. using value_type = typename E1::value_type;
  2927. if (y.dimension() == 0)
  2928. {
  2929. auto s = x.shape();
  2930. using size_type = std::decay_t<decltype(s[0])>;
  2931. if (x.dimension() == 1)
  2932. {
  2933. auto covar = eval(zeros<value_type>({1, 1}));
  2934. auto x_norm = x - eval(mean(x));
  2935. covar(0, 0) = std::inner_product(x_norm.begin(), x_norm.end(), x_norm.begin(), 0.0)
  2936. / value_type(s[0] - 1);
  2937. return covar;
  2938. }
  2939. XTENSOR_ASSERT(x.dimension() == 2);
  2940. auto covar = eval(zeros<value_type>({s[0], s[0]}));
  2941. auto m = eval(mean(x, {1}));
  2942. m.reshape({m.shape()[0], 1});
  2943. auto x_norm = x - m;
  2944. for (size_type i = 0; i < s[0]; i++)
  2945. {
  2946. auto xi = strided_view(x_norm, {range(i, i + 1), all()});
  2947. for (size_type j = i; j < s[0]; j++)
  2948. {
  2949. auto xj = strided_view(x_norm, {range(j, j + 1), all()});
  2950. covar(j, i) = std::inner_product(xi.begin(), xi.end(), xj.begin(), 0.0)
  2951. / value_type(s[1] - 1);
  2952. }
  2953. }
  2954. return eval(covar + transpose(covar) - diag(diagonal(covar)));
  2955. }
  2956. else
  2957. {
  2958. return cov(eval(stack(xtuple(x, y))));
  2959. }
  2960. }
  2961. /*
  2962. * convolution mode placeholders for selecting the algorithm
  2963. * used in computing a 1D convolution.
  2964. * Same as NumPy's mode parameter.
  2965. */
  2966. namespace convolve_mode
  2967. {
  2968. struct valid
  2969. {
  2970. };
  2971. struct full
  2972. {
  2973. };
  2974. }
  2975. namespace detail
  2976. {
  2977. template <class E1, class E2>
  2978. inline auto convolve_impl(E1&& e1, E2&& e2, convolve_mode::valid)
  2979. {
  2980. using value_type = typename std::decay<E1>::type::value_type;
  2981. const std::size_t na = e1.size();
  2982. const std::size_t nv = e2.size();
  2983. const std::size_t n = na - nv + 1;
  2984. xt::xtensor<value_type, 1> out = xt::zeros<value_type>({n});
  2985. for (std::size_t i = 0; i < n; i++)
  2986. {
  2987. for (std::size_t j = 0; j < nv; j++)
  2988. {
  2989. out(i) += e1(j) * e2(j + i);
  2990. }
  2991. }
  2992. return out;
  2993. }
  2994. template <class E1, class E2>
  2995. inline auto convolve_impl(E1&& e1, E2&& e2, convolve_mode::full)
  2996. {
  2997. using value_type = typename std::decay<E1>::type::value_type;
  2998. const std::size_t na = e1.size();
  2999. const std::size_t nv = e2.size();
  3000. const std::size_t n = na + nv - 1;
  3001. xt::xtensor<value_type, 1> out = xt::zeros<value_type>({n});
  3002. for (std::size_t i = 0; i < n; i++)
  3003. {
  3004. const std::size_t jmn = (i >= nv - 1) ? i - (nv - 1) : 0;
  3005. const std::size_t jmx = (i < na - 1) ? i : na - 1;
  3006. for (std::size_t j = jmn; j <= jmx; ++j)
  3007. {
  3008. out(i) += e1(j) * e2(i - j);
  3009. }
  3010. }
  3011. return out;
  3012. }
  3013. }
  3014. /*
  3015. * @brief computes the 1D convolution between two 1D expressions
  3016. *
  3017. * @param a 1D expression
  3018. * @param v 1D expression
  3019. * @param mode placeholder Select algorithm #convolve_mode
  3020. *
  3021. * @detail the algorithm convolves a with v and will incur a copy overhead
  3022. * should v be longer than a.
  3023. */
  3024. template <class E1, class E2, class E3>
  3025. inline auto convolve(E1&& a, E2&& v, E3 mode)
  3026. {
  3027. if (a.dimension() != 1 || v.dimension() != 1)
  3028. {
  3029. XTENSOR_THROW(std::runtime_error, "Invalid dimentions convolution arguments must be 1D expressions");
  3030. }
  3031. XTENSOR_ASSERT(a.size() > 0 && v.size() > 0);
  3032. // swap them so a is always the longest one
  3033. if (a.size() < v.size())
  3034. {
  3035. return detail::convolve_impl(std::forward<E2>(v), std::forward<E1>(a), mode);
  3036. }
  3037. else
  3038. {
  3039. return detail::convolve_impl(std::forward<E1>(a), std::forward<E2>(v), mode);
  3040. }
  3041. }
  3042. }
  3043. #endif