o 6at@sjddlZddlZddlZddlZddlZddlZddlmZmZm Z ddl m Z ddl m Z mZmZddlZgdZddZdd ZGd d d Zd d ZddZddZddZd1ddZddZdadad2ddZejfddZ e dddejdfddZ!e dejfd d!Z"iZ#e$d"ej%Z&e d $ d3d%d&Z'd'd(Z(d)d*Z)d+d,Z*d-d.Z+d/d0Z,dS)4N) issubclass_ issubsctype issubdtype) set_module)ndarrayufuncasarray) rrr deprecatedeprecate_with_doc get_includeinfosourcewholookfor byte_bounds safe_evalcCsXddl}|jdurtjtj|jdd}|Sddlm}tjtj|jd}|S)a Return the directory that contains the NumPy \*.h header files. Extension modules that need to compile against NumPy should use this function to locate the appropriate include directory. Notes ----- When using ``distutils``, for example in ``setup.py``. :: import numpy as np ... Extension('extension_name', ... include_dirs=[np.get_include()]) ... rNcoreinclude) numpy show_configospathjoindirname__file__ numpy.corer)rdrr1/usr/lib/python3/dist-packages/numpy/lib/utils.pyr s  r cCs ||_|SN)__name__)funcnamerrr_set_function_name1sr#c@s"eZdZdZdddZddZdS) _Deprecatez Decorator class to deprecate old functions. Refer to `deprecate` for details. See Also -------- deprecate NcCs||_||_||_dSr)old_namenew_namemessage)selfr%r&r'rrr__init__Bs z_Deprecate.__init__csv|j}|j}|j}|durzj}Wn tyj}Ynw|dur(d|nd||f|dur8d|7fdd}t||}j}|durN}nR|d} t | dd} | d rj| d |}n't | dd} | ddD]} t | | krn | t | d7} qx|| d}t d | d |g}||_zj} Wn tyY|Sw|j| |S) z: Decorator call. Refer to ``decorate``. Nz`%s` is deprecated!z%`%s` is deprecated, use `%s` instead! cstjtdd|i|S)z1`arrayrange` is deprecated, use `arange` instead!) stacklevel)warningswarnDeprecationWarning)argskwdsdepdocr!rrnewfunc^sz$_Deprecate.__call__..newfuncr z )r%r&r'r AttributeErrorr#__doc__ expandtabssplit _get_indentlstriplentextwrapindentr__dict__update)r(r!r0kwargsr%r&r'r4doclinesr?skiplinerrr2r__call__GsT            z_Deprecate.__call__)NNN)r __module__ __qualname__r8r)rGrrrrr$6s r$cCsDtj}|D]}t|}|rt|t||}q|tjkr d}|S)zU Determines the leading whitespace that could be removed from all the lines. r)sysmaxsizer=r<min)rDr?rFcontentrrrr;s  r;cOs8|r|d}|dd}t|i||St|i|S)a Issues a DeprecationWarning, adds warning to `old_name`'s docstring, rebinds ``old_name.__name__`` and returns the new function object. This function may also be used as a decorator. Parameters ---------- func : function The function to be deprecated. old_name : str, optional The name of the function to be deprecated. Default is None, in which case the name of `func` is used. new_name : str, optional The new name for the function. Default is None, in which case the deprecation message is that `old_name` is deprecated. If given, the deprecation message is that `old_name` is deprecated and `new_name` should be used instead. message : str, optional Additional explanation of the deprecation. Displayed in the docstring after the warning. Returns ------- old_func : function The deprecated function. Examples -------- Note that ``olduint`` returns a value after printing Deprecation Warning: >>> olduint = np.deprecate(np.uint) DeprecationWarning: `uint64` is deprecated! # may vary >>> olduint(6) 6 rr5Nr$)r0rBfnrrrr s , r cCs t|dS)a Deprecates a function and includes the deprecation in its docstring. This function is used as a decorator. It returns an object that can be used to issue a DeprecationWarning, by passing the to-be decorated function as argument, this adds warning to the to-be decorated function's docstring and returns the new function object. See Also -------- deprecate : Decorate a function such that it issues a `DeprecationWarning` Parameters ---------- msg : str Additional explanation of the deprecation. Displayed in the docstring after the warning. Returns ------- obj : object )r'rN)msgrrrr s r c Cs|j}|dd}|d}|d}t|jj}|}}|dur*||j|7}||fSt||D]\}} | dkr@||d| 7}q/||d| 7}q/||7}||fS)a# Returns pointers to the end-points of an array. Parameters ---------- a : ndarray Input array. It must conform to the Python-side of the array interface. Returns ------- (low, high) : tuple of 2 integers The first integer is the first byte of the array, the second integer is just past the last byte of the array. If `a` is not contiguous it will not use every byte between the (`low`, `high`) values. Examples -------- >>> I = np.eye(2, dtype='f'); I.dtype dtype('float32') >>> low, high = np.byte_bounds(I) >>> high - low == I.size*I.itemsize True >>> I = np.eye(2); I.dtype dtype('float64') >>> low, high = np.byte_bounds(I) >>> high - low == I.size*I.itemsize True datarstridesshapeNr5)__array_interface__rdtypeitemsizesizezip) aaia_dataastridesashapebytes_aa_lowa_highrSstriderrrrs  rc Cs<|dur tj}|j}g}i}|D]D}t||trX||}t|}||vr6|d||}d}n|||<|}d}dt t |j } t |j } | || | |jj|gqd} d} d} d}tt|D]<}||}| t|dkr{t|d} | t|dkrt|d} | t|dkrt|d} |dr|t|d7}qgt|dkrtd| }td| }td| }d |d |d |d f}t|d d t|d d tt|D]9}||}td|dd |t|dd|dd |t|dd |dd |t|dd |dfqtd|dS)a% Print the NumPy arrays in the given dictionary. If there is no dictionary passed in or `vardict` is None then returns NumPy arrays in the globals() dictionary (all NumPy arrays in the namespace). Parameters ---------- vardict : dict, optional A dictionary possibly containing ndarrays. Default is globals(). Returns ------- out : None Returns 'None'. Notes ----- Prints out the name, shape, bytes and type of all of the ndarrays present in `vardict`. Examples -------- >>> a = np.arange(10) >>> b = np.ones(20) >>> np.who() Name Shape Bytes Type =========================================================== a 10 80 int64 b 20 160 float64 Upper bound on total bytes = 240 >>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str', ... 'idx':5} >>> np.who(d) Name Shape Bytes Type =========================================================== x 2 16 float64 y 3 24 float64 Upper bound on total bytes = 40 Nz (%s)rr5z x r+ zName %s Shape %s Bytes %s Typer6r*=z%s %s %s %s %s %s %sz' Upper bound on total bytes = %d)rJ _getframef_back f_globalskeys isinstanceridrmapstrrSnbytesappendrUr"ranger=intmaxprint)vardictframestacacher"varidvnamestroriginalshapestrbytestrmaxnamemaxshapemaxbyte totalbyteskvalsp1sp2sp3prvalrrrrsf,              rc Cst|}|}|}d}||}|D]4}||krd} n|} |t|t| }||kr?|dt|}|dd|d|}q|| |}q|S)Nz, r5z, r6r+)r=r:) r" argumentswidth firstwidthrnewstrsepstrarglistargumentaddstrrrr _split_lines rrcCst|ttg}|j|ji}|jg}|jg} t|dkr# ||fS|d}|D]&}t||t j rR||j}||vrR||j}| || ||||<q,q)NTr) __import__globalslocalsr r@r=poprjrktypes ModuleTyperp)modulethedictdictlist totraversethisdictxmodnamemoddictrrr _makenamedicts&       rc Cstd}d}dd}t|dt|}t|d|}|j}|jj}td||dtd|j|dtd ||dtd |j|dtd ||jj |dtd ||jj |dtd |jj |dtdt |j jj|f|dtdd|d|dvrtd|tj|f|dd} n#|dkrtd||f|dtjdk} ntd||f|dtjdk} td|| |dtd|j|ddS)aOProvide information about ndarray obj. Parameters ---------- obj : ndarray Must be ndarray, not checked. output Where printed output goes. Notes ----- Copied over from the numarray module prior to its removal. Adapted somewhat as only numpy is an option now. Called by info. rcSs|Srr)rrrrsz_info.. __class__r zclass: filezshape: z strides: z itemsize: z aligned: z contiguous: z fortran: zdata pointer: %s%sz byteorder: r6)endr)|rdz%s%s%sF>z%sbig%sbigz %slittle%slittlez byteswap: ztype: %sN)getattrtyperRrU byteorderrtrSrVflagsaligned contiguousfortranhexctypes_as_parameter_valuerJ) objoutputextraticbpclsnmrRendianbyteswaprrr_infos:   rLc CsFddl}ddl}t|dst|dr|j}nt|dr|j}|dur(ttdSt|tr5t||ddSt|t rt durDt |\a a d}g}t D]A}z6t ||} t | |vrbtd||dn|t | td ||dt| td ||d|d 7}WqJtyYqJw|dkrtd ||ddStd ||ddS||s||r|j} z t ||} Wn tyd} Ynwt| | |krt| | |} n| | } td| d|dt|||ddS||r|j} z t ||} Wn ty d} Ynwt| | |krt| | |} n| | } td| d|d||} | durFt|drEt||j|dn t|||d||}dd|D}|rtd|d|D]'}t||d}|dur|||p|d\}}td||f|dqfdSdSt|drt|||ddSdS)a Get help information for a function, class, or module. Parameters ---------- object : object or str, optional Input object or name to get information about. If `object` is a numpy object, its docstring is given. If it is a string, available modules are searched for matching objects. If None, information about `info` itself is returned. maxwidth : int, optional Printing width. output : file like object, optional File like object that the output is written to, default is ``stdout``. The object has to be opened in 'w' or 'a' mode. toplevel : str, optional Start search at this level. See Also -------- source, lookfor Notes ----- When used interactively with an object, ``np.info(obj)`` is equivalent to ``help(obj)`` on the Python prompt or ``obj?`` on the IPython prompt. Examples -------- >>> np.info(np.polyval) # doctest: +SKIP polyval(p, x) Evaluate the polynomial p at x. ... When using a string for `object` it is possible to get multiple results. >>> np.info('fft') # doctest: +SKIP *** Found in numpy *** Core FFT routines ... *** Found in numpy.fft *** fft(a, n=None, axis=-1) ... *** Repeat reference found in numpy.fft.fftpack *** *** Total of 3 references found. *** rN_ppimport_importer_ppimport_module_ppimport_attr)rz+ *** Repeat reference found in %s *** rz *** Found in %s ***-r5zHelp for %s not found.z+ *** Total of %d references found. ***z()r6r*r)cSsg|] }|ddkr|qS)r_r).0methrrr hszinfo..z Methods: Nonez %s -- %sr8)pydocinspecthasattrrrr rkrrrn _namedictr _dictlistrlrtrpKeyError isfunctionismethodr signature Exceptionr=rgetdocisclassr) allmethodsrsplitdoc)objectmaxwidthrtoplevelrrnumfoundobjlistr{rr"rargstrdoc1methodspublic_methodsrthisobjmethstrotherrrrr s4                     r cCsXddl}ztd|||dt|||dWdSty+td|dYdSw)a Print or write to a file the source code for a NumPy object. The source code is only returned for objects written in Python. Many functions and classes are defined in C and will therefore not return useful information. Parameters ---------- object : numpy object Input object. This can be any object (function, class, module, ...). output : file object, optional If `output` not supplied then source code is printed to screen (sys.stdout). File object must be created with either write 'w' or append 'a' modes. See Also -------- lookfor, info Examples -------- >>> np.source(np.interp) #doctest: +SKIP In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py def interp(x, xp, fp, left=None, right=None): """.... (full docstring printed)""" if isinstance(x, (float, int, number)): return compiled_interp([x], xp, fp, left, right).item() else: return compiled_interp(x, xp, fp, left, right) The source code is only returned for objects written in Python. >>> np.source(np.array) #doctest: +SKIP Not available for this object. rNz In file: %s rzNot available for this object.)rrt getsourcefile getsourcer)rrrrrrr ws) r z[a-z0-9_]+\(.*[,=].*\)TFc sddl}t|||g}t|sdSD] \}\}} } | dvr(q|tfddDr<||qdddddfd d fd d } |j| d dd } | dt | g} |dddD]=}|\} }dd dD}z|d }t |r|d }Wn tyd}Ynw| d||fqn|s| d|dur|d | dSt | dkr|}|d | dStd | dS)a Do a keyword search on docstrings. A list of objects that matched the search is displayed, sorted by relevance. All given keywords need to be found in the docstring for it to be returned as a result, but the order does not matter. Parameters ---------- what : str String containing words to look for. module : str or list, optional Name of module(s) whose docstrings to go through. import_modules : bool, optional Whether to import sub-modules in packages. Default is True. regenerate : bool, optional Whether to re-generate the docstring cache. Default is False. output : file-like, optional File-like object to write the output to. If omitted, use a pager. See Also -------- source, info Notes ----- Relevance is determined only roughly, by checking if the keywords occur in the function name, at the start of a docstring, etc. Examples -------- >>> np.lookfor('binary representation') # doctest: +SKIP Search results for 'binary representation' ------------------------------------------ numpy.binary_repr Return the binary representation of the input number as a string. numpy.core.setup_common.long_double_representation Given a binary dump as given by GNU od -b, look for long double numpy.base_repr Return a string representation of a number in the given base system. ... rN)rrc3s|]}|vVqdSrrrw)rCrr szlookfor..i)r!classrrcsd}d|ddd|tfddD7}|tfddD7}|t d7}||d7}|d  d 7}|t| d d 7}|S) Nrr*rfcg|]}|vrdqS)rr) first_docrrrz.lookfor..relevance..cr)rr)r"rrrrrer.rcdi) rlowerstripr:sumr=getcountrs)r"docstrkindindexr)kind_relevancewhats)rr"r relevances zlookfor..relevancecs|g|RSrr)rY)rxrrrrelevance_value sz lookfor..relevance_value)keyzSearch results for '%s'r6rcSsg|] }|r|qSr)r)rrFrrrrszlookfor..r*r5rz %s %szNothing found.rc)r_lookfor_generate_cachernrr:itemsallrpsortrr=r_function_signature_research IndexErrorwritegetpagerrt)whatrimport_modules regeneraterrfoundr" docstringrrrs help_textixdoclinesrpagerr)rxrCrrrrrsR/         rc Csddl}ddlm}|durd}t|tr-zt|Wn ty&iYSwtj|}nt|t s7t|t rIi}|D] }| t |||q;|St |tvrW|sWtt |Si}|tt |<i}d}|j|fg} | r| d\} } t | |vrzqid|t | <|d7}d} || rd} z| j} Wn tyd} Ynw|rt| d r| jD]l}t|D]d}tj||}tj||d }tj|r|d r|dd }n tj|r|}nq|d krqz(tj}tj}z|t_|t_td| |fW|t_|t_n|t_|t_wWqtyYqwqt| D]f\}}zt |dd| |f}t |dd}Wnt!yDd| |f}d}Ynwd|vrS|rSd||f}|"| dsdt|t#rbnq||sv| dusv|| vsvq| $d| |f|fqn&|%| rd} t| D]\}}| $d| |f|fqnt| drd} z|&| }Wn t!yd}Ynw|dur|| |f|| <| sl|S)a Generate docstring cache for given module. Parameters ---------- module : str, None, module Module for which to generate docstring cache import_modules : bool Whether to import sub-modules in packages. regenerate : bool Re-generate the docstring cache Returns ------- cache : dict {obj_full_name: (docstring, kind, index), ...} Docstring cache for the module, either cached one (regenerate=False) or newly generated. rN)StringIOrTr5rr__path__z __init__.pyz.pyr)z%s.%sr rHrrrGr!)'riorrkrnr ImportErrorrJmoduleslisttuplerArrl_lookfor_cachesr rismodule__all__r7rrrlistdirrrisfileendswithstdoutstderr BaseException _getmembersr NameError startswithrrprr)rr r rrrxmodseenrstackr"itemr_allpthmod_paththis_pyinit_py to_import old_stdout old_stderrnv item_namemod_namerCrrrr.s                         SrcsDddl}z|}W|Sty!fddtD}Y|Sw)Nrcs$g|]}t|r|t|fqSr)rr)rrr+rrrsz_getmembers..)r getmembersrdir)r+rmembersrr8rr%s  r%cCsddl}||S)a Protected string evaluation. Evaluate a string containing a Python literal expression without allowing the execution of arbitrary non-literal code. Parameters ---------- source : str The string to evaluate. Returns ------- obj : object The result of evaluating `source`. Raises ------ SyntaxError If the code has invalid Python syntax, or if it contains non-literal code. Examples -------- >>> np.safe_eval('1') 1 >>> np.safe_eval('[1, 2, 3]') [1, 2, 3] >>> np.safe_eval('{"foo": ("bar", 10.0)}') {'foo': ('bar', 10.0)} >>> np.safe_eval('import os') Traceback (most recent call last): ... SyntaxError: invalid syntax >>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()') Traceback (most recent call last): ... ValueError: malformed node or string: <_ast.Call object at 0x...> rN)ast literal_eval)r r<rrrrs, rcCs|jdkr|St|jd|d}tj|r|d}|jdkr?|dkr=|dur6|j tj |d<|}|S|j tj }|St | dkrMtj ||<|S)a@ Utility function to check median result from data for NaN values at the end and return NaN in that case. Input result can also be a MaskedArray. Parameters ---------- data : array Input data to median function result : Array or MaskedArray Result of median function axis : int Axis along which the median was computed. out : ndarray, optional Output array in which to place the result. Returns ------- median : scalar or ndarray Median or NaN in axes which contained NaN in the input. rr)axisFTN.) rWnpisnantakema isMaskedArrayfilledndimrUrnan count_nonzeroravel)rQresultr>outr4rrr_median_nanchecks     rKcCsrddlm}m}m}t|dkrt|dkrdSd|}|D]}||r.|d|d7}q|d|d7}q|S)a Returns a string contains the supported CPU features by the current build. The string format can be explained as follows: - dispatched features that are supported by the running machine end with `*`. - dispatched features that are "not" supported by the running machine end with `?`. - remained features are representing the baseline. r)__cpu_features____cpu_baseline____cpu_dispatch__rr6*?)numpy.core._multiarray_umathrLrMrNr=r)rLrMrNenabled_featuresfeaturerrr _opt_infos  rTr)r)NTFN)-rrJr>rrer-numpy.core.numerictypesrrrnumpy.core.overridesrrrrrrr?rr r#r$r;r r rrrrrrr"rr r rcompileIrrrr%rrKrTrrrrsR L5 9i 33 { 0 &