function_base.py 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809
  1. from __future__ import division, absolute_import, print_function
  2. try:
  3. # Accessing collections abstact classes from collections
  4. # has been deprecated since Python 3.3
  5. import collections.abc as collections_abc
  6. except ImportError:
  7. import collections as collections_abc
  8. import functools
  9. import re
  10. import sys
  11. import warnings
  12. import numpy as np
  13. import numpy.core.numeric as _nx
  14. from numpy.core import atleast_1d, transpose
  15. from numpy.core.numeric import (
  16. ones, zeros, arange, concatenate, array, asarray, asanyarray, empty,
  17. empty_like, ndarray, around, floor, ceil, take, dot, where, intp,
  18. integer, isscalar, absolute
  19. )
  20. from numpy.core.umath import (
  21. pi, add, arctan2, frompyfunc, cos, less_equal, sqrt, sin,
  22. mod, exp, not_equal, subtract
  23. )
  24. from numpy.core.fromnumeric import (
  25. ravel, nonzero, partition, mean, any, sum
  26. )
  27. from numpy.core.numerictypes import typecodes
  28. from numpy.core.overrides import set_module
  29. from numpy.core import overrides
  30. from numpy.core.function_base import add_newdoc
  31. from numpy.lib.twodim_base import diag
  32. from .utils import deprecate
  33. from numpy.core.multiarray import (
  34. _insert, add_docstring, bincount, normalize_axis_index, _monotonicity,
  35. interp as compiled_interp, interp_complex as compiled_interp_complex
  36. )
  37. from numpy.core.umath import _add_newdoc_ufunc as add_newdoc_ufunc
  38. from numpy.compat import long
  39. if sys.version_info[0] < 3:
  40. # Force range to be a generator, for np.delete's usage.
  41. range = xrange
  42. import __builtin__ as builtins
  43. else:
  44. import builtins
  45. array_function_dispatch = functools.partial(
  46. overrides.array_function_dispatch, module='numpy')
  47. # needed in this module for compatibility
  48. from numpy.lib.histograms import histogram, histogramdd
  49. __all__ = [
  50. 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', 'percentile',
  51. 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', 'flip',
  52. 'rot90', 'extract', 'place', 'vectorize', 'asarray_chkfinite', 'average',
  53. 'bincount', 'digitize', 'cov', 'corrcoef',
  54. 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett',
  55. 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring',
  56. 'meshgrid', 'delete', 'insert', 'append', 'interp', 'add_newdoc_ufunc',
  57. 'quantile'
  58. ]
  59. def _rot90_dispatcher(m, k=None, axes=None):
  60. return (m,)
  61. @array_function_dispatch(_rot90_dispatcher)
  62. def rot90(m, k=1, axes=(0,1)):
  63. """
  64. Rotate an array by 90 degrees in the plane specified by axes.
  65. Rotation direction is from the first towards the second axis.
  66. Parameters
  67. ----------
  68. m : array_like
  69. Array of two or more dimensions.
  70. k : integer
  71. Number of times the array is rotated by 90 degrees.
  72. axes: (2,) array_like
  73. The array is rotated in the plane defined by the axes.
  74. Axes must be different.
  75. .. versionadded:: 1.12.0
  76. Returns
  77. -------
  78. y : ndarray
  79. A rotated view of `m`.
  80. See Also
  81. --------
  82. flip : Reverse the order of elements in an array along the given axis.
  83. fliplr : Flip an array horizontally.
  84. flipud : Flip an array vertically.
  85. Notes
  86. -----
  87. rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1))
  88. rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1))
  89. Examples
  90. --------
  91. >>> m = np.array([[1,2],[3,4]], int)
  92. >>> m
  93. array([[1, 2],
  94. [3, 4]])
  95. >>> np.rot90(m)
  96. array([[2, 4],
  97. [1, 3]])
  98. >>> np.rot90(m, 2)
  99. array([[4, 3],
  100. [2, 1]])
  101. >>> m = np.arange(8).reshape((2,2,2))
  102. >>> np.rot90(m, 1, (1,2))
  103. array([[[1, 3],
  104. [0, 2]],
  105. [[5, 7],
  106. [4, 6]]])
  107. """
  108. axes = tuple(axes)
  109. if len(axes) != 2:
  110. raise ValueError("len(axes) must be 2.")
  111. m = asanyarray(m)
  112. if axes[0] == axes[1] or absolute(axes[0] - axes[1]) == m.ndim:
  113. raise ValueError("Axes must be different.")
  114. if (axes[0] >= m.ndim or axes[0] < -m.ndim
  115. or axes[1] >= m.ndim or axes[1] < -m.ndim):
  116. raise ValueError("Axes={} out of range for array of ndim={}."
  117. .format(axes, m.ndim))
  118. k %= 4
  119. if k == 0:
  120. return m[:]
  121. if k == 2:
  122. return flip(flip(m, axes[0]), axes[1])
  123. axes_list = arange(0, m.ndim)
  124. (axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]],
  125. axes_list[axes[0]])
  126. if k == 1:
  127. return transpose(flip(m,axes[1]), axes_list)
  128. else:
  129. # k == 3
  130. return flip(transpose(m, axes_list), axes[1])
  131. def _flip_dispatcher(m, axis=None):
  132. return (m,)
  133. @array_function_dispatch(_flip_dispatcher)
  134. def flip(m, axis=None):
  135. """
  136. Reverse the order of elements in an array along the given axis.
  137. The shape of the array is preserved, but the elements are reordered.
  138. .. versionadded:: 1.12.0
  139. Parameters
  140. ----------
  141. m : array_like
  142. Input array.
  143. axis : None or int or tuple of ints, optional
  144. Axis or axes along which to flip over. The default,
  145. axis=None, will flip over all of the axes of the input array.
  146. If axis is negative it counts from the last to the first axis.
  147. If axis is a tuple of ints, flipping is performed on all of the axes
  148. specified in the tuple.
  149. .. versionchanged:: 1.15.0
  150. None and tuples of axes are supported
  151. Returns
  152. -------
  153. out : array_like
  154. A view of `m` with the entries of axis reversed. Since a view is
  155. returned, this operation is done in constant time.
  156. See Also
  157. --------
  158. flipud : Flip an array vertically (axis=0).
  159. fliplr : Flip an array horizontally (axis=1).
  160. Notes
  161. -----
  162. flip(m, 0) is equivalent to flipud(m).
  163. flip(m, 1) is equivalent to fliplr(m).
  164. flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at position n.
  165. flip(m) corresponds to ``m[::-1,::-1,...,::-1]`` with ``::-1`` at all
  166. positions.
  167. flip(m, (0, 1)) corresponds to ``m[::-1,::-1,...]`` with ``::-1`` at
  168. position 0 and position 1.
  169. Examples
  170. --------
  171. >>> A = np.arange(8).reshape((2,2,2))
  172. >>> A
  173. array([[[0, 1],
  174. [2, 3]],
  175. [[4, 5],
  176. [6, 7]]])
  177. >>> flip(A, 0)
  178. array([[[4, 5],
  179. [6, 7]],
  180. [[0, 1],
  181. [2, 3]]])
  182. >>> flip(A, 1)
  183. array([[[2, 3],
  184. [0, 1]],
  185. [[6, 7],
  186. [4, 5]]])
  187. >>> np.flip(A)
  188. array([[[7, 6],
  189. [5, 4]],
  190. [[3, 2],
  191. [1, 0]]])
  192. >>> np.flip(A, (0, 2))
  193. array([[[5, 4],
  194. [7, 6]],
  195. [[1, 0],
  196. [3, 2]]])
  197. >>> A = np.random.randn(3,4,5)
  198. >>> np.all(flip(A,2) == A[:,:,::-1,...])
  199. True
  200. """
  201. if not hasattr(m, 'ndim'):
  202. m = asarray(m)
  203. if axis is None:
  204. indexer = (np.s_[::-1],) * m.ndim
  205. else:
  206. axis = _nx.normalize_axis_tuple(axis, m.ndim)
  207. indexer = [np.s_[:]] * m.ndim
  208. for ax in axis:
  209. indexer[ax] = np.s_[::-1]
  210. indexer = tuple(indexer)
  211. return m[indexer]
  212. @set_module('numpy')
  213. def iterable(y):
  214. """
  215. Check whether or not an object can be iterated over.
  216. Parameters
  217. ----------
  218. y : object
  219. Input object.
  220. Returns
  221. -------
  222. b : bool
  223. Return ``True`` if the object has an iterator method or is a
  224. sequence and ``False`` otherwise.
  225. Examples
  226. --------
  227. >>> np.iterable([1, 2, 3])
  228. True
  229. >>> np.iterable(2)
  230. False
  231. """
  232. try:
  233. iter(y)
  234. except TypeError:
  235. return False
  236. return True
  237. def _average_dispatcher(a, axis=None, weights=None, returned=None):
  238. return (a, weights)
  239. @array_function_dispatch(_average_dispatcher)
  240. def average(a, axis=None, weights=None, returned=False):
  241. """
  242. Compute the weighted average along the specified axis.
  243. Parameters
  244. ----------
  245. a : array_like
  246. Array containing data to be averaged. If `a` is not an array, a
  247. conversion is attempted.
  248. axis : None or int or tuple of ints, optional
  249. Axis or axes along which to average `a`. The default,
  250. axis=None, will average over all of the elements of the input array.
  251. If axis is negative it counts from the last to the first axis.
  252. .. versionadded:: 1.7.0
  253. If axis is a tuple of ints, averaging is performed on all of the axes
  254. specified in the tuple instead of a single axis or all the axes as
  255. before.
  256. weights : array_like, optional
  257. An array of weights associated with the values in `a`. Each value in
  258. `a` contributes to the average according to its associated weight.
  259. The weights array can either be 1-D (in which case its length must be
  260. the size of `a` along the given axis) or of the same shape as `a`.
  261. If `weights=None`, then all data in `a` are assumed to have a
  262. weight equal to one.
  263. returned : bool, optional
  264. Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`)
  265. is returned, otherwise only the average is returned.
  266. If `weights=None`, `sum_of_weights` is equivalent to the number of
  267. elements over which the average is taken.
  268. Returns
  269. -------
  270. retval, [sum_of_weights] : array_type or double
  271. Return the average along the specified axis. When `returned` is `True`,
  272. return a tuple with the average as the first element and the sum
  273. of the weights as the second element. `sum_of_weights` is of the
  274. same type as `retval`. The result dtype follows a genereal pattern.
  275. If `weights` is None, the result dtype will be that of `a` , or ``float64``
  276. if `a` is integral. Otherwise, if `weights` is not None and `a` is non-
  277. integral, the result type will be the type of lowest precision capable of
  278. representing values of both `a` and `weights`. If `a` happens to be
  279. integral, the previous rules still applies but the result dtype will
  280. at least be ``float64``.
  281. Raises
  282. ------
  283. ZeroDivisionError
  284. When all weights along axis are zero. See `numpy.ma.average` for a
  285. version robust to this type of error.
  286. TypeError
  287. When the length of 1D `weights` is not the same as the shape of `a`
  288. along axis.
  289. See Also
  290. --------
  291. mean
  292. ma.average : average for masked arrays -- useful if your data contains
  293. "missing" values
  294. numpy.result_type : Returns the type that results from applying the
  295. numpy type promotion rules to the arguments.
  296. Examples
  297. --------
  298. >>> data = range(1,5)
  299. >>> data
  300. [1, 2, 3, 4]
  301. >>> np.average(data)
  302. 2.5
  303. >>> np.average(range(1,11), weights=range(10,0,-1))
  304. 4.0
  305. >>> data = np.arange(6).reshape((3,2))
  306. >>> data
  307. array([[0, 1],
  308. [2, 3],
  309. [4, 5]])
  310. >>> np.average(data, axis=1, weights=[1./4, 3./4])
  311. array([ 0.75, 2.75, 4.75])
  312. >>> np.average(data, weights=[1./4, 3./4])
  313. Traceback (most recent call last):
  314. ...
  315. TypeError: Axis must be specified when shapes of a and weights differ.
  316. >>> a = np.ones(5, dtype=np.float128)
  317. >>> w = np.ones(5, dtype=np.complex64)
  318. >>> avg = np.average(a, weights=w)
  319. >>> print(avg.dtype)
  320. complex256
  321. """
  322. a = np.asanyarray(a)
  323. if weights is None:
  324. avg = a.mean(axis)
  325. scl = avg.dtype.type(a.size/avg.size)
  326. else:
  327. wgt = np.asanyarray(weights)
  328. if issubclass(a.dtype.type, (np.integer, np.bool_)):
  329. result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8')
  330. else:
  331. result_dtype = np.result_type(a.dtype, wgt.dtype)
  332. # Sanity checks
  333. if a.shape != wgt.shape:
  334. if axis is None:
  335. raise TypeError(
  336. "Axis must be specified when shapes of a and weights "
  337. "differ.")
  338. if wgt.ndim != 1:
  339. raise TypeError(
  340. "1D weights expected when shapes of a and weights differ.")
  341. if wgt.shape[0] != a.shape[axis]:
  342. raise ValueError(
  343. "Length of weights not compatible with specified axis.")
  344. # setup wgt to broadcast along axis
  345. wgt = np.broadcast_to(wgt, (a.ndim-1)*(1,) + wgt.shape)
  346. wgt = wgt.swapaxes(-1, axis)
  347. scl = wgt.sum(axis=axis, dtype=result_dtype)
  348. if np.any(scl == 0.0):
  349. raise ZeroDivisionError(
  350. "Weights sum to zero, can't be normalized")
  351. avg = np.multiply(a, wgt, dtype=result_dtype).sum(axis)/scl
  352. if returned:
  353. if scl.shape != avg.shape:
  354. scl = np.broadcast_to(scl, avg.shape).copy()
  355. return avg, scl
  356. else:
  357. return avg
  358. @set_module('numpy')
  359. def asarray_chkfinite(a, dtype=None, order=None):
  360. """Convert the input to an array, checking for NaNs or Infs.
  361. Parameters
  362. ----------
  363. a : array_like
  364. Input data, in any form that can be converted to an array. This
  365. includes lists, lists of tuples, tuples, tuples of tuples, tuples
  366. of lists and ndarrays. Success requires no NaNs or Infs.
  367. dtype : data-type, optional
  368. By default, the data-type is inferred from the input data.
  369. order : {'C', 'F'}, optional
  370. Whether to use row-major (C-style) or
  371. column-major (Fortran-style) memory representation.
  372. Defaults to 'C'.
  373. Returns
  374. -------
  375. out : ndarray
  376. Array interpretation of `a`. No copy is performed if the input
  377. is already an ndarray. If `a` is a subclass of ndarray, a base
  378. class ndarray is returned.
  379. Raises
  380. ------
  381. ValueError
  382. Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity).
  383. See Also
  384. --------
  385. asarray : Create and array.
  386. asanyarray : Similar function which passes through subclasses.
  387. ascontiguousarray : Convert input to a contiguous array.
  388. asfarray : Convert input to a floating point ndarray.
  389. asfortranarray : Convert input to an ndarray with column-major
  390. memory order.
  391. fromiter : Create an array from an iterator.
  392. fromfunction : Construct an array by executing a function on grid
  393. positions.
  394. Examples
  395. --------
  396. Convert a list into an array. If all elements are finite
  397. ``asarray_chkfinite`` is identical to ``asarray``.
  398. >>> a = [1, 2]
  399. >>> np.asarray_chkfinite(a, dtype=float)
  400. array([1., 2.])
  401. Raises ValueError if array_like contains Nans or Infs.
  402. >>> a = [1, 2, np.inf]
  403. >>> try:
  404. ... np.asarray_chkfinite(a)
  405. ... except ValueError:
  406. ... print('ValueError')
  407. ...
  408. ValueError
  409. """
  410. a = asarray(a, dtype=dtype, order=order)
  411. if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all():
  412. raise ValueError(
  413. "array must not contain infs or NaNs")
  414. return a
  415. def _piecewise_dispatcher(x, condlist, funclist, *args, **kw):
  416. yield x
  417. # support the undocumented behavior of allowing scalars
  418. if np.iterable(condlist):
  419. for c in condlist:
  420. yield c
  421. @array_function_dispatch(_piecewise_dispatcher)
  422. def piecewise(x, condlist, funclist, *args, **kw):
  423. """
  424. Evaluate a piecewise-defined function.
  425. Given a set of conditions and corresponding functions, evaluate each
  426. function on the input data wherever its condition is true.
  427. Parameters
  428. ----------
  429. x : ndarray or scalar
  430. The input domain.
  431. condlist : list of bool arrays or bool scalars
  432. Each boolean array corresponds to a function in `funclist`. Wherever
  433. `condlist[i]` is True, `funclist[i](x)` is used as the output value.
  434. Each boolean array in `condlist` selects a piece of `x`,
  435. and should therefore be of the same shape as `x`.
  436. The length of `condlist` must correspond to that of `funclist`.
  437. If one extra function is given, i.e. if
  438. ``len(funclist) == len(condlist) + 1``, then that extra function
  439. is the default value, used wherever all conditions are false.
  440. funclist : list of callables, f(x,*args,**kw), or scalars
  441. Each function is evaluated over `x` wherever its corresponding
  442. condition is True. It should take a 1d array as input and give an 1d
  443. array or a scalar value as output. If, instead of a callable,
  444. a scalar is provided then a constant function (``lambda x: scalar``) is
  445. assumed.
  446. args : tuple, optional
  447. Any further arguments given to `piecewise` are passed to the functions
  448. upon execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then
  449. each function is called as ``f(x, 1, 'a')``.
  450. kw : dict, optional
  451. Keyword arguments used in calling `piecewise` are passed to the
  452. functions upon execution, i.e., if called
  453. ``piecewise(..., ..., alpha=1)``, then each function is called as
  454. ``f(x, alpha=1)``.
  455. Returns
  456. -------
  457. out : ndarray
  458. The output is the same shape and type as x and is found by
  459. calling the functions in `funclist` on the appropriate portions of `x`,
  460. as defined by the boolean arrays in `condlist`. Portions not covered
  461. by any condition have a default value of 0.
  462. See Also
  463. --------
  464. choose, select, where
  465. Notes
  466. -----
  467. This is similar to choose or select, except that functions are
  468. evaluated on elements of `x` that satisfy the corresponding condition from
  469. `condlist`.
  470. The result is::
  471. |--
  472. |funclist[0](x[condlist[0]])
  473. out = |funclist[1](x[condlist[1]])
  474. |...
  475. |funclist[n2](x[condlist[n2]])
  476. |--
  477. Examples
  478. --------
  479. Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``.
  480. >>> x = np.linspace(-2.5, 2.5, 6)
  481. >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
  482. array([-1., -1., -1., 1., 1., 1.])
  483. Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for
  484. ``x >= 0``.
  485. >>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
  486. array([ 2.5, 1.5, 0.5, 0.5, 1.5, 2.5])
  487. Apply the same function to a scalar value.
  488. >>> y = -2
  489. >>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x])
  490. array(2)
  491. """
  492. x = asanyarray(x)
  493. n2 = len(funclist)
  494. # undocumented: single condition is promoted to a list of one condition
  495. if isscalar(condlist) or (
  496. not isinstance(condlist[0], (list, ndarray)) and x.ndim != 0):
  497. condlist = [condlist]
  498. condlist = array(condlist, dtype=bool)
  499. n = len(condlist)
  500. if n == n2 - 1: # compute the "otherwise" condition.
  501. condelse = ~np.any(condlist, axis=0, keepdims=True)
  502. condlist = np.concatenate([condlist, condelse], axis=0)
  503. n += 1
  504. elif n != n2:
  505. raise ValueError(
  506. "with {} condition(s), either {} or {} functions are expected"
  507. .format(n, n, n+1)
  508. )
  509. y = zeros(x.shape, x.dtype)
  510. for k in range(n):
  511. item = funclist[k]
  512. if not isinstance(item, collections_abc.Callable):
  513. y[condlist[k]] = item
  514. else:
  515. vals = x[condlist[k]]
  516. if vals.size > 0:
  517. y[condlist[k]] = item(vals, *args, **kw)
  518. return y
  519. def _select_dispatcher(condlist, choicelist, default=None):
  520. for c in condlist:
  521. yield c
  522. for c in choicelist:
  523. yield c
  524. @array_function_dispatch(_select_dispatcher)
  525. def select(condlist, choicelist, default=0):
  526. """
  527. Return an array drawn from elements in choicelist, depending on conditions.
  528. Parameters
  529. ----------
  530. condlist : list of bool ndarrays
  531. The list of conditions which determine from which array in `choicelist`
  532. the output elements are taken. When multiple conditions are satisfied,
  533. the first one encountered in `condlist` is used.
  534. choicelist : list of ndarrays
  535. The list of arrays from which the output elements are taken. It has
  536. to be of the same length as `condlist`.
  537. default : scalar, optional
  538. The element inserted in `output` when all conditions evaluate to False.
  539. Returns
  540. -------
  541. output : ndarray
  542. The output at position m is the m-th element of the array in
  543. `choicelist` where the m-th element of the corresponding array in
  544. `condlist` is True.
  545. See Also
  546. --------
  547. where : Return elements from one of two arrays depending on condition.
  548. take, choose, compress, diag, diagonal
  549. Examples
  550. --------
  551. >>> x = np.arange(10)
  552. >>> condlist = [x<3, x>5]
  553. >>> choicelist = [x, x**2]
  554. >>> np.select(condlist, choicelist)
  555. array([ 0, 1, 2, 0, 0, 0, 36, 49, 64, 81])
  556. """
  557. # Check the size of condlist and choicelist are the same, or abort.
  558. if len(condlist) != len(choicelist):
  559. raise ValueError(
  560. 'list of cases must be same length as list of conditions')
  561. # Now that the dtype is known, handle the deprecated select([], []) case
  562. if len(condlist) == 0:
  563. # 2014-02-24, 1.9
  564. warnings.warn("select with an empty condition list is not possible"
  565. "and will be deprecated",
  566. DeprecationWarning, stacklevel=2)
  567. return np.asarray(default)[()]
  568. choicelist = [np.asarray(choice) for choice in choicelist]
  569. choicelist.append(np.asarray(default))
  570. # need to get the result type before broadcasting for correct scalar
  571. # behaviour
  572. dtype = np.result_type(*choicelist)
  573. # Convert conditions to arrays and broadcast conditions and choices
  574. # as the shape is needed for the result. Doing it separately optimizes
  575. # for example when all choices are scalars.
  576. condlist = np.broadcast_arrays(*condlist)
  577. choicelist = np.broadcast_arrays(*choicelist)
  578. # If cond array is not an ndarray in boolean format or scalar bool, abort.
  579. deprecated_ints = False
  580. for i in range(len(condlist)):
  581. cond = condlist[i]
  582. if cond.dtype.type is not np.bool_:
  583. if np.issubdtype(cond.dtype, np.integer):
  584. # A previous implementation accepted int ndarrays accidentally.
  585. # Supported here deliberately, but deprecated.
  586. condlist[i] = condlist[i].astype(bool)
  587. deprecated_ints = True
  588. else:
  589. raise ValueError(
  590. 'invalid entry {} in condlist: should be boolean ndarray'.format(i))
  591. if deprecated_ints:
  592. # 2014-02-24, 1.9
  593. msg = "select condlists containing integer ndarrays is deprecated " \
  594. "and will be removed in the future. Use `.astype(bool)` to " \
  595. "convert to bools."
  596. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  597. if choicelist[0].ndim == 0:
  598. # This may be common, so avoid the call.
  599. result_shape = condlist[0].shape
  600. else:
  601. result_shape = np.broadcast_arrays(condlist[0], choicelist[0])[0].shape
  602. result = np.full(result_shape, choicelist[-1], dtype)
  603. # Use np.copyto to burn each choicelist array onto result, using the
  604. # corresponding condlist as a boolean mask. This is done in reverse
  605. # order since the first choice should take precedence.
  606. choicelist = choicelist[-2::-1]
  607. condlist = condlist[::-1]
  608. for choice, cond in zip(choicelist, condlist):
  609. np.copyto(result, choice, where=cond)
  610. return result
  611. def _copy_dispatcher(a, order=None):
  612. return (a,)
  613. @array_function_dispatch(_copy_dispatcher)
  614. def copy(a, order='K'):
  615. """
  616. Return an array copy of the given object.
  617. Parameters
  618. ----------
  619. a : array_like
  620. Input data.
  621. order : {'C', 'F', 'A', 'K'}, optional
  622. Controls the memory layout of the copy. 'C' means C-order,
  623. 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
  624. 'C' otherwise. 'K' means match the layout of `a` as closely
  625. as possible. (Note that this function and :meth:`ndarray.copy` are very
  626. similar, but have different default values for their order=
  627. arguments.)
  628. Returns
  629. -------
  630. arr : ndarray
  631. Array interpretation of `a`.
  632. Notes
  633. -----
  634. This is equivalent to:
  635. >>> np.array(a, copy=True) #doctest: +SKIP
  636. Examples
  637. --------
  638. Create an array x, with a reference y and a copy z:
  639. >>> x = np.array([1, 2, 3])
  640. >>> y = x
  641. >>> z = np.copy(x)
  642. Note that, when we modify x, y changes, but not z:
  643. >>> x[0] = 10
  644. >>> x[0] == y[0]
  645. True
  646. >>> x[0] == z[0]
  647. False
  648. """
  649. return array(a, order=order, copy=True)
  650. # Basic operations
  651. def _gradient_dispatcher(f, *varargs, **kwargs):
  652. yield f
  653. for v in varargs:
  654. yield v
  655. @array_function_dispatch(_gradient_dispatcher)
  656. def gradient(f, *varargs, **kwargs):
  657. """
  658. Return the gradient of an N-dimensional array.
  659. The gradient is computed using second order accurate central differences
  660. in the interior points and either first or second order accurate one-sides
  661. (forward or backwards) differences at the boundaries.
  662. The returned gradient hence has the same shape as the input array.
  663. Parameters
  664. ----------
  665. f : array_like
  666. An N-dimensional array containing samples of a scalar function.
  667. varargs : list of scalar or array, optional
  668. Spacing between f values. Default unitary spacing for all dimensions.
  669. Spacing can be specified using:
  670. 1. single scalar to specify a sample distance for all dimensions.
  671. 2. N scalars to specify a constant sample distance for each dimension.
  672. i.e. `dx`, `dy`, `dz`, ...
  673. 3. N arrays to specify the coordinates of the values along each
  674. dimension of F. The length of the array must match the size of
  675. the corresponding dimension
  676. 4. Any combination of N scalars/arrays with the meaning of 2. and 3.
  677. If `axis` is given, the number of varargs must equal the number of axes.
  678. Default: 1.
  679. edge_order : {1, 2}, optional
  680. Gradient is calculated using N-th order accurate differences
  681. at the boundaries. Default: 1.
  682. .. versionadded:: 1.9.1
  683. axis : None or int or tuple of ints, optional
  684. Gradient is calculated only along the given axis or axes
  685. The default (axis = None) is to calculate the gradient for all the axes
  686. of the input array. axis may be negative, in which case it counts from
  687. the last to the first axis.
  688. .. versionadded:: 1.11.0
  689. Returns
  690. -------
  691. gradient : ndarray or list of ndarray
  692. A set of ndarrays (or a single ndarray if there is only one dimension)
  693. corresponding to the derivatives of f with respect to each dimension.
  694. Each derivative has the same shape as f.
  695. Examples
  696. --------
  697. >>> f = np.array([1, 2, 4, 7, 11, 16], dtype=float)
  698. >>> np.gradient(f)
  699. array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ])
  700. >>> np.gradient(f, 2)
  701. array([ 0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ])
  702. Spacing can be also specified with an array that represents the coordinates
  703. of the values F along the dimensions.
  704. For instance a uniform spacing:
  705. >>> x = np.arange(f.size)
  706. >>> np.gradient(f, x)
  707. array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ])
  708. Or a non uniform one:
  709. >>> x = np.array([0., 1., 1.5, 3.5, 4., 6.], dtype=float)
  710. >>> np.gradient(f, x)
  711. array([ 1. , 3. , 3.5, 6.7, 6.9, 2.5])
  712. For two dimensional arrays, the return will be two arrays ordered by
  713. axis. In this example the first array stands for the gradient in
  714. rows and the second one in columns direction:
  715. >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float))
  716. [array([[ 2., 2., -1.],
  717. [ 2., 2., -1.]]), array([[ 1. , 2.5, 4. ],
  718. [ 1. , 1. , 1. ]])]
  719. In this example the spacing is also specified:
  720. uniform for axis=0 and non uniform for axis=1
  721. >>> dx = 2.
  722. >>> y = [1., 1.5, 3.5]
  723. >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), dx, y)
  724. [array([[ 1. , 1. , -0.5],
  725. [ 1. , 1. , -0.5]]), array([[ 2. , 2. , 2. ],
  726. [ 2. , 1.7, 0.5]])]
  727. It is possible to specify how boundaries are treated using `edge_order`
  728. >>> x = np.array([0, 1, 2, 3, 4])
  729. >>> f = x**2
  730. >>> np.gradient(f, edge_order=1)
  731. array([ 1., 2., 4., 6., 7.])
  732. >>> np.gradient(f, edge_order=2)
  733. array([-0., 2., 4., 6., 8.])
  734. The `axis` keyword can be used to specify a subset of axes of which the
  735. gradient is calculated
  736. >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), axis=0)
  737. array([[ 2., 2., -1.],
  738. [ 2., 2., -1.]])
  739. Notes
  740. -----
  741. Assuming that :math:`f\\in C^{3}` (i.e., :math:`f` has at least 3 continuous
  742. derivatives) and let :math:`h_{*}` be a non-homogeneous stepsize, we
  743. minimize the "consistency error" :math:`\\eta_{i}` between the true gradient
  744. and its estimate from a linear combination of the neighboring grid-points:
  745. .. math::
  746. \\eta_{i} = f_{i}^{\\left(1\\right)} -
  747. \\left[ \\alpha f\\left(x_{i}\\right) +
  748. \\beta f\\left(x_{i} + h_{d}\\right) +
  749. \\gamma f\\left(x_{i}-h_{s}\\right)
  750. \\right]
  751. By substituting :math:`f(x_{i} + h_{d})` and :math:`f(x_{i} - h_{s})`
  752. with their Taylor series expansion, this translates into solving
  753. the following the linear system:
  754. .. math::
  755. \\left\\{
  756. \\begin{array}{r}
  757. \\alpha+\\beta+\\gamma=0 \\\\
  758. \\beta h_{d}-\\gamma h_{s}=1 \\\\
  759. \\beta h_{d}^{2}+\\gamma h_{s}^{2}=0
  760. \\end{array}
  761. \\right.
  762. The resulting approximation of :math:`f_{i}^{(1)}` is the following:
  763. .. math::
  764. \\hat f_{i}^{(1)} =
  765. \\frac{
  766. h_{s}^{2}f\\left(x_{i} + h_{d}\\right)
  767. + \\left(h_{d}^{2} - h_{s}^{2}\\right)f\\left(x_{i}\\right)
  768. - h_{d}^{2}f\\left(x_{i}-h_{s}\\right)}
  769. { h_{s}h_{d}\\left(h_{d} + h_{s}\\right)}
  770. + \\mathcal{O}\\left(\\frac{h_{d}h_{s}^{2}
  771. + h_{s}h_{d}^{2}}{h_{d}
  772. + h_{s}}\\right)
  773. It is worth noting that if :math:`h_{s}=h_{d}`
  774. (i.e., data are evenly spaced)
  775. we find the standard second order approximation:
  776. .. math::
  777. \\hat f_{i}^{(1)}=
  778. \\frac{f\\left(x_{i+1}\\right) - f\\left(x_{i-1}\\right)}{2h}
  779. + \\mathcal{O}\\left(h^{2}\\right)
  780. With a similar procedure the forward/backward approximations used for
  781. boundaries can be derived.
  782. References
  783. ----------
  784. .. [1] Quarteroni A., Sacco R., Saleri F. (2007) Numerical Mathematics
  785. (Texts in Applied Mathematics). New York: Springer.
  786. .. [2] Durran D. R. (1999) Numerical Methods for Wave Equations
  787. in Geophysical Fluid Dynamics. New York: Springer.
  788. .. [3] Fornberg B. (1988) Generation of Finite Difference Formulas on
  789. Arbitrarily Spaced Grids,
  790. Mathematics of Computation 51, no. 184 : 699-706.
  791. `PDF <http://www.ams.org/journals/mcom/1988-51-184/
  792. S0025-5718-1988-0935077-0/S0025-5718-1988-0935077-0.pdf>`_.
  793. """
  794. f = np.asanyarray(f)
  795. N = f.ndim # number of dimensions
  796. axes = kwargs.pop('axis', None)
  797. if axes is None:
  798. axes = tuple(range(N))
  799. else:
  800. axes = _nx.normalize_axis_tuple(axes, N)
  801. len_axes = len(axes)
  802. n = len(varargs)
  803. if n == 0:
  804. # no spacing argument - use 1 in all axes
  805. dx = [1.0] * len_axes
  806. elif n == 1 and np.ndim(varargs[0]) == 0:
  807. # single scalar for all axes
  808. dx = varargs * len_axes
  809. elif n == len_axes:
  810. # scalar or 1d array for each axis
  811. dx = list(varargs)
  812. for i, distances in enumerate(dx):
  813. if np.ndim(distances) == 0:
  814. continue
  815. elif np.ndim(distances) != 1:
  816. raise ValueError("distances must be either scalars or 1d")
  817. if len(distances) != f.shape[axes[i]]:
  818. raise ValueError("when 1d, distances must match "
  819. "the length of the corresponding dimension")
  820. diffx = np.diff(distances)
  821. # if distances are constant reduce to the scalar case
  822. # since it brings a consistent speedup
  823. if (diffx == diffx[0]).all():
  824. diffx = diffx[0]
  825. dx[i] = diffx
  826. else:
  827. raise TypeError("invalid number of arguments")
  828. edge_order = kwargs.pop('edge_order', 1)
  829. if kwargs:
  830. raise TypeError('"{}" are not valid keyword arguments.'.format(
  831. '", "'.join(kwargs.keys())))
  832. if edge_order > 2:
  833. raise ValueError("'edge_order' greater than 2 not supported")
  834. # use central differences on interior and one-sided differences on the
  835. # endpoints. This preserves second order-accuracy over the full domain.
  836. outvals = []
  837. # create slice objects --- initially all are [:, :, ..., :]
  838. slice1 = [slice(None)]*N
  839. slice2 = [slice(None)]*N
  840. slice3 = [slice(None)]*N
  841. slice4 = [slice(None)]*N
  842. otype = f.dtype
  843. if otype.type is np.datetime64:
  844. # the timedelta dtype with the same unit information
  845. otype = np.dtype(otype.name.replace('datetime', 'timedelta'))
  846. # view as timedelta to allow addition
  847. f = f.view(otype)
  848. elif otype.type is np.timedelta64:
  849. pass
  850. elif np.issubdtype(otype, np.inexact):
  851. pass
  852. else:
  853. # all other types convert to floating point
  854. otype = np.double
  855. for axis, ax_dx in zip(axes, dx):
  856. if f.shape[axis] < edge_order + 1:
  857. raise ValueError(
  858. "Shape of array too small to calculate a numerical gradient, "
  859. "at least (edge_order + 1) elements are required.")
  860. # result allocation
  861. out = np.empty_like(f, dtype=otype)
  862. # spacing for the current axis
  863. uniform_spacing = np.ndim(ax_dx) == 0
  864. # Numerical differentiation: 2nd order interior
  865. slice1[axis] = slice(1, -1)
  866. slice2[axis] = slice(None, -2)
  867. slice3[axis] = slice(1, -1)
  868. slice4[axis] = slice(2, None)
  869. if uniform_spacing:
  870. out[tuple(slice1)] = (f[tuple(slice4)] - f[tuple(slice2)]) / (2. * ax_dx)
  871. else:
  872. dx1 = ax_dx[0:-1]
  873. dx2 = ax_dx[1:]
  874. a = -(dx2)/(dx1 * (dx1 + dx2))
  875. b = (dx2 - dx1) / (dx1 * dx2)
  876. c = dx1 / (dx2 * (dx1 + dx2))
  877. # fix the shape for broadcasting
  878. shape = np.ones(N, dtype=int)
  879. shape[axis] = -1
  880. a.shape = b.shape = c.shape = shape
  881. # 1D equivalent -- out[1:-1] = a * f[:-2] + b * f[1:-1] + c * f[2:]
  882. out[tuple(slice1)] = a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)]
  883. # Numerical differentiation: 1st order edges
  884. if edge_order == 1:
  885. slice1[axis] = 0
  886. slice2[axis] = 1
  887. slice3[axis] = 0
  888. dx_0 = ax_dx if uniform_spacing else ax_dx[0]
  889. # 1D equivalent -- out[0] = (f[1] - f[0]) / (x[1] - x[0])
  890. out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_0
  891. slice1[axis] = -1
  892. slice2[axis] = -1
  893. slice3[axis] = -2
  894. dx_n = ax_dx if uniform_spacing else ax_dx[-1]
  895. # 1D equivalent -- out[-1] = (f[-1] - f[-2]) / (x[-1] - x[-2])
  896. out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_n
  897. # Numerical differentiation: 2nd order edges
  898. else:
  899. slice1[axis] = 0
  900. slice2[axis] = 0
  901. slice3[axis] = 1
  902. slice4[axis] = 2
  903. if uniform_spacing:
  904. a = -1.5 / ax_dx
  905. b = 2. / ax_dx
  906. c = -0.5 / ax_dx
  907. else:
  908. dx1 = ax_dx[0]
  909. dx2 = ax_dx[1]
  910. a = -(2. * dx1 + dx2)/(dx1 * (dx1 + dx2))
  911. b = (dx1 + dx2) / (dx1 * dx2)
  912. c = - dx1 / (dx2 * (dx1 + dx2))
  913. # 1D equivalent -- out[0] = a * f[0] + b * f[1] + c * f[2]
  914. out[tuple(slice1)] = a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)]
  915. slice1[axis] = -1
  916. slice2[axis] = -3
  917. slice3[axis] = -2
  918. slice4[axis] = -1
  919. if uniform_spacing:
  920. a = 0.5 / ax_dx
  921. b = -2. / ax_dx
  922. c = 1.5 / ax_dx
  923. else:
  924. dx1 = ax_dx[-2]
  925. dx2 = ax_dx[-1]
  926. a = (dx2) / (dx1 * (dx1 + dx2))
  927. b = - (dx2 + dx1) / (dx1 * dx2)
  928. c = (2. * dx2 + dx1) / (dx2 * (dx1 + dx2))
  929. # 1D equivalent -- out[-1] = a * f[-3] + b * f[-2] + c * f[-1]
  930. out[tuple(slice1)] = a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)]
  931. outvals.append(out)
  932. # reset the slice object in this dimension to ":"
  933. slice1[axis] = slice(None)
  934. slice2[axis] = slice(None)
  935. slice3[axis] = slice(None)
  936. slice4[axis] = slice(None)
  937. if len_axes == 1:
  938. return outvals[0]
  939. else:
  940. return outvals
  941. def _diff_dispatcher(a, n=None, axis=None, prepend=None, append=None):
  942. return (a, prepend, append)
  943. @array_function_dispatch(_diff_dispatcher)
  944. def diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue):
  945. """
  946. Calculate the n-th discrete difference along the given axis.
  947. The first difference is given by ``out[n] = a[n+1] - a[n]`` along
  948. the given axis, higher differences are calculated by using `diff`
  949. recursively.
  950. Parameters
  951. ----------
  952. a : array_like
  953. Input array
  954. n : int, optional
  955. The number of times values are differenced. If zero, the input
  956. is returned as-is.
  957. axis : int, optional
  958. The axis along which the difference is taken, default is the
  959. last axis.
  960. prepend, append : array_like, optional
  961. Values to prepend or append to "a" along axis prior to
  962. performing the difference. Scalar values are expanded to
  963. arrays with length 1 in the direction of axis and the shape
  964. of the input array in along all other axes. Otherwise the
  965. dimension and shape must match "a" except along axis.
  966. Returns
  967. -------
  968. diff : ndarray
  969. The n-th differences. The shape of the output is the same as `a`
  970. except along `axis` where the dimension is smaller by `n`. The
  971. type of the output is the same as the type of the difference
  972. between any two elements of `a`. This is the same as the type of
  973. `a` in most cases. A notable exception is `datetime64`, which
  974. results in a `timedelta64` output array.
  975. See Also
  976. --------
  977. gradient, ediff1d, cumsum
  978. Notes
  979. -----
  980. Type is preserved for boolean arrays, so the result will contain
  981. `False` when consecutive elements are the same and `True` when they
  982. differ.
  983. For unsigned integer arrays, the results will also be unsigned. This
  984. should not be surprising, as the result is consistent with
  985. calculating the difference directly:
  986. >>> u8_arr = np.array([1, 0], dtype=np.uint8)
  987. >>> np.diff(u8_arr)
  988. array([255], dtype=uint8)
  989. >>> u8_arr[1,...] - u8_arr[0,...]
  990. array(255, np.uint8)
  991. If this is not desirable, then the array should be cast to a larger
  992. integer type first:
  993. >>> i16_arr = u8_arr.astype(np.int16)
  994. >>> np.diff(i16_arr)
  995. array([-1], dtype=int16)
  996. Examples
  997. --------
  998. >>> x = np.array([1, 2, 4, 7, 0])
  999. >>> np.diff(x)
  1000. array([ 1, 2, 3, -7])
  1001. >>> np.diff(x, n=2)
  1002. array([ 1, 1, -10])
  1003. >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]])
  1004. >>> np.diff(x)
  1005. array([[2, 3, 4],
  1006. [5, 1, 2]])
  1007. >>> np.diff(x, axis=0)
  1008. array([[-1, 2, 0, -2]])
  1009. >>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
  1010. >>> np.diff(x)
  1011. array([1, 1], dtype='timedelta64[D]')
  1012. """
  1013. if n == 0:
  1014. return a
  1015. if n < 0:
  1016. raise ValueError(
  1017. "order must be non-negative but got " + repr(n))
  1018. a = asanyarray(a)
  1019. nd = a.ndim
  1020. axis = normalize_axis_index(axis, nd)
  1021. combined = []
  1022. if prepend is not np._NoValue:
  1023. prepend = np.asanyarray(prepend)
  1024. if prepend.ndim == 0:
  1025. shape = list(a.shape)
  1026. shape[axis] = 1
  1027. prepend = np.broadcast_to(prepend, tuple(shape))
  1028. combined.append(prepend)
  1029. combined.append(a)
  1030. if append is not np._NoValue:
  1031. append = np.asanyarray(append)
  1032. if append.ndim == 0:
  1033. shape = list(a.shape)
  1034. shape[axis] = 1
  1035. append = np.broadcast_to(append, tuple(shape))
  1036. combined.append(append)
  1037. if len(combined) > 1:
  1038. a = np.concatenate(combined, axis)
  1039. slice1 = [slice(None)] * nd
  1040. slice2 = [slice(None)] * nd
  1041. slice1[axis] = slice(1, None)
  1042. slice2[axis] = slice(None, -1)
  1043. slice1 = tuple(slice1)
  1044. slice2 = tuple(slice2)
  1045. op = not_equal if a.dtype == np.bool_ else subtract
  1046. for _ in range(n):
  1047. a = op(a[slice1], a[slice2])
  1048. return a
  1049. def _interp_dispatcher(x, xp, fp, left=None, right=None, period=None):
  1050. return (x, xp, fp)
  1051. @array_function_dispatch(_interp_dispatcher)
  1052. def interp(x, xp, fp, left=None, right=None, period=None):
  1053. """
  1054. One-dimensional linear interpolation.
  1055. Returns the one-dimensional piecewise linear interpolant to a function
  1056. with given discrete data points (`xp`, `fp`), evaluated at `x`.
  1057. Parameters
  1058. ----------
  1059. x : array_like
  1060. The x-coordinates at which to evaluate the interpolated values.
  1061. xp : 1-D sequence of floats
  1062. The x-coordinates of the data points, must be increasing if argument
  1063. `period` is not specified. Otherwise, `xp` is internally sorted after
  1064. normalizing the periodic boundaries with ``xp = xp % period``.
  1065. fp : 1-D sequence of float or complex
  1066. The y-coordinates of the data points, same length as `xp`.
  1067. left : optional float or complex corresponding to fp
  1068. Value to return for `x < xp[0]`, default is `fp[0]`.
  1069. right : optional float or complex corresponding to fp
  1070. Value to return for `x > xp[-1]`, default is `fp[-1]`.
  1071. period : None or float, optional
  1072. A period for the x-coordinates. This parameter allows the proper
  1073. interpolation of angular x-coordinates. Parameters `left` and `right`
  1074. are ignored if `period` is specified.
  1075. .. versionadded:: 1.10.0
  1076. Returns
  1077. -------
  1078. y : float or complex (corresponding to fp) or ndarray
  1079. The interpolated values, same shape as `x`.
  1080. Raises
  1081. ------
  1082. ValueError
  1083. If `xp` and `fp` have different length
  1084. If `xp` or `fp` are not 1-D sequences
  1085. If `period == 0`
  1086. Notes
  1087. -----
  1088. Does not check that the x-coordinate sequence `xp` is increasing.
  1089. If `xp` is not increasing, the results are nonsense.
  1090. A simple check for increasing is::
  1091. np.all(np.diff(xp) > 0)
  1092. Examples
  1093. --------
  1094. >>> xp = [1, 2, 3]
  1095. >>> fp = [3, 2, 0]
  1096. >>> np.interp(2.5, xp, fp)
  1097. 1.0
  1098. >>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
  1099. array([ 3. , 3. , 2.5 , 0.56, 0. ])
  1100. >>> UNDEF = -99.0
  1101. >>> np.interp(3.14, xp, fp, right=UNDEF)
  1102. -99.0
  1103. Plot an interpolant to the sine function:
  1104. >>> x = np.linspace(0, 2*np.pi, 10)
  1105. >>> y = np.sin(x)
  1106. >>> xvals = np.linspace(0, 2*np.pi, 50)
  1107. >>> yinterp = np.interp(xvals, x, y)
  1108. >>> import matplotlib.pyplot as plt
  1109. >>> plt.plot(x, y, 'o')
  1110. [<matplotlib.lines.Line2D object at 0x...>]
  1111. >>> plt.plot(xvals, yinterp, '-x')
  1112. [<matplotlib.lines.Line2D object at 0x...>]
  1113. >>> plt.show()
  1114. Interpolation with periodic x-coordinates:
  1115. >>> x = [-180, -170, -185, 185, -10, -5, 0, 365]
  1116. >>> xp = [190, -190, 350, -350]
  1117. >>> fp = [5, 10, 3, 4]
  1118. >>> np.interp(x, xp, fp, period=360)
  1119. array([7.5, 5., 8.75, 6.25, 3., 3.25, 3.5, 3.75])
  1120. Complex interpolation:
  1121. >>> x = [1.5, 4.0]
  1122. >>> xp = [2,3,5]
  1123. >>> fp = [1.0j, 0, 2+3j]
  1124. >>> np.interp(x, xp, fp)
  1125. array([ 0.+1.j , 1.+1.5j])
  1126. """
  1127. fp = np.asarray(fp)
  1128. if np.iscomplexobj(fp):
  1129. interp_func = compiled_interp_complex
  1130. input_dtype = np.complex128
  1131. else:
  1132. interp_func = compiled_interp
  1133. input_dtype = np.float64
  1134. if period is not None:
  1135. if period == 0:
  1136. raise ValueError("period must be a non-zero value")
  1137. period = abs(period)
  1138. left = None
  1139. right = None
  1140. x = np.asarray(x, dtype=np.float64)
  1141. xp = np.asarray(xp, dtype=np.float64)
  1142. fp = np.asarray(fp, dtype=input_dtype)
  1143. if xp.ndim != 1 or fp.ndim != 1:
  1144. raise ValueError("Data points must be 1-D sequences")
  1145. if xp.shape[0] != fp.shape[0]:
  1146. raise ValueError("fp and xp are not of the same length")
  1147. # normalizing periodic boundaries
  1148. x = x % period
  1149. xp = xp % period
  1150. asort_xp = np.argsort(xp)
  1151. xp = xp[asort_xp]
  1152. fp = fp[asort_xp]
  1153. xp = np.concatenate((xp[-1:]-period, xp, xp[0:1]+period))
  1154. fp = np.concatenate((fp[-1:], fp, fp[0:1]))
  1155. return interp_func(x, xp, fp, left, right)
  1156. def _angle_dispatcher(z, deg=None):
  1157. return (z,)
  1158. @array_function_dispatch(_angle_dispatcher)
  1159. def angle(z, deg=False):
  1160. """
  1161. Return the angle of the complex argument.
  1162. Parameters
  1163. ----------
  1164. z : array_like
  1165. A complex number or sequence of complex numbers.
  1166. deg : bool, optional
  1167. Return angle in degrees if True, radians if False (default).
  1168. Returns
  1169. -------
  1170. angle : ndarray or scalar
  1171. The counterclockwise angle from the positive real axis on
  1172. the complex plane, with dtype as numpy.float64.
  1173. ..versionchanged:: 1.16.0
  1174. This function works on subclasses of ndarray like `ma.array`.
  1175. See Also
  1176. --------
  1177. arctan2
  1178. absolute
  1179. Examples
  1180. --------
  1181. >>> np.angle([1.0, 1.0j, 1+1j]) # in radians
  1182. array([ 0. , 1.57079633, 0.78539816])
  1183. >>> np.angle(1+1j, deg=True) # in degrees
  1184. 45.0
  1185. """
  1186. z = asanyarray(z)
  1187. if issubclass(z.dtype.type, _nx.complexfloating):
  1188. zimag = z.imag
  1189. zreal = z.real
  1190. else:
  1191. zimag = 0
  1192. zreal = z
  1193. a = arctan2(zimag, zreal)
  1194. if deg:
  1195. a *= 180/pi
  1196. return a
  1197. def _unwrap_dispatcher(p, discont=None, axis=None):
  1198. return (p,)
  1199. @array_function_dispatch(_unwrap_dispatcher)
  1200. def unwrap(p, discont=pi, axis=-1):
  1201. """
  1202. Unwrap by changing deltas between values to 2*pi complement.
  1203. Unwrap radian phase `p` by changing absolute jumps greater than
  1204. `discont` to their 2*pi complement along the given axis.
  1205. Parameters
  1206. ----------
  1207. p : array_like
  1208. Input array.
  1209. discont : float, optional
  1210. Maximum discontinuity between values, default is ``pi``.
  1211. axis : int, optional
  1212. Axis along which unwrap will operate, default is the last axis.
  1213. Returns
  1214. -------
  1215. out : ndarray
  1216. Output array.
  1217. See Also
  1218. --------
  1219. rad2deg, deg2rad
  1220. Notes
  1221. -----
  1222. If the discontinuity in `p` is smaller than ``pi``, but larger than
  1223. `discont`, no unwrapping is done because taking the 2*pi complement
  1224. would only make the discontinuity larger.
  1225. Examples
  1226. --------
  1227. >>> phase = np.linspace(0, np.pi, num=5)
  1228. >>> phase[3:] += np.pi
  1229. >>> phase
  1230. array([ 0. , 0.78539816, 1.57079633, 5.49778714, 6.28318531])
  1231. >>> np.unwrap(phase)
  1232. array([ 0. , 0.78539816, 1.57079633, -0.78539816, 0. ])
  1233. """
  1234. p = asarray(p)
  1235. nd = p.ndim
  1236. dd = diff(p, axis=axis)
  1237. slice1 = [slice(None, None)]*nd # full slices
  1238. slice1[axis] = slice(1, None)
  1239. slice1 = tuple(slice1)
  1240. ddmod = mod(dd + pi, 2*pi) - pi
  1241. _nx.copyto(ddmod, pi, where=(ddmod == -pi) & (dd > 0))
  1242. ph_correct = ddmod - dd
  1243. _nx.copyto(ph_correct, 0, where=abs(dd) < discont)
  1244. up = array(p, copy=True, dtype='d')
  1245. up[slice1] = p[slice1] + ph_correct.cumsum(axis)
  1246. return up
  1247. def _sort_complex(a):
  1248. return (a,)
  1249. @array_function_dispatch(_sort_complex)
  1250. def sort_complex(a):
  1251. """
  1252. Sort a complex array using the real part first, then the imaginary part.
  1253. Parameters
  1254. ----------
  1255. a : array_like
  1256. Input array
  1257. Returns
  1258. -------
  1259. out : complex ndarray
  1260. Always returns a sorted complex array.
  1261. Examples
  1262. --------
  1263. >>> np.sort_complex([5, 3, 6, 2, 1])
  1264. array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j])
  1265. >>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j])
  1266. array([ 1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j])
  1267. """
  1268. b = array(a, copy=True)
  1269. b.sort()
  1270. if not issubclass(b.dtype.type, _nx.complexfloating):
  1271. if b.dtype.char in 'bhBH':
  1272. return b.astype('F')
  1273. elif b.dtype.char == 'g':
  1274. return b.astype('G')
  1275. else:
  1276. return b.astype('D')
  1277. else:
  1278. return b
  1279. def _trim_zeros(filt, trim=None):
  1280. return (filt,)
  1281. @array_function_dispatch(_trim_zeros)
  1282. def trim_zeros(filt, trim='fb'):
  1283. """
  1284. Trim the leading and/or trailing zeros from a 1-D array or sequence.
  1285. Parameters
  1286. ----------
  1287. filt : 1-D array or sequence
  1288. Input array.
  1289. trim : str, optional
  1290. A string with 'f' representing trim from front and 'b' to trim from
  1291. back. Default is 'fb', trim zeros from both front and back of the
  1292. array.
  1293. Returns
  1294. -------
  1295. trimmed : 1-D array or sequence
  1296. The result of trimming the input. The input data type is preserved.
  1297. Examples
  1298. --------
  1299. >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0))
  1300. >>> np.trim_zeros(a)
  1301. array([1, 2, 3, 0, 2, 1])
  1302. >>> np.trim_zeros(a, 'b')
  1303. array([0, 0, 0, 1, 2, 3, 0, 2, 1])
  1304. The input data type is preserved, list/tuple in means list/tuple out.
  1305. >>> np.trim_zeros([0, 1, 2, 0])
  1306. [1, 2]
  1307. """
  1308. first = 0
  1309. trim = trim.upper()
  1310. if 'F' in trim:
  1311. for i in filt:
  1312. if i != 0.:
  1313. break
  1314. else:
  1315. first = first + 1
  1316. last = len(filt)
  1317. if 'B' in trim:
  1318. for i in filt[::-1]:
  1319. if i != 0.:
  1320. break
  1321. else:
  1322. last = last - 1
  1323. return filt[first:last]
  1324. def _extract_dispatcher(condition, arr):
  1325. return (condition, arr)
  1326. @array_function_dispatch(_extract_dispatcher)
  1327. def extract(condition, arr):
  1328. """
  1329. Return the elements of an array that satisfy some condition.
  1330. This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If
  1331. `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``.
  1332. Note that `place` does the exact opposite of `extract`.
  1333. Parameters
  1334. ----------
  1335. condition : array_like
  1336. An array whose nonzero or True entries indicate the elements of `arr`
  1337. to extract.
  1338. arr : array_like
  1339. Input array of the same size as `condition`.
  1340. Returns
  1341. -------
  1342. extract : ndarray
  1343. Rank 1 array of values from `arr` where `condition` is True.
  1344. See Also
  1345. --------
  1346. take, put, copyto, compress, place
  1347. Examples
  1348. --------
  1349. >>> arr = np.arange(12).reshape((3, 4))
  1350. >>> arr
  1351. array([[ 0, 1, 2, 3],
  1352. [ 4, 5, 6, 7],
  1353. [ 8, 9, 10, 11]])
  1354. >>> condition = np.mod(arr, 3)==0
  1355. >>> condition
  1356. array([[ True, False, False, True],
  1357. [False, False, True, False],
  1358. [False, True, False, False]])
  1359. >>> np.extract(condition, arr)
  1360. array([0, 3, 6, 9])
  1361. If `condition` is boolean:
  1362. >>> arr[condition]
  1363. array([0, 3, 6, 9])
  1364. """
  1365. return _nx.take(ravel(arr), nonzero(ravel(condition))[0])
  1366. def _place_dispatcher(arr, mask, vals):
  1367. return (arr, mask, vals)
  1368. @array_function_dispatch(_place_dispatcher)
  1369. def place(arr, mask, vals):
  1370. """
  1371. Change elements of an array based on conditional and input values.
  1372. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
  1373. `place` uses the first N elements of `vals`, where N is the number of
  1374. True values in `mask`, while `copyto` uses the elements where `mask`
  1375. is True.
  1376. Note that `extract` does the exact opposite of `place`.
  1377. Parameters
  1378. ----------
  1379. arr : ndarray
  1380. Array to put data into.
  1381. mask : array_like
  1382. Boolean mask array. Must have the same size as `a`.
  1383. vals : 1-D sequence
  1384. Values to put into `a`. Only the first N elements are used, where
  1385. N is the number of True values in `mask`. If `vals` is smaller
  1386. than N, it will be repeated, and if elements of `a` are to be masked,
  1387. this sequence must be non-empty.
  1388. See Also
  1389. --------
  1390. copyto, put, take, extract
  1391. Examples
  1392. --------
  1393. >>> arr = np.arange(6).reshape(2, 3)
  1394. >>> np.place(arr, arr>2, [44, 55])
  1395. >>> arr
  1396. array([[ 0, 1, 2],
  1397. [44, 55, 44]])
  1398. """
  1399. if not isinstance(arr, np.ndarray):
  1400. raise TypeError("argument 1 must be numpy.ndarray, "
  1401. "not {name}".format(name=type(arr).__name__))
  1402. return _insert(arr, mask, vals)
  1403. def disp(mesg, device=None, linefeed=True):
  1404. """
  1405. Display a message on a device.
  1406. Parameters
  1407. ----------
  1408. mesg : str
  1409. Message to display.
  1410. device : object
  1411. Device to write message. If None, defaults to ``sys.stdout`` which is
  1412. very similar to ``print``. `device` needs to have ``write()`` and
  1413. ``flush()`` methods.
  1414. linefeed : bool, optional
  1415. Option whether to print a line feed or not. Defaults to True.
  1416. Raises
  1417. ------
  1418. AttributeError
  1419. If `device` does not have a ``write()`` or ``flush()`` method.
  1420. Examples
  1421. --------
  1422. Besides ``sys.stdout``, a file-like object can also be used as it has
  1423. both required methods:
  1424. >>> from io import StringIO
  1425. >>> buf = StringIO()
  1426. >>> np.disp(u'"Display" in a file', device=buf)
  1427. >>> buf.getvalue()
  1428. '"Display" in a file\\n'
  1429. """
  1430. if device is None:
  1431. device = sys.stdout
  1432. if linefeed:
  1433. device.write('%s\n' % mesg)
  1434. else:
  1435. device.write('%s' % mesg)
  1436. device.flush()
  1437. return
  1438. # See https://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html
  1439. _DIMENSION_NAME = r'\w+'
  1440. _CORE_DIMENSION_LIST = '(?:{0:}(?:,{0:})*)?'.format(_DIMENSION_NAME)
  1441. _ARGUMENT = r'\({}\)'.format(_CORE_DIMENSION_LIST)
  1442. _ARGUMENT_LIST = '{0:}(?:,{0:})*'.format(_ARGUMENT)
  1443. _SIGNATURE = '^{0:}->{0:}$'.format(_ARGUMENT_LIST)
  1444. def _parse_gufunc_signature(signature):
  1445. """
  1446. Parse string signatures for a generalized universal function.
  1447. Arguments
  1448. ---------
  1449. signature : string
  1450. Generalized universal function signature, e.g., ``(m,n),(n,p)->(m,p)``
  1451. for ``np.matmul``.
  1452. Returns
  1453. -------
  1454. Tuple of input and output core dimensions parsed from the signature, each
  1455. of the form List[Tuple[str, ...]].
  1456. """
  1457. if not re.match(_SIGNATURE, signature):
  1458. raise ValueError(
  1459. 'not a valid gufunc signature: {}'.format(signature))
  1460. return tuple([tuple(re.findall(_DIMENSION_NAME, arg))
  1461. for arg in re.findall(_ARGUMENT, arg_list)]
  1462. for arg_list in signature.split('->'))
  1463. def _update_dim_sizes(dim_sizes, arg, core_dims):
  1464. """
  1465. Incrementally check and update core dimension sizes for a single argument.
  1466. Arguments
  1467. ---------
  1468. dim_sizes : Dict[str, int]
  1469. Sizes of existing core dimensions. Will be updated in-place.
  1470. arg : ndarray
  1471. Argument to examine.
  1472. core_dims : Tuple[str, ...]
  1473. Core dimensions for this argument.
  1474. """
  1475. if not core_dims:
  1476. return
  1477. num_core_dims = len(core_dims)
  1478. if arg.ndim < num_core_dims:
  1479. raise ValueError(
  1480. '%d-dimensional argument does not have enough '
  1481. 'dimensions for all core dimensions %r'
  1482. % (arg.ndim, core_dims))
  1483. core_shape = arg.shape[-num_core_dims:]
  1484. for dim, size in zip(core_dims, core_shape):
  1485. if dim in dim_sizes:
  1486. if size != dim_sizes[dim]:
  1487. raise ValueError(
  1488. 'inconsistent size for core dimension %r: %r vs %r'
  1489. % (dim, size, dim_sizes[dim]))
  1490. else:
  1491. dim_sizes[dim] = size
  1492. def _parse_input_dimensions(args, input_core_dims):
  1493. """
  1494. Parse broadcast and core dimensions for vectorize with a signature.
  1495. Arguments
  1496. ---------
  1497. args : Tuple[ndarray, ...]
  1498. Tuple of input arguments to examine.
  1499. input_core_dims : List[Tuple[str, ...]]
  1500. List of core dimensions corresponding to each input.
  1501. Returns
  1502. -------
  1503. broadcast_shape : Tuple[int, ...]
  1504. Common shape to broadcast all non-core dimensions to.
  1505. dim_sizes : Dict[str, int]
  1506. Common sizes for named core dimensions.
  1507. """
  1508. broadcast_args = []
  1509. dim_sizes = {}
  1510. for arg, core_dims in zip(args, input_core_dims):
  1511. _update_dim_sizes(dim_sizes, arg, core_dims)
  1512. ndim = arg.ndim - len(core_dims)
  1513. dummy_array = np.lib.stride_tricks.as_strided(0, arg.shape[:ndim])
  1514. broadcast_args.append(dummy_array)
  1515. broadcast_shape = np.lib.stride_tricks._broadcast_shape(*broadcast_args)
  1516. return broadcast_shape, dim_sizes
  1517. def _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims):
  1518. """Helper for calculating broadcast shapes with core dimensions."""
  1519. return [broadcast_shape + tuple(dim_sizes[dim] for dim in core_dims)
  1520. for core_dims in list_of_core_dims]
  1521. def _create_arrays(broadcast_shape, dim_sizes, list_of_core_dims, dtypes):
  1522. """Helper for creating output arrays in vectorize."""
  1523. shapes = _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims)
  1524. arrays = tuple(np.empty(shape, dtype=dtype)
  1525. for shape, dtype in zip(shapes, dtypes))
  1526. return arrays
  1527. @set_module('numpy')
  1528. class vectorize(object):
  1529. """
  1530. vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False,
  1531. signature=None)
  1532. Generalized function class.
  1533. Define a vectorized function which takes a nested sequence of objects or
  1534. numpy arrays as inputs and returns a single numpy array or a tuple of numpy
  1535. arrays. The vectorized function evaluates `pyfunc` over successive tuples
  1536. of the input arrays like the python map function, except it uses the
  1537. broadcasting rules of numpy.
  1538. The data type of the output of `vectorized` is determined by calling
  1539. the function with the first element of the input. This can be avoided
  1540. by specifying the `otypes` argument.
  1541. Parameters
  1542. ----------
  1543. pyfunc : callable
  1544. A python function or method.
  1545. otypes : str or list of dtypes, optional
  1546. The output data type. It must be specified as either a string of
  1547. typecode characters or a list of data type specifiers. There should
  1548. be one data type specifier for each output.
  1549. doc : str, optional
  1550. The docstring for the function. If `None`, the docstring will be the
  1551. ``pyfunc.__doc__``.
  1552. excluded : set, optional
  1553. Set of strings or integers representing the positional or keyword
  1554. arguments for which the function will not be vectorized. These will be
  1555. passed directly to `pyfunc` unmodified.
  1556. .. versionadded:: 1.7.0
  1557. cache : bool, optional
  1558. If `True`, then cache the first function call that determines the number
  1559. of outputs if `otypes` is not provided.
  1560. .. versionadded:: 1.7.0
  1561. signature : string, optional
  1562. Generalized universal function signature, e.g., ``(m,n),(n)->(m)`` for
  1563. vectorized matrix-vector multiplication. If provided, ``pyfunc`` will
  1564. be called with (and expected to return) arrays with shapes given by the
  1565. size of corresponding core dimensions. By default, ``pyfunc`` is
  1566. assumed to take scalars as input and output.
  1567. .. versionadded:: 1.12.0
  1568. Returns
  1569. -------
  1570. vectorized : callable
  1571. Vectorized function.
  1572. Examples
  1573. --------
  1574. >>> def myfunc(a, b):
  1575. ... "Return a-b if a>b, otherwise return a+b"
  1576. ... if a > b:
  1577. ... return a - b
  1578. ... else:
  1579. ... return a + b
  1580. >>> vfunc = np.vectorize(myfunc)
  1581. >>> vfunc([1, 2, 3, 4], 2)
  1582. array([3, 4, 1, 2])
  1583. The docstring is taken from the input function to `vectorize` unless it
  1584. is specified:
  1585. >>> vfunc.__doc__
  1586. 'Return a-b if a>b, otherwise return a+b'
  1587. >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`')
  1588. >>> vfunc.__doc__
  1589. 'Vectorized `myfunc`'
  1590. The output type is determined by evaluating the first element of the input,
  1591. unless it is specified:
  1592. >>> out = vfunc([1, 2, 3, 4], 2)
  1593. >>> type(out[0])
  1594. <type 'numpy.int32'>
  1595. >>> vfunc = np.vectorize(myfunc, otypes=[float])
  1596. >>> out = vfunc([1, 2, 3, 4], 2)
  1597. >>> type(out[0])
  1598. <type 'numpy.float64'>
  1599. The `excluded` argument can be used to prevent vectorizing over certain
  1600. arguments. This can be useful for array-like arguments of a fixed length
  1601. such as the coefficients for a polynomial as in `polyval`:
  1602. >>> def mypolyval(p, x):
  1603. ... _p = list(p)
  1604. ... res = _p.pop(0)
  1605. ... while _p:
  1606. ... res = res*x + _p.pop(0)
  1607. ... return res
  1608. >>> vpolyval = np.vectorize(mypolyval, excluded=['p'])
  1609. >>> vpolyval(p=[1, 2, 3], x=[0, 1])
  1610. array([3, 6])
  1611. Positional arguments may also be excluded by specifying their position:
  1612. >>> vpolyval.excluded.add(0)
  1613. >>> vpolyval([1, 2, 3], x=[0, 1])
  1614. array([3, 6])
  1615. The `signature` argument allows for vectorizing functions that act on
  1616. non-scalar arrays of fixed length. For example, you can use it for a
  1617. vectorized calculation of Pearson correlation coefficient and its p-value:
  1618. >>> import scipy.stats
  1619. >>> pearsonr = np.vectorize(scipy.stats.pearsonr,
  1620. ... signature='(n),(n)->(),()')
  1621. >>> pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]])
  1622. (array([ 1., -1.]), array([ 0., 0.]))
  1623. Or for a vectorized convolution:
  1624. >>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)')
  1625. >>> convolve(np.eye(4), [1, 2, 1])
  1626. array([[ 1., 2., 1., 0., 0., 0.],
  1627. [ 0., 1., 2., 1., 0., 0.],
  1628. [ 0., 0., 1., 2., 1., 0.],
  1629. [ 0., 0., 0., 1., 2., 1.]])
  1630. See Also
  1631. --------
  1632. frompyfunc : Takes an arbitrary Python function and returns a ufunc
  1633. Notes
  1634. -----
  1635. The `vectorize` function is provided primarily for convenience, not for
  1636. performance. The implementation is essentially a for loop.
  1637. If `otypes` is not specified, then a call to the function with the
  1638. first argument will be used to determine the number of outputs. The
  1639. results of this call will be cached if `cache` is `True` to prevent
  1640. calling the function twice. However, to implement the cache, the
  1641. original function must be wrapped which will slow down subsequent
  1642. calls, so only do this if your function is expensive.
  1643. The new keyword argument interface and `excluded` argument support
  1644. further degrades performance.
  1645. References
  1646. ----------
  1647. .. [1] NumPy Reference, section `Generalized Universal Function API
  1648. <https://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html>`_.
  1649. """
  1650. def __init__(self, pyfunc, otypes=None, doc=None, excluded=None,
  1651. cache=False, signature=None):
  1652. self.pyfunc = pyfunc
  1653. self.cache = cache
  1654. self.signature = signature
  1655. self._ufunc = None # Caching to improve default performance
  1656. if doc is None:
  1657. self.__doc__ = pyfunc.__doc__
  1658. else:
  1659. self.__doc__ = doc
  1660. if isinstance(otypes, str):
  1661. for char in otypes:
  1662. if char not in typecodes['All']:
  1663. raise ValueError("Invalid otype specified: %s" % (char,))
  1664. elif iterable(otypes):
  1665. otypes = ''.join([_nx.dtype(x).char for x in otypes])
  1666. elif otypes is not None:
  1667. raise ValueError("Invalid otype specification")
  1668. self.otypes = otypes
  1669. # Excluded variable support
  1670. if excluded is None:
  1671. excluded = set()
  1672. self.excluded = set(excluded)
  1673. if signature is not None:
  1674. self._in_and_out_core_dims = _parse_gufunc_signature(signature)
  1675. else:
  1676. self._in_and_out_core_dims = None
  1677. def __call__(self, *args, **kwargs):
  1678. """
  1679. Return arrays with the results of `pyfunc` broadcast (vectorized) over
  1680. `args` and `kwargs` not in `excluded`.
  1681. """
  1682. excluded = self.excluded
  1683. if not kwargs and not excluded:
  1684. func = self.pyfunc
  1685. vargs = args
  1686. else:
  1687. # The wrapper accepts only positional arguments: we use `names` and
  1688. # `inds` to mutate `the_args` and `kwargs` to pass to the original
  1689. # function.
  1690. nargs = len(args)
  1691. names = [_n for _n in kwargs if _n not in excluded]
  1692. inds = [_i for _i in range(nargs) if _i not in excluded]
  1693. the_args = list(args)
  1694. def func(*vargs):
  1695. for _n, _i in enumerate(inds):
  1696. the_args[_i] = vargs[_n]
  1697. kwargs.update(zip(names, vargs[len(inds):]))
  1698. return self.pyfunc(*the_args, **kwargs)
  1699. vargs = [args[_i] for _i in inds]
  1700. vargs.extend([kwargs[_n] for _n in names])
  1701. return self._vectorize_call(func=func, args=vargs)
  1702. def _get_ufunc_and_otypes(self, func, args):
  1703. """Return (ufunc, otypes)."""
  1704. # frompyfunc will fail if args is empty
  1705. if not args:
  1706. raise ValueError('args can not be empty')
  1707. if self.otypes is not None:
  1708. otypes = self.otypes
  1709. nout = len(otypes)
  1710. # Note logic here: We only *use* self._ufunc if func is self.pyfunc
  1711. # even though we set self._ufunc regardless.
  1712. if func is self.pyfunc and self._ufunc is not None:
  1713. ufunc = self._ufunc
  1714. else:
  1715. ufunc = self._ufunc = frompyfunc(func, len(args), nout)
  1716. else:
  1717. # Get number of outputs and output types by calling the function on
  1718. # the first entries of args. We also cache the result to prevent
  1719. # the subsequent call when the ufunc is evaluated.
  1720. # Assumes that ufunc first evaluates the 0th elements in the input
  1721. # arrays (the input values are not checked to ensure this)
  1722. args = [asarray(arg) for arg in args]
  1723. if builtins.any(arg.size == 0 for arg in args):
  1724. raise ValueError('cannot call `vectorize` on size 0 inputs '
  1725. 'unless `otypes` is set')
  1726. inputs = [arg.flat[0] for arg in args]
  1727. outputs = func(*inputs)
  1728. # Performance note: profiling indicates that -- for simple
  1729. # functions at least -- this wrapping can almost double the
  1730. # execution time.
  1731. # Hence we make it optional.
  1732. if self.cache:
  1733. _cache = [outputs]
  1734. def _func(*vargs):
  1735. if _cache:
  1736. return _cache.pop()
  1737. else:
  1738. return func(*vargs)
  1739. else:
  1740. _func = func
  1741. if isinstance(outputs, tuple):
  1742. nout = len(outputs)
  1743. else:
  1744. nout = 1
  1745. outputs = (outputs,)
  1746. otypes = ''.join([asarray(outputs[_k]).dtype.char
  1747. for _k in range(nout)])
  1748. # Performance note: profiling indicates that creating the ufunc is
  1749. # not a significant cost compared with wrapping so it seems not
  1750. # worth trying to cache this.
  1751. ufunc = frompyfunc(_func, len(args), nout)
  1752. return ufunc, otypes
  1753. def _vectorize_call(self, func, args):
  1754. """Vectorized call to `func` over positional `args`."""
  1755. if self.signature is not None:
  1756. res = self._vectorize_call_with_signature(func, args)
  1757. elif not args:
  1758. res = func()
  1759. else:
  1760. ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
  1761. # Convert args to object arrays first
  1762. inputs = [array(a, copy=False, subok=True, dtype=object)
  1763. for a in args]
  1764. outputs = ufunc(*inputs)
  1765. if ufunc.nout == 1:
  1766. res = array(outputs, copy=False, subok=True, dtype=otypes[0])
  1767. else:
  1768. res = tuple([array(x, copy=False, subok=True, dtype=t)
  1769. for x, t in zip(outputs, otypes)])
  1770. return res
  1771. def _vectorize_call_with_signature(self, func, args):
  1772. """Vectorized call over positional arguments with a signature."""
  1773. input_core_dims, output_core_dims = self._in_and_out_core_dims
  1774. if len(args) != len(input_core_dims):
  1775. raise TypeError('wrong number of positional arguments: '
  1776. 'expected %r, got %r'
  1777. % (len(input_core_dims), len(args)))
  1778. args = tuple(asanyarray(arg) for arg in args)
  1779. broadcast_shape, dim_sizes = _parse_input_dimensions(
  1780. args, input_core_dims)
  1781. input_shapes = _calculate_shapes(broadcast_shape, dim_sizes,
  1782. input_core_dims)
  1783. args = [np.broadcast_to(arg, shape, subok=True)
  1784. for arg, shape in zip(args, input_shapes)]
  1785. outputs = None
  1786. otypes = self.otypes
  1787. nout = len(output_core_dims)
  1788. for index in np.ndindex(*broadcast_shape):
  1789. results = func(*(arg[index] for arg in args))
  1790. n_results = len(results) if isinstance(results, tuple) else 1
  1791. if nout != n_results:
  1792. raise ValueError(
  1793. 'wrong number of outputs from pyfunc: expected %r, got %r'
  1794. % (nout, n_results))
  1795. if nout == 1:
  1796. results = (results,)
  1797. if outputs is None:
  1798. for result, core_dims in zip(results, output_core_dims):
  1799. _update_dim_sizes(dim_sizes, result, core_dims)
  1800. if otypes is None:
  1801. otypes = [asarray(result).dtype for result in results]
  1802. outputs = _create_arrays(broadcast_shape, dim_sizes,
  1803. output_core_dims, otypes)
  1804. for output, result in zip(outputs, results):
  1805. output[index] = result
  1806. if outputs is None:
  1807. # did not call the function even once
  1808. if otypes is None:
  1809. raise ValueError('cannot call `vectorize` on size 0 inputs '
  1810. 'unless `otypes` is set')
  1811. if builtins.any(dim not in dim_sizes
  1812. for dims in output_core_dims
  1813. for dim in dims):
  1814. raise ValueError('cannot call `vectorize` with a signature '
  1815. 'including new output dimensions on size 0 '
  1816. 'inputs')
  1817. outputs = _create_arrays(broadcast_shape, dim_sizes,
  1818. output_core_dims, otypes)
  1819. return outputs[0] if nout == 1 else outputs
  1820. def _cov_dispatcher(m, y=None, rowvar=None, bias=None, ddof=None,
  1821. fweights=None, aweights=None):
  1822. return (m, y, fweights, aweights)
  1823. @array_function_dispatch(_cov_dispatcher)
  1824. def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,
  1825. aweights=None):
  1826. """
  1827. Estimate a covariance matrix, given data and weights.
  1828. Covariance indicates the level to which two variables vary together.
  1829. If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
  1830. then the covariance matrix element :math:`C_{ij}` is the covariance of
  1831. :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
  1832. of :math:`x_i`.
  1833. See the notes for an outline of the algorithm.
  1834. Parameters
  1835. ----------
  1836. m : array_like
  1837. A 1-D or 2-D array containing multiple variables and observations.
  1838. Each row of `m` represents a variable, and each column a single
  1839. observation of all those variables. Also see `rowvar` below.
  1840. y : array_like, optional
  1841. An additional set of variables and observations. `y` has the same form
  1842. as that of `m`.
  1843. rowvar : bool, optional
  1844. If `rowvar` is True (default), then each row represents a
  1845. variable, with observations in the columns. Otherwise, the relationship
  1846. is transposed: each column represents a variable, while the rows
  1847. contain observations.
  1848. bias : bool, optional
  1849. Default normalization (False) is by ``(N - 1)``, where ``N`` is the
  1850. number of observations given (unbiased estimate). If `bias` is True,
  1851. then normalization is by ``N``. These values can be overridden by using
  1852. the keyword ``ddof`` in numpy versions >= 1.5.
  1853. ddof : int, optional
  1854. If not ``None`` the default value implied by `bias` is overridden.
  1855. Note that ``ddof=1`` will return the unbiased estimate, even if both
  1856. `fweights` and `aweights` are specified, and ``ddof=0`` will return
  1857. the simple average. See the notes for the details. The default value
  1858. is ``None``.
  1859. .. versionadded:: 1.5
  1860. fweights : array_like, int, optional
  1861. 1-D array of integer frequency weights; the number of times each
  1862. observation vector should be repeated.
  1863. .. versionadded:: 1.10
  1864. aweights : array_like, optional
  1865. 1-D array of observation vector weights. These relative weights are
  1866. typically large for observations considered "important" and smaller for
  1867. observations considered less "important". If ``ddof=0`` the array of
  1868. weights can be used to assign probabilities to observation vectors.
  1869. .. versionadded:: 1.10
  1870. Returns
  1871. -------
  1872. out : ndarray
  1873. The covariance matrix of the variables.
  1874. See Also
  1875. --------
  1876. corrcoef : Normalized covariance matrix
  1877. Notes
  1878. -----
  1879. Assume that the observations are in the columns of the observation
  1880. array `m` and let ``f = fweights`` and ``a = aweights`` for brevity. The
  1881. steps to compute the weighted covariance are as follows::
  1882. >>> w = f * a
  1883. >>> v1 = np.sum(w)
  1884. >>> v2 = np.sum(w * a)
  1885. >>> m -= np.sum(m * w, axis=1, keepdims=True) / v1
  1886. >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)
  1887. Note that when ``a == 1``, the normalization factor
  1888. ``v1 / (v1**2 - ddof * v2)`` goes over to ``1 / (np.sum(f) - ddof)``
  1889. as it should.
  1890. Examples
  1891. --------
  1892. Consider two variables, :math:`x_0` and :math:`x_1`, which
  1893. correlate perfectly, but in opposite directions:
  1894. >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
  1895. >>> x
  1896. array([[0, 1, 2],
  1897. [2, 1, 0]])
  1898. Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
  1899. matrix shows this clearly:
  1900. >>> np.cov(x)
  1901. array([[ 1., -1.],
  1902. [-1., 1.]])
  1903. Note that element :math:`C_{0,1}`, which shows the correlation between
  1904. :math:`x_0` and :math:`x_1`, is negative.
  1905. Further, note how `x` and `y` are combined:
  1906. >>> x = [-2.1, -1, 4.3]
  1907. >>> y = [3, 1.1, 0.12]
  1908. >>> X = np.stack((x, y), axis=0)
  1909. >>> print(np.cov(X))
  1910. [[ 11.71 -4.286 ]
  1911. [ -4.286 2.14413333]]
  1912. >>> print(np.cov(x, y))
  1913. [[ 11.71 -4.286 ]
  1914. [ -4.286 2.14413333]]
  1915. >>> print(np.cov(x))
  1916. 11.71
  1917. """
  1918. # Check inputs
  1919. if ddof is not None and ddof != int(ddof):
  1920. raise ValueError(
  1921. "ddof must be integer")
  1922. # Handles complex arrays too
  1923. m = np.asarray(m)
  1924. if m.ndim > 2:
  1925. raise ValueError("m has more than 2 dimensions")
  1926. if y is None:
  1927. dtype = np.result_type(m, np.float64)
  1928. else:
  1929. y = np.asarray(y)
  1930. if y.ndim > 2:
  1931. raise ValueError("y has more than 2 dimensions")
  1932. dtype = np.result_type(m, y, np.float64)
  1933. X = array(m, ndmin=2, dtype=dtype)
  1934. if not rowvar and X.shape[0] != 1:
  1935. X = X.T
  1936. if X.shape[0] == 0:
  1937. return np.array([]).reshape(0, 0)
  1938. if y is not None:
  1939. y = array(y, copy=False, ndmin=2, dtype=dtype)
  1940. if not rowvar and y.shape[0] != 1:
  1941. y = y.T
  1942. X = np.concatenate((X, y), axis=0)
  1943. if ddof is None:
  1944. if bias == 0:
  1945. ddof = 1
  1946. else:
  1947. ddof = 0
  1948. # Get the product of frequencies and weights
  1949. w = None
  1950. if fweights is not None:
  1951. fweights = np.asarray(fweights, dtype=float)
  1952. if not np.all(fweights == np.around(fweights)):
  1953. raise TypeError(
  1954. "fweights must be integer")
  1955. if fweights.ndim > 1:
  1956. raise RuntimeError(
  1957. "cannot handle multidimensional fweights")
  1958. if fweights.shape[0] != X.shape[1]:
  1959. raise RuntimeError(
  1960. "incompatible numbers of samples and fweights")
  1961. if any(fweights < 0):
  1962. raise ValueError(
  1963. "fweights cannot be negative")
  1964. w = fweights
  1965. if aweights is not None:
  1966. aweights = np.asarray(aweights, dtype=float)
  1967. if aweights.ndim > 1:
  1968. raise RuntimeError(
  1969. "cannot handle multidimensional aweights")
  1970. if aweights.shape[0] != X.shape[1]:
  1971. raise RuntimeError(
  1972. "incompatible numbers of samples and aweights")
  1973. if any(aweights < 0):
  1974. raise ValueError(
  1975. "aweights cannot be negative")
  1976. if w is None:
  1977. w = aweights
  1978. else:
  1979. w *= aweights
  1980. avg, w_sum = average(X, axis=1, weights=w, returned=True)
  1981. w_sum = w_sum[0]
  1982. # Determine the normalization
  1983. if w is None:
  1984. fact = X.shape[1] - ddof
  1985. elif ddof == 0:
  1986. fact = w_sum
  1987. elif aweights is None:
  1988. fact = w_sum - ddof
  1989. else:
  1990. fact = w_sum - ddof*sum(w*aweights)/w_sum
  1991. if fact <= 0:
  1992. warnings.warn("Degrees of freedom <= 0 for slice",
  1993. RuntimeWarning, stacklevel=2)
  1994. fact = 0.0
  1995. X -= avg[:, None]
  1996. if w is None:
  1997. X_T = X.T
  1998. else:
  1999. X_T = (X*w).T
  2000. c = dot(X, X_T.conj())
  2001. c *= np.true_divide(1, fact)
  2002. return c.squeeze()
  2003. def _corrcoef_dispatcher(x, y=None, rowvar=None, bias=None, ddof=None):
  2004. return (x, y)
  2005. @array_function_dispatch(_corrcoef_dispatcher)
  2006. def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue):
  2007. """
  2008. Return Pearson product-moment correlation coefficients.
  2009. Please refer to the documentation for `cov` for more detail. The
  2010. relationship between the correlation coefficient matrix, `R`, and the
  2011. covariance matrix, `C`, is
  2012. .. math:: R_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } }
  2013. The values of `R` are between -1 and 1, inclusive.
  2014. Parameters
  2015. ----------
  2016. x : array_like
  2017. A 1-D or 2-D array containing multiple variables and observations.
  2018. Each row of `x` represents a variable, and each column a single
  2019. observation of all those variables. Also see `rowvar` below.
  2020. y : array_like, optional
  2021. An additional set of variables and observations. `y` has the same
  2022. shape as `x`.
  2023. rowvar : bool, optional
  2024. If `rowvar` is True (default), then each row represents a
  2025. variable, with observations in the columns. Otherwise, the relationship
  2026. is transposed: each column represents a variable, while the rows
  2027. contain observations.
  2028. bias : _NoValue, optional
  2029. Has no effect, do not use.
  2030. .. deprecated:: 1.10.0
  2031. ddof : _NoValue, optional
  2032. Has no effect, do not use.
  2033. .. deprecated:: 1.10.0
  2034. Returns
  2035. -------
  2036. R : ndarray
  2037. The correlation coefficient matrix of the variables.
  2038. See Also
  2039. --------
  2040. cov : Covariance matrix
  2041. Notes
  2042. -----
  2043. Due to floating point rounding the resulting array may not be Hermitian,
  2044. the diagonal elements may not be 1, and the elements may not satisfy the
  2045. inequality abs(a) <= 1. The real and imaginary parts are clipped to the
  2046. interval [-1, 1] in an attempt to improve on that situation but is not
  2047. much help in the complex case.
  2048. This function accepts but discards arguments `bias` and `ddof`. This is
  2049. for backwards compatibility with previous versions of this function. These
  2050. arguments had no effect on the return values of the function and can be
  2051. safely ignored in this and previous versions of numpy.
  2052. """
  2053. if bias is not np._NoValue or ddof is not np._NoValue:
  2054. # 2015-03-15, 1.10
  2055. warnings.warn('bias and ddof have no effect and are deprecated',
  2056. DeprecationWarning, stacklevel=2)
  2057. c = cov(x, y, rowvar)
  2058. try:
  2059. d = diag(c)
  2060. except ValueError:
  2061. # scalar covariance
  2062. # nan if incorrect value (nan, inf, 0), 1 otherwise
  2063. return c / c
  2064. stddev = sqrt(d.real)
  2065. c /= stddev[:, None]
  2066. c /= stddev[None, :]
  2067. # Clip real and imaginary parts to [-1, 1]. This does not guarantee
  2068. # abs(a[i,j]) <= 1 for complex arrays, but is the best we can do without
  2069. # excessive work.
  2070. np.clip(c.real, -1, 1, out=c.real)
  2071. if np.iscomplexobj(c):
  2072. np.clip(c.imag, -1, 1, out=c.imag)
  2073. return c
  2074. @set_module('numpy')
  2075. def blackman(M):
  2076. """
  2077. Return the Blackman window.
  2078. The Blackman window is a taper formed by using the first three
  2079. terms of a summation of cosines. It was designed to have close to the
  2080. minimal leakage possible. It is close to optimal, only slightly worse
  2081. than a Kaiser window.
  2082. Parameters
  2083. ----------
  2084. M : int
  2085. Number of points in the output window. If zero or less, an empty
  2086. array is returned.
  2087. Returns
  2088. -------
  2089. out : ndarray
  2090. The window, with the maximum value normalized to one (the value one
  2091. appears only if the number of samples is odd).
  2092. See Also
  2093. --------
  2094. bartlett, hamming, hanning, kaiser
  2095. Notes
  2096. -----
  2097. The Blackman window is defined as
  2098. .. math:: w(n) = 0.42 - 0.5 \\cos(2\\pi n/M) + 0.08 \\cos(4\\pi n/M)
  2099. Most references to the Blackman window come from the signal processing
  2100. literature, where it is used as one of many windowing functions for
  2101. smoothing values. It is also known as an apodization (which means
  2102. "removing the foot", i.e. smoothing discontinuities at the beginning
  2103. and end of the sampled signal) or tapering function. It is known as a
  2104. "near optimal" tapering function, almost as good (by some measures)
  2105. as the kaiser window.
  2106. References
  2107. ----------
  2108. Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra,
  2109. Dover Publications, New York.
  2110. Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
  2111. Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
  2112. Examples
  2113. --------
  2114. >>> import matplotlib.pyplot as plt
  2115. >>> np.blackman(12)
  2116. array([ -1.38777878e-17, 3.26064346e-02, 1.59903635e-01,
  2117. 4.14397981e-01, 7.36045180e-01, 9.67046769e-01,
  2118. 9.67046769e-01, 7.36045180e-01, 4.14397981e-01,
  2119. 1.59903635e-01, 3.26064346e-02, -1.38777878e-17])
  2120. Plot the window and the frequency response:
  2121. >>> from numpy.fft import fft, fftshift
  2122. >>> window = np.blackman(51)
  2123. >>> plt.plot(window)
  2124. [<matplotlib.lines.Line2D object at 0x...>]
  2125. >>> plt.title("Blackman window")
  2126. <matplotlib.text.Text object at 0x...>
  2127. >>> plt.ylabel("Amplitude")
  2128. <matplotlib.text.Text object at 0x...>
  2129. >>> plt.xlabel("Sample")
  2130. <matplotlib.text.Text object at 0x...>
  2131. >>> plt.show()
  2132. >>> plt.figure()
  2133. <matplotlib.figure.Figure object at 0x...>
  2134. >>> A = fft(window, 2048) / 25.5
  2135. >>> mag = np.abs(fftshift(A))
  2136. >>> freq = np.linspace(-0.5, 0.5, len(A))
  2137. >>> response = 20 * np.log10(mag)
  2138. >>> response = np.clip(response, -100, 100)
  2139. >>> plt.plot(freq, response)
  2140. [<matplotlib.lines.Line2D object at 0x...>]
  2141. >>> plt.title("Frequency response of Blackman window")
  2142. <matplotlib.text.Text object at 0x...>
  2143. >>> plt.ylabel("Magnitude [dB]")
  2144. <matplotlib.text.Text object at 0x...>
  2145. >>> plt.xlabel("Normalized frequency [cycles per sample]")
  2146. <matplotlib.text.Text object at 0x...>
  2147. >>> plt.axis('tight')
  2148. (-0.5, 0.5, -100.0, ...)
  2149. >>> plt.show()
  2150. """
  2151. if M < 1:
  2152. return array([])
  2153. if M == 1:
  2154. return ones(1, float)
  2155. n = arange(0, M)
  2156. return 0.42 - 0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1))
  2157. @set_module('numpy')
  2158. def bartlett(M):
  2159. """
  2160. Return the Bartlett window.
  2161. The Bartlett window is very similar to a triangular window, except
  2162. that the end points are at zero. It is often used in signal
  2163. processing for tapering a signal, without generating too much
  2164. ripple in the frequency domain.
  2165. Parameters
  2166. ----------
  2167. M : int
  2168. Number of points in the output window. If zero or less, an
  2169. empty array is returned.
  2170. Returns
  2171. -------
  2172. out : array
  2173. The triangular window, with the maximum value normalized to one
  2174. (the value one appears only if the number of samples is odd), with
  2175. the first and last samples equal to zero.
  2176. See Also
  2177. --------
  2178. blackman, hamming, hanning, kaiser
  2179. Notes
  2180. -----
  2181. The Bartlett window is defined as
  2182. .. math:: w(n) = \\frac{2}{M-1} \\left(
  2183. \\frac{M-1}{2} - \\left|n - \\frac{M-1}{2}\\right|
  2184. \\right)
  2185. Most references to the Bartlett window come from the signal
  2186. processing literature, where it is used as one of many windowing
  2187. functions for smoothing values. Note that convolution with this
  2188. window produces linear interpolation. It is also known as an
  2189. apodization (which means"removing the foot", i.e. smoothing
  2190. discontinuities at the beginning and end of the sampled signal) or
  2191. tapering function. The fourier transform of the Bartlett is the product
  2192. of two sinc functions.
  2193. Note the excellent discussion in Kanasewich.
  2194. References
  2195. ----------
  2196. .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
  2197. Biometrika 37, 1-16, 1950.
  2198. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
  2199. The University of Alberta Press, 1975, pp. 109-110.
  2200. .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal
  2201. Processing", Prentice-Hall, 1999, pp. 468-471.
  2202. .. [4] Wikipedia, "Window function",
  2203. https://en.wikipedia.org/wiki/Window_function
  2204. .. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
  2205. "Numerical Recipes", Cambridge University Press, 1986, page 429.
  2206. Examples
  2207. --------
  2208. >>> np.bartlett(12)
  2209. array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273,
  2210. 0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636,
  2211. 0.18181818, 0. ])
  2212. Plot the window and its frequency response (requires SciPy and matplotlib):
  2213. >>> from numpy.fft import fft, fftshift
  2214. >>> window = np.bartlett(51)
  2215. >>> plt.plot(window)
  2216. [<matplotlib.lines.Line2D object at 0x...>]
  2217. >>> plt.title("Bartlett window")
  2218. <matplotlib.text.Text object at 0x...>
  2219. >>> plt.ylabel("Amplitude")
  2220. <matplotlib.text.Text object at 0x...>
  2221. >>> plt.xlabel("Sample")
  2222. <matplotlib.text.Text object at 0x...>
  2223. >>> plt.show()
  2224. >>> plt.figure()
  2225. <matplotlib.figure.Figure object at 0x...>
  2226. >>> A = fft(window, 2048) / 25.5
  2227. >>> mag = np.abs(fftshift(A))
  2228. >>> freq = np.linspace(-0.5, 0.5, len(A))
  2229. >>> response = 20 * np.log10(mag)
  2230. >>> response = np.clip(response, -100, 100)
  2231. >>> plt.plot(freq, response)
  2232. [<matplotlib.lines.Line2D object at 0x...>]
  2233. >>> plt.title("Frequency response of Bartlett window")
  2234. <matplotlib.text.Text object at 0x...>
  2235. >>> plt.ylabel("Magnitude [dB]")
  2236. <matplotlib.text.Text object at 0x...>
  2237. >>> plt.xlabel("Normalized frequency [cycles per sample]")
  2238. <matplotlib.text.Text object at 0x...>
  2239. >>> plt.axis('tight')
  2240. (-0.5, 0.5, -100.0, ...)
  2241. >>> plt.show()
  2242. """
  2243. if M < 1:
  2244. return array([])
  2245. if M == 1:
  2246. return ones(1, float)
  2247. n = arange(0, M)
  2248. return where(less_equal(n, (M-1)/2.0), 2.0*n/(M-1), 2.0 - 2.0*n/(M-1))
  2249. @set_module('numpy')
  2250. def hanning(M):
  2251. """
  2252. Return the Hanning window.
  2253. The Hanning window is a taper formed by using a weighted cosine.
  2254. Parameters
  2255. ----------
  2256. M : int
  2257. Number of points in the output window. If zero or less, an
  2258. empty array is returned.
  2259. Returns
  2260. -------
  2261. out : ndarray, shape(M,)
  2262. The window, with the maximum value normalized to one (the value
  2263. one appears only if `M` is odd).
  2264. See Also
  2265. --------
  2266. bartlett, blackman, hamming, kaiser
  2267. Notes
  2268. -----
  2269. The Hanning window is defined as
  2270. .. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
  2271. \\qquad 0 \\leq n \\leq M-1
  2272. The Hanning was named for Julius von Hann, an Austrian meteorologist.
  2273. It is also known as the Cosine Bell. Some authors prefer that it be
  2274. called a Hann window, to help avoid confusion with the very similar
  2275. Hamming window.
  2276. Most references to the Hanning window come from the signal processing
  2277. literature, where it is used as one of many windowing functions for
  2278. smoothing values. It is also known as an apodization (which means
  2279. "removing the foot", i.e. smoothing discontinuities at the beginning
  2280. and end of the sampled signal) or tapering function.
  2281. References
  2282. ----------
  2283. .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
  2284. spectra, Dover Publications, New York.
  2285. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
  2286. The University of Alberta Press, 1975, pp. 106-108.
  2287. .. [3] Wikipedia, "Window function",
  2288. https://en.wikipedia.org/wiki/Window_function
  2289. .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
  2290. "Numerical Recipes", Cambridge University Press, 1986, page 425.
  2291. Examples
  2292. --------
  2293. >>> np.hanning(12)
  2294. array([ 0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037,
  2295. 0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249,
  2296. 0.07937323, 0. ])
  2297. Plot the window and its frequency response:
  2298. >>> import matplotlib.pyplot as plt
  2299. >>> from numpy.fft import fft, fftshift
  2300. >>> window = np.hanning(51)
  2301. >>> plt.plot(window)
  2302. [<matplotlib.lines.Line2D object at 0x...>]
  2303. >>> plt.title("Hann window")
  2304. <matplotlib.text.Text object at 0x...>
  2305. >>> plt.ylabel("Amplitude")
  2306. <matplotlib.text.Text object at 0x...>
  2307. >>> plt.xlabel("Sample")
  2308. <matplotlib.text.Text object at 0x...>
  2309. >>> plt.show()
  2310. >>> plt.figure()
  2311. <matplotlib.figure.Figure object at 0x...>
  2312. >>> A = fft(window, 2048) / 25.5
  2313. >>> mag = np.abs(fftshift(A))
  2314. >>> freq = np.linspace(-0.5, 0.5, len(A))
  2315. >>> response = 20 * np.log10(mag)
  2316. >>> response = np.clip(response, -100, 100)
  2317. >>> plt.plot(freq, response)
  2318. [<matplotlib.lines.Line2D object at 0x...>]
  2319. >>> plt.title("Frequency response of the Hann window")
  2320. <matplotlib.text.Text object at 0x...>
  2321. >>> plt.ylabel("Magnitude [dB]")
  2322. <matplotlib.text.Text object at 0x...>
  2323. >>> plt.xlabel("Normalized frequency [cycles per sample]")
  2324. <matplotlib.text.Text object at 0x...>
  2325. >>> plt.axis('tight')
  2326. (-0.5, 0.5, -100.0, ...)
  2327. >>> plt.show()
  2328. """
  2329. if M < 1:
  2330. return array([])
  2331. if M == 1:
  2332. return ones(1, float)
  2333. n = arange(0, M)
  2334. return 0.5 - 0.5*cos(2.0*pi*n/(M-1))
  2335. @set_module('numpy')
  2336. def hamming(M):
  2337. """
  2338. Return the Hamming window.
  2339. The Hamming window is a taper formed by using a weighted cosine.
  2340. Parameters
  2341. ----------
  2342. M : int
  2343. Number of points in the output window. If zero or less, an
  2344. empty array is returned.
  2345. Returns
  2346. -------
  2347. out : ndarray
  2348. The window, with the maximum value normalized to one (the value
  2349. one appears only if the number of samples is odd).
  2350. See Also
  2351. --------
  2352. bartlett, blackman, hanning, kaiser
  2353. Notes
  2354. -----
  2355. The Hamming window is defined as
  2356. .. math:: w(n) = 0.54 - 0.46cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
  2357. \\qquad 0 \\leq n \\leq M-1
  2358. The Hamming was named for R. W. Hamming, an associate of J. W. Tukey
  2359. and is described in Blackman and Tukey. It was recommended for
  2360. smoothing the truncated autocovariance function in the time domain.
  2361. Most references to the Hamming window come from the signal processing
  2362. literature, where it is used as one of many windowing functions for
  2363. smoothing values. It is also known as an apodization (which means
  2364. "removing the foot", i.e. smoothing discontinuities at the beginning
  2365. and end of the sampled signal) or tapering function.
  2366. References
  2367. ----------
  2368. .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
  2369. spectra, Dover Publications, New York.
  2370. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
  2371. University of Alberta Press, 1975, pp. 109-110.
  2372. .. [3] Wikipedia, "Window function",
  2373. https://en.wikipedia.org/wiki/Window_function
  2374. .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
  2375. "Numerical Recipes", Cambridge University Press, 1986, page 425.
  2376. Examples
  2377. --------
  2378. >>> np.hamming(12)
  2379. array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594,
  2380. 0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909,
  2381. 0.15302337, 0.08 ])
  2382. Plot the window and the frequency response:
  2383. >>> import matplotlib.pyplot as plt
  2384. >>> from numpy.fft import fft, fftshift
  2385. >>> window = np.hamming(51)
  2386. >>> plt.plot(window)
  2387. [<matplotlib.lines.Line2D object at 0x...>]
  2388. >>> plt.title("Hamming window")
  2389. <matplotlib.text.Text object at 0x...>
  2390. >>> plt.ylabel("Amplitude")
  2391. <matplotlib.text.Text object at 0x...>
  2392. >>> plt.xlabel("Sample")
  2393. <matplotlib.text.Text object at 0x...>
  2394. >>> plt.show()
  2395. >>> plt.figure()
  2396. <matplotlib.figure.Figure object at 0x...>
  2397. >>> A = fft(window, 2048) / 25.5
  2398. >>> mag = np.abs(fftshift(A))
  2399. >>> freq = np.linspace(-0.5, 0.5, len(A))
  2400. >>> response = 20 * np.log10(mag)
  2401. >>> response = np.clip(response, -100, 100)
  2402. >>> plt.plot(freq, response)
  2403. [<matplotlib.lines.Line2D object at 0x...>]
  2404. >>> plt.title("Frequency response of Hamming window")
  2405. <matplotlib.text.Text object at 0x...>
  2406. >>> plt.ylabel("Magnitude [dB]")
  2407. <matplotlib.text.Text object at 0x...>
  2408. >>> plt.xlabel("Normalized frequency [cycles per sample]")
  2409. <matplotlib.text.Text object at 0x...>
  2410. >>> plt.axis('tight')
  2411. (-0.5, 0.5, -100.0, ...)
  2412. >>> plt.show()
  2413. """
  2414. if M < 1:
  2415. return array([])
  2416. if M == 1:
  2417. return ones(1, float)
  2418. n = arange(0, M)
  2419. return 0.54 - 0.46*cos(2.0*pi*n/(M-1))
  2420. ## Code from cephes for i0
  2421. _i0A = [
  2422. -4.41534164647933937950E-18,
  2423. 3.33079451882223809783E-17,
  2424. -2.43127984654795469359E-16,
  2425. 1.71539128555513303061E-15,
  2426. -1.16853328779934516808E-14,
  2427. 7.67618549860493561688E-14,
  2428. -4.85644678311192946090E-13,
  2429. 2.95505266312963983461E-12,
  2430. -1.72682629144155570723E-11,
  2431. 9.67580903537323691224E-11,
  2432. -5.18979560163526290666E-10,
  2433. 2.65982372468238665035E-9,
  2434. -1.30002500998624804212E-8,
  2435. 6.04699502254191894932E-8,
  2436. -2.67079385394061173391E-7,
  2437. 1.11738753912010371815E-6,
  2438. -4.41673835845875056359E-6,
  2439. 1.64484480707288970893E-5,
  2440. -5.75419501008210370398E-5,
  2441. 1.88502885095841655729E-4,
  2442. -5.76375574538582365885E-4,
  2443. 1.63947561694133579842E-3,
  2444. -4.32430999505057594430E-3,
  2445. 1.05464603945949983183E-2,
  2446. -2.37374148058994688156E-2,
  2447. 4.93052842396707084878E-2,
  2448. -9.49010970480476444210E-2,
  2449. 1.71620901522208775349E-1,
  2450. -3.04682672343198398683E-1,
  2451. 6.76795274409476084995E-1
  2452. ]
  2453. _i0B = [
  2454. -7.23318048787475395456E-18,
  2455. -4.83050448594418207126E-18,
  2456. 4.46562142029675999901E-17,
  2457. 3.46122286769746109310E-17,
  2458. -2.82762398051658348494E-16,
  2459. -3.42548561967721913462E-16,
  2460. 1.77256013305652638360E-15,
  2461. 3.81168066935262242075E-15,
  2462. -9.55484669882830764870E-15,
  2463. -4.15056934728722208663E-14,
  2464. 1.54008621752140982691E-14,
  2465. 3.85277838274214270114E-13,
  2466. 7.18012445138366623367E-13,
  2467. -1.79417853150680611778E-12,
  2468. -1.32158118404477131188E-11,
  2469. -3.14991652796324136454E-11,
  2470. 1.18891471078464383424E-11,
  2471. 4.94060238822496958910E-10,
  2472. 3.39623202570838634515E-9,
  2473. 2.26666899049817806459E-8,
  2474. 2.04891858946906374183E-7,
  2475. 2.89137052083475648297E-6,
  2476. 6.88975834691682398426E-5,
  2477. 3.36911647825569408990E-3,
  2478. 8.04490411014108831608E-1
  2479. ]
  2480. def _chbevl(x, vals):
  2481. b0 = vals[0]
  2482. b1 = 0.0
  2483. for i in range(1, len(vals)):
  2484. b2 = b1
  2485. b1 = b0
  2486. b0 = x*b1 - b2 + vals[i]
  2487. return 0.5*(b0 - b2)
  2488. def _i0_1(x):
  2489. return exp(x) * _chbevl(x/2.0-2, _i0A)
  2490. def _i0_2(x):
  2491. return exp(x) * _chbevl(32.0/x - 2.0, _i0B) / sqrt(x)
  2492. def _i0_dispatcher(x):
  2493. return (x,)
  2494. @array_function_dispatch(_i0_dispatcher)
  2495. def i0(x):
  2496. """
  2497. Modified Bessel function of the first kind, order 0.
  2498. Usually denoted :math:`I_0`. This function does broadcast, but will *not*
  2499. "up-cast" int dtype arguments unless accompanied by at least one float or
  2500. complex dtype argument (see Raises below).
  2501. Parameters
  2502. ----------
  2503. x : array_like, dtype float or complex
  2504. Argument of the Bessel function.
  2505. Returns
  2506. -------
  2507. out : ndarray, shape = x.shape, dtype = x.dtype
  2508. The modified Bessel function evaluated at each of the elements of `x`.
  2509. Raises
  2510. ------
  2511. TypeError: array cannot be safely cast to required type
  2512. If argument consists exclusively of int dtypes.
  2513. See Also
  2514. --------
  2515. scipy.special.iv, scipy.special.ive
  2516. Notes
  2517. -----
  2518. We use the algorithm published by Clenshaw [1]_ and referenced by
  2519. Abramowitz and Stegun [2]_, for which the function domain is
  2520. partitioned into the two intervals [0,8] and (8,inf), and Chebyshev
  2521. polynomial expansions are employed in each interval. Relative error on
  2522. the domain [0,30] using IEEE arithmetic is documented [3]_ as having a
  2523. peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000).
  2524. References
  2525. ----------
  2526. .. [1] C. W. Clenshaw, "Chebyshev series for mathematical functions", in
  2527. *National Physical Laboratory Mathematical Tables*, vol. 5, London:
  2528. Her Majesty's Stationery Office, 1962.
  2529. .. [2] M. Abramowitz and I. A. Stegun, *Handbook of Mathematical
  2530. Functions*, 10th printing, New York: Dover, 1964, pp. 379.
  2531. http://www.math.sfu.ca/~cbm/aands/page_379.htm
  2532. .. [3] http://kobesearch.cpan.org/htdocs/Math-Cephes/Math/Cephes.html
  2533. Examples
  2534. --------
  2535. >>> np.i0([0.])
  2536. array(1.0)
  2537. >>> np.i0([0., 1. + 2j])
  2538. array([ 1.00000000+0.j , 0.18785373+0.64616944j])
  2539. """
  2540. x = atleast_1d(x).copy()
  2541. y = empty_like(x)
  2542. ind = (x < 0)
  2543. x[ind] = -x[ind]
  2544. ind = (x <= 8.0)
  2545. y[ind] = _i0_1(x[ind])
  2546. ind2 = ~ind
  2547. y[ind2] = _i0_2(x[ind2])
  2548. return y.squeeze()
  2549. ## End of cephes code for i0
  2550. @set_module('numpy')
  2551. def kaiser(M, beta):
  2552. """
  2553. Return the Kaiser window.
  2554. The Kaiser window is a taper formed by using a Bessel function.
  2555. Parameters
  2556. ----------
  2557. M : int
  2558. Number of points in the output window. If zero or less, an
  2559. empty array is returned.
  2560. beta : float
  2561. Shape parameter for window.
  2562. Returns
  2563. -------
  2564. out : array
  2565. The window, with the maximum value normalized to one (the value
  2566. one appears only if the number of samples is odd).
  2567. See Also
  2568. --------
  2569. bartlett, blackman, hamming, hanning
  2570. Notes
  2571. -----
  2572. The Kaiser window is defined as
  2573. .. math:: w(n) = I_0\\left( \\beta \\sqrt{1-\\frac{4n^2}{(M-1)^2}}
  2574. \\right)/I_0(\\beta)
  2575. with
  2576. .. math:: \\quad -\\frac{M-1}{2} \\leq n \\leq \\frac{M-1}{2},
  2577. where :math:`I_0` is the modified zeroth-order Bessel function.
  2578. The Kaiser was named for Jim Kaiser, who discovered a simple
  2579. approximation to the DPSS window based on Bessel functions. The Kaiser
  2580. window is a very good approximation to the Digital Prolate Spheroidal
  2581. Sequence, or Slepian window, which is the transform which maximizes the
  2582. energy in the main lobe of the window relative to total energy.
  2583. The Kaiser can approximate many other windows by varying the beta
  2584. parameter.
  2585. ==== =======================
  2586. beta Window shape
  2587. ==== =======================
  2588. 0 Rectangular
  2589. 5 Similar to a Hamming
  2590. 6 Similar to a Hanning
  2591. 8.6 Similar to a Blackman
  2592. ==== =======================
  2593. A beta value of 14 is probably a good starting point. Note that as beta
  2594. gets large, the window narrows, and so the number of samples needs to be
  2595. large enough to sample the increasingly narrow spike, otherwise NaNs will
  2596. get returned.
  2597. Most references to the Kaiser window come from the signal processing
  2598. literature, where it is used as one of many windowing functions for
  2599. smoothing values. It is also known as an apodization (which means
  2600. "removing the foot", i.e. smoothing discontinuities at the beginning
  2601. and end of the sampled signal) or tapering function.
  2602. References
  2603. ----------
  2604. .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by
  2605. digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285.
  2606. John Wiley and Sons, New York, (1966).
  2607. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
  2608. University of Alberta Press, 1975, pp. 177-178.
  2609. .. [3] Wikipedia, "Window function",
  2610. https://en.wikipedia.org/wiki/Window_function
  2611. Examples
  2612. --------
  2613. >>> import matplotlib.pyplot as plt
  2614. >>> np.kaiser(12, 14)
  2615. array([ 7.72686684e-06, 3.46009194e-03, 4.65200189e-02,
  2616. 2.29737120e-01, 5.99885316e-01, 9.45674898e-01,
  2617. 9.45674898e-01, 5.99885316e-01, 2.29737120e-01,
  2618. 4.65200189e-02, 3.46009194e-03, 7.72686684e-06])
  2619. Plot the window and the frequency response:
  2620. >>> from numpy.fft import fft, fftshift
  2621. >>> window = np.kaiser(51, 14)
  2622. >>> plt.plot(window)
  2623. [<matplotlib.lines.Line2D object at 0x...>]
  2624. >>> plt.title("Kaiser window")
  2625. <matplotlib.text.Text object at 0x...>
  2626. >>> plt.ylabel("Amplitude")
  2627. <matplotlib.text.Text object at 0x...>
  2628. >>> plt.xlabel("Sample")
  2629. <matplotlib.text.Text object at 0x...>
  2630. >>> plt.show()
  2631. >>> plt.figure()
  2632. <matplotlib.figure.Figure object at 0x...>
  2633. >>> A = fft(window, 2048) / 25.5
  2634. >>> mag = np.abs(fftshift(A))
  2635. >>> freq = np.linspace(-0.5, 0.5, len(A))
  2636. >>> response = 20 * np.log10(mag)
  2637. >>> response = np.clip(response, -100, 100)
  2638. >>> plt.plot(freq, response)
  2639. [<matplotlib.lines.Line2D object at 0x...>]
  2640. >>> plt.title("Frequency response of Kaiser window")
  2641. <matplotlib.text.Text object at 0x...>
  2642. >>> plt.ylabel("Magnitude [dB]")
  2643. <matplotlib.text.Text object at 0x...>
  2644. >>> plt.xlabel("Normalized frequency [cycles per sample]")
  2645. <matplotlib.text.Text object at 0x...>
  2646. >>> plt.axis('tight')
  2647. (-0.5, 0.5, -100.0, ...)
  2648. >>> plt.show()
  2649. """
  2650. from numpy.dual import i0
  2651. if M == 1:
  2652. return np.array([1.])
  2653. n = arange(0, M)
  2654. alpha = (M-1)/2.0
  2655. return i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/i0(float(beta))
  2656. def _sinc_dispatcher(x):
  2657. return (x,)
  2658. @array_function_dispatch(_sinc_dispatcher)
  2659. def sinc(x):
  2660. """
  2661. Return the sinc function.
  2662. The sinc function is :math:`\\sin(\\pi x)/(\\pi x)`.
  2663. Parameters
  2664. ----------
  2665. x : ndarray
  2666. Array (possibly multi-dimensional) of values for which to to
  2667. calculate ``sinc(x)``.
  2668. Returns
  2669. -------
  2670. out : ndarray
  2671. ``sinc(x)``, which has the same shape as the input.
  2672. Notes
  2673. -----
  2674. ``sinc(0)`` is the limit value 1.
  2675. The name sinc is short for "sine cardinal" or "sinus cardinalis".
  2676. The sinc function is used in various signal processing applications,
  2677. including in anti-aliasing, in the construction of a Lanczos resampling
  2678. filter, and in interpolation.
  2679. For bandlimited interpolation of discrete-time signals, the ideal
  2680. interpolation kernel is proportional to the sinc function.
  2681. References
  2682. ----------
  2683. .. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
  2684. Resource. http://mathworld.wolfram.com/SincFunction.html
  2685. .. [2] Wikipedia, "Sinc function",
  2686. https://en.wikipedia.org/wiki/Sinc_function
  2687. Examples
  2688. --------
  2689. >>> import matplotlib.pyplot as plt
  2690. >>> x = np.linspace(-4, 4, 41)
  2691. >>> np.sinc(x)
  2692. array([ -3.89804309e-17, -4.92362781e-02, -8.40918587e-02,
  2693. -8.90384387e-02, -5.84680802e-02, 3.89804309e-17,
  2694. 6.68206631e-02, 1.16434881e-01, 1.26137788e-01,
  2695. 8.50444803e-02, -3.89804309e-17, -1.03943254e-01,
  2696. -1.89206682e-01, -2.16236208e-01, -1.55914881e-01,
  2697. 3.89804309e-17, 2.33872321e-01, 5.04551152e-01,
  2698. 7.56826729e-01, 9.35489284e-01, 1.00000000e+00,
  2699. 9.35489284e-01, 7.56826729e-01, 5.04551152e-01,
  2700. 2.33872321e-01, 3.89804309e-17, -1.55914881e-01,
  2701. -2.16236208e-01, -1.89206682e-01, -1.03943254e-01,
  2702. -3.89804309e-17, 8.50444803e-02, 1.26137788e-01,
  2703. 1.16434881e-01, 6.68206631e-02, 3.89804309e-17,
  2704. -5.84680802e-02, -8.90384387e-02, -8.40918587e-02,
  2705. -4.92362781e-02, -3.89804309e-17])
  2706. >>> plt.plot(x, np.sinc(x))
  2707. [<matplotlib.lines.Line2D object at 0x...>]
  2708. >>> plt.title("Sinc Function")
  2709. <matplotlib.text.Text object at 0x...>
  2710. >>> plt.ylabel("Amplitude")
  2711. <matplotlib.text.Text object at 0x...>
  2712. >>> plt.xlabel("X")
  2713. <matplotlib.text.Text object at 0x...>
  2714. >>> plt.show()
  2715. It works in 2-D as well:
  2716. >>> x = np.linspace(-4, 4, 401)
  2717. >>> xx = np.outer(x, x)
  2718. >>> plt.imshow(np.sinc(xx))
  2719. <matplotlib.image.AxesImage object at 0x...>
  2720. """
  2721. x = np.asanyarray(x)
  2722. y = pi * where(x == 0, 1.0e-20, x)
  2723. return sin(y)/y
  2724. def _msort_dispatcher(a):
  2725. return (a,)
  2726. @array_function_dispatch(_msort_dispatcher)
  2727. def msort(a):
  2728. """
  2729. Return a copy of an array sorted along the first axis.
  2730. Parameters
  2731. ----------
  2732. a : array_like
  2733. Array to be sorted.
  2734. Returns
  2735. -------
  2736. sorted_array : ndarray
  2737. Array of the same type and shape as `a`.
  2738. See Also
  2739. --------
  2740. sort
  2741. Notes
  2742. -----
  2743. ``np.msort(a)`` is equivalent to ``np.sort(a, axis=0)``.
  2744. """
  2745. b = array(a, subok=True, copy=True)
  2746. b.sort(0)
  2747. return b
  2748. def _ureduce(a, func, **kwargs):
  2749. """
  2750. Internal Function.
  2751. Call `func` with `a` as first argument swapping the axes to use extended
  2752. axis on functions that don't support it natively.
  2753. Returns result and a.shape with axis dims set to 1.
  2754. Parameters
  2755. ----------
  2756. a : array_like
  2757. Input array or object that can be converted to an array.
  2758. func : callable
  2759. Reduction function capable of receiving a single axis argument.
  2760. It is called with `a` as first argument followed by `kwargs`.
  2761. kwargs : keyword arguments
  2762. additional keyword arguments to pass to `func`.
  2763. Returns
  2764. -------
  2765. result : tuple
  2766. Result of func(a, **kwargs) and a.shape with axis dims set to 1
  2767. which can be used to reshape the result to the same shape a ufunc with
  2768. keepdims=True would produce.
  2769. """
  2770. a = np.asanyarray(a)
  2771. axis = kwargs.get('axis', None)
  2772. if axis is not None:
  2773. keepdim = list(a.shape)
  2774. nd = a.ndim
  2775. axis = _nx.normalize_axis_tuple(axis, nd)
  2776. for ax in axis:
  2777. keepdim[ax] = 1
  2778. if len(axis) == 1:
  2779. kwargs['axis'] = axis[0]
  2780. else:
  2781. keep = set(range(nd)) - set(axis)
  2782. nkeep = len(keep)
  2783. # swap axis that should not be reduced to front
  2784. for i, s in enumerate(sorted(keep)):
  2785. a = a.swapaxes(i, s)
  2786. # merge reduced axis
  2787. a = a.reshape(a.shape[:nkeep] + (-1,))
  2788. kwargs['axis'] = -1
  2789. keepdim = tuple(keepdim)
  2790. else:
  2791. keepdim = (1,) * a.ndim
  2792. r = func(a, **kwargs)
  2793. return r, keepdim
  2794. def _median_dispatcher(
  2795. a, axis=None, out=None, overwrite_input=None, keepdims=None):
  2796. return (a, out)
  2797. @array_function_dispatch(_median_dispatcher)
  2798. def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):
  2799. """
  2800. Compute the median along the specified axis.
  2801. Returns the median of the array elements.
  2802. Parameters
  2803. ----------
  2804. a : array_like
  2805. Input array or object that can be converted to an array.
  2806. axis : {int, sequence of int, None}, optional
  2807. Axis or axes along which the medians are computed. The default
  2808. is to compute the median along a flattened version of the array.
  2809. A sequence of axes is supported since version 1.9.0.
  2810. out : ndarray, optional
  2811. Alternative output array in which to place the result. It must
  2812. have the same shape and buffer length as the expected output,
  2813. but the type (of the output) will be cast if necessary.
  2814. overwrite_input : bool, optional
  2815. If True, then allow use of memory of input array `a` for
  2816. calculations. The input array will be modified by the call to
  2817. `median`. This will save memory when you do not need to preserve
  2818. the contents of the input array. Treat the input as undefined,
  2819. but it will probably be fully or partially sorted. Default is
  2820. False. If `overwrite_input` is ``True`` and `a` is not already an
  2821. `ndarray`, an error will be raised.
  2822. keepdims : bool, optional
  2823. If this is set to True, the axes which are reduced are left
  2824. in the result as dimensions with size one. With this option,
  2825. the result will broadcast correctly against the original `arr`.
  2826. .. versionadded:: 1.9.0
  2827. Returns
  2828. -------
  2829. median : ndarray
  2830. A new array holding the result. If the input contains integers
  2831. or floats smaller than ``float64``, then the output data-type is
  2832. ``np.float64``. Otherwise, the data-type of the output is the
  2833. same as that of the input. If `out` is specified, that array is
  2834. returned instead.
  2835. See Also
  2836. --------
  2837. mean, percentile
  2838. Notes
  2839. -----
  2840. Given a vector ``V`` of length ``N``, the median of ``V`` is the
  2841. middle value of a sorted copy of ``V``, ``V_sorted`` - i
  2842. e., ``V_sorted[(N-1)/2]``, when ``N`` is odd, and the average of the
  2843. two middle values of ``V_sorted`` when ``N`` is even.
  2844. Examples
  2845. --------
  2846. >>> a = np.array([[10, 7, 4], [3, 2, 1]])
  2847. >>> a
  2848. array([[10, 7, 4],
  2849. [ 3, 2, 1]])
  2850. >>> np.median(a)
  2851. 3.5
  2852. >>> np.median(a, axis=0)
  2853. array([ 6.5, 4.5, 2.5])
  2854. >>> np.median(a, axis=1)
  2855. array([ 7., 2.])
  2856. >>> m = np.median(a, axis=0)
  2857. >>> out = np.zeros_like(m)
  2858. >>> np.median(a, axis=0, out=m)
  2859. array([ 6.5, 4.5, 2.5])
  2860. >>> m
  2861. array([ 6.5, 4.5, 2.5])
  2862. >>> b = a.copy()
  2863. >>> np.median(b, axis=1, overwrite_input=True)
  2864. array([ 7., 2.])
  2865. >>> assert not np.all(a==b)
  2866. >>> b = a.copy()
  2867. >>> np.median(b, axis=None, overwrite_input=True)
  2868. 3.5
  2869. >>> assert not np.all(a==b)
  2870. """
  2871. r, k = _ureduce(a, func=_median, axis=axis, out=out,
  2872. overwrite_input=overwrite_input)
  2873. if keepdims:
  2874. return r.reshape(k)
  2875. else:
  2876. return r
  2877. def _median(a, axis=None, out=None, overwrite_input=False):
  2878. # can't be reasonably be implemented in terms of percentile as we have to
  2879. # call mean to not break astropy
  2880. a = np.asanyarray(a)
  2881. # Set the partition indexes
  2882. if axis is None:
  2883. sz = a.size
  2884. else:
  2885. sz = a.shape[axis]
  2886. if sz % 2 == 0:
  2887. szh = sz // 2
  2888. kth = [szh - 1, szh]
  2889. else:
  2890. kth = [(sz - 1) // 2]
  2891. # Check if the array contains any nan's
  2892. if np.issubdtype(a.dtype, np.inexact):
  2893. kth.append(-1)
  2894. if overwrite_input:
  2895. if axis is None:
  2896. part = a.ravel()
  2897. part.partition(kth)
  2898. else:
  2899. a.partition(kth, axis=axis)
  2900. part = a
  2901. else:
  2902. part = partition(a, kth, axis=axis)
  2903. if part.shape == ():
  2904. # make 0-D arrays work
  2905. return part.item()
  2906. if axis is None:
  2907. axis = 0
  2908. indexer = [slice(None)] * part.ndim
  2909. index = part.shape[axis] // 2
  2910. if part.shape[axis] % 2 == 1:
  2911. # index with slice to allow mean (below) to work
  2912. indexer[axis] = slice(index, index+1)
  2913. else:
  2914. indexer[axis] = slice(index-1, index+1)
  2915. indexer = tuple(indexer)
  2916. # Check if the array contains any nan's
  2917. if np.issubdtype(a.dtype, np.inexact) and sz > 0:
  2918. # warn and return nans like mean would
  2919. rout = mean(part[indexer], axis=axis, out=out)
  2920. return np.lib.utils._median_nancheck(part, rout, axis, out)
  2921. else:
  2922. # if there are no nans
  2923. # Use mean in odd and even case to coerce data type
  2924. # and check, use out array.
  2925. return mean(part[indexer], axis=axis, out=out)
  2926. def _percentile_dispatcher(a, q, axis=None, out=None, overwrite_input=None,
  2927. interpolation=None, keepdims=None):
  2928. return (a, q, out)
  2929. @array_function_dispatch(_percentile_dispatcher)
  2930. def percentile(a, q, axis=None, out=None,
  2931. overwrite_input=False, interpolation='linear', keepdims=False):
  2932. """
  2933. Compute the q-th percentile of the data along the specified axis.
  2934. Returns the q-th percentile(s) of the array elements.
  2935. Parameters
  2936. ----------
  2937. a : array_like
  2938. Input array or object that can be converted to an array.
  2939. q : array_like of float
  2940. Percentile or sequence of percentiles to compute, which must be between
  2941. 0 and 100 inclusive.
  2942. axis : {int, tuple of int, None}, optional
  2943. Axis or axes along which the percentiles are computed. The
  2944. default is to compute the percentile(s) along a flattened
  2945. version of the array.
  2946. .. versionchanged:: 1.9.0
  2947. A tuple of axes is supported
  2948. out : ndarray, optional
  2949. Alternative output array in which to place the result. It must
  2950. have the same shape and buffer length as the expected output,
  2951. but the type (of the output) will be cast if necessary.
  2952. overwrite_input : bool, optional
  2953. If True, then allow the input array `a` to be modified by intermediate
  2954. calculations, to save memory. In this case, the contents of the input
  2955. `a` after this function completes is undefined.
  2956. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
  2957. This optional parameter specifies the interpolation method to
  2958. use when the desired percentile lies between two data points
  2959. ``i < j``:
  2960. * 'linear': ``i + (j - i) * fraction``, where ``fraction``
  2961. is the fractional part of the index surrounded by ``i``
  2962. and ``j``.
  2963. * 'lower': ``i``.
  2964. * 'higher': ``j``.
  2965. * 'nearest': ``i`` or ``j``, whichever is nearest.
  2966. * 'midpoint': ``(i + j) / 2``.
  2967. .. versionadded:: 1.9.0
  2968. keepdims : bool, optional
  2969. If this is set to True, the axes which are reduced are left in
  2970. the result as dimensions with size one. With this option, the
  2971. result will broadcast correctly against the original array `a`.
  2972. .. versionadded:: 1.9.0
  2973. Returns
  2974. -------
  2975. percentile : scalar or ndarray
  2976. If `q` is a single percentile and `axis=None`, then the result
  2977. is a scalar. If multiple percentiles are given, first axis of
  2978. the result corresponds to the percentiles. The other axes are
  2979. the axes that remain after the reduction of `a`. If the input
  2980. contains integers or floats smaller than ``float64``, the output
  2981. data-type is ``float64``. Otherwise, the output data-type is the
  2982. same as that of the input. If `out` is specified, that array is
  2983. returned instead.
  2984. See Also
  2985. --------
  2986. mean
  2987. median : equivalent to ``percentile(..., 50)``
  2988. nanpercentile
  2989. quantile : equivalent to percentile, except with q in the range [0, 1].
  2990. Notes
  2991. -----
  2992. Given a vector ``V`` of length ``N``, the q-th percentile of
  2993. ``V`` is the value ``q/100`` of the way from the minimum to the
  2994. maximum in a sorted copy of ``V``. The values and distances of
  2995. the two nearest neighbors as well as the `interpolation` parameter
  2996. will determine the percentile if the normalized ranking does not
  2997. match the location of ``q`` exactly. This function is the same as
  2998. the median if ``q=50``, the same as the minimum if ``q=0`` and the
  2999. same as the maximum if ``q=100``.
  3000. Examples
  3001. --------
  3002. >>> a = np.array([[10, 7, 4], [3, 2, 1]])
  3003. >>> a
  3004. array([[10, 7, 4],
  3005. [ 3, 2, 1]])
  3006. >>> np.percentile(a, 50)
  3007. 3.5
  3008. >>> np.percentile(a, 50, axis=0)
  3009. array([[ 6.5, 4.5, 2.5]])
  3010. >>> np.percentile(a, 50, axis=1)
  3011. array([ 7., 2.])
  3012. >>> np.percentile(a, 50, axis=1, keepdims=True)
  3013. array([[ 7.],
  3014. [ 2.]])
  3015. >>> m = np.percentile(a, 50, axis=0)
  3016. >>> out = np.zeros_like(m)
  3017. >>> np.percentile(a, 50, axis=0, out=out)
  3018. array([[ 6.5, 4.5, 2.5]])
  3019. >>> m
  3020. array([[ 6.5, 4.5, 2.5]])
  3021. >>> b = a.copy()
  3022. >>> np.percentile(b, 50, axis=1, overwrite_input=True)
  3023. array([ 7., 2.])
  3024. >>> assert not np.all(a == b)
  3025. The different types of interpolation can be visualized graphically:
  3026. .. plot::
  3027. import matplotlib.pyplot as plt
  3028. a = np.arange(4)
  3029. p = np.linspace(0, 100, 6001)
  3030. ax = plt.gca()
  3031. lines = [
  3032. ('linear', None),
  3033. ('higher', '--'),
  3034. ('lower', '--'),
  3035. ('nearest', '-.'),
  3036. ('midpoint', '-.'),
  3037. ]
  3038. for interpolation, style in lines:
  3039. ax.plot(
  3040. p, np.percentile(a, p, interpolation=interpolation),
  3041. label=interpolation, linestyle=style)
  3042. ax.set(
  3043. title='Interpolation methods for list: ' + str(a),
  3044. xlabel='Percentile',
  3045. ylabel='List item returned',
  3046. yticks=a)
  3047. ax.legend()
  3048. plt.show()
  3049. """
  3050. q = np.true_divide(q, 100.0) # handles the asarray for us too
  3051. if not _quantile_is_valid(q):
  3052. raise ValueError("Percentiles must be in the range [0, 100]")
  3053. return _quantile_unchecked(
  3054. a, q, axis, out, overwrite_input, interpolation, keepdims)
  3055. def _quantile_dispatcher(a, q, axis=None, out=None, overwrite_input=None,
  3056. interpolation=None, keepdims=None):
  3057. return (a, q, out)
  3058. @array_function_dispatch(_quantile_dispatcher)
  3059. def quantile(a, q, axis=None, out=None,
  3060. overwrite_input=False, interpolation='linear', keepdims=False):
  3061. """
  3062. Compute the q-th quantile of the data along the specified axis.
  3063. ..versionadded:: 1.15.0
  3064. Parameters
  3065. ----------
  3066. a : array_like
  3067. Input array or object that can be converted to an array.
  3068. q : array_like of float
  3069. Quantile or sequence of quantiles to compute, which must be between
  3070. 0 and 1 inclusive.
  3071. axis : {int, tuple of int, None}, optional
  3072. Axis or axes along which the quantiles are computed. The
  3073. default is to compute the quantile(s) along a flattened
  3074. version of the array.
  3075. out : ndarray, optional
  3076. Alternative output array in which to place the result. It must
  3077. have the same shape and buffer length as the expected output,
  3078. but the type (of the output) will be cast if necessary.
  3079. overwrite_input : bool, optional
  3080. If True, then allow the input array `a` to be modified by intermediate
  3081. calculations, to save memory. In this case, the contents of the input
  3082. `a` after this function completes is undefined.
  3083. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
  3084. This optional parameter specifies the interpolation method to
  3085. use when the desired quantile lies between two data points
  3086. ``i < j``:
  3087. * linear: ``i + (j - i) * fraction``, where ``fraction``
  3088. is the fractional part of the index surrounded by ``i``
  3089. and ``j``.
  3090. * lower: ``i``.
  3091. * higher: ``j``.
  3092. * nearest: ``i`` or ``j``, whichever is nearest.
  3093. * midpoint: ``(i + j) / 2``.
  3094. keepdims : bool, optional
  3095. If this is set to True, the axes which are reduced are left in
  3096. the result as dimensions with size one. With this option, the
  3097. result will broadcast correctly against the original array `a`.
  3098. Returns
  3099. -------
  3100. quantile : scalar or ndarray
  3101. If `q` is a single quantile and `axis=None`, then the result
  3102. is a scalar. If multiple quantiles are given, first axis of
  3103. the result corresponds to the quantiles. The other axes are
  3104. the axes that remain after the reduction of `a`. If the input
  3105. contains integers or floats smaller than ``float64``, the output
  3106. data-type is ``float64``. Otherwise, the output data-type is the
  3107. same as that of the input. If `out` is specified, that array is
  3108. returned instead.
  3109. See Also
  3110. --------
  3111. mean
  3112. percentile : equivalent to quantile, but with q in the range [0, 100].
  3113. median : equivalent to ``quantile(..., 0.5)``
  3114. nanquantile
  3115. Notes
  3116. -----
  3117. Given a vector ``V`` of length ``N``, the q-th quantile of
  3118. ``V`` is the value ``q`` of the way from the minimum to the
  3119. maximum in a sorted copy of ``V``. The values and distances of
  3120. the two nearest neighbors as well as the `interpolation` parameter
  3121. will determine the quantile if the normalized ranking does not
  3122. match the location of ``q`` exactly. This function is the same as
  3123. the median if ``q=0.5``, the same as the minimum if ``q=0.0`` and the
  3124. same as the maximum if ``q=1.0``.
  3125. Examples
  3126. --------
  3127. >>> a = np.array([[10, 7, 4], [3, 2, 1]])
  3128. >>> a
  3129. array([[10, 7, 4],
  3130. [ 3, 2, 1]])
  3131. >>> np.quantile(a, 0.5)
  3132. 3.5
  3133. >>> np.quantile(a, 0.5, axis=0)
  3134. array([[ 6.5, 4.5, 2.5]])
  3135. >>> np.quantile(a, 0.5, axis=1)
  3136. array([ 7., 2.])
  3137. >>> np.quantile(a, 0.5, axis=1, keepdims=True)
  3138. array([[ 7.],
  3139. [ 2.]])
  3140. >>> m = np.quantile(a, 0.5, axis=0)
  3141. >>> out = np.zeros_like(m)
  3142. >>> np.quantile(a, 0.5, axis=0, out=out)
  3143. array([[ 6.5, 4.5, 2.5]])
  3144. >>> m
  3145. array([[ 6.5, 4.5, 2.5]])
  3146. >>> b = a.copy()
  3147. >>> np.quantile(b, 0.5, axis=1, overwrite_input=True)
  3148. array([ 7., 2.])
  3149. >>> assert not np.all(a == b)
  3150. """
  3151. q = np.asanyarray(q)
  3152. if not _quantile_is_valid(q):
  3153. raise ValueError("Quantiles must be in the range [0, 1]")
  3154. return _quantile_unchecked(
  3155. a, q, axis, out, overwrite_input, interpolation, keepdims)
  3156. def _quantile_unchecked(a, q, axis=None, out=None, overwrite_input=False,
  3157. interpolation='linear', keepdims=False):
  3158. """Assumes that q is in [0, 1], and is an ndarray"""
  3159. r, k = _ureduce(a, func=_quantile_ureduce_func, q=q, axis=axis, out=out,
  3160. overwrite_input=overwrite_input,
  3161. interpolation=interpolation)
  3162. if keepdims:
  3163. return r.reshape(q.shape + k)
  3164. else:
  3165. return r
  3166. def _quantile_is_valid(q):
  3167. # avoid expensive reductions, relevant for arrays with < O(1000) elements
  3168. if q.ndim == 1 and q.size < 10:
  3169. for i in range(q.size):
  3170. if q[i] < 0.0 or q[i] > 1.0:
  3171. return False
  3172. else:
  3173. # faster than any()
  3174. if np.count_nonzero(q < 0.0) or np.count_nonzero(q > 1.0):
  3175. return False
  3176. return True
  3177. def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
  3178. interpolation='linear', keepdims=False):
  3179. a = asarray(a)
  3180. if q.ndim == 0:
  3181. # Do not allow 0-d arrays because following code fails for scalar
  3182. zerod = True
  3183. q = q[None]
  3184. else:
  3185. zerod = False
  3186. # prepare a for partitioning
  3187. if overwrite_input:
  3188. if axis is None:
  3189. ap = a.ravel()
  3190. else:
  3191. ap = a
  3192. else:
  3193. if axis is None:
  3194. ap = a.flatten()
  3195. else:
  3196. ap = a.copy()
  3197. if axis is None:
  3198. axis = 0
  3199. Nx = ap.shape[axis]
  3200. indices = q * (Nx - 1)
  3201. # round fractional indices according to interpolation method
  3202. if interpolation == 'lower':
  3203. indices = floor(indices).astype(intp)
  3204. elif interpolation == 'higher':
  3205. indices = ceil(indices).astype(intp)
  3206. elif interpolation == 'midpoint':
  3207. indices = 0.5 * (floor(indices) + ceil(indices))
  3208. elif interpolation == 'nearest':
  3209. indices = around(indices).astype(intp)
  3210. elif interpolation == 'linear':
  3211. pass # keep index as fraction and interpolate
  3212. else:
  3213. raise ValueError(
  3214. "interpolation can only be 'linear', 'lower' 'higher', "
  3215. "'midpoint', or 'nearest'")
  3216. n = np.array(False, dtype=bool) # check for nan's flag
  3217. if indices.dtype == intp: # take the points along axis
  3218. # Check if the array contains any nan's
  3219. if np.issubdtype(a.dtype, np.inexact):
  3220. indices = concatenate((indices, [-1]))
  3221. ap.partition(indices, axis=axis)
  3222. # ensure axis with q-th is first
  3223. ap = np.moveaxis(ap, axis, 0)
  3224. axis = 0
  3225. # Check if the array contains any nan's
  3226. if np.issubdtype(a.dtype, np.inexact):
  3227. indices = indices[:-1]
  3228. n = np.isnan(ap[-1:, ...])
  3229. if zerod:
  3230. indices = indices[0]
  3231. r = take(ap, indices, axis=axis, out=out)
  3232. else: # weight the points above and below the indices
  3233. indices_below = floor(indices).astype(intp)
  3234. indices_above = indices_below + 1
  3235. indices_above[indices_above > Nx - 1] = Nx - 1
  3236. # Check if the array contains any nan's
  3237. if np.issubdtype(a.dtype, np.inexact):
  3238. indices_above = concatenate((indices_above, [-1]))
  3239. weights_above = indices - indices_below
  3240. weights_below = 1.0 - weights_above
  3241. weights_shape = [1, ] * ap.ndim
  3242. weights_shape[axis] = len(indices)
  3243. weights_below.shape = weights_shape
  3244. weights_above.shape = weights_shape
  3245. ap.partition(concatenate((indices_below, indices_above)), axis=axis)
  3246. # ensure axis with q-th is first
  3247. ap = np.moveaxis(ap, axis, 0)
  3248. weights_below = np.moveaxis(weights_below, axis, 0)
  3249. weights_above = np.moveaxis(weights_above, axis, 0)
  3250. axis = 0
  3251. # Check if the array contains any nan's
  3252. if np.issubdtype(a.dtype, np.inexact):
  3253. indices_above = indices_above[:-1]
  3254. n = np.isnan(ap[-1:, ...])
  3255. x1 = take(ap, indices_below, axis=axis) * weights_below
  3256. x2 = take(ap, indices_above, axis=axis) * weights_above
  3257. # ensure axis with q-th is first
  3258. x1 = np.moveaxis(x1, axis, 0)
  3259. x2 = np.moveaxis(x2, axis, 0)
  3260. if zerod:
  3261. x1 = x1.squeeze(0)
  3262. x2 = x2.squeeze(0)
  3263. if out is not None:
  3264. r = add(x1, x2, out=out)
  3265. else:
  3266. r = add(x1, x2)
  3267. if np.any(n):
  3268. warnings.warn("Invalid value encountered in percentile",
  3269. RuntimeWarning, stacklevel=3)
  3270. if zerod:
  3271. if ap.ndim == 1:
  3272. if out is not None:
  3273. out[...] = a.dtype.type(np.nan)
  3274. r = out
  3275. else:
  3276. r = a.dtype.type(np.nan)
  3277. else:
  3278. r[..., n.squeeze(0)] = a.dtype.type(np.nan)
  3279. else:
  3280. if r.ndim == 1:
  3281. r[:] = a.dtype.type(np.nan)
  3282. else:
  3283. r[..., n.repeat(q.size, 0)] = a.dtype.type(np.nan)
  3284. return r
  3285. def _trapz_dispatcher(y, x=None, dx=None, axis=None):
  3286. return (y, x)
  3287. @array_function_dispatch(_trapz_dispatcher)
  3288. def trapz(y, x=None, dx=1.0, axis=-1):
  3289. """
  3290. Integrate along the given axis using the composite trapezoidal rule.
  3291. Integrate `y` (`x`) along given axis.
  3292. Parameters
  3293. ----------
  3294. y : array_like
  3295. Input array to integrate.
  3296. x : array_like, optional
  3297. The sample points corresponding to the `y` values. If `x` is None,
  3298. the sample points are assumed to be evenly spaced `dx` apart. The
  3299. default is None.
  3300. dx : scalar, optional
  3301. The spacing between sample points when `x` is None. The default is 1.
  3302. axis : int, optional
  3303. The axis along which to integrate.
  3304. Returns
  3305. -------
  3306. trapz : float
  3307. Definite integral as approximated by trapezoidal rule.
  3308. See Also
  3309. --------
  3310. sum, cumsum
  3311. Notes
  3312. -----
  3313. Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
  3314. will be taken from `y` array, by default x-axis distances between
  3315. points will be 1.0, alternatively they can be provided with `x` array
  3316. or with `dx` scalar. Return value will be equal to combined area under
  3317. the red lines.
  3318. References
  3319. ----------
  3320. .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
  3321. .. [2] Illustration image:
  3322. https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
  3323. Examples
  3324. --------
  3325. >>> np.trapz([1,2,3])
  3326. 4.0
  3327. >>> np.trapz([1,2,3], x=[4,6,8])
  3328. 8.0
  3329. >>> np.trapz([1,2,3], dx=2)
  3330. 8.0
  3331. >>> a = np.arange(6).reshape(2, 3)
  3332. >>> a
  3333. array([[0, 1, 2],
  3334. [3, 4, 5]])
  3335. >>> np.trapz(a, axis=0)
  3336. array([ 1.5, 2.5, 3.5])
  3337. >>> np.trapz(a, axis=1)
  3338. array([ 2., 8.])
  3339. """
  3340. y = asanyarray(y)
  3341. if x is None:
  3342. d = dx
  3343. else:
  3344. x = asanyarray(x)
  3345. if x.ndim == 1:
  3346. d = diff(x)
  3347. # reshape to correct shape
  3348. shape = [1]*y.ndim
  3349. shape[axis] = d.shape[0]
  3350. d = d.reshape(shape)
  3351. else:
  3352. d = diff(x, axis=axis)
  3353. nd = y.ndim
  3354. slice1 = [slice(None)]*nd
  3355. slice2 = [slice(None)]*nd
  3356. slice1[axis] = slice(1, None)
  3357. slice2[axis] = slice(None, -1)
  3358. try:
  3359. ret = (d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0).sum(axis)
  3360. except ValueError:
  3361. # Operations didn't work, cast to ndarray
  3362. d = np.asarray(d)
  3363. y = np.asarray(y)
  3364. ret = add.reduce(d * (y[tuple(slice1)]+y[tuple(slice2)])/2.0, axis)
  3365. return ret
  3366. def _meshgrid_dispatcher(*xi, **kwargs):
  3367. return xi
  3368. # Based on scitools meshgrid
  3369. @array_function_dispatch(_meshgrid_dispatcher)
  3370. def meshgrid(*xi, **kwargs):
  3371. """
  3372. Return coordinate matrices from coordinate vectors.
  3373. Make N-D coordinate arrays for vectorized evaluations of
  3374. N-D scalar/vector fields over N-D grids, given
  3375. one-dimensional coordinate arrays x1, x2,..., xn.
  3376. .. versionchanged:: 1.9
  3377. 1-D and 0-D cases are allowed.
  3378. Parameters
  3379. ----------
  3380. x1, x2,..., xn : array_like
  3381. 1-D arrays representing the coordinates of a grid.
  3382. indexing : {'xy', 'ij'}, optional
  3383. Cartesian ('xy', default) or matrix ('ij') indexing of output.
  3384. See Notes for more details.
  3385. .. versionadded:: 1.7.0
  3386. sparse : bool, optional
  3387. If True a sparse grid is returned in order to conserve memory.
  3388. Default is False.
  3389. .. versionadded:: 1.7.0
  3390. copy : bool, optional
  3391. If False, a view into the original arrays are returned in order to
  3392. conserve memory. Default is True. Please note that
  3393. ``sparse=False, copy=False`` will likely return non-contiguous
  3394. arrays. Furthermore, more than one element of a broadcast array
  3395. may refer to a single memory location. If you need to write to the
  3396. arrays, make copies first.
  3397. .. versionadded:: 1.7.0
  3398. Returns
  3399. -------
  3400. X1, X2,..., XN : ndarray
  3401. For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` ,
  3402. return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij'
  3403. or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy'
  3404. with the elements of `xi` repeated to fill the matrix along
  3405. the first dimension for `x1`, the second for `x2` and so on.
  3406. Notes
  3407. -----
  3408. This function supports both indexing conventions through the indexing
  3409. keyword argument. Giving the string 'ij' returns a meshgrid with
  3410. matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing.
  3411. In the 2-D case with inputs of length M and N, the outputs are of shape
  3412. (N, M) for 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D case
  3413. with inputs of length M, N and P, outputs are of shape (N, M, P) for
  3414. 'xy' indexing and (M, N, P) for 'ij' indexing. The difference is
  3415. illustrated by the following code snippet::
  3416. xv, yv = np.meshgrid(x, y, sparse=False, indexing='ij')
  3417. for i in range(nx):
  3418. for j in range(ny):
  3419. # treat xv[i,j], yv[i,j]
  3420. xv, yv = np.meshgrid(x, y, sparse=False, indexing='xy')
  3421. for i in range(nx):
  3422. for j in range(ny):
  3423. # treat xv[j,i], yv[j,i]
  3424. In the 1-D and 0-D case, the indexing and sparse keywords have no effect.
  3425. See Also
  3426. --------
  3427. index_tricks.mgrid : Construct a multi-dimensional "meshgrid"
  3428. using indexing notation.
  3429. index_tricks.ogrid : Construct an open multi-dimensional "meshgrid"
  3430. using indexing notation.
  3431. Examples
  3432. --------
  3433. >>> nx, ny = (3, 2)
  3434. >>> x = np.linspace(0, 1, nx)
  3435. >>> y = np.linspace(0, 1, ny)
  3436. >>> xv, yv = np.meshgrid(x, y)
  3437. >>> xv
  3438. array([[ 0. , 0.5, 1. ],
  3439. [ 0. , 0.5, 1. ]])
  3440. >>> yv
  3441. array([[ 0., 0., 0.],
  3442. [ 1., 1., 1.]])
  3443. >>> xv, yv = np.meshgrid(x, y, sparse=True) # make sparse output arrays
  3444. >>> xv
  3445. array([[ 0. , 0.5, 1. ]])
  3446. >>> yv
  3447. array([[ 0.],
  3448. [ 1.]])
  3449. `meshgrid` is very useful to evaluate functions on a grid.
  3450. >>> import matplotlib.pyplot as plt
  3451. >>> x = np.arange(-5, 5, 0.1)
  3452. >>> y = np.arange(-5, 5, 0.1)
  3453. >>> xx, yy = np.meshgrid(x, y, sparse=True)
  3454. >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
  3455. >>> h = plt.contourf(x,y,z)
  3456. >>> plt.show()
  3457. """
  3458. ndim = len(xi)
  3459. copy_ = kwargs.pop('copy', True)
  3460. sparse = kwargs.pop('sparse', False)
  3461. indexing = kwargs.pop('indexing', 'xy')
  3462. if kwargs:
  3463. raise TypeError("meshgrid() got an unexpected keyword argument '%s'"
  3464. % (list(kwargs)[0],))
  3465. if indexing not in ['xy', 'ij']:
  3466. raise ValueError(
  3467. "Valid values for `indexing` are 'xy' and 'ij'.")
  3468. s0 = (1,) * ndim
  3469. output = [np.asanyarray(x).reshape(s0[:i] + (-1,) + s0[i + 1:])
  3470. for i, x in enumerate(xi)]
  3471. if indexing == 'xy' and ndim > 1:
  3472. # switch first and second axis
  3473. output[0].shape = (1, -1) + s0[2:]
  3474. output[1].shape = (-1, 1) + s0[2:]
  3475. if not sparse:
  3476. # Return the full N-D matrix (not only the 1-D vector)
  3477. output = np.broadcast_arrays(*output, subok=True)
  3478. if copy_:
  3479. output = [x.copy() for x in output]
  3480. return output
  3481. def _delete_dispatcher(arr, obj, axis=None):
  3482. return (arr, obj)
  3483. @array_function_dispatch(_delete_dispatcher)
  3484. def delete(arr, obj, axis=None):
  3485. """
  3486. Return a new array with sub-arrays along an axis deleted. For a one
  3487. dimensional array, this returns those entries not returned by
  3488. `arr[obj]`.
  3489. Parameters
  3490. ----------
  3491. arr : array_like
  3492. Input array.
  3493. obj : slice, int or array of ints
  3494. Indicate which sub-arrays to remove.
  3495. axis : int, optional
  3496. The axis along which to delete the subarray defined by `obj`.
  3497. If `axis` is None, `obj` is applied to the flattened array.
  3498. Returns
  3499. -------
  3500. out : ndarray
  3501. A copy of `arr` with the elements specified by `obj` removed. Note
  3502. that `delete` does not occur in-place. If `axis` is None, `out` is
  3503. a flattened array.
  3504. See Also
  3505. --------
  3506. insert : Insert elements into an array.
  3507. append : Append elements at the end of an array.
  3508. Notes
  3509. -----
  3510. Often it is preferable to use a boolean mask. For example:
  3511. >>> mask = np.ones(len(arr), dtype=bool)
  3512. >>> mask[[0,2,4]] = False
  3513. >>> result = arr[mask,...]
  3514. Is equivalent to `np.delete(arr, [0,2,4], axis=0)`, but allows further
  3515. use of `mask`.
  3516. Examples
  3517. --------
  3518. >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
  3519. >>> arr
  3520. array([[ 1, 2, 3, 4],
  3521. [ 5, 6, 7, 8],
  3522. [ 9, 10, 11, 12]])
  3523. >>> np.delete(arr, 1, 0)
  3524. array([[ 1, 2, 3, 4],
  3525. [ 9, 10, 11, 12]])
  3526. >>> np.delete(arr, np.s_[::2], 1)
  3527. array([[ 2, 4],
  3528. [ 6, 8],
  3529. [10, 12]])
  3530. >>> np.delete(arr, [1,3,5], None)
  3531. array([ 1, 3, 5, 7, 8, 9, 10, 11, 12])
  3532. """
  3533. wrap = None
  3534. if type(arr) is not ndarray:
  3535. try:
  3536. wrap = arr.__array_wrap__
  3537. except AttributeError:
  3538. pass
  3539. arr = asarray(arr)
  3540. ndim = arr.ndim
  3541. arrorder = 'F' if arr.flags.fnc else 'C'
  3542. if axis is None:
  3543. if ndim != 1:
  3544. arr = arr.ravel()
  3545. ndim = arr.ndim
  3546. axis = -1
  3547. if ndim == 0:
  3548. # 2013-09-24, 1.9
  3549. warnings.warn(
  3550. "in the future the special handling of scalars will be removed "
  3551. "from delete and raise an error", DeprecationWarning, stacklevel=2)
  3552. if wrap:
  3553. return wrap(arr)
  3554. else:
  3555. return arr.copy(order=arrorder)
  3556. axis = normalize_axis_index(axis, ndim)
  3557. slobj = [slice(None)]*ndim
  3558. N = arr.shape[axis]
  3559. newshape = list(arr.shape)
  3560. if isinstance(obj, slice):
  3561. start, stop, step = obj.indices(N)
  3562. xr = range(start, stop, step)
  3563. numtodel = len(xr)
  3564. if numtodel <= 0:
  3565. if wrap:
  3566. return wrap(arr.copy(order=arrorder))
  3567. else:
  3568. return arr.copy(order=arrorder)
  3569. # Invert if step is negative:
  3570. if step < 0:
  3571. step = -step
  3572. start = xr[-1]
  3573. stop = xr[0] + 1
  3574. newshape[axis] -= numtodel
  3575. new = empty(newshape, arr.dtype, arrorder)
  3576. # copy initial chunk
  3577. if start == 0:
  3578. pass
  3579. else:
  3580. slobj[axis] = slice(None, start)
  3581. new[tuple(slobj)] = arr[tuple(slobj)]
  3582. # copy end chunck
  3583. if stop == N:
  3584. pass
  3585. else:
  3586. slobj[axis] = slice(stop-numtodel, None)
  3587. slobj2 = [slice(None)]*ndim
  3588. slobj2[axis] = slice(stop, None)
  3589. new[tuple(slobj)] = arr[tuple(slobj2)]
  3590. # copy middle pieces
  3591. if step == 1:
  3592. pass
  3593. else: # use array indexing.
  3594. keep = ones(stop-start, dtype=bool)
  3595. keep[:stop-start:step] = False
  3596. slobj[axis] = slice(start, stop-numtodel)
  3597. slobj2 = [slice(None)]*ndim
  3598. slobj2[axis] = slice(start, stop)
  3599. arr = arr[tuple(slobj2)]
  3600. slobj2[axis] = keep
  3601. new[tuple(slobj)] = arr[tuple(slobj2)]
  3602. if wrap:
  3603. return wrap(new)
  3604. else:
  3605. return new
  3606. _obj = obj
  3607. obj = np.asarray(obj)
  3608. # After removing the special handling of booleans and out of
  3609. # bounds values, the conversion to the array can be removed.
  3610. if obj.dtype == bool:
  3611. warnings.warn("in the future insert will treat boolean arrays and "
  3612. "array-likes as boolean index instead of casting it "
  3613. "to integer", FutureWarning, stacklevel=2)
  3614. obj = obj.astype(intp)
  3615. if isinstance(_obj, (int, long, integer)):
  3616. # optimization for a single value
  3617. obj = obj.item()
  3618. if (obj < -N or obj >= N):
  3619. raise IndexError(
  3620. "index %i is out of bounds for axis %i with "
  3621. "size %i" % (obj, axis, N))
  3622. if (obj < 0):
  3623. obj += N
  3624. newshape[axis] -= 1
  3625. new = empty(newshape, arr.dtype, arrorder)
  3626. slobj[axis] = slice(None, obj)
  3627. new[tuple(slobj)] = arr[tuple(slobj)]
  3628. slobj[axis] = slice(obj, None)
  3629. slobj2 = [slice(None)]*ndim
  3630. slobj2[axis] = slice(obj+1, None)
  3631. new[tuple(slobj)] = arr[tuple(slobj2)]
  3632. else:
  3633. if obj.size == 0 and not isinstance(_obj, np.ndarray):
  3634. obj = obj.astype(intp)
  3635. if not np.can_cast(obj, intp, 'same_kind'):
  3636. # obj.size = 1 special case always failed and would just
  3637. # give superfluous warnings.
  3638. # 2013-09-24, 1.9
  3639. warnings.warn(
  3640. "using a non-integer array as obj in delete will result in an "
  3641. "error in the future", DeprecationWarning, stacklevel=2)
  3642. obj = obj.astype(intp)
  3643. keep = ones(N, dtype=bool)
  3644. # Test if there are out of bound indices, this is deprecated
  3645. inside_bounds = (obj < N) & (obj >= -N)
  3646. if not inside_bounds.all():
  3647. # 2013-09-24, 1.9
  3648. warnings.warn(
  3649. "in the future out of bounds indices will raise an error "
  3650. "instead of being ignored by `numpy.delete`.",
  3651. DeprecationWarning, stacklevel=2)
  3652. obj = obj[inside_bounds]
  3653. positive_indices = obj >= 0
  3654. if not positive_indices.all():
  3655. warnings.warn(
  3656. "in the future negative indices will not be ignored by "
  3657. "`numpy.delete`.", FutureWarning, stacklevel=2)
  3658. obj = obj[positive_indices]
  3659. keep[obj, ] = False
  3660. slobj[axis] = keep
  3661. new = arr[tuple(slobj)]
  3662. if wrap:
  3663. return wrap(new)
  3664. else:
  3665. return new
  3666. def _insert_dispatcher(arr, obj, values, axis=None):
  3667. return (arr, obj, values)
  3668. @array_function_dispatch(_insert_dispatcher)
  3669. def insert(arr, obj, values, axis=None):
  3670. """
  3671. Insert values along the given axis before the given indices.
  3672. Parameters
  3673. ----------
  3674. arr : array_like
  3675. Input array.
  3676. obj : int, slice or sequence of ints
  3677. Object that defines the index or indices before which `values` is
  3678. inserted.
  3679. .. versionadded:: 1.8.0
  3680. Support for multiple insertions when `obj` is a single scalar or a
  3681. sequence with one element (similar to calling insert multiple
  3682. times).
  3683. values : array_like
  3684. Values to insert into `arr`. If the type of `values` is different
  3685. from that of `arr`, `values` is converted to the type of `arr`.
  3686. `values` should be shaped so that ``arr[...,obj,...] = values``
  3687. is legal.
  3688. axis : int, optional
  3689. Axis along which to insert `values`. If `axis` is None then `arr`
  3690. is flattened first.
  3691. Returns
  3692. -------
  3693. out : ndarray
  3694. A copy of `arr` with `values` inserted. Note that `insert`
  3695. does not occur in-place: a new array is returned. If
  3696. `axis` is None, `out` is a flattened array.
  3697. See Also
  3698. --------
  3699. append : Append elements at the end of an array.
  3700. concatenate : Join a sequence of arrays along an existing axis.
  3701. delete : Delete elements from an array.
  3702. Notes
  3703. -----
  3704. Note that for higher dimensional inserts `obj=0` behaves very different
  3705. from `obj=[0]` just like `arr[:,0,:] = values` is different from
  3706. `arr[:,[0],:] = values`.
  3707. Examples
  3708. --------
  3709. >>> a = np.array([[1, 1], [2, 2], [3, 3]])
  3710. >>> a
  3711. array([[1, 1],
  3712. [2, 2],
  3713. [3, 3]])
  3714. >>> np.insert(a, 1, 5)
  3715. array([1, 5, 1, 2, 2, 3, 3])
  3716. >>> np.insert(a, 1, 5, axis=1)
  3717. array([[1, 5, 1],
  3718. [2, 5, 2],
  3719. [3, 5, 3]])
  3720. Difference between sequence and scalars:
  3721. >>> np.insert(a, [1], [[1],[2],[3]], axis=1)
  3722. array([[1, 1, 1],
  3723. [2, 2, 2],
  3724. [3, 3, 3]])
  3725. >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1),
  3726. ... np.insert(a, [1], [[1],[2],[3]], axis=1))
  3727. True
  3728. >>> b = a.flatten()
  3729. >>> b
  3730. array([1, 1, 2, 2, 3, 3])
  3731. >>> np.insert(b, [2, 2], [5, 6])
  3732. array([1, 1, 5, 6, 2, 2, 3, 3])
  3733. >>> np.insert(b, slice(2, 4), [5, 6])
  3734. array([1, 1, 5, 2, 6, 2, 3, 3])
  3735. >>> np.insert(b, [2, 2], [7.13, False]) # type casting
  3736. array([1, 1, 7, 0, 2, 2, 3, 3])
  3737. >>> x = np.arange(8).reshape(2, 4)
  3738. >>> idx = (1, 3)
  3739. >>> np.insert(x, idx, 999, axis=1)
  3740. array([[ 0, 999, 1, 2, 999, 3],
  3741. [ 4, 999, 5, 6, 999, 7]])
  3742. """
  3743. wrap = None
  3744. if type(arr) is not ndarray:
  3745. try:
  3746. wrap = arr.__array_wrap__
  3747. except AttributeError:
  3748. pass
  3749. arr = asarray(arr)
  3750. ndim = arr.ndim
  3751. arrorder = 'F' if arr.flags.fnc else 'C'
  3752. if axis is None:
  3753. if ndim != 1:
  3754. arr = arr.ravel()
  3755. ndim = arr.ndim
  3756. axis = ndim - 1
  3757. elif ndim == 0:
  3758. # 2013-09-24, 1.9
  3759. warnings.warn(
  3760. "in the future the special handling of scalars will be removed "
  3761. "from insert and raise an error", DeprecationWarning, stacklevel=2)
  3762. arr = arr.copy(order=arrorder)
  3763. arr[...] = values
  3764. if wrap:
  3765. return wrap(arr)
  3766. else:
  3767. return arr
  3768. else:
  3769. axis = normalize_axis_index(axis, ndim)
  3770. slobj = [slice(None)]*ndim
  3771. N = arr.shape[axis]
  3772. newshape = list(arr.shape)
  3773. if isinstance(obj, slice):
  3774. # turn it into a range object
  3775. indices = arange(*obj.indices(N), **{'dtype': intp})
  3776. else:
  3777. # need to copy obj, because indices will be changed in-place
  3778. indices = np.array(obj)
  3779. if indices.dtype == bool:
  3780. # See also delete
  3781. warnings.warn(
  3782. "in the future insert will treat boolean arrays and "
  3783. "array-likes as a boolean index instead of casting it to "
  3784. "integer", FutureWarning, stacklevel=2)
  3785. indices = indices.astype(intp)
  3786. # Code after warning period:
  3787. #if obj.ndim != 1:
  3788. # raise ValueError('boolean array argument obj to insert '
  3789. # 'must be one dimensional')
  3790. #indices = np.flatnonzero(obj)
  3791. elif indices.ndim > 1:
  3792. raise ValueError(
  3793. "index array argument obj to insert must be one dimensional "
  3794. "or scalar")
  3795. if indices.size == 1:
  3796. index = indices.item()
  3797. if index < -N or index > N:
  3798. raise IndexError(
  3799. "index %i is out of bounds for axis %i with "
  3800. "size %i" % (obj, axis, N))
  3801. if (index < 0):
  3802. index += N
  3803. # There are some object array corner cases here, but we cannot avoid
  3804. # that:
  3805. values = array(values, copy=False, ndmin=arr.ndim, dtype=arr.dtype)
  3806. if indices.ndim == 0:
  3807. # broadcasting is very different here, since a[:,0,:] = ... behaves
  3808. # very different from a[:,[0],:] = ...! This changes values so that
  3809. # it works likes the second case. (here a[:,0:1,:])
  3810. values = np.moveaxis(values, 0, axis)
  3811. numnew = values.shape[axis]
  3812. newshape[axis] += numnew
  3813. new = empty(newshape, arr.dtype, arrorder)
  3814. slobj[axis] = slice(None, index)
  3815. new[tuple(slobj)] = arr[tuple(slobj)]
  3816. slobj[axis] = slice(index, index+numnew)
  3817. new[tuple(slobj)] = values
  3818. slobj[axis] = slice(index+numnew, None)
  3819. slobj2 = [slice(None)] * ndim
  3820. slobj2[axis] = slice(index, None)
  3821. new[tuple(slobj)] = arr[tuple(slobj2)]
  3822. if wrap:
  3823. return wrap(new)
  3824. return new
  3825. elif indices.size == 0 and not isinstance(obj, np.ndarray):
  3826. # Can safely cast the empty list to intp
  3827. indices = indices.astype(intp)
  3828. if not np.can_cast(indices, intp, 'same_kind'):
  3829. # 2013-09-24, 1.9
  3830. warnings.warn(
  3831. "using a non-integer array as obj in insert will result in an "
  3832. "error in the future", DeprecationWarning, stacklevel=2)
  3833. indices = indices.astype(intp)
  3834. indices[indices < 0] += N
  3835. numnew = len(indices)
  3836. order = indices.argsort(kind='mergesort') # stable sort
  3837. indices[order] += np.arange(numnew)
  3838. newshape[axis] += numnew
  3839. old_mask = ones(newshape[axis], dtype=bool)
  3840. old_mask[indices] = False
  3841. new = empty(newshape, arr.dtype, arrorder)
  3842. slobj2 = [slice(None)]*ndim
  3843. slobj[axis] = indices
  3844. slobj2[axis] = old_mask
  3845. new[tuple(slobj)] = values
  3846. new[tuple(slobj2)] = arr
  3847. if wrap:
  3848. return wrap(new)
  3849. return new
  3850. def _append_dispatcher(arr, values, axis=None):
  3851. return (arr, values)
  3852. @array_function_dispatch(_append_dispatcher)
  3853. def append(arr, values, axis=None):
  3854. """
  3855. Append values to the end of an array.
  3856. Parameters
  3857. ----------
  3858. arr : array_like
  3859. Values are appended to a copy of this array.
  3860. values : array_like
  3861. These values are appended to a copy of `arr`. It must be of the
  3862. correct shape (the same shape as `arr`, excluding `axis`). If
  3863. `axis` is not specified, `values` can be any shape and will be
  3864. flattened before use.
  3865. axis : int, optional
  3866. The axis along which `values` are appended. If `axis` is not
  3867. given, both `arr` and `values` are flattened before use.
  3868. Returns
  3869. -------
  3870. append : ndarray
  3871. A copy of `arr` with `values` appended to `axis`. Note that
  3872. `append` does not occur in-place: a new array is allocated and
  3873. filled. If `axis` is None, `out` is a flattened array.
  3874. See Also
  3875. --------
  3876. insert : Insert elements into an array.
  3877. delete : Delete elements from an array.
  3878. Examples
  3879. --------
  3880. >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
  3881. array([1, 2, 3, 4, 5, 6, 7, 8, 9])
  3882. When `axis` is specified, `values` must have the correct shape.
  3883. >>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
  3884. array([[1, 2, 3],
  3885. [4, 5, 6],
  3886. [7, 8, 9]])
  3887. >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
  3888. Traceback (most recent call last):
  3889. ...
  3890. ValueError: arrays must have same number of dimensions
  3891. """
  3892. arr = asanyarray(arr)
  3893. if axis is None:
  3894. if arr.ndim != 1:
  3895. arr = arr.ravel()
  3896. values = ravel(values)
  3897. axis = arr.ndim-1
  3898. return concatenate((arr, values), axis=axis)
  3899. def _digitize_dispatcher(x, bins, right=None):
  3900. return (x, bins)
  3901. @array_function_dispatch(_digitize_dispatcher)
  3902. def digitize(x, bins, right=False):
  3903. """
  3904. Return the indices of the bins to which each value in input array belongs.
  3905. ========= ============= ============================
  3906. `right` order of bins returned index `i` satisfies
  3907. ========= ============= ============================
  3908. ``False`` increasing ``bins[i-1] <= x < bins[i]``
  3909. ``True`` increasing ``bins[i-1] < x <= bins[i]``
  3910. ``False`` decreasing ``bins[i-1] > x >= bins[i]``
  3911. ``True`` decreasing ``bins[i-1] >= x > bins[i]``
  3912. ========= ============= ============================
  3913. If values in `x` are beyond the bounds of `bins`, 0 or ``len(bins)`` is
  3914. returned as appropriate.
  3915. Parameters
  3916. ----------
  3917. x : array_like
  3918. Input array to be binned. Prior to NumPy 1.10.0, this array had to
  3919. be 1-dimensional, but can now have any shape.
  3920. bins : array_like
  3921. Array of bins. It has to be 1-dimensional and monotonic.
  3922. right : bool, optional
  3923. Indicating whether the intervals include the right or the left bin
  3924. edge. Default behavior is (right==False) indicating that the interval
  3925. does not include the right edge. The left bin end is open in this
  3926. case, i.e., bins[i-1] <= x < bins[i] is the default behavior for
  3927. monotonically increasing bins.
  3928. Returns
  3929. -------
  3930. indices : ndarray of ints
  3931. Output array of indices, of same shape as `x`.
  3932. Raises
  3933. ------
  3934. ValueError
  3935. If `bins` is not monotonic.
  3936. TypeError
  3937. If the type of the input is complex.
  3938. See Also
  3939. --------
  3940. bincount, histogram, unique, searchsorted
  3941. Notes
  3942. -----
  3943. If values in `x` are such that they fall outside the bin range,
  3944. attempting to index `bins` with the indices that `digitize` returns
  3945. will result in an IndexError.
  3946. .. versionadded:: 1.10.0
  3947. `np.digitize` is implemented in terms of `np.searchsorted`. This means
  3948. that a binary search is used to bin the values, which scales much better
  3949. for larger number of bins than the previous linear search. It also removes
  3950. the requirement for the input array to be 1-dimensional.
  3951. For monotonically _increasing_ `bins`, the following are equivalent::
  3952. np.digitize(x, bins, right=True)
  3953. np.searchsorted(bins, x, side='left')
  3954. Note that as the order of the arguments are reversed, the side must be too.
  3955. The `searchsorted` call is marginally faster, as it does not do any
  3956. monotonicity checks. Perhaps more importantly, it supports all dtypes.
  3957. Examples
  3958. --------
  3959. >>> x = np.array([0.2, 6.4, 3.0, 1.6])
  3960. >>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
  3961. >>> inds = np.digitize(x, bins)
  3962. >>> inds
  3963. array([1, 4, 3, 2])
  3964. >>> for n in range(x.size):
  3965. ... print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]])
  3966. ...
  3967. 0.0 <= 0.2 < 1.0
  3968. 4.0 <= 6.4 < 10.0
  3969. 2.5 <= 3.0 < 4.0
  3970. 1.0 <= 1.6 < 2.5
  3971. >>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.])
  3972. >>> bins = np.array([0, 5, 10, 15, 20])
  3973. >>> np.digitize(x,bins,right=True)
  3974. array([1, 2, 3, 4, 4])
  3975. >>> np.digitize(x,bins,right=False)
  3976. array([1, 3, 3, 4, 5])
  3977. """
  3978. x = _nx.asarray(x)
  3979. bins = _nx.asarray(bins)
  3980. # here for compatibility, searchsorted below is happy to take this
  3981. if np.issubdtype(x.dtype, _nx.complexfloating):
  3982. raise TypeError("x may not be complex")
  3983. mono = _monotonicity(bins)
  3984. if mono == 0:
  3985. raise ValueError("bins must be monotonically increasing or decreasing")
  3986. # this is backwards because the arguments below are swapped
  3987. side = 'left' if right else 'right'
  3988. if mono == -1:
  3989. # reverse the bins, and invert the results
  3990. return len(bins) - _nx.searchsorted(bins[::-1], x, side=side)
  3991. else:
  3992. return _nx.searchsorted(bins, x, side=side)