U C^" @sddlmZmZmZddlZddlZddlZddlZddlZddl m Z m Z m Z ddl mZddlmZmZmZddlZddlmZmZddd d d d d dddddg Zdd ZddZGdddeZddZdd ZddZddZ d4ddZ!dd Z"da#da$d5d"d#Z%ej&fd$d%Z'ed!dd&ej&d!fd'd Z(ed!ej&fd(dZ)ia*e+d)ej,Z-ed!d6d,dZ.d-d.Z/d/d0Z0d1dZ1d2d3Z2dS)7)divisionabsolute_importprint_functionN) issubclass_ issubsctype issubdtype) set_module)ndarrayufuncasarray) getargspec formatargspecrrr deprecatedeprecate_with_doc get_includeinfosourcewholookfor byte_bounds safe_evalcCsVddl}|jdkr.tjtj|jdd}n$ddlm}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) numpyZ show_configospathjoindirname__file__ numpy.corer)rdrr!2/tmp/pip-install-6_kvzl1k/numpy/numpy/lib/utils.pyrs   cCs ||_|SN)__name__)funcnamer!r!r"_set_function_name5sr'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+r!r!r"__init__Fsz_Deprecate.__init__csn|j}|j}|j}|dkr@z j}Wntk r>j}YnX|dkrRd|n d||f|dk rrd|7fdd}t||}j}|dkr}n|d} t | dd} | d r| d |}nRt | dd} | ddD](} t | | kr q| t | d7} q|| d}d |g}||_z j } Wntk r\YnX|j | |S) z: Decorator call. Refer to ``decorate``. Nz`%s` is deprecated!z%`%s` is deprecated, use `%s` instead! cstjtdd||S)z1`arrayrange` is deprecated, use `arange` instead!) stacklevel)warningswarnDeprecationWarning)argskwdsZdepdocr%r!r"newfuncbsz$_Deprecate.__call__..newfuncr z )r)r*r+r$AttributeErrorr'__doc__ expandtabssplit _get_indentlstriplenr__dict__update)r,r%r4kwargsr)r*r+r7doclinesindentskipliner r!r6r"__call__KsL         z_Deprecate.__call__)NNN)r$ __module__ __qualname__r;r-rIr!r!r!r"r(:s r(cCsDtj}|D]&}t|}|r t|t||}q |tjkr@d}|S)zU Determines the leading whitespace that could be removed from all the lines. r)sysmaxsizer@r?min)rErFrHcontentr!r!r"r>s  r>cOs4|r&|d}|dd}t|||St||SdS)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 rr8Nr()r4rCfnr!r!r"rs , cCs t|dS)N)r+rP)msgr!r!r"rSc Cs|j}|dd}|d}|d}t|jj}|}}|dkrN||j|7}nFt||D]2\}} | dkrz||d| 7}qX||d| 7}qX||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 datarstridesshapeNr8)Z__array_interface__r dtypeitemsizesizezip) aZaiZa_dataZastridesZashapeZbytes_aZa_lowZa_highrWZstrider!r!r"rs   c CsD|dkrtj}|j}g}i}|D]}t||tr(||}t|}||krl|d||}d}n|||<|}d}dt t |j } t |j } | || | |jj|gq(d} d} d} d}tt|D]|}||}| t|dkrt|d} | t|dkrt|d} | t|dkr2t|d} |dr|t|d7}qt|dkrtd| }td| }td| }d |d |d |d f}t|d d t|d d tt|D]t}||}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)rr8z x r/ zName %s Shape %s Bytes %s Typer9r.=z%s %s %s %s %s %s %sz' Upper bound on total bytes = %d)rL _getframef_back f_globalskeys isinstancer idrmapstrrWnbytesappendrXr&ranger@intmaxprint)vardictframeZstacacher&varZidvnamestroriginalZshapestrZbytestrZmaxnameZmaxshapeZmaxbyteZ totalbyteskvalZsp1Zsp2Zsp3Zprvalr!r!r"rsf,              c Cst|}|}|}d}||}|D]h}||kr4d} n|} |t|t| }||kr~|dt|}|dd|d|}q"|| |}q"|S)N, r8z, r9r/)r@r=) r& argumentswidthZ firstwidthrvZnewstrZsepstrarglistargumentZaddstrr!r!r" _split_lineps r~rcCst|ttg}|j|ji}|jg}|jg}t|dkr. __class__r$zclass: filezshape: z strides: z itemsize: z aligned: z contiguous: z fortran: zdata pointer: %s%sz byteorder: r9)endr)|r_z%s%s%sF>z%sbig%sbigz %slittle%slittlez byteswap: ztype: %sN)getattrtyperVrX byteorderrorWrYflagsZaligned contiguousZfortranhexctypesZ_as_parameter_valuerL) objoutputextraZticZbpclsnmrVZendianZbyteswapr!r!r"_infos:     rLc Csdddl}ddl}t|ds$t|dr,|j}nt|dr<|j}|dkrPttnt|trjt||dnt|t rPt dkrt |\a a d}g}t D]}zlt ||} t | |krtd||dn6|t | td ||dt| td ||d|d 7}Wqtk rYqXq|dkr>> 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. *** rNZ_ppimport_importer_ppimport_module_ppimport_attr)rz+ *** Repeat reference found in %s *** rz *** Found in %s ***-r8zHelp for %s not found.z+ *** Total of %d references found. ***r9r.z()r-rx(z Methods: _Nonez %s -- %srazInstance of class: rIr&z%szr;))pydocinspecthasattrrrrrfr rri _namedictr _dictlistrgrorkKeyError isfunctionr$r r r@r~getdocisclassr-__func__r=r ExceptionZ allmethodsrZsplitdocrL version_inforZ InstanceTyperrIr&ismethod)objectZmaxwidthrtoplevelrrZnumfoundZobjlistrtrr&rzZargstrr|Zdoc1methodsmethZthisobjZmethstrotherrDr!r!r"rs4                                     cCsZddl}z,td|||dt|||dWn tk rTtd|dYnXdS)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.)rro getsourcefile getsourcer)rrrr!r!r"rs )z[a-z0-9_]+\(.*[,=].*\)TFc sddl}t|||g}t|s0dSD]@\}\}} } | dkrPq8|tfddDr8||q8dddddfd d fd d } |j| d dd } | dt | g} |dddD]}|\} }dd dD}z(|d }t |r,|d }Wntk rHd}YnX| d||fq|sn| d|dk r|d | n4t | dkr|}|d | ntd | 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|]}|kVqdSr#r!.0w)rDr!r" szlookfor..i)r%classrrcsd}d|ddd|tfddD7}|tfddD7}|t d7}||d7}|d  d 7}|t| d d 7}|S) Nrr.racsg|]}|krdqS)r!r) first_docr!r" &sz.lookfor..relevance..csg|]}|krdqS)r!r)r&r!r"r(sr`r.r^di) rlowerstripr=sumr@getcountrn)r&Zdocstrkindindexr)kind_relevancewhats)rr&r" relevance"s zlookfor..relevancecs|f|Sr#r!)r\)rrrr!r"relevance_value2sz lookfor..relevance_value)keyzSearch results for '%s'r9rcSsg|]}|r|qSr!)r)rrHr!r!r"r<szlookfor..r.r8ryz %s %szNothing found.r^)r_lookfor_generate_cacherirr=itemsallrksortrr@r_function_signature_research IndexErrorwriteZgetpagerro)whatrimport_modules regeneraterrfoundr&Z docstringrrrs help_textixZdoclinesrZpagerr!)rrrDrrrr"rsN/        c Csddl}tjddkr$ddlm}n ddlm}|dkrd } z | j} Wntk r`d} YnX|rbt| d rb| jD]}t|D]}tj||}tj||d }tj|r|d r|dd }ntj|r|}nq|dkrqzDtj}tj}z$|t_|t_td| |fW5|t_|t_XWntk rXYqYnXqqzt | D]\}}z$t!|dd| |f}t!|dd}Wn&t"k rd| |f}d}YnXd|kr|rd||f}|#| dst|t$rjnqjn$||s"| dks"|| ks"qj| %d| |f|fqjnL|&| rzd} t | D] \}}| %d| |f|fqVnt| drd} z|'| }Wnt"k rd}YnX|dk r|| |f|| <q|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. rNra)StringIOrTr8rr__path__z __init__.pyz.pyr-z%s.%sr$rJrrrIr%)(rrLriorrfrir ImportErrormoduleslisttuplerBrrg_lookfor_cachesr$rismodule__all__r:rrrlistdirrrisfileendswithstdoutstderr BaseException _getmembersr NameError startswithr rkrr)rrrrrrrmodseenrstackr&itemrZ_allpthZmod_pathZthis_pyZinit_pyZ to_importZ old_stdoutZ old_stderrnvZ item_namemod_namerDr!r!r"rTs                        rcsFddl}z|}Wn*tk r@fddtD}YnX|S)Nrcs$g|]}t|r|t|fqSr!)rr)rrrr!r"rs z_getmembers..)r getmembersrdir)rrmembersr!rr"rs rcCsddl}||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)rrr!r!r"rs,cCs|jdkr|St||d}t|d}tj|r@|d}|jdkr|dkr|dk rr|j tj |d<|}q|j tj }nt | dkrtj ||<|S)aj 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, sequence of int, None}, optional Axis or axes 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).rFTN.) rZnpZmoveaxisisnanmaZ isMaskedArrayZfilledndimrXrnanZ count_nonzeroZravel)rUresultZaxisoutrr!r!r"_median_nanchecks     r )N)r)NTFN)3 __future__rrrrrLrrer1Znumpy.core.numerictypesrrrZnumpy.core.overridesrrr r r rrZ numpy.compatr r rrr'rr(r>rrrrr~rrrrrrrrcompileIrrrrrr r!r!r!r"sh K49 i 3N3 {  0