Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/numpy/lib/utils.py
7757 views
import os1import sys2import textwrap3import types4import re5import warnings67from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype8from numpy.core.overrides import set_module9from numpy.core import ndarray, ufunc, asarray10import numpy as np1112__all__ = [13'issubclass_', 'issubsctype', 'issubdtype', 'deprecate',14'deprecate_with_doc', 'get_include', 'info', 'source', 'who',15'lookfor', 'byte_bounds', 'safe_eval'16]1718def get_include():19"""20Return the directory that contains the NumPy \\*.h header files.2122Extension modules that need to compile against NumPy should use this23function to locate the appropriate include directory.2425Notes26-----27When using ``distutils``, for example in ``setup.py``.28::2930import numpy as np31...32Extension('extension_name', ...33include_dirs=[np.get_include()])34...3536"""37import numpy38if numpy.show_config is None:39# running from numpy source directory40d = os.path.join(os.path.dirname(numpy.__file__), 'core', 'include')41else:42# using installed numpy core headers43import numpy.core as core44d = os.path.join(os.path.dirname(core.__file__), 'include')45return d464748def _set_function_name(func, name):49func.__name__ = name50return func515253class _Deprecate:54"""55Decorator class to deprecate old functions.5657Refer to `deprecate` for details.5859See Also60--------61deprecate6263"""6465def __init__(self, old_name=None, new_name=None, message=None):66self.old_name = old_name67self.new_name = new_name68self.message = message6970def __call__(self, func, *args, **kwargs):71"""72Decorator call. Refer to ``decorate``.7374"""75old_name = self.old_name76new_name = self.new_name77message = self.message7879if old_name is None:80try:81old_name = func.__name__82except AttributeError:83old_name = func.__name__84if new_name is None:85depdoc = "`%s` is deprecated!" % old_name86else:87depdoc = "`%s` is deprecated, use `%s` instead!" % \88(old_name, new_name)8990if message is not None:91depdoc += "\n" + message9293def newfunc(*args,**kwds):94"""`arrayrange` is deprecated, use `arange` instead!"""95warnings.warn(depdoc, DeprecationWarning, stacklevel=2)96return func(*args, **kwds)9798newfunc = _set_function_name(newfunc, old_name)99doc = func.__doc__100if doc is None:101doc = depdoc102else:103lines = doc.expandtabs().split('\n')104indent = _get_indent(lines[1:])105if lines[0].lstrip():106# Indent the original first line to let inspect.cleandoc()107# dedent the docstring despite the deprecation notice.108doc = indent * ' ' + doc109else:110# Remove the same leading blank lines as cleandoc() would.111skip = len(lines[0]) + 1112for line in lines[1:]:113if len(line) > indent:114break115skip += len(line) + 1116doc = doc[skip:]117depdoc = textwrap.indent(depdoc, ' ' * indent)118doc = '\n\n'.join([depdoc, doc])119newfunc.__doc__ = doc120try:121d = func.__dict__122except AttributeError:123pass124else:125newfunc.__dict__.update(d)126return newfunc127128129def _get_indent(lines):130"""131Determines the leading whitespace that could be removed from all the lines.132"""133indent = sys.maxsize134for line in lines:135content = len(line.lstrip())136if content:137indent = min(indent, len(line) - content)138if indent == sys.maxsize:139indent = 0140return indent141142143def deprecate(*args, **kwargs):144"""145Issues a DeprecationWarning, adds warning to `old_name`'s146docstring, rebinds ``old_name.__name__`` and returns the new147function object.148149This function may also be used as a decorator.150151Parameters152----------153func : function154The function to be deprecated.155old_name : str, optional156The name of the function to be deprecated. Default is None, in157which case the name of `func` is used.158new_name : str, optional159The new name for the function. Default is None, in which case the160deprecation message is that `old_name` is deprecated. If given, the161deprecation message is that `old_name` is deprecated and `new_name`162should be used instead.163message : str, optional164Additional explanation of the deprecation. Displayed in the165docstring after the warning.166167Returns168-------169old_func : function170The deprecated function.171172Examples173--------174Note that ``olduint`` returns a value after printing Deprecation175Warning:176177>>> olduint = np.deprecate(np.uint)178DeprecationWarning: `uint64` is deprecated! # may vary179>>> olduint(6)1806181182"""183# Deprecate may be run as a function or as a decorator184# If run as a function, we initialise the decorator class185# and execute its __call__ method.186187if args:188fn = args[0]189args = args[1:]190191return _Deprecate(*args, **kwargs)(fn)192else:193return _Deprecate(*args, **kwargs)194195196def deprecate_with_doc(msg):197"""198Deprecates a function and includes the deprecation in its docstring.199200This function is used as a decorator. It returns an object that can be201used to issue a DeprecationWarning, by passing the to-be decorated202function as argument, this adds warning to the to-be decorated function's203docstring and returns the new function object.204205See Also206--------207deprecate : Decorate a function such that it issues a `DeprecationWarning`208209Parameters210----------211msg : str212Additional explanation of the deprecation. Displayed in the213docstring after the warning.214215Returns216-------217obj : object218219"""220return _Deprecate(message=msg)221222223#--------------------------------------------224# Determine if two arrays can share memory225#--------------------------------------------226227def byte_bounds(a):228"""229Returns pointers to the end-points of an array.230231Parameters232----------233a : ndarray234Input array. It must conform to the Python-side of the array235interface.236237Returns238-------239(low, high) : tuple of 2 integers240The first integer is the first byte of the array, the second241integer is just past the last byte of the array. If `a` is not242contiguous it will not use every byte between the (`low`, `high`)243values.244245Examples246--------247>>> I = np.eye(2, dtype='f'); I.dtype248dtype('float32')249>>> low, high = np.byte_bounds(I)250>>> high - low == I.size*I.itemsize251True252>>> I = np.eye(2); I.dtype253dtype('float64')254>>> low, high = np.byte_bounds(I)255>>> high - low == I.size*I.itemsize256True257258"""259ai = a.__array_interface__260a_data = ai['data'][0]261astrides = ai['strides']262ashape = ai['shape']263bytes_a = asarray(a).dtype.itemsize264265a_low = a_high = a_data266if astrides is None:267# contiguous case268a_high += a.size * bytes_a269else:270for shape, stride in zip(ashape, astrides):271if stride < 0:272a_low += (shape-1)*stride273else:274a_high += (shape-1)*stride275a_high += bytes_a276return a_low, a_high277278279#-----------------------------------------------------------------------------280# Function for output and information on the variables used.281#-----------------------------------------------------------------------------282283284def who(vardict=None):285"""286Print the NumPy arrays in the given dictionary.287288If there is no dictionary passed in or `vardict` is None then returns289NumPy arrays in the globals() dictionary (all NumPy arrays in the290namespace).291292Parameters293----------294vardict : dict, optional295A dictionary possibly containing ndarrays. Default is globals().296297Returns298-------299out : None300Returns 'None'.301302Notes303-----304Prints out the name, shape, bytes and type of all of the ndarrays305present in `vardict`.306307Examples308--------309>>> a = np.arange(10)310>>> b = np.ones(20)311>>> np.who()312Name Shape Bytes Type313===========================================================314a 10 80 int64315b 20 160 float64316Upper bound on total bytes = 240317318>>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str',319... 'idx':5}320>>> np.who(d)321Name Shape Bytes Type322===========================================================323x 2 16 float64324y 3 24 float64325Upper bound on total bytes = 40326327"""328if vardict is None:329frame = sys._getframe().f_back330vardict = frame.f_globals331sta = []332cache = {}333for name in vardict.keys():334if isinstance(vardict[name], ndarray):335var = vardict[name]336idv = id(var)337if idv in cache.keys():338namestr = name + " (%s)" % cache[idv]339original = 0340else:341cache[idv] = name342namestr = name343original = 1344shapestr = " x ".join(map(str, var.shape))345bytestr = str(var.nbytes)346sta.append([namestr, shapestr, bytestr, var.dtype.name,347original])348349maxname = 0350maxshape = 0351maxbyte = 0352totalbytes = 0353for val in sta:354if maxname < len(val[0]):355maxname = len(val[0])356if maxshape < len(val[1]):357maxshape = len(val[1])358if maxbyte < len(val[2]):359maxbyte = len(val[2])360if val[4]:361totalbytes += int(val[2])362363if len(sta) > 0:364sp1 = max(10, maxname)365sp2 = max(10, maxshape)366sp3 = max(10, maxbyte)367prval = "Name %s Shape %s Bytes %s Type" % (sp1*' ', sp2*' ', sp3*' ')368print(prval + "\n" + "="*(len(prval)+5) + "\n")369370for val in sta:371print("%s %s %s %s %s %s %s" % (val[0], ' '*(sp1-len(val[0])+4),372val[1], ' '*(sp2-len(val[1])+5),373val[2], ' '*(sp3-len(val[2])+5),374val[3]))375print("\nUpper bound on total bytes = %d" % totalbytes)376return377378#-----------------------------------------------------------------------------379380381# NOTE: pydoc defines a help function which works similarly to this382# except it uses a pager to take over the screen.383384# combine name and arguments and split to multiple lines of width385# characters. End lines on a comma and begin argument list indented with386# the rest of the arguments.387def _split_line(name, arguments, width):388firstwidth = len(name)389k = firstwidth390newstr = name391sepstr = ", "392arglist = arguments.split(sepstr)393for argument in arglist:394if k == firstwidth:395addstr = ""396else:397addstr = sepstr398k = k + len(argument) + len(addstr)399if k > width:400k = firstwidth + 1 + len(argument)401newstr = newstr + ",\n" + " "*(firstwidth+2) + argument402else:403newstr = newstr + addstr + argument404return newstr405406_namedict = None407_dictlist = None408409# Traverse all module directories underneath globals410# to see if something is defined411def _makenamedict(module='numpy'):412module = __import__(module, globals(), locals(), [])413thedict = {module.__name__:module.__dict__}414dictlist = [module.__name__]415totraverse = [module.__dict__]416while True:417if len(totraverse) == 0:418break419thisdict = totraverse.pop(0)420for x in thisdict.keys():421if isinstance(thisdict[x], types.ModuleType):422modname = thisdict[x].__name__423if modname not in dictlist:424moddict = thisdict[x].__dict__425dictlist.append(modname)426totraverse.append(moddict)427thedict[modname] = moddict428return thedict, dictlist429430431def _info(obj, output=sys.stdout):432"""Provide information about ndarray obj.433434Parameters435----------436obj : ndarray437Must be ndarray, not checked.438output439Where printed output goes.440441Notes442-----443Copied over from the numarray module prior to its removal.444Adapted somewhat as only numpy is an option now.445446Called by info.447448"""449extra = ""450tic = ""451bp = lambda x: x452cls = getattr(obj, '__class__', type(obj))453nm = getattr(cls, '__name__', cls)454strides = obj.strides455endian = obj.dtype.byteorder456457print("class: ", nm, file=output)458print("shape: ", obj.shape, file=output)459print("strides: ", strides, file=output)460print("itemsize: ", obj.itemsize, file=output)461print("aligned: ", bp(obj.flags.aligned), file=output)462print("contiguous: ", bp(obj.flags.contiguous), file=output)463print("fortran: ", obj.flags.fortran, file=output)464print(465"data pointer: %s%s" % (hex(obj.ctypes._as_parameter_.value), extra),466file=output467)468print("byteorder: ", end=' ', file=output)469if endian in ['|', '=']:470print("%s%s%s" % (tic, sys.byteorder, tic), file=output)471byteswap = False472elif endian == '>':473print("%sbig%s" % (tic, tic), file=output)474byteswap = sys.byteorder != "big"475else:476print("%slittle%s" % (tic, tic), file=output)477byteswap = sys.byteorder != "little"478print("byteswap: ", bp(byteswap), file=output)479print("type: %s" % obj.dtype, file=output)480481482@set_module('numpy')483def info(object=None, maxwidth=76, output=sys.stdout, toplevel='numpy'):484"""485Get help information for a function, class, or module.486487Parameters488----------489object : object or str, optional490Input object or name to get information about. If `object` is a491numpy object, its docstring is given. If it is a string, available492modules are searched for matching objects. If None, information493about `info` itself is returned.494maxwidth : int, optional495Printing width.496output : file like object, optional497File like object that the output is written to, default is498``stdout``. The object has to be opened in 'w' or 'a' mode.499toplevel : str, optional500Start search at this level.501502See Also503--------504source, lookfor505506Notes507-----508When used interactively with an object, ``np.info(obj)`` is equivalent509to ``help(obj)`` on the Python prompt or ``obj?`` on the IPython510prompt.511512Examples513--------514>>> np.info(np.polyval) # doctest: +SKIP515polyval(p, x)516Evaluate the polynomial p at x.517...518519When using a string for `object` it is possible to get multiple results.520521>>> np.info('fft') # doctest: +SKIP522*** Found in numpy ***523Core FFT routines524...525*** Found in numpy.fft ***526fft(a, n=None, axis=-1)527...528*** Repeat reference found in numpy.fft.fftpack ***529*** Total of 3 references found. ***530531"""532global _namedict, _dictlist533# Local import to speed up numpy's import time.534import pydoc535import inspect536537if (hasattr(object, '_ppimport_importer') or538hasattr(object, '_ppimport_module')):539object = object._ppimport_module540elif hasattr(object, '_ppimport_attr'):541object = object._ppimport_attr542543if object is None:544info(info)545elif isinstance(object, ndarray):546_info(object, output=output)547elif isinstance(object, str):548if _namedict is None:549_namedict, _dictlist = _makenamedict(toplevel)550numfound = 0551objlist = []552for namestr in _dictlist:553try:554obj = _namedict[namestr][object]555if id(obj) in objlist:556print("\n "557"*** Repeat reference found in %s *** " % namestr,558file=output559)560else:561objlist.append(id(obj))562print(" *** Found in %s ***" % namestr, file=output)563info(obj)564print("-"*maxwidth, file=output)565numfound += 1566except KeyError:567pass568if numfound == 0:569print("Help for %s not found." % object, file=output)570else:571print("\n "572"*** Total of %d references found. ***" % numfound,573file=output574)575576elif inspect.isfunction(object) or inspect.ismethod(object):577name = object.__name__578try:579arguments = str(inspect.signature(object))580except Exception:581arguments = "()"582583if len(name+arguments) > maxwidth:584argstr = _split_line(name, arguments, maxwidth)585else:586argstr = name + arguments587588print(" " + argstr + "\n", file=output)589print(inspect.getdoc(object), file=output)590591elif inspect.isclass(object):592name = object.__name__593try:594arguments = str(inspect.signature(object))595except Exception:596arguments = "()"597598if len(name+arguments) > maxwidth:599argstr = _split_line(name, arguments, maxwidth)600else:601argstr = name + arguments602603print(" " + argstr + "\n", file=output)604doc1 = inspect.getdoc(object)605if doc1 is None:606if hasattr(object, '__init__'):607print(inspect.getdoc(object.__init__), file=output)608else:609print(inspect.getdoc(object), file=output)610611methods = pydoc.allmethods(object)612613public_methods = [meth for meth in methods if meth[0] != '_']614if public_methods:615print("\n\nMethods:\n", file=output)616for meth in public_methods:617thisobj = getattr(object, meth, None)618if thisobj is not None:619methstr, other = pydoc.splitdoc(620inspect.getdoc(thisobj) or "None"621)622print(" %s -- %s" % (meth, methstr), file=output)623624elif hasattr(object, '__doc__'):625print(inspect.getdoc(object), file=output)626627628@set_module('numpy')629def source(object, output=sys.stdout):630"""631Print or write to a file the source code for a NumPy object.632633The source code is only returned for objects written in Python. Many634functions and classes are defined in C and will therefore not return635useful information.636637Parameters638----------639object : numpy object640Input object. This can be any object (function, class, module,641...).642output : file object, optional643If `output` not supplied then source code is printed to screen644(sys.stdout). File object must be created with either write 'w' or645append 'a' modes.646647See Also648--------649lookfor, info650651Examples652--------653>>> np.source(np.interp) #doctest: +SKIP654In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py655def interp(x, xp, fp, left=None, right=None):656\"\"\".... (full docstring printed)\"\"\"657if isinstance(x, (float, int, number)):658return compiled_interp([x], xp, fp, left, right).item()659else:660return compiled_interp(x, xp, fp, left, right)661662The source code is only returned for objects written in Python.663664>>> np.source(np.array) #doctest: +SKIP665Not available for this object.666667"""668# Local import to speed up numpy's import time.669import inspect670try:671print("In file: %s\n" % inspect.getsourcefile(object), file=output)672print(inspect.getsource(object), file=output)673except Exception:674print("Not available for this object.", file=output)675676677# Cache for lookfor: {id(module): {name: (docstring, kind, index), ...}...}678# where kind: "func", "class", "module", "object"679# and index: index in breadth-first namespace traversal680_lookfor_caches = {}681682# regexp whose match indicates that the string may contain a function683# signature684_function_signature_re = re.compile(r"[a-z0-9_]+\(.*[,=].*\)", re.I)685686687@set_module('numpy')688def lookfor(what, module=None, import_modules=True, regenerate=False,689output=None):690"""691Do a keyword search on docstrings.692693A list of objects that matched the search is displayed,694sorted by relevance. All given keywords need to be found in the695docstring for it to be returned as a result, but the order does696not matter.697698Parameters699----------700what : str701String containing words to look for.702module : str or list, optional703Name of module(s) whose docstrings to go through.704import_modules : bool, optional705Whether to import sub-modules in packages. Default is True.706regenerate : bool, optional707Whether to re-generate the docstring cache. Default is False.708output : file-like, optional709File-like object to write the output to. If omitted, use a pager.710711See Also712--------713source, info714715Notes716-----717Relevance is determined only roughly, by checking if the keywords occur718in the function name, at the start of a docstring, etc.719720Examples721--------722>>> np.lookfor('binary representation') # doctest: +SKIP723Search results for 'binary representation'724------------------------------------------725numpy.binary_repr726Return the binary representation of the input number as a string.727numpy.core.setup_common.long_double_representation728Given a binary dump as given by GNU od -b, look for long double729numpy.base_repr730Return a string representation of a number in the given base system.731...732733"""734import pydoc735736# Cache737cache = _lookfor_generate_cache(module, import_modules, regenerate)738739# Search740# XXX: maybe using a real stemming search engine would be better?741found = []742whats = str(what).lower().split()743if not whats:744return745746for name, (docstring, kind, index) in cache.items():747if kind in ('module', 'object'):748# don't show modules or objects749continue750doc = docstring.lower()751if all(w in doc for w in whats):752found.append(name)753754# Relevance sort755# XXX: this is full Harrison-Stetson heuristics now,756# XXX: it probably could be improved757758kind_relevance = {'func': 1000, 'class': 1000,759'module': -1000, 'object': -1000}760761def relevance(name, docstr, kind, index):762r = 0763# do the keywords occur within the start of the docstring?764first_doc = "\n".join(docstr.lower().strip().split("\n")[:3])765r += sum([200 for w in whats if w in first_doc])766# do the keywords occur in the function name?767r += sum([30 for w in whats if w in name])768# is the full name long?769r += -len(name) * 5770# is the object of bad type?771r += kind_relevance.get(kind, -1000)772# is the object deep in namespace hierarchy?773r += -name.count('.') * 10774r += max(-index / 100, -100)775return r776777def relevance_value(a):778return relevance(a, *cache[a])779found.sort(key=relevance_value)780781# Pretty-print782s = "Search results for '%s'" % (' '.join(whats))783help_text = [s, "-"*len(s)]784for name in found[::-1]:785doc, kind, ix = cache[name]786787doclines = [line.strip() for line in doc.strip().split("\n")788if line.strip()]789790# find a suitable short description791try:792first_doc = doclines[0].strip()793if _function_signature_re.search(first_doc):794first_doc = doclines[1].strip()795except IndexError:796first_doc = ""797help_text.append("%s\n %s" % (name, first_doc))798799if not found:800help_text.append("Nothing found.")801802# Output803if output is not None:804output.write("\n".join(help_text))805elif len(help_text) > 10:806pager = pydoc.getpager()807pager("\n".join(help_text))808else:809print("\n".join(help_text))810811def _lookfor_generate_cache(module, import_modules, regenerate):812"""813Generate docstring cache for given module.814815Parameters816----------817module : str, None, module818Module for which to generate docstring cache819import_modules : bool820Whether to import sub-modules in packages.821regenerate : bool822Re-generate the docstring cache823824Returns825-------826cache : dict {obj_full_name: (docstring, kind, index), ...}827Docstring cache for the module, either cached one (regenerate=False)828or newly generated.829830"""831# Local import to speed up numpy's import time.832import inspect833834from io import StringIO835836if module is None:837module = "numpy"838839if isinstance(module, str):840try:841__import__(module)842except ImportError:843return {}844module = sys.modules[module]845elif isinstance(module, list) or isinstance(module, tuple):846cache = {}847for mod in module:848cache.update(_lookfor_generate_cache(mod, import_modules,849regenerate))850return cache851852if id(module) in _lookfor_caches and not regenerate:853return _lookfor_caches[id(module)]854855# walk items and collect docstrings856cache = {}857_lookfor_caches[id(module)] = cache858seen = {}859index = 0860stack = [(module.__name__, module)]861while stack:862name, item = stack.pop(0)863if id(item) in seen:864continue865seen[id(item)] = True866867index += 1868kind = "object"869870if inspect.ismodule(item):871kind = "module"872try:873_all = item.__all__874except AttributeError:875_all = None876877# import sub-packages878if import_modules and hasattr(item, '__path__'):879for pth in item.__path__:880for mod_path in os.listdir(pth):881this_py = os.path.join(pth, mod_path)882init_py = os.path.join(pth, mod_path, '__init__.py')883if (os.path.isfile(this_py) and884mod_path.endswith('.py')):885to_import = mod_path[:-3]886elif os.path.isfile(init_py):887to_import = mod_path888else:889continue890if to_import == '__init__':891continue892893try:894old_stdout = sys.stdout895old_stderr = sys.stderr896try:897sys.stdout = StringIO()898sys.stderr = StringIO()899__import__("%s.%s" % (name, to_import))900finally:901sys.stdout = old_stdout902sys.stderr = old_stderr903# Catch SystemExit, too904except (Exception, SystemExit):905continue906907for n, v in _getmembers(item):908try:909item_name = getattr(v, '__name__', "%s.%s" % (name, n))910mod_name = getattr(v, '__module__', None)911except NameError:912# ref. SWIG's global cvars913# NameError: Unknown C global variable914item_name = "%s.%s" % (name, n)915mod_name = None916if '.' not in item_name and mod_name:917item_name = "%s.%s" % (mod_name, item_name)918919if not item_name.startswith(name + '.'):920# don't crawl "foreign" objects921if isinstance(v, ufunc):922# ... unless they are ufuncs923pass924else:925continue926elif not (inspect.ismodule(v) or _all is None or n in _all):927continue928stack.append(("%s.%s" % (name, n), v))929elif inspect.isclass(item):930kind = "class"931for n, v in _getmembers(item):932stack.append(("%s.%s" % (name, n), v))933elif hasattr(item, "__call__"):934kind = "func"935936try:937doc = inspect.getdoc(item)938except NameError:939# ref SWIG's NameError: Unknown C global variable940doc = None941if doc is not None:942cache[name] = (doc, kind, index)943944return cache945946def _getmembers(item):947import inspect948try:949members = inspect.getmembers(item)950except Exception:951members = [(x, getattr(item, x)) for x in dir(item)952if hasattr(item, x)]953return members954955956def safe_eval(source):957"""958Protected string evaluation.959960Evaluate a string containing a Python literal expression without961allowing the execution of arbitrary non-literal code.962963Parameters964----------965source : str966The string to evaluate.967968Returns969-------970obj : object971The result of evaluating `source`.972973Raises974------975SyntaxError976If the code has invalid Python syntax, or if it contains977non-literal code.978979Examples980--------981>>> np.safe_eval('1')9821983>>> np.safe_eval('[1, 2, 3]')984[1, 2, 3]985>>> np.safe_eval('{"foo": ("bar", 10.0)}')986{'foo': ('bar', 10.0)}987988>>> np.safe_eval('import os')989Traceback (most recent call last):990...991SyntaxError: invalid syntax992993>>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()')994Traceback (most recent call last):995...996ValueError: malformed node or string: <_ast.Call object at 0x...>997998"""999# Local import to speed up numpy's import time.1000import ast1001return ast.literal_eval(source)100210031004def _median_nancheck(data, result, axis):1005"""1006Utility function to check median result from data for NaN values at the end1007and return NaN in that case. Input result can also be a MaskedArray.10081009Parameters1010----------1011data : array1012Sorted input data to median function1013result : Array or MaskedArray1014Result of median function.1015axis : int1016Axis along which the median was computed.10171018Returns1019-------1020result : scalar or ndarray1021Median or NaN in axes which contained NaN in the input. If the input1022was an array, NaN will be inserted in-place. If a scalar, either the1023input itself or a scalar NaN.1024"""1025if data.size == 0:1026return result1027n = np.isnan(data.take(-1, axis=axis))1028# masked NaN values are ok1029if np.ma.isMaskedArray(n):1030n = n.filled(False)1031if np.count_nonzero(n.ravel()) > 0:1032# Without given output, it is possible that the current result is a1033# numpy scalar, which is not writeable. If so, just return nan.1034if isinstance(result, np.generic):1035return data.dtype.type(np.nan)10361037result[n] = np.nan1038return result10391040def _opt_info():1041"""1042Returns a string contains the supported CPU features by the current build.10431044The string format can be explained as follows:1045- dispatched features that are supported by the running machine1046end with `*`.1047- dispatched features that are "not" supported by the running machine1048end with `?`.1049- remained features are representing the baseline.1050"""1051from numpy.core._multiarray_umath import (1052__cpu_features__, __cpu_baseline__, __cpu_dispatch__1053)10541055if len(__cpu_baseline__) == 0 and len(__cpu_dispatch__) == 0:1056return ''10571058enabled_features = ' '.join(__cpu_baseline__)1059for feature in __cpu_dispatch__:1060if __cpu_features__[feature]:1061enabled_features += f" {feature}*"1062else:1063enabled_features += f" {feature}?"10641065return enabled_features1066#-----------------------------------------------------------------------------106710681069