# File: numpy-main/doc/neps/conf.py from datetime import datetime extensions = ['sphinx.ext.imgmath', 'sphinx.ext.intersphinx'] templates_path = ['../source/_templates/'] source_suffix = '.rst' master_doc = 'content' project = 'NumPy Enhancement Proposals' year = datetime.now().year copyright = f'2017-{year}, NumPy Developers' author = 'NumPy Developers' title = 'NumPy Enhancement Proposals Documentation' version = '' release = '' language = 'en' exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] pygments_style = 'sphinx' todo_include_todos = False html_theme = 'pydata_sphinx_theme' html_logo = '../source/_static/numpylogo.svg' html_favicon = '../source/_static/favicon/favicon.ico' html_theme_options = {'github_url': 'https://github.com/numpy/numpy', 'external_links': [{'name': 'Wishlist', 'url': 'https://github.com/numpy/numpy/issues?q=is%3Aopen+is%3Aissue+label%3A%2223+-+Wish+List%22'}], 'show_prev_next': False} html_title = '%s' % project html_static_path = ['../source/_static'] html_last_updated_fmt = '%b %d, %Y' html_use_modindex = True html_copy_source = False html_domain_indices = False html_file_suffix = '.html' if 'sphinx.ext.pngmath' in extensions: pngmath_use_preview = True pngmath_dvipng_args = ['-gamma', '1.5', '-D', '96', '-bg', 'Transparent'] plot_html_show_formats = False plot_html_show_source_link = False htmlhelp_basename = 'NumPyEnhancementProposalsdoc' latex_elements = {} latex_documents = [(master_doc, 'NumPyEnhancementProposals.tex', title, 'NumPy Developers', 'manual')] man_pages = [(master_doc, 'numpyenhancementproposals', title, [author], 1)] texinfo_documents = [(master_doc, 'NumPyEnhancementProposals', title, author, 'NumPyEnhancementProposals', 'One line description of project.', 'Miscellaneous')] intersphinx_mapping = {'python': ('https://docs.python.org/dev', None), 'numpy': ('https://numpy.org/devdocs', None), 'scipy': ('https://docs.scipy.org/doc/scipy/reference', None), 'matplotlib': ('https://matplotlib.org', None)} # File: numpy-main/doc/neps/nep-0016-benchmark.py import perf import abc import numpy as np class NotArray: pass class AttrArray: __array_implementer__ = True class ArrayBase(abc.ABC): pass class ABCArray1(ArrayBase): pass class ABCArray2: pass ArrayBase.register(ABCArray2) not_array = NotArray() attr_array = AttrArray() abc_array_1 = ABCArray1() abc_array_2 = ABCArray2() isinstance(not_array, ArrayBase) isinstance(abc_array_1, ArrayBase) isinstance(abc_array_2, ArrayBase) runner = perf.Runner() def t(name, statement): runner.timeit(name, statement, globals=globals()) t('np.asarray([])', 'np.asarray([])') arrobj = np.array([]) t('np.asarray(arrobj)', 'np.asarray(arrobj)') t('attr, False', "getattr(not_array, '__array_implementer__', False)") t('attr, True', "getattr(attr_array, '__array_implementer__', False)") t('ABC, False', 'isinstance(not_array, ArrayBase)') t('ABC, True, via inheritance', 'isinstance(abc_array_1, ArrayBase)') t('ABC, True, via register', 'isinstance(abc_array_2, ArrayBase)') # File: numpy-main/doc/neps/tools/build_index.py """""" import os import jinja2 import glob import re def render(tpl_path, context): (path, filename) = os.path.split(tpl_path) return jinja2.Environment(loader=jinja2.FileSystemLoader(path or './')).get_template(filename).render(context) def nep_metadata(): ignore = 'nep-template.rst' sources = sorted(glob.glob('nep-*.rst')) sources = [s for s in sources if s not in ignore] meta_re = ':([a-zA-Z\\-]*): (.*)' has_provisional = False neps = {} print('Loading metadata for:') for source in sources: print(f' - {source}') nr = int(re.match('nep-([0-9]{4}).*\\.rst', source).group(1)) with open(source) as f: lines = f.readlines() tags = [re.match(meta_re, line) for line in lines] tags = [match.groups() for match in tags if match is not None] tags = {tag[0]: tag[1] for tag in tags} for (i, line) in enumerate(lines[:-1]): chars = set(line.rstrip()) if len(chars) == 1 and ('=' in chars or '*' in chars): break else: raise RuntimeError('Unable to find NEP title.') tags['Title'] = lines[i + 1].strip() tags['Filename'] = source if not tags['Title'].startswith(f'NEP {nr} — '): raise RuntimeError(f"""Title for NEP {nr} does not start with "NEP {nr} — " (note that — here is a special, elongated dash). Got: {tags['Title']!r}""") if tags['Status'] in ('Accepted', 'Rejected', 'Withdrawn'): if 'Resolution' not in tags: raise RuntimeError(f'NEP {nr} is Accepted/Rejected/Withdrawn but has no Resolution tag') if tags['Status'] == 'Provisional': has_provisional = True neps[nr] = tags for (nr, tags) in neps.items(): if tags['Status'] == 'Superseded': if 'Replaced-By' not in tags: raise RuntimeError(f'NEP {nr} has been Superseded, but has no Replaced-By tag') replaced_by = int(re.findall('\\d+', tags['Replaced-By'])[0]) replacement_nep = neps[replaced_by] if 'Replaces' not in replacement_nep: raise RuntimeError(f'NEP {nr} is superseded by {replaced_by}, but that NEP has no Replaces tag.') if nr not in parse_replaces_metadata(replacement_nep): raise RuntimeError(f"NEP {nr} is superseded by {replaced_by}, but that NEP has a Replaces tag of `{replacement_nep['Replaces']}`.") if 'Replaces' in tags: replaced_neps = parse_replaces_metadata(tags) for nr_replaced in replaced_neps: replaced_nep_tags = neps[nr_replaced] if not replaced_nep_tags['Status'] == 'Superseded': raise RuntimeError(f'NEP {nr} replaces NEP {nr_replaced}, but that NEP has not been set to Superseded') return {'neps': neps, 'has_provisional': has_provisional} def parse_replaces_metadata(replacement_nep): replaces = re.findall('\\d+', replacement_nep['Replaces']) replaced_neps = [int(s) for s in replaces] return replaced_neps meta = nep_metadata() for nepcat in ('provisional', 'accepted', 'deferred', 'finished', 'meta', 'open', 'rejected'): infile = f'{nepcat}.rst.tmpl' outfile = f'{nepcat}.rst' print(f'Compiling {infile} -> {outfile}') genf = render(infile, meta) with open(outfile, 'w') as f: f.write(genf) # File: numpy-main/doc/postprocess.py """""" def main(): import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('mode', help='file mode', choices=('html', 'tex')) parser.add_argument('file', nargs='+', help='input file(s)') args = parser.parse_args() mode = args.mode for fn in args.file: with open(fn, encoding='utf-8') as f: if mode == 'html': lines = process_html(fn, f.readlines()) elif mode == 'tex': lines = process_tex(f.readlines()) with open(fn, 'w', encoding='utf-8') as f: f.write(''.join(lines)) def process_html(fn, lines): return lines def process_tex(lines): new_lines = [] for line in lines: if line.startswith(('\\section{numpy.', '\\subsection{numpy.', '\\subsubsection{numpy.', '\\paragraph{numpy.', '\\subparagraph{numpy.')): pass else: new_lines.append(line) return new_lines if __name__ == '__main__': main() # File: numpy-main/doc/preprocess.py import os from string import Template def main(): doxy_gen(os.path.abspath(os.path.join('..'))) def doxy_gen(root_path): confs = doxy_config(root_path) build_path = os.path.join(root_path, 'doc', 'build', 'doxygen') gen_path = os.path.join(build_path, 'Doxyfile') if not os.path.exists(build_path): os.makedirs(build_path) with open(gen_path, 'w') as fd: fd.write("#Please Don't Edit! This config file was autogenerated by ") fd.write(f'doxy_gen({root_path}) in doc/preprocess.py.\n') for c in confs: fd.write(c) class DoxyTpl(Template): delimiter = '@' def doxy_config(root_path): confs = [] dsrc_path = os.path.join(root_path, 'doc', 'source') sub = dict(ROOT_DIR=root_path) with open(os.path.join(dsrc_path, 'doxyfile')) as fd: conf = DoxyTpl(fd.read()) confs.append(conf.substitute(CUR_DIR=dsrc_path, **sub)) for (dpath, _, files) in os.walk(root_path): if '.doxyfile' not in files: continue conf_path = os.path.join(dpath, '.doxyfile') with open(conf_path) as fd: conf = DoxyTpl(fd.read()) confs.append(conf.substitute(CUR_DIR=dpath, **sub)) return confs if __name__ == '__main__': main() # File: numpy-main/doc/source/conf.py import os import re import sys import importlib from docutils import nodes from docutils.parsers.rst import Directive from datetime import datetime needs_sphinx = '4.3' _name_cache = {} def replace_scalar_type_names(): import ctypes Py_ssize_t = ctypes.c_int64 if ctypes.sizeof(ctypes.c_void_p) == 8 else ctypes.c_int32 class PyObject(ctypes.Structure): pass class PyTypeObject(ctypes.Structure): pass PyObject._fields_ = [('ob_refcnt', Py_ssize_t), ('ob_type', ctypes.POINTER(PyTypeObject))] PyTypeObject._fields_ = [('ob_base', PyObject), ('ob_size', Py_ssize_t), ('tp_name', ctypes.c_char_p)] import numpy for name in ['byte', 'short', 'intc', 'int_', 'longlong', 'ubyte', 'ushort', 'uintc', 'uint', 'ulonglong', 'half', 'single', 'double', 'longdouble', 'half', 'csingle', 'cdouble', 'clongdouble']: typ = getattr(numpy, name) c_typ = PyTypeObject.from_address(id(typ)) c_typ.tp_name = _name_cache[typ] = b'numpy.' + name.encode('utf8') replace_scalar_type_names() import warnings warnings.filterwarnings('ignore', 'In the future.*NumPy scalar', FutureWarning) sys.path.insert(0, os.path.abspath('../sphinxext')) extensions = ['sphinx.ext.autodoc', 'numpydoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage', 'sphinx.ext.doctest', 'sphinx.ext.autosummary', 'sphinx.ext.graphviz', 'sphinx.ext.ifconfig', 'matplotlib.sphinxext.plot_directive', 'IPython.sphinxext.ipython_console_highlighting', 'IPython.sphinxext.ipython_directive', 'sphinx.ext.mathjax', 'sphinx_copybutton', 'sphinx_design'] skippable_extensions = [('breathe', 'skip generating C/C++ API from comment blocks.')] for (ext, warn) in skippable_extensions: ext_exist = importlib.util.find_spec(ext) is not None if ext_exist: extensions.append(ext) else: print(f"Unable to find Sphinx extension '{ext}', {warn}.") templates_path = ['_templates'] source_suffix = '.rst' project = 'NumPy' year = datetime.now().year copyright = f'2008-{year}, NumPy Developers' import numpy version = re.sub('(\\d+\\.\\d+)\\.\\d+(.*)', '\\1\\2', numpy.__version__) version = re.sub('(\\.dev\\d+).*?$', '\\1', version) release = numpy.__version__ print('%s %s' % (version, release)) today_fmt = '%B %d, %Y' default_role = 'autolink' exclude_dirs = [] exclude_patterns = [] if sys.version_info[:2] >= (3, 12): exclude_patterns += ['reference/distutils.rst'] add_function_parentheses = False class LegacyDirective(Directive): has_content = True node_class = nodes.admonition optional_arguments = 1 def run(self): try: obj = self.arguments[0] except IndexError: obj = 'submodule' text = f'This {obj} is considered legacy and will no longer receive updates. This could also mean it will be removed in future NumPy versions.' try: self.content[0] = text + ' ' + self.content[0] except IndexError: (source, lineno) = self.state_machine.get_source_and_line(self.lineno) self.content.append(text, source=source, offset=lineno) text = '\n'.join(self.content) admonition_node = self.node_class(rawsource=text) title_text = 'Legacy' (textnodes, _) = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) admonition_node += title admonition_node['classes'] = ['admonition-legacy'] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] def setup(app): app.add_config_value('python_version_major', str(sys.version_info.major), 'env') app.add_lexer('NumPyC', NumPyLexer) app.add_directive('legacy', LegacyDirective) sys.modules['numpy.char'] = numpy.char html_theme = 'pydata_sphinx_theme' html_favicon = '_static/favicon/favicon.ico' if os.environ.get('CIRCLE_JOB', False) and os.environ.get('CIRCLE_BRANCH', '') != 'main': switcher_version = os.environ['CIRCLE_BRANCH'] elif '.dev' in version: switcher_version = 'devdocs' else: switcher_version = f'{version}' html_theme_options = {'logo': {'image_light': '_static/numpylogo.svg', 'image_dark': '_static/numpylogo_dark.svg'}, 'github_url': 'https://github.com/numpy/numpy', 'collapse_navigation': True, 'external_links': [{'name': 'Learn', 'url': 'https://numpy.org/numpy-tutorials/'}, {'name': 'NEPs', 'url': 'https://numpy.org/neps'}], 'header_links_before_dropdown': 6, 'navbar_end': ['search-button', 'theme-switcher', 'version-switcher', 'navbar-icon-links'], 'navbar_persistent': [], 'switcher': {'version_match': switcher_version, 'json_url': 'https://numpy.org/doc/_static/versions.json'}, 'show_version_warning_banner': True} html_title = '%s v%s Manual' % (project, version) html_static_path = ['_static'] html_last_updated_fmt = '%b %d, %Y' html_css_files = ['numpy.css'] html_context = {'default_mode': 'light'} html_use_modindex = True html_copy_source = False html_domain_indices = False html_file_suffix = '.html' htmlhelp_basename = 'numpy' if 'sphinx.ext.pngmath' in extensions: pngmath_use_preview = True pngmath_dvipng_args = ['-gamma', '1.5', '-D', '96', '-bg', 'Transparent'] mathjax_path = 'scipy-mathjax/MathJax.js?config=scipy-mathjax' plot_html_show_formats = False plot_html_show_source_link = False copybutton_prompt_text = '>>> |\\.\\.\\. |\\$ |In \\[\\d*\\]: | {2,5}\\.\\.\\.: | {5,8}: ' copybutton_prompt_is_regexp = True latex_engine = 'xelatex' _stdauthor = 'Written by the NumPy community' latex_documents = [('reference/index', 'numpy-ref.tex', 'NumPy Reference', _stdauthor, 'manual'), ('user/index', 'numpy-user.tex', 'NumPy User Guide', _stdauthor, 'manual')] latex_elements = {} latex_elements['preamble'] = "\n\\newfontfamily\\FontForChinese{FandolSong-Regular}[Extension=.otf]\n\\catcode`琴\\active\\protected\\def琴{{\\FontForChinese\\string琴}}\n\\catcode`春\\active\\protected\\def春{{\\FontForChinese\\string春}}\n\\catcode`鈴\\active\\protected\\def鈴{{\\FontForChinese\\string鈴}}\n\\catcode`猫\\active\\protected\\def猫{{\\FontForChinese\\string猫}}\n\\catcode`傅\\active\\protected\\def傅{{\\FontForChinese\\string傅}}\n\\catcode`立\\active\\protected\\def立{{\\FontForChinese\\string立}}\n\\catcode`业\\active\\protected\\def业{{\\FontForChinese\\string业}}\n\\catcode`(\\active\\protected\\def({{\\FontForChinese\\string(}}\n\\catcode`)\\active\\protected\\def){{\\FontForChinese\\string)}}\n\n% In the parameters section, place a newline after the Parameters\n% header. This is default with Sphinx 5.0.0+, so no need for\n% the old hack then.\n% Unfortunately sphinx.sty 5.0.0 did not bump its version date\n% so we check rather sphinxpackagefootnote.sty (which exists\n% since Sphinx 4.0.0).\n\\makeatletter\n\\@ifpackagelater{sphinxpackagefootnote}{2022/02/12}\n {}% Sphinx >= 5.0.0, nothing to do\n {%\n\\usepackage{expdlist}\n\\let\\latexdescription=\\description\n\\def\\description{\\latexdescription{}{} \\breaklabel}\n% but expdlist old LaTeX package requires fixes:\n% 1) remove extra space\n\\usepackage{etoolbox}\n\\patchcmd\\@item{{\\@breaklabel} }{{\\@breaklabel}}{}{}\n% 2) fix bug in expdlist's way of breaking the line after long item label\n\\def\\breaklabel{%\n \\def\\@breaklabel{%\n \\leavevmode\\par\n % now a hack because Sphinx inserts \\leavevmode after term node\n \\def\\leavevmode{\\def\\leavevmode{\\unhbox\\voidb@x}}%\n }%\n}\n }% Sphinx < 5.0.0 (and assumed >= 4.0.0)\n\\makeatother\n\n% Make Examples/etc section headers smaller and more compact\n\\makeatletter\n\\titleformat{\\paragraph}{\\normalsize\\py@HeaderFamily}%\n {\\py@TitleColor}{0em}{\\py@TitleColor}{\\py@NormalColor}\n\\titlespacing*{\\paragraph}{0pt}{1ex}{0pt}\n\\makeatother\n\n% Fix footer/header\n\\renewcommand{\\chaptermark}[1]{\\markboth{\\MakeUppercase{\\thechapter.\\ #1}}{}}\n\\renewcommand{\\sectionmark}[1]{\\markright{\\MakeUppercase{\\thesection.\\ #1}}}\n" latex_use_modindex = False texinfo_documents = [('index', 'numpy', 'NumPy Documentation', _stdauthor, 'NumPy', 'NumPy: array processing for numbers, strings, records, and objects.', 'Programming', 1)] intersphinx_mapping = {'neps': ('https://numpy.org/neps', None), 'python': ('https://docs.python.org/3', None), 'scipy': ('https://docs.scipy.org/doc/scipy', None), 'matplotlib': ('https://matplotlib.org/stable', None), 'imageio': ('https://imageio.readthedocs.io/en/stable', None), 'skimage': ('https://scikit-image.org/docs/stable', None), 'pandas': ('https://pandas.pydata.org/pandas-docs/stable', None), 'scipy-lecture-notes': ('https://scipy-lectures.org', None), 'pytest': ('https://docs.pytest.org/en/stable', None), 'numpy-tutorials': ('https://numpy.org/numpy-tutorials', None), 'numpydoc': ('https://numpydoc.readthedocs.io/en/latest', None), 'dlpack': ('https://dmlc.github.io/dlpack/latest', None)} phantom_import_file = 'dump.xml' numpydoc_use_plots = True autosummary_generate = True coverage_ignore_modules = '\n '.split() coverage_ignore_functions = '\n test($|_) (some|all)true bitwise_not cumproduct pkgload\n generic\\.\n '.split() coverage_ignore_classes = '\n '.split() coverage_c_path = [] coverage_c_regexes = {} coverage_ignore_c_items = {} plot_pre_code = '\nimport numpy as np\nnp.random.seed(0)\n' plot_include_source = True plot_formats = [('png', 100), 'pdf'] import math phi = (math.sqrt(5) + 1) / 2 plot_rcparams = {'font.size': 8, 'axes.titlesize': 8, 'axes.labelsize': 8, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'legend.fontsize': 8, 'figure.figsize': (3 * phi, 3), 'figure.subplot.bottom': 0.2, 'figure.subplot.left': 0.2, 'figure.subplot.right': 0.9, 'figure.subplot.top': 0.85, 'figure.subplot.wspace': 0.4, 'text.usetex': False} import inspect from os.path import relpath, dirname for name in ['sphinx.ext.linkcode', 'numpydoc.linkcode']: try: __import__(name) extensions.append(name) break except ImportError: pass else: print('NOTE: linkcode extension not found -- no links to source generated') def _get_c_source_file(obj): if issubclass(obj, numpy.generic): return '_core/src/multiarray/scalartypes.c.src' elif obj is numpy.ndarray: return '_core/src/multiarray/arrayobject.c' else: return None def linkcode_resolve(domain, info): if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except Exception: return None try: unwrap = inspect.unwrap except AttributeError: pass else: obj = unwrap(obj) fn = None lineno = None if isinstance(obj, type) and obj.__module__ == 'numpy': fn = _get_c_source_file(obj) if fn is None: try: fn = inspect.getsourcefile(obj) except Exception: fn = None if not fn: return None module = inspect.getmodule(obj) if module is not None and (not module.__name__.startswith('numpy')): return None try: (source, lineno) = inspect.getsourcelines(obj) except Exception: lineno = None fn = relpath(fn, start=dirname(numpy.__file__)) if lineno: linespec = '#L%d-L%d' % (lineno, lineno + len(source) - 1) else: linespec = '' if 'dev' in numpy.__version__: return 'https://github.com/numpy/numpy/blob/main/numpy/%s%s' % (fn, linespec) else: return 'https://github.com/numpy/numpy/blob/v%s/numpy/%s%s' % (numpy.__version__, fn, linespec) from pygments.lexers import CLexer from pygments.lexer import inherit from pygments.token import Comment class NumPyLexer(CLexer): name = 'NUMPYLEXER' tokens = {'statements': [('@[a-zA-Z_]*@', Comment.Preproc, 'macro'), inherit]} breathe_projects = dict(numpy=os.path.join('..', 'build', 'doxygen', 'xml')) breathe_default_project = 'numpy' breathe_default_members = ('members', 'undoc-members', 'protected-members') nitpick_ignore = [('c:identifier', 'FILE'), ('c:identifier', 'size_t'), ('c:identifier', 'PyHeapTypeObject')] # File: numpy-main/doc/source/f2py/code/setup_example.py from numpy.distutils.core import Extension ext1 = Extension(name='scalar', sources=['scalar.f']) ext2 = Extension(name='fib2', sources=['fib2.pyf', 'fib1.f']) if __name__ == '__main__': from numpy.distutils.core import setup setup(name='f2py_example', description='F2PY Users Guide examples', author='Pearu Peterson', author_email='pearu@cens.ioc.ee', ext_modules=[ext1, ext2]) # File: numpy-main/doc/source/reference/random/performance.py from timeit import repeat import pandas as pd import numpy as np from numpy.random import MT19937, PCG64, PCG64DXSM, Philox, SFC64 PRNGS = [MT19937, PCG64, PCG64DXSM, Philox, SFC64] funcs = {} integers = 'integers(0, 2**{bits},size=1000000, dtype="uint{bits}")' funcs['32-bit Unsigned Ints'] = integers.format(bits=32) funcs['64-bit Unsigned Ints'] = integers.format(bits=64) funcs['Uniforms'] = 'random(size=1000000)' funcs['Normals'] = 'standard_normal(size=1000000)' funcs['Exponentials'] = 'standard_exponential(size=1000000)' funcs['Gammas'] = 'standard_gamma(3.0,size=1000000)' funcs['Binomials'] = 'binomial(9, .1, size=1000000)' funcs['Laplaces'] = 'laplace(size=1000000)' funcs['Poissons'] = 'poisson(3.0, size=1000000)' setup = '\nfrom numpy.random import {prng}, Generator\nrg = Generator({prng}())\n' test = 'rg.{func}' table = {} for prng in PRNGS: print(prng) col = {} for key in funcs: t = repeat(test.format(func=funcs[key]), setup.format(prng=prng().__class__.__name__), number=1, repeat=3) col[key] = 1000 * min(t) col = pd.Series(col) table[prng().__class__.__name__] = col npfuncs = {} npfuncs.update(funcs) npfuncs['32-bit Unsigned Ints'] = 'randint(2**32,dtype="uint32",size=1000000)' npfuncs['64-bit Unsigned Ints'] = 'randint(2**64,dtype="uint64",size=1000000)' setup = '\nfrom numpy.random import RandomState\nrg = RandomState()\n' col = {} for key in npfuncs: t = repeat(test.format(func=npfuncs[key]), setup.format(prng=prng().__class__.__name__), number=1, repeat=3) col[key] = 1000 * min(t) table['RandomState'] = pd.Series(col) columns = ['MT19937', 'PCG64', 'PCG64DXSM', 'Philox', 'SFC64', 'RandomState'] table = pd.DataFrame(table) order = np.log(table).mean().sort_values().index table = table.T table = table.reindex(columns) table = table.T table = table.reindex(list(funcs), axis=0) print(table.to_csv(float_format='%0.1f')) rel = table.loc[:, ['RandomState']].values @ np.ones((1, table.shape[1])) / table rel.pop('RandomState') rel = rel.T rel['Overall'] = np.exp(np.log(rel).mean(1)) rel *= 100 rel = np.round(rel) rel = rel.T print(rel.to_csv(float_format='%0d')) rows = ['32-bit Unsigned Ints', '64-bit Unsigned Ints', 'Uniforms', 'Normals', 'Exponentials'] xplat = rel.reindex(rows, axis=0) xplat = 100 * (xplat / xplat.MT19937.values[:, None]) overall = np.exp(np.log(xplat).mean(0)) xplat = xplat.T.copy() xplat['Overall'] = overall print(xplat.T.round(1)) # File: numpy-main/doc/source/reference/simd/gen_features.py """""" from os import path from numpy.distutils.ccompiler_opt import CCompilerOpt class FakeCCompilerOpt(CCompilerOpt): conf_nocache = True def __init__(self, arch, cc, *args, **kwargs): self.fake_info = (arch, cc, '') CCompilerOpt.__init__(self, None, **kwargs) def dist_compile(self, sources, flags, **kwargs): return sources def dist_info(self): return self.fake_info @staticmethod def dist_log(*args, stderr=False): pass def feature_test(self, name, force_flags=None, macros=[]): return True class Features: def __init__(self, arch, cc): self.copt = FakeCCompilerOpt(arch, cc, cpu_baseline='max') def names(self): return self.copt.cpu_baseline_names() def serialize(self, features_names): result = [] for f in self.copt.feature_sorted(features_names): gather = self.copt.feature_supported.get(f, {}).get('group', []) implies = self.copt.feature_sorted(self.copt.feature_implies(f)) result.append((f, implies, gather)) return result def table(self, **kwargs): return self.gen_table(self.serialize(self.names()), **kwargs) def table_diff(self, vs, **kwargs): fnames = set(self.names()) fnames_vs = set(vs.names()) common = fnames.intersection(fnames_vs) extra = fnames.difference(fnames_vs) notavl = fnames_vs.difference(fnames) iextra = {} inotavl = {} idiff = set() for f in common: implies = self.copt.feature_implies(f) implies_vs = vs.copt.feature_implies(f) e = implies.difference(implies_vs) i = implies_vs.difference(implies) if not i and (not e): continue if e: iextra[f] = e if i: inotavl[f] = e idiff.add(f) def fbold(f): if f in extra: return f':enabled:`{f}`' if f in notavl: return f':disabled:`{f}`' return f def fbold_implies(f, i): if i in iextra.get(f, {}): return f':enabled:`{i}`' if f in notavl or i in inotavl.get(f, {}): return f':disabled:`{i}`' return i diff_all = self.serialize(idiff.union(extra)) diff_all += vs.serialize(notavl) content = self.gen_table(diff_all, fstyle=fbold, fstyle_implies=fbold_implies, **kwargs) return content def gen_table(self, serialized_features, fstyle=None, fstyle_implies=None, **kwargs): if fstyle is None: fstyle = lambda ft: f'``{ft}``' if fstyle_implies is None: fstyle_implies = lambda origin, ft: fstyle(ft) rows = [] have_gather = False for (f, implies, gather) in serialized_features: if gather: have_gather = True name = fstyle(f) implies = ' '.join([fstyle_implies(f, i) for i in implies]) gather = ' '.join([fstyle_implies(f, i) for i in gather]) rows.append((name, implies, gather)) if not rows: return '' fields = ['Name', 'Implies', 'Gathers'] if not have_gather: del fields[2] rows = [(name, implies) for (name, implies, _) in rows] return self.gen_rst_table(fields, rows, **kwargs) def gen_rst_table(self, field_names, rows, tab_size=4): assert not rows or len(field_names) == len(rows[0]) rows.append(field_names) fld_len = len(field_names) cls_len = [max((len(c[i]) for c in rows)) for i in range(fld_len)] del rows[-1] cformat = ' '.join(('{:<%d}' % i for i in cls_len)) border = cformat.format(*['=' * i for i in cls_len]) rows = [cformat.format(*row) for row in rows] rows = [border, cformat.format(*field_names), border] + rows rows += [border] rows = [' ' * tab_size + r for r in rows] return '\n'.join(rows) def wrapper_section(title, content, tab_size=4): tab = ' ' * tab_size if content: return f"{title}\n{'~' * len(title)}\n.. table::\n{tab}:align: left\n\n{content}\n\n" return '' def wrapper_tab(title, table, tab_size=4): tab = ' ' * tab_size if table: ('\n' + tab).join(('.. tab:: ' + title, tab + '.. table::', tab + 'align: left', table + '\n\n')) return '' if __name__ == '__main__': pretty_names = {'PPC64': 'IBM/POWER big-endian', 'PPC64LE': 'IBM/POWER little-endian', 'S390X': 'IBM/ZSYSTEM(S390X)', 'ARMHF': 'ARMv7/A32', 'AARCH64': 'ARMv8/A64', 'ICC': 'Intel Compiler', 'MSVC': 'Microsoft Visual C/C++'} gen_path = path.join(path.dirname(path.realpath(__file__)), 'generated_tables') with open(path.join(gen_path, 'cpu_features.inc'), 'w') as fd: fd.write(f'.. generated via {__file__}\n\n') for arch in ('x86', 'PPC64', 'PPC64LE', 'ARMHF', 'AARCH64', 'S390X'): title = 'On ' + pretty_names.get(arch, arch) table = Features(arch, 'gcc').table() fd.write(wrapper_section(title, table)) with open(path.join(gen_path, 'compilers-diff.inc'), 'w') as fd: fd.write(f'.. generated via {__file__}\n\n') for (arch, cc_names) in (('x86', ('clang', 'ICC', 'MSVC')), ('PPC64', ('clang',)), ('PPC64LE', ('clang',)), ('ARMHF', ('clang',)), ('AARCH64', ('clang',)), ('S390X', ('clang',))): arch_pname = pretty_names.get(arch, arch) for cc in cc_names: title = f'On {arch_pname}::{pretty_names.get(cc, cc)}' table = Features(arch, cc).table_diff(Features(arch, 'gcc')) fd.write(wrapper_section(title, table)) # File: numpy-main/doc/source/user/plots/matplotlib3.py import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(projection='3d') X = np.arange(-5, 5, 0.15) Y = np.arange(-5, 5, 0.15) (X, Y) = np.meshgrid(X, Y) R = np.sqrt(X ** 2 + Y ** 2) Z = np.sin(R) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis') plt.show() # File: numpy-main/numpy/__init__.py """""" import os import sys import warnings from ._globals import _NoValue, _CopyMode from ._expired_attrs_2_0 import __expired_attributes__ from . import version from .version import __version__ try: __NUMPY_SETUP__ except NameError: __NUMPY_SETUP__ = False if __NUMPY_SETUP__: sys.stderr.write('Running from numpy source directory.\n') else: from . import _distributor_init try: from numpy.__config__ import show as show_config except ImportError as e: msg = 'Error importing numpy: you should not try to import numpy from\n its source directory; please exit the numpy source tree, and relaunch\n your python interpreter from there.' raise ImportError(msg) from e from . import _core from ._core import False_, ScalarType, True_, abs, absolute, acos, acosh, add, all, allclose, amax, amin, any, arange, arccos, arccosh, arcsin, arcsinh, arctan, arctan2, arctanh, argmax, argmin, argpartition, argsort, argwhere, around, array, array2string, array_equal, array_equiv, array_repr, array_str, asanyarray, asarray, ascontiguousarray, asfortranarray, asin, asinh, atan, atanh, atan2, astype, atleast_1d, atleast_2d, atleast_3d, base_repr, binary_repr, bitwise_and, bitwise_count, bitwise_invert, bitwise_left_shift, bitwise_not, bitwise_or, bitwise_right_shift, bitwise_xor, block, bool, bool_, broadcast, busday_count, busday_offset, busdaycalendar, byte, bytes_, can_cast, cbrt, cdouble, ceil, character, choose, clip, clongdouble, complex128, complex64, complexfloating, compress, concat, concatenate, conj, conjugate, convolve, copysign, copyto, correlate, cos, cosh, count_nonzero, cross, csingle, cumprod, cumsum, cumulative_prod, cumulative_sum, datetime64, datetime_as_string, datetime_data, deg2rad, degrees, diagonal, divide, divmod, dot, double, dtype, e, einsum, einsum_path, empty, empty_like, equal, errstate, euler_gamma, exp, exp2, expm1, fabs, finfo, flatiter, flatnonzero, flexible, float16, float32, float64, float_power, floating, floor, floor_divide, fmax, fmin, fmod, format_float_positional, format_float_scientific, frexp, from_dlpack, frombuffer, fromfile, fromfunction, fromiter, frompyfunc, fromstring, full, full_like, gcd, generic, geomspace, get_printoptions, getbufsize, geterr, geterrcall, greater, greater_equal, half, heaviside, hstack, hypot, identity, iinfo, indices, inexact, inf, inner, int16, int32, int64, int8, int_, intc, integer, intp, invert, is_busday, isclose, isdtype, isfinite, isfortran, isinf, isnan, isnat, isscalar, issubdtype, lcm, ldexp, left_shift, less, less_equal, lexsort, linspace, little_endian, log, log10, log1p, log2, logaddexp, logaddexp2, logical_and, logical_not, logical_or, logical_xor, logspace, long, longdouble, longlong, matmul, matrix_transpose, max, maximum, may_share_memory, mean, memmap, min, min_scalar_type, minimum, mod, modf, moveaxis, multiply, nan, ndarray, ndim, nditer, negative, nested_iters, newaxis, nextafter, nonzero, not_equal, number, object_, ones, ones_like, outer, partition, permute_dims, pi, positive, pow, power, printoptions, prod, promote_types, ptp, put, putmask, rad2deg, radians, ravel, recarray, reciprocal, record, remainder, repeat, require, reshape, resize, result_type, right_shift, rint, roll, rollaxis, round, sctypeDict, searchsorted, set_printoptions, setbufsize, seterr, seterrcall, shape, shares_memory, short, sign, signbit, signedinteger, sin, single, sinh, size, sort, spacing, sqrt, square, squeeze, stack, std, str_, subtract, sum, swapaxes, take, tan, tanh, tensordot, timedelta64, trace, transpose, true_divide, trunc, typecodes, ubyte, ufunc, uint, uint16, uint32, uint64, uint8, uintc, uintp, ulong, ulonglong, unsignedinteger, unstack, ushort, var, vdot, vecdot, void, vstack, where, zeros, zeros_like for ta in ['float96', 'float128', 'complex192', 'complex256']: try: globals()[ta] = getattr(_core, ta) except AttributeError: pass del ta from . import lib from .lib import scimath as emath from .lib._histograms_impl import histogram, histogram_bin_edges, histogramdd from .lib._nanfunctions_impl import nanargmax, nanargmin, nancumprod, nancumsum, nanmax, nanmean, nanmedian, nanmin, nanpercentile, nanprod, nanquantile, nanstd, nansum, nanvar from .lib._function_base_impl import select, piecewise, trim_zeros, copy, iterable, percentile, diff, gradient, angle, unwrap, sort_complex, flip, rot90, extract, place, vectorize, asarray_chkfinite, average, bincount, digitize, cov, corrcoef, median, sinc, hamming, hanning, bartlett, blackman, kaiser, trapezoid, trapz, i0, meshgrid, delete, insert, append, interp, quantile from .lib._twodim_base_impl import diag, diagflat, eye, fliplr, flipud, tri, triu, tril, vander, histogram2d, mask_indices, tril_indices, tril_indices_from, triu_indices, triu_indices_from from .lib._shape_base_impl import apply_over_axes, apply_along_axis, array_split, column_stack, dsplit, dstack, expand_dims, hsplit, kron, put_along_axis, row_stack, split, take_along_axis, tile, vsplit from .lib._type_check_impl import iscomplexobj, isrealobj, imag, iscomplex, isreal, nan_to_num, real, real_if_close, typename, mintypecode, common_type from .lib._arraysetops_impl import ediff1d, in1d, intersect1d, isin, setdiff1d, setxor1d, union1d, unique, unique_all, unique_counts, unique_inverse, unique_values from .lib._ufunclike_impl import fix, isneginf, isposinf from .lib._arraypad_impl import pad from .lib._utils_impl import show_runtime, get_include, info from .lib._stride_tricks_impl import broadcast_arrays, broadcast_shapes, broadcast_to from .lib._polynomial_impl import poly, polyint, polyder, polyadd, polysub, polymul, polydiv, polyval, polyfit, poly1d, roots from .lib._npyio_impl import savetxt, loadtxt, genfromtxt, load, save, savez, packbits, savez_compressed, unpackbits, fromregex from .lib._index_tricks_impl import diag_indices_from, diag_indices, fill_diagonal, ndindex, ndenumerate, ix_, c_, r_, s_, ogrid, mgrid, unravel_index, ravel_multi_index, index_exp from . import matrixlib as _mat from .matrixlib import asmatrix, bmat, matrix __numpy_submodules__ = {'linalg', 'fft', 'dtypes', 'random', 'polynomial', 'ma', 'exceptions', 'lib', 'ctypeslib', 'testing', 'typing', 'f2py', 'test', 'rec', 'char', 'core', 'strings'} _msg = "module 'numpy' has no attribute '{n}'.\n`np.{n}` was a deprecated alias for the builtin `{n}`. To avoid this error in existing code, use `{n}` by itself. Doing this will not modify any behavior and is safe. {extended_msg}\nThe aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at:\n https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations" _specific_msg = 'If you specifically wanted the numpy scalar type, use `np.{}` here.' _int_extended_msg = 'When replacing `np.{}`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.' _type_info = [('object', ''), ('float', _specific_msg.format('float64')), ('complex', _specific_msg.format('complex128')), ('str', _specific_msg.format('str_')), ('int', _int_extended_msg.format('int'))] __former_attrs__ = {n: _msg.format(n=n, extended_msg=extended_msg) for (n, extended_msg) in _type_info} __future_scalars__ = {'str', 'bytes', 'object'} __array_api_version__ = '2023.12' from ._array_api_info import __array_namespace_info__ _core.getlimits._register_known_types() __all__ = list(__numpy_submodules__ | set(_core.__all__) | set(_mat.__all__) | set(lib._histograms_impl.__all__) | set(lib._nanfunctions_impl.__all__) | set(lib._function_base_impl.__all__) | set(lib._twodim_base_impl.__all__) | set(lib._shape_base_impl.__all__) | set(lib._type_check_impl.__all__) | set(lib._arraysetops_impl.__all__) | set(lib._ufunclike_impl.__all__) | set(lib._arraypad_impl.__all__) | set(lib._utils_impl.__all__) | set(lib._stride_tricks_impl.__all__) | set(lib._polynomial_impl.__all__) | set(lib._npyio_impl.__all__) | set(lib._index_tricks_impl.__all__) | {'emath', 'show_config', '__version__', '__array_namespace_info__'}) warnings.filterwarnings('ignore', message='numpy.dtype size changed') warnings.filterwarnings('ignore', message='numpy.ufunc size changed') warnings.filterwarnings('ignore', message='numpy.ndarray size changed') def __getattr__(attr): import warnings if attr == 'linalg': import numpy.linalg as linalg return linalg elif attr == 'fft': import numpy.fft as fft return fft elif attr == 'dtypes': import numpy.dtypes as dtypes return dtypes elif attr == 'random': import numpy.random as random return random elif attr == 'polynomial': import numpy.polynomial as polynomial return polynomial elif attr == 'ma': import numpy.ma as ma return ma elif attr == 'ctypeslib': import numpy.ctypeslib as ctypeslib return ctypeslib elif attr == 'exceptions': import numpy.exceptions as exceptions return exceptions elif attr == 'testing': import numpy.testing as testing return testing elif attr == 'matlib': import numpy.matlib as matlib return matlib elif attr == 'f2py': import numpy.f2py as f2py return f2py elif attr == 'typing': import numpy.typing as typing return typing elif attr == 'rec': import numpy.rec as rec return rec elif attr == 'char': import numpy.char as char return char elif attr == 'array_api': raise AttributeError('`numpy.array_api` is not available from numpy 2.0 onwards', name=None) elif attr == 'core': import numpy.core as core return core elif attr == 'strings': import numpy.strings as strings return strings elif attr == 'distutils': if 'distutils' in __numpy_submodules__: import numpy.distutils as distutils return distutils else: raise AttributeError('`numpy.distutils` is not available from Python 3.12 onwards', name=None) if attr in __future_scalars__: warnings.warn(f'In the future `np.{attr}` will be defined as the corresponding NumPy scalar.', FutureWarning, stacklevel=2) if attr in __former_attrs__: raise AttributeError(__former_attrs__[attr], name=None) if attr in __expired_attributes__: raise AttributeError(f'`np.{attr}` was removed in the NumPy 2.0 release. {__expired_attributes__[attr]}', name=None) if attr == 'chararray': warnings.warn('`np.chararray` is deprecated and will be removed from the main namespace in the future. Use an array with a string or bytes dtype instead.', DeprecationWarning, stacklevel=2) import numpy.char as char return char.chararray raise AttributeError('module {!r} has no attribute {!r}'.format(__name__, attr)) def __dir__(): public_symbols = globals().keys() | __numpy_submodules__ public_symbols -= {'matrixlib', 'matlib', 'tests', 'conftest', 'version', 'compat', 'distutils', 'array_api'} return list(public_symbols) from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester def _sanity_check(): try: x = ones(2, dtype=float32) if not abs(x.dot(x) - float32(2.0)) < 1e-05: raise AssertionError except AssertionError: msg = 'The current Numpy installation ({!r}) fails to pass simple sanity checks. This can be caused for example by incorrect BLAS library being linked in, or by mixing package managers (pip, conda, apt, ...). Search closed numpy issues for similar problems.' raise RuntimeError(msg.format(__file__)) from None _sanity_check() del _sanity_check def _mac_os_check(): try: c = array([3.0, 2.0, 1.0]) x = linspace(0, 2, 5) y = polyval(c, x) _ = polyfit(x, y, 2, cov=True) except ValueError: pass if sys.platform == 'darwin': from . import exceptions with warnings.catch_warnings(record=True) as w: _mac_os_check() if len(w) > 0: for _wn in w: if _wn.category is exceptions.RankWarning: error_message = f'{_wn.category.__name__}: {_wn.message}' msg = 'Polyfit sanity test emitted a warning, most likely due to using a buggy Accelerate backend.\nIf you compiled yourself, more information is available at:\nhttps://numpy.org/devdocs/building/index.html\nOtherwise report this to the vendor that provided NumPy.\n\n{}\n'.format(error_message) raise RuntimeError(msg) del _wn del w del _mac_os_check def hugepage_setup(): use_hugepage = os.environ.get('NUMPY_MADVISE_HUGEPAGE', None) if sys.platform == 'linux' and use_hugepage is None: try: use_hugepage = 1 kernel_version = os.uname().release.split('.')[:2] kernel_version = tuple((int(v) for v in kernel_version)) if kernel_version < (4, 6): use_hugepage = 0 except ValueError: use_hugepage = 0 elif use_hugepage is None: use_hugepage = 1 else: use_hugepage = int(use_hugepage) return use_hugepage _core.multiarray._set_madvise_hugepage(hugepage_setup()) del hugepage_setup _core.multiarray._multiarray_umath._reload_guard() if os.environ.get('NPY_PROMOTION_STATE', 'weak') != 'weak': warnings.warn('NPY_PROMOTION_STATE was a temporary feature for NumPy 2.0 transition and is ignored after NumPy 2.2.', UserWarning, stacklevel=2) def _pyinstaller_hooks_dir(): from pathlib import Path return [str(Path(__file__).with_name('_pyinstaller').resolve())] del os, sys, warnings # File: numpy-main/numpy/_array_api_info.py """""" from numpy._core import dtype, bool, intp, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, complex64, complex128 class __array_namespace_info__: __module__ = 'numpy' def capabilities(self): return {'boolean indexing': True, 'data-dependent shapes': True} def default_device(self): return 'cpu' def default_dtypes(self, *, device=None): if device not in ['cpu', None]: raise ValueError(f'Device not understood. Only "cpu" is allowed, but received: {device}') return {'real floating': dtype(float64), 'complex floating': dtype(complex128), 'integral': dtype(intp), 'indexing': dtype(intp)} def dtypes(self, *, device=None, kind=None): if device not in ['cpu', None]: raise ValueError(f'Device not understood. Only "cpu" is allowed, but received: {device}') if kind is None: return {'bool': dtype(bool), 'int8': dtype(int8), 'int16': dtype(int16), 'int32': dtype(int32), 'int64': dtype(int64), 'uint8': dtype(uint8), 'uint16': dtype(uint16), 'uint32': dtype(uint32), 'uint64': dtype(uint64), 'float32': dtype(float32), 'float64': dtype(float64), 'complex64': dtype(complex64), 'complex128': dtype(complex128)} if kind == 'bool': return {'bool': bool} if kind == 'signed integer': return {'int8': dtype(int8), 'int16': dtype(int16), 'int32': dtype(int32), 'int64': dtype(int64)} if kind == 'unsigned integer': return {'uint8': dtype(uint8), 'uint16': dtype(uint16), 'uint32': dtype(uint32), 'uint64': dtype(uint64)} if kind == 'integral': return {'int8': dtype(int8), 'int16': dtype(int16), 'int32': dtype(int32), 'int64': dtype(int64), 'uint8': dtype(uint8), 'uint16': dtype(uint16), 'uint32': dtype(uint32), 'uint64': dtype(uint64)} if kind == 'real floating': return {'float32': dtype(float32), 'float64': dtype(float64)} if kind == 'complex floating': return {'complex64': dtype(complex64), 'complex128': dtype(complex128)} if kind == 'numeric': return {'int8': dtype(int8), 'int16': dtype(int16), 'int32': dtype(int32), 'int64': dtype(int64), 'uint8': dtype(uint8), 'uint16': dtype(uint16), 'uint32': dtype(uint32), 'uint64': dtype(uint64), 'float32': dtype(float32), 'float64': dtype(float64), 'complex64': dtype(complex64), 'complex128': dtype(complex128)} if isinstance(kind, tuple): res = {} for k in kind: res.update(self.dtypes(kind=k)) return res raise ValueError(f'unsupported kind: {kind!r}') def devices(self): return ['cpu'] # File: numpy-main/numpy/_build_utils/__init__.py numpy_nodepr_api = dict(define_macros=[('NPY_NO_DEPRECATED_API', 'NPY_1_9_API_VERSION')]) def import_file(folder, module_name): import importlib import pathlib fname = pathlib.Path(folder) / f'{module_name}.py' spec = importlib.util.spec_from_file_location(module_name, str(fname)) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module # File: numpy-main/numpy/_build_utils/gcc_build_bitness.py """""" import re from subprocess import run def main(): res = run(['gcc', '-v'], check=True, text=True, capture_output=True) target = re.search('^Target: (.*)$', res.stderr, flags=re.M).groups()[0] if target.startswith('i686'): print('32') elif target.startswith('x86_64'): print('64') else: raise RuntimeError('Could not detect Mingw-w64 bitness') if __name__ == '__main__': main() # File: numpy-main/numpy/_build_utils/gitversion.py import os import textwrap def init_version(): init = os.path.join(os.path.dirname(__file__), '../../pyproject.toml') with open(init) as fid: data = fid.readlines() version_line = next((line for line in data if line.startswith('version ='))) version = version_line.strip().split(' = ')[1] version = version.replace('"', '').replace("'", '') return version def git_version(version): import subprocess import os.path git_hash = '' try: p = subprocess.Popen(['git', 'log', '-1', '--format="%H %aI"'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(__file__)) except FileNotFoundError: pass else: (out, err) = p.communicate() if p.returncode == 0: (git_hash, git_date) = out.decode('utf-8').strip().replace('"', '').split('T')[0].replace('-', '').split() if 'dev' in version: version += f'+git{git_date}.{git_hash[:7]}' return (version, git_hash) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--write', help='Save version to this file') parser.add_argument('--meson-dist', help='Output path is relative to MESON_DIST_ROOT', action='store_true') args = parser.parse_args() (version, git_hash) = git_version(init_version()) template = textwrap.dedent(f'''\n """\n Module to expose more detailed version info for the installed `numpy`\n """\n version = "{version}"\n __version__ = version\n full_version = version\n\n git_revision = "{git_hash}"\n release = 'dev' not in version and '+' not in version\n short_version = version.split("+")[0]\n ''') if args.write: outfile = args.write if args.meson_dist: outfile = os.path.join(os.environ.get('MESON_DIST_ROOT', ''), outfile) relpath = os.path.relpath(outfile) if relpath.startswith('.'): relpath = outfile with open(outfile, 'w') as f: print(f'Saving version to {relpath}') f.write(template) else: print(version) # File: numpy-main/numpy/_build_utils/process_src_template.py import os import argparse import importlib.util def get_processor(): conv_template_path = os.path.join(os.path.dirname(__file__), '..', 'distutils', 'conv_template.py') spec = importlib.util.spec_from_file_location('conv_template', conv_template_path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod.process_file def process_and_write_file(fromfile, outfile): process_file = get_processor() content = process_file(fromfile) with open(outfile, 'w') as f: f.write(content) def main(): parser = argparse.ArgumentParser() parser.add_argument('infile', type=str, help='Path to the input file') parser.add_argument('-o', '--outfile', type=str, help='Path to the output file') parser.add_argument('-i', '--ignore', type=str, help='An ignored input - may be useful to add a dependency between custom targets') args = parser.parse_args() if not args.infile.endswith('.src'): raise ValueError(f'Unexpected extension: {args.infile}') outfile_abs = os.path.join(os.getcwd(), args.outfile) process_and_write_file(args.infile, outfile_abs) if __name__ == '__main__': main() # File: numpy-main/numpy/_build_utils/tempita.py import sys import os import argparse from Cython import Tempita as tempita def process_tempita(fromfile, outfile=None): if outfile is None: outfile = os.path.splitext(fromfile)[0] from_filename = tempita.Template.from_filename template = from_filename(fromfile, encoding=sys.getdefaultencoding()) content = template.substitute() with open(outfile, 'w') as f: f.write(content) def main(): parser = argparse.ArgumentParser() parser.add_argument('infile', type=str, help='Path to the input file') parser.add_argument('-o', '--outfile', type=str, help='Path to the output file') parser.add_argument('-i', '--ignore', type=str, help='An ignored input - may be useful to add a dependency between custom targets') args = parser.parse_args() if not args.infile.endswith('.in'): raise ValueError(f'Unexpected extension: {args.infile}') outfile_abs = os.path.join(os.getcwd(), args.outfile) process_tempita(args.infile, outfile_abs) if __name__ == '__main__': main() # File: numpy-main/numpy/_configtool.py import argparse from pathlib import Path import sys from .version import __version__ from .lib._utils_impl import get_include def main() -> None: parser = argparse.ArgumentParser() parser.add_argument('--version', action='version', version=__version__, help='Print the version and exit.') parser.add_argument('--cflags', action='store_true', help='Compile flag needed when using the NumPy headers.') parser.add_argument('--pkgconfigdir', action='store_true', help='Print the pkgconfig directory in which `numpy.pc` is stored (useful for setting $PKG_CONFIG_PATH).') args = parser.parse_args() if not sys.argv[1:]: parser.print_help() if args.cflags: print('-I' + get_include()) if args.pkgconfigdir: _path = Path(get_include()) / '..' / 'lib' / 'pkgconfig' print(_path.resolve()) if __name__ == '__main__': main() # File: numpy-main/numpy/_core/__init__.py """""" import os from numpy.version import version as __version__ env_added = [] for envkey in ['OPENBLAS_MAIN_FREE', 'GOTOBLAS_MAIN_FREE']: if envkey not in os.environ: os.environ[envkey] = '1' env_added.append(envkey) try: from . import multiarray except ImportError as exc: import sys msg = '\n\nIMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!\n\nImporting the numpy C-extensions failed. This error can happen for\nmany reasons, often due to issues with your setup or how NumPy was\ninstalled.\n\nWe have compiled some common reasons and troubleshooting tips at:\n\n https://numpy.org/devdocs/user/troubleshooting-importerror.html\n\nPlease note and check the following:\n\n * The Python version is: Python%d.%d from "%s"\n * The NumPy version is: "%s"\n\nand make sure that they are the versions you expect.\nPlease carefully study the documentation linked above for further help.\n\nOriginal error was: %s\n' % (sys.version_info[0], sys.version_info[1], sys.executable, __version__, exc) raise ImportError(msg) finally: for envkey in env_added: del os.environ[envkey] del envkey del env_added del os from . import umath if not (hasattr(multiarray, '_multiarray_umath') and hasattr(umath, '_multiarray_umath')): import sys path = sys.modules['numpy'].__path__ msg = 'Something is wrong with the numpy installation. While importing we detected an older version of numpy in {}. One method of fixing this is to repeatedly uninstall numpy until none is found, then reinstall this version.' raise ImportError(msg.format(path)) from . import numerictypes as nt from .numerictypes import sctypes, sctypeDict multiarray.set_typeDict(nt.sctypeDict) from . import numeric from .numeric import * from . import fromnumeric from .fromnumeric import * from .records import record, recarray from .memmap import * from . import function_base from .function_base import * from . import _machar from . import getlimits from .getlimits import * from . import shape_base from .shape_base import * from . import einsumfunc from .einsumfunc import * del nt from .numeric import absolute as abs from . import _add_newdocs from . import _add_newdocs_scalars from . import _dtype_ctypes from . import _internal from . import _dtype from . import _methods acos = numeric.arccos acosh = numeric.arccosh asin = numeric.arcsin asinh = numeric.arcsinh atan = numeric.arctan atanh = numeric.arctanh atan2 = numeric.arctan2 concat = numeric.concatenate bitwise_left_shift = numeric.left_shift bitwise_invert = numeric.invert bitwise_right_shift = numeric.right_shift permute_dims = numeric.transpose pow = numeric.power __all__ = ['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'atan2', 'bitwise_invert', 'bitwise_left_shift', 'bitwise_right_shift', 'concat', 'pow', 'permute_dims', 'memmap', 'sctypeDict', 'record', 'recarray'] __all__ += numeric.__all__ __all__ += function_base.__all__ __all__ += getlimits.__all__ __all__ += shape_base.__all__ __all__ += einsumfunc.__all__ def _ufunc_reduce(func): return func.__name__ def _DType_reconstruct(scalar_type): return type(dtype(scalar_type)) def _DType_reduce(DType): if not DType._legacy or DType.__module__ == 'numpy.dtypes': return DType.__name__ scalar_type = DType.type return (_DType_reconstruct, (scalar_type,)) def __getattr__(name): if name == 'MachAr': import warnings warnings.warn('The `np._core.MachAr` is considered private API (NumPy 1.24)', DeprecationWarning, stacklevel=2) return _machar.MachAr raise AttributeError(f'Module {__name__!r} has no attribute {name!r}') import copyreg copyreg.pickle(ufunc, _ufunc_reduce) copyreg.pickle(type(dtype), _DType_reduce, _DType_reconstruct) del copyreg, _ufunc_reduce, _DType_reduce from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester # File: numpy-main/numpy/_core/_add_newdocs.py """""" from numpy._core.function_base import add_newdoc from numpy._core.overrides import array_function_like_doc add_newdoc('numpy._core', 'flatiter', "\n Flat iterator object to iterate over arrays.\n\n A `flatiter` iterator is returned by ``x.flat`` for any array `x`.\n It allows iterating over the array as if it were a 1-D array,\n either in a for-loop or by calling its `next` method.\n\n Iteration is done in row-major, C-style order (the last\n index varying the fastest). The iterator can also be indexed using\n basic slicing or advanced indexing.\n\n See Also\n --------\n ndarray.flat : Return a flat iterator over an array.\n ndarray.flatten : Returns a flattened copy of an array.\n\n Notes\n -----\n A `flatiter` iterator can not be constructed directly from Python code\n by calling the `flatiter` constructor.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.arange(6).reshape(2, 3)\n >>> fl = x.flat\n >>> type(fl)\n \n >>> for item in fl:\n ... print(item)\n ...\n 0\n 1\n 2\n 3\n 4\n 5\n\n >>> fl[2:4]\n array([2, 3])\n\n ") add_newdoc('numpy._core', 'flatiter', ('base', '\n A reference to the array that is iterated over.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.arange(5)\n >>> fl = x.flat\n >>> fl.base is x\n True\n\n ')) add_newdoc('numpy._core', 'flatiter', ('coords', '\n An N-dimensional tuple of current coordinates.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.arange(6).reshape(2, 3)\n >>> fl = x.flat\n >>> fl.coords\n (0, 0)\n >>> next(fl)\n 0\n >>> fl.coords\n (0, 1)\n\n ')) add_newdoc('numpy._core', 'flatiter', ('index', '\n Current flat index into the array.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.arange(6).reshape(2, 3)\n >>> fl = x.flat\n >>> fl.index\n 0\n >>> next(fl)\n 0\n >>> fl.index\n 1\n\n ')) add_newdoc('numpy._core', 'flatiter', ('__array__', '__array__(type=None) Get array from iterator\n\n ')) add_newdoc('numpy._core', 'flatiter', ('copy', '\n copy()\n\n Get a copy of the iterator as a 1-D array.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.arange(6).reshape(2, 3)\n >>> x\n array([[0, 1, 2],\n [3, 4, 5]])\n >>> fl = x.flat\n >>> fl.copy()\n array([0, 1, 2, 3, 4, 5])\n\n ')) add_newdoc('numpy._core', 'nditer', '\n nditer(op, flags=None, op_flags=None, op_dtypes=None, order=\'K\',\n casting=\'safe\', op_axes=None, itershape=None, buffersize=0)\n\n Efficient multi-dimensional iterator object to iterate over arrays.\n To get started using this object, see the\n :ref:`introductory guide to array iteration `.\n\n Parameters\n ----------\n op : ndarray or sequence of array_like\n The array(s) to iterate over.\n\n flags : sequence of str, optional\n Flags to control the behavior of the iterator.\n\n * ``buffered`` enables buffering when required.\n * ``c_index`` causes a C-order index to be tracked.\n * ``f_index`` causes a Fortran-order index to be tracked.\n * ``multi_index`` causes a multi-index, or a tuple of indices\n with one per iteration dimension, to be tracked.\n * ``common_dtype`` causes all the operands to be converted to\n a common data type, with copying or buffering as necessary.\n * ``copy_if_overlap`` causes the iterator to determine if read\n operands have overlap with write operands, and make temporary\n copies as necessary to avoid overlap. False positives (needless\n copying) are possible in some cases.\n * ``delay_bufalloc`` delays allocation of the buffers until\n a reset() call is made. Allows ``allocate`` operands to\n be initialized before their values are copied into the buffers.\n * ``external_loop`` causes the ``values`` given to be\n one-dimensional arrays with multiple values instead of\n zero-dimensional arrays.\n * ``grow_inner`` allows the ``value`` array sizes to be made\n larger than the buffer size when both ``buffered`` and\n ``external_loop`` is used.\n * ``ranged`` allows the iterator to be restricted to a sub-range\n of the iterindex values.\n * ``refs_ok`` enables iteration of reference types, such as\n object arrays.\n * ``reduce_ok`` enables iteration of ``readwrite`` operands\n which are broadcasted, also known as reduction operands.\n * ``zerosize_ok`` allows `itersize` to be zero.\n op_flags : list of list of str, optional\n This is a list of flags for each operand. At minimum, one of\n ``readonly``, ``readwrite``, or ``writeonly`` must be specified.\n\n * ``readonly`` indicates the operand will only be read from.\n * ``readwrite`` indicates the operand will be read from and written to.\n * ``writeonly`` indicates the operand will only be written to.\n * ``no_broadcast`` prevents the operand from being broadcasted.\n * ``contig`` forces the operand data to be contiguous.\n * ``aligned`` forces the operand data to be aligned.\n * ``nbo`` forces the operand data to be in native byte order.\n * ``copy`` allows a temporary read-only copy if required.\n * ``updateifcopy`` allows a temporary read-write copy if required.\n * ``allocate`` causes the array to be allocated if it is None\n in the ``op`` parameter.\n * ``no_subtype`` prevents an ``allocate`` operand from using a subtype.\n * ``arraymask`` indicates that this operand is the mask to use\n for selecting elements when writing to operands with the\n \'writemasked\' flag set. The iterator does not enforce this,\n but when writing from a buffer back to the array, it only\n copies those elements indicated by this mask.\n * ``writemasked`` indicates that only elements where the chosen\n ``arraymask`` operand is True will be written to.\n * ``overlap_assume_elementwise`` can be used to mark operands that are\n accessed only in the iterator order, to allow less conservative\n copying when ``copy_if_overlap`` is present.\n op_dtypes : dtype or tuple of dtype(s), optional\n The required data type(s) of the operands. If copying or buffering\n is enabled, the data will be converted to/from their original types.\n order : {\'C\', \'F\', \'A\', \'K\'}, optional\n Controls the iteration order. \'C\' means C order, \'F\' means\n Fortran order, \'A\' means \'F\' order if all the arrays are Fortran\n contiguous, \'C\' order otherwise, and \'K\' means as close to the\n order the array elements appear in memory as possible. This also\n affects the element memory order of ``allocate`` operands, as they\n are allocated to be compatible with iteration order.\n Default is \'K\'.\n casting : {\'no\', \'equiv\', \'safe\', \'same_kind\', \'unsafe\'}, optional\n Controls what kind of data casting may occur when making a copy\n or buffering. Setting this to \'unsafe\' is not recommended,\n as it can adversely affect accumulations.\n\n * \'no\' means the data types should not be cast at all.\n * \'equiv\' means only byte-order changes are allowed.\n * \'safe\' means only casts which can preserve values are allowed.\n * \'same_kind\' means only safe casts or casts within a kind,\n like float64 to float32, are allowed.\n * \'unsafe\' means any data conversions may be done.\n op_axes : list of list of ints, optional\n If provided, is a list of ints or None for each operands.\n The list of axes for an operand is a mapping from the dimensions\n of the iterator to the dimensions of the operand. A value of\n -1 can be placed for entries, causing that dimension to be\n treated as `newaxis`.\n itershape : tuple of ints, optional\n The desired shape of the iterator. This allows ``allocate`` operands\n with a dimension mapped by op_axes not corresponding to a dimension\n of a different operand to get a value not equal to 1 for that\n dimension.\n buffersize : int, optional\n When buffering is enabled, controls the size of the temporary\n buffers. Set to 0 for the default value.\n\n Attributes\n ----------\n dtypes : tuple of dtype(s)\n The data types of the values provided in `value`. This may be\n different from the operand data types if buffering is enabled.\n Valid only before the iterator is closed.\n finished : bool\n Whether the iteration over the operands is finished or not.\n has_delayed_bufalloc : bool\n If True, the iterator was created with the ``delay_bufalloc`` flag,\n and no reset() function was called on it yet.\n has_index : bool\n If True, the iterator was created with either the ``c_index`` or\n the ``f_index`` flag, and the property `index` can be used to\n retrieve it.\n has_multi_index : bool\n If True, the iterator was created with the ``multi_index`` flag,\n and the property `multi_index` can be used to retrieve it.\n index\n When the ``c_index`` or ``f_index`` flag was used, this property\n provides access to the index. Raises a ValueError if accessed\n and ``has_index`` is False.\n iterationneedsapi : bool\n Whether iteration requires access to the Python API, for example\n if one of the operands is an object array.\n iterindex : int\n An index which matches the order of iteration.\n itersize : int\n Size of the iterator.\n itviews\n Structured view(s) of `operands` in memory, matching the reordered\n and optimized iterator access pattern. Valid only before the iterator\n is closed.\n multi_index\n When the ``multi_index`` flag was used, this property\n provides access to the index. Raises a ValueError if accessed\n accessed and ``has_multi_index`` is False.\n ndim : int\n The dimensions of the iterator.\n nop : int\n The number of iterator operands.\n operands : tuple of operand(s)\n The array(s) to be iterated over. Valid only before the iterator is\n closed.\n shape : tuple of ints\n Shape tuple, the shape of the iterator.\n value\n Value of ``operands`` at current iteration. Normally, this is a\n tuple of array scalars, but if the flag ``external_loop`` is used,\n it is a tuple of one dimensional arrays.\n\n Notes\n -----\n `nditer` supersedes `flatiter`. The iterator implementation behind\n `nditer` is also exposed by the NumPy C API.\n\n The Python exposure supplies two iteration interfaces, one which follows\n the Python iterator protocol, and another which mirrors the C-style\n do-while pattern. The native Python approach is better in most cases, but\n if you need the coordinates or index of an iterator, use the C-style pattern.\n\n Examples\n --------\n Here is how we might write an ``iter_add`` function, using the\n Python iterator protocol:\n\n >>> import numpy as np\n\n >>> def iter_add_py(x, y, out=None):\n ... addop = np.add\n ... it = np.nditer([x, y, out], [],\n ... [[\'readonly\'], [\'readonly\'], [\'writeonly\',\'allocate\']])\n ... with it:\n ... for (a, b, c) in it:\n ... addop(a, b, out=c)\n ... return it.operands[2]\n\n Here is the same function, but following the C-style pattern:\n\n >>> def iter_add(x, y, out=None):\n ... addop = np.add\n ... it = np.nditer([x, y, out], [],\n ... [[\'readonly\'], [\'readonly\'], [\'writeonly\',\'allocate\']])\n ... with it:\n ... while not it.finished:\n ... addop(it[0], it[1], out=it[2])\n ... it.iternext()\n ... return it.operands[2]\n\n Here is an example outer product function:\n\n >>> def outer_it(x, y, out=None):\n ... mulop = np.multiply\n ... it = np.nditer([x, y, out], [\'external_loop\'],\n ... [[\'readonly\'], [\'readonly\'], [\'writeonly\', \'allocate\']],\n ... op_axes=[list(range(x.ndim)) + [-1] * y.ndim,\n ... [-1] * x.ndim + list(range(y.ndim)),\n ... None])\n ... with it:\n ... for (a, b, c) in it:\n ... mulop(a, b, out=c)\n ... return it.operands[2]\n\n >>> a = np.arange(2)+1\n >>> b = np.arange(3)+1\n >>> outer_it(a,b)\n array([[1, 2, 3],\n [2, 4, 6]])\n\n Here is an example function which operates like a "lambda" ufunc:\n\n >>> def luf(lamdaexpr, *args, **kwargs):\n ... \'\'\'luf(lambdaexpr, op1, ..., opn, out=None, order=\'K\', casting=\'safe\', buffersize=0)\'\'\'\n ... nargs = len(args)\n ... op = (kwargs.get(\'out\',None),) + args\n ... it = np.nditer(op, [\'buffered\',\'external_loop\'],\n ... [[\'writeonly\',\'allocate\',\'no_broadcast\']] +\n ... [[\'readonly\',\'nbo\',\'aligned\']]*nargs,\n ... order=kwargs.get(\'order\',\'K\'),\n ... casting=kwargs.get(\'casting\',\'safe\'),\n ... buffersize=kwargs.get(\'buffersize\',0))\n ... while not it.finished:\n ... it[0] = lamdaexpr(*it[1:])\n ... it.iternext()\n ... return it.operands[0]\n\n >>> a = np.arange(5)\n >>> b = np.ones(5)\n >>> luf(lambda i,j:i*i + j/2, a, b)\n array([ 0.5, 1.5, 4.5, 9.5, 16.5])\n\n If operand flags ``"writeonly"`` or ``"readwrite"`` are used the\n operands may be views into the original data with the\n `WRITEBACKIFCOPY` flag. In this case `nditer` must be used as a\n context manager or the `nditer.close` method must be called before\n using the result. The temporary data will be written back to the\n original data when the :meth:`~object.__exit__` function is called\n but not before:\n\n >>> a = np.arange(6, dtype=\'i4\')[::-2]\n >>> with np.nditer(a, [],\n ... [[\'writeonly\', \'updateifcopy\']],\n ... casting=\'unsafe\',\n ... op_dtypes=[np.dtype(\'f4\')]) as i:\n ... x = i.operands[0]\n ... x[:] = [-1, -2, -3]\n ... # a still unchanged here\n >>> a, x\n (array([-1, -2, -3], dtype=int32), array([-1., -2., -3.], dtype=float32))\n\n It is important to note that once the iterator is exited, dangling\n references (like `x` in the example) may or may not share data with\n the original data `a`. If writeback semantics were active, i.e. if\n `x.base.flags.writebackifcopy` is `True`, then exiting the iterator\n will sever the connection between `x` and `a`, writing to `x` will\n no longer write to `a`. If writeback semantics are not active, then\n `x.data` will still point at some part of `a.data`, and writing to\n one will affect the other.\n\n Context management and the `close` method appeared in version 1.15.0.\n\n ') add_newdoc('numpy._core', 'nditer', ('copy', '\n copy()\n\n Get a copy of the iterator in its current state.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.arange(10)\n >>> y = x + 1\n >>> it = np.nditer([x, y])\n >>> next(it)\n (array(0), array(1))\n >>> it2 = it.copy()\n >>> next(it2)\n (array(1), array(2))\n\n ')) add_newdoc('numpy._core', 'nditer', ('operands', '\n operands[`Slice`]\n\n The array(s) to be iterated over. Valid only before the iterator is closed.\n ')) add_newdoc('numpy._core', 'nditer', ('debug_print', '\n debug_print()\n\n Print the current state of the `nditer` instance and debug info to stdout.\n\n ')) add_newdoc('numpy._core', 'nditer', ('enable_external_loop', '\n enable_external_loop()\n\n When the "external_loop" was not used during construction, but\n is desired, this modifies the iterator to behave as if the flag\n was specified.\n\n ')) add_newdoc('numpy._core', 'nditer', ('iternext', '\n iternext()\n\n Check whether iterations are left, and perform a single internal iteration\n without returning the result. Used in the C-style pattern do-while\n pattern. For an example, see `nditer`.\n\n Returns\n -------\n iternext : bool\n Whether or not there are iterations left.\n\n ')) add_newdoc('numpy._core', 'nditer', ('remove_axis', '\n remove_axis(i, /)\n\n Removes axis `i` from the iterator. Requires that the flag "multi_index"\n be enabled.\n\n ')) add_newdoc('numpy._core', 'nditer', ('remove_multi_index', '\n remove_multi_index()\n\n When the "multi_index" flag was specified, this removes it, allowing\n the internal iteration structure to be optimized further.\n\n ')) add_newdoc('numpy._core', 'nditer', ('reset', '\n reset()\n\n Reset the iterator to its initial state.\n\n ')) add_newdoc('numpy._core', 'nested_iters', '\n nested_iters(op, axes, flags=None, op_flags=None, op_dtypes=None, order="K", casting="safe", buffersize=0)\n\n Create nditers for use in nested loops\n\n Create a tuple of `nditer` objects which iterate in nested loops over\n different axes of the op argument. The first iterator is used in the\n outermost loop, the last in the innermost loop. Advancing one will change\n the subsequent iterators to point at its new element.\n\n Parameters\n ----------\n op : ndarray or sequence of array_like\n The array(s) to iterate over.\n\n axes : list of list of int\n Each item is used as an "op_axes" argument to an nditer\n\n flags, op_flags, op_dtypes, order, casting, buffersize (optional)\n See `nditer` parameters of the same name\n\n Returns\n -------\n iters : tuple of nditer\n An nditer for each item in `axes`, outermost first\n\n See Also\n --------\n nditer\n\n Examples\n --------\n\n Basic usage. Note how y is the "flattened" version of\n [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified\n the first iter\'s axes as [1]\n\n >>> import numpy as np\n >>> a = np.arange(12).reshape(2, 3, 2)\n >>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"])\n >>> for x in i:\n ... print(i.multi_index)\n ... for y in j:\n ... print(\'\', j.multi_index, y)\n (0,)\n (0, 0) 0\n (0, 1) 1\n (1, 0) 6\n (1, 1) 7\n (1,)\n (0, 0) 2\n (0, 1) 3\n (1, 0) 8\n (1, 1) 9\n (2,)\n (0, 0) 4\n (0, 1) 5\n (1, 0) 10\n (1, 1) 11\n\n ') add_newdoc('numpy._core', 'nditer', ('close', '\n close()\n\n Resolve all writeback semantics in writeable operands.\n\n .. versionadded:: 1.15.0\n\n See Also\n --------\n\n :ref:`nditer-context-manager`\n\n ')) add_newdoc('numpy._core', 'broadcast', '\n Produce an object that mimics broadcasting.\n\n Parameters\n ----------\n in1, in2, ... : array_like\n Input parameters.\n\n Returns\n -------\n b : broadcast object\n Broadcast the input parameters against one another, and\n return an object that encapsulates the result.\n Amongst others, it has ``shape`` and ``nd`` properties, and\n may be used as an iterator.\n\n See Also\n --------\n broadcast_arrays\n broadcast_to\n broadcast_shapes\n\n Examples\n --------\n\n Manually adding two vectors, using broadcasting:\n\n >>> import numpy as np\n >>> x = np.array([[1], [2], [3]])\n >>> y = np.array([4, 5, 6])\n >>> b = np.broadcast(x, y)\n\n >>> out = np.empty(b.shape)\n >>> out.flat = [u+v for (u,v) in b]\n >>> out\n array([[5., 6., 7.],\n [6., 7., 8.],\n [7., 8., 9.]])\n\n Compare against built-in broadcasting:\n\n >>> x + y\n array([[5, 6, 7],\n [6, 7, 8],\n [7, 8, 9]])\n\n ') add_newdoc('numpy._core', 'broadcast', ('index', '\n current index in broadcasted result\n\n Examples\n --------\n\n >>> import numpy as np\n >>> x = np.array([[1], [2], [3]])\n >>> y = np.array([4, 5, 6])\n >>> b = np.broadcast(x, y)\n >>> b.index\n 0\n >>> next(b), next(b), next(b)\n ((1, 4), (1, 5), (1, 6))\n >>> b.index\n 3\n\n ')) add_newdoc('numpy._core', 'broadcast', ('iters', '\n tuple of iterators along ``self``\'s "components."\n\n Returns a tuple of `numpy.flatiter` objects, one for each "component"\n of ``self``.\n\n See Also\n --------\n numpy.flatiter\n\n Examples\n --------\n\n >>> import numpy as np\n >>> x = np.array([1, 2, 3])\n >>> y = np.array([[4], [5], [6]])\n >>> b = np.broadcast(x, y)\n >>> row, col = b.iters\n >>> next(row), next(col)\n (1, 4)\n\n ')) add_newdoc('numpy._core', 'broadcast', ('ndim', '\n Number of dimensions of broadcasted result. Alias for `nd`.\n\n .. versionadded:: 1.12.0\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([1, 2, 3])\n >>> y = np.array([[4], [5], [6]])\n >>> b = np.broadcast(x, y)\n >>> b.ndim\n 2\n\n ')) add_newdoc('numpy._core', 'broadcast', ('nd', '\n Number of dimensions of broadcasted result. For code intended for NumPy\n 1.12.0 and later the more consistent `ndim` is preferred.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([1, 2, 3])\n >>> y = np.array([[4], [5], [6]])\n >>> b = np.broadcast(x, y)\n >>> b.nd\n 2\n\n ')) add_newdoc('numpy._core', 'broadcast', ('numiter', '\n Number of iterators possessed by the broadcasted result.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([1, 2, 3])\n >>> y = np.array([[4], [5], [6]])\n >>> b = np.broadcast(x, y)\n >>> b.numiter\n 2\n\n ')) add_newdoc('numpy._core', 'broadcast', ('shape', '\n Shape of broadcasted result.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([1, 2, 3])\n >>> y = np.array([[4], [5], [6]])\n >>> b = np.broadcast(x, y)\n >>> b.shape\n (3, 3)\n\n ')) add_newdoc('numpy._core', 'broadcast', ('size', '\n Total size of broadcasted result.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([1, 2, 3])\n >>> y = np.array([[4], [5], [6]])\n >>> b = np.broadcast(x, y)\n >>> b.size\n 9\n\n ')) add_newdoc('numpy._core', 'broadcast', ('reset', "\n reset()\n\n Reset the broadcasted result's iterator(s).\n\n Parameters\n ----------\n None\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([1, 2, 3])\n >>> y = np.array([[4], [5], [6]])\n >>> b = np.broadcast(x, y)\n >>> b.index\n 0\n >>> next(b), next(b), next(b)\n ((1, 4), (2, 4), (3, 4))\n >>> b.index\n 3\n >>> b.reset()\n >>> b.index\n 0\n\n ")) add_newdoc('numpy._core.multiarray', 'array', "\n array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0,\n like=None)\n\n Create an array.\n\n Parameters\n ----------\n object : array_like\n An array, any object exposing the array interface, an object whose\n ``__array__`` method returns an array, or any (nested) sequence.\n If object is a scalar, a 0-dimensional array containing object is\n returned.\n dtype : data-type, optional\n The desired data-type for the array. If not given, NumPy will try to use\n a default ``dtype`` that can represent the values (by applying promotion\n rules when necessary.)\n copy : bool, optional\n If ``True`` (default), then the array data is copied. If ``None``,\n a copy will only be made if ``__array__`` returns a copy, if obj is\n a nested sequence, or if a copy is needed to satisfy any of the other\n requirements (``dtype``, ``order``, etc.). Note that any copy of\n the data is shallow, i.e., for arrays with object dtype, the new\n array will point to the same objects. See Examples for `ndarray.copy`.\n For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.\n Default: ``True``.\n order : {'K', 'A', 'C', 'F'}, optional\n Specify the memory layout of the array. If object is not an array, the\n newly created array will be in C order (row major) unless 'F' is\n specified, in which case it will be in Fortran order (column major).\n If object is an array the following holds.\n\n ===== ========= ===================================================\n order no copy copy=True\n ===== ========= ===================================================\n 'K' unchanged F & C order preserved, otherwise most similar order\n 'A' unchanged F order if input is F and not C, otherwise C order\n 'C' C order C order\n 'F' F order F order\n ===== ========= ===================================================\n\n When ``copy=None`` and a copy is made for other reasons, the result is\n the same as if ``copy=True``, with some exceptions for 'A', see the\n Notes section. The default order is 'K'.\n subok : bool, optional\n If True, then sub-classes will be passed-through, otherwise\n the returned array will be forced to be a base-class array (default).\n ndmin : int, optional\n Specifies the minimum number of dimensions that the resulting\n array should have. Ones will be prepended to the shape as\n needed to meet this requirement.\n ${ARRAY_FUNCTION_LIKE}\n\n .. versionadded:: 1.20.0\n\n Returns\n -------\n out : ndarray\n An array object satisfying the specified requirements.\n\n See Also\n --------\n empty_like : Return an empty array with shape and type of input.\n ones_like : Return an array of ones with shape and type of input.\n zeros_like : Return an array of zeros with shape and type of input.\n full_like : Return a new array with shape of input filled with value.\n empty : Return a new uninitialized array.\n ones : Return a new array setting values to one.\n zeros : Return a new array setting values to zero.\n full : Return a new array of given shape filled with value.\n copy: Return an array copy of the given object.\n\n\n Notes\n -----\n When order is 'A' and ``object`` is an array in neither 'C' nor 'F' order,\n and a copy is forced by a change in dtype, then the order of the result is\n not necessarily 'C' as expected. This is likely a bug.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.array([1, 2, 3])\n array([1, 2, 3])\n\n Upcasting:\n\n >>> np.array([1, 2, 3.0])\n array([ 1., 2., 3.])\n\n More than one dimension:\n\n >>> np.array([[1, 2], [3, 4]])\n array([[1, 2],\n [3, 4]])\n\n Minimum dimensions 2:\n\n >>> np.array([1, 2, 3], ndmin=2)\n array([[1, 2, 3]])\n\n Type provided:\n\n >>> np.array([1, 2, 3], dtype=complex)\n array([ 1.+0.j, 2.+0.j, 3.+0.j])\n\n Data-type consisting of more than one element:\n\n >>> x = np.array([(1,2),(3,4)],dtype=[('a','>> x['a']\n array([1, 3], dtype=int32)\n\n Creating an array from sub-classes:\n\n >>> np.array(np.asmatrix('1 2; 3 4'))\n array([[1, 2],\n [3, 4]])\n\n >>> np.array(np.asmatrix('1 2; 3 4'), subok=True)\n matrix([[1, 2],\n [3, 4]])\n\n ".replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc)) add_newdoc('numpy._core.multiarray', 'asarray', '\n asarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)\n\n Convert the input to an array.\n\n Parameters\n ----------\n a : array_like\n Input data, in any form that can be converted to an array. This\n includes lists, lists of tuples, tuples, tuples of tuples, tuples\n of lists and ndarrays.\n dtype : data-type, optional\n By default, the data-type is inferred from the input data.\n order : {\'C\', \'F\', \'A\', \'K\'}, optional\n Memory layout. \'A\' and \'K\' depend on the order of input array a.\n \'C\' row-major (C-style),\n \'F\' column-major (Fortran-style) memory representation.\n \'A\' (any) means \'F\' if `a` is Fortran contiguous, \'C\' otherwise\n \'K\' (keep) preserve input order\n Defaults to \'K\'.\n device : str, optional\n The device on which to place the created array. Default: ``None``.\n For Array-API interoperability only, so must be ``"cpu"`` if passed.\n\n .. versionadded:: 2.0.0\n copy : bool, optional\n If ``True``, then the object is copied. If ``None`` then the object is\n copied only if needed, i.e. if ``__array__`` returns a copy, if obj\n is a nested sequence, or if a copy is needed to satisfy any of\n the other requirements (``dtype``, ``order``, etc.).\n For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.\n Default: ``None``.\n\n .. versionadded:: 2.0.0\n ${ARRAY_FUNCTION_LIKE}\n\n .. versionadded:: 1.20.0\n\n Returns\n -------\n out : ndarray\n Array interpretation of ``a``. No copy is performed if the input\n is already an ndarray with matching dtype and order. If ``a`` is a\n subclass of ndarray, a base class ndarray is returned.\n\n See Also\n --------\n asanyarray : Similar function which passes through subclasses.\n ascontiguousarray : Convert input to a contiguous array.\n asfortranarray : Convert input to an ndarray with column-major\n memory order.\n asarray_chkfinite : Similar function which checks input for NaNs and Infs.\n fromiter : Create an array from an iterator.\n fromfunction : Construct an array by executing a function on grid\n positions.\n\n Examples\n --------\n Convert a list into an array:\n\n >>> a = [1, 2]\n >>> import numpy as np\n >>> np.asarray(a)\n array([1, 2])\n\n Existing arrays are not copied:\n\n >>> a = np.array([1, 2])\n >>> np.asarray(a) is a\n True\n\n If `dtype` is set, array is copied only if dtype does not match:\n\n >>> a = np.array([1, 2], dtype=np.float32)\n >>> np.shares_memory(np.asarray(a, dtype=np.float32), a)\n True\n >>> np.shares_memory(np.asarray(a, dtype=np.float64), a)\n False\n\n Contrary to `asanyarray`, ndarray subclasses are not passed through:\n\n >>> issubclass(np.recarray, np.ndarray)\n True\n >>> a = np.array([(1., 2), (3., 4)], dtype=\'f4,i4\').view(np.recarray)\n >>> np.asarray(a) is a\n False\n >>> np.asanyarray(a) is a\n True\n\n '.replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc)) add_newdoc('numpy._core.multiarray', 'asanyarray', '\n asanyarray(a, dtype=None, order=None, *, like=None)\n\n Convert the input to an ndarray, but pass ndarray subclasses through.\n\n Parameters\n ----------\n a : array_like\n Input data, in any form that can be converted to an array. This\n includes scalars, lists, lists of tuples, tuples, tuples of tuples,\n tuples of lists, and ndarrays.\n dtype : data-type, optional\n By default, the data-type is inferred from the input data.\n order : {\'C\', \'F\', \'A\', \'K\'}, optional\n Memory layout. \'A\' and \'K\' depend on the order of input array a.\n \'C\' row-major (C-style),\n \'F\' column-major (Fortran-style) memory representation.\n \'A\' (any) means \'F\' if `a` is Fortran contiguous, \'C\' otherwise\n \'K\' (keep) preserve input order\n Defaults to \'C\'.\n device : str, optional\n The device on which to place the created array. Default: ``None``.\n For Array-API interoperability only, so must be ``"cpu"`` if passed.\n\n .. versionadded:: 2.1.0\n\n copy : bool, optional\n If ``True``, then the object is copied. If ``None`` then the object is\n copied only if needed, i.e. if ``__array__`` returns a copy, if obj\n is a nested sequence, or if a copy is needed to satisfy any of\n the other requirements (``dtype``, ``order``, etc.).\n For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.\n Default: ``None``.\n\n .. versionadded:: 2.1.0\n\n ${ARRAY_FUNCTION_LIKE}\n\n .. versionadded:: 1.20.0\n\n Returns\n -------\n out : ndarray or an ndarray subclass\n Array interpretation of `a`. If `a` is an ndarray or a subclass\n of ndarray, it is returned as-is and no copy is performed.\n\n See Also\n --------\n asarray : Similar function which always returns ndarrays.\n ascontiguousarray : Convert input to a contiguous array.\n asfortranarray : Convert input to an ndarray with column-major\n memory order.\n asarray_chkfinite : Similar function which checks input for NaNs and\n Infs.\n fromiter : Create an array from an iterator.\n fromfunction : Construct an array by executing a function on grid\n positions.\n\n Examples\n --------\n Convert a list into an array:\n\n >>> a = [1, 2]\n >>> import numpy as np\n >>> np.asanyarray(a)\n array([1, 2])\n\n Instances of `ndarray` subclasses are passed through as-is:\n\n >>> a = np.array([(1., 2), (3., 4)], dtype=\'f4,i4\').view(np.recarray)\n >>> np.asanyarray(a) is a\n True\n\n '.replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc)) add_newdoc('numpy._core.multiarray', 'ascontiguousarray', "\n ascontiguousarray(a, dtype=None, *, like=None)\n\n Return a contiguous array (ndim >= 1) in memory (C order).\n\n Parameters\n ----------\n a : array_like\n Input array.\n dtype : str or dtype object, optional\n Data-type of returned array.\n ${ARRAY_FUNCTION_LIKE}\n\n .. versionadded:: 1.20.0\n\n Returns\n -------\n out : ndarray\n Contiguous array of same shape and content as `a`, with type `dtype`\n if specified.\n\n See Also\n --------\n asfortranarray : Convert input to an ndarray with column-major\n memory order.\n require : Return an ndarray that satisfies requirements.\n ndarray.flags : Information about the memory layout of the array.\n\n Examples\n --------\n Starting with a Fortran-contiguous array:\n\n >>> import numpy as np\n >>> x = np.ones((2, 3), order='F')\n >>> x.flags['F_CONTIGUOUS']\n True\n\n Calling ``ascontiguousarray`` makes a C-contiguous copy:\n\n >>> y = np.ascontiguousarray(x)\n >>> y.flags['C_CONTIGUOUS']\n True\n >>> np.may_share_memory(x, y)\n False\n\n Now, starting with a C-contiguous array:\n\n >>> x = np.ones((2, 3), order='C')\n >>> x.flags['C_CONTIGUOUS']\n True\n\n Then, calling ``ascontiguousarray`` returns the same object:\n\n >>> y = np.ascontiguousarray(x)\n >>> x is y\n True\n\n Note: This function returns an array with at least one-dimension (1-d)\n so it will not preserve 0-d arrays.\n\n ".replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc)) add_newdoc('numpy._core.multiarray', 'asfortranarray', "\n asfortranarray(a, dtype=None, *, like=None)\n\n Return an array (ndim >= 1) laid out in Fortran order in memory.\n\n Parameters\n ----------\n a : array_like\n Input array.\n dtype : str or dtype object, optional\n By default, the data-type is inferred from the input data.\n ${ARRAY_FUNCTION_LIKE}\n\n .. versionadded:: 1.20.0\n\n Returns\n -------\n out : ndarray\n The input `a` in Fortran, or column-major, order.\n\n See Also\n --------\n ascontiguousarray : Convert input to a contiguous (C order) array.\n asanyarray : Convert input to an ndarray with either row or\n column-major memory order.\n require : Return an ndarray that satisfies requirements.\n ndarray.flags : Information about the memory layout of the array.\n\n Examples\n --------\n Starting with a C-contiguous array:\n\n >>> import numpy as np\n >>> x = np.ones((2, 3), order='C')\n >>> x.flags['C_CONTIGUOUS']\n True\n\n Calling ``asfortranarray`` makes a Fortran-contiguous copy:\n\n >>> y = np.asfortranarray(x)\n >>> y.flags['F_CONTIGUOUS']\n True\n >>> np.may_share_memory(x, y)\n False\n\n Now, starting with a Fortran-contiguous array:\n\n >>> x = np.ones((2, 3), order='F')\n >>> x.flags['F_CONTIGUOUS']\n True\n\n Then, calling ``asfortranarray`` returns the same object:\n\n >>> y = np.asfortranarray(x)\n >>> x is y\n True\n\n Note: This function returns an array with at least one-dimension (1-d)\n so it will not preserve 0-d arrays.\n\n ".replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc)) add_newdoc('numpy._core.multiarray', 'empty', '\n empty(shape, dtype=float, order=\'C\', *, device=None, like=None)\n\n Return a new array of given shape and type, without initializing entries.\n\n Parameters\n ----------\n shape : int or tuple of int\n Shape of the empty array, e.g., ``(2, 3)`` or ``2``.\n dtype : data-type, optional\n Desired output data-type for the array, e.g, `numpy.int8`. Default is\n `numpy.float64`.\n order : {\'C\', \'F\'}, optional, default: \'C\'\n Whether to store multi-dimensional data in row-major\n (C-style) or column-major (Fortran-style) order in\n memory.\n device : str, optional\n The device on which to place the created array. Default: ``None``.\n For Array-API interoperability only, so must be ``"cpu"`` if passed.\n\n .. versionadded:: 2.0.0\n ${ARRAY_FUNCTION_LIKE}\n\n .. versionadded:: 1.20.0\n\n Returns\n -------\n out : ndarray\n Array of uninitialized (arbitrary) data of the given shape, dtype, and\n order. Object arrays will be initialized to None.\n\n See Also\n --------\n empty_like : Return an empty array with shape and type of input.\n ones : Return a new array setting values to one.\n zeros : Return a new array setting values to zero.\n full : Return a new array of given shape filled with value.\n\n Notes\n -----\n Unlike other array creation functions (e.g. `zeros`, `ones`, `full`),\n `empty` does not initialize the values of the array, and may therefore be\n marginally faster. However, the values stored in the newly allocated array\n are arbitrary. For reproducible behavior, be sure to set each element of\n the array before reading.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.empty([2, 2])\n array([[ -9.74499359e+001, 6.69583040e-309],\n [ 2.13182611e-314, 3.06959433e-309]]) #uninitialized\n\n >>> np.empty([2, 2], dtype=int)\n array([[-1073741821, -1067949133],\n [ 496041986, 19249760]]) #uninitialized\n\n '.replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc)) add_newdoc('numpy._core.multiarray', 'scalar', '\n scalar(dtype, obj)\n\n Return a new scalar array of the given type initialized with obj.\n\n This function is meant mainly for pickle support. `dtype` must be a\n valid data-type descriptor. If `dtype` corresponds to an object\n descriptor, then `obj` can be any object, otherwise `obj` must be a\n string. If `obj` is not given, it will be interpreted as None for object\n type and as zeros for all other types.\n\n ') add_newdoc('numpy._core.multiarray', 'zeros', "\n zeros(shape, dtype=float, order='C', *, like=None)\n\n Return a new array of given shape and type, filled with zeros.\n\n Parameters\n ----------\n shape : int or tuple of ints\n Shape of the new array, e.g., ``(2, 3)`` or ``2``.\n dtype : data-type, optional\n The desired data-type for the array, e.g., `numpy.int8`. Default is\n `numpy.float64`.\n order : {'C', 'F'}, optional, default: 'C'\n Whether to store multi-dimensional data in row-major\n (C-style) or column-major (Fortran-style) order in\n memory.\n ${ARRAY_FUNCTION_LIKE}\n\n .. versionadded:: 1.20.0\n\n Returns\n -------\n out : ndarray\n Array of zeros with the given shape, dtype, and order.\n\n See Also\n --------\n zeros_like : Return an array of zeros with shape and type of input.\n empty : Return a new uninitialized array.\n ones : Return a new array setting values to one.\n full : Return a new array of given shape filled with value.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.zeros(5)\n array([ 0., 0., 0., 0., 0.])\n\n >>> np.zeros((5,), dtype=int)\n array([0, 0, 0, 0, 0])\n\n >>> np.zeros((2, 1))\n array([[ 0.],\n [ 0.]])\n\n >>> s = (2,2)\n >>> np.zeros(s)\n array([[ 0., 0.],\n [ 0., 0.]])\n\n >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype\n array([(0, 0), (0, 0)],\n dtype=[('x', '>> import numpy as np\n >>> np.fromstring('1 2', dtype=int, sep=' ')\n array([1, 2])\n >>> np.fromstring('1, 2', dtype=int, sep=',')\n array([1, 2])\n\n ".replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc)) add_newdoc('numpy._core.multiarray', 'compare_chararrays', '\n compare_chararrays(a1, a2, cmp, rstrip)\n\n Performs element-wise comparison of two string arrays using the\n comparison operator specified by `cmp`.\n\n Parameters\n ----------\n a1, a2 : array_like\n Arrays to be compared.\n cmp : {"<", "<=", "==", ">=", ">", "!="}\n Type of comparison.\n rstrip : Boolean\n If True, the spaces at the end of Strings are removed before the comparison.\n\n Returns\n -------\n out : ndarray\n The output array of type Boolean with the same shape as a and b.\n\n Raises\n ------\n ValueError\n If `cmp` is not valid.\n TypeError\n If at least one of `a` or `b` is a non-string array\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array(["a", "b", "cde"])\n >>> b = np.array(["a", "a", "dec"])\n >>> np.char.compare_chararrays(a, b, ">", True)\n array([False, True, False])\n\n ') add_newdoc('numpy._core.multiarray', 'fromiter', '\n fromiter(iter, dtype, count=-1, *, like=None)\n\n Create a new 1-dimensional array from an iterable object.\n\n Parameters\n ----------\n iter : iterable object\n An iterable object providing data for the array.\n dtype : data-type\n The data-type of the returned array.\n\n .. versionchanged:: 1.23\n Object and subarray dtypes are now supported (note that the final\n result is not 1-D for a subarray dtype).\n\n count : int, optional\n The number of items to read from *iterable*. The default is -1,\n which means all data is read.\n ${ARRAY_FUNCTION_LIKE}\n\n .. versionadded:: 1.20.0\n\n Returns\n -------\n out : ndarray\n The output array.\n\n Notes\n -----\n Specify `count` to improve performance. It allows ``fromiter`` to\n pre-allocate the output array, instead of resizing it on demand.\n\n Examples\n --------\n >>> import numpy as np\n >>> iterable = (x*x for x in range(5))\n >>> np.fromiter(iterable, float)\n array([ 0., 1., 4., 9., 16.])\n\n A carefully constructed subarray dtype will lead to higher dimensional\n results:\n\n >>> iterable = ((x+1, x+2) for x in range(5))\n >>> np.fromiter(iterable, dtype=np.dtype((int, 2)))\n array([[1, 2],\n [2, 3],\n [3, 4],\n [4, 5],\n [5, 6]])\n\n\n '.replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc)) add_newdoc('numpy._core.multiarray', 'fromfile', '\n fromfile(file, dtype=float, count=-1, sep=\'\', offset=0, *, like=None)\n\n Construct an array from data in a text or binary file.\n\n A highly efficient way of reading binary data with a known data-type,\n as well as parsing simply formatted text files. Data written using the\n `tofile` method can be read using this function.\n\n Parameters\n ----------\n file : file or str or Path\n Open file object or filename.\n\n .. versionchanged:: 1.17.0\n `pathlib.Path` objects are now accepted.\n\n dtype : data-type\n Data type of the returned array.\n For binary files, it is used to determine the size and byte-order\n of the items in the file.\n Most builtin numeric types are supported and extension types may be supported.\n\n .. versionadded:: 1.18.0\n Complex dtypes.\n\n count : int\n Number of items to read. ``-1`` means all items (i.e., the complete\n file).\n sep : str\n Separator between items if file is a text file.\n Empty ("") separator means the file should be treated as binary.\n Spaces (" ") in the separator match zero or more whitespace characters.\n A separator consisting only of spaces must match at least one\n whitespace.\n offset : int\n The offset (in bytes) from the file\'s current position. Defaults to 0.\n Only permitted for binary files.\n\n .. versionadded:: 1.17.0\n ${ARRAY_FUNCTION_LIKE}\n\n .. versionadded:: 1.20.0\n\n See also\n --------\n load, save\n ndarray.tofile\n loadtxt : More flexible way of loading data from a text file.\n\n Notes\n -----\n Do not rely on the combination of `tofile` and `fromfile` for\n data storage, as the binary files generated are not platform\n independent. In particular, no byte-order or data-type information is\n saved. Data can be stored in the platform independent ``.npy`` format\n using `save` and `load` instead.\n\n Examples\n --------\n Construct an ndarray:\n\n >>> import numpy as np\n >>> dt = np.dtype([(\'time\', [(\'min\', np.int64), (\'sec\', np.int64)]),\n ... (\'temp\', float)])\n >>> x = np.zeros((1,), dtype=dt)\n >>> x[\'time\'][\'min\'] = 10; x[\'temp\'] = 98.25\n >>> x\n array([((10, 0), 98.25)],\n dtype=[(\'time\', [(\'min\', \'>> import tempfile\n >>> fname = tempfile.mkstemp()[1]\n >>> x.tofile(fname)\n\n Read the raw data from disk:\n\n >>> np.fromfile(fname, dtype=dt)\n array([((10, 0), 98.25)],\n dtype=[(\'time\', [(\'min\', \'>> np.save(fname, x)\n >>> np.load(fname + \'.npy\')\n array([((10, 0), 98.25)],\n dtype=[(\'time\', [(\'min\', \'>> dt = np.dtype(int)\n >>> dt = dt.newbyteorder('>')\n >>> np.frombuffer(buf, dtype=dt) # doctest: +SKIP\n\n The data of the resulting array will not be byteswapped, but will be\n interpreted correctly.\n\n This function creates a view into the original object. This should be safe\n in general, but it may make sense to copy the result when the original\n object is mutable or untrusted.\n\n Examples\n --------\n >>> import numpy as np\n >>> s = b'hello world'\n >>> np.frombuffer(s, dtype='S1', count=5, offset=6)\n array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')\n\n >>> np.frombuffer(b'\\x01\\x02', dtype=np.uint8)\n array([1, 2], dtype=uint8)\n >>> np.frombuffer(b'\\x01\\x02\\x03\\x04\\x05', dtype=np.uint8, count=3)\n array([1, 2, 3], dtype=uint8)\n\n ".replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc)) add_newdoc('numpy._core.multiarray', 'from_dlpack', '\n from_dlpack(x, /, *, device=None, copy=None)\n\n Create a NumPy array from an object implementing the ``__dlpack__``\n protocol. Generally, the returned NumPy array is a read-only view\n of the input object. See [1]_ and [2]_ for more details.\n\n Parameters\n ----------\n x : object\n A Python object that implements the ``__dlpack__`` and\n ``__dlpack_device__`` methods.\n device : device, optional\n Device on which to place the created array. Default: ``None``.\n Must be ``"cpu"`` if passed which may allow importing an array\n that is not already CPU available.\n copy : bool, optional\n Boolean indicating whether or not to copy the input. If ``True``,\n the copy will be made. If ``False``, the function will never copy,\n and will raise ``BufferError`` in case a copy is deemed necessary.\n Passing it requests a copy from the exporter who may or may not\n implement the capability.\n If ``None``, the function will reuse the existing memory buffer if\n possible and copy otherwise. Default: ``None``.\n\n\n Returns\n -------\n out : ndarray\n\n References\n ----------\n .. [1] Array API documentation,\n https://data-apis.org/array-api/latest/design_topics/data_interchange.html#syntax-for-data-interchange-with-dlpack\n\n .. [2] Python specification for DLPack,\n https://dmlc.github.io/dlpack/latest/python_spec.html\n\n Examples\n --------\n >>> import torch # doctest: +SKIP\n >>> x = torch.arange(10) # doctest: +SKIP\n >>> # create a view of the torch tensor "x" in NumPy\n >>> y = np.from_dlpack(x) # doctest: +SKIP\n ') add_newdoc('numpy._core.multiarray', 'correlate', 'cross_correlate(a,v, mode=0)') add_newdoc('numpy._core.multiarray', 'arange', '\n arange([start,] stop[, step,], dtype=None, *, device=None, like=None)\n\n Return evenly spaced values within a given interval.\n\n ``arange`` can be called with a varying number of positional arguments:\n\n * ``arange(stop)``: Values are generated within the half-open interval\n ``[0, stop)`` (in other words, the interval including `start` but\n excluding `stop`).\n * ``arange(start, stop)``: Values are generated within the half-open\n interval ``[start, stop)``.\n * ``arange(start, stop, step)`` Values are generated within the half-open\n interval ``[start, stop)``, with spacing between values given by\n ``step``.\n\n For integer arguments the function is roughly equivalent to the Python\n built-in :py:class:`range`, but returns an ndarray rather than a ``range``\n instance.\n\n When using a non-integer step, such as 0.1, it is often better to use\n `numpy.linspace`.\n\n See the Warning sections below for more information.\n\n Parameters\n ----------\n start : integer or real, optional\n Start of interval. The interval includes this value. The default\n start value is 0.\n stop : integer or real\n End of interval. The interval does not include this value, except\n in some cases where `step` is not an integer and floating point\n round-off affects the length of `out`.\n step : integer or real, optional\n Spacing between values. For any output `out`, this is the distance\n between two adjacent values, ``out[i+1] - out[i]``. The default\n step size is 1. If `step` is specified as a position argument,\n `start` must also be given.\n dtype : dtype, optional\n The type of the output array. If `dtype` is not given, infer the data\n type from the other input arguments.\n device : str, optional\n The device on which to place the created array. Default: ``None``.\n For Array-API interoperability only, so must be ``"cpu"`` if passed.\n\n .. versionadded:: 2.0.0\n ${ARRAY_FUNCTION_LIKE}\n\n .. versionadded:: 1.20.0\n\n Returns\n -------\n arange : ndarray\n Array of evenly spaced values.\n\n For floating point arguments, the length of the result is\n ``ceil((stop - start)/step)``. Because of floating point overflow,\n this rule may result in the last element of `out` being greater\n than `stop`.\n\n Warnings\n --------\n The length of the output might not be numerically stable.\n\n Another stability issue is due to the internal implementation of\n `numpy.arange`.\n The actual step value used to populate the array is\n ``dtype(start + step) - dtype(start)`` and not `step`. Precision loss\n can occur here, due to casting or due to using floating points when\n `start` is much larger than `step`. This can lead to unexpected\n behaviour. For example::\n\n >>> np.arange(0, 5, 0.5, dtype=int)\n array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n >>> np.arange(-3, 3, 0.5, dtype=int)\n array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])\n\n In such cases, the use of `numpy.linspace` should be preferred.\n\n The built-in :py:class:`range` generates :std:doc:`Python built-in integers\n that have arbitrary size `, while `numpy.arange`\n produces `numpy.int32` or `numpy.int64` numbers. This may result in\n incorrect results for large integer values::\n\n >>> power = 40\n >>> modulo = 10000\n >>> x1 = [(n ** power) % modulo for n in range(8)]\n >>> x2 = [(n ** power) % modulo for n in np.arange(8)]\n >>> print(x1)\n [0, 1, 7776, 8801, 6176, 625, 6576, 4001] # correct\n >>> print(x2)\n [0, 1, 7776, 7185, 0, 5969, 4816, 3361] # incorrect\n\n See Also\n --------\n numpy.linspace : Evenly spaced numbers with careful handling of endpoints.\n numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.\n numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.\n :ref:`how-to-partition`\n\n Examples\n --------\n >>> import numpy as np\n >>> np.arange(3)\n array([0, 1, 2])\n >>> np.arange(3.0)\n array([ 0., 1., 2.])\n >>> np.arange(3,7)\n array([3, 4, 5, 6])\n >>> np.arange(3,7,2)\n array([3, 5])\n\n '.replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc)) add_newdoc('numpy._core.multiarray', '_get_ndarray_c_version', '_get_ndarray_c_version()\n\n Return the compile time NPY_VERSION (formerly called NDARRAY_VERSION) number.\n\n ') add_newdoc('numpy._core.multiarray', '_reconstruct', '_reconstruct(subtype, shape, dtype)\n\n Construct an empty array. Used by Pickles.\n\n ') add_newdoc('numpy._core.multiarray', 'promote_types', '\n promote_types(type1, type2)\n\n Returns the data type with the smallest size and smallest scalar\n kind to which both ``type1`` and ``type2`` may be safely cast.\n The returned data type is always considered "canonical", this mainly\n means that the promoted dtype will always be in native byte order.\n\n This function is symmetric, but rarely associative.\n\n Parameters\n ----------\n type1 : dtype or dtype specifier\n First data type.\n type2 : dtype or dtype specifier\n Second data type.\n\n Returns\n -------\n out : dtype\n The promoted data type.\n\n Notes\n -----\n Please see `numpy.result_type` for additional information about promotion.\n\n .. versionadded:: 1.6.0\n\n Starting in NumPy 1.9, promote_types function now returns a valid string\n length when given an integer or float dtype as one argument and a string\n dtype as another argument. Previously it always returned the input string\n dtype, even if it wasn\'t long enough to store the max integer/float value\n converted to a string.\n\n .. versionchanged:: 1.23.0\n\n NumPy now supports promotion for more structured dtypes. It will now\n remove unnecessary padding from a structure dtype and promote included\n fields individually.\n\n See Also\n --------\n result_type, dtype, can_cast\n\n Examples\n --------\n >>> import numpy as np\n >>> np.promote_types(\'f4\', \'f8\')\n dtype(\'float64\')\n\n >>> np.promote_types(\'i8\', \'f4\')\n dtype(\'float64\')\n\n >>> np.promote_types(\'>i8\', \'>> np.promote_types(\'i4\', \'S8\')\n dtype(\'S11\')\n\n An example of a non-associative case:\n\n >>> p = np.promote_types\n >>> p(\'S\', p(\'i1\', \'u1\'))\n dtype(\'S6\')\n >>> p(p(\'S\', \'i1\'), \'u1\')\n dtype(\'S4\')\n\n ') add_newdoc('numpy._core.multiarray', 'c_einsum', "\n c_einsum(subscripts, *operands, out=None, dtype=None, order='K',\n casting='safe')\n\n *This documentation shadows that of the native python implementation of the `einsum` function,\n except all references and examples related to the `optimize` argument (v 0.12.0) have been removed.*\n\n Evaluates the Einstein summation convention on the operands.\n\n Using the Einstein summation convention, many common multi-dimensional,\n linear algebraic array operations can be represented in a simple fashion.\n In *implicit* mode `einsum` computes these values.\n\n In *explicit* mode, `einsum` provides further flexibility to compute\n other array operations that might not be considered classical Einstein\n summation operations, by disabling, or forcing summation over specified\n subscript labels.\n\n See the notes and examples for clarification.\n\n Parameters\n ----------\n subscripts : str\n Specifies the subscripts for summation as comma separated list of\n subscript labels. An implicit (classical Einstein summation)\n calculation is performed unless the explicit indicator '->' is\n included as well as subscript labels of the precise output form.\n operands : list of array_like\n These are the arrays for the operation.\n out : ndarray, optional\n If provided, the calculation is done into this array.\n dtype : {data-type, None}, optional\n If provided, forces the calculation to use the data type specified.\n Note that you may have to also give a more liberal `casting`\n parameter to allow the conversions. Default is None.\n order : {'C', 'F', 'A', 'K'}, optional\n Controls the memory layout of the output. 'C' means it should\n be C contiguous. 'F' means it should be Fortran contiguous,\n 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.\n 'K' means it should be as close to the layout of the inputs as\n is possible, including arbitrarily permuted axes.\n Default is 'K'.\n casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional\n Controls what kind of data casting may occur. Setting this to\n 'unsafe' is not recommended, as it can adversely affect accumulations.\n\n * 'no' means the data types should not be cast at all.\n * 'equiv' means only byte-order changes are allowed.\n * 'safe' means only casts which can preserve values are allowed.\n * 'same_kind' means only safe casts or casts within a kind,\n like float64 to float32, are allowed.\n * 'unsafe' means any data conversions may be done.\n\n Default is 'safe'.\n optimize : {False, True, 'greedy', 'optimal'}, optional\n Controls if intermediate optimization should occur. No optimization\n will occur if False and True will default to the 'greedy' algorithm.\n Also accepts an explicit contraction list from the ``np.einsum_path``\n function. See ``np.einsum_path`` for more details. Defaults to False.\n\n Returns\n -------\n output : ndarray\n The calculation based on the Einstein summation convention.\n\n See Also\n --------\n einsum_path, dot, inner, outer, tensordot, linalg.multi_dot\n\n Notes\n -----\n .. versionadded:: 1.6.0\n\n The Einstein summation convention can be used to compute\n many multi-dimensional, linear algebraic array operations. `einsum`\n provides a succinct way of representing these.\n\n A non-exhaustive list of these operations,\n which can be computed by `einsum`, is shown below along with examples:\n\n * Trace of an array, :py:func:`numpy.trace`.\n * Return a diagonal, :py:func:`numpy.diag`.\n * Array axis summations, :py:func:`numpy.sum`.\n * Transpositions and permutations, :py:func:`numpy.transpose`.\n * Matrix multiplication and dot product, :py:func:`numpy.matmul` :py:func:`numpy.dot`.\n * Vector inner and outer products, :py:func:`numpy.inner` :py:func:`numpy.outer`.\n * Broadcasting, element-wise and scalar multiplication, :py:func:`numpy.multiply`.\n * Tensor contractions, :py:func:`numpy.tensordot`.\n * Chained array operations, in efficient calculation order, :py:func:`numpy.einsum_path`.\n\n The subscripts string is a comma-separated list of subscript labels,\n where each label refers to a dimension of the corresponding operand.\n Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``\n is equivalent to :py:func:`np.inner(a,b) `. If a label\n appears only once, it is not summed, so ``np.einsum('i', a)`` produces a\n view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)``\n describes traditional matrix multiplication and is equivalent to\n :py:func:`np.matmul(a,b) `. Repeated subscript labels in one\n operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent\n to :py:func:`np.trace(a) `.\n\n In *implicit mode*, the chosen subscripts are important\n since the axes of the output are reordered alphabetically. This\n means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while\n ``np.einsum('ji', a)`` takes its transpose. Additionally,\n ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,\n ``np.einsum('ij,jh', a, b)`` returns the transpose of the\n multiplication since subscript 'h' precedes subscript 'i'.\n\n In *explicit mode* the output can be directly controlled by\n specifying output subscript labels. This requires the\n identifier '->' as well as the list of output subscript labels.\n This feature increases the flexibility of the function since\n summing can be disabled or forced when required. The call\n ``np.einsum('i->', a)`` is like :py:func:`np.sum(a) `\n if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``\n is like :py:func:`np.diag(a) ` if ``a`` is a square 2-D array.\n The difference is that `einsum` does not allow broadcasting by default.\n Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the\n order of the output subscript labels and therefore returns matrix\n multiplication, unlike the example above in implicit mode.\n\n To enable and control broadcasting, use an ellipsis. Default\n NumPy-style broadcasting is done by adding an ellipsis\n to the left of each term, like ``np.einsum('...ii->...i', a)``.\n ``np.einsum('...i->...', a)`` is like\n :py:func:`np.sum(a, axis=-1) ` for array ``a`` of any shape.\n To take the trace along the first and last axes,\n you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix\n product with the left-most indices instead of rightmost, one can do\n ``np.einsum('ij...,jk...->ik...', a, b)``.\n\n When there is only one operand, no axes are summed, and no output\n parameter is provided, a view into the operand is returned instead\n of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``\n produces a view (changed in version 1.10.0).\n\n `einsum` also provides an alternative way to provide the subscripts\n and operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.\n If the output shape is not provided in this format `einsum` will be\n calculated in implicit mode, otherwise it will be performed explicitly.\n The examples below have corresponding `einsum` calls with the two\n parameter methods.\n\n .. versionadded:: 1.10.0\n\n Views returned from einsum are now writeable whenever the input array\n is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now\n have the same effect as :py:func:`np.swapaxes(a, 0, 2) `\n and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal\n of a 2D array.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.arange(25).reshape(5,5)\n >>> b = np.arange(5)\n >>> c = np.arange(6).reshape(2,3)\n\n Trace of a matrix:\n\n >>> np.einsum('ii', a)\n 60\n >>> np.einsum(a, [0,0])\n 60\n >>> np.trace(a)\n 60\n\n Extract the diagonal (requires explicit form):\n\n >>> np.einsum('ii->i', a)\n array([ 0, 6, 12, 18, 24])\n >>> np.einsum(a, [0,0], [0])\n array([ 0, 6, 12, 18, 24])\n >>> np.diag(a)\n array([ 0, 6, 12, 18, 24])\n\n Sum over an axis (requires explicit form):\n\n >>> np.einsum('ij->i', a)\n array([ 10, 35, 60, 85, 110])\n >>> np.einsum(a, [0,1], [0])\n array([ 10, 35, 60, 85, 110])\n >>> np.sum(a, axis=1)\n array([ 10, 35, 60, 85, 110])\n\n For higher dimensional arrays summing a single axis can be done with ellipsis:\n\n >>> np.einsum('...j->...', a)\n array([ 10, 35, 60, 85, 110])\n >>> np.einsum(a, [Ellipsis,1], [Ellipsis])\n array([ 10, 35, 60, 85, 110])\n\n Compute a matrix transpose, or reorder any number of axes:\n\n >>> np.einsum('ji', c)\n array([[0, 3],\n [1, 4],\n [2, 5]])\n >>> np.einsum('ij->ji', c)\n array([[0, 3],\n [1, 4],\n [2, 5]])\n >>> np.einsum(c, [1,0])\n array([[0, 3],\n [1, 4],\n [2, 5]])\n >>> np.transpose(c)\n array([[0, 3],\n [1, 4],\n [2, 5]])\n\n Vector inner products:\n\n >>> np.einsum('i,i', b, b)\n 30\n >>> np.einsum(b, [0], b, [0])\n 30\n >>> np.inner(b,b)\n 30\n\n Matrix vector multiplication:\n\n >>> np.einsum('ij,j', a, b)\n array([ 30, 80, 130, 180, 230])\n >>> np.einsum(a, [0,1], b, [1])\n array([ 30, 80, 130, 180, 230])\n >>> np.dot(a, b)\n array([ 30, 80, 130, 180, 230])\n >>> np.einsum('...j,j', a, b)\n array([ 30, 80, 130, 180, 230])\n\n Broadcasting and scalar multiplication:\n\n >>> np.einsum('..., ...', 3, c)\n array([[ 0, 3, 6],\n [ 9, 12, 15]])\n >>> np.einsum(',ij', 3, c)\n array([[ 0, 3, 6],\n [ 9, 12, 15]])\n >>> np.einsum(3, [Ellipsis], c, [Ellipsis])\n array([[ 0, 3, 6],\n [ 9, 12, 15]])\n >>> np.multiply(3, c)\n array([[ 0, 3, 6],\n [ 9, 12, 15]])\n\n Vector outer product:\n\n >>> np.einsum('i,j', np.arange(2)+1, b)\n array([[0, 1, 2, 3, 4],\n [0, 2, 4, 6, 8]])\n >>> np.einsum(np.arange(2)+1, [0], b, [1])\n array([[0, 1, 2, 3, 4],\n [0, 2, 4, 6, 8]])\n >>> np.outer(np.arange(2)+1, b)\n array([[0, 1, 2, 3, 4],\n [0, 2, 4, 6, 8]])\n\n Tensor contraction:\n\n >>> a = np.arange(60.).reshape(3,4,5)\n >>> b = np.arange(24.).reshape(4,3,2)\n >>> np.einsum('ijk,jil->kl', a, b)\n array([[ 4400., 4730.],\n [ 4532., 4874.],\n [ 4664., 5018.],\n [ 4796., 5162.],\n [ 4928., 5306.]])\n >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])\n array([[ 4400., 4730.],\n [ 4532., 4874.],\n [ 4664., 5018.],\n [ 4796., 5162.],\n [ 4928., 5306.]])\n >>> np.tensordot(a,b, axes=([1,0],[0,1]))\n array([[ 4400., 4730.],\n [ 4532., 4874.],\n [ 4664., 5018.],\n [ 4796., 5162.],\n [ 4928., 5306.]])\n\n Writeable returned arrays (since version 1.10.0):\n\n >>> a = np.zeros((3, 3))\n >>> np.einsum('ii->i', a)[:] = 1\n >>> a\n array([[ 1., 0., 0.],\n [ 0., 1., 0.],\n [ 0., 0., 1.]])\n\n Example of ellipsis use:\n\n >>> a = np.arange(6).reshape((3,2))\n >>> b = np.arange(12).reshape((4,3))\n >>> np.einsum('ki,jk->ij', a, b)\n array([[10, 28, 46, 64],\n [13, 40, 67, 94]])\n >>> np.einsum('ki,...k->i...', a, b)\n array([[10, 28, 46, 64],\n [13, 40, 67, 94]])\n >>> np.einsum('k...,jk', a, b)\n array([[10, 28, 46, 64],\n [13, 40, 67, 94]])\n\n ") add_newdoc('numpy._core.multiarray', 'ndarray', '\n ndarray(shape, dtype=float, buffer=None, offset=0,\n strides=None, order=None)\n\n An array object represents a multidimensional, homogeneous array\n of fixed-size items. An associated data-type object describes the\n format of each element in the array (its byte-order, how many bytes it\n occupies in memory, whether it is an integer, a floating point number,\n or something else, etc.)\n\n Arrays should be constructed using `array`, `zeros` or `empty` (refer\n to the See Also section below). The parameters given here refer to\n a low-level method (`ndarray(...)`) for instantiating an array.\n\n For more information, refer to the `numpy` module and examine the\n methods and attributes of an array.\n\n Parameters\n ----------\n (for the __new__ method; see Notes below)\n\n shape : tuple of ints\n Shape of created array.\n dtype : data-type, optional\n Any object that can be interpreted as a numpy data type.\n buffer : object exposing buffer interface, optional\n Used to fill the array with data.\n offset : int, optional\n Offset of array data in buffer.\n strides : tuple of ints, optional\n Strides of data in memory.\n order : {\'C\', \'F\'}, optional\n Row-major (C-style) or column-major (Fortran-style) order.\n\n Attributes\n ----------\n T : ndarray\n Transpose of the array.\n data : buffer\n The array\'s elements, in memory.\n dtype : dtype object\n Describes the format of the elements in the array.\n flags : dict\n Dictionary containing information related to memory use, e.g.,\n \'C_CONTIGUOUS\', \'OWNDATA\', \'WRITEABLE\', etc.\n flat : numpy.flatiter object\n Flattened version of the array as an iterator. The iterator\n allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for\n assignment examples; TODO).\n imag : ndarray\n Imaginary part of the array.\n real : ndarray\n Real part of the array.\n size : int\n Number of elements in the array.\n itemsize : int\n The memory use of each array element in bytes.\n nbytes : int\n The total number of bytes required to store the array data,\n i.e., ``itemsize * size``.\n ndim : int\n The array\'s number of dimensions.\n shape : tuple of ints\n Shape of the array.\n strides : tuple of ints\n The step-size required to move from one element to the next in\n memory. For example, a contiguous ``(3, 4)`` array of type\n ``int16`` in C-order has strides ``(8, 2)``. This implies that\n to move from element to element in memory requires jumps of 2 bytes.\n To move from row-to-row, one needs to jump 8 bytes at a time\n (``2 * 4``).\n ctypes : ctypes object\n Class containing properties of the array needed for interaction\n with ctypes.\n base : ndarray\n If the array is a view into another array, that array is its `base`\n (unless that array is also a view). The `base` array is where the\n array data is actually stored.\n\n See Also\n --------\n array : Construct an array.\n zeros : Create an array, each element of which is zero.\n empty : Create an array, but leave its allocated memory unchanged (i.e.,\n it contains "garbage").\n dtype : Create a data-type.\n numpy.typing.NDArray : An ndarray alias :term:`generic `\n w.r.t. its `dtype.type `.\n\n Notes\n -----\n There are two modes of creating an array using ``__new__``:\n\n 1. If `buffer` is None, then only `shape`, `dtype`, and `order`\n are used.\n 2. If `buffer` is an object exposing the buffer interface, then\n all keywords are interpreted.\n\n No ``__init__`` method is needed because the array is fully initialized\n after the ``__new__`` method.\n\n Examples\n --------\n These examples illustrate the low-level `ndarray` constructor. Refer\n to the `See Also` section above for easier ways of constructing an\n ndarray.\n\n First mode, `buffer` is None:\n\n >>> import numpy as np\n >>> np.ndarray(shape=(2,2), dtype=float, order=\'F\')\n array([[0.0e+000, 0.0e+000], # random\n [ nan, 2.5e-323]])\n\n Second mode:\n\n >>> np.ndarray((2,), buffer=np.array([1,2,3]),\n ... offset=np.int_().itemsize,\n ... dtype=int) # offset = 1*itemsize, i.e. skip first element\n array([2, 3])\n\n ') add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_interface__', 'Array protocol: Python side.')) add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_priority__', 'Array priority.')) add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_struct__', 'Array protocol: C-struct side.')) add_newdoc('numpy._core.multiarray', 'ndarray', ('__dlpack__', '\n a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)\n\n DLPack Protocol: Part of the Array API.\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('__dlpack_device__', '\n a.__dlpack_device__()\n\n DLPack Protocol: Part of the Array API.\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('base', '\n Base object if memory is from some other object.\n\n Examples\n --------\n The base of an array that owns its memory is None:\n\n >>> import numpy as np\n >>> x = np.array([1,2,3,4])\n >>> x.base is None\n True\n\n Slicing creates a view, whose memory is shared with x:\n\n >>> y = x[2:]\n >>> y.base is x\n True\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('ctypes', '\n An object to simplify the interaction of the array with the ctypes\n module.\n\n This attribute creates an object that makes it easier to use arrays\n when calling shared libraries with the ctypes module. The returned\n object has, among others, data, shape, and strides attributes (see\n Notes below) which themselves return ctypes objects that can be used\n as arguments to a shared library.\n\n Parameters\n ----------\n None\n\n Returns\n -------\n c : Python object\n Possessing attributes data, shape, strides, etc.\n\n See Also\n --------\n numpy.ctypeslib\n\n Notes\n -----\n Below are the public attributes of this object which were documented\n in "Guide to NumPy" (we have omitted undocumented public attributes,\n as well as documented private attributes):\n\n .. autoattribute:: numpy._core._internal._ctypes.data\n :noindex:\n\n .. autoattribute:: numpy._core._internal._ctypes.shape\n :noindex:\n\n .. autoattribute:: numpy._core._internal._ctypes.strides\n :noindex:\n\n .. automethod:: numpy._core._internal._ctypes.data_as\n :noindex:\n\n .. automethod:: numpy._core._internal._ctypes.shape_as\n :noindex:\n\n .. automethod:: numpy._core._internal._ctypes.strides_as\n :noindex:\n\n If the ctypes module is not available, then the ctypes attribute\n of array objects still returns something useful, but ctypes objects\n are not returned and errors may be raised instead. In particular,\n the object will still have the ``as_parameter`` attribute which will\n return an integer equal to the data attribute.\n\n Examples\n --------\n >>> import numpy as np\n >>> import ctypes\n >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)\n >>> x\n array([[0, 1],\n [2, 3]], dtype=int32)\n >>> x.ctypes.data\n 31962608 # may vary\n >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))\n <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary\n >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents\n c_uint(0)\n >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents\n c_ulong(4294967296)\n >>> x.ctypes.shape\n # may vary\n >>> x.ctypes.strides\n # may vary\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('data', "Python buffer object pointing to the start of the array's data.")) add_newdoc('numpy._core.multiarray', 'ndarray', ('dtype', "\n Data-type of the array's elements.\n\n .. warning::\n\n Setting ``arr.dtype`` is discouraged and may be deprecated in the\n future. Setting will replace the ``dtype`` without modifying the\n memory (see also `ndarray.view` and `ndarray.astype`).\n\n Parameters\n ----------\n None\n\n Returns\n -------\n d : numpy dtype object\n\n See Also\n --------\n ndarray.astype : Cast the values contained in the array to a new data-type.\n ndarray.view : Create a view of the same data but a different data-type.\n numpy.dtype\n\n Examples\n --------\n >>> x\n array([[0, 1],\n [2, 3]])\n >>> x.dtype\n dtype('int32')\n >>> type(x.dtype)\n \n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('imag', "\n The imaginary part of the array.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.sqrt([1+0j, 0+1j])\n >>> x.imag\n array([ 0. , 0.70710678])\n >>> x.imag.dtype\n dtype('float64')\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('itemsize', '\n Length of one array element in bytes.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([1,2,3], dtype=np.float64)\n >>> x.itemsize\n 8\n >>> x = np.array([1,2,3], dtype=np.complex128)\n >>> x.itemsize\n 16\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('flags', "\n Information about the memory layout of the array.\n\n Attributes\n ----------\n C_CONTIGUOUS (C)\n The data is in a single, C-style contiguous segment.\n F_CONTIGUOUS (F)\n The data is in a single, Fortran-style contiguous segment.\n OWNDATA (O)\n The array owns the memory it uses or borrows it from another object.\n WRITEABLE (W)\n The data area can be written to. Setting this to False locks\n the data, making it read-only. A view (slice, etc.) inherits WRITEABLE\n from its base array at creation time, but a view of a writeable\n array may be subsequently locked while the base array remains writeable.\n (The opposite is not true, in that a view of a locked array may not\n be made writeable. However, currently, locking a base object does not\n lock any views that already reference it, so under that circumstance it\n is possible to alter the contents of a locked array via a previously\n created writeable view onto it.) Attempting to change a non-writeable\n array raises a RuntimeError exception.\n ALIGNED (A)\n The data and all elements are aligned appropriately for the hardware.\n WRITEBACKIFCOPY (X)\n This array is a copy of some other array. The C-API function\n PyArray_ResolveWritebackIfCopy must be called before deallocating\n to the base array will be updated with the contents of this array.\n FNC\n F_CONTIGUOUS and not C_CONTIGUOUS.\n FORC\n F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).\n BEHAVED (B)\n ALIGNED and WRITEABLE.\n CARRAY (CA)\n BEHAVED and C_CONTIGUOUS.\n FARRAY (FA)\n BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.\n\n Notes\n -----\n The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),\n or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag\n names are only supported in dictionary access.\n\n Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be\n changed by the user, via direct assignment to the attribute or dictionary\n entry, or by calling `ndarray.setflags`.\n\n The array flags cannot be set arbitrarily:\n\n - WRITEBACKIFCOPY can only be set ``False``.\n - ALIGNED can only be set ``True`` if the data is truly aligned.\n - WRITEABLE can only be set ``True`` if the array owns its own memory\n or the ultimate owner of the memory exposes a writeable buffer\n interface or is a string.\n\n Arrays can be both C-style and Fortran-style contiguous simultaneously.\n This is clear for 1-dimensional arrays, but can also be true for higher\n dimensional arrays.\n\n Even for contiguous arrays a stride for a given dimension\n ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``\n or the array has no elements.\n It does *not* generally hold that ``self.strides[-1] == self.itemsize``\n for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for\n Fortran-style contiguous arrays is true.\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('flat', "\n A 1-D iterator over the array.\n\n This is a `numpy.flatiter` instance, which acts similarly to, but is not\n a subclass of, Python's built-in iterator object.\n\n See Also\n --------\n flatten : Return a copy of the array collapsed into one dimension.\n\n flatiter\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.arange(1, 7).reshape(2, 3)\n >>> x\n array([[1, 2, 3],\n [4, 5, 6]])\n >>> x.flat[3]\n 4\n >>> x.T\n array([[1, 4],\n [2, 5],\n [3, 6]])\n >>> x.T.flat[3]\n 5\n >>> type(x.flat)\n \n\n An assignment example:\n\n >>> x.flat = 3; x\n array([[3, 3, 3],\n [3, 3, 3]])\n >>> x.flat[[1,4]] = 1; x\n array([[3, 1, 3],\n [3, 1, 3]])\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('nbytes', '\n Total bytes consumed by the elements of the array.\n\n Notes\n -----\n Does not include memory consumed by non-element attributes of the\n array object.\n\n See Also\n --------\n sys.getsizeof\n Memory consumed by the object itself without parents in case view.\n This does include memory consumed by non-element attributes.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.zeros((3,5,2), dtype=np.complex128)\n >>> x.nbytes\n 480\n >>> np.prod(x.shape) * x.itemsize\n 480\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('ndim', '\n Number of array dimensions.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([1, 2, 3])\n >>> x.ndim\n 1\n >>> y = np.zeros((2, 3, 4))\n >>> y.ndim\n 3\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('real', "\n The real part of the array.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.sqrt([1+0j, 0+1j])\n >>> x.real\n array([ 1. , 0.70710678])\n >>> x.real.dtype\n dtype('float64')\n\n See Also\n --------\n numpy.real : equivalent function\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('shape', '\n Tuple of array dimensions.\n\n The shape property is usually used to get the current shape of an array,\n but may also be used to reshape the array in-place by assigning a tuple of\n array dimensions to it. As with `numpy.reshape`, one of the new shape\n dimensions can be -1, in which case its value is inferred from the size of\n the array and the remaining dimensions. Reshaping an array in-place will\n fail if a copy is required.\n\n .. warning::\n\n Setting ``arr.shape`` is discouraged and may be deprecated in the\n future. Using `ndarray.reshape` is the preferred approach.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([1, 2, 3, 4])\n >>> x.shape\n (4,)\n >>> y = np.zeros((2, 3, 4))\n >>> y.shape\n (2, 3, 4)\n >>> y.shape = (3, 8)\n >>> y\n array([[ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.]])\n >>> y.shape = (3, 6)\n Traceback (most recent call last):\n File "", line 1, in \n ValueError: total size of new array must be unchanged\n >>> np.zeros((4,2))[::2].shape = (-1,)\n Traceback (most recent call last):\n File "", line 1, in \n AttributeError: Incompatible shape for in-place modification. Use\n `.reshape()` to make a copy with the desired shape.\n\n See Also\n --------\n numpy.shape : Equivalent getter function.\n numpy.reshape : Function similar to setting ``shape``.\n ndarray.reshape : Method similar to setting ``shape``.\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('size', "\n Number of elements in the array.\n\n Equal to ``np.prod(a.shape)``, i.e., the product of the array's\n dimensions.\n\n Notes\n -----\n `a.size` returns a standard arbitrary precision Python integer. This\n may not be the case with other methods of obtaining the same value\n (like the suggested ``np.prod(a.shape)``, which returns an instance\n of ``np.int_``), and may be relevant if the value is used further in\n calculations that may overflow a fixed size integer type.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.zeros((3, 5, 2), dtype=np.complex128)\n >>> x.size\n 30\n >>> np.prod(x.shape)\n 30\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('strides', '\n Tuple of bytes to step in each dimension when traversing an array.\n\n The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`\n is::\n\n offset = sum(np.array(i) * a.strides)\n\n A more detailed explanation of strides can be found in\n :ref:`arrays.ndarray`.\n\n .. warning::\n\n Setting ``arr.strides`` is discouraged and may be deprecated in the\n future. `numpy.lib.stride_tricks.as_strided` should be preferred\n to create a new view of the same data in a safer way.\n\n Notes\n -----\n Imagine an array of 32-bit integers (each 4 bytes)::\n\n x = np.array([[0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9]], dtype=np.int32)\n\n This array is stored in memory as 40 bytes, one after the other\n (known as a contiguous block of memory). The strides of an array tell\n us how many bytes we have to skip in memory to move to the next position\n along a certain axis. For example, we have to skip 4 bytes (1 value) to\n move to the next column, but 20 bytes (5 values) to get to the same\n position in the next row. As such, the strides for the array `x` will be\n ``(20, 4)``.\n\n See Also\n --------\n numpy.lib.stride_tricks.as_strided\n\n Examples\n --------\n >>> import numpy as np\n >>> y = np.reshape(np.arange(2*3*4), (2,3,4))\n >>> y\n array([[[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]],\n [[12, 13, 14, 15],\n [16, 17, 18, 19],\n [20, 21, 22, 23]]])\n >>> y.strides\n (48, 16, 4)\n >>> y[1,1,1]\n 17\n >>> offset=sum(y.strides * np.array((1,1,1)))\n >>> offset/y.itemsize\n 17\n\n >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)\n >>> x.strides\n (32, 4, 224, 1344)\n >>> i = np.array([3,5,2,2])\n >>> offset = sum(i * x.strides)\n >>> x[3,5,2,2]\n 813\n >>> offset / x.itemsize\n 813\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('T', '\n View of the transposed array.\n\n Same as ``self.transpose()``.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array([[1, 2], [3, 4]])\n >>> a\n array([[1, 2],\n [3, 4]])\n >>> a.T\n array([[1, 3],\n [2, 4]])\n\n >>> a = np.array([1, 2, 3, 4])\n >>> a\n array([1, 2, 3, 4])\n >>> a.T\n array([1, 2, 3, 4])\n\n See Also\n --------\n transpose\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('mT', '\n View of the matrix transposed array.\n\n The matrix transpose is the transpose of the last two dimensions, even\n if the array is of higher dimension.\n\n .. versionadded:: 2.0\n\n Raises\n ------\n ValueError\n If the array is of dimension less than 2.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array([[1, 2], [3, 4]])\n >>> a\n array([[1, 2],\n [3, 4]])\n >>> a.mT\n array([[1, 3],\n [2, 4]])\n\n >>> a = np.arange(8).reshape((2, 2, 2))\n >>> a\n array([[[0, 1],\n [2, 3]],\n \n [[4, 5],\n [6, 7]]])\n >>> a.mT\n array([[[0, 2],\n [1, 3]],\n \n [[4, 6],\n [5, 7]]])\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('__array__', "\n a.__array__([dtype], *, copy=None)\n\n For ``dtype`` parameter it returns a new reference to self if\n ``dtype`` is not given or it matches array's data type.\n A new array of provided data type is returned if ``dtype``\n is different from the current data type of the array.\n For ``copy`` parameter it returns a new reference to self if\n ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``\n parameter. The method returns a new array for ``copy=True``, regardless of\n ``dtype`` parameter.\n\n A more detailed explanation of the ``__array__`` interface\n can be found in :ref:`dunder_array.interface`.\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_finalize__', '\n a.__array_finalize__(obj, /)\n\n Present so subclasses can call super. Does nothing.\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_wrap__', '\n a.__array_wrap__(array[, context], /)\n\n Returns a view of `array` with the same type as self.\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('__copy__', "\n a.__copy__()\n\n Used if :func:`copy.copy` is called on an array. Returns a copy of the array.\n\n Equivalent to ``a.copy(order='K')``.\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('__class_getitem__', '\n a.__class_getitem__(item, /)\n\n Return a parametrized wrapper around the `~numpy.ndarray` type.\n\n .. versionadded:: 1.22\n\n Returns\n -------\n alias : types.GenericAlias\n A parametrized `~numpy.ndarray` type.\n\n Examples\n --------\n >>> from typing import Any\n >>> import numpy as np\n\n >>> np.ndarray[Any, np.dtype[Any]]\n numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]\n\n See Also\n --------\n :pep:`585` : Type hinting generics in standard collections.\n numpy.typing.NDArray : An ndarray alias :term:`generic `\n w.r.t. its `dtype.type `.\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('__deepcopy__', '\n a.__deepcopy__(memo, /)\n\n Used if :func:`copy.deepcopy` is called on an array.\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('__reduce__', '\n a.__reduce__()\n\n For pickling.\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('__setstate__', "\n a.__setstate__(state, /)\n\n For unpickling.\n\n The `state` argument must be a sequence that contains the following\n elements:\n\n Parameters\n ----------\n version : int\n optional pickle version. If omitted defaults to 0.\n shape : tuple\n dtype : data-type\n isFortran : bool\n rawdata : string or list\n a binary string with the data (or a list if 'a' is an object array)\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('all', '\n a.all(axis=None, out=None, keepdims=False, *, where=True)\n\n Returns True if all elements evaluate to True.\n\n Refer to `numpy.all` for full documentation.\n\n See Also\n --------\n numpy.all : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('any', '\n a.any(axis=None, out=None, keepdims=False, *, where=True)\n\n Returns True if any of the elements of `a` evaluate to True.\n\n Refer to `numpy.any` for full documentation.\n\n See Also\n --------\n numpy.any : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('argmax', '\n a.argmax(axis=None, out=None, *, keepdims=False)\n\n Return indices of the maximum values along the given axis.\n\n Refer to `numpy.argmax` for full documentation.\n\n See Also\n --------\n numpy.argmax : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('argmin', '\n a.argmin(axis=None, out=None, *, keepdims=False)\n\n Return indices of the minimum values along the given axis.\n\n Refer to `numpy.argmin` for detailed documentation.\n\n See Also\n --------\n numpy.argmin : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('argsort', '\n a.argsort(axis=-1, kind=None, order=None)\n\n Returns the indices that would sort this array.\n\n Refer to `numpy.argsort` for full documentation.\n\n See Also\n --------\n numpy.argsort : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('argpartition', "\n a.argpartition(kth, axis=-1, kind='introselect', order=None)\n\n Returns the indices that would partition this array.\n\n Refer to `numpy.argpartition` for full documentation.\n\n .. versionadded:: 1.8.0\n\n See Also\n --------\n numpy.argpartition : equivalent function\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('astype', '\n a.astype(dtype, order=\'K\', casting=\'unsafe\', subok=True, copy=True)\n\n Copy of the array, cast to a specified type.\n\n Parameters\n ----------\n dtype : str or dtype\n Typecode or data-type to which the array is cast.\n order : {\'C\', \'F\', \'A\', \'K\'}, optional\n Controls the memory layout order of the result.\n \'C\' means C order, \'F\' means Fortran order, \'A\'\n means \'F\' order if all the arrays are Fortran contiguous,\n \'C\' order otherwise, and \'K\' means as close to the\n order the array elements appear in memory as possible.\n Default is \'K\'.\n casting : {\'no\', \'equiv\', \'safe\', \'same_kind\', \'unsafe\'}, optional\n Controls what kind of data casting may occur. Defaults to \'unsafe\'\n for backwards compatibility.\n\n * \'no\' means the data types should not be cast at all.\n * \'equiv\' means only byte-order changes are allowed.\n * \'safe\' means only casts which can preserve values are allowed.\n * \'same_kind\' means only safe casts or casts within a kind,\n like float64 to float32, are allowed.\n * \'unsafe\' means any data conversions may be done.\n subok : bool, optional\n If True, then sub-classes will be passed-through (default), otherwise\n the returned array will be forced to be a base-class array.\n copy : bool, optional\n By default, astype always returns a newly allocated array. If this\n is set to false, and the `dtype`, `order`, and `subok`\n requirements are satisfied, the input array is returned instead\n of a copy.\n\n Returns\n -------\n arr_t : ndarray\n Unless `copy` is False and the other conditions for returning the input\n array are satisfied (see description for `copy` input parameter), `arr_t`\n is a new array of the same shape as the input array, with dtype, order\n given by `dtype`, `order`.\n\n Notes\n -----\n .. versionchanged:: 1.17.0\n Casting between a simple data type and a structured one is possible only\n for "unsafe" casting. Casting to multiple fields is allowed, but\n casting from multiple fields is not.\n\n .. versionchanged:: 1.9.0\n Casting from numeric to string types in \'safe\' casting mode requires\n that the string dtype length is long enough to store the max\n integer/float value converted.\n\n Raises\n ------\n ComplexWarning\n When casting from complex to float or int. To avoid this,\n one should use ``a.real.astype(t)``.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([1, 2, 2.5])\n >>> x\n array([1. , 2. , 2.5])\n\n >>> x.astype(int)\n array([1, 2, 2])\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('byteswap', "\n a.byteswap(inplace=False)\n\n Swap the bytes of the array elements\n\n Toggle between low-endian and big-endian data representation by\n returning a byteswapped array, optionally swapped in-place.\n Arrays of byte-strings are not swapped. The real and imaginary\n parts of a complex number are swapped individually.\n\n Parameters\n ----------\n inplace : bool, optional\n If ``True``, swap bytes in-place, default is ``False``.\n\n Returns\n -------\n out : ndarray\n The byteswapped array. If `inplace` is ``True``, this is\n a view to self.\n\n Examples\n --------\n >>> import numpy as np\n >>> A = np.array([1, 256, 8755], dtype=np.int16)\n >>> list(map(hex, A))\n ['0x1', '0x100', '0x2233']\n >>> A.byteswap(inplace=True)\n array([ 256, 1, 13090], dtype=int16)\n >>> list(map(hex, A))\n ['0x100', '0x1', '0x3322']\n\n Arrays of byte-strings are not swapped\n\n >>> A = np.array([b'ceg', b'fac'])\n >>> A.byteswap()\n array([b'ceg', b'fac'], dtype='|S3')\n\n ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with\n the same values but different representation in memory\n\n >>> A = np.array([1, 2, 3])\n >>> A.view(np.uint8)\n array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,\n 0, 0], dtype=uint8)\n >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)\n array([1, 2, 3], dtype='>i8')\n >>> A.view(np.uint8)\n array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,\n 0, 3], dtype=uint8)\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('choose', "\n a.choose(choices, out=None, mode='raise')\n\n Use an index array to construct a new array from a set of choices.\n\n Refer to `numpy.choose` for full documentation.\n\n See Also\n --------\n numpy.choose : equivalent function\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('clip', '\n a.clip(min=None, max=None, out=None, **kwargs)\n\n Return an array whose values are limited to ``[min, max]``.\n One of max or min must be given.\n\n Refer to `numpy.clip` for full documentation.\n\n See Also\n --------\n numpy.clip : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('compress', '\n a.compress(condition, axis=None, out=None)\n\n Return selected slices of this array along given axis.\n\n Refer to `numpy.compress` for full documentation.\n\n See Also\n --------\n numpy.compress : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('conj', '\n a.conj()\n\n Complex-conjugate all elements.\n\n Refer to `numpy.conjugate` for full documentation.\n\n See Also\n --------\n numpy.conjugate : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('conjugate', '\n a.conjugate()\n\n Return the complex conjugate, element-wise.\n\n Refer to `numpy.conjugate` for full documentation.\n\n See Also\n --------\n numpy.conjugate : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('copy', "\n a.copy(order='C')\n\n Return a copy of the array.\n\n Parameters\n ----------\n order : {'C', 'F', 'A', 'K'}, optional\n Controls the memory layout of the copy. 'C' means C-order,\n 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,\n 'C' otherwise. 'K' means match the layout of `a` as closely\n as possible. (Note that this function and :func:`numpy.copy` are very\n similar but have different default values for their order=\n arguments, and this function always passes sub-classes through.)\n\n See also\n --------\n numpy.copy : Similar function with different default behavior\n numpy.copyto\n\n Notes\n -----\n This function is the preferred method for creating an array copy. The\n function :func:`numpy.copy` is similar, but it defaults to using order 'K',\n and will not pass sub-classes through by default.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([[1,2,3],[4,5,6]], order='F')\n\n >>> y = x.copy()\n\n >>> x.fill(0)\n\n >>> x\n array([[0, 0, 0],\n [0, 0, 0]])\n\n >>> y\n array([[1, 2, 3],\n [4, 5, 6]])\n\n >>> y.flags['C_CONTIGUOUS']\n True\n\n For arrays containing Python objects (e.g. dtype=object),\n the copy is a shallow one. The new array will contain the\n same object which may lead to surprises if that object can\n be modified (is mutable):\n\n >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)\n >>> b = a.copy()\n >>> b[2][0] = 10\n >>> a\n array([1, 'm', list([10, 3, 4])], dtype=object)\n\n To ensure all elements within an ``object`` array are copied,\n use `copy.deepcopy`:\n\n >>> import copy\n >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)\n >>> c = copy.deepcopy(a)\n >>> c[2][0] = 10\n >>> c\n array([1, 'm', list([10, 3, 4])], dtype=object)\n >>> a\n array([1, 'm', list([2, 3, 4])], dtype=object)\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('cumprod', '\n a.cumprod(axis=None, dtype=None, out=None)\n\n Return the cumulative product of the elements along the given axis.\n\n Refer to `numpy.cumprod` for full documentation.\n\n See Also\n --------\n numpy.cumprod : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('cumsum', '\n a.cumsum(axis=None, dtype=None, out=None)\n\n Return the cumulative sum of the elements along the given axis.\n\n Refer to `numpy.cumsum` for full documentation.\n\n See Also\n --------\n numpy.cumsum : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('diagonal', '\n a.diagonal(offset=0, axis1=0, axis2=1)\n\n Return specified diagonals. In NumPy 1.9 the returned array is a\n read-only view instead of a copy as in previous NumPy versions. In\n a future version the read-only restriction will be removed.\n\n Refer to :func:`numpy.diagonal` for full documentation.\n\n See Also\n --------\n numpy.diagonal : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', 'dot') add_newdoc('numpy._core.multiarray', 'ndarray', ('dump', '\n a.dump(file)\n\n Dump a pickle of the array to the specified file.\n The array can be read back with pickle.load or numpy.load.\n\n Parameters\n ----------\n file : str or Path\n A string naming the dump file.\n\n .. versionchanged:: 1.17.0\n `pathlib.Path` objects are now accepted.\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('dumps', '\n a.dumps()\n\n Returns the pickle of the array as a string.\n pickle.loads will convert the string back to an array.\n\n Parameters\n ----------\n None\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('fill', '\n a.fill(value)\n\n Fill the array with a scalar value.\n\n Parameters\n ----------\n value : scalar\n All elements of `a` will be assigned this value.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array([1, 2])\n >>> a.fill(0)\n >>> a\n array([0, 0])\n >>> a = np.empty(2)\n >>> a.fill(1)\n >>> a\n array([1., 1.])\n\n Fill expects a scalar value and always behaves the same as assigning\n to a single array element. The following is a rare example where this\n distinction is important:\n\n >>> a = np.array([None, None], dtype=object)\n >>> a[0] = np.array(3)\n >>> a\n array([array(3), None], dtype=object)\n >>> a.fill(np.array(3))\n >>> a\n array([array(3), array(3)], dtype=object)\n\n Where other forms of assignments will unpack the array being assigned:\n\n >>> a[...] = np.array(3)\n >>> a\n array([3, 3], dtype=object)\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('flatten', "\n a.flatten(order='C')\n\n Return a copy of the array collapsed into one dimension.\n\n Parameters\n ----------\n order : {'C', 'F', 'A', 'K'}, optional\n 'C' means to flatten in row-major (C-style) order.\n 'F' means to flatten in column-major (Fortran-\n style) order. 'A' means to flatten in column-major\n order if `a` is Fortran *contiguous* in memory,\n row-major order otherwise. 'K' means to flatten\n `a` in the order the elements occur in memory.\n The default is 'C'.\n\n Returns\n -------\n y : ndarray\n A copy of the input array, flattened to one dimension.\n\n See Also\n --------\n ravel : Return a flattened array.\n flat : A 1-D flat iterator over the array.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array([[1,2], [3,4]])\n >>> a.flatten()\n array([1, 2, 3, 4])\n >>> a.flatten('F')\n array([1, 3, 2, 4])\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('getfield', '\n a.getfield(dtype, offset=0)\n\n Returns a field of the given array as a certain type.\n\n A field is a view of the array data with a given data-type. The values in\n the view are determined by the given type and the offset into the current\n array in bytes. The offset needs to be such that the view dtype fits in the\n array dtype; for example an array of dtype complex128 has 16-byte elements.\n If taking a view with a 32-bit integer (4 bytes), the offset needs to be\n between 0 and 12 bytes.\n\n Parameters\n ----------\n dtype : str or dtype\n The data type of the view. The dtype size of the view can not be larger\n than that of the array itself.\n offset : int\n Number of bytes to skip before beginning the element view.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.diag([1.+1.j]*2)\n >>> x[1, 1] = 2 + 4.j\n >>> x\n array([[1.+1.j, 0.+0.j],\n [0.+0.j, 2.+4.j]])\n >>> x.getfield(np.float64)\n array([[1., 0.],\n [0., 2.]])\n\n By choosing an offset of 8 bytes we can select the complex part of the\n array for our view:\n\n >>> x.getfield(np.float64, offset=8)\n array([[1., 0.],\n [0., 4.]])\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('item', "\n a.item(*args)\n\n Copy an element of an array to a standard Python scalar and return it.\n\n Parameters\n ----------\n \\*args : Arguments (variable number and type)\n\n * none: in this case, the method only works for arrays\n with one element (`a.size == 1`), which element is\n copied into a standard Python scalar object and returned.\n\n * int_type: this argument is interpreted as a flat index into\n the array, specifying which element to copy and return.\n\n * tuple of int_types: functions as does a single int_type argument,\n except that the argument is interpreted as an nd-index into the\n array.\n\n Returns\n -------\n z : Standard Python scalar object\n A copy of the specified element of the array as a suitable\n Python scalar\n\n Notes\n -----\n When the data type of `a` is longdouble or clongdouble, item() returns\n a scalar array object because there is no available Python scalar that\n would not lose information. Void arrays return a buffer object for item(),\n unless fields are defined, in which case a tuple is returned.\n\n `item` is very similar to a[args], except, instead of an array scalar,\n a standard Python scalar is returned. This can be useful for speeding up\n access to elements of the array and doing arithmetic on elements of the\n array using Python's optimized math.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.random.seed(123)\n >>> x = np.random.randint(9, size=(3, 3))\n >>> x\n array([[2, 2, 6],\n [1, 3, 6],\n [1, 0, 1]])\n >>> x.item(3)\n 1\n >>> x.item(7)\n 0\n >>> x.item((0, 1))\n 2\n >>> x.item((2, 2))\n 1\n\n For an array with object dtype, elements are returned as-is.\n\n >>> a = np.array([np.int64(1)], dtype=object)\n >>> a.item() #return np.int64\n np.int64(1)\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('max', '\n a.max(axis=None, out=None, keepdims=False, initial=, where=True)\n\n Return the maximum along a given axis.\n\n Refer to `numpy.amax` for full documentation.\n\n See Also\n --------\n numpy.amax : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('mean', '\n a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)\n\n Returns the average of the array elements along given axis.\n\n Refer to `numpy.mean` for full documentation.\n\n See Also\n --------\n numpy.mean : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('min', '\n a.min(axis=None, out=None, keepdims=False, initial=, where=True)\n\n Return the minimum along a given axis.\n\n Refer to `numpy.amin` for full documentation.\n\n See Also\n --------\n numpy.amin : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('nonzero', '\n a.nonzero()\n\n Return the indices of the elements that are non-zero.\n\n Refer to `numpy.nonzero` for full documentation.\n\n See Also\n --------\n numpy.nonzero : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('prod', '\n a.prod(axis=None, dtype=None, out=None, keepdims=False,\n initial=1, where=True)\n\n Return the product of the array elements over the given axis\n\n Refer to `numpy.prod` for full documentation.\n\n See Also\n --------\n numpy.prod : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('put', "\n a.put(indices, values, mode='raise')\n\n Set ``a.flat[n] = values[n]`` for all `n` in indices.\n\n Refer to `numpy.put` for full documentation.\n\n See Also\n --------\n numpy.put : equivalent function\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('ravel', '\n a.ravel([order])\n\n Return a flattened array.\n\n Refer to `numpy.ravel` for full documentation.\n\n See Also\n --------\n numpy.ravel : equivalent function\n\n ndarray.flat : a flat iterator on the array.\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('repeat', '\n a.repeat(repeats, axis=None)\n\n Repeat elements of an array.\n\n Refer to `numpy.repeat` for full documentation.\n\n See Also\n --------\n numpy.repeat : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('reshape', "\n a.reshape(shape, /, *, order='C', copy=None)\n\n Returns an array containing the same data with a new shape.\n\n Refer to `numpy.reshape` for full documentation.\n\n See Also\n --------\n numpy.reshape : equivalent function\n\n Notes\n -----\n Unlike the free function `numpy.reshape`, this method on `ndarray` allows\n the elements of the shape parameter to be passed in as separate arguments.\n For example, ``a.reshape(10, 11)`` is equivalent to\n ``a.reshape((10, 11))``.\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('resize', "\n a.resize(new_shape, refcheck=True)\n\n Change shape and size of array in-place.\n\n Parameters\n ----------\n new_shape : tuple of ints, or `n` ints\n Shape of resized array.\n refcheck : bool, optional\n If False, reference count will not be checked. Default is True.\n\n Returns\n -------\n None\n\n Raises\n ------\n ValueError\n If `a` does not own its own data or references or views to it exist,\n and the data memory must be changed.\n PyPy only: will always raise if the data memory must be changed, since\n there is no reliable way to determine if references or views to it\n exist.\n\n SystemError\n If the `order` keyword argument is specified. This behaviour is a\n bug in NumPy.\n\n See Also\n --------\n resize : Return a new array with the specified shape.\n\n Notes\n -----\n This reallocates space for the data area if necessary.\n\n Only contiguous arrays (data elements consecutive in memory) can be\n resized.\n\n The purpose of the reference count check is to make sure you\n do not use this array as a buffer for another Python object and then\n reallocate the memory. However, reference counts can increase in\n other ways so if you are sure that you have not shared the memory\n for this array with another Python object, then you may safely set\n `refcheck` to False.\n\n Examples\n --------\n Shrinking an array: array is flattened (in the order that the data are\n stored in memory), resized, and reshaped:\n\n >>> import numpy as np\n\n >>> a = np.array([[0, 1], [2, 3]], order='C')\n >>> a.resize((2, 1))\n >>> a\n array([[0],\n [1]])\n\n >>> a = np.array([[0, 1], [2, 3]], order='F')\n >>> a.resize((2, 1))\n >>> a\n array([[0],\n [2]])\n\n Enlarging an array: as above, but missing entries are filled with zeros:\n\n >>> b = np.array([[0, 1], [2, 3]])\n >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple\n >>> b\n array([[0, 1, 2],\n [3, 0, 0]])\n\n Referencing an array prevents resizing...\n\n >>> c = a\n >>> a.resize((1, 1))\n Traceback (most recent call last):\n ...\n ValueError: cannot resize an array that references or is referenced ...\n\n Unless `refcheck` is False:\n\n >>> a.resize((1, 1), refcheck=False)\n >>> a\n array([[0]])\n >>> c\n array([[0]])\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('round', '\n a.round(decimals=0, out=None)\n\n Return `a` with each element rounded to the given number of decimals.\n\n Refer to `numpy.around` for full documentation.\n\n See Also\n --------\n numpy.around : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('searchsorted', "\n a.searchsorted(v, side='left', sorter=None)\n\n Find indices where elements of v should be inserted in a to maintain order.\n\n For full documentation, see `numpy.searchsorted`\n\n See Also\n --------\n numpy.searchsorted : equivalent function\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('setfield', "\n a.setfield(val, dtype, offset=0)\n\n Put a value into a specified place in a field defined by a data-type.\n\n Place `val` into `a`'s field defined by `dtype` and beginning `offset`\n bytes into the field.\n\n Parameters\n ----------\n val : object\n Value to be placed in field.\n dtype : dtype object\n Data-type of the field in which to place `val`.\n offset : int, optional\n The number of bytes into the field at which to place `val`.\n\n Returns\n -------\n None\n\n See Also\n --------\n getfield\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.eye(3)\n >>> x.getfield(np.float64)\n array([[1., 0., 0.],\n [0., 1., 0.],\n [0., 0., 1.]])\n >>> x.setfield(3, np.int32)\n >>> x.getfield(np.int32)\n array([[3, 3, 3],\n [3, 3, 3],\n [3, 3, 3]], dtype=int32)\n >>> x\n array([[1.0e+000, 1.5e-323, 1.5e-323],\n [1.5e-323, 1.0e+000, 1.5e-323],\n [1.5e-323, 1.5e-323, 1.0e+000]])\n >>> x.setfield(np.eye(3), np.int32)\n >>> x\n array([[1., 0., 0.],\n [0., 1., 0.],\n [0., 0., 1.]])\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('setflags', '\n a.setflags(write=None, align=None, uic=None)\n\n Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,\n respectively.\n\n These Boolean-valued flags affect how numpy interprets the memory\n area used by `a` (see Notes below). The ALIGNED flag can only\n be set to True if the data is actually aligned according to the type.\n The WRITEBACKIFCOPY flag can never be set\n to True. The flag WRITEABLE can only be set to True if the array owns its\n own memory, or the ultimate owner of the memory exposes a writeable buffer\n interface, or is a string. (The exception for string is made so that\n unpickling can be done without copying memory.)\n\n Parameters\n ----------\n write : bool, optional\n Describes whether or not `a` can be written to.\n align : bool, optional\n Describes whether or not `a` is aligned properly for its type.\n uic : bool, optional\n Describes whether or not `a` is a copy of another "base" array.\n\n Notes\n -----\n Array flags provide information about how the memory area used\n for the array is to be interpreted. There are 7 Boolean flags\n in use, only three of which can be changed by the user:\n WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.\n\n WRITEABLE (W) the data area can be written to;\n\n ALIGNED (A) the data and strides are aligned appropriately for the hardware\n (as determined by the compiler);\n\n WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced\n by .base). When the C-API function PyArray_ResolveWritebackIfCopy is\n called, the base array will be updated with the contents of this array.\n\n All flags can be accessed using the single (upper case) letter as well\n as the full name.\n\n Examples\n --------\n >>> import numpy as np\n >>> y = np.array([[3, 1, 7],\n ... [2, 0, 0],\n ... [8, 5, 9]])\n >>> y\n array([[3, 1, 7],\n [2, 0, 0],\n [8, 5, 9]])\n >>> y.flags\n C_CONTIGUOUS : True\n F_CONTIGUOUS : False\n OWNDATA : True\n WRITEABLE : True\n ALIGNED : True\n WRITEBACKIFCOPY : False\n >>> y.setflags(write=0, align=0)\n >>> y.flags\n C_CONTIGUOUS : True\n F_CONTIGUOUS : False\n OWNDATA : True\n WRITEABLE : False\n ALIGNED : False\n WRITEBACKIFCOPY : False\n >>> y.setflags(uic=1)\n Traceback (most recent call last):\n File "", line 1, in \n ValueError: cannot set WRITEBACKIFCOPY flag to True\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('sort', "\n a.sort(axis=-1, kind=None, order=None)\n\n Sort an array in-place. Refer to `numpy.sort` for full documentation.\n\n Parameters\n ----------\n axis : int, optional\n Axis along which to sort. Default is -1, which means sort along the\n last axis.\n kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional\n Sorting algorithm. The default is 'quicksort'. Note that both 'stable'\n and 'mergesort' use timsort under the covers and, in general, the\n actual implementation will vary with datatype. The 'mergesort' option\n is retained for backwards compatibility.\n\n .. versionchanged:: 1.15.0\n The 'stable' option was added.\n\n order : str or list of str, optional\n When `a` is an array with fields defined, this argument specifies\n which fields to compare first, second, etc. A single field can\n be specified as a string, and not all fields need be specified,\n but unspecified fields will still be used, in the order in which\n they come up in the dtype, to break ties.\n\n See Also\n --------\n numpy.sort : Return a sorted copy of an array.\n numpy.argsort : Indirect sort.\n numpy.lexsort : Indirect stable sort on multiple keys.\n numpy.searchsorted : Find elements in sorted array.\n numpy.partition: Partial sort.\n\n Notes\n -----\n See `numpy.sort` for notes on the different sorting algorithms.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array([[1,4], [3,1]])\n >>> a.sort(axis=1)\n >>> a\n array([[1, 4],\n [1, 3]])\n >>> a.sort(axis=0)\n >>> a\n array([[1, 3],\n [1, 4]])\n\n Use the `order` keyword to specify a field to use when sorting a\n structured array:\n\n >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])\n >>> a.sort(order='y')\n >>> a\n array([(b'c', 1), (b'a', 2)],\n dtype=[('x', 'S1'), ('y', '>> import numpy as np\n >>> a = np.array([3, 4, 2, 1])\n >>> a.partition(3)\n >>> a\n array([2, 1, 3, 4]) # may vary\n\n >>> a.partition((1, 3))\n >>> a\n array([1, 2, 3, 4])\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('squeeze', '\n a.squeeze(axis=None)\n\n Remove axes of length one from `a`.\n\n Refer to `numpy.squeeze` for full documentation.\n\n See Also\n --------\n numpy.squeeze : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('std', '\n a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)\n\n Returns the standard deviation of the array elements along given axis.\n\n Refer to `numpy.std` for full documentation.\n\n See Also\n --------\n numpy.std : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('sum', '\n a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)\n\n Return the sum of the array elements over the given axis.\n\n Refer to `numpy.sum` for full documentation.\n\n See Also\n --------\n numpy.sum : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('swapaxes', '\n a.swapaxes(axis1, axis2)\n\n Return a view of the array with `axis1` and `axis2` interchanged.\n\n Refer to `numpy.swapaxes` for full documentation.\n\n See Also\n --------\n numpy.swapaxes : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('take', "\n a.take(indices, axis=None, out=None, mode='raise')\n\n Return an array formed from the elements of `a` at the given indices.\n\n Refer to `numpy.take` for full documentation.\n\n See Also\n --------\n numpy.take : equivalent function\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('tofile', '\n a.tofile(fid, sep="", format="%s")\n\n Write array to a file as text or binary (default).\n\n Data is always written in \'C\' order, independent of the order of `a`.\n The data produced by this method can be recovered using the function\n fromfile().\n\n Parameters\n ----------\n fid : file or str or Path\n An open file object, or a string containing a filename.\n\n .. versionchanged:: 1.17.0\n `pathlib.Path` objects are now accepted.\n\n sep : str\n Separator between array items for text output.\n If "" (empty), a binary file is written, equivalent to\n ``file.write(a.tobytes())``.\n format : str\n Format string for text file output.\n Each entry in the array is formatted to text by first converting\n it to the closest Python type, and then using "format" % item.\n\n Notes\n -----\n This is a convenience function for quick storage of array data.\n Information on endianness and precision is lost, so this method is not a\n good choice for files intended to archive data or transport data between\n machines with different endianness. Some of these problems can be overcome\n by outputting the data as text files, at the expense of speed and file\n size.\n\n When fid is a file object, array contents are directly written to the\n file, bypassing the file object\'s ``write`` method. As a result, tofile\n cannot be used with files objects supporting compression (e.g., GzipFile)\n or file-like objects that do not support ``fileno()`` (e.g., BytesIO).\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('tolist', "\n a.tolist()\n\n Return the array as an ``a.ndim``-levels deep nested list of Python scalars.\n\n Return a copy of the array data as a (nested) Python list.\n Data items are converted to the nearest compatible builtin Python type, via\n the `~numpy.ndarray.item` function.\n\n If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will\n not be a list at all, but a simple Python scalar.\n\n Parameters\n ----------\n none\n\n Returns\n -------\n y : object, or list of object, or list of list of object, or ...\n The possibly nested list of array elements.\n\n Notes\n -----\n The array may be recreated via ``a = np.array(a.tolist())``, although this\n may sometimes lose precision.\n\n Examples\n --------\n For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,\n except that ``tolist`` changes numpy scalars to Python scalars:\n\n >>> import numpy as np\n >>> a = np.uint32([1, 2])\n >>> a_list = list(a)\n >>> a_list\n [np.uint32(1), np.uint32(2)]\n >>> type(a_list[0])\n \n >>> a_tolist = a.tolist()\n >>> a_tolist\n [1, 2]\n >>> type(a_tolist[0])\n \n\n Additionally, for a 2D array, ``tolist`` applies recursively:\n\n >>> a = np.array([[1, 2], [3, 4]])\n >>> list(a)\n [array([1, 2]), array([3, 4])]\n >>> a.tolist()\n [[1, 2], [3, 4]]\n\n The base case for this recursion is a 0D array:\n\n >>> a = np.array(1)\n >>> list(a)\n Traceback (most recent call last):\n ...\n TypeError: iteration over a 0-d array\n >>> a.tolist()\n 1\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('tobytes', "\n a.tobytes(order='C')\n\n Construct Python bytes containing the raw data bytes in the array.\n\n Constructs Python bytes showing a copy of the raw contents of\n data memory. The bytes object is produced in C-order by default.\n This behavior is controlled by the ``order`` parameter.\n\n .. versionadded:: 1.9.0\n\n Parameters\n ----------\n order : {'C', 'F', 'A'}, optional\n Controls the memory layout of the bytes object. 'C' means C-order,\n 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is\n Fortran contiguous, 'C' otherwise. Default is 'C'.\n\n Returns\n -------\n s : bytes\n Python bytes exhibiting a copy of `a`'s raw data.\n\n See also\n --------\n frombuffer\n Inverse of this operation, construct a 1-dimensional array from Python\n bytes.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([[0, 1], [2, 3]], dtype='>> x.tobytes()\n b'\\x00\\x00\\x01\\x00\\x02\\x00\\x03\\x00'\n >>> x.tobytes('C') == x.tobytes()\n True\n >>> x.tobytes('F')\n b'\\x00\\x00\\x02\\x00\\x01\\x00\\x03\\x00'\n\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('tostring', "\n a.tostring(order='C')\n\n A compatibility alias for `~ndarray.tobytes`, with exactly the same\n behavior.\n\n Despite its name, it returns :class:`bytes` not :class:`str`\\ s.\n\n .. deprecated:: 1.19.0\n ")) add_newdoc('numpy._core.multiarray', 'ndarray', ('trace', '\n a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)\n\n Return the sum along diagonals of the array.\n\n Refer to `numpy.trace` for full documentation.\n\n See Also\n --------\n numpy.trace : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('transpose', '\n a.transpose(*axes)\n\n Returns a view of the array with axes transposed.\n\n Refer to `numpy.transpose` for full documentation.\n\n Parameters\n ----------\n axes : None, tuple of ints, or `n` ints\n\n * None or no argument: reverses the order of the axes.\n\n * tuple of ints: `i` in the `j`-th place in the tuple means that the\n array\'s `i`-th axis becomes the transposed array\'s `j`-th axis.\n\n * `n` ints: same as an n-tuple of the same ints (this form is\n intended simply as a "convenience" alternative to the tuple form).\n\n Returns\n -------\n p : ndarray\n View of the array with its axes suitably permuted.\n\n See Also\n --------\n transpose : Equivalent function.\n ndarray.T : Array property returning the array transposed.\n ndarray.reshape : Give a new shape to an array without changing its data.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array([[1, 2], [3, 4]])\n >>> a\n array([[1, 2],\n [3, 4]])\n >>> a.transpose()\n array([[1, 3],\n [2, 4]])\n >>> a.transpose((1, 0))\n array([[1, 3],\n [2, 4]])\n >>> a.transpose(1, 0)\n array([[1, 3],\n [2, 4]])\n\n >>> a = np.array([1, 2, 3, 4])\n >>> a\n array([1, 2, 3, 4])\n >>> a.transpose()\n array([1, 2, 3, 4])\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('var', '\n a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)\n\n Returns the variance of the array elements, along given axis.\n\n Refer to `numpy.var` for full documentation.\n\n See Also\n --------\n numpy.var : equivalent function\n\n ')) add_newdoc('numpy._core.multiarray', 'ndarray', ('view', '\n a.view([dtype][, type])\n\n New view of array with the same data.\n\n .. note::\n Passing None for ``dtype`` is different from omitting the parameter,\n since the former invokes ``dtype(None)`` which is an alias for\n ``dtype(\'float64\')``.\n\n Parameters\n ----------\n dtype : data-type or ndarray sub-class, optional\n Data-type descriptor of the returned view, e.g., float32 or int16.\n Omitting it results in the view having the same data-type as `a`.\n This argument can also be specified as an ndarray sub-class, which\n then specifies the type of the returned object (this is equivalent to\n setting the ``type`` parameter).\n type : Python type, optional\n Type of the returned view, e.g., ndarray or matrix. Again, omission\n of the parameter results in type preservation.\n\n Notes\n -----\n ``a.view()`` is used two different ways:\n\n ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view\n of the array\'s memory with a different data-type. This can cause a\n reinterpretation of the bytes of memory.\n\n ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just\n returns an instance of `ndarray_subclass` that looks at the same array\n (same shape, dtype, etc.) This does not cause a reinterpretation of the\n memory.\n\n For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of\n bytes per entry than the previous dtype (for example, converting a regular\n array to a structured array), then the last axis of ``a`` must be\n contiguous. This axis will be resized in the result.\n\n .. versionchanged:: 1.23.0\n Only the last axis needs to be contiguous. Previously, the entire array\n had to be C-contiguous.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([(-1, 2)], dtype=[(\'a\', np.int8), (\'b\', np.int8)])\n\n Viewing array data using a different type and dtype:\n\n >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])\n >>> y = x.view(dtype=nonneg, type=np.recarray)\n >>> x["a"]\n array([-1], dtype=int8)\n >>> y.a\n array([255], dtype=uint8)\n\n Creating a view on a structured array so it can be used in calculations\n\n >>> x = np.array([(1, 2),(3,4)], dtype=[(\'a\', np.int8), (\'b\', np.int8)])\n >>> xv = x.view(dtype=np.int8).reshape(-1,2)\n >>> xv\n array([[1, 2],\n [3, 4]], dtype=int8)\n >>> xv.mean(0)\n array([2., 3.])\n\n Making changes to the view changes the underlying array\n\n >>> xv[0,1] = 20\n >>> x\n array([(1, 20), (3, 4)], dtype=[(\'a\', \'i1\'), (\'b\', \'i1\')])\n\n Using a view to convert an array to a recarray:\n\n >>> z = x.view(np.recarray)\n >>> z.a\n array([1, 3], dtype=int8)\n\n Views share data:\n\n >>> x[0] = (9, 10)\n >>> z[0]\n np.record((9, 10), dtype=[(\'a\', \'i1\'), (\'b\', \'i1\')])\n\n Views that change the dtype size (bytes per entry) should normally be\n avoided on arrays defined by slices, transposes, fortran-ordering, etc.:\n\n >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)\n >>> y = x[:, ::2]\n >>> y\n array([[1, 3],\n [4, 6]], dtype=int16)\n >>> y.view(dtype=[(\'width\', np.int16), (\'length\', np.int16)])\n Traceback (most recent call last):\n ...\n ValueError: To change to a dtype of a different size, the last axis must be contiguous\n >>> z = y.copy()\n >>> z.view(dtype=[(\'width\', np.int16), (\'length\', np.int16)])\n array([[(1, 3)],\n [(4, 6)]], dtype=[(\'width\', \'>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)\n >>> x.transpose(1, 0, 2).view(np.int16)\n array([[[ 256, 770],\n [3340, 3854]],\n \n [[1284, 1798],\n [4368, 4882]],\n \n [[2312, 2826],\n [5396, 5910]]], dtype=int16)\n\n ')) add_newdoc('numpy._core.umath', 'frompyfunc', "\n frompyfunc(func, /, nin, nout, *[, identity])\n\n Takes an arbitrary Python function and returns a NumPy ufunc.\n\n Can be used, for example, to add broadcasting to a built-in Python\n function (see Examples section).\n\n Parameters\n ----------\n func : Python function object\n An arbitrary Python function.\n nin : int\n The number of input arguments.\n nout : int\n The number of objects returned by `func`.\n identity : object, optional\n The value to use for the `~numpy.ufunc.identity` attribute of the resulting\n object. If specified, this is equivalent to setting the underlying\n C ``identity`` field to ``PyUFunc_IdentityValue``.\n If omitted, the identity is set to ``PyUFunc_None``. Note that this is\n _not_ equivalent to setting the identity to ``None``, which implies the\n operation is reorderable.\n\n Returns\n -------\n out : ufunc\n Returns a NumPy universal function (``ufunc``) object.\n\n See Also\n --------\n vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy.\n\n Notes\n -----\n The returned ufunc always returns PyObject arrays.\n\n Examples\n --------\n Use frompyfunc to add broadcasting to the Python function ``oct``:\n\n >>> import numpy as np\n >>> oct_array = np.frompyfunc(oct, 1, 1)\n >>> oct_array(np.array((10, 30, 100)))\n array(['0o12', '0o36', '0o144'], dtype=object)\n >>> np.array((oct(10), oct(30), oct(100))) # for comparison\n array(['0o12', '0o36', '0o144'], dtype='doc is NULL.)\n\n Parameters\n ----------\n ufunc : numpy.ufunc\n A ufunc whose current doc is NULL.\n new_docstring : string\n The new docstring for the ufunc.\n\n Notes\n -----\n This method allocates memory for new_docstring on\n the heap. Technically this creates a memory leak, since this\n memory will not be reclaimed until the end of the program\n even if the ufunc itself is removed. However this will only\n be a problem if the user is repeatedly creating ufuncs with\n no documentation, adding documentation via add_newdoc_ufunc,\n and then throwing away the ufunc.\n ') add_newdoc('numpy._core.multiarray', 'get_handler_name', '\n get_handler_name(a: ndarray) -> str,None\n\n Return the name of the memory handler used by `a`. If not provided, return\n the name of the memory handler that will be used to allocate data for the\n next `ndarray` in this context. May return None if `a` does not own its\n memory, in which case you can traverse ``a.base`` for a memory handler.\n ') add_newdoc('numpy._core.multiarray', 'get_handler_version', '\n get_handler_version(a: ndarray) -> int,None\n\n Return the version of the memory handler used by `a`. If not provided,\n return the version of the memory handler that will be used to allocate data\n for the next `ndarray` in this context. May return None if `a` does not own\n its memory, in which case you can traverse ``a.base`` for a memory handler.\n ') add_newdoc('numpy._core._multiarray_umath', '_array_converter', '\n _array_converter(*array_likes)\n\n Helper to convert one or more objects to arrays. Integrates machinery\n to deal with the ``result_type`` and ``__array_wrap__``.\n\n The reason for this is that e.g. ``result_type`` needs to convert to arrays\n to find the ``dtype``. But converting to an array before calling\n ``result_type`` would incorrectly "forget" whether it was a Python int,\n float, or complex.\n ') add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('scalar_input', '\n A tuple which indicates for each input whether it was a scalar that\n was coerced to a 0-D array (and was not already an array or something\n converted via a protocol like ``__array__()``).\n ')) add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('as_arrays', '\n as_arrays(/, subok=True, pyscalars="convert_if_no_array")\n\n Return the inputs as arrays or scalars.\n\n Parameters\n ----------\n subok : True or False, optional\n Whether array subclasses are preserved.\n pyscalars : {"convert", "preserve", "convert_if_no_array"}, optional\n To allow NEP 50 weak promotion later, it may be desirable to preserve\n Python scalars. As default, these are preserved unless all inputs\n are Python scalars. "convert" enforces an array return.\n ')) add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('result_type', 'result_type(/, extra_dtype=None, ensure_inexact=False)\n\n Find the ``result_type`` just as ``np.result_type`` would, but taking\n into account that the original inputs (before converting to an array) may\n have been Python scalars with weak promotion.\n\n Parameters\n ----------\n extra_dtype : dtype instance or class\n An additional DType or dtype instance to promote (e.g. could be used\n to ensure the result precision is at least float32).\n ensure_inexact : True or False\n When ``True``, ensures a floating point (or complex) result replacing\n the ``arr * 1.`` or ``result_type(..., 0.0)`` pattern.\n ')) add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('wrap', '\n wrap(arr, /, to_scalar=None)\n\n Call ``__array_wrap__`` on ``arr`` if ``arr`` is not the same subclass\n as the input the ``__array_wrap__`` method was retrieved from.\n\n Parameters\n ----------\n arr : ndarray\n The object to be wrapped. Normally an ndarray or subclass,\n although for backward compatibility NumPy scalars are also accepted\n (these will be converted to a NumPy array before being passed on to\n the ``__array_wrap__`` method).\n to_scalar : {True, False, None}, optional\n When ``True`` will convert a 0-d array to a scalar via ``result[()]``\n (with a fast-path for non-subclasses). If ``False`` the result should\n be an array-like (as ``__array_wrap__`` is free to return a non-array).\n By default (``None``), a scalar is returned if all inputs were scalar.\n ')) add_newdoc('numpy._core.multiarray', '_get_madvise_hugepage', '\n _get_madvise_hugepage() -> bool\n\n Get use of ``madvise (2)`` MADV_HUGEPAGE support when\n allocating the array data. Returns the currently set value.\n See `global_state` for more information.\n ') add_newdoc('numpy._core.multiarray', '_set_madvise_hugepage', '\n _set_madvise_hugepage(enabled: bool) -> bool\n\n Set or unset use of ``madvise (2)`` MADV_HUGEPAGE support when\n allocating the array data. Returns the previously set value.\n See `global_state` for more information.\n ') add_newdoc('numpy._core', 'ufunc', "\n Functions that operate element by element on whole arrays.\n\n To see the documentation for a specific ufunc, use `info`. For\n example, ``np.info(np.sin)``. Because ufuncs are written in C\n (for speed) and linked into Python with NumPy's ufunc facility,\n Python's help() function finds this page whenever help() is called\n on a ufunc.\n\n A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.\n\n **Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)``\n\n Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.\n\n The broadcasting rules are:\n\n * Dimensions of length 1 may be prepended to either array.\n * Arrays may be repeated along dimensions of length 1.\n\n Parameters\n ----------\n *x : array_like\n Input arrays.\n out : ndarray, None, or tuple of ndarray and None, optional\n Alternate array object(s) in which to put the result; if provided, it\n must have a shape that the inputs broadcast to. A tuple of arrays\n (possible only as a keyword argument) must have length equal to the\n number of outputs; use None for uninitialized outputs to be\n allocated by the ufunc.\n where : array_like, optional\n This condition is broadcast over the input. At locations where the\n condition is True, the `out` array will be set to the ufunc result.\n Elsewhere, the `out` array will retain its original value.\n Note that if an uninitialized `out` array is created via the default\n ``out=None``, locations within it where the condition is False will\n remain uninitialized.\n **kwargs\n For other keyword-only arguments, see the :ref:`ufunc docs `.\n\n Returns\n -------\n r : ndarray or tuple of ndarray\n `r` will have the shape that the arrays in `x` broadcast to; if `out` is\n provided, it will be returned. If not, `r` will be allocated and\n may contain uninitialized values. If the function has more than one\n output, then the result will be a tuple of arrays.\n\n ") add_newdoc('numpy._core', 'ufunc', ('identity', '\n The identity value.\n\n Data attribute containing the identity element for the ufunc,\n if it has one. If it does not, the attribute value is None.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.add.identity\n 0\n >>> np.multiply.identity\n 1\n >>> np.power.identity\n 1\n >>> print(np.exp.identity)\n None\n ')) add_newdoc('numpy._core', 'ufunc', ('nargs', '\n The number of arguments.\n\n Data attribute containing the number of arguments the ufunc takes, including\n optional ones.\n\n Notes\n -----\n Typically this value will be one more than what you might expect\n because all ufuncs take the optional "out" argument.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.add.nargs\n 3\n >>> np.multiply.nargs\n 3\n >>> np.power.nargs\n 3\n >>> np.exp.nargs\n 2\n ')) add_newdoc('numpy._core', 'ufunc', ('nin', '\n The number of inputs.\n\n Data attribute containing the number of arguments the ufunc treats as input.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.add.nin\n 2\n >>> np.multiply.nin\n 2\n >>> np.power.nin\n 2\n >>> np.exp.nin\n 1\n ')) add_newdoc('numpy._core', 'ufunc', ('nout', '\n The number of outputs.\n\n Data attribute containing the number of arguments the ufunc treats as output.\n\n Notes\n -----\n Since all ufuncs can take output arguments, this will always be at least 1.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.add.nout\n 1\n >>> np.multiply.nout\n 1\n >>> np.power.nout\n 1\n >>> np.exp.nout\n 1\n\n ')) add_newdoc('numpy._core', 'ufunc', ('ntypes', '\n The number of types.\n\n The number of numerical NumPy types - of which there are 18 total - on which\n the ufunc can operate.\n\n See Also\n --------\n numpy.ufunc.types\n\n Examples\n --------\n >>> import numpy as np\n >>> np.add.ntypes\n 18\n >>> np.multiply.ntypes\n 18\n >>> np.power.ntypes\n 17\n >>> np.exp.ntypes\n 7\n >>> np.remainder.ntypes\n 14\n\n ')) add_newdoc('numpy._core', 'ufunc', ('types', '\n Returns a list with types grouped input->output.\n\n Data attribute listing the data-type "Domain-Range" groupings the ufunc can\n deliver. The data-types are given using the character codes.\n\n See Also\n --------\n numpy.ufunc.ntypes\n\n Examples\n --------\n >>> import numpy as np\n >>> np.add.types\n [\'??->?\', \'bb->b\', \'BB->B\', \'hh->h\', \'HH->H\', \'ii->i\', \'II->I\', \'ll->l\',\n \'LL->L\', \'qq->q\', \'QQ->Q\', \'ff->f\', \'dd->d\', \'gg->g\', \'FF->F\', \'DD->D\',\n \'GG->G\', \'OO->O\']\n\n >>> np.multiply.types\n [\'??->?\', \'bb->b\', \'BB->B\', \'hh->h\', \'HH->H\', \'ii->i\', \'II->I\', \'ll->l\',\n \'LL->L\', \'qq->q\', \'QQ->Q\', \'ff->f\', \'dd->d\', \'gg->g\', \'FF->F\', \'DD->D\',\n \'GG->G\', \'OO->O\']\n\n >>> np.power.types\n [\'bb->b\', \'BB->B\', \'hh->h\', \'HH->H\', \'ii->i\', \'II->I\', \'ll->l\', \'LL->L\',\n \'qq->q\', \'QQ->Q\', \'ff->f\', \'dd->d\', \'gg->g\', \'FF->F\', \'DD->D\', \'GG->G\',\n \'OO->O\']\n\n >>> np.exp.types\n [\'f->f\', \'d->d\', \'g->g\', \'F->F\', \'D->D\', \'G->G\', \'O->O\']\n\n >>> np.remainder.types\n [\'bb->b\', \'BB->B\', \'hh->h\', \'HH->H\', \'ii->i\', \'II->I\', \'ll->l\', \'LL->L\',\n \'qq->q\', \'QQ->Q\', \'ff->f\', \'dd->d\', \'gg->g\', \'OO->O\']\n\n ')) add_newdoc('numpy._core', 'ufunc', ('signature', "\n Definition of the core elements a generalized ufunc operates on.\n\n The signature determines how the dimensions of each input/output array\n are split into core and loop dimensions:\n\n 1. Each dimension in the signature is matched to a dimension of the\n corresponding passed-in array, starting from the end of the shape tuple.\n 2. Core dimensions assigned to the same label in the signature must have\n exactly matching sizes, no broadcasting is performed.\n 3. The core dimensions are removed from all inputs and the remaining\n dimensions are broadcast together, defining the loop dimensions.\n\n Notes\n -----\n Generalized ufuncs are used internally in many linalg functions, and in\n the testing suite; the examples below are taken from these.\n For ufuncs that operate on scalars, the signature is None, which is\n equivalent to '()' for every argument.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.linalg._umath_linalg.det.signature\n '(m,m)->()'\n >>> np.matmul.signature\n '(n?,k),(k,m?)->(n?,m?)'\n >>> np.add.signature is None\n True # equivalent to '(),()->()'\n ")) add_newdoc('numpy._core', 'ufunc', ('reduce', "\n reduce(array, axis=0, dtype=None, out=None, keepdims=False, initial=, where=True)\n\n Reduces `array`'s dimension by one, by applying ufunc along one axis.\n\n Let :math:`array.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then\n :math:`ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` =\n the result of iterating `j` over :math:`range(N_i)`, cumulatively applying\n ufunc to each :math:`array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`.\n For a one-dimensional array, reduce produces results equivalent to:\n ::\n\n r = op.identity # op = ufunc\n for i in range(len(A)):\n r = op(r, A[i])\n return r\n\n For example, add.reduce() is equivalent to sum().\n\n Parameters\n ----------\n array : array_like\n The array to act on.\n axis : None or int or tuple of ints, optional\n Axis or axes along which a reduction is performed.\n The default (`axis` = 0) is perform a reduction over the first\n dimension of the input array. `axis` may be negative, in\n which case it counts from the last to the first axis.\n\n .. versionadded:: 1.7.0\n\n If this is None, a reduction is performed over all the axes.\n If this is a tuple of ints, a reduction is performed on multiple\n axes, instead of a single axis or all the axes as before.\n\n For operations which are either not commutative or not associative,\n doing a reduction over multiple axes is not well-defined. The\n ufuncs do not currently raise an exception in this case, but will\n likely do so in the future.\n dtype : data-type code, optional\n The data type used to perform the operation. Defaults to that of\n ``out`` if given, and the data type of ``array`` otherwise (though\n upcast to conserve precision for some cases, such as\n ``numpy.add.reduce`` for integer or boolean input).\n out : ndarray, None, or tuple of ndarray and None, optional\n A location into which the result is stored. If not provided or None,\n a freshly-allocated array is returned. For consistency with\n ``ufunc.__call__``, if given as a keyword, this may be wrapped in a\n 1-element tuple.\n\n .. versionchanged:: 1.13.0\n Tuples are allowed for keyword argument.\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the original `array`.\n\n .. versionadded:: 1.7.0\n initial : scalar, optional\n The value with which to start the reduction.\n If the ufunc has no identity or the dtype is object, this defaults\n to None - otherwise it defaults to ufunc.identity.\n If ``None`` is given, the first element of the reduction is used,\n and an error is thrown if the reduction is empty.\n\n .. versionadded:: 1.15.0\n\n where : array_like of bool, optional\n A boolean array which is broadcasted to match the dimensions\n of `array`, and selects elements to include in the reduction. Note\n that for ufuncs like ``minimum`` that do not have an identity\n defined, one has to pass in also ``initial``.\n\n .. versionadded:: 1.17.0\n\n Returns\n -------\n r : ndarray\n The reduced array. If `out` was supplied, `r` is a reference to it.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.multiply.reduce([2,3,5])\n 30\n\n A multi-dimensional array example:\n\n >>> X = np.arange(8).reshape((2,2,2))\n >>> X\n array([[[0, 1],\n [2, 3]],\n [[4, 5],\n [6, 7]]])\n >>> np.add.reduce(X, 0)\n array([[ 4, 6],\n [ 8, 10]])\n >>> np.add.reduce(X) # confirm: default axis value is 0\n array([[ 4, 6],\n [ 8, 10]])\n >>> np.add.reduce(X, 1)\n array([[ 2, 4],\n [10, 12]])\n >>> np.add.reduce(X, 2)\n array([[ 1, 5],\n [ 9, 13]])\n\n You can use the ``initial`` keyword argument to initialize the reduction\n with a different value, and ``where`` to select specific elements to include:\n\n >>> np.add.reduce([10], initial=5)\n 15\n >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)\n array([14., 14.])\n >>> a = np.array([10., np.nan, 10])\n >>> np.add.reduce(a, where=~np.isnan(a))\n 20.0\n\n Allows reductions of empty arrays where they would normally fail, i.e.\n for ufuncs without an identity.\n\n >>> np.minimum.reduce([], initial=np.inf)\n inf\n >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])\n array([ 1., 10.])\n >>> np.minimum.reduce([])\n Traceback (most recent call last):\n ...\n ValueError: zero-size array to reduction operation minimum which has no identity\n ")) add_newdoc('numpy._core', 'ufunc', ('accumulate', "\n accumulate(array, axis=0, dtype=None, out=None)\n\n Accumulate the result of applying the operator to all elements.\n\n For a one-dimensional array, accumulate produces results equivalent to::\n\n r = np.empty(len(A))\n t = op.identity # op = the ufunc being applied to A's elements\n for i in range(len(A)):\n t = op(t, A[i])\n r[i] = t\n return r\n\n For example, add.accumulate() is equivalent to np.cumsum().\n\n For a multi-dimensional array, accumulate is applied along only one\n axis (axis zero by default; see Examples below) so repeated use is\n necessary if one wants to accumulate over multiple axes.\n\n Parameters\n ----------\n array : array_like\n The array to act on.\n axis : int, optional\n The axis along which to apply the accumulation; default is zero.\n dtype : data-type code, optional\n The data-type used to represent the intermediate results. Defaults\n to the data-type of the output array if such is provided, or the\n data-type of the input array if no output array is provided.\n out : ndarray, None, or tuple of ndarray and None, optional\n A location into which the result is stored. If not provided or None,\n a freshly-allocated array is returned. For consistency with\n ``ufunc.__call__``, if given as a keyword, this may be wrapped in a\n 1-element tuple.\n\n .. versionchanged:: 1.13.0\n Tuples are allowed for keyword argument.\n\n Returns\n -------\n r : ndarray\n The accumulated values. If `out` was supplied, `r` is a reference to\n `out`.\n\n Examples\n --------\n 1-D array examples:\n\n >>> import numpy as np\n >>> np.add.accumulate([2, 3, 5])\n array([ 2, 5, 10])\n >>> np.multiply.accumulate([2, 3, 5])\n array([ 2, 6, 30])\n\n 2-D array examples:\n\n >>> I = np.eye(2)\n >>> I\n array([[1., 0.],\n [0., 1.]])\n\n Accumulate along axis 0 (rows), down columns:\n\n >>> np.add.accumulate(I, 0)\n array([[1., 0.],\n [1., 1.]])\n >>> np.add.accumulate(I) # no axis specified = axis zero\n array([[1., 0.],\n [1., 1.]])\n\n Accumulate along axis 1 (columns), through rows:\n\n >>> np.add.accumulate(I, 1)\n array([[1., 1.],\n [0., 1.]])\n\n ")) add_newdoc('numpy._core', 'ufunc', ('reduceat', '\n reduceat(array, indices, axis=0, dtype=None, out=None)\n\n Performs a (local) reduce with specified slices over a single axis.\n\n For i in ``range(len(indices))``, `reduceat` computes\n ``ufunc.reduce(array[indices[i]:indices[i+1]])``, which becomes the i-th\n generalized "row" parallel to `axis` in the final result (i.e., in a\n 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if\n `axis = 1`, it becomes the i-th column). There are three exceptions to this:\n\n * when ``i = len(indices) - 1`` (so for the last index),\n ``indices[i+1] = array.shape[axis]``.\n * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is\n simply ``array[indices[i]]``.\n * if ``indices[i] >= len(array)`` or ``indices[i] < 0``, an error is raised.\n\n The shape of the output depends on the size of `indices`, and may be\n larger than `array` (this happens if ``len(indices) > array.shape[axis]``).\n\n Parameters\n ----------\n array : array_like\n The array to act on.\n indices : array_like\n Paired indices, comma separated (not colon), specifying slices to\n reduce.\n axis : int, optional\n The axis along which to apply the reduceat.\n dtype : data-type code, optional\n The data type used to perform the operation. Defaults to that of\n ``out`` if given, and the data type of ``array`` otherwise (though\n upcast to conserve precision for some cases, such as\n ``numpy.add.reduce`` for integer or boolean input).\n out : ndarray, None, or tuple of ndarray and None, optional\n A location into which the result is stored. If not provided or None,\n a freshly-allocated array is returned. For consistency with\n ``ufunc.__call__``, if given as a keyword, this may be wrapped in a\n 1-element tuple.\n\n .. versionchanged:: 1.13.0\n Tuples are allowed for keyword argument.\n\n Returns\n -------\n r : ndarray\n The reduced values. If `out` was supplied, `r` is a reference to\n `out`.\n\n Notes\n -----\n A descriptive example:\n\n If `array` is 1-D, the function `ufunc.accumulate(array)` is the same as\n ``ufunc.reduceat(array, indices)[::2]`` where `indices` is\n ``range(len(array) - 1)`` with a zero placed\n in every other element:\n ``indices = zeros(2 * len(array) - 1)``,\n ``indices[1::2] = range(1, len(array))``.\n\n Don\'t be fooled by this attribute\'s name: `reduceat(array)` is not\n necessarily smaller than `array`.\n\n Examples\n --------\n To take the running sum of four successive values:\n\n >>> import numpy as np\n >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]\n array([ 6, 10, 14, 18])\n\n A 2-D example:\n\n >>> x = np.linspace(0, 15, 16).reshape(4,4)\n >>> x\n array([[ 0., 1., 2., 3.],\n [ 4., 5., 6., 7.],\n [ 8., 9., 10., 11.],\n [12., 13., 14., 15.]])\n\n ::\n\n # reduce such that the result has the following five rows:\n # [row1 + row2 + row3]\n # [row4]\n # [row2]\n # [row3]\n # [row1 + row2 + row3 + row4]\n\n >>> np.add.reduceat(x, [0, 3, 1, 2, 0])\n array([[12., 15., 18., 21.],\n [12., 13., 14., 15.],\n [ 4., 5., 6., 7.],\n [ 8., 9., 10., 11.],\n [24., 28., 32., 36.]])\n\n ::\n\n # reduce such that result has the following two columns:\n # [col1 * col2 * col3, col4]\n\n >>> np.multiply.reduceat(x, [0, 3], 1)\n array([[ 0., 3.],\n [ 120., 7.],\n [ 720., 11.],\n [2184., 15.]])\n\n ')) add_newdoc('numpy._core', 'ufunc', ('outer', '\n outer(A, B, /, **kwargs)\n\n Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.\n\n Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of\n ``op.outer(A, B)`` is an array of dimension M + N such that:\n\n .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] =\n op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}])\n\n For `A` and `B` one-dimensional, this is equivalent to::\n\n r = empty(len(A),len(B))\n for i in range(len(A)):\n for j in range(len(B)):\n r[i,j] = op(A[i], B[j]) # op = ufunc in question\n\n Parameters\n ----------\n A : array_like\n First array\n B : array_like\n Second array\n kwargs : any\n Arguments to pass on to the ufunc. Typically `dtype` or `out`.\n See `ufunc` for a comprehensive overview of all available arguments.\n\n Returns\n -------\n r : ndarray\n Output array\n\n See Also\n --------\n numpy.outer : A less powerful version of ``np.multiply.outer``\n that `ravel`\\ s all inputs to 1D. This exists\n primarily for compatibility with old code.\n\n tensordot : ``np.tensordot(a, b, axes=((), ()))`` and\n ``np.multiply.outer(a, b)`` behave same for all\n dimensions of a and b.\n\n Examples\n --------\n >>> np.multiply.outer([1, 2, 3], [4, 5, 6])\n array([[ 4, 5, 6],\n [ 8, 10, 12],\n [12, 15, 18]])\n\n A multi-dimensional example:\n\n >>> A = np.array([[1, 2, 3], [4, 5, 6]])\n >>> A.shape\n (2, 3)\n >>> B = np.array([[1, 2, 3, 4]])\n >>> B.shape\n (1, 4)\n >>> C = np.multiply.outer(A, B)\n >>> C.shape; C\n (2, 3, 1, 4)\n array([[[[ 1, 2, 3, 4]],\n [[ 2, 4, 6, 8]],\n [[ 3, 6, 9, 12]]],\n [[[ 4, 8, 12, 16]],\n [[ 5, 10, 15, 20]],\n [[ 6, 12, 18, 24]]]])\n\n ')) add_newdoc('numpy._core', 'ufunc', ('at', "\n at(a, indices, b=None, /)\n\n Performs unbuffered in place operation on operand 'a' for elements\n specified by 'indices'. For addition ufunc, this method is equivalent to\n ``a[indices] += b``, except that results are accumulated for elements that\n are indexed more than once. For example, ``a[[0,0]] += 1`` will only\n increment the first element once because of buffering, whereas\n ``add.at(a, [0,0], 1)`` will increment the first element twice.\n\n .. versionadded:: 1.8.0\n\n Parameters\n ----------\n a : array_like\n The array to perform in place operation on.\n indices : array_like or tuple\n Array like index object or slice object for indexing into first\n operand. If first operand has multiple dimensions, indices can be a\n tuple of array like index objects or slice objects.\n b : array_like\n Second operand for ufuncs requiring two operands. Operand must be\n broadcastable over first operand after indexing or slicing.\n\n Examples\n --------\n Set items 0 and 1 to their negative values:\n\n >>> import numpy as np\n >>> a = np.array([1, 2, 3, 4])\n >>> np.negative.at(a, [0, 1])\n >>> a\n array([-1, -2, 3, 4])\n\n Increment items 0 and 1, and increment item 2 twice:\n\n >>> a = np.array([1, 2, 3, 4])\n >>> np.add.at(a, [0, 1, 2, 2], 1)\n >>> a\n array([2, 3, 5, 4])\n\n Add items 0 and 1 in first array to second array,\n and store results in first array:\n\n >>> a = np.array([1, 2, 3, 4])\n >>> b = np.array([1, 2])\n >>> np.add.at(a, [0, 1], b)\n >>> a\n array([2, 4, 3, 4])\n\n ")) add_newdoc('numpy._core', 'ufunc', ('resolve_dtypes', '\n resolve_dtypes(dtypes, *, signature=None, casting=None, reduction=False)\n\n Find the dtypes NumPy will use for the operation. Both input and\n output dtypes are returned and may differ from those provided.\n\n .. note::\n\n This function always applies NEP 50 rules since it is not provided\n any actual values. The Python types ``int``, ``float``, and\n ``complex`` thus behave weak and should be passed for "untyped"\n Python input.\n\n Parameters\n ----------\n dtypes : tuple of dtypes, None, or literal int, float, complex\n The input dtypes for each operand. Output operands can be\n None, indicating that the dtype must be found.\n signature : tuple of DTypes or None, optional\n If given, enforces exact DType (classes) of the specific operand.\n The ufunc ``dtype`` argument is equivalent to passing a tuple with\n only output dtypes set.\n casting : {\'no\', \'equiv\', \'safe\', \'same_kind\', \'unsafe\'}, optional\n The casting mode when casting is necessary. This is identical to\n the ufunc call casting modes.\n reduction : boolean\n If given, the resolution assumes a reduce operation is happening\n which slightly changes the promotion and type resolution rules.\n `dtypes` is usually something like ``(None, np.dtype("i2"), None)``\n for reductions (first input is also the output).\n\n .. note::\n\n The default casting mode is "same_kind", however, as of\n NumPy 1.24, NumPy uses "unsafe" for reductions.\n\n Returns\n -------\n dtypes : tuple of dtypes\n The dtypes which NumPy would use for the calculation. Note that\n dtypes may not match the passed in ones (casting is necessary).\n\n\n Examples\n --------\n This API requires passing dtypes, define them for convenience:\n\n >>> import numpy as np\n >>> int32 = np.dtype("int32")\n >>> float32 = np.dtype("float32")\n\n The typical ufunc call does not pass an output dtype. `numpy.add` has two\n inputs and one output, so leave the output as ``None`` (not provided):\n\n >>> np.add.resolve_dtypes((int32, float32, None))\n (dtype(\'float64\'), dtype(\'float64\'), dtype(\'float64\'))\n\n The loop found uses "float64" for all operands (including the output), the\n first input would be cast.\n\n ``resolve_dtypes`` supports "weak" handling for Python scalars by passing\n ``int``, ``float``, or ``complex``:\n\n >>> np.add.resolve_dtypes((float32, float, None))\n (dtype(\'float32\'), dtype(\'float32\'), dtype(\'float32\'))\n\n Where the Python ``float`` behaves similar to a Python value ``0.0``\n in a ufunc call. (See :ref:`NEP 50 ` for details.)\n\n ')) add_newdoc('numpy._core', 'ufunc', ('_resolve_dtypes_and_context', '\n _resolve_dtypes_and_context(dtypes, *, signature=None, casting=None, reduction=False)\n\n See `numpy.ufunc.resolve_dtypes` for parameter information. This\n function is considered *unstable*. You may use it, but the returned\n information is NumPy version specific and expected to change.\n Large API/ABI changes are not expected, but a new NumPy version is\n expected to require updating code using this functionality.\n\n This function is designed to be used in conjunction with\n `numpy.ufunc._get_strided_loop`. The calls are split to mirror the C API\n and allow future improvements.\n\n Returns\n -------\n dtypes : tuple of dtypes\n call_info :\n PyCapsule with all necessary information to get access to low level\n C calls. See `numpy.ufunc._get_strided_loop` for more information.\n\n ')) add_newdoc('numpy._core', 'ufunc', ('_get_strided_loop', "\n _get_strided_loop(call_info, /, *, fixed_strides=None)\n\n This function fills in the ``call_info`` capsule to include all\n information necessary to call the low-level strided loop from NumPy.\n\n See notes for more information.\n\n Parameters\n ----------\n call_info : PyCapsule\n The PyCapsule returned by `numpy.ufunc._resolve_dtypes_and_context`.\n fixed_strides : tuple of int or None, optional\n A tuple with fixed byte strides of all input arrays. NumPy may use\n this information to find specialized loops, so any call must follow\n the given stride. Use ``None`` to indicate that the stride is not\n known (or not fixed) for all calls.\n\n Notes\n -----\n Together with `numpy.ufunc._resolve_dtypes_and_context` this function\n gives low-level access to the NumPy ufunc loops.\n The first function does general preparation and returns the required\n information. It returns this as a C capsule with the version specific\n name ``numpy_1.24_ufunc_call_info``.\n The NumPy 1.24 ufunc call info capsule has the following layout::\n\n typedef struct {\n PyArrayMethod_StridedLoop *strided_loop;\n PyArrayMethod_Context *context;\n NpyAuxData *auxdata;\n\n /* Flag information (expected to change) */\n npy_bool requires_pyapi; /* GIL is required by loop */\n\n /* Loop doesn't set FPE flags; if not set check FPE flags */\n npy_bool no_floatingpoint_errors;\n } ufunc_call_info;\n\n Note that the first call only fills in the ``context``. The call to\n ``_get_strided_loop`` fills in all other data. The main thing to note is\n that the new-style loops return 0 on success, -1 on failure. They are\n passed context as new first input and ``auxdata`` as (replaced) last.\n\n Only the ``strided_loop``signature is considered guaranteed stable\n for NumPy bug-fix releases. All other API is tied to the experimental\n API versioning.\n\n The reason for the split call is that cast information is required to\n decide what the fixed-strides will be.\n\n NumPy ties the lifetime of the ``auxdata`` information to the capsule.\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', '\n dtype(dtype, align=False, copy=False, [metadata])\n\n Create a data type object.\n\n A numpy array is homogeneous, and contains elements described by a\n dtype object. A dtype object can be constructed from different\n combinations of fundamental numeric types.\n\n Parameters\n ----------\n dtype\n Object to be converted to a data type object.\n align : bool, optional\n Add padding to the fields to match what a C compiler would output\n for a similar C-struct. Can be ``True`` only if `obj` is a dictionary\n or a comma-separated string. If a struct dtype is being created,\n this also sets a sticky alignment flag ``isalignedstruct``.\n copy : bool, optional\n Make a new copy of the data-type object. If ``False``, the result\n may just be a reference to a built-in data-type object.\n metadata : dict, optional\n An optional dictionary with dtype metadata.\n\n See also\n --------\n result_type\n\n Examples\n --------\n Using array-scalar type:\n\n >>> import numpy as np\n >>> np.dtype(np.int16)\n dtype(\'int16\')\n\n Structured type, one field name \'f1\', containing int16:\n\n >>> np.dtype([(\'f1\', np.int16)])\n dtype([(\'f1\', \'>> np.dtype([(\'f1\', [(\'f1\', np.int16)])])\n dtype([(\'f1\', [(\'f1\', \'>> np.dtype([(\'f1\', np.uint64), (\'f2\', np.int32)])\n dtype([(\'f1\', \'>> np.dtype([(\'a\',\'f8\'),(\'b\',\'S10\')])\n dtype([(\'a\', \'>> np.dtype("i4, (2,3)f8")\n dtype([(\'f0\', \'>> np.dtype([(\'hello\',(np.int64,3)),(\'world\',np.void,10)])\n dtype([(\'hello\', \'>> np.dtype((np.int16, {\'x\':(np.int8,0), \'y\':(np.int8,1)}))\n dtype((numpy.int16, [(\'x\', \'i1\'), (\'y\', \'i1\')]))\n\n Using dictionaries. Two fields named \'gender\' and \'age\':\n\n >>> np.dtype({\'names\':[\'gender\',\'age\'], \'formats\':[\'S1\',np.uint8]})\n dtype([(\'gender\', \'S1\'), (\'age\', \'u1\')])\n\n Offsets in bytes, here 0 and 25:\n\n >>> np.dtype({\'surname\':(\'S25\',0),\'age\':(np.uint8,25)})\n dtype([(\'surname\', \'S25\'), (\'age\', \'u1\')])\n\n ') add_newdoc('numpy._core.multiarray', 'dtype', ('alignment', "\n The required alignment (bytes) of this data-type according to the compiler.\n\n More information is available in the C-API section of the manual.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> x = np.dtype('i4')\n >>> x.alignment\n 4\n\n >>> x = np.dtype(float)\n >>> x.alignment\n 8\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('byteorder', "\n A character indicating the byte-order of this data-type object.\n\n One of:\n\n === ==============\n '=' native\n '<' little-endian\n '>' big-endian\n '|' not applicable\n === ==============\n\n All built-in data-type objects have byteorder either '=' or '|'.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> dt = np.dtype('i2')\n >>> dt.byteorder\n '='\n >>> # endian is not relevant for 8 bit numbers\n >>> np.dtype('i1').byteorder\n '|'\n >>> # or ASCII strings\n >>> np.dtype('S2').byteorder\n '|'\n >>> # Even if specific code is given, and it is native\n >>> # '=' is the byteorder\n >>> import sys\n >>> sys_is_le = sys.byteorder == 'little'\n >>> native_code = '<' if sys_is_le else '>'\n >>> swapped_code = '>' if sys_is_le else '<'\n >>> dt = np.dtype(native_code + 'i2')\n >>> dt.byteorder\n '='\n >>> # Swapped code shows up as itself\n >>> dt = np.dtype(swapped_code + 'i2')\n >>> dt.byteorder == swapped_code\n True\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('char', "A unique character code for each of the 21 different built-in types.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> x = np.dtype(float)\n >>> x.char\n 'd'\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('descr', "\n `__array_interface__` description of the data-type.\n\n The format is that required by the 'descr' key in the\n `__array_interface__` attribute.\n\n Warning: This attribute exists specifically for `__array_interface__`,\n and passing it directly to `numpy.dtype` will not accurately reconstruct\n some dtypes (e.g., scalar and subarray dtypes).\n\n Examples\n --------\n\n >>> import numpy as np\n >>> x = np.dtype(float)\n >>> x.descr\n [('', '>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])\n >>> dt.descr\n [('name', '>> import numpy as np\n >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])\n >>> print(dt.fields)\n {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('flags', "\n Bit-flags describing how this data type is to be interpreted.\n\n Bit-masks are in ``numpy._core.multiarray`` as the constants\n `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,\n `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation\n of these flags is in C-API documentation; they are largely useful\n for user-defined data-types.\n\n The following example demonstrates that operations on this particular\n dtype requires Python C-API.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])\n >>> x.flags\n 16\n >>> np._core.multiarray.NEEDS_PYAPI\n 16\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('hasobject', "\n Boolean indicating whether this dtype contains any reference-counted\n objects in any fields or sub-dtypes.\n\n Recall that what is actually in the ndarray memory representing\n the Python object is the memory address of that object (a pointer).\n Special handling may be required, and this attribute is useful for\n distinguishing data types that may contain arbitrary Python objects\n and data-types that won't.\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('isbuiltin', "\n Integer indicating how this dtype relates to the built-in dtypes.\n\n Read-only.\n\n = ========================================================================\n 0 if this is a structured array type, with fields\n 1 if this is a dtype compiled into numpy (such as ints, floats etc)\n 2 if the dtype is for a user-defined numpy type\n A user-defined type uses the numpy C-API machinery to extend\n numpy to handle a new array type. See\n :ref:`user.user-defined-data-types` in the NumPy manual.\n = ========================================================================\n\n Examples\n --------\n\n >>> import numpy as np\n >>> dt = np.dtype('i2')\n >>> dt.isbuiltin\n 1\n >>> dt = np.dtype('f8')\n >>> dt.isbuiltin\n 1\n >>> dt = np.dtype([('field1', 'f8')])\n >>> dt.isbuiltin\n 0\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('isnative', '\n Boolean indicating whether the byte order of this dtype is native\n to the platform.\n\n ')) add_newdoc('numpy._core.multiarray', 'dtype', ('isalignedstruct', '\n Boolean indicating whether the dtype is a struct which maintains\n field alignment. This flag is sticky, so when combining multiple\n structs together, it is preserved and produces new dtypes which\n are also aligned.\n\n ')) add_newdoc('numpy._core.multiarray', 'dtype', ('itemsize', "\n The element size of this data-type object.\n\n For 18 of the 21 types this number is fixed by the data-type.\n For the flexible data-types, this number can be anything.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> arr = np.array([[1, 2], [3, 4]])\n >>> arr.dtype\n dtype('int64')\n >>> arr.itemsize\n 8\n\n >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])\n >>> dt.itemsize\n 80\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('kind', "\n A character code (one of 'biufcmMOSUV') identifying the general kind of data.\n\n = ======================\n b boolean\n i signed integer\n u unsigned integer\n f floating-point\n c complex floating-point\n m timedelta\n M datetime\n O object\n S (byte-)string\n U Unicode\n V void\n = ======================\n\n Examples\n --------\n\n >>> import numpy as np\n >>> dt = np.dtype('i4')\n >>> dt.kind\n 'i'\n >>> dt = np.dtype('f8')\n >>> dt.kind\n 'f'\n >>> dt = np.dtype([('field1', 'f8')])\n >>> dt.kind\n 'V'\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('metadata', '\n Either ``None`` or a readonly dictionary of metadata (mappingproxy).\n\n The metadata field can be set using any dictionary at data-type\n creation. NumPy currently has no uniform approach to propagating\n metadata; although some array operations preserve it, there is no\n guarantee that others will.\n\n .. warning::\n\n Although used in certain projects, this feature was long undocumented\n and is not well supported. Some aspects of metadata propagation\n are expected to change in the future.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> dt = np.dtype(float, metadata={"key": "value"})\n >>> dt.metadata["key"]\n \'value\'\n >>> arr = np.array([1, 2, 3], dtype=dt)\n >>> arr.dtype.metadata\n mappingproxy({\'key\': \'value\'})\n\n Adding arrays with identical datatypes currently preserves the metadata:\n\n >>> (arr + arr).dtype.metadata\n mappingproxy({\'key\': \'value\'})\n\n But if the arrays have different dtype metadata, the metadata may be\n dropped:\n\n >>> dt2 = np.dtype(float, metadata={"key2": "value2"})\n >>> arr2 = np.array([3, 2, 1], dtype=dt2)\n >>> (arr + arr2).dtype.metadata is None\n True # The metadata field is cleared so None is returned\n ')) add_newdoc('numpy._core.multiarray', 'dtype', ('name', "\n A bit-width name for this data-type.\n\n Un-sized flexible data-type objects do not have this attribute.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> x = np.dtype(float)\n >>> x.name\n 'float64'\n >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])\n >>> x.name\n 'void640'\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('names', "\n Ordered list of field names, or ``None`` if there are no fields.\n\n The names are ordered according to increasing byte offset. This can be\n used, for example, to walk through all of the named fields in offset order.\n\n Examples\n --------\n >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])\n >>> dt.names\n ('name', 'grades')\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('num', '\n A unique number for each of the 21 different built-in types.\n\n These are roughly ordered from least-to-most precision.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> dt = np.dtype(str)\n >>> dt.num\n 19\n\n >>> dt = np.dtype(float)\n >>> dt.num\n 12\n\n ')) add_newdoc('numpy._core.multiarray', 'dtype', ('shape', "\n Shape tuple of the sub-array if this data type describes a sub-array,\n and ``()`` otherwise.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> dt = np.dtype(('i4', 4))\n >>> dt.shape\n (4,)\n\n >>> dt = np.dtype(('i4', (2, 3)))\n >>> dt.shape\n (2, 3)\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('ndim', "\n Number of dimensions of the sub-array if this data type describes a\n sub-array, and ``0`` otherwise.\n\n .. versionadded:: 1.13.0\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.dtype(float)\n >>> x.ndim\n 0\n\n >>> x = np.dtype((float, 8))\n >>> x.ndim\n 1\n\n >>> x = np.dtype(('i4', (3, 4)))\n >>> x.ndim\n 2\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('str', 'The array-protocol typestring of this data-type object.')) add_newdoc('numpy._core.multiarray', 'dtype', ('subdtype', "\n Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and\n None otherwise.\n\n The *shape* is the fixed shape of the sub-array described by this\n data type, and *item_dtype* the data type of the array.\n\n If a field whose dtype object has this attribute is retrieved,\n then the extra dimensions implied by *shape* are tacked on to\n the end of the retrieved array.\n\n See Also\n --------\n dtype.base\n\n Examples\n --------\n >>> import numpy as np\n >>> x = numpy.dtype('8f')\n >>> x.subdtype\n (dtype('float32'), (8,))\n\n >>> x = numpy.dtype('i2')\n >>> x.subdtype\n >>>\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('base', "\n Returns dtype for the base element of the subarrays,\n regardless of their dimension or shape.\n\n See Also\n --------\n dtype.subdtype\n\n Examples\n --------\n >>> import numpy as np\n >>> x = numpy.dtype('8f')\n >>> x.base\n dtype('float32')\n\n >>> x = numpy.dtype('i2')\n >>> x.base\n dtype('int16')\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('type', 'The type object used to instantiate a scalar of this data-type.')) add_newdoc('numpy._core.multiarray', 'dtype', ('newbyteorder', "\n newbyteorder(new_order='S', /)\n\n Return a new dtype with a different byte order.\n\n Changes are also made in all fields and sub-arrays of the data type.\n\n Parameters\n ----------\n new_order : string, optional\n Byte order to force; a value from the byte order specifications\n below. The default value ('S') results in swapping the current\n byte order. `new_order` codes can be any of:\n\n * 'S' - swap dtype from current to opposite endian\n * {'<', 'little'} - little endian\n * {'>', 'big'} - big endian\n * {'=', 'native'} - native order\n * {'|', 'I'} - ignore (no change to byte order)\n\n Returns\n -------\n new_dtype : dtype\n New dtype object with the given change to the byte order.\n\n Notes\n -----\n Changes are also made in all fields and sub-arrays of the data type.\n\n Examples\n --------\n >>> import sys\n >>> sys_is_le = sys.byteorder == 'little'\n >>> native_code = '<' if sys_is_le else '>'\n >>> swapped_code = '>' if sys_is_le else '<'\n >>> import numpy as np\n >>> native_dt = np.dtype(native_code+'i2')\n >>> swapped_dt = np.dtype(swapped_code+'i2')\n >>> native_dt.newbyteorder('S') == swapped_dt\n True\n >>> native_dt.newbyteorder() == swapped_dt\n True\n >>> native_dt == swapped_dt.newbyteorder('S')\n True\n >>> native_dt == swapped_dt.newbyteorder('=')\n True\n >>> native_dt == swapped_dt.newbyteorder('N')\n True\n >>> native_dt == native_dt.newbyteorder('|')\n True\n >>> np.dtype('>> np.dtype('>> np.dtype('>i2') == native_dt.newbyteorder('>')\n True\n >>> np.dtype('>i2') == native_dt.newbyteorder('B')\n True\n\n ")) add_newdoc('numpy._core.multiarray', 'dtype', ('__class_getitem__', '\n __class_getitem__(item, /)\n\n Return a parametrized wrapper around the `~numpy.dtype` type.\n\n .. versionadded:: 1.22\n\n Returns\n -------\n alias : types.GenericAlias\n A parametrized `~numpy.dtype` type.\n\n Examples\n --------\n >>> import numpy as np\n\n >>> np.dtype[np.int64]\n numpy.dtype[numpy.int64]\n\n See Also\n --------\n :pep:`585` : Type hinting generics in standard collections.\n\n ')) add_newdoc('numpy._core.multiarray', 'dtype', ('__ge__', '\n __ge__(value, /)\n\n Return ``self >= value``.\n\n Equivalent to ``np.can_cast(value, self, casting="safe")``.\n\n See Also\n --------\n can_cast : Returns True if cast between data types can occur according to\n the casting rule.\n\n ')) add_newdoc('numpy._core.multiarray', 'dtype', ('__le__', '\n __le__(value, /)\n\n Return ``self <= value``.\n\n Equivalent to ``np.can_cast(self, value, casting="safe")``.\n\n See Also\n --------\n can_cast : Returns True if cast between data types can occur according to\n the casting rule.\n\n ')) add_newdoc('numpy._core.multiarray', 'dtype', ('__gt__', '\n __ge__(value, /)\n\n Return ``self > value``.\n\n Equivalent to\n ``self != value and np.can_cast(value, self, casting="safe")``.\n\n See Also\n --------\n can_cast : Returns True if cast between data types can occur according to\n the casting rule.\n\n ')) add_newdoc('numpy._core.multiarray', 'dtype', ('__lt__', '\n __lt__(value, /)\n\n Return ``self < value``.\n\n Equivalent to\n ``self != value and np.can_cast(self, value, casting="safe")``.\n\n See Also\n --------\n can_cast : Returns True if cast between data types can occur according to\n the casting rule.\n\n ')) add_newdoc('numpy._core.multiarray', 'busdaycalendar', '\n busdaycalendar(weekmask=\'1111100\', holidays=None)\n\n A business day calendar object that efficiently stores information\n defining valid days for the busday family of functions.\n\n The default valid days are Monday through Friday ("business days").\n A busdaycalendar object can be specified with any set of weekly\n valid days, plus an optional "holiday" dates that always will be invalid.\n\n Once a busdaycalendar object is created, the weekmask and holidays\n cannot be modified.\n\n .. versionadded:: 1.7.0\n\n Parameters\n ----------\n weekmask : str or array_like of bool, optional\n A seven-element array indicating which of Monday through Sunday are\n valid days. May be specified as a length-seven list or array, like\n [1,1,1,1,1,0,0]; a length-seven string, like \'1111100\'; or a string\n like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for\n weekdays, optionally separated by white space. Valid abbreviations\n are: Mon Tue Wed Thu Fri Sat Sun\n holidays : array_like of datetime64[D], optional\n An array of dates to consider as invalid dates, no matter which\n weekday they fall upon. Holiday dates may be specified in any\n order, and NaT (not-a-time) dates are ignored. This list is\n saved in a normalized form that is suited for fast calculations\n of valid days.\n\n Returns\n -------\n out : busdaycalendar\n A business day calendar object containing the specified\n weekmask and holidays values.\n\n See Also\n --------\n is_busday : Returns a boolean array indicating valid days.\n busday_offset : Applies an offset counted in valid days.\n busday_count : Counts how many valid days are in a half-open date range.\n\n Attributes\n ----------\n weekmask : (copy) seven-element array of bool\n holidays : (copy) sorted array of datetime64[D]\n\n Notes\n -----\n Once a busdaycalendar object is created, you cannot modify the\n weekmask or holidays. The attributes return copies of internal data.\n\n Examples\n --------\n >>> import numpy as np\n >>> # Some important days in July\n ... bdd = np.busdaycalendar(\n ... holidays=[\'2011-07-01\', \'2011-07-04\', \'2011-07-17\'])\n >>> # Default is Monday to Friday weekdays\n ... bdd.weekmask\n array([ True, True, True, True, True, False, False])\n >>> # Any holidays already on the weekend are removed\n ... bdd.holidays\n array([\'2011-07-01\', \'2011-07-04\'], dtype=\'datetime64[D]\')\n ') add_newdoc('numpy._core.multiarray', 'busdaycalendar', ('weekmask', 'A copy of the seven-element boolean mask indicating valid days.')) add_newdoc('numpy._core.multiarray', 'busdaycalendar', ('holidays', 'A copy of the holiday array indicating additional invalid days.')) add_newdoc('numpy._core.multiarray', 'normalize_axis_index', "\n normalize_axis_index(axis, ndim, msg_prefix=None)\n\n Normalizes an axis index, `axis`, such that is a valid positive index into\n the shape of array with `ndim` dimensions. Raises an AxisError with an\n appropriate message if this is not possible.\n\n Used internally by all axis-checking logic.\n\n .. versionadded:: 1.13.0\n\n Parameters\n ----------\n axis : int\n The un-normalized index of the axis. Can be negative\n ndim : int\n The number of dimensions of the array that `axis` should be normalized\n against\n msg_prefix : str\n A prefix to put before the message, typically the name of the argument\n\n Returns\n -------\n normalized_axis : int\n The normalized axis index, such that `0 <= normalized_axis < ndim`\n\n Raises\n ------\n AxisError\n If the axis index is invalid, when `-ndim <= axis < ndim` is false.\n\n Examples\n --------\n >>> import numpy as np\n >>> from numpy.lib.array_utils import normalize_axis_index\n >>> normalize_axis_index(0, ndim=3)\n 0\n >>> normalize_axis_index(1, ndim=3)\n 1\n >>> normalize_axis_index(-1, ndim=3)\n 2\n\n >>> normalize_axis_index(3, ndim=3)\n Traceback (most recent call last):\n ...\n numpy.exceptions.AxisError: axis 3 is out of bounds for array ...\n >>> normalize_axis_index(-4, ndim=3, msg_prefix='axes_arg')\n Traceback (most recent call last):\n ...\n numpy.exceptions.AxisError: axes_arg: axis -4 is out of bounds ...\n ") add_newdoc('numpy._core.multiarray', 'datetime_data', "\n datetime_data(dtype, /)\n\n Get information about the step size of a date or time type.\n\n The returned tuple can be passed as the second argument of `numpy.datetime64` and\n `numpy.timedelta64`.\n\n Parameters\n ----------\n dtype : dtype\n The dtype object, which must be a `datetime64` or `timedelta64` type.\n\n Returns\n -------\n unit : str\n The :ref:`datetime unit ` on which this dtype\n is based.\n count : int\n The number of base units in a step.\n\n Examples\n --------\n >>> import numpy as np\n >>> dt_25s = np.dtype('timedelta64[25s]')\n >>> np.datetime_data(dt_25s)\n ('s', 25)\n >>> np.array(10, dt_25s).astype('timedelta64[s]')\n array(250, dtype='timedelta64[s]')\n\n The result can be used to construct a datetime that uses the same units\n as a timedelta\n\n >>> np.datetime64('2010', np.datetime_data(dt_25s))\n np.datetime64('2010-01-01T00:00:00','25s')\n ") add_newdoc('numpy._core.numerictypes', 'generic', '\n Base class for numpy scalar types.\n\n Class from which most (all?) numpy scalar types are derived. For\n consistency, exposes the same API as `ndarray`, despite many\n consequent attributes being either "get-only," or completely irrelevant.\n This is the class from which it is strongly suggested users should derive\n custom scalar types.\n\n ') def refer_to_array_attribute(attr, method=True): docstring = '\n Scalar {} identical to the corresponding array attribute.\n\n Please see `ndarray.{}`.\n ' return (attr, docstring.format('method' if method else 'attribute', attr)) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('T', method=False)) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('base', method=False)) add_newdoc('numpy._core.numerictypes', 'generic', ('data', 'Pointer to start of data.')) add_newdoc('numpy._core.numerictypes', 'generic', ('dtype', 'Get array data-descriptor.')) add_newdoc('numpy._core.numerictypes', 'generic', ('flags', 'The integer value of flags.')) add_newdoc('numpy._core.numerictypes', 'generic', ('flat', 'A 1-D view of the scalar.')) add_newdoc('numpy._core.numerictypes', 'generic', ('imag', 'The imaginary part of the scalar.')) add_newdoc('numpy._core.numerictypes', 'generic', ('itemsize', 'The length of one element in bytes.')) add_newdoc('numpy._core.numerictypes', 'generic', ('ndim', 'The number of array dimensions.')) add_newdoc('numpy._core.numerictypes', 'generic', ('real', 'The real part of the scalar.')) add_newdoc('numpy._core.numerictypes', 'generic', ('shape', 'Tuple of array dimensions.')) add_newdoc('numpy._core.numerictypes', 'generic', ('size', 'The number of elements in the gentype.')) add_newdoc('numpy._core.numerictypes', 'generic', ('strides', 'Tuple of bytes steps in each dimension.')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('all')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('any')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('argmax')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('argmin')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('argsort')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('astype')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('byteswap')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('choose')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('clip')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('compress')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('conjugate')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('copy')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('cumprod')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('cumsum')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('diagonal')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('dump')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('dumps')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('fill')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('flatten')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('getfield')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('item')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('max')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('mean')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('min')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('nonzero')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('prod')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('put')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('ravel')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('repeat')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('reshape')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('resize')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('round')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('searchsorted')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('setfield')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('setflags')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('sort')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('squeeze')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('std')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('sum')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('swapaxes')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('take')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('tofile')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('tolist')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('tostring')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('trace')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('transpose')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('var')) add_newdoc('numpy._core.numerictypes', 'generic', refer_to_array_attribute('view')) add_newdoc('numpy._core.numerictypes', 'number', ('__class_getitem__', '\n __class_getitem__(item, /)\n\n Return a parametrized wrapper around the `~numpy.number` type.\n\n .. versionadded:: 1.22\n\n Returns\n -------\n alias : types.GenericAlias\n A parametrized `~numpy.number` type.\n\n Examples\n --------\n >>> from typing import Any\n >>> import numpy as np\n\n >>> np.signedinteger[Any]\n numpy.signedinteger[typing.Any]\n\n See Also\n --------\n :pep:`585` : Type hinting generics in standard collections.\n\n ')) add_newdoc('numpy._core.numerictypes', 'number', '\n Abstract base class of all numeric scalar types.\n\n ') add_newdoc('numpy._core.numerictypes', 'integer', '\n Abstract base class of all integer scalar types.\n\n ') add_newdoc('numpy._core.numerictypes', 'signedinteger', '\n Abstract base class of all signed integer scalar types.\n\n ') add_newdoc('numpy._core.numerictypes', 'unsignedinteger', '\n Abstract base class of all unsigned integer scalar types.\n\n ') add_newdoc('numpy._core.numerictypes', 'inexact', '\n Abstract base class of all numeric scalar types with a (potentially)\n inexact representation of the values in its range, such as\n floating-point numbers.\n\n ') add_newdoc('numpy._core.numerictypes', 'floating', '\n Abstract base class of all floating-point scalar types.\n\n ') add_newdoc('numpy._core.numerictypes', 'complexfloating', '\n Abstract base class of all complex number scalar types that are made up of\n floating-point numbers.\n\n ') add_newdoc('numpy._core.numerictypes', 'flexible', '\n Abstract base class of all scalar types without predefined length.\n The actual size of these types depends on the specific `numpy.dtype`\n instantiation.\n\n ') add_newdoc('numpy._core.numerictypes', 'character', '\n Abstract base class of all character string scalar types.\n\n ') add_newdoc('numpy._core.multiarray', 'StringDType', '\n StringDType(*, na_object=np._NoValue, coerce=True)\n\n Create a StringDType instance.\n\n StringDType can be used to store UTF-8 encoded variable-width strings in\n a NumPy array.\n\n Parameters\n ----------\n na_object : object, optional\n Object used to represent missing data. If unset, the array will not\n use a missing data sentinel.\n coerce : bool, optional\n Whether or not items in an array-like passed to an array creation\n function that are neither a str or str subtype should be coerced to\n str. Defaults to True. If set to False, creating a StringDType\n array from an array-like containing entries that are not already\n strings will raise an error.\n\n Examples\n --------\n\n >>> import numpy as np\n\n >>> from numpy.dtypes import StringDType\n >>> np.array(["hello", "world"], dtype=StringDType())\n array(["hello", "world"], dtype=StringDType())\n\n >>> arr = np.array(["hello", None, "world"],\n ... dtype=StringDType(na_object=None))\n >>> arr\n array(["hello", None, "world"], dtype=StringDType(na_object=None))\n >>> arr[1] is None\n True\n\n >>> arr = np.array(["hello", np.nan, "world"],\n ... dtype=StringDType(na_object=np.nan))\n >>> np.isnan(arr)\n array([False, True, False])\n\n >>> np.array([1.2, object(), "hello world"],\n ... dtype=StringDType(coerce=True))\n ValueError: StringDType only allows string data when string coercion\n is disabled.\n\n >>> np.array(["hello", "world"], dtype=StringDType(coerce=True))\n array(["hello", "world"], dtype=StringDType(coerce=True))\n ') # File: numpy-main/numpy/_core/_add_newdocs_scalars.py """""" import sys import os from numpy._core import dtype from numpy._core import numerictypes as _numerictypes from numpy._core.function_base import add_newdoc def numeric_type_aliases(aliases): def type_aliases_gen(): for (alias, doc) in aliases: try: alias_type = getattr(_numerictypes, alias) except AttributeError: pass else: yield (alias_type, alias, doc) return list(type_aliases_gen()) possible_aliases = numeric_type_aliases([('int8', '8-bit signed integer (``-128`` to ``127``)'), ('int16', '16-bit signed integer (``-32_768`` to ``32_767``)'), ('int32', '32-bit signed integer (``-2_147_483_648`` to ``2_147_483_647``)'), ('int64', '64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``)'), ('intp', 'Signed integer large enough to fit pointer, compatible with C ``intptr_t``'), ('uint8', '8-bit unsigned integer (``0`` to ``255``)'), ('uint16', '16-bit unsigned integer (``0`` to ``65_535``)'), ('uint32', '32-bit unsigned integer (``0`` to ``4_294_967_295``)'), ('uint64', '64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``)'), ('uintp', 'Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``'), ('float16', '16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa'), ('float32', '32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa'), ('float64', '64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa'), ('float96', '96-bit extended-precision floating-point number type'), ('float128', '128-bit extended-precision floating-point number type'), ('complex64', 'Complex number type composed of 2 32-bit-precision floating-point numbers'), ('complex128', 'Complex number type composed of 2 64-bit-precision floating-point numbers'), ('complex192', 'Complex number type composed of 2 96-bit extended-precision floating-point numbers'), ('complex256', 'Complex number type composed of 2 128-bit extended-precision floating-point numbers')]) def _get_platform_and_machine(): try: (system, _, _, _, machine) = os.uname() except AttributeError: system = sys.platform if system == 'win32': machine = os.environ.get('PROCESSOR_ARCHITEW6432', '') or os.environ.get('PROCESSOR_ARCHITECTURE', '') else: machine = 'unknown' return (system, machine) (_system, _machine) = _get_platform_and_machine() _doc_alias_string = f':Alias on this platform ({_system} {_machine}):' def add_newdoc_for_scalar_type(obj, fixed_aliases, doc): o = getattr(_numerictypes, obj) character_code = dtype(o).char canonical_name_doc = '' if obj == o.__name__ else f':Canonical name: `numpy.{obj}`\n ' if fixed_aliases: alias_doc = ''.join((f':Alias: `numpy.{alias}`\n ' for alias in fixed_aliases)) else: alias_doc = '' alias_doc += ''.join((f'{_doc_alias_string} `numpy.{alias}`: {doc}.\n ' for (alias_type, alias, doc) in possible_aliases if alias_type is o)) docstring = f"\n {doc.strip()}\n\n :Character code: ``'{character_code}'``\n {canonical_name_doc}{alias_doc}\n " add_newdoc('numpy._core.numerictypes', obj, docstring) _bool_docstring = "\n Boolean type (True or False), stored as a byte.\n\n .. warning::\n\n The :class:`bool` type is not a subclass of the :class:`int_` type\n (the :class:`bool` is not even a number type). This is different\n than Python's default implementation of :class:`bool` as a\n sub-class of :class:`int`.\n " add_newdoc_for_scalar_type('bool', [], _bool_docstring) add_newdoc_for_scalar_type('bool_', [], _bool_docstring) add_newdoc_for_scalar_type('byte', [], '\n Signed integer type, compatible with C ``char``.\n ') add_newdoc_for_scalar_type('short', [], '\n Signed integer type, compatible with C ``short``.\n ') add_newdoc_for_scalar_type('intc', [], '\n Signed integer type, compatible with C ``int``.\n ') add_newdoc_for_scalar_type('int_', [], '\n Default signed integer type, 64bit on 64bit systems and 32bit on 32bit\n systems.\n ') add_newdoc_for_scalar_type('longlong', [], '\n Signed integer type, compatible with C ``long long``.\n ') add_newdoc_for_scalar_type('ubyte', [], '\n Unsigned integer type, compatible with C ``unsigned char``.\n ') add_newdoc_for_scalar_type('ushort', [], '\n Unsigned integer type, compatible with C ``unsigned short``.\n ') add_newdoc_for_scalar_type('uintc', [], '\n Unsigned integer type, compatible with C ``unsigned int``.\n ') add_newdoc_for_scalar_type('uint', [], '\n Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit\n systems.\n ') add_newdoc_for_scalar_type('ulonglong', [], '\n Signed integer type, compatible with C ``unsigned long long``.\n ') add_newdoc_for_scalar_type('half', [], '\n Half-precision floating-point number type.\n ') add_newdoc_for_scalar_type('single', [], '\n Single-precision floating-point number type, compatible with C ``float``.\n ') add_newdoc_for_scalar_type('double', [], '\n Double-precision floating-point number type, compatible with Python\n :class:`float` and C ``double``.\n ') add_newdoc_for_scalar_type('longdouble', [], '\n Extended-precision floating-point number type, compatible with C\n ``long double`` but not necessarily with IEEE 754 quadruple-precision.\n ') add_newdoc_for_scalar_type('csingle', [], '\n Complex number type composed of two single-precision floating-point\n numbers.\n ') add_newdoc_for_scalar_type('cdouble', [], '\n Complex number type composed of two double-precision floating-point\n numbers, compatible with Python :class:`complex`.\n ') add_newdoc_for_scalar_type('clongdouble', [], '\n Complex number type composed of two extended-precision floating-point\n numbers.\n ') add_newdoc_for_scalar_type('object_', [], '\n Any Python object.\n ') add_newdoc_for_scalar_type('str_', [], '\n A unicode string.\n\n This type strips trailing null codepoints.\n\n >>> s = np.str_("abc\\x00")\n >>> s\n \'abc\'\n\n Unlike the builtin :class:`str`, this supports the\n :ref:`python:bufferobjects`, exposing its contents as UCS4:\n\n >>> m = memoryview(np.str_("abc"))\n >>> m.format\n \'3w\'\n >>> m.tobytes()\n b\'a\\x00\\x00\\x00b\\x00\\x00\\x00c\\x00\\x00\\x00\'\n ') add_newdoc_for_scalar_type('bytes_', [], '\n A byte string.\n\n When used in arrays, this type strips trailing null bytes.\n ') add_newdoc_for_scalar_type('void', [], '\n np.void(length_or_data, /, dtype=None)\n\n Create a new structured or unstructured void scalar.\n\n Parameters\n ----------\n length_or_data : int, array-like, bytes-like, object\n One of multiple meanings (see notes). The length or\n bytes data of an unstructured void. Or alternatively,\n the data to be stored in the new scalar when `dtype`\n is provided.\n This can be an array-like, in which case an array may\n be returned.\n dtype : dtype, optional\n If provided the dtype of the new scalar. This dtype must\n be "void" dtype (i.e. a structured or unstructured void,\n see also :ref:`defining-structured-types`).\n\n .. versionadded:: 1.24\n\n Notes\n -----\n For historical reasons and because void scalars can represent both\n arbitrary byte data and structured dtypes, the void constructor\n has three calling conventions:\n\n 1. ``np.void(5)`` creates a ``dtype="V5"`` scalar filled with five\n ``\\0`` bytes. The 5 can be a Python or NumPy integer.\n 2. ``np.void(b"bytes-like")`` creates a void scalar from the byte string.\n The dtype itemsize will match the byte string length, here ``"V10"``.\n 3. When a ``dtype=`` is passed the call is roughly the same as an\n array creation. However, a void scalar rather than array is returned.\n\n Please see the examples which show all three different conventions.\n\n Examples\n --------\n >>> np.void(5)\n np.void(b\'\\x00\\x00\\x00\\x00\\x00\')\n >>> np.void(b\'abcd\')\n np.void(b\'\\x61\\x62\\x63\\x64\')\n >>> np.void((3.2, b\'eggs\'), dtype="d,S5")\n np.void((3.2, b\'eggs\'), dtype=[(\'f0\', \'>> np.void(3, dtype=[(\'x\', np.int8), (\'y\', np.int8)])\n np.void((3, 3), dtype=[(\'x\', \'i1\'), (\'y\', \'i1\')])\n\n ') add_newdoc_for_scalar_type('datetime64', [], "\n If created from a 64-bit integer, it represents an offset from\n ``1970-01-01T00:00:00``.\n If created from string, the string can be in ISO 8601 date\n or datetime format.\n\n When parsing a string to create a datetime object, if the string contains\n a trailing timezone (A 'Z' or a timezone offset), the timezone will be\n dropped and a User Warning is given.\n\n Datetime64 objects should be considered to be UTC and therefore have an\n offset of +0000.\n\n >>> np.datetime64(10, 'Y')\n np.datetime64('1980')\n >>> np.datetime64('1980', 'Y')\n np.datetime64('1980')\n >>> np.datetime64(10, 'D')\n np.datetime64('1970-01-11')\n\n See :ref:`arrays.datetime` for more information.\n ") add_newdoc_for_scalar_type('timedelta64', [], '\n A timedelta stored as a 64-bit integer.\n\n See :ref:`arrays.datetime` for more information.\n ') add_newdoc('numpy._core.numerictypes', 'integer', ('is_integer', '\n integer.is_integer() -> bool\n\n Return ``True`` if the number is finite with integral value.\n\n .. versionadded:: 1.22\n\n Examples\n --------\n >>> import numpy as np\n >>> np.int64(-2).is_integer()\n True\n >>> np.uint32(5).is_integer()\n True\n ')) for float_name in ('half', 'single', 'double', 'longdouble'): add_newdoc('numpy._core.numerictypes', float_name, ('as_integer_ratio', '\n {ftype}.as_integer_ratio() -> (int, int)\n\n Return a pair of integers, whose ratio is exactly equal to the original\n floating point number, and with a positive denominator.\n Raise `OverflowError` on infinities and a `ValueError` on NaNs.\n\n >>> np.{ftype}(10.0).as_integer_ratio()\n (10, 1)\n >>> np.{ftype}(0.0).as_integer_ratio()\n (0, 1)\n >>> np.{ftype}(-.25).as_integer_ratio()\n (-1, 4)\n '.format(ftype=float_name))) add_newdoc('numpy._core.numerictypes', float_name, ('is_integer', f'\n {float_name}.is_integer() -> bool\n\n Return ``True`` if the floating point number is finite with integral\n value, and ``False`` otherwise.\n\n .. versionadded:: 1.22\n\n Examples\n --------\n >>> np.{float_name}(-2.0).is_integer()\n True\n >>> np.{float_name}(3.2).is_integer()\n False\n ')) for int_name in ('int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'int64', 'uint64', 'int64', 'uint64'): add_newdoc('numpy._core.numerictypes', int_name, ('bit_count', f'\n {int_name}.bit_count() -> int\n\n Computes the number of 1-bits in the absolute value of the input.\n Analogous to the builtin `int.bit_count` or ``popcount`` in C++.\n\n Examples\n --------\n >>> np.{int_name}(127).bit_count()\n 7' + (f'\n >>> np.{int_name}(-127).bit_count()\n 7\n ' if dtype(int_name).char.islower() else ''))) # File: numpy-main/numpy/_core/_asarray.py """""" from .overrides import array_function_dispatch, set_array_function_like_doc, set_module from .multiarray import array, asanyarray __all__ = ['require'] POSSIBLE_FLAGS = {'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C', 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F', 'A': 'A', 'ALIGNED': 'A', 'W': 'W', 'WRITEABLE': 'W', 'O': 'O', 'OWNDATA': 'O', 'E': 'E', 'ENSUREARRAY': 'E'} @set_array_function_like_doc @set_module('numpy') def require(a, dtype=None, requirements=None, *, like=None): if like is not None: return _require_with_like(like, a, dtype=dtype, requirements=requirements) if not requirements: return asanyarray(a, dtype=dtype) requirements = {POSSIBLE_FLAGS[x.upper()] for x in requirements} if 'E' in requirements: requirements.remove('E') subok = False else: subok = True order = 'A' if requirements >= {'C', 'F'}: raise ValueError('Cannot specify both "C" and "F" order') elif 'F' in requirements: order = 'F' requirements.remove('F') elif 'C' in requirements: order = 'C' requirements.remove('C') arr = array(a, dtype=dtype, order=order, copy=None, subok=subok) for prop in requirements: if not arr.flags[prop]: return arr.copy(order) return arr _require_with_like = array_function_dispatch()(require) # File: numpy-main/numpy/_core/_dtype.py """""" import numpy as np _kind_to_stem = {'u': 'uint', 'i': 'int', 'c': 'complex', 'f': 'float', 'b': 'bool', 'V': 'void', 'O': 'object', 'M': 'datetime', 'm': 'timedelta', 'S': 'bytes', 'U': 'str'} def _kind_name(dtype): try: return _kind_to_stem[dtype.kind] except KeyError as e: raise RuntimeError('internal dtype error, unknown kind {!r}'.format(dtype.kind)) from None def __str__(dtype): if dtype.fields is not None: return _struct_str(dtype, include_align=True) elif dtype.subdtype: return _subarray_str(dtype) elif issubclass(dtype.type, np.flexible) or not dtype.isnative: return dtype.str else: return dtype.name def __repr__(dtype): arg_str = _construction_repr(dtype, include_align=False) if dtype.isalignedstruct: arg_str = arg_str + ', align=True' return 'dtype({})'.format(arg_str) def _unpack_field(dtype, offset, title=None): return (dtype, offset, title) def _isunsized(dtype): return dtype.itemsize == 0 def _construction_repr(dtype, include_align=False, short=False): if dtype.fields is not None: return _struct_str(dtype, include_align=include_align) elif dtype.subdtype: return _subarray_str(dtype) else: return _scalar_str(dtype, short=short) def _scalar_str(dtype, short): byteorder = _byte_order_str(dtype) if dtype.type == np.bool: if short: return "'?'" else: return "'bool'" elif dtype.type == np.object_: return "'O'" elif dtype.type == np.bytes_: if _isunsized(dtype): return "'S'" else: return "'S%d'" % dtype.itemsize elif dtype.type == np.str_: if _isunsized(dtype): return "'%sU'" % byteorder else: return "'%sU%d'" % (byteorder, dtype.itemsize / 4) elif dtype.type == str: return "'T'" elif not type(dtype)._legacy: return f"'{byteorder}{type(dtype).__name__}{dtype.itemsize * 8}'" elif issubclass(dtype.type, np.void): if _isunsized(dtype): return "'V'" else: return "'V%d'" % dtype.itemsize elif dtype.type == np.datetime64: return "'%sM8%s'" % (byteorder, _datetime_metadata_str(dtype)) elif dtype.type == np.timedelta64: return "'%sm8%s'" % (byteorder, _datetime_metadata_str(dtype)) elif np.issubdtype(dtype, np.number): if short or dtype.byteorder not in ('=', '|'): return "'%s%c%d'" % (byteorder, dtype.kind, dtype.itemsize) else: return "'%s%d'" % (_kind_name(dtype), 8 * dtype.itemsize) elif dtype.isbuiltin == 2: return dtype.type.__name__ else: raise RuntimeError('Internal error: NumPy dtype unrecognized type number') def _byte_order_str(dtype): swapped = np.dtype(int).newbyteorder('S') native = swapped.newbyteorder('S') byteorder = dtype.byteorder if byteorder == '=': return native.byteorder if byteorder == 'S': return swapped.byteorder elif byteorder == '|': return '' else: return byteorder def _datetime_metadata_str(dtype): (unit, count) = np.datetime_data(dtype) if unit == 'generic': return '' elif count == 1: return '[{}]'.format(unit) else: return '[{}{}]'.format(count, unit) def _struct_dict_str(dtype, includealignedflag): names = dtype.names fld_dtypes = [] offsets = [] titles = [] for name in names: (fld_dtype, offset, title) = _unpack_field(*dtype.fields[name]) fld_dtypes.append(fld_dtype) offsets.append(offset) titles.append(title) if np._core.arrayprint._get_legacy_print_mode() <= 121: colon = ':' fieldsep = ',' else: colon = ': ' fieldsep = ', ' ret = "{'names'%s[" % colon ret += fieldsep.join((repr(name) for name in names)) ret += "], 'formats'%s[" % colon ret += fieldsep.join((_construction_repr(fld_dtype, short=True) for fld_dtype in fld_dtypes)) ret += "], 'offsets'%s[" % colon ret += fieldsep.join(('%d' % offset for offset in offsets)) if any((title is not None for title in titles)): ret += "], 'titles'%s[" % colon ret += fieldsep.join((repr(title) for title in titles)) ret += "], 'itemsize'%s%d" % (colon, dtype.itemsize) if includealignedflag and dtype.isalignedstruct: ret += ", 'aligned'%sTrue}" % colon else: ret += '}' return ret def _aligned_offset(offset, alignment): return -(-offset // alignment) * alignment def _is_packed(dtype): align = dtype.isalignedstruct max_alignment = 1 total_offset = 0 for name in dtype.names: (fld_dtype, fld_offset, title) = _unpack_field(*dtype.fields[name]) if align: total_offset = _aligned_offset(total_offset, fld_dtype.alignment) max_alignment = max(max_alignment, fld_dtype.alignment) if fld_offset != total_offset: return False total_offset += fld_dtype.itemsize if align: total_offset = _aligned_offset(total_offset, max_alignment) return total_offset == dtype.itemsize def _struct_list_str(dtype): items = [] for name in dtype.names: (fld_dtype, fld_offset, title) = _unpack_field(*dtype.fields[name]) item = '(' if title is not None: item += '({!r}, {!r}), '.format(title, name) else: item += '{!r}, '.format(name) if fld_dtype.subdtype is not None: (base, shape) = fld_dtype.subdtype item += '{}, {}'.format(_construction_repr(base, short=True), shape) else: item += _construction_repr(fld_dtype, short=True) item += ')' items.append(item) return '[' + ', '.join(items) + ']' def _struct_str(dtype, include_align): if not (include_align and dtype.isalignedstruct) and _is_packed(dtype): sub = _struct_list_str(dtype) else: sub = _struct_dict_str(dtype, include_align) if dtype.type != np.void: return '({t.__module__}.{t.__name__}, {f})'.format(t=dtype.type, f=sub) else: return sub def _subarray_str(dtype): (base, shape) = dtype.subdtype return '({}, {})'.format(_construction_repr(base, short=True), shape) def _name_includes_bit_suffix(dtype): if dtype.type == np.object_: return False elif dtype.type == np.bool: return False elif dtype.type is None: return True elif np.issubdtype(dtype, np.flexible) and _isunsized(dtype): return False else: return True def _name_get(dtype): if dtype.isbuiltin == 2: return dtype.type.__name__ if not type(dtype)._legacy: name = type(dtype).__name__ elif issubclass(dtype.type, np.void): name = dtype.type.__name__ else: name = _kind_name(dtype) if _name_includes_bit_suffix(dtype): name += '{}'.format(dtype.itemsize * 8) if dtype.type in (np.datetime64, np.timedelta64): name += _datetime_metadata_str(dtype) return name # File: numpy-main/numpy/_core/_dtype_ctypes.py """""" import numpy as np def _from_ctypes_array(t): return np.dtype((dtype_from_ctypes_type(t._type_), (t._length_,))) def _from_ctypes_structure(t): for item in t._fields_: if len(item) > 2: raise TypeError('ctypes bitfields have no dtype equivalent') if hasattr(t, '_pack_'): import ctypes formats = [] offsets = [] names = [] current_offset = 0 for (fname, ftyp) in t._fields_: names.append(fname) formats.append(dtype_from_ctypes_type(ftyp)) effective_pack = min(t._pack_, ctypes.alignment(ftyp)) current_offset = (current_offset + effective_pack - 1) // effective_pack * effective_pack offsets.append(current_offset) current_offset += ctypes.sizeof(ftyp) return np.dtype(dict(formats=formats, offsets=offsets, names=names, itemsize=ctypes.sizeof(t))) else: fields = [] for (fname, ftyp) in t._fields_: fields.append((fname, dtype_from_ctypes_type(ftyp))) return np.dtype(fields, align=True) def _from_ctypes_scalar(t): if getattr(t, '__ctype_be__', None) is t: return np.dtype('>' + t._type_) elif getattr(t, '__ctype_le__', None) is t: return np.dtype('<' + t._type_) else: return np.dtype(t._type_) def _from_ctypes_union(t): import ctypes formats = [] offsets = [] names = [] for (fname, ftyp) in t._fields_: names.append(fname) formats.append(dtype_from_ctypes_type(ftyp)) offsets.append(0) return np.dtype(dict(formats=formats, offsets=offsets, names=names, itemsize=ctypes.sizeof(t))) def dtype_from_ctypes_type(t): import _ctypes if issubclass(t, _ctypes.Array): return _from_ctypes_array(t) elif issubclass(t, _ctypes._Pointer): raise TypeError('ctypes pointers have no dtype equivalent') elif issubclass(t, _ctypes.Structure): return _from_ctypes_structure(t) elif issubclass(t, _ctypes.Union): return _from_ctypes_union(t) elif isinstance(getattr(t, '_type_', None), str): return _from_ctypes_scalar(t) else: raise NotImplementedError('Unknown ctypes type {}'.format(t.__name__)) # File: numpy-main/numpy/_core/_exceptions.py """""" from .._utils import set_module def _unpack_tuple(tup): if len(tup) == 1: return tup[0] else: return tup def _display_as_base(cls): assert issubclass(cls, Exception) cls.__name__ = cls.__base__.__name__ return cls class UFuncTypeError(TypeError): def __init__(self, ufunc): self.ufunc = ufunc @_display_as_base class _UFuncNoLoopError(UFuncTypeError): def __init__(self, ufunc, dtypes): super().__init__(ufunc) self.dtypes = tuple(dtypes) def __str__(self): return 'ufunc {!r} did not contain a loop with signature matching types {!r} -> {!r}'.format(self.ufunc.__name__, _unpack_tuple(self.dtypes[:self.ufunc.nin]), _unpack_tuple(self.dtypes[self.ufunc.nin:])) @_display_as_base class _UFuncBinaryResolutionError(_UFuncNoLoopError): def __init__(self, ufunc, dtypes): super().__init__(ufunc, dtypes) assert len(self.dtypes) == 2 def __str__(self): return 'ufunc {!r} cannot use operands with types {!r} and {!r}'.format(self.ufunc.__name__, *self.dtypes) @_display_as_base class _UFuncCastingError(UFuncTypeError): def __init__(self, ufunc, casting, from_, to): super().__init__(ufunc) self.casting = casting self.from_ = from_ self.to = to @_display_as_base class _UFuncInputCastingError(_UFuncCastingError): def __init__(self, ufunc, casting, from_, to, i): super().__init__(ufunc, casting, from_, to) self.in_i = i def __str__(self): i_str = '{} '.format(self.in_i) if self.ufunc.nin != 1 else '' return 'Cannot cast ufunc {!r} input {}from {!r} to {!r} with casting rule {!r}'.format(self.ufunc.__name__, i_str, self.from_, self.to, self.casting) @_display_as_base class _UFuncOutputCastingError(_UFuncCastingError): def __init__(self, ufunc, casting, from_, to, i): super().__init__(ufunc, casting, from_, to) self.out_i = i def __str__(self): i_str = '{} '.format(self.out_i) if self.ufunc.nout != 1 else '' return 'Cannot cast ufunc {!r} output {}from {!r} to {!r} with casting rule {!r}'.format(self.ufunc.__name__, i_str, self.from_, self.to, self.casting) @_display_as_base class _ArrayMemoryError(MemoryError): def __init__(self, shape, dtype): self.shape = shape self.dtype = dtype @property def _total_size(self): num_bytes = self.dtype.itemsize for dim in self.shape: num_bytes *= dim return num_bytes @staticmethod def _size_to_string(num_bytes): LOG2_STEP = 10 STEP = 1024 units = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'] unit_i = max(num_bytes.bit_length() - 1, 1) // LOG2_STEP unit_val = 1 << unit_i * LOG2_STEP n_units = num_bytes / unit_val del unit_val if round(n_units) == STEP: unit_i += 1 n_units /= STEP if unit_i >= len(units): new_unit_i = len(units) - 1 n_units *= 1 << (unit_i - new_unit_i) * LOG2_STEP unit_i = new_unit_i unit_name = units[unit_i] if unit_i == 0: return '{:.0f} {}'.format(n_units, unit_name) elif round(n_units) < 1000: return '{:#.3g} {}'.format(n_units, unit_name) else: return '{:#.0f} {}'.format(n_units, unit_name) def __str__(self): size_str = self._size_to_string(self._total_size) return 'Unable to allocate {} for an array with shape {} and data type {}'.format(size_str, self.shape, self.dtype) # File: numpy-main/numpy/_core/_internal.py """""" import ast import math import re import sys import warnings from ..exceptions import DTypePromotionError from .multiarray import dtype, array, ndarray, promote_types, StringDType from numpy import _NoValue try: import ctypes except ImportError: ctypes = None IS_PYPY = sys.implementation.name == 'pypy' if sys.byteorder == 'little': _nbo = '<' else: _nbo = '>' def _makenames_list(adict, align): allfields = [] for (fname, obj) in adict.items(): n = len(obj) if not isinstance(obj, tuple) or n not in (2, 3): raise ValueError('entry not a 2- or 3- tuple') if n > 2 and obj[2] == fname: continue num = int(obj[1]) if num < 0: raise ValueError('invalid offset.') format = dtype(obj[0], align=align) if n > 2: title = obj[2] else: title = None allfields.append((fname, format, num, title)) allfields.sort(key=lambda x: x[2]) names = [x[0] for x in allfields] formats = [x[1] for x in allfields] offsets = [x[2] for x in allfields] titles = [x[3] for x in allfields] return (names, formats, offsets, titles) def _usefields(adict, align): try: names = adict[-1] except KeyError: names = None if names is None: (names, formats, offsets, titles) = _makenames_list(adict, align) else: formats = [] offsets = [] titles = [] for name in names: res = adict[name] formats.append(res[0]) offsets.append(res[1]) if len(res) > 2: titles.append(res[2]) else: titles.append(None) return dtype({'names': names, 'formats': formats, 'offsets': offsets, 'titles': titles}, align) def _array_descr(descriptor): fields = descriptor.fields if fields is None: subdtype = descriptor.subdtype if subdtype is None: if descriptor.metadata is None: return descriptor.str else: new = descriptor.metadata.copy() if new: return (descriptor.str, new) else: return descriptor.str else: return (_array_descr(subdtype[0]), subdtype[1]) names = descriptor.names ordered_fields = [fields[x] + (x,) for x in names] result = [] offset = 0 for field in ordered_fields: if field[1] > offset: num = field[1] - offset result.append(('', f'|V{num}')) offset += num elif field[1] < offset: raise ValueError('dtype.descr is not defined for types with overlapping or out-of-order fields') if len(field) > 3: name = (field[2], field[3]) else: name = field[2] if field[0].subdtype: tup = (name, _array_descr(field[0].subdtype[0]), field[0].subdtype[1]) else: tup = (name, _array_descr(field[0])) offset += field[0].itemsize result.append(tup) if descriptor.itemsize > offset: num = descriptor.itemsize - offset result.append(('', f'|V{num}')) return result format_re = re.compile('(?P[<>|=]?)(?P *[(]?[ ,0-9]*[)]? *)(?P[<>|=]?)(?P[A-Za-z0-9.?]*(?:\\[[a-zA-Z0-9,.]+\\])?)') sep_re = re.compile('\\s*,\\s*') space_re = re.compile('\\s+$') _convorder = {'=': _nbo} def _commastring(astr): startindex = 0 result = [] islist = False while startindex < len(astr): mo = format_re.match(astr, pos=startindex) try: (order1, repeats, order2, dtype) = mo.groups() except (TypeError, AttributeError): raise ValueError(f'format number {len(result) + 1} of "{astr}" is not recognized') from None startindex = mo.end() if startindex < len(astr): if space_re.match(astr, pos=startindex): startindex = len(astr) else: mo = sep_re.match(astr, pos=startindex) if not mo: raise ValueError('format number %d of "%s" is not recognized' % (len(result) + 1, astr)) startindex = mo.end() islist = True if order2 == '': order = order1 elif order1 == '': order = order2 else: order1 = _convorder.get(order1, order1) order2 = _convorder.get(order2, order2) if order1 != order2: raise ValueError('inconsistent byte-order specification %s and %s' % (order1, order2)) order = order1 if order in ('|', '=', _nbo): order = '' dtype = order + dtype if repeats == '': newitem = dtype else: if repeats[0] == '(' and repeats[-1] == ')' and (repeats[1:-1].strip() != '') and (',' not in repeats): warnings.warn('Passing in a parenthesized single number for repeats is deprecated; pass either a single number or indicate a tuple with a comma, like "(2,)".', DeprecationWarning, stacklevel=2) newitem = (dtype, ast.literal_eval(repeats)) result.append(newitem) return result if islist else result[0] class dummy_ctype: def __init__(self, cls): self._cls = cls def __mul__(self, other): return self def __call__(self, *other): return self._cls(other) def __eq__(self, other): return self._cls == other._cls def __ne__(self, other): return self._cls != other._cls def _getintp_ctype(): val = _getintp_ctype.cache if val is not None: return val if ctypes is None: import numpy as np val = dummy_ctype(np.intp) else: char = dtype('n').char if char == 'i': val = ctypes.c_int elif char == 'l': val = ctypes.c_long elif char == 'q': val = ctypes.c_longlong else: val = ctypes.c_long _getintp_ctype.cache = val return val _getintp_ctype.cache = None class _missing_ctypes: def cast(self, num, obj): return num.value class c_void_p: def __init__(self, ptr): self.value = ptr class _ctypes: def __init__(self, array, ptr=None): self._arr = array if ctypes: self._ctypes = ctypes self._data = self._ctypes.c_void_p(ptr) else: self._ctypes = _missing_ctypes() self._data = self._ctypes.c_void_p(ptr) self._data._objects = array if self._arr.ndim == 0: self._zerod = True else: self._zerod = False def data_as(self, obj): ptr = self._ctypes.cast(self._data, obj) ptr._arr = self._arr return ptr def shape_as(self, obj): if self._zerod: return None return (obj * self._arr.ndim)(*self._arr.shape) def strides_as(self, obj): if self._zerod: return None return (obj * self._arr.ndim)(*self._arr.strides) @property def data(self): return self._data.value @property def shape(self): return self.shape_as(_getintp_ctype()) @property def strides(self): return self.strides_as(_getintp_ctype()) @property def _as_parameter_(self): return self.data_as(ctypes.c_void_p) def get_data(self): warnings.warn('"get_data" is deprecated. Use "data" instead', DeprecationWarning, stacklevel=2) return self.data def get_shape(self): warnings.warn('"get_shape" is deprecated. Use "shape" instead', DeprecationWarning, stacklevel=2) return self.shape def get_strides(self): warnings.warn('"get_strides" is deprecated. Use "strides" instead', DeprecationWarning, stacklevel=2) return self.strides def get_as_parameter(self): warnings.warn('"get_as_parameter" is deprecated. Use "_as_parameter_" instead', DeprecationWarning, stacklevel=2) return self._as_parameter_ def _newnames(datatype, order): oldnames = datatype.names nameslist = list(oldnames) if isinstance(order, str): order = [order] seen = set() if isinstance(order, (list, tuple)): for name in order: try: nameslist.remove(name) except ValueError: if name in seen: raise ValueError(f'duplicate field name: {name}') from None else: raise ValueError(f'unknown field name: {name}') from None seen.add(name) return tuple(list(order) + nameslist) raise ValueError(f'unsupported order value: {order}') def _copy_fields(ary): dt = ary.dtype copy_dtype = {'names': dt.names, 'formats': [dt.fields[name][0] for name in dt.names]} return array(ary, dtype=copy_dtype, copy=True) def _promote_fields(dt1, dt2): if (dt1.names is None or dt2.names is None) or dt1.names != dt2.names: raise DTypePromotionError(f'field names `{dt1.names}` and `{dt2.names}` mismatch.') identical = dt1 is dt2 new_fields = [] for name in dt1.names: field1 = dt1.fields[name] field2 = dt2.fields[name] new_descr = promote_types(field1[0], field2[0]) identical = identical and new_descr is field1[0] if field1[2:] != field2[2:]: raise DTypePromotionError(f"field titles of field '{name}' mismatch") if len(field1) == 2: new_fields.append((name, new_descr)) else: new_fields.append(((field1[2], name), new_descr)) res = dtype(new_fields, align=dt1.isalignedstruct or dt2.isalignedstruct) if identical and res.itemsize == dt1.itemsize: for name in dt1.names: if dt1.fields[name][1] != res.fields[name][1]: return res return dt1 return res def _getfield_is_safe(oldtype, newtype, offset): if newtype.hasobject or oldtype.hasobject: if offset == 0 and newtype == oldtype: return if oldtype.names is not None: for name in oldtype.names: if oldtype.fields[name][1] == offset and oldtype.fields[name][0] == newtype: return raise TypeError('Cannot get/set field of an object array') return def _view_is_safe(oldtype, newtype): if oldtype == newtype: return if newtype.hasobject or oldtype.hasobject: raise TypeError('Cannot change data-type for array of references.') return _pep3118_native_map = {'?': '?', 'c': 'S1', 'b': 'b', 'B': 'B', 'h': 'h', 'H': 'H', 'i': 'i', 'I': 'I', 'l': 'l', 'L': 'L', 'q': 'q', 'Q': 'Q', 'e': 'e', 'f': 'f', 'd': 'd', 'g': 'g', 'Zf': 'F', 'Zd': 'D', 'Zg': 'G', 's': 'S', 'w': 'U', 'O': 'O', 'x': 'V'} _pep3118_native_typechars = ''.join(_pep3118_native_map.keys()) _pep3118_standard_map = {'?': '?', 'c': 'S1', 'b': 'b', 'B': 'B', 'h': 'i2', 'H': 'u2', 'i': 'i4', 'I': 'u4', 'l': 'i4', 'L': 'u4', 'q': 'i8', 'Q': 'u8', 'e': 'f2', 'f': 'f', 'd': 'd', 'Zf': 'F', 'Zd': 'D', 's': 'S', 'w': 'U', 'O': 'O', 'x': 'V'} _pep3118_standard_typechars = ''.join(_pep3118_standard_map.keys()) _pep3118_unsupported_map = {'u': 'UCS-2 strings', '&': 'pointers', 't': 'bitfields', 'X': 'function pointers'} class _Stream: def __init__(self, s): self.s = s self.byteorder = '@' def advance(self, n): res = self.s[:n] self.s = self.s[n:] return res def consume(self, c): if self.s[:len(c)] == c: self.advance(len(c)) return True return False def consume_until(self, c): if callable(c): i = 0 while i < len(self.s) and (not c(self.s[i])): i = i + 1 return self.advance(i) else: i = self.s.index(c) res = self.advance(i) self.advance(len(c)) return res @property def next(self): return self.s[0] def __bool__(self): return bool(self.s) def _dtype_from_pep3118(spec): stream = _Stream(spec) (dtype, align) = __dtype_from_pep3118(stream, is_subdtype=False) return dtype def __dtype_from_pep3118(stream, is_subdtype): field_spec = dict(names=[], formats=[], offsets=[], itemsize=0) offset = 0 common_alignment = 1 is_padding = False while stream: value = None if stream.consume('}'): break shape = None if stream.consume('('): shape = stream.consume_until(')') shape = tuple(map(int, shape.split(','))) if stream.next in ('@', '=', '<', '>', '^', '!'): byteorder = stream.advance(1) if byteorder == '!': byteorder = '>' stream.byteorder = byteorder if stream.byteorder in ('@', '^'): type_map = _pep3118_native_map type_map_chars = _pep3118_native_typechars else: type_map = _pep3118_standard_map type_map_chars = _pep3118_standard_typechars itemsize_str = stream.consume_until(lambda c: not c.isdigit()) if itemsize_str: itemsize = int(itemsize_str) else: itemsize = 1 is_padding = False if stream.consume('T{'): (value, align) = __dtype_from_pep3118(stream, is_subdtype=True) elif stream.next in type_map_chars: if stream.next == 'Z': typechar = stream.advance(2) else: typechar = stream.advance(1) is_padding = typechar == 'x' dtypechar = type_map[typechar] if dtypechar in 'USV': dtypechar += '%d' % itemsize itemsize = 1 numpy_byteorder = {'@': '=', '^': '='}.get(stream.byteorder, stream.byteorder) value = dtype(numpy_byteorder + dtypechar) align = value.alignment elif stream.next in _pep3118_unsupported_map: desc = _pep3118_unsupported_map[stream.next] raise NotImplementedError('Unrepresentable PEP 3118 data type {!r} ({})'.format(stream.next, desc)) else: raise ValueError('Unknown PEP 3118 data type specifier %r' % stream.s) extra_offset = 0 if stream.byteorder == '@': start_padding = -offset % align intra_padding = -value.itemsize % align offset += start_padding if intra_padding != 0: if itemsize > 1 or (shape is not None and _prod(shape) > 1): value = _add_trailing_padding(value, intra_padding) else: extra_offset += intra_padding common_alignment = _lcm(align, common_alignment) if itemsize != 1: value = dtype((value, (itemsize,))) if shape is not None: value = dtype((value, shape)) if stream.consume(':'): name = stream.consume_until(':') else: name = None if not (is_padding and name is None): if name is not None and name in field_spec['names']: raise RuntimeError(f"Duplicate field name '{name}' in PEP3118 format") field_spec['names'].append(name) field_spec['formats'].append(value) field_spec['offsets'].append(offset) offset += value.itemsize offset += extra_offset field_spec['itemsize'] = offset if stream.byteorder == '@': field_spec['itemsize'] += -offset % common_alignment if field_spec['names'] == [None] and field_spec['offsets'][0] == 0 and (field_spec['itemsize'] == field_spec['formats'][0].itemsize) and (not is_subdtype): ret = field_spec['formats'][0] else: _fix_names(field_spec) ret = dtype(field_spec) return (ret, common_alignment) def _fix_names(field_spec): names = field_spec['names'] for (i, name) in enumerate(names): if name is not None: continue j = 0 while True: name = f'f{j}' if name not in names: break j = j + 1 names[i] = name def _add_trailing_padding(value, padding): if value.fields is None: field_spec = dict(names=['f0'], formats=[value], offsets=[0], itemsize=value.itemsize) else: fields = value.fields names = value.names field_spec = dict(names=names, formats=[fields[name][0] for name in names], offsets=[fields[name][1] for name in names], itemsize=value.itemsize) field_spec['itemsize'] += padding return dtype(field_spec) def _prod(a): p = 1 for x in a: p *= x return p def _gcd(a, b): if not (math.isfinite(a) and math.isfinite(b)): raise ValueError(f'Can only find greatest common divisor of finite arguments, found "{a}" and "{b}"') while b: (a, b) = (b, a % b) return a def _lcm(a, b): return a // _gcd(a, b) * b def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs): args_string = ', '.join(['{!r}'.format(arg) for arg in inputs] + ['{}={!r}'.format(k, v) for (k, v) in kwargs.items()]) args = inputs + kwargs.get('out', ()) types_string = ', '.join((repr(type(arg).__name__) for arg in args)) return 'operand type(s) all returned NotImplemented from __array_ufunc__({!r}, {!r}, {}): {}'.format(ufunc, method, args_string, types_string) def array_function_errmsg_formatter(public_api, types): func_name = '{}.{}'.format(public_api.__module__, public_api.__name__) return "no implementation found for '{}' on types that implement __array_function__: {}".format(func_name, list(types)) def _ufunc_doc_signature_formatter(ufunc): if ufunc.nin == 1: in_args = 'x' else: in_args = ', '.join((f'x{i + 1}' for i in range(ufunc.nin))) if ufunc.nout == 0: out_args = ', /, out=()' elif ufunc.nout == 1: out_args = ', /, out=None' else: out_args = '[, {positional}], / [, out={default}]'.format(positional=', '.join(('out{}'.format(i + 1) for i in range(ufunc.nout))), default=repr((None,) * ufunc.nout)) kwargs = ", casting='same_kind', order='K', dtype=None, subok=True" if ufunc.signature is None: kwargs = f', where=True{kwargs}[, signature]' else: kwargs += '[, signature, axes, axis]' return '{name}({in_args}{out_args}, *{kwargs})'.format(name=ufunc.__name__, in_args=in_args, out_args=out_args, kwargs=kwargs) def npy_ctypes_check(cls): try: if IS_PYPY: ctype_base = cls.__mro__[-3] else: ctype_base = cls.__mro__[-2] return '_ctypes' in ctype_base.__module__ except Exception: return False def _convert_to_stringdtype_kwargs(coerce, na_object=_NoValue): if na_object is _NoValue: return StringDType(coerce=coerce) return StringDType(coerce=coerce, na_object=na_object) # File: numpy-main/numpy/_core/_machar.py """""" __all__ = ['MachAr'] from .fromnumeric import any from ._ufunc_config import errstate from .._utils import set_module class MachAr: def __init__(self, float_conv=float, int_conv=int, float_to_float=float, float_to_str=lambda v: '%24.16e' % v, title='Python floating point number'): with errstate(under='ignore'): self._do_init(float_conv, int_conv, float_to_float, float_to_str, title) def _do_init(self, float_conv, int_conv, float_to_float, float_to_str, title): max_iterN = 10000 msg = 'Did not converge after %d tries with %s' one = float_conv(1) two = one + one zero = one - one a = one for _ in range(max_iterN): a = a + a temp = a + one temp1 = temp - a if any(temp1 - one != zero): break else: raise RuntimeError(msg % (_, one.dtype)) b = one for _ in range(max_iterN): b = b + b temp = a + b itemp = int_conv(temp - a) if any(itemp != 0): break else: raise RuntimeError(msg % (_, one.dtype)) ibeta = itemp beta = float_conv(ibeta) it = -1 b = one for _ in range(max_iterN): it = it + 1 b = b * beta temp = b + one temp1 = temp - b if any(temp1 - one != zero): break else: raise RuntimeError(msg % (_, one.dtype)) betah = beta / two a = one for _ in range(max_iterN): a = a + a temp = a + one temp1 = temp - a if any(temp1 - one != zero): break else: raise RuntimeError(msg % (_, one.dtype)) temp = a + betah irnd = 0 if any(temp - a != zero): irnd = 1 tempa = a + beta temp = tempa + betah if irnd == 0 and any(temp - tempa != zero): irnd = 2 negep = it + 3 betain = one / beta a = one for i in range(negep): a = a * betain b = a for _ in range(max_iterN): temp = one - a if any(temp - one != zero): break a = a * beta negep = negep - 1 if negep < 0: raise RuntimeError("could not determine machine tolerance for 'negep', locals() -> %s" % locals()) else: raise RuntimeError(msg % (_, one.dtype)) negep = -negep epsneg = a machep = -it - 3 a = b for _ in range(max_iterN): temp = one + a if any(temp - one != zero): break a = a * beta machep = machep + 1 else: raise RuntimeError(msg % (_, one.dtype)) eps = a ngrd = 0 temp = one + eps if irnd == 0 and any(temp * one - one != zero): ngrd = 1 i = 0 k = 1 z = betain t = one + eps nxres = 0 for _ in range(max_iterN): y = z z = y * y a = z * one temp = z * t if any(a + a == zero) or any(abs(z) >= y): break temp1 = temp * betain if any(temp1 * beta == z): break i = i + 1 k = k + k else: raise RuntimeError(msg % (_, one.dtype)) if ibeta != 10: iexp = i + 1 mx = k + k else: iexp = 2 iz = ibeta while k >= iz: iz = iz * ibeta iexp = iexp + 1 mx = iz + iz - 1 for _ in range(max_iterN): xmin = y y = y * betain a = y * one temp = y * t if any(a + a != zero) and any(abs(y) < xmin): k = k + 1 temp1 = temp * betain if any(temp1 * beta == y) and any(temp != y): nxres = 3 xmin = y break else: break else: raise RuntimeError(msg % (_, one.dtype)) minexp = -k if mx <= k + k - 3 and ibeta != 10: mx = mx + mx iexp = iexp + 1 maxexp = mx + minexp irnd = irnd + nxres if irnd >= 2: maxexp = maxexp - 2 i = maxexp + minexp if ibeta == 2 and (not i): maxexp = maxexp - 1 if i > 20: maxexp = maxexp - 1 if any(a != y): maxexp = maxexp - 2 xmax = one - epsneg if any(xmax * one != xmax): xmax = one - beta * epsneg xmax = xmax / (xmin * beta * beta * beta) i = maxexp + minexp + 3 for j in range(i): if ibeta == 2: xmax = xmax + xmax else: xmax = xmax * beta smallest_subnormal = abs(xmin / beta ** it) self.ibeta = ibeta self.it = it self.negep = negep self.epsneg = float_to_float(epsneg) self._str_epsneg = float_to_str(epsneg) self.machep = machep self.eps = float_to_float(eps) self._str_eps = float_to_str(eps) self.ngrd = ngrd self.iexp = iexp self.minexp = minexp self.xmin = float_to_float(xmin) self._str_xmin = float_to_str(xmin) self.maxexp = maxexp self.xmax = float_to_float(xmax) self._str_xmax = float_to_str(xmax) self.irnd = irnd self.title = title self.epsilon = self.eps self.tiny = self.xmin self.huge = self.xmax self.smallest_normal = self.xmin self._str_smallest_normal = float_to_str(self.xmin) self.smallest_subnormal = float_to_float(smallest_subnormal) self._str_smallest_subnormal = float_to_str(smallest_subnormal) import math self.precision = int(-math.log10(float_to_float(self.eps))) ten = two + two + two + two + two resolution = ten ** (-self.precision) self.resolution = float_to_float(resolution) self._str_resolution = float_to_str(resolution) def __str__(self): fmt = 'Machine parameters for %(title)s\n---------------------------------------------------------------------\nibeta=%(ibeta)s it=%(it)s iexp=%(iexp)s ngrd=%(ngrd)s irnd=%(irnd)s\nmachep=%(machep)s eps=%(_str_eps)s (beta**machep == epsilon)\nnegep =%(negep)s epsneg=%(_str_epsneg)s (beta**epsneg)\nminexp=%(minexp)s xmin=%(_str_xmin)s (beta**minexp == tiny)\nmaxexp=%(maxexp)s xmax=%(_str_xmax)s ((1-epsneg)*beta**maxexp == huge)\nsmallest_normal=%(smallest_normal)s smallest_subnormal=%(smallest_subnormal)s\n---------------------------------------------------------------------\n' return fmt % self.__dict__ if __name__ == '__main__': print(MachAr()) # File: numpy-main/numpy/_core/_methods.py """""" import os import pickle import warnings from contextlib import nullcontext import numpy as np from numpy._core import multiarray as mu from numpy._core import umath as um from numpy._core.multiarray import asanyarray from numpy._core import numerictypes as nt from numpy._core import _exceptions from numpy._globals import _NoValue bool_dt = mu.dtype('bool') umr_maximum = um.maximum.reduce umr_minimum = um.minimum.reduce umr_sum = um.add.reduce umr_prod = um.multiply.reduce umr_bitwise_count = um.bitwise_count umr_any = um.logical_or.reduce umr_all = um.logical_and.reduce _complex_to_float = {nt.dtype(nt.csingle): nt.dtype(nt.single), nt.dtype(nt.cdouble): nt.dtype(nt.double)} if nt.dtype(nt.longdouble) != nt.dtype(nt.double): _complex_to_float.update({nt.dtype(nt.clongdouble): nt.dtype(nt.longdouble)}) def _amax(a, axis=None, out=None, keepdims=False, initial=_NoValue, where=True): return umr_maximum(a, axis, None, out, keepdims, initial, where) def _amin(a, axis=None, out=None, keepdims=False, initial=_NoValue, where=True): return umr_minimum(a, axis, None, out, keepdims, initial, where) def _sum(a, axis=None, dtype=None, out=None, keepdims=False, initial=_NoValue, where=True): return umr_sum(a, axis, dtype, out, keepdims, initial, where) def _prod(a, axis=None, dtype=None, out=None, keepdims=False, initial=_NoValue, where=True): return umr_prod(a, axis, dtype, out, keepdims, initial, where) def _any(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True): if dtype is None: dtype = bool_dt if where is True: return umr_any(a, axis, dtype, out, keepdims) return umr_any(a, axis, dtype, out, keepdims, where=where) def _all(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True): if dtype is None: dtype = bool_dt if where is True: return umr_all(a, axis, dtype, out, keepdims) return umr_all(a, axis, dtype, out, keepdims, where=where) def _count_reduce_items(arr, axis, keepdims=False, where=True): if where is True: if axis is None: axis = tuple(range(arr.ndim)) elif not isinstance(axis, tuple): axis = (axis,) items = 1 for ax in axis: items *= arr.shape[mu.normalize_axis_index(ax, arr.ndim)] items = nt.intp(items) else: from numpy.lib._stride_tricks_impl import broadcast_to items = umr_sum(broadcast_to(where, arr.shape), axis, nt.intp, None, keepdims) return items def _clip(a, min=None, max=None, out=None, **kwargs): if a.dtype.kind in 'iu': if type(min) is int and min <= np.iinfo(a.dtype).min: min = None if type(max) is int and max >= np.iinfo(a.dtype).max: max = None if min is None and max is None: return um.positive(a, out=out, **kwargs) elif min is None: return um.minimum(a, max, out=out, **kwargs) elif max is None: return um.maximum(a, min, out=out, **kwargs) else: return um.clip(a, min, max, out=out, **kwargs) def _mean(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True): arr = asanyarray(a) is_float16_result = False rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where) if rcount == 0 if where is True else umr_any(rcount == 0, axis=None): warnings.warn('Mean of empty slice.', RuntimeWarning, stacklevel=2) if dtype is None: if issubclass(arr.dtype.type, (nt.integer, nt.bool)): dtype = mu.dtype('f8') elif issubclass(arr.dtype.type, nt.float16): dtype = mu.dtype('f4') is_float16_result = True ret = umr_sum(arr, axis, dtype, out, keepdims, where=where) if isinstance(ret, mu.ndarray): ret = um.true_divide(ret, rcount, out=ret, casting='unsafe', subok=False) if is_float16_result and out is None: ret = arr.dtype.type(ret) elif hasattr(ret, 'dtype'): if is_float16_result: ret = arr.dtype.type(ret / rcount) else: ret = ret.dtype.type(ret / rcount) else: ret = ret / rcount return ret def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True, mean=None): arr = asanyarray(a) rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where) if ddof >= rcount if where is True else umr_any(ddof >= rcount, axis=None): warnings.warn('Degrees of freedom <= 0 for slice', RuntimeWarning, stacklevel=2) if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool)): dtype = mu.dtype('f8') if mean is not None: arrmean = mean else: arrmean = umr_sum(arr, axis, dtype, keepdims=True, where=where) if rcount.ndim == 0: div = rcount else: div = rcount.reshape(arrmean.shape) if isinstance(arrmean, mu.ndarray): arrmean = um.true_divide(arrmean, div, out=arrmean, casting='unsafe', subok=False) elif hasattr(arrmean, 'dtype'): arrmean = arrmean.dtype.type(arrmean / rcount) else: arrmean = arrmean / rcount x = asanyarray(arr - arrmean) if issubclass(arr.dtype.type, (nt.floating, nt.integer)): x = um.multiply(x, x, out=x) elif x.dtype in _complex_to_float: xv = x.view(dtype=(_complex_to_float[x.dtype], (2,))) um.multiply(xv, xv, out=xv) x = um.add(xv[..., 0], xv[..., 1], out=x.real).real else: x = um.multiply(x, um.conjugate(x), out=x).real ret = umr_sum(x, axis, dtype, out, keepdims=keepdims, where=where) rcount = um.maximum(rcount - ddof, 0) if isinstance(ret, mu.ndarray): ret = um.true_divide(ret, rcount, out=ret, casting='unsafe', subok=False) elif hasattr(ret, 'dtype'): ret = ret.dtype.type(ret / rcount) else: ret = ret / rcount return ret def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True, mean=None): ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, where=where, mean=mean) if isinstance(ret, mu.ndarray): ret = um.sqrt(ret, out=ret) elif hasattr(ret, 'dtype'): ret = ret.dtype.type(um.sqrt(ret)) else: ret = um.sqrt(ret) return ret def _ptp(a, axis=None, out=None, keepdims=False): return um.subtract(umr_maximum(a, axis, None, out, keepdims), umr_minimum(a, axis, None, None, keepdims), out) def _dump(self, file, protocol=2): if hasattr(file, 'write'): ctx = nullcontext(file) else: ctx = open(os.fspath(file), 'wb') with ctx as f: pickle.dump(self, f, protocol=protocol) def _dumps(self, protocol=2): return pickle.dumps(self, protocol=protocol) def _bitwise_count(a, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True): return umr_bitwise_count(a, out, where=where, casting=casting, order=order, dtype=dtype, subok=subok) # File: numpy-main/numpy/_core/_string_helpers.py """""" _all_chars = tuple(map(chr, range(256))) _ascii_upper = _all_chars[65:65 + 26] _ascii_lower = _all_chars[97:97 + 26] LOWER_TABLE = _all_chars[:65] + _ascii_lower + _all_chars[65 + 26:] UPPER_TABLE = _all_chars[:97] + _ascii_upper + _all_chars[97 + 26:] def english_lower(s): lowered = s.translate(LOWER_TABLE) return lowered def english_upper(s): uppered = s.translate(UPPER_TABLE) return uppered def english_capitalize(s): if s: return english_upper(s[0]) + s[1:] else: return s # File: numpy-main/numpy/_core/_type_aliases.py """""" import numpy._core.multiarray as ma from numpy._core.multiarray import typeinfo, dtype sctypeDict = {} allTypes = {} c_names_dict = {} _abstract_type_names = {'generic', 'integer', 'inexact', 'floating', 'number', 'flexible', 'character', 'complexfloating', 'unsignedinteger', 'signedinteger'} for _abstract_type_name in _abstract_type_names: allTypes[_abstract_type_name] = getattr(ma, _abstract_type_name) for (k, v) in typeinfo.items(): if k.startswith('NPY_') and v not in c_names_dict: c_names_dict[k[4:]] = v else: concrete_type = v.type allTypes[k] = concrete_type sctypeDict[k] = concrete_type _aliases = {'double': 'float64', 'cdouble': 'complex128', 'single': 'float32', 'csingle': 'complex64', 'half': 'float16', 'bool_': 'bool', 'int_': 'intp', 'uint': 'uintp'} for (k, v) in _aliases.items(): sctypeDict[k] = allTypes[v] allTypes[k] = allTypes[v] _extra_aliases = {'float': 'float64', 'complex': 'complex128', 'object': 'object_', 'bytes': 'bytes_', 'a': 'bytes_', 'int': 'int_', 'str': 'str_', 'unicode': 'str_'} for (k, v) in _extra_aliases.items(): sctypeDict[k] = allTypes[v] for (is_complex, full_name) in [(False, 'longdouble'), (True, 'clongdouble')]: longdouble_type: type = allTypes[full_name] bits: int = dtype(longdouble_type).itemsize * 8 base_name: str = 'complex' if is_complex else 'float' extended_prec_name: str = f'{base_name}{bits}' if extended_prec_name not in allTypes: sctypeDict[extended_prec_name] = longdouble_type allTypes[extended_prec_name] = longdouble_type sctypes = {'int': set(), 'uint': set(), 'float': set(), 'complex': set(), 'others': set()} for type_info in typeinfo.values(): if type_info.kind in ['M', 'm']: continue concrete_type = type_info.type for (type_group, abstract_type) in [('int', ma.signedinteger), ('uint', ma.unsignedinteger), ('float', ma.floating), ('complex', ma.complexfloating), ('others', ma.generic)]: if issubclass(concrete_type, abstract_type): sctypes[type_group].add(concrete_type) break for sctype_key in sctypes.keys(): sctype_list = list(sctypes[sctype_key]) sctype_list.sort(key=lambda x: dtype(x).itemsize) sctypes[sctype_key] = sctype_list # File: numpy-main/numpy/_core/_ufunc_config.py """""" import contextlib import contextvars import functools from .._utils import set_module from .umath import _make_extobj, _get_extobj_dict, _extobj_contextvar __all__ = ['seterr', 'geterr', 'setbufsize', 'getbufsize', 'seterrcall', 'geterrcall', 'errstate'] @set_module('numpy') def seterr(all=None, divide=None, over=None, under=None, invalid=None): old = _get_extobj_dict() old.pop('call', None) old.pop('bufsize', None) extobj = _make_extobj(all=all, divide=divide, over=over, under=under, invalid=invalid) _extobj_contextvar.set(extobj) return old @set_module('numpy') def geterr(): res = _get_extobj_dict() res.pop('call', None) res.pop('bufsize', None) return res @set_module('numpy') def setbufsize(size): old = _get_extobj_dict()['bufsize'] extobj = _make_extobj(bufsize=size) _extobj_contextvar.set(extobj) return old @set_module('numpy') def getbufsize(): return _get_extobj_dict()['bufsize'] @set_module('numpy') def seterrcall(func): old = _get_extobj_dict()['call'] extobj = _make_extobj(call=func) _extobj_contextvar.set(extobj) return old @set_module('numpy') def geterrcall(): return _get_extobj_dict()['call'] class _unspecified: pass _Unspecified = _unspecified() @set_module('numpy') class errstate: __slots__ = ('_call', '_all', '_divide', '_over', '_under', '_invalid', '_token') def __init__(self, *, call=_Unspecified, all=None, divide=None, over=None, under=None, invalid=None): self._token = None self._call = call self._all = all self._divide = divide self._over = over self._under = under self._invalid = invalid def __enter__(self): if self._token is not None: raise TypeError('Cannot enter `np.errstate` twice.') if self._call is _Unspecified: extobj = _make_extobj(all=self._all, divide=self._divide, over=self._over, under=self._under, invalid=self._invalid) else: extobj = _make_extobj(call=self._call, all=self._all, divide=self._divide, over=self._over, under=self._under, invalid=self._invalid) self._token = _extobj_contextvar.set(extobj) def __exit__(self, *exc_info): _extobj_contextvar.reset(self._token) def __call__(self, func): @functools.wraps(func) def inner(*args, **kwargs): if self._call is _Unspecified: extobj = _make_extobj(all=self._all, divide=self._divide, over=self._over, under=self._under, invalid=self._invalid) else: extobj = _make_extobj(call=self._call, all=self._all, divide=self._divide, over=self._over, under=self._under, invalid=self._invalid) _token = _extobj_contextvar.set(extobj) try: return func(*args, **kwargs) finally: _extobj_contextvar.reset(_token) return inner # File: numpy-main/numpy/_core/arrayprint.py """""" __all__ = ['array2string', 'array_str', 'array_repr', 'set_printoptions', 'get_printoptions', 'printoptions', 'format_float_positional', 'format_float_scientific'] __docformat__ = 'restructuredtext' import functools import numbers import sys try: from _thread import get_ident except ImportError: from _dummy_thread import get_ident import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import longlong, intc, int_, float64, complex128, flexible from .overrides import array_function_dispatch, set_module from .printoptions import format_options import operator import warnings import contextlib def _make_options_dict(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, sign=None, formatter=None, floatmode=None, legacy=None, override_repr=None): options = {k: v for (k, v) in list(locals().items()) if v is not None} if suppress is not None: options['suppress'] = bool(suppress) modes = ['fixed', 'unique', 'maxprec', 'maxprec_equal'] if floatmode not in modes + [None]: raise ValueError('floatmode option must be one of ' + ', '.join(('"{}"'.format(m) for m in modes))) if sign not in [None, '-', '+', ' ']: raise ValueError("sign option must be one of ' ', '+', or '-'") if legacy is False: options['legacy'] = sys.maxsize elif legacy == False: warnings.warn(f'Passing `legacy={legacy!r}` is deprecated.', FutureWarning, stacklevel=3) options['legacy'] = sys.maxsize elif legacy == '1.13': options['legacy'] = 113 elif legacy == '1.21': options['legacy'] = 121 elif legacy == '1.25': options['legacy'] = 125 elif legacy is None: pass else: warnings.warn("legacy printing option can currently only be '1.13', '1.21', '1.25', or `False`", stacklevel=3) if threshold is not None: if not isinstance(threshold, numbers.Number): raise TypeError('threshold must be numeric') if np.isnan(threshold): raise ValueError('threshold must be non-NAN, try sys.maxsize for untruncated representation') if precision is not None: try: options['precision'] = operator.index(precision) except TypeError as e: raise TypeError('precision must be an integer') from e return options @set_module('numpy') def set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, *, legacy=None, override_repr=None): _set_printoptions(precision, threshold, edgeitems, linewidth, suppress, nanstr, infstr, formatter, sign, floatmode, legacy=legacy, override_repr=override_repr) def _set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, *, legacy=None, override_repr=None): new_opt = _make_options_dict(precision, threshold, edgeitems, linewidth, suppress, nanstr, infstr, sign, formatter, floatmode, legacy) new_opt['formatter'] = formatter new_opt['override_repr'] = override_repr updated_opt = format_options.get() | new_opt updated_opt.update(new_opt) if updated_opt['legacy'] == 113: updated_opt['sign'] = '-' return format_options.set(updated_opt) @set_module('numpy') def get_printoptions(): opts = format_options.get().copy() opts['legacy'] = {113: '1.13', 121: '1.21', 125: '1.25', sys.maxsize: False}[opts['legacy']] return opts def _get_legacy_print_mode(): return format_options.get()['legacy'] @set_module('numpy') @contextlib.contextmanager def printoptions(*args, **kwargs): token = _set_printoptions(*args, **kwargs) try: yield get_printoptions() finally: format_options.reset(token) def _leading_trailing(a, edgeitems, index=()): axis = len(index) if axis == a.ndim: return a[index] if a.shape[axis] > 2 * edgeitems: return concatenate((_leading_trailing(a, edgeitems, index + np.index_exp[:edgeitems]), _leading_trailing(a, edgeitems, index + np.index_exp[-edgeitems:])), axis=axis) else: return _leading_trailing(a, edgeitems, index + np.index_exp[:]) def _object_format(o): if type(o) is list: fmt = 'list({!r})' else: fmt = '{!r}' return fmt.format(o) def repr_format(x): if isinstance(x, (np.str_, np.bytes_)): return repr(x.item()) return repr(x) def str_format(x): if isinstance(x, (np.str_, np.bytes_)): return str(x.item()) return str(x) def _get_formatdict(data, *, precision, floatmode, suppress, sign, legacy, formatter, **kwargs): formatdict = {'bool': lambda : BoolFormat(data), 'int': lambda : IntegerFormat(data, sign), 'float': lambda : FloatingFormat(data, precision, floatmode, suppress, sign, legacy=legacy), 'longfloat': lambda : FloatingFormat(data, precision, floatmode, suppress, sign, legacy=legacy), 'complexfloat': lambda : ComplexFloatingFormat(data, precision, floatmode, suppress, sign, legacy=legacy), 'longcomplexfloat': lambda : ComplexFloatingFormat(data, precision, floatmode, suppress, sign, legacy=legacy), 'datetime': lambda : DatetimeFormat(data, legacy=legacy), 'timedelta': lambda : TimedeltaFormat(data), 'object': lambda : _object_format, 'void': lambda : str_format, 'numpystr': lambda : repr_format} def indirect(x): return lambda : x if formatter is not None: fkeys = [k for k in formatter.keys() if formatter[k] is not None] if 'all' in fkeys: for key in formatdict.keys(): formatdict[key] = indirect(formatter['all']) if 'int_kind' in fkeys: for key in ['int']: formatdict[key] = indirect(formatter['int_kind']) if 'float_kind' in fkeys: for key in ['float', 'longfloat']: formatdict[key] = indirect(formatter['float_kind']) if 'complex_kind' in fkeys: for key in ['complexfloat', 'longcomplexfloat']: formatdict[key] = indirect(formatter['complex_kind']) if 'str_kind' in fkeys: formatdict['numpystr'] = indirect(formatter['str_kind']) for key in formatdict.keys(): if key in fkeys: formatdict[key] = indirect(formatter[key]) return formatdict def _get_format_function(data, **options): dtype_ = data.dtype dtypeobj = dtype_.type formatdict = _get_formatdict(data, **options) if dtypeobj is None: return formatdict['numpystr']() elif issubclass(dtypeobj, _nt.bool): return formatdict['bool']() elif issubclass(dtypeobj, _nt.integer): if issubclass(dtypeobj, _nt.timedelta64): return formatdict['timedelta']() else: return formatdict['int']() elif issubclass(dtypeobj, _nt.floating): if issubclass(dtypeobj, _nt.longdouble): return formatdict['longfloat']() else: return formatdict['float']() elif issubclass(dtypeobj, _nt.complexfloating): if issubclass(dtypeobj, _nt.clongdouble): return formatdict['longcomplexfloat']() else: return formatdict['complexfloat']() elif issubclass(dtypeobj, (_nt.str_, _nt.bytes_)): return formatdict['numpystr']() elif issubclass(dtypeobj, _nt.datetime64): return formatdict['datetime']() elif issubclass(dtypeobj, _nt.object_): return formatdict['object']() elif issubclass(dtypeobj, _nt.void): if dtype_.names is not None: return StructuredVoidFormat.from_data(data, **options) else: return formatdict['void']() else: return formatdict['numpystr']() def _recursive_guard(fillvalue='...'): def decorating_function(f): repr_running = set() @functools.wraps(f) def wrapper(self, *args, **kwargs): key = (id(self), get_ident()) if key in repr_running: return fillvalue repr_running.add(key) try: return f(self, *args, **kwargs) finally: repr_running.discard(key) return wrapper return decorating_function @_recursive_guard() def _array2string(a, options, separator=' ', prefix=''): data = asarray(a) if a.shape == (): a = data if a.size > options['threshold']: summary_insert = '...' data = _leading_trailing(data, options['edgeitems']) else: summary_insert = '' format_function = _get_format_function(data, **options) next_line_prefix = ' ' next_line_prefix += ' ' * len(prefix) lst = _formatArray(a, format_function, options['linewidth'], next_line_prefix, separator, options['edgeitems'], summary_insert, options['legacy']) return lst def _array2string_dispatcher(a, max_line_width=None, precision=None, suppress_small=None, separator=None, prefix=None, style=None, formatter=None, threshold=None, edgeitems=None, sign=None, floatmode=None, suffix=None, *, legacy=None): return (a,) @array_function_dispatch(_array2string_dispatcher, module='numpy') def array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix='', style=np._NoValue, formatter=None, threshold=None, edgeitems=None, sign=None, floatmode=None, suffix='', *, legacy=None): overrides = _make_options_dict(precision, threshold, edgeitems, max_line_width, suppress_small, None, None, sign, formatter, floatmode, legacy) options = format_options.get().copy() options.update(overrides) if options['legacy'] <= 113: if style is np._NoValue: style = repr if a.shape == () and a.dtype.names is None: return style(a.item()) elif style is not np._NoValue: warnings.warn("'style' argument is deprecated and no longer functional except in 1.13 'legacy' mode", DeprecationWarning, stacklevel=2) if options['legacy'] > 113: options['linewidth'] -= len(suffix) if a.size == 0: return '[]' return _array2string(a, options, separator, prefix) def _extendLine(s, line, word, line_width, next_line_prefix, legacy): needs_wrap = len(line) + len(word) > line_width if legacy > 113: if len(line) <= len(next_line_prefix): needs_wrap = False if needs_wrap: s += line.rstrip() + '\n' line = next_line_prefix line += word return (s, line) def _extendLine_pretty(s, line, word, line_width, next_line_prefix, legacy): words = word.splitlines() if len(words) == 1 or legacy <= 113: return _extendLine(s, line, word, line_width, next_line_prefix, legacy) max_word_length = max((len(word) for word in words)) if len(line) + max_word_length > line_width and len(line) > len(next_line_prefix): s += line.rstrip() + '\n' line = next_line_prefix + words[0] indent = next_line_prefix else: indent = len(line) * ' ' line += words[0] for word in words[1:]: s += line.rstrip() + '\n' line = indent + word suffix_length = max_word_length - len(words[-1]) line += suffix_length * ' ' return (s, line) def _formatArray(a, format_function, line_width, next_line_prefix, separator, edge_items, summary_insert, legacy): def recurser(index, hanging_indent, curr_width): axis = len(index) axes_left = a.ndim - axis if axes_left == 0: return format_function(a[index]) next_hanging_indent = hanging_indent + ' ' if legacy <= 113: next_width = curr_width else: next_width = curr_width - len(']') a_len = a.shape[axis] show_summary = summary_insert and 2 * edge_items < a_len if show_summary: leading_items = edge_items trailing_items = edge_items else: leading_items = 0 trailing_items = a_len s = '' if axes_left == 1: if legacy <= 113: elem_width = curr_width - len(separator.rstrip()) else: elem_width = curr_width - max(len(separator.rstrip()), len(']')) line = hanging_indent for i in range(leading_items): word = recurser(index + (i,), next_hanging_indent, next_width) (s, line) = _extendLine_pretty(s, line, word, elem_width, hanging_indent, legacy) line += separator if show_summary: (s, line) = _extendLine(s, line, summary_insert, elem_width, hanging_indent, legacy) if legacy <= 113: line += ', ' else: line += separator for i in range(trailing_items, 1, -1): word = recurser(index + (-i,), next_hanging_indent, next_width) (s, line) = _extendLine_pretty(s, line, word, elem_width, hanging_indent, legacy) line += separator if legacy <= 113: elem_width = curr_width word = recurser(index + (-1,), next_hanging_indent, next_width) (s, line) = _extendLine_pretty(s, line, word, elem_width, hanging_indent, legacy) s += line else: s = '' line_sep = separator.rstrip() + '\n' * (axes_left - 1) for i in range(leading_items): nested = recurser(index + (i,), next_hanging_indent, next_width) s += hanging_indent + nested + line_sep if show_summary: if legacy <= 113: s += hanging_indent + summary_insert + ', \n' else: s += hanging_indent + summary_insert + line_sep for i in range(trailing_items, 1, -1): nested = recurser(index + (-i,), next_hanging_indent, next_width) s += hanging_indent + nested + line_sep nested = recurser(index + (-1,), next_hanging_indent, next_width) s += hanging_indent + nested s = '[' + s[len(hanging_indent):] + ']' return s try: return recurser(index=(), hanging_indent=next_line_prefix, curr_width=line_width) finally: recurser = None def _none_or_positive_arg(x, name): if x is None: return -1 if x < 0: raise ValueError('{} must be >= 0'.format(name)) return x class FloatingFormat: def __init__(self, data, precision, floatmode, suppress_small, sign=False, *, legacy=None): if isinstance(sign, bool): sign = '+' if sign else '-' self._legacy = legacy if self._legacy <= 113: if data.shape != () and sign == '-': sign = ' ' self.floatmode = floatmode if floatmode == 'unique': self.precision = None else: self.precision = precision self.precision = _none_or_positive_arg(self.precision, 'precision') self.suppress_small = suppress_small self.sign = sign self.exp_format = False self.large_exponent = False self.fillFormat(data) def fillFormat(self, data): finite_vals = data[isfinite(data)] abs_non_zero = absolute(finite_vals[finite_vals != 0]) if len(abs_non_zero) != 0: max_val = np.max(abs_non_zero) min_val = np.min(abs_non_zero) with errstate(over='ignore'): if max_val >= 100000000.0 or (not self.suppress_small and (min_val < 0.0001 or max_val / min_val > 1000.0)): self.exp_format = True if len(finite_vals) == 0: self.pad_left = 0 self.pad_right = 0 self.trim = '.' self.exp_size = -1 self.unique = True self.min_digits = None elif self.exp_format: (trim, unique) = ('.', True) if self.floatmode == 'fixed' or self._legacy <= 113: (trim, unique) = ('k', False) strs = (dragon4_scientific(x, precision=self.precision, unique=unique, trim=trim, sign=self.sign == '+') for x in finite_vals) (frac_strs, _, exp_strs) = zip(*(s.partition('e') for s in strs)) (int_part, frac_part) = zip(*(s.split('.') for s in frac_strs)) self.exp_size = max((len(s) for s in exp_strs)) - 1 self.trim = 'k' self.precision = max((len(s) for s in frac_part)) self.min_digits = self.precision self.unique = unique if self._legacy <= 113: self.pad_left = 3 else: self.pad_left = max((len(s) for s in int_part)) self.pad_right = self.exp_size + 2 + self.precision else: (trim, unique) = ('.', True) if self.floatmode == 'fixed': (trim, unique) = ('k', False) strs = (dragon4_positional(x, precision=self.precision, fractional=True, unique=unique, trim=trim, sign=self.sign == '+') for x in finite_vals) (int_part, frac_part) = zip(*(s.split('.') for s in strs)) if self._legacy <= 113: self.pad_left = 1 + max((len(s.lstrip('-+')) for s in int_part)) else: self.pad_left = max((len(s) for s in int_part)) self.pad_right = max((len(s) for s in frac_part)) self.exp_size = -1 self.unique = unique if self.floatmode in ['fixed', 'maxprec_equal']: self.precision = self.min_digits = self.pad_right self.trim = 'k' else: self.trim = '.' self.min_digits = 0 if self._legacy > 113: if self.sign == ' ' and (not any(np.signbit(finite_vals))): self.pad_left += 1 if data.size != finite_vals.size: neginf = self.sign != '-' or any(data[isinf(data)] < 0) offset = self.pad_right + 1 current_options = format_options.get() self.pad_left = max(self.pad_left, len(current_options['nanstr']) - offset, len(current_options['infstr']) + neginf - offset) def __call__(self, x): if not np.isfinite(x): with errstate(invalid='ignore'): current_options = format_options.get() if np.isnan(x): sign = '+' if self.sign == '+' else '' ret = sign + current_options['nanstr'] else: sign = '-' if x < 0 else '+' if self.sign == '+' else '' ret = sign + current_options['infstr'] return ' ' * (self.pad_left + self.pad_right + 1 - len(ret)) + ret if self.exp_format: return dragon4_scientific(x, precision=self.precision, min_digits=self.min_digits, unique=self.unique, trim=self.trim, sign=self.sign == '+', pad_left=self.pad_left, exp_digits=self.exp_size) else: return dragon4_positional(x, precision=self.precision, min_digits=self.min_digits, unique=self.unique, fractional=True, trim=self.trim, sign=self.sign == '+', pad_left=self.pad_left, pad_right=self.pad_right) @set_module('numpy') def format_float_scientific(x, precision=None, unique=True, trim='k', sign=False, pad_left=None, exp_digits=None, min_digits=None): precision = _none_or_positive_arg(precision, 'precision') pad_left = _none_or_positive_arg(pad_left, 'pad_left') exp_digits = _none_or_positive_arg(exp_digits, 'exp_digits') min_digits = _none_or_positive_arg(min_digits, 'min_digits') if min_digits > 0 and precision > 0 and (min_digits > precision): raise ValueError('min_digits must be less than or equal to precision') return dragon4_scientific(x, precision=precision, unique=unique, trim=trim, sign=sign, pad_left=pad_left, exp_digits=exp_digits, min_digits=min_digits) @set_module('numpy') def format_float_positional(x, precision=None, unique=True, fractional=True, trim='k', sign=False, pad_left=None, pad_right=None, min_digits=None): precision = _none_or_positive_arg(precision, 'precision') pad_left = _none_or_positive_arg(pad_left, 'pad_left') pad_right = _none_or_positive_arg(pad_right, 'pad_right') min_digits = _none_or_positive_arg(min_digits, 'min_digits') if not fractional and precision == 0: raise ValueError('precision must be greater than 0 if fractional=False') if min_digits > 0 and precision > 0 and (min_digits > precision): raise ValueError('min_digits must be less than or equal to precision') return dragon4_positional(x, precision=precision, unique=unique, fractional=fractional, trim=trim, sign=sign, pad_left=pad_left, pad_right=pad_right, min_digits=min_digits) class IntegerFormat: def __init__(self, data, sign='-'): if data.size > 0: data_max = np.max(data) data_min = np.min(data) data_max_str_len = len(str(data_max)) if sign == ' ' and data_min < 0: sign = '-' if data_max >= 0 and sign in '+ ': data_max_str_len += 1 max_str_len = max(data_max_str_len, len(str(data_min))) else: max_str_len = 0 self.format = f'{{:{sign}{max_str_len}d}}' def __call__(self, x): return self.format.format(x) class BoolFormat: def __init__(self, data, **kwargs): self.truestr = ' True' if data.shape != () else 'True' def __call__(self, x): return self.truestr if x else 'False' class ComplexFloatingFormat: def __init__(self, x, precision, floatmode, suppress_small, sign=False, *, legacy=None): if isinstance(sign, bool): sign = '+' if sign else '-' floatmode_real = floatmode_imag = floatmode if legacy <= 113: floatmode_real = 'maxprec_equal' floatmode_imag = 'maxprec' self.real_format = FloatingFormat(x.real, precision, floatmode_real, suppress_small, sign=sign, legacy=legacy) self.imag_format = FloatingFormat(x.imag, precision, floatmode_imag, suppress_small, sign='+', legacy=legacy) def __call__(self, x): r = self.real_format(x.real) i = self.imag_format(x.imag) sp = len(i.rstrip()) i = i[:sp] + 'j' + i[sp:] return r + i class _TimelikeFormat: def __init__(self, data): non_nat = data[~isnat(data)] if len(non_nat) > 0: max_str_len = max(len(self._format_non_nat(np.max(non_nat))), len(self._format_non_nat(np.min(non_nat)))) else: max_str_len = 0 if len(non_nat) < data.size: max_str_len = max(max_str_len, 5) self._format = '%{}s'.format(max_str_len) self._nat = "'NaT'".rjust(max_str_len) def _format_non_nat(self, x): raise NotImplementedError def __call__(self, x): if isnat(x): return self._nat else: return self._format % self._format_non_nat(x) class DatetimeFormat(_TimelikeFormat): def __init__(self, x, unit=None, timezone=None, casting='same_kind', legacy=False): if unit is None: if x.dtype.kind == 'M': unit = datetime_data(x.dtype)[0] else: unit = 's' if timezone is None: timezone = 'naive' self.timezone = timezone self.unit = unit self.casting = casting self.legacy = legacy super().__init__(x) def __call__(self, x): if self.legacy <= 113: return self._format_non_nat(x) return super().__call__(x) def _format_non_nat(self, x): return "'%s'" % datetime_as_string(x, unit=self.unit, timezone=self.timezone, casting=self.casting) class TimedeltaFormat(_TimelikeFormat): def _format_non_nat(self, x): return str(x.astype('i8')) class SubArrayFormat: def __init__(self, format_function, **options): self.format_function = format_function self.threshold = options['threshold'] self.edge_items = options['edgeitems'] def __call__(self, a): self.summary_insert = '...' if a.size > self.threshold else '' return self.format_array(a) def format_array(self, a): if np.ndim(a) == 0: return self.format_function(a) if self.summary_insert and a.shape[0] > 2 * self.edge_items: formatted = [self.format_array(a_) for a_ in a[:self.edge_items]] + [self.summary_insert] + [self.format_array(a_) for a_ in a[-self.edge_items:]] else: formatted = [self.format_array(a_) for a_ in a] return '[' + ', '.join(formatted) + ']' class StructuredVoidFormat: def __init__(self, format_functions): self.format_functions = format_functions @classmethod def from_data(cls, data, **options): format_functions = [] for field_name in data.dtype.names: format_function = _get_format_function(data[field_name], **options) if data.dtype[field_name].shape != (): format_function = SubArrayFormat(format_function, **options) format_functions.append(format_function) return cls(format_functions) def __call__(self, x): str_fields = [format_function(field) for (field, format_function) in zip(x, self.format_functions)] if len(str_fields) == 1: return '({},)'.format(str_fields[0]) else: return '({})'.format(', '.join(str_fields)) def _void_scalar_to_string(x, is_repr=True): options = format_options.get().copy() if options['legacy'] <= 125: return StructuredVoidFormat.from_data(array(x), **options)(x) if options.get('formatter') is None: options['formatter'] = {} options['formatter'].setdefault('float_kind', str) val_repr = StructuredVoidFormat.from_data(array(x), **options)(x) if not is_repr: return val_repr cls = type(x) cls_fqn = cls.__module__.replace('numpy', 'np') + '.' + cls.__name__ void_dtype = np.dtype((np.void, x.dtype)) return f'{cls_fqn}({val_repr}, dtype={void_dtype!s})' _typelessdata = [int_, float64, complex128, _nt.bool] def dtype_is_implied(dtype): dtype = np.dtype(dtype) if format_options.get()['legacy'] <= 113 and dtype.type == np.bool: return False if dtype.names is not None: return False if not dtype.isnative: return False return dtype.type in _typelessdata def dtype_short_repr(dtype): if type(dtype).__repr__ != np.dtype.__repr__: return repr(dtype) if dtype.names is not None: return str(dtype) elif issubclass(dtype.type, flexible): return "'%s'" % str(dtype) typename = dtype.name if not dtype.isnative: return "'%s'" % str(dtype) if typename and (not (typename[0].isalpha() and typename.isalnum())): typename = repr(typename) return typename def _array_repr_implementation(arr, max_line_width=None, precision=None, suppress_small=None, array2string=array2string): current_options = format_options.get() override_repr = current_options['override_repr'] if override_repr is not None: return override_repr(arr) if max_line_width is None: max_line_width = current_options['linewidth'] if type(arr) is not ndarray: class_name = type(arr).__name__ else: class_name = 'array' skipdtype = dtype_is_implied(arr.dtype) and arr.size > 0 prefix = class_name + '(' suffix = ')' if skipdtype else ',' if current_options['legacy'] <= 113 and arr.shape == () and (not arr.dtype.names): lst = repr(arr.item()) elif arr.size > 0 or arr.shape == (0,): lst = array2string(arr, max_line_width, precision, suppress_small, ', ', prefix, suffix=suffix) else: lst = '[], shape=%s' % (repr(arr.shape),) arr_str = prefix + lst + suffix if skipdtype: return arr_str dtype_str = 'dtype={})'.format(dtype_short_repr(arr.dtype)) last_line_len = len(arr_str) - (arr_str.rfind('\n') + 1) spacer = ' ' if current_options['legacy'] <= 113: if issubclass(arr.dtype.type, flexible): spacer = '\n' + ' ' * len(class_name + '(') elif last_line_len + len(dtype_str) + 1 > max_line_width: spacer = '\n' + ' ' * len(class_name + '(') return arr_str + spacer + dtype_str def _array_repr_dispatcher(arr, max_line_width=None, precision=None, suppress_small=None): return (arr,) @array_function_dispatch(_array_repr_dispatcher, module='numpy') def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): return _array_repr_implementation(arr, max_line_width, precision, suppress_small) @_recursive_guard() def _guarded_repr_or_str(v): if isinstance(v, bytes): return repr(v) return str(v) def _array_str_implementation(a, max_line_width=None, precision=None, suppress_small=None, array2string=array2string): if format_options.get()['legacy'] <= 113 and a.shape == () and (not a.dtype.names): return str(a.item()) if a.shape == (): return _guarded_repr_or_str(np.ndarray.__getitem__(a, ())) return array2string(a, max_line_width, precision, suppress_small, ' ', '') def _array_str_dispatcher(a, max_line_width=None, precision=None, suppress_small=None): return (a,) @array_function_dispatch(_array_str_dispatcher, module='numpy') def array_str(a, max_line_width=None, precision=None, suppress_small=None): return _array_str_implementation(a, max_line_width, precision, suppress_small) _array2string_impl = getattr(array2string, '__wrapped__', array2string) _default_array_str = functools.partial(_array_str_implementation, array2string=_array2string_impl) _default_array_repr = functools.partial(_array_repr_implementation, array2string=_array2string_impl) # File: numpy-main/numpy/_core/code_generators/genapi.py """""" import hashlib import io import os import re import sys import importlib.util import textwrap from os.path import join def get_processor(): conv_template_path = os.path.join(os.path.dirname(__file__), '..', '..', 'distutils', 'conv_template.py') spec = importlib.util.spec_from_file_location('conv_template', conv_template_path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod.process_file process_c_file = get_processor() __docformat__ = 'restructuredtext' API_FILES = [join('multiarray', 'alloc.c'), join('multiarray', 'abstractdtypes.c'), join('multiarray', 'arrayfunction_override.c'), join('multiarray', 'array_api_standard.c'), join('multiarray', 'array_assign_array.c'), join('multiarray', 'array_assign_scalar.c'), join('multiarray', 'array_coercion.c'), join('multiarray', 'array_converter.c'), join('multiarray', 'array_method.c'), join('multiarray', 'arrayobject.c'), join('multiarray', 'arraytypes.c.src'), join('multiarray', 'buffer.c'), join('multiarray', 'calculation.c'), join('multiarray', 'common_dtype.c'), join('multiarray', 'conversion_utils.c'), join('multiarray', 'convert.c'), join('multiarray', 'convert_datatype.c'), join('multiarray', 'ctors.c'), join('multiarray', 'datetime.c'), join('multiarray', 'datetime_busday.c'), join('multiarray', 'datetime_busdaycal.c'), join('multiarray', 'datetime_strings.c'), join('multiarray', 'descriptor.c'), join('multiarray', 'dlpack.c'), join('multiarray', 'dtypemeta.c'), join('multiarray', 'einsum.c.src'), join('multiarray', 'public_dtype_api.c'), join('multiarray', 'flagsobject.c'), join('multiarray', 'getset.c'), join('multiarray', 'item_selection.c'), join('multiarray', 'iterators.c'), join('multiarray', 'mapping.c'), join('multiarray', 'methods.c'), join('multiarray', 'multiarraymodule.c'), join('multiarray', 'nditer_api.c'), join('multiarray', 'nditer_constr.c'), join('multiarray', 'nditer_pywrap.c'), join('multiarray', 'nditer_templ.c.src'), join('multiarray', 'number.c'), join('multiarray', 'refcount.c'), join('multiarray', 'scalartypes.c.src'), join('multiarray', 'scalarapi.c'), join('multiarray', 'sequence.c'), join('multiarray', 'shape.c'), join('multiarray', 'stringdtype', 'static_string.c'), join('multiarray', 'strfuncs.c'), join('multiarray', 'usertypes.c'), join('umath', 'dispatching.c'), join('umath', 'extobj.c'), join('umath', 'loops.c.src'), join('umath', 'reduction.c'), join('umath', 'ufunc_object.c'), join('umath', 'ufunc_type_resolution.c'), join('umath', 'wrapping_array_method.c')] THIS_DIR = os.path.dirname(__file__) API_FILES = [os.path.join(THIS_DIR, '..', 'src', a) for a in API_FILES] def file_in_this_dir(filename): return os.path.join(THIS_DIR, filename) def remove_whitespace(s): return ''.join(s.split()) def _repl(str): return str.replace('Bool', 'npy_bool') class MinVersion: def __init__(self, version): (major, minor) = version.split('.') self.version = f'NPY_{major}_{minor}_API_VERSION' def __str__(self): return self.version def add_guard(self, name, normal_define): wrap = textwrap.dedent(f'\n #if NPY_FEATURE_VERSION >= {self.version}\n {{define}}\n #endif') return wrap.format(define=normal_define) class StealRef: def __init__(self, arg): self.arg = arg def __str__(self): try: return ' '.join(('NPY_STEALS_REF_TO_ARG(%d)' % x for x in self.arg)) except TypeError: return 'NPY_STEALS_REF_TO_ARG(%d)' % self.arg class Function: def __init__(self, name, return_type, args, doc=''): self.name = name self.return_type = _repl(return_type) self.args = args self.doc = doc def _format_arg(self, typename, name): if typename.endswith('*'): return typename + name else: return typename + ' ' + name def __str__(self): argstr = ', '.join([self._format_arg(*a) for a in self.args]) if self.doc: doccomment = '/* %s */\n' % self.doc else: doccomment = '' return '%s%s %s(%s)' % (doccomment, self.return_type, self.name, argstr) def api_hash(self): m = hashlib.md5(usedforsecurity=False) m.update(remove_whitespace(self.return_type)) m.update('\x00') m.update(self.name) m.update('\x00') for (typename, name) in self.args: m.update(remove_whitespace(typename)) m.update('\x00') return m.hexdigest()[:8] class ParseError(Exception): def __init__(self, filename, lineno, msg): self.filename = filename self.lineno = lineno self.msg = msg def __str__(self): return '%s:%s:%s' % (self.filename, self.lineno, self.msg) def skip_brackets(s, lbrac, rbrac): count = 0 for (i, c) in enumerate(s): if c == lbrac: count += 1 elif c == rbrac: count -= 1 if count == 0: return i raise ValueError("no match '%s' for '%s' (%r)" % (lbrac, rbrac, s)) def split_arguments(argstr): arguments = [] current_argument = [] i = 0 def finish_arg(): if current_argument: argstr = ''.join(current_argument).strip() m = re.match('(.*(\\s+|\\*))(\\w+)$', argstr) if m: typename = m.group(1).strip() name = m.group(3) else: typename = argstr name = '' arguments.append((typename, name)) del current_argument[:] while i < len(argstr): c = argstr[i] if c == ',': finish_arg() elif c == '(': p = skip_brackets(argstr[i:], '(', ')') current_argument += argstr[i:i + p] i += p - 1 else: current_argument += c i += 1 finish_arg() return arguments def find_functions(filename, tag='API'): if filename.endswith(('.c.src', '.h.src')): fo = io.StringIO(process_c_file(filename)) else: fo = open(filename, 'r') functions = [] return_type = None function_name = None function_args = [] doclist = [] (SCANNING, STATE_DOC, STATE_RETTYPE, STATE_NAME, STATE_ARGS) = list(range(5)) state = SCANNING tagcomment = '/*' + tag for (lineno, line) in enumerate(fo): try: line = line.strip() if state == SCANNING: if line.startswith(tagcomment): if line.endswith('*/'): state = STATE_RETTYPE else: state = STATE_DOC elif state == STATE_DOC: if line.startswith('*/'): state = STATE_RETTYPE else: line = line.lstrip(' *') doclist.append(line) elif state == STATE_RETTYPE: m = re.match('NPY_NO_EXPORT\\s+(.*)$', line) if m: line = m.group(1) return_type = line state = STATE_NAME elif state == STATE_NAME: m = re.match('(\\w+)\\s*\\(', line) if m: function_name = m.group(1) else: raise ParseError(filename, lineno + 1, 'could not find function name') function_args.append(line[m.end():]) state = STATE_ARGS elif state == STATE_ARGS: if line.startswith('{'): fargs_str = ' '.join(function_args).rstrip()[:-1].rstrip() fargs = split_arguments(fargs_str) f = Function(function_name, return_type, fargs, '\n'.join(doclist)) functions.append(f) return_type = None function_name = None function_args = [] doclist = [] state = SCANNING else: function_args.append(line) except ParseError: raise except Exception as e: msg = 'see chained exception for details' raise ParseError(filename, lineno + 1, msg) from e fo.close() return functions def write_file(filename, data): if os.path.exists(filename): with open(filename) as f: if data == f.read(): return with open(filename, 'w') as fid: fid.write(data) class TypeApi: def __init__(self, name, index, ptr_cast, api_name, internal_type=None): self.index = index self.name = name self.ptr_cast = ptr_cast self.api_name = api_name self.internal_type = internal_type def define_from_array_api_string(self): return '#define %s (*(%s *)%s[%d])' % (self.name, self.ptr_cast, self.api_name, self.index) def array_api_define(self): return ' (void *) &%s' % self.name def internal_define(self): if self.internal_type is None: return f'extern NPY_NO_EXPORT {self.ptr_cast} {self.name};\n' mangled_name = f'{self.name}Full' astr = f'extern NPY_NO_EXPORT {self.internal_type} {mangled_name};\n#define {self.name} (*({self.ptr_cast} *)(&{mangled_name}))\n' return astr class GlobalVarApi: def __init__(self, name, index, type, api_name): self.name = name self.index = index self.type = type self.api_name = api_name def define_from_array_api_string(self): return '#define %s (*(%s *)%s[%d])' % (self.name, self.type, self.api_name, self.index) def array_api_define(self): return ' (%s *) &%s' % (self.type, self.name) def internal_define(self): astr = 'extern NPY_NO_EXPORT %(type)s %(name)s;\n' % {'type': self.type, 'name': self.name} return astr class BoolValuesApi: def __init__(self, name, index, api_name): self.name = name self.index = index self.type = 'PyBoolScalarObject' self.api_name = api_name def define_from_array_api_string(self): return '#define %s ((%s *)%s[%d])' % (self.name, self.type, self.api_name, self.index) def array_api_define(self): return ' (void *) &%s' % self.name def internal_define(self): astr = 'extern NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2];\n' return astr class FunctionApi: def __init__(self, name, index, annotations, return_type, args, api_name): self.name = name self.index = index self.min_version = None self.annotations = [] for annotation in annotations: if type(annotation).__name__ == 'StealRef': self.annotations.append(annotation) elif type(annotation).__name__ == 'MinVersion': if self.min_version is not None: raise ValueError('Two minimum versions specified!') self.min_version = annotation else: raise ValueError(f'unknown annotation {annotation}') self.return_type = return_type self.args = args self.api_name = api_name def _argtypes_string(self): if not self.args: return 'void' argstr = ', '.join([_repl(a[0]) for a in self.args]) return argstr def define_from_array_api_string(self): arguments = self._argtypes_string() define = textwrap.dedent(f' #define {self.name} \\\n (*({self.return_type} (*)({arguments})) \\\n {self.api_name}[{self.index}])') if self.min_version is not None: define = self.min_version.add_guard(self.name, define) return define def array_api_define(self): return ' (void *) %s' % self.name def internal_define(self): annstr = [str(a) for a in self.annotations] annstr = ' '.join(annstr) astr = 'NPY_NO_EXPORT %s %s %s \\\n (%s);' % (annstr, self.return_type, self.name, self._argtypes_string()) return astr def order_dict(d): o = list(d.items()) def _key(x): return x[1] + (x[0],) return sorted(o, key=_key) def merge_api_dicts(dicts): ret = {} for d in dicts: for (k, v) in d.items(): ret[k] = v return ret def check_api_dict(d): removed = set(d.pop('__unused_indices__', [])) index_d = {k: v[0] for (k, v) in d.items()} revert_dict = {v: k for (k, v) in index_d.items()} if not len(revert_dict) == len(index_d): doubled = {} for (name, index) in index_d.items(): try: doubled[index].append(name) except KeyError: doubled[index] = [name] fmt = 'Same index has been used twice in api definition: {}' val = ''.join(('\n\tindex {} -> {}'.format(index, names) for (index, names) in doubled.items() if len(names) != 1)) raise ValueError(fmt.format(val)) indexes = set(index_d.values()) expected = set(range(len(indexes) + len(removed))) if not indexes.isdisjoint(removed): raise ValueError(f'API index used but marked unused: {indexes.intersection(removed)}') if indexes.union(removed) != expected: diff = expected.symmetric_difference(indexes.union(removed)) msg = 'There are some holes in the API indexing: (symmetric diff is %s)' % diff raise ValueError(msg) def get_api_functions(tagname, api_dict): functions = [] for f in API_FILES: functions.extend(find_functions(f, tagname)) dfunctions = [(api_dict[func.name][0], func) for func in functions] dfunctions.sort() return [a[1] for a in dfunctions] def fullapi_hash(api_dicts): a = [] for d in api_dicts: d = d.copy() d.pop('__unused_indices__', None) for (name, data) in order_dict(d): a.extend(name) a.extend(','.join(map(str, data))) return hashlib.md5(''.join(a).encode('ascii'), usedforsecurity=False).hexdigest() VERRE = re.compile('(^0x[\\da-f]{8})\\s*=\\s*([\\da-f]{32})') def get_versions_hash(): d = [] file = os.path.join(os.path.dirname(__file__), 'cversions.txt') with open(file) as fid: for line in fid: m = VERRE.match(line) if m: d.append((int(m.group(1), 16), m.group(2))) return dict(d) def main(): tagname = sys.argv[1] order_file = sys.argv[2] functions = get_api_functions(tagname, order_file) m = hashlib.md5(tagname, usedforsecurity=False) for func in functions: print(func) ah = func.api_hash() m.update(ah) print(hex(int(ah, 16))) print(hex(int(m.hexdigest()[:8], 16))) if __name__ == '__main__': main() # File: numpy-main/numpy/_core/code_generators/generate_numpy_api.py import os import argparse import genapi from genapi import TypeApi, GlobalVarApi, FunctionApi, BoolValuesApi import numpy_api h_template = '\n#if defined(_MULTIARRAYMODULE) || defined(WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE)\n\ntypedef struct {\n PyObject_HEAD\n npy_bool obval;\n} PyBoolScalarObject;\n\nextern NPY_NO_EXPORT PyTypeObject PyArrayNeighborhoodIter_Type;\nextern NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2];\n\n%s\n\n#else\n\n#if defined(PY_ARRAY_UNIQUE_SYMBOL)\n #define PyArray_API PY_ARRAY_UNIQUE_SYMBOL\n #define _NPY_VERSION_CONCAT_HELPER2(x, y) x ## y\n #define _NPY_VERSION_CONCAT_HELPER(arg) \\\n _NPY_VERSION_CONCAT_HELPER2(arg, PyArray_RUNTIME_VERSION)\n #define PyArray_RUNTIME_VERSION \\\n _NPY_VERSION_CONCAT_HELPER(PY_ARRAY_UNIQUE_SYMBOL)\n#endif\n\n/* By default do not export API in an .so (was never the case on windows) */\n#ifndef NPY_API_SYMBOL_ATTRIBUTE\n #define NPY_API_SYMBOL_ATTRIBUTE NPY_VISIBILITY_HIDDEN\n#endif\n\n#if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY)\nextern NPY_API_SYMBOL_ATTRIBUTE void **PyArray_API;\nextern NPY_API_SYMBOL_ATTRIBUTE int PyArray_RUNTIME_VERSION;\n#else\n#if defined(PY_ARRAY_UNIQUE_SYMBOL)\nNPY_API_SYMBOL_ATTRIBUTE void **PyArray_API;\nNPY_API_SYMBOL_ATTRIBUTE int PyArray_RUNTIME_VERSION;\n#else\nstatic void **PyArray_API = NULL;\nstatic int PyArray_RUNTIME_VERSION = 0;\n#endif\n#endif\n\n%s\n\n/*\n * The DType classes are inconvenient for the Python generation so exposed\n * manually in the header below (may be moved).\n */\n#include "numpy/_public_dtype_api_table.h"\n\n#if !defined(NO_IMPORT_ARRAY) && !defined(NO_IMPORT)\nstatic int\n_import_array(void)\n{\n int st;\n PyObject *numpy = PyImport_ImportModule("numpy._core._multiarray_umath");\n if (numpy == NULL && PyErr_ExceptionMatches(PyExc_ModuleNotFoundError)) {\n PyErr_Clear();\n numpy = PyImport_ImportModule("numpy.core._multiarray_umath");\n }\n\n if (numpy == NULL) {\n return -1;\n }\n\n PyObject *c_api = PyObject_GetAttrString(numpy, "_ARRAY_API");\n Py_DECREF(numpy);\n if (c_api == NULL) {\n return -1;\n }\n\n if (!PyCapsule_CheckExact(c_api)) {\n PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is not PyCapsule object");\n Py_DECREF(c_api);\n return -1;\n }\n PyArray_API = (void **)PyCapsule_GetPointer(c_api, NULL);\n Py_DECREF(c_api);\n if (PyArray_API == NULL) {\n PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is NULL pointer");\n return -1;\n }\n\n /*\n * On exceedingly few platforms these sizes may not match, in which case\n * We do not support older NumPy versions at all.\n */\n if (sizeof(Py_ssize_t) != sizeof(Py_intptr_t) &&\n PyArray_RUNTIME_VERSION < NPY_2_0_API_VERSION) {\n PyErr_Format(PyExc_RuntimeError,\n "module compiled against NumPy 2.0 but running on NumPy 1.x. "\n "Unfortunately, this is not supported on niche platforms where "\n "`sizeof(size_t) != sizeof(inptr_t)`.");\n }\n /*\n * Perform runtime check of C API version. As of now NumPy 2.0 is ABI\n * backwards compatible (in the exposed feature subset!) for all practical\n * purposes.\n */\n if (NPY_VERSION < PyArray_GetNDArrayCVersion()) {\n PyErr_Format(PyExc_RuntimeError, "module compiled against "\\\n "ABI version 0x%%x but this version of numpy is 0x%%x", \\\n (int) NPY_VERSION, (int) PyArray_GetNDArrayCVersion());\n return -1;\n }\n PyArray_RUNTIME_VERSION = (int)PyArray_GetNDArrayCFeatureVersion();\n if (NPY_FEATURE_VERSION > PyArray_RUNTIME_VERSION) {\n PyErr_Format(PyExc_RuntimeError,\n "module was compiled against NumPy C-API version 0x%%x "\n "(NumPy " NPY_FEATURE_VERSION_STRING ") "\n "but the running NumPy has C-API version 0x%%x. "\n "Check the section C-API incompatibility at the "\n "Troubleshooting ImportError section at "\n "https://numpy.org/devdocs/user/troubleshooting-importerror.html"\n "#c-api-incompatibility "\n "for indications on how to solve this problem.",\n (int)NPY_FEATURE_VERSION, PyArray_RUNTIME_VERSION);\n return -1;\n }\n\n /*\n * Perform runtime check of endianness and check it matches the one set by\n * the headers (npy_endian.h) as a safeguard\n */\n st = PyArray_GetEndianness();\n if (st == NPY_CPU_UNKNOWN_ENDIAN) {\n PyErr_SetString(PyExc_RuntimeError,\n "FATAL: module compiled as unknown endian");\n return -1;\n }\n#if NPY_BYTE_ORDER == NPY_BIG_ENDIAN\n if (st != NPY_CPU_BIG) {\n PyErr_SetString(PyExc_RuntimeError,\n "FATAL: module compiled as big endian, but "\n "detected different endianness at runtime");\n return -1;\n }\n#elif NPY_BYTE_ORDER == NPY_LITTLE_ENDIAN\n if (st != NPY_CPU_LITTLE) {\n PyErr_SetString(PyExc_RuntimeError,\n "FATAL: module compiled as little endian, but "\n "detected different endianness at runtime");\n return -1;\n }\n#endif\n\n return 0;\n}\n\n#define import_array() { \\\n if (_import_array() < 0) { \\\n PyErr_Print(); \\\n PyErr_SetString( \\\n PyExc_ImportError, \\\n "numpy._core.multiarray failed to import" \\\n ); \\\n return NULL; \\\n } \\\n}\n\n#define import_array1(ret) { \\\n if (_import_array() < 0) { \\\n PyErr_Print(); \\\n PyErr_SetString( \\\n PyExc_ImportError, \\\n "numpy._core.multiarray failed to import" \\\n ); \\\n return ret; \\\n } \\\n}\n\n#define import_array2(msg, ret) { \\\n if (_import_array() < 0) { \\\n PyErr_Print(); \\\n PyErr_SetString(PyExc_ImportError, msg); \\\n return ret; \\\n } \\\n}\n\n#endif\n\n#endif\n' c_template = '\n/* These pointers will be stored in the C-object for use in other\n extension modules\n*/\n\nvoid *PyArray_API[] = {\n%s\n};\n' def generate_api(output_dir, force=False): basename = 'multiarray_api' h_file = os.path.join(output_dir, '__%s.h' % basename) c_file = os.path.join(output_dir, '__%s.c' % basename) targets = (h_file, c_file) sources = numpy_api.multiarray_api do_generate_api(targets, sources) return targets def do_generate_api(targets, sources): header_file = targets[0] c_file = targets[1] global_vars = sources[0] scalar_bool_values = sources[1] types_api = sources[2] multiarray_funcs = sources[3] multiarray_api = sources[:] module_list = [] extension_list = [] init_list = [] multiarray_api_index = genapi.merge_api_dicts(multiarray_api) unused_index_max = max(multiarray_api_index.get('__unused_indices__', 0)) genapi.check_api_dict(multiarray_api_index) numpyapi_list = genapi.get_api_functions('NUMPY_API', multiarray_funcs) api_name = 'PyArray_API' multiarray_api_dict = {} for f in numpyapi_list: name = f.name index = multiarray_funcs[name][0] annotations = multiarray_funcs[name][1:] multiarray_api_dict[f.name] = FunctionApi(f.name, index, annotations, f.return_type, f.args, api_name) for (name, val) in global_vars.items(): (index, type) = val multiarray_api_dict[name] = GlobalVarApi(name, index, type, api_name) for (name, val) in scalar_bool_values.items(): index = val[0] multiarray_api_dict[name] = BoolValuesApi(name, index, api_name) for (name, val) in types_api.items(): index = val[0] internal_type = None if len(val) == 1 else val[1] multiarray_api_dict[name] = TypeApi(name, index, 'PyTypeObject', api_name, internal_type) if len(multiarray_api_dict) != len(multiarray_api_index): keys_dict = set(multiarray_api_dict.keys()) keys_index = set(multiarray_api_index.keys()) raise AssertionError('Multiarray API size mismatch - index has extra keys {}, dict has extra keys {}'.format(keys_index - keys_dict, keys_dict - keys_index)) extension_list = [] for (name, index) in genapi.order_dict(multiarray_api_index): api_item = multiarray_api_dict[name] while len(init_list) < api_item.index: init_list.append(' NULL') extension_list.append(api_item.define_from_array_api_string()) init_list.append(api_item.array_api_define()) module_list.append(api_item.internal_define()) while len(init_list) <= unused_index_max: init_list.append(' NULL') s = h_template % ('\n'.join(module_list), '\n'.join(extension_list)) genapi.write_file(header_file, s) s = c_template % ',\n'.join(init_list) genapi.write_file(c_file, s) return targets def main(): parser = argparse.ArgumentParser() parser.add_argument('-o', '--outdir', type=str, help='Path to the output directory') parser.add_argument('-i', '--ignore', type=str, help='An ignored input - may be useful to add a dependency between custom targets') args = parser.parse_args() outdir_abs = os.path.join(os.getcwd(), args.outdir) generate_api(outdir_abs) if __name__ == '__main__': main() # File: numpy-main/numpy/_core/code_generators/generate_ufunc_api.py import os import argparse import genapi from genapi import TypeApi, FunctionApi import numpy_api h_template = '\n#ifdef _UMATHMODULE\n\nextern NPY_NO_EXPORT PyTypeObject PyUFunc_Type;\n\n%s\n\n#else\n\n#if defined(PY_UFUNC_UNIQUE_SYMBOL)\n#define PyUFunc_API PY_UFUNC_UNIQUE_SYMBOL\n#endif\n\n/* By default do not export API in an .so (was never the case on windows) */\n#ifndef NPY_API_SYMBOL_ATTRIBUTE\n #define NPY_API_SYMBOL_ATTRIBUTE NPY_VISIBILITY_HIDDEN\n#endif\n\n#if defined(NO_IMPORT) || defined(NO_IMPORT_UFUNC)\nextern NPY_API_SYMBOL_ATTRIBUTE void **PyUFunc_API;\n#else\n#if defined(PY_UFUNC_UNIQUE_SYMBOL)\nNPY_API_SYMBOL_ATTRIBUTE void **PyUFunc_API;\n#else\nstatic void **PyUFunc_API=NULL;\n#endif\n#endif\n\n%s\n\nstatic inline int\n_import_umath(void)\n{\n PyObject *numpy = PyImport_ImportModule("numpy._core._multiarray_umath");\n if (numpy == NULL && PyErr_ExceptionMatches(PyExc_ModuleNotFoundError)) {\n PyErr_Clear();\n numpy = PyImport_ImportModule("numpy.core._multiarray_umath");\n }\n\n if (numpy == NULL) {\n PyErr_SetString(PyExc_ImportError,\n "_multiarray_umath failed to import");\n return -1;\n }\n\n PyObject *c_api = PyObject_GetAttrString(numpy, "_UFUNC_API");\n Py_DECREF(numpy);\n if (c_api == NULL) {\n PyErr_SetString(PyExc_AttributeError, "_UFUNC_API not found");\n return -1;\n }\n\n if (!PyCapsule_CheckExact(c_api)) {\n PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is not PyCapsule object");\n Py_DECREF(c_api);\n return -1;\n }\n PyUFunc_API = (void **)PyCapsule_GetPointer(c_api, NULL);\n Py_DECREF(c_api);\n if (PyUFunc_API == NULL) {\n PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is NULL pointer");\n return -1;\n }\n return 0;\n}\n\n#define import_umath() \\\n do {\\\n UFUNC_NOFPE\\\n if (_import_umath() < 0) {\\\n PyErr_Print();\\\n PyErr_SetString(PyExc_ImportError,\\\n "numpy._core.umath failed to import");\\\n return NULL;\\\n }\\\n } while(0)\n\n#define import_umath1(ret) \\\n do {\\\n UFUNC_NOFPE\\\n if (_import_umath() < 0) {\\\n PyErr_Print();\\\n PyErr_SetString(PyExc_ImportError,\\\n "numpy._core.umath failed to import");\\\n return ret;\\\n }\\\n } while(0)\n\n#define import_umath2(ret, msg) \\\n do {\\\n UFUNC_NOFPE\\\n if (_import_umath() < 0) {\\\n PyErr_Print();\\\n PyErr_SetString(PyExc_ImportError, msg);\\\n return ret;\\\n }\\\n } while(0)\n\n#define import_ufunc() \\\n do {\\\n UFUNC_NOFPE\\\n if (_import_umath() < 0) {\\\n PyErr_Print();\\\n PyErr_SetString(PyExc_ImportError,\\\n "numpy._core.umath failed to import");\\\n }\\\n } while(0)\n\n\nstatic inline int\nPyUFunc_ImportUFuncAPI()\n{\n if (NPY_UNLIKELY(PyUFunc_API == NULL)) {\n import_umath1(-1);\n }\n return 0;\n}\n\n#endif\n' c_template = '\n/* These pointers will be stored in the C-object for use in other\n extension modules\n*/\n\nvoid *PyUFunc_API[] = {\n%s\n};\n' def generate_api(output_dir, force=False): basename = 'ufunc_api' h_file = os.path.join(output_dir, '__%s.h' % basename) c_file = os.path.join(output_dir, '__%s.c' % basename) targets = (h_file, c_file) sources = ['ufunc_api_order.txt'] do_generate_api(targets, sources) return targets def do_generate_api(targets, sources): header_file = targets[0] c_file = targets[1] ufunc_api_index = genapi.merge_api_dicts((numpy_api.ufunc_funcs_api, numpy_api.ufunc_types_api)) genapi.check_api_dict(ufunc_api_index) ufunc_api_list = genapi.get_api_functions('UFUNC_API', numpy_api.ufunc_funcs_api) ufunc_api_dict = {} api_name = 'PyUFunc_API' for f in ufunc_api_list: name = f.name index = ufunc_api_index[name][0] annotations = ufunc_api_index[name][1:] ufunc_api_dict[name] = FunctionApi(f.name, index, annotations, f.return_type, f.args, api_name) for (name, val) in numpy_api.ufunc_types_api.items(): index = val[0] ufunc_api_dict[name] = TypeApi(name, index, 'PyTypeObject', api_name) module_list = [] extension_list = [] init_list = [] for (name, index) in genapi.order_dict(ufunc_api_index): api_item = ufunc_api_dict[name] while len(init_list) < api_item.index: init_list.append(' NULL') extension_list.append(api_item.define_from_array_api_string()) init_list.append(api_item.array_api_define()) module_list.append(api_item.internal_define()) s = h_template % ('\n'.join(module_list), '\n'.join(extension_list)) genapi.write_file(header_file, s) s = c_template % ',\n'.join(init_list) genapi.write_file(c_file, s) return targets def main(): parser = argparse.ArgumentParser() parser.add_argument('-o', '--outdir', type=str, help='Path to the output directory') args = parser.parse_args() outdir_abs = os.path.join(os.getcwd(), args.outdir) generate_api(outdir_abs) if __name__ == '__main__': main() # File: numpy-main/numpy/_core/code_generators/generate_umath.py """""" import os import re import textwrap import argparse Zero = 'PyLong_FromLong(0)' One = 'PyLong_FromLong(1)' True_ = '(Py_INCREF(Py_True), Py_True)' False_ = '(Py_INCREF(Py_False), Py_False)' None_ = object() AllOnes = 'PyLong_FromLong(-1)' MinusInfinity = 'PyFloat_FromDouble(-NPY_INFINITY)' ReorderableNone = '(Py_INCREF(Py_None), Py_None)' class docstrings: @staticmethod def get(place): return 'DOC_' + place.upper().replace('.', '_') class FullTypeDescr: pass class FuncNameSuffix: def __init__(self, suffix): self.suffix = suffix class TypeDescription: def __init__(self, type, f=None, in_=None, out=None, astype=None, cfunc_alias=None, dispatch=None): self.type = type self.func_data = f if astype is None: astype = {} self.astype_dict = astype if in_ is not None: in_ = in_.replace('P', type) self.in_ = in_ if out is not None: out = out.replace('P', type) self.out = out self.cfunc_alias = cfunc_alias self.dispatch = dispatch def finish_signature(self, nin, nout): if self.in_ is None: self.in_ = self.type * nin assert len(self.in_) == nin if self.out is None: self.out = self.type * nout assert len(self.out) == nout self.astype = self.astype_dict.get(self.type, None) def _check_order(types1, types2): dtype_order = bints + 'kK' + times + flts + cmplxP + 'O' for (t1, t2) in zip(types1, types2): if t1 in 'OP' or t2 in 'OP': return True if t1 in 'mM' or t2 in 'mM': return True t1i = dtype_order.index(t1) t2i = dtype_order.index(t2) if t1i < t2i: return if t2i > t1i: break if types1 == 'QQ?' and types2 == 'qQ?': return raise TypeError(f'Input dtypes are unsorted or duplicate: {types1} and {types2}') def check_td_order(tds): signatures = [t.in_ + t.out for t in tds] for (prev_i, sign) in enumerate(signatures[1:]): if sign in signatures[:prev_i + 1]: continue _check_order(signatures[prev_i], sign) _floatformat_map = dict(e='npy_%sf', f='npy_%sf', d='npy_%s', g='npy_%sl', F='nc_%sf', D='nc_%s', G='nc_%sl') def build_func_data(types, f): func_data = [_floatformat_map.get(t, '%s') % (f,) for t in types] return func_data def TD(types, f=None, astype=None, in_=None, out=None, cfunc_alias=None, dispatch=None): if f is not None: if isinstance(f, str): func_data = build_func_data(types, f) elif len(f) != len(types): raise ValueError('Number of types and f do not match') else: func_data = f else: func_data = (None,) * len(types) if isinstance(in_, str): in_ = (in_,) * len(types) elif in_ is None: in_ = (None,) * len(types) elif len(in_) != len(types): raise ValueError('Number of types and inputs do not match') if isinstance(out, str): out = (out,) * len(types) elif out is None: out = (None,) * len(types) elif len(out) != len(types): raise ValueError('Number of types and outputs do not match') tds = [] for (t, fd, i, o) in zip(types, func_data, in_, out): if dispatch: dispt = ([k for (k, v) in dispatch if t in v] + [None])[0] else: dispt = None tds.append(TypeDescription(t, f=fd, in_=i, out=o, astype=astype, cfunc_alias=cfunc_alias, dispatch=dispt)) return tds class Ufunc: def __init__(self, nin, nout, identity, docstring, typereso, *type_descriptions, signature=None, indexed=''): self.nin = nin self.nout = nout if identity is None: identity = None_ self.identity = identity self.docstring = docstring self.typereso = typereso self.type_descriptions = [] self.signature = signature self.indexed = indexed for td in type_descriptions: self.type_descriptions.extend(td) for td in self.type_descriptions: td.finish_signature(self.nin, self.nout) check_td_order(self.type_descriptions) import string UPPER_TABLE = bytes.maketrans(bytes(string.ascii_lowercase, 'ascii'), bytes(string.ascii_uppercase, 'ascii')) def english_upper(s): uppered = s.translate(UPPER_TABLE) return uppered chartoname = {'?': 'bool', 'b': 'byte', 'B': 'ubyte', 'h': 'short', 'H': 'ushort', 'i': 'int', 'I': 'uint', 'l': 'long', 'L': 'ulong', 'k': 'int64', 'K': 'uint64', 'q': 'longlong', 'Q': 'ulonglong', 'e': 'half', 'f': 'float', 'd': 'double', 'g': 'longdouble', 'F': 'cfloat', 'D': 'cdouble', 'G': 'clongdouble', 'M': 'datetime', 'm': 'timedelta', 'O': 'OBJECT', 'P': 'OBJECT'} no_obj_bool = 'bBhHiIlLqQefdgFDGmM' noobj = '?' + no_obj_bool all = '?bBhHiIlLqQefdgFDGOmM' O = 'O' P = 'P' ints = 'bBhHiIlLqQ' sints = 'bhilq' uints = 'BHILQ' times = 'Mm' timedeltaonly = 'm' intsO = ints + O bints = '?' + ints bintsO = bints + O flts = 'efdg' fltsO = flts + O fltsP = flts + P cmplx = 'FDG' cmplxvec = 'FD' cmplxO = cmplx + O cmplxP = cmplx + P inexact = flts + cmplx inexactvec = 'fd' noint = inexact + O nointP = inexact + P allP = bints + times + flts + cmplxP nobool_or_obj = noobj[1:] nobool_or_datetime = noobj[1:-1] + O intflt = ints + flts intfltcmplx = ints + flts + cmplx nocmplx = bints + times + flts nocmplxO = nocmplx + O nocmplxP = nocmplx + P notimes_or_obj = bints + inexact nodatetime_or_obj = bints + inexact no_bool_times_obj = ints + inexact int64 = 'k' uint64 = 'K' defdict = {'add': Ufunc(2, 1, Zero, docstrings.get('numpy._core.umath.add'), 'PyUFunc_AdditionTypeResolver', TD('?', cfunc_alias='logical_or', dispatch=[('loops_logical', '?')]), TD(no_bool_times_obj, dispatch=[('loops_arithm_fp', 'fdFD'), ('loops_autovec', ints)]), [TypeDescription('M', FullTypeDescr, 'Mm', 'M'), TypeDescription('m', FullTypeDescr, 'mm', 'm'), TypeDescription('M', FullTypeDescr, 'mM', 'M')], TD(O, f='PyNumber_Add'), indexed=intfltcmplx), 'subtract': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.subtract'), 'PyUFunc_SubtractionTypeResolver', TD(no_bool_times_obj, dispatch=[('loops_arithm_fp', 'fdFD'), ('loops_autovec', ints)]), [TypeDescription('M', FullTypeDescr, 'Mm', 'M'), TypeDescription('m', FullTypeDescr, 'mm', 'm'), TypeDescription('M', FullTypeDescr, 'MM', 'm')], TD(O, f='PyNumber_Subtract'), indexed=intfltcmplx), 'multiply': Ufunc(2, 1, One, docstrings.get('numpy._core.umath.multiply'), 'PyUFunc_MultiplicationTypeResolver', TD('?', cfunc_alias='logical_and', dispatch=[('loops_logical', '?')]), TD(no_bool_times_obj, dispatch=[('loops_arithm_fp', 'fdFD'), ('loops_autovec', ints)]), [TypeDescription('m', FullTypeDescr, 'mq', 'm'), TypeDescription('m', FullTypeDescr, 'qm', 'm'), TypeDescription('m', FullTypeDescr, 'md', 'm'), TypeDescription('m', FullTypeDescr, 'dm', 'm')], TD(O, f='PyNumber_Multiply'), indexed=intfltcmplx), 'floor_divide': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.floor_divide'), 'PyUFunc_DivisionTypeResolver', TD(ints, cfunc_alias='divide', dispatch=[('loops_arithmetic', 'bBhHiIlLqQ')]), TD(flts), [TypeDescription('m', FullTypeDescr, 'mq', 'm'), TypeDescription('m', FullTypeDescr, 'md', 'm'), TypeDescription('m', FullTypeDescr, 'mm', 'q')], TD(O, f='PyNumber_FloorDivide'), indexed=flts + ints), 'divide': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.divide'), 'PyUFunc_TrueDivisionTypeResolver', TD(flts + cmplx, cfunc_alias='divide', dispatch=[('loops_arithm_fp', 'fd')]), [TypeDescription('m', FullTypeDescr, 'mq', 'm', cfunc_alias='divide'), TypeDescription('m', FullTypeDescr, 'md', 'm', cfunc_alias='divide'), TypeDescription('m', FullTypeDescr, 'mm', 'd', cfunc_alias='divide')], TD(O, f='PyNumber_TrueDivide'), indexed=flts), 'conjugate': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.conjugate'), None, TD(ints + flts + cmplx, dispatch=[('loops_arithm_fp', 'FD'), ('loops_autovec', ints)]), TD(P, f='conjugate')), 'fmod': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.fmod'), None, TD(ints, dispatch=[('loops_modulo', ints)]), TD(flts, f='fmod', astype={'e': 'f'}), TD(P, f='fmod')), 'square': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.square'), None, TD(ints + inexact, dispatch=[('loops_unary_fp', 'fd'), ('loops_arithm_fp', 'FD'), ('loops_autovec', ints)]), TD(O, f='Py_square')), 'reciprocal': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.reciprocal'), None, TD(ints + inexact, dispatch=[('loops_unary_fp', 'fd'), ('loops_autovec', ints)]), TD(O, f='Py_reciprocal')), '_ones_like': Ufunc(1, 1, None, docstrings.get('numpy._core.umath._ones_like'), 'PyUFunc_OnesLikeTypeResolver', TD(noobj), TD(O, f='Py_get_one')), 'power': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.power'), None, TD(ints), TD('e', f='pow', astype={'e': 'f'}), TD('fd', dispatch=[('loops_umath_fp', 'fd')]), TD(inexact, f='pow', astype={'e': 'f'}), TD(O, f='npy_ObjectPower')), 'float_power': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.float_power'), None, TD('dgDG', f='pow')), 'absolute': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.absolute'), 'PyUFunc_AbsoluteTypeResolver', TD(bints + flts + timedeltaonly, dispatch=[('loops_unary_fp', 'fd'), ('loops_logical', '?'), ('loops_autovec', ints + 'e')]), TD(cmplx, dispatch=[('loops_unary_complex', 'FD')], out=('f', 'd', 'g')), TD(O, f='PyNumber_Absolute')), '_arg': Ufunc(1, 1, None, docstrings.get('numpy._core.umath._arg'), None, TD(cmplx, out=('f', 'd', 'g'))), 'negative': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.negative'), 'PyUFunc_NegativeTypeResolver', TD(ints + flts + timedeltaonly, dispatch=[('loops_unary', ints + 'fdg')]), TD(cmplx, f='neg'), TD(O, f='PyNumber_Negative')), 'positive': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.positive'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD(ints + flts + timedeltaonly), TD(cmplx, f='pos'), TD(O, f='PyNumber_Positive')), 'sign': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.sign'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD(nobool_or_datetime, dispatch=[('loops_autovec', ints)])), 'greater': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.greater'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(bints, out='?'), [TypeDescription('q', FullTypeDescr, 'qQ', '?'), TypeDescription('q', FullTypeDescr, 'Qq', '?')], TD(inexact + times, out='?', dispatch=[('loops_comparison', bints + 'fd')]), TD('O', out='?'), [TypeDescription('O', FullTypeDescr, 'OO', 'O')]), 'greater_equal': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.greater_equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(bints, out='?'), [TypeDescription('q', FullTypeDescr, 'qQ', '?'), TypeDescription('q', FullTypeDescr, 'Qq', '?')], TD(inexact + times, out='?', dispatch=[('loops_comparison', bints + 'fd')]), TD('O', out='?'), [TypeDescription('O', FullTypeDescr, 'OO', 'O')]), 'less': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.less'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(bints, out='?'), [TypeDescription('q', FullTypeDescr, 'qQ', '?'), TypeDescription('q', FullTypeDescr, 'Qq', '?')], TD(inexact + times, out='?', dispatch=[('loops_comparison', bints + 'fd')]), TD('O', out='?'), [TypeDescription('O', FullTypeDescr, 'OO', 'O')]), 'less_equal': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.less_equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(bints, out='?'), [TypeDescription('q', FullTypeDescr, 'qQ', '?'), TypeDescription('q', FullTypeDescr, 'Qq', '?')], TD(inexact + times, out='?', dispatch=[('loops_comparison', bints + 'fd')]), TD('O', out='?'), [TypeDescription('O', FullTypeDescr, 'OO', 'O')]), 'equal': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(bints, out='?'), [TypeDescription('q', FullTypeDescr, 'qQ', '?'), TypeDescription('q', FullTypeDescr, 'Qq', '?')], TD(inexact + times, out='?', dispatch=[('loops_comparison', bints + 'fd')]), TD('O', out='?'), [TypeDescription('O', FullTypeDescr, 'OO', 'O')]), 'not_equal': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.not_equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(bints, out='?'), [TypeDescription('q', FullTypeDescr, 'qQ', '?'), TypeDescription('q', FullTypeDescr, 'Qq', '?')], TD(inexact + times, out='?', dispatch=[('loops_comparison', bints + 'fd')]), TD('O', out='?'), [TypeDescription('O', FullTypeDescr, 'OO', 'O')]), 'logical_and': Ufunc(2, 1, True_, docstrings.get('numpy._core.umath.logical_and'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(nodatetime_or_obj, out='?', dispatch=[('loops_logical', '?'), ('loops_autovec', ints)]), TD(O, f='npy_ObjectLogicalAnd')), 'logical_not': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.logical_not'), None, TD(nodatetime_or_obj, out='?', dispatch=[('loops_logical', '?'), ('loops_autovec', ints)]), TD(O, f='npy_ObjectLogicalNot')), 'logical_or': Ufunc(2, 1, False_, docstrings.get('numpy._core.umath.logical_or'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(nodatetime_or_obj, out='?', dispatch=[('loops_logical', '?'), ('loops_autovec', ints)]), TD(O, f='npy_ObjectLogicalOr')), 'logical_xor': Ufunc(2, 1, False_, docstrings.get('numpy._core.umath.logical_xor'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD('?', out='?', cfunc_alias='not_equal', dispatch=[('loops_comparison', '?')]), TD(no_bool_times_obj, out='?', dispatch=[('loops_autovec', ints)]), TD(P, f='logical_xor')), 'maximum': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy._core.umath.maximum'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD('?', cfunc_alias='logical_or', dispatch=[('loops_logical', '?')]), TD(no_obj_bool, dispatch=[('loops_minmax', ints + 'fdg')]), TD(O, f='npy_ObjectMax'), indexed=flts + ints), 'minimum': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy._core.umath.minimum'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD('?', cfunc_alias='logical_and', dispatch=[('loops_logical', '?')]), TD(no_obj_bool, dispatch=[('loops_minmax', ints + 'fdg')]), TD(O, f='npy_ObjectMin'), indexed=flts + ints), 'clip': Ufunc(3, 1, ReorderableNone, docstrings.get('numpy._core.umath.clip'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD(noobj), [TypeDescription('O', 'npy_ObjectClip', 'OOO', 'O')]), 'fmax': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy._core.umath.fmax'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD('?', cfunc_alias='logical_or', dispatch=[('loops_logical', '?')]), TD(no_obj_bool, dispatch=[('loops_minmax', 'fdg')]), TD(O, f='npy_ObjectMax'), indexed=flts + ints), 'fmin': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy._core.umath.fmin'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD('?', cfunc_alias='logical_and', dispatch=[('loops_logical', '?')]), TD(no_obj_bool, dispatch=[('loops_minmax', 'fdg')]), TD(O, f='npy_ObjectMin'), indexed=flts + ints), 'logaddexp': Ufunc(2, 1, MinusInfinity, docstrings.get('numpy._core.umath.logaddexp'), None, TD(flts, f='logaddexp', astype={'e': 'f'})), 'logaddexp2': Ufunc(2, 1, MinusInfinity, docstrings.get('numpy._core.umath.logaddexp2'), None, TD(flts, f='logaddexp2', astype={'e': 'f'})), 'bitwise_and': Ufunc(2, 1, AllOnes, docstrings.get('numpy._core.umath.bitwise_and'), None, TD('?', cfunc_alias='logical_and', dispatch=[('loops_logical', '?')]), TD(ints, dispatch=[('loops_autovec', ints)]), TD(O, f='PyNumber_And')), 'bitwise_or': Ufunc(2, 1, Zero, docstrings.get('numpy._core.umath.bitwise_or'), None, TD('?', cfunc_alias='logical_or', dispatch=[('loops_logical', '?')]), TD(ints, dispatch=[('loops_autovec', ints)]), TD(O, f='PyNumber_Or')), 'bitwise_xor': Ufunc(2, 1, Zero, docstrings.get('numpy._core.umath.bitwise_xor'), None, TD('?', cfunc_alias='not_equal', dispatch=[('loops_comparison', '?')]), TD(ints, dispatch=[('loops_autovec', ints)]), TD(O, f='PyNumber_Xor')), 'invert': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.invert'), None, TD('?', cfunc_alias='logical_not', dispatch=[('loops_logical', '?')]), TD(ints, dispatch=[('loops_autovec', ints)]), TD(O, f='PyNumber_Invert')), 'left_shift': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.left_shift'), None, TD(ints, dispatch=[('loops_autovec', ints)]), TD(O, f='PyNumber_Lshift')), 'right_shift': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.right_shift'), None, TD(ints, dispatch=[('loops_autovec', ints)]), TD(O, f='PyNumber_Rshift')), 'heaviside': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.heaviside'), None, TD(flts, f='heaviside', astype={'e': 'f'})), 'degrees': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.degrees'), None, TD(fltsP, f='degrees', astype={'e': 'f'})), 'rad2deg': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.rad2deg'), None, TD(fltsP, f='rad2deg', astype={'e': 'f'})), 'radians': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.radians'), None, TD(fltsP, f='radians', astype={'e': 'f'})), 'deg2rad': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.deg2rad'), None, TD(fltsP, f='deg2rad', astype={'e': 'f'})), 'arccos': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.arccos'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='acos', astype={'e': 'f'}), TD(P, f='arccos')), 'arccosh': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.arccosh'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='acosh', astype={'e': 'f'}), TD(P, f='arccosh')), 'arcsin': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.arcsin'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='asin', astype={'e': 'f'}), TD(P, f='arcsin')), 'arcsinh': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.arcsinh'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='asinh', astype={'e': 'f'}), TD(P, f='arcsinh')), 'arctan': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.arctan'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='atan', astype={'e': 'f'}), TD(P, f='arctan')), 'arctanh': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.arctanh'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='atanh', astype={'e': 'f'}), TD(P, f='arctanh')), 'cos': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.cos'), None, TD('e', dispatch=[('loops_umath_fp', 'e')]), TD('f', dispatch=[('loops_trigonometric', 'f')]), TD('d', dispatch=[('loops_trigonometric', 'd')]), TD('g' + cmplx, f='cos'), TD(P, f='cos')), 'sin': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.sin'), None, TD('e', dispatch=[('loops_umath_fp', 'e')]), TD('f', dispatch=[('loops_trigonometric', 'f')]), TD('d', dispatch=[('loops_trigonometric', 'd')]), TD('g' + cmplx, f='sin'), TD(P, f='sin')), 'tan': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.tan'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='tan', astype={'e': 'f'}), TD(P, f='tan')), 'cosh': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.cosh'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='cosh', astype={'e': 'f'}), TD(P, f='cosh')), 'sinh': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.sinh'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='sinh', astype={'e': 'f'}), TD(P, f='sinh')), 'tanh': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.tanh'), None, TD('e', dispatch=[('loops_umath_fp', 'e')]), TD('fd', dispatch=[('loops_hyperbolic', 'fd')]), TD(inexact, f='tanh', astype={'e': 'f'}), TD(P, f='tanh')), 'exp': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.exp'), None, TD('e', dispatch=[('loops_umath_fp', 'e')]), TD('fd', dispatch=[('loops_exponent_log', 'fd')]), TD('fdg' + cmplx, f='exp'), TD(P, f='exp')), 'exp2': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.exp2'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='exp2', astype={'e': 'f'}), TD(P, f='exp2')), 'expm1': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.expm1'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='expm1', astype={'e': 'f'}), TD(P, f='expm1')), 'log': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.log'), None, TD('e', dispatch=[('loops_umath_fp', 'e')]), TD('fd', dispatch=[('loops_exponent_log', 'fd')]), TD('fdg' + cmplx, f='log'), TD(P, f='log')), 'log2': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.log2'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='log2', astype={'e': 'f'}), TD(P, f='log2')), 'log10': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.log10'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='log10', astype={'e': 'f'}), TD(P, f='log10')), 'log1p': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.log1p'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(inexact, f='log1p', astype={'e': 'f'}), TD(P, f='log1p')), 'sqrt': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.sqrt'), None, TD('e', f='sqrt', astype={'e': 'f'}), TD(inexactvec, dispatch=[('loops_unary_fp', 'fd')]), TD('fdg' + cmplx, f='sqrt'), TD(P, f='sqrt')), 'cbrt': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.cbrt'), None, TD('efd', dispatch=[('loops_umath_fp', 'efd')]), TD(flts, f='cbrt', astype={'e': 'f'}), TD(P, f='cbrt')), 'ceil': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.ceil'), None, TD(bints), TD('e', f='ceil', astype={'e': 'f'}), TD(inexactvec, dispatch=[('loops_unary_fp', 'fd')]), TD('fdg', f='ceil'), TD(O, f='npy_ObjectCeil')), 'trunc': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.trunc'), None, TD(bints), TD('e', f='trunc', astype={'e': 'f'}), TD(inexactvec, dispatch=[('loops_unary_fp', 'fd')]), TD('fdg', f='trunc'), TD(O, f='npy_ObjectTrunc')), 'fabs': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.fabs'), None, TD(flts, f='fabs', astype={'e': 'f'}), TD(P, f='fabs')), 'floor': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.floor'), None, TD(bints), TD('e', f='floor', astype={'e': 'f'}), TD(inexactvec, dispatch=[('loops_unary_fp', 'fd')]), TD('fdg', f='floor'), TD(O, f='npy_ObjectFloor')), 'rint': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.rint'), None, TD('e', f='rint', astype={'e': 'f'}), TD(inexactvec, dispatch=[('loops_unary_fp', 'fd')]), TD('fdg' + cmplx, f='rint'), TD(P, f='rint')), 'arctan2': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.arctan2'), None, TD('e', f='atan2', astype={'e': 'f'}), TD('fd', dispatch=[('loops_umath_fp', 'fd')]), TD('g', f='atan2', astype={'e': 'f'}), TD(P, f='arctan2')), 'remainder': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.remainder'), 'PyUFunc_RemainderTypeResolver', TD(ints, dispatch=[('loops_modulo', ints)]), TD(flts), [TypeDescription('m', FullTypeDescr, 'mm', 'm')], TD(O, f='PyNumber_Remainder')), 'divmod': Ufunc(2, 2, None, docstrings.get('numpy._core.umath.divmod'), 'PyUFunc_DivmodTypeResolver', TD(ints, dispatch=[('loops_modulo', ints)]), TD(flts), [TypeDescription('m', FullTypeDescr, 'mm', 'qm')]), 'hypot': Ufunc(2, 1, Zero, docstrings.get('numpy._core.umath.hypot'), None, TD(flts, f='hypot', astype={'e': 'f'}), TD(P, f='hypot')), 'isnan': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.isnan'), 'PyUFunc_IsFiniteTypeResolver', TD(noobj, out='?', dispatch=[('loops_unary_fp_le', inexactvec), ('loops_autovec', bints)])), 'isnat': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.isnat'), 'PyUFunc_IsNaTTypeResolver', TD(times, out='?')), 'isinf': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.isinf'), 'PyUFunc_IsFiniteTypeResolver', TD(noobj, out='?', dispatch=[('loops_unary_fp_le', inexactvec), ('loops_autovec', bints + 'mM')])), 'isfinite': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.isfinite'), 'PyUFunc_IsFiniteTypeResolver', TD(noobj, out='?', dispatch=[('loops_unary_fp_le', inexactvec), ('loops_autovec', bints)])), 'signbit': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.signbit'), None, TD(flts, out='?', dispatch=[('loops_unary_fp_le', inexactvec)])), 'copysign': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.copysign'), None, TD(flts)), 'nextafter': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.nextafter'), None, TD(flts)), 'spacing': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.spacing'), None, TD(flts)), 'modf': Ufunc(1, 2, None, docstrings.get('numpy._core.umath.modf'), None, TD(flts)), 'ldexp': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.ldexp'), None, [TypeDescription('e', None, 'ei', 'e'), TypeDescription('f', None, 'fi', 'f', dispatch='loops_exponent_log'), TypeDescription('e', FuncNameSuffix('int64'), 'e' + int64, 'e'), TypeDescription('f', FuncNameSuffix('int64'), 'f' + int64, 'f'), TypeDescription('d', None, 'di', 'd', dispatch='loops_exponent_log'), TypeDescription('d', FuncNameSuffix('int64'), 'd' + int64, 'd'), TypeDescription('g', None, 'gi', 'g'), TypeDescription('g', FuncNameSuffix('int64'), 'g' + int64, 'g')]), 'frexp': Ufunc(1, 2, None, docstrings.get('numpy._core.umath.frexp'), None, [TypeDescription('e', None, 'e', 'ei'), TypeDescription('f', None, 'f', 'fi', dispatch='loops_exponent_log'), TypeDescription('d', None, 'd', 'di', dispatch='loops_exponent_log'), TypeDescription('g', None, 'g', 'gi')]), 'gcd': Ufunc(2, 1, Zero, docstrings.get('numpy._core.umath.gcd'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD(ints), TD('O', f='npy_ObjectGCD')), 'lcm': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.lcm'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD(ints), TD('O', f='npy_ObjectLCM')), 'bitwise_count': Ufunc(1, 1, None, docstrings.get('numpy._core.umath.bitwise_count'), None, TD(ints, dispatch=[('loops_autovec', ints)], out='B'), TD(P, f='bit_count')), 'matmul': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.matmul'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD(notimes_or_obj), TD(O), signature='(n?,k),(k,m?)->(n?,m?)'), 'vecdot': Ufunc(2, 1, None, docstrings.get('numpy._core.umath.vecdot'), 'PyUFunc_SimpleUniformOperationTypeResolver', TD(notimes_or_obj), TD(O), signature='(n),(n)->()'), 'str_len': Ufunc(1, 1, Zero, docstrings.get('numpy._core.umath.str_len'), None), 'isalpha': Ufunc(1, 1, False_, docstrings.get('numpy._core.umath.isalpha'), None), 'isdigit': Ufunc(1, 1, False_, docstrings.get('numpy._core.umath.isdigit'), None), 'isspace': Ufunc(1, 1, False_, docstrings.get('numpy._core.umath.isspace'), None), 'isalnum': Ufunc(1, 1, False_, docstrings.get('numpy._core.umath.isalnum'), None), 'islower': Ufunc(1, 1, False_, docstrings.get('numpy._core.umath.islower'), None), 'isupper': Ufunc(1, 1, False_, docstrings.get('numpy._core.umath.isupper'), None), 'istitle': Ufunc(1, 1, False_, docstrings.get('numpy._core.umath.istitle'), None), 'isdecimal': Ufunc(1, 1, False_, docstrings.get('numpy._core.umath.isdecimal'), None), 'isnumeric': Ufunc(1, 1, False_, docstrings.get('numpy._core.umath.isnumeric'), None), 'find': Ufunc(4, 1, None, docstrings.get('numpy._core.umath.find'), None), 'rfind': Ufunc(4, 1, None, docstrings.get('numpy._core.umath.rfind'), None), 'count': Ufunc(4, 1, None, docstrings.get('numpy._core.umath.count'), None), 'index': Ufunc(4, 1, None, docstrings.get('numpy._core.umath.index'), None), 'rindex': Ufunc(4, 1, None, docstrings.get('numpy._core.umath.rindex'), None), '_replace': Ufunc(4, 1, None, docstrings.get('numpy._core.umath._replace'), None), 'startswith': Ufunc(4, 1, False_, docstrings.get('numpy._core.umath.startswith'), None), 'endswith': Ufunc(4, 1, False_, docstrings.get('numpy._core.umath.endswith'), None), '_strip_chars': Ufunc(2, 1, None, docstrings.get('numpy._core.umath._strip_chars'), None), '_lstrip_chars': Ufunc(2, 1, None, docstrings.get('numpy._core.umath._lstrip_chars'), None), '_rstrip_chars': Ufunc(2, 1, None, docstrings.get('numpy._core.umath._rstrip_chars'), None), '_strip_whitespace': Ufunc(1, 1, None, docstrings.get('numpy._core.umath._strip_whitespace'), None), '_lstrip_whitespace': Ufunc(1, 1, None, docstrings.get('numpy._core.umath._lstrip_whitespace'), None), '_rstrip_whitespace': Ufunc(1, 1, None, docstrings.get('numpy._core.umath._rstrip_whitespace'), None), '_expandtabs_length': Ufunc(2, 1, None, docstrings.get('numpy._core.umath._expandtabs_length'), None), '_expandtabs': Ufunc(2, 1, None, docstrings.get('numpy._core.umath._expandtabs'), None), '_center': Ufunc(3, 1, None, docstrings.get('numpy._core.umath._center'), None), '_ljust': Ufunc(3, 1, None, docstrings.get('numpy._core.umath._ljust'), None), '_rjust': Ufunc(3, 1, None, docstrings.get('numpy._core.umath._rjust'), None), '_zfill': Ufunc(2, 1, None, docstrings.get('numpy._core.umath._zfill'), None), '_partition_index': Ufunc(3, 3, None, docstrings.get('numpy._core.umath._partition_index'), None), '_rpartition_index': Ufunc(3, 3, None, docstrings.get('numpy._core.umath._rpartition_index'), None), '_partition': Ufunc(2, 3, None, docstrings.get('numpy._core.umath._partition'), None), '_rpartition': Ufunc(2, 3, None, docstrings.get('numpy._core.umath._rpartition'), None)} def indent(st, spaces): indentation = ' ' * spaces indented = indentation + st.replace('\n', '\n' + indentation) indented = re.sub(' +$', '', indented) return indented arity_lookup = {(1, 1): {'e': 'e_e', 'f': 'f_f', 'd': 'd_d', 'g': 'g_g', 'F': 'F_F', 'D': 'D_D', 'G': 'G_G', 'O': 'O_O', 'P': 'O_O_method'}, (2, 1): {'e': 'ee_e', 'f': 'ff_f', 'd': 'dd_d', 'g': 'gg_g', 'F': 'FF_F', 'D': 'DD_D', 'G': 'GG_G', 'O': 'OO_O', 'P': 'OO_O_method'}, (3, 1): {'O': 'OOO_O'}} def make_arrays(funcdict): code1list = [] code2list = [] dispdict = {} names = sorted(funcdict.keys()) for name in names: uf = funcdict[name] funclist = [] datalist = [] siglist = [] sub = 0 for (k, t) in enumerate(uf.type_descriptions): cfunc_alias = t.cfunc_alias if t.cfunc_alias else name cfunc_fname = None if t.func_data is FullTypeDescr: tname = english_upper(chartoname[t.type]) datalist.append('(void *)NULL') if t.out == '?': cfunc_fname = f'{tname}_{t.in_}_bool_{cfunc_alias}' else: cfunc_fname = f'{tname}_{t.in_}_{t.out}_{cfunc_alias}' elif isinstance(t.func_data, FuncNameSuffix): datalist.append('(void *)NULL') tname = english_upper(chartoname[t.type]) cfunc_fname = f'{tname}_{cfunc_alias}_{t.func_data.suffix}' elif t.func_data is None: datalist.append('(void *)NULL') tname = english_upper(chartoname[t.type]) cfunc_fname = f'{tname}_{cfunc_alias}' else: try: thedict = arity_lookup[uf.nin, uf.nout] except KeyError as e: raise ValueError(f'Could not handle {name}[{t.type}] with nin={uf.nin}, nout={uf.nout}') from None astype = '' if t.astype is not None: astype = '_As_%s' % thedict[t.astype] astr = '%s_functions[%d] = PyUFunc_%s%s;' % (name, k, thedict[t.type], astype) code2list.append(astr) if t.type == 'O': astr = '%s_data[%d] = (void *) %s;' % (name, k, t.func_data) code2list.append(astr) datalist.append('(void *)NULL') elif t.type == 'P': datalist.append('(void *)"%s"' % t.func_data) else: astr = '%s_data[%d] = (void *) %s;' % (name, k, t.func_data) code2list.append(astr) datalist.append('(void *)NULL') sub += 1 if cfunc_fname: funclist.append(cfunc_fname) if t.dispatch: dispdict.setdefault(t.dispatch, []).append((name, k, cfunc_fname, t.in_ + t.out)) else: funclist.append('NULL') for x in t.in_ + t.out: siglist.append('NPY_%s' % (english_upper(chartoname[x]),)) if funclist or siglist or datalist: funcnames = ', '.join(funclist) signames = ', '.join(siglist) datanames = ', '.join(datalist) code1list.append('static PyUFuncGenericFunction %s_functions[] = {%s};' % (name, funcnames)) code1list.append('static void * %s_data[] = {%s};' % (name, datanames)) code1list.append('static const char %s_signatures[] = {%s};' % (name, signames)) uf.empty = False else: uf.empty = True for (dname, funcs) in dispdict.items(): code2list.append(textwrap.dedent(f'\n #ifndef NPY_DISABLE_OPTIMIZATION\n #include "{dname}.dispatch.h"\n #endif\n ')) for (ufunc_name, func_idx, cfunc_name, inout) in funcs: code2list.append(textwrap.dedent(f''' NPY_CPU_DISPATCH_TRACE("{ufunc_name}", "{''.join(inout)}");\n NPY_CPU_DISPATCH_CALL_XB({ufunc_name}_functions[{func_idx}] = {cfunc_name});\n ''')) return ('\n'.join(code1list), '\n'.join(code2list)) def make_ufuncs(funcdict): code3list = [] names = sorted(funcdict.keys()) for name in names: uf = funcdict[name] mlist = [] if uf.signature is None: sig = 'NULL' else: sig = '"{}"'.format(uf.signature) fmt = textwrap.dedent(' identity = {identity_expr};\n if ({has_identity} && identity == NULL) {{\n return -1;\n }}\n f = PyUFunc_FromFuncAndDataAndSignatureAndIdentity(\n {funcs}, {data}, {signatures}, {nloops},\n {nin}, {nout}, {identity}, "{name}",\n {doc}, 0, {sig}, identity\n );\n if ({has_identity}) {{\n Py_DECREF(identity);\n }}\n if (f == NULL) {{\n return -1;\n }}\n ') args = dict(name=name, funcs=f'{name}_functions' if not uf.empty else 'NULL', data=f'{name}_data' if not uf.empty else 'NULL', signatures=f'{name}_signatures' if not uf.empty else 'NULL', nloops=len(uf.type_descriptions), nin=uf.nin, nout=uf.nout, has_identity='0' if uf.identity is None_ else '1', identity='PyUFunc_IdentityValue', identity_expr=uf.identity, doc=uf.docstring, sig=sig) if uf.identity is None_: args['identity'] = 'PyUFunc_None' args['identity_expr'] = 'NULL' mlist.append(fmt.format(**args)) if uf.typereso is not None: mlist.append('((PyUFuncObject *)f)->type_resolver = &%s;' % uf.typereso) for c in uf.indexed: fmt = textwrap.dedent('\n {{\n PyArray_DTypeMeta *dtype = PyArray_DTypeFromTypeNum({typenum});\n PyObject *info = get_info_no_cast((PyUFuncObject *)f,\n dtype, {count});\n if (info == NULL) {{\n return -1;\n }}\n if (info == Py_None) {{\n PyErr_SetString(PyExc_RuntimeError,\n "cannot add indexed loop to ufunc "\n "{name} with {typenum}");\n return -1;\n }}\n if (!PyObject_TypeCheck(info, &PyArrayMethod_Type)) {{\n PyErr_SetString(PyExc_RuntimeError,\n "Not a PyArrayMethodObject in ufunc "\n "{name} with {typenum}");\n }}\n ((PyArrayMethodObject*)info)->contiguous_indexed_loop =\n {funcname};\n /* info is borrowed, no need to decref*/\n }}\n ') mlist.append(fmt.format(typenum=f'NPY_{english_upper(chartoname[c])}', count=uf.nin + uf.nout, name=name, funcname=f'{english_upper(chartoname[c])}_{name}_indexed')) mlist.append('PyDict_SetItemString(dictionary, "%s", f);' % name) mlist.append('Py_DECREF(f);') code3list.append('\n'.join(mlist)) return '\n'.join(code3list) def make_code(funcdict, filename): (code1, code2) = make_arrays(funcdict) code3 = make_ufuncs(funcdict) code2 = indent(code2, 4) code3 = indent(code3, 4) code = textwrap.dedent('\n\n /** Warning this file is autogenerated!!!\n\n Please make changes to the code generator program (%s)\n **/\n #include "ufunc_object.h"\n #include "ufunc_type_resolution.h"\n #include "loops.h"\n #include "matmul.h"\n #include "clip.h"\n #include "dtypemeta.h"\n #include "_umath_doc_generated.h"\n\n %s\n /* Returns a borrowed ref of the second value in the matching info tuple */\n PyObject *\n get_info_no_cast(PyUFuncObject *ufunc, PyArray_DTypeMeta *op_dtype,\n int ndtypes);\n\n static int\n InitOperators(PyObject *dictionary) {\n PyObject *f, *identity;\n\n %s\n %s\n\n return 0;\n }\n ') % (os.path.basename(filename), code1, code2, code3) return code def main(): parser = argparse.ArgumentParser() parser.add_argument('-o', '--outfile', type=str, help='Path to the output directory') args = parser.parse_args() filename = __file__ code = make_code(defdict, filename) if not args.outfile: outfile = '__umath_generated.c' else: outfile = os.path.join(os.getcwd(), args.outfile) with open(outfile, 'w') as f: f.write(code) if __name__ == '__main__': main() # File: numpy-main/numpy/_core/code_generators/generate_umath_doc.py import sys import os import textwrap import argparse sys.path.insert(0, os.path.dirname(__file__)) import ufunc_docstrings as docstrings sys.path.pop(0) def normalize_doc(docstring): docstring = textwrap.dedent(docstring).strip() docstring = docstring.encode('unicode-escape').decode('ascii') docstring = docstring.replace('"', '\\"') docstring = docstring.replace("'", "\\'") docstring = '\\n""'.join(docstring.split('\\n')) return docstring def write_code(target): with open(target, 'w') as fid: fid.write('#ifndef NUMPY_CORE_INCLUDE__UMATH_DOC_GENERATED_H_\n#define NUMPY_CORE_INCLUDE__UMATH_DOC_GENERATED_H_\n') for (place, string) in docstrings.docdict.items(): cdef_name = f"DOC_{place.upper().replace('.', '_')}" cdef_str = normalize_doc(string) fid.write(f'#define {cdef_name} "{cdef_str}"\n') fid.write('#endif //NUMPY_CORE_INCLUDE__UMATH_DOC_GENERATED_H\n') def main(): parser = argparse.ArgumentParser() parser.add_argument('-o', '--outfile', type=str, help='Path to the output directory') args = parser.parse_args() outfile = os.path.join(os.getcwd(), args.outfile) write_code(outfile) if __name__ == '__main__': main() # File: numpy-main/numpy/_core/code_generators/numpy_api.py """""" import os import importlib.util def get_annotations(): genapi_py = os.path.join(os.path.dirname(__file__), 'genapi.py') spec = importlib.util.spec_from_file_location('conv_template', genapi_py) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return (mod.StealRef, mod.MinVersion) (StealRef, MinVersion) = get_annotations() multiarray_global_vars = {'NPY_NUMUSERTYPES': (7, 'int'), 'NPY_DEFAULT_ASSIGN_CASTING': (292, 'NPY_CASTING'), 'PyDataMem_DefaultHandler': (306, 'PyObject*')} multiarray_scalar_bool_values = {'_PyArrayScalar_BoolValues': (9,)} multiarray_types_api = {'PyArray_Type': (2,), 'PyArrayDescr_Type': (3, 'PyArray_DTypeMeta'), 'PyArrayIter_Type': (5,), 'PyArrayMultiIter_Type': (6,), 'PyBoolArrType_Type': (8,), 'PyGenericArrType_Type': (10,), 'PyNumberArrType_Type': (11,), 'PyIntegerArrType_Type': (12,), 'PySignedIntegerArrType_Type': (13,), 'PyUnsignedIntegerArrType_Type': (14,), 'PyInexactArrType_Type': (15,), 'PyFloatingArrType_Type': (16,), 'PyComplexFloatingArrType_Type': (17,), 'PyFlexibleArrType_Type': (18,), 'PyCharacterArrType_Type': (19,), 'PyByteArrType_Type': (20,), 'PyShortArrType_Type': (21,), 'PyIntArrType_Type': (22,), 'PyLongArrType_Type': (23,), 'PyLongLongArrType_Type': (24,), 'PyUByteArrType_Type': (25,), 'PyUShortArrType_Type': (26,), 'PyUIntArrType_Type': (27,), 'PyULongArrType_Type': (28,), 'PyULongLongArrType_Type': (29,), 'PyFloatArrType_Type': (30,), 'PyDoubleArrType_Type': (31,), 'PyLongDoubleArrType_Type': (32,), 'PyCFloatArrType_Type': (33,), 'PyCDoubleArrType_Type': (34,), 'PyCLongDoubleArrType_Type': (35,), 'PyObjectArrType_Type': (36,), 'PyStringArrType_Type': (37,), 'PyUnicodeArrType_Type': (38,), 'PyVoidArrType_Type': (39,), 'PyTimeIntegerArrType_Type': (214,), 'PyDatetimeArrType_Type': (215,), 'PyTimedeltaArrType_Type': (216,), 'PyHalfArrType_Type': (217,), 'NpyIter_Type': (218,)} multiarray_funcs_api = {'__unused_indices__': [1, 4, 40, 41, 66, 67, 68, 81, 82, 83, 103, 115, 117, 122, 163, 164, 171, 173, 197, 201, 202, 208, 219, 220, 221, 222, 223, 278, 291, 293, 294, 295, 301] + list(range(320, 361)) + [366, 367, 368], 'PyArray_GetNDArrayCVersion': (0,), 'PyArray_INCREF': (42,), 'PyArray_XDECREF': (43,), 'PyArray_SetStringFunction': (44,), 'PyArray_DescrFromType': (45,), 'PyArray_TypeObjectFromType': (46,), 'PyArray_Zero': (47,), 'PyArray_One': (48,), 'PyArray_CastToType': (49, StealRef(2)), 'PyArray_CopyInto': (50,), 'PyArray_CopyAnyInto': (51,), 'PyArray_CanCastSafely': (52,), 'PyArray_CanCastTo': (53,), 'PyArray_ObjectType': (54,), 'PyArray_DescrFromObject': (55,), 'PyArray_ConvertToCommonType': (56,), 'PyArray_DescrFromScalar': (57,), 'PyArray_DescrFromTypeObject': (58,), 'PyArray_Size': (59,), 'PyArray_Scalar': (60,), 'PyArray_FromScalar': (61, StealRef(2)), 'PyArray_ScalarAsCtype': (62,), 'PyArray_CastScalarToCtype': (63,), 'PyArray_CastScalarDirect': (64,), 'PyArray_Pack': (65, MinVersion('2.0')), 'PyArray_FromAny': (69, StealRef(2)), 'PyArray_EnsureArray': (70, StealRef(1)), 'PyArray_EnsureAnyArray': (71, StealRef(1)), 'PyArray_FromFile': (72,), 'PyArray_FromString': (73,), 'PyArray_FromBuffer': (74,), 'PyArray_FromIter': (75, StealRef(2)), 'PyArray_Return': (76, StealRef(1)), 'PyArray_GetField': (77, StealRef(2)), 'PyArray_SetField': (78, StealRef(2)), 'PyArray_Byteswap': (79,), 'PyArray_Resize': (80,), 'PyArray_CopyObject': (84,), 'PyArray_NewCopy': (85,), 'PyArray_ToList': (86,), 'PyArray_ToString': (87,), 'PyArray_ToFile': (88,), 'PyArray_Dump': (89,), 'PyArray_Dumps': (90,), 'PyArray_ValidType': (91,), 'PyArray_UpdateFlags': (92,), 'PyArray_New': (93,), 'PyArray_NewFromDescr': (94, StealRef(2)), 'PyArray_DescrNew': (95,), 'PyArray_DescrNewFromType': (96,), 'PyArray_GetPriority': (97,), 'PyArray_IterNew': (98,), 'PyArray_MultiIterNew': (99,), 'PyArray_PyIntAsInt': (100,), 'PyArray_PyIntAsIntp': (101,), 'PyArray_Broadcast': (102,), 'PyArray_FillWithScalar': (104,), 'PyArray_CheckStrides': (105,), 'PyArray_DescrNewByteorder': (106,), 'PyArray_IterAllButAxis': (107,), 'PyArray_CheckFromAny': (108, StealRef(2)), 'PyArray_FromArray': (109, StealRef(2)), 'PyArray_FromInterface': (110,), 'PyArray_FromStructInterface': (111,), 'PyArray_FromArrayAttr': (112,), 'PyArray_ScalarKind': (113,), 'PyArray_CanCoerceScalar': (114,), 'PyArray_CanCastScalar': (116,), 'PyArray_RemoveSmallest': (118,), 'PyArray_ElementStrides': (119,), 'PyArray_Item_INCREF': (120,), 'PyArray_Item_XDECREF': (121,), 'PyArray_Transpose': (123,), 'PyArray_TakeFrom': (124,), 'PyArray_PutTo': (125,), 'PyArray_PutMask': (126,), 'PyArray_Repeat': (127,), 'PyArray_Choose': (128,), 'PyArray_Sort': (129,), 'PyArray_ArgSort': (130,), 'PyArray_SearchSorted': (131,), 'PyArray_ArgMax': (132,), 'PyArray_ArgMin': (133,), 'PyArray_Reshape': (134,), 'PyArray_Newshape': (135,), 'PyArray_Squeeze': (136,), 'PyArray_View': (137, StealRef(2)), 'PyArray_SwapAxes': (138,), 'PyArray_Max': (139,), 'PyArray_Min': (140,), 'PyArray_Ptp': (141,), 'PyArray_Mean': (142,), 'PyArray_Trace': (143,), 'PyArray_Diagonal': (144,), 'PyArray_Clip': (145,), 'PyArray_Conjugate': (146,), 'PyArray_Nonzero': (147,), 'PyArray_Std': (148,), 'PyArray_Sum': (149,), 'PyArray_CumSum': (150,), 'PyArray_Prod': (151,), 'PyArray_CumProd': (152,), 'PyArray_All': (153,), 'PyArray_Any': (154,), 'PyArray_Compress': (155,), 'PyArray_Flatten': (156,), 'PyArray_Ravel': (157,), 'PyArray_MultiplyList': (158,), 'PyArray_MultiplyIntList': (159,), 'PyArray_GetPtr': (160,), 'PyArray_CompareLists': (161,), 'PyArray_AsCArray': (162, StealRef(5)), 'PyArray_Free': (165,), 'PyArray_Converter': (166,), 'PyArray_IntpFromSequence': (167,), 'PyArray_Concatenate': (168,), 'PyArray_InnerProduct': (169,), 'PyArray_MatrixProduct': (170,), 'PyArray_Correlate': (172,), 'PyArray_DescrConverter': (174,), 'PyArray_DescrConverter2': (175,), 'PyArray_IntpConverter': (176,), 'PyArray_BufferConverter': (177,), 'PyArray_AxisConverter': (178,), 'PyArray_BoolConverter': (179,), 'PyArray_ByteorderConverter': (180,), 'PyArray_OrderConverter': (181,), 'PyArray_EquivTypes': (182,), 'PyArray_Zeros': (183, StealRef(3)), 'PyArray_Empty': (184, StealRef(3)), 'PyArray_Where': (185,), 'PyArray_Arange': (186,), 'PyArray_ArangeObj': (187,), 'PyArray_SortkindConverter': (188,), 'PyArray_LexSort': (189,), 'PyArray_Round': (190,), 'PyArray_EquivTypenums': (191,), 'PyArray_RegisterDataType': (192,), 'PyArray_RegisterCastFunc': (193,), 'PyArray_RegisterCanCast': (194,), 'PyArray_InitArrFuncs': (195,), 'PyArray_IntTupleFromIntp': (196,), 'PyArray_ClipmodeConverter': (198,), 'PyArray_OutputConverter': (199,), 'PyArray_BroadcastToShape': (200,), 'PyArray_DescrAlignConverter': (203,), 'PyArray_DescrAlignConverter2': (204,), 'PyArray_SearchsideConverter': (205,), 'PyArray_CheckAxis': (206,), 'PyArray_OverflowMultiplyList': (207,), 'PyArray_MultiIterFromObjects': (209,), 'PyArray_GetEndianness': (210,), 'PyArray_GetNDArrayCFeatureVersion': (211,), 'PyArray_Correlate2': (212,), 'PyArray_NeighborhoodIterNew': (213,), 'NpyIter_New': (224,), 'NpyIter_MultiNew': (225,), 'NpyIter_AdvancedNew': (226,), 'NpyIter_Copy': (227,), 'NpyIter_Deallocate': (228,), 'NpyIter_HasDelayedBufAlloc': (229,), 'NpyIter_HasExternalLoop': (230,), 'NpyIter_EnableExternalLoop': (231,), 'NpyIter_GetInnerStrideArray': (232,), 'NpyIter_GetInnerLoopSizePtr': (233,), 'NpyIter_Reset': (234,), 'NpyIter_ResetBasePointers': (235,), 'NpyIter_ResetToIterIndexRange': (236,), 'NpyIter_GetNDim': (237,), 'NpyIter_GetNOp': (238,), 'NpyIter_GetIterNext': (239,), 'NpyIter_GetIterSize': (240,), 'NpyIter_GetIterIndexRange': (241,), 'NpyIter_GetIterIndex': (242,), 'NpyIter_GotoIterIndex': (243,), 'NpyIter_HasMultiIndex': (244,), 'NpyIter_GetShape': (245,), 'NpyIter_GetGetMultiIndex': (246,), 'NpyIter_GotoMultiIndex': (247,), 'NpyIter_RemoveMultiIndex': (248,), 'NpyIter_HasIndex': (249,), 'NpyIter_IsBuffered': (250,), 'NpyIter_IsGrowInner': (251,), 'NpyIter_GetBufferSize': (252,), 'NpyIter_GetIndexPtr': (253,), 'NpyIter_GotoIndex': (254,), 'NpyIter_GetDataPtrArray': (255,), 'NpyIter_GetDescrArray': (256,), 'NpyIter_GetOperandArray': (257,), 'NpyIter_GetIterView': (258,), 'NpyIter_GetReadFlags': (259,), 'NpyIter_GetWriteFlags': (260,), 'NpyIter_DebugPrint': (261,), 'NpyIter_IterationNeedsAPI': (262,), 'NpyIter_GetInnerFixedStrideArray': (263,), 'NpyIter_RemoveAxis': (264,), 'NpyIter_GetAxisStrideArray': (265,), 'NpyIter_RequiresBuffering': (266,), 'NpyIter_GetInitialDataPtrArray': (267,), 'NpyIter_CreateCompatibleStrides': (268,), 'PyArray_CastingConverter': (269,), 'PyArray_CountNonzero': (270,), 'PyArray_PromoteTypes': (271,), 'PyArray_MinScalarType': (272,), 'PyArray_ResultType': (273,), 'PyArray_CanCastArrayTo': (274,), 'PyArray_CanCastTypeTo': (275,), 'PyArray_EinsteinSum': (276,), 'PyArray_NewLikeArray': (277, StealRef(3)), 'PyArray_ConvertClipmodeSequence': (279,), 'PyArray_MatrixProduct2': (280,), 'NpyIter_IsFirstVisit': (281,), 'PyArray_SetBaseObject': (282, StealRef(2)), 'PyArray_CreateSortedStridePerm': (283,), 'PyArray_RemoveAxesInPlace': (284,), 'PyArray_DebugPrint': (285,), 'PyArray_FailUnlessWriteable': (286,), 'PyArray_SetUpdateIfCopyBase': (287, StealRef(2)), 'PyDataMem_NEW': (288,), 'PyDataMem_FREE': (289,), 'PyDataMem_RENEW': (290,), 'PyArray_Partition': (296,), 'PyArray_ArgPartition': (297,), 'PyArray_SelectkindConverter': (298,), 'PyDataMem_NEW_ZEROED': (299,), 'PyArray_CheckAnyScalarExact': (300,), 'PyArray_ResolveWritebackIfCopy': (302,), 'PyArray_SetWritebackIfCopyBase': (303,), 'PyDataMem_SetHandler': (304, MinVersion('1.22')), 'PyDataMem_GetHandler': (305, MinVersion('1.22')), 'NpyDatetime_ConvertDatetime64ToDatetimeStruct': (307, MinVersion('2.0')), 'NpyDatetime_ConvertDatetimeStructToDatetime64': (308, MinVersion('2.0')), 'NpyDatetime_ConvertPyDateTimeToDatetimeStruct': (309, MinVersion('2.0')), 'NpyDatetime_GetDatetimeISO8601StrLen': (310, MinVersion('2.0')), 'NpyDatetime_MakeISO8601Datetime': (311, MinVersion('2.0')), 'NpyDatetime_ParseISO8601Datetime': (312, MinVersion('2.0')), 'NpyString_load': (313, MinVersion('2.0')), 'NpyString_pack': (314, MinVersion('2.0')), 'NpyString_pack_null': (315, MinVersion('2.0')), 'NpyString_acquire_allocator': (316, MinVersion('2.0')), 'NpyString_acquire_allocators': (317, MinVersion('2.0')), 'NpyString_release_allocator': (318, MinVersion('2.0')), 'NpyString_release_allocators': (319, MinVersion('2.0')), 'PyArray_GetDefaultDescr': (361, MinVersion('2.0')), 'PyArrayInitDTypeMeta_FromSpec': (362, MinVersion('2.0')), 'PyArray_CommonDType': (363, MinVersion('2.0')), 'PyArray_PromoteDTypeSequence': (364, MinVersion('2.0')), '_PyDataType_GetArrFuncs': (365,)} ufunc_types_api = {'PyUFunc_Type': (0,)} ufunc_funcs_api = {'__unused_indices__': [3, 25, 26, 29, 32], 'PyUFunc_FromFuncAndData': (1,), 'PyUFunc_RegisterLoopForType': (2,), 'PyUFunc_f_f_As_d_d': (4,), 'PyUFunc_d_d': (5,), 'PyUFunc_f_f': (6,), 'PyUFunc_g_g': (7,), 'PyUFunc_F_F_As_D_D': (8,), 'PyUFunc_F_F': (9,), 'PyUFunc_D_D': (10,), 'PyUFunc_G_G': (11,), 'PyUFunc_O_O': (12,), 'PyUFunc_ff_f_As_dd_d': (13,), 'PyUFunc_ff_f': (14,), 'PyUFunc_dd_d': (15,), 'PyUFunc_gg_g': (16,), 'PyUFunc_FF_F_As_DD_D': (17,), 'PyUFunc_DD_D': (18,), 'PyUFunc_FF_F': (19,), 'PyUFunc_GG_G': (20,), 'PyUFunc_OO_O': (21,), 'PyUFunc_O_O_method': (22,), 'PyUFunc_OO_O_method': (23,), 'PyUFunc_On_Om': (24,), 'PyUFunc_clearfperr': (27,), 'PyUFunc_getfperr': (28,), 'PyUFunc_ReplaceLoopBySignature': (30,), 'PyUFunc_FromFuncAndDataAndSignature': (31,), 'PyUFunc_e_e': (33,), 'PyUFunc_e_e_As_f_f': (34,), 'PyUFunc_e_e_As_d_d': (35,), 'PyUFunc_ee_e': (36,), 'PyUFunc_ee_e_As_ff_f': (37,), 'PyUFunc_ee_e_As_dd_d': (38,), 'PyUFunc_DefaultTypeResolver': (39,), 'PyUFunc_ValidateCasting': (40,), 'PyUFunc_RegisterLoopForDescr': (41,), 'PyUFunc_FromFuncAndDataAndSignatureAndIdentity': (42, MinVersion('1.16')), 'PyUFunc_AddLoopFromSpec': (43, MinVersion('2.0')), 'PyUFunc_AddPromoter': (44, MinVersion('2.0')), 'PyUFunc_AddWrappingLoop': (45, MinVersion('2.0')), 'PyUFunc_GiveFloatingpointErrors': (46, MinVersion('2.0'))} multiarray_api = (multiarray_global_vars, multiarray_scalar_bool_values, multiarray_types_api, multiarray_funcs_api) ufunc_api = (ufunc_funcs_api, ufunc_types_api) full_api = multiarray_api + ufunc_api # File: numpy-main/numpy/_core/code_generators/ufunc_docstrings.py """""" import textwrap docdict = {} subst = {'PARAMS': textwrap.dedent('\n out : ndarray, None, or tuple of ndarray and None, optional\n A location into which the result is stored. If provided, it must have\n a shape that the inputs broadcast to. If not provided or None,\n a freshly-allocated array is returned. A tuple (possible only as a\n keyword argument) must have length equal to the number of outputs.\n where : array_like, optional\n This condition is broadcast over the input. At locations where the\n condition is True, the `out` array will be set to the ufunc result.\n Elsewhere, the `out` array will retain its original value.\n Note that if an uninitialized `out` array is created via the default\n ``out=None``, locations within it where the condition is False will\n remain uninitialized.\n **kwargs\n For other keyword-only arguments, see the\n :ref:`ufunc docs `.\n ').strip(), 'BROADCASTABLE_2': 'If ``x1.shape != x2.shape``, they must be broadcastable to a common\n shape (which becomes the shape of the output).', 'OUT_SCALAR_1': 'This is a scalar if `x` is a scalar.', 'OUT_SCALAR_2': 'This is a scalar if both `x1` and `x2` are scalars.'} def add_newdoc(place, name, doc): doc = textwrap.dedent(doc).strip() skip = ('matmul', 'vecdot', 'clip') if name[0] != '_' and name not in skip: if '\nx :' in doc: assert '$OUT_SCALAR_1' in doc, 'in {}'.format(name) elif '\nx2 :' in doc or '\nx1, x2 :' in doc: assert '$OUT_SCALAR_2' in doc, 'in {}'.format(name) else: assert False, 'Could not detect number of inputs in {}'.format(name) for (k, v) in subst.items(): doc = doc.replace('$' + k, v) docdict[f'{place}.{name}'] = doc add_newdoc('numpy._core.umath', 'absolute', "\n Calculate the absolute value element-wise.\n\n ``np.abs`` is a shorthand for this function.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n absolute : ndarray\n An ndarray containing the absolute value of\n each element in `x`. For complex input, ``a + ib``, the\n absolute value is :math:`\\sqrt{ a^2 + b^2 }`.\n $OUT_SCALAR_1\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([-1.2, 1.2])\n >>> np.absolute(x)\n array([ 1.2, 1.2])\n >>> np.absolute(1.2 + 1j)\n 1.5620499351813308\n\n Plot the function over ``[-10, 10]``:\n\n >>> import matplotlib.pyplot as plt\n\n >>> x = np.linspace(start=-10, stop=10, num=101)\n >>> plt.plot(x, np.absolute(x))\n >>> plt.show()\n\n Plot the function over the complex plane:\n\n >>> xx = x + 1j * x[:, np.newaxis]\n >>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray')\n >>> plt.show()\n\n The `abs` function can be used as a shorthand for ``np.absolute`` on\n ndarrays.\n\n >>> x = np.array([-1.2, 1.2])\n >>> abs(x)\n array([1.2, 1.2])\n\n ") add_newdoc('numpy._core.umath', 'add', '\n Add arguments element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n The arrays to be added.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n add : ndarray or scalar\n The sum of `x1` and `x2`, element-wise.\n $OUT_SCALAR_2\n\n Notes\n -----\n Equivalent to `x1` + `x2` in terms of array broadcasting.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.add(1.0, 4.0)\n 5.0\n >>> x1 = np.arange(9.0).reshape((3, 3))\n >>> x2 = np.arange(3.0)\n >>> np.add(x1, x2)\n array([[ 0., 2., 4.],\n [ 3., 5., 7.],\n [ 6., 8., 10.]])\n\n The ``+`` operator can be used as a shorthand for ``np.add`` on ndarrays.\n\n >>> x1 = np.arange(9.0).reshape((3, 3))\n >>> x2 = np.arange(3.0)\n >>> x1 + x2\n array([[ 0., 2., 4.],\n [ 3., 5., 7.],\n [ 6., 8., 10.]])\n ') add_newdoc('numpy._core.umath', 'arccos', '\n Trigonometric inverse cosine, element-wise.\n\n The inverse of `cos` so that, if ``y = cos(x)``, then ``x = arccos(y)``.\n\n Parameters\n ----------\n x : array_like\n `x`-coordinate on the unit circle.\n For real arguments, the domain is [-1, 1].\n $PARAMS\n\n Returns\n -------\n angle : ndarray\n The angle of the ray intersecting the unit circle at the given\n `x`-coordinate in radians [0, pi].\n $OUT_SCALAR_1\n\n See Also\n --------\n cos, arctan, arcsin, emath.arccos\n\n Notes\n -----\n `arccos` is a multivalued function: for each `x` there are infinitely\n many numbers `z` such that ``cos(z) = x``. The convention is to return\n the angle `z` whose real part lies in `[0, pi]`.\n\n For real-valued input data types, `arccos` always returns real output.\n For each value that cannot be expressed as a real number or infinity,\n it yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arccos` is a complex analytic function that\n has branch cuts ``[-inf, -1]`` and `[1, inf]` and is continuous from\n above on the former and from below on the latter.\n\n The inverse `cos` is also known as `acos` or cos^-1.\n\n References\n ----------\n M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",\n 10th printing, 1964, pp. 79.\n https://personal.math.ubc.ca/~cbm/aands/page_79.htm\n\n Examples\n --------\n >>> import numpy as np\n\n We expect the arccos of 1 to be 0, and of -1 to be pi:\n\n >>> np.arccos([1, -1])\n array([ 0. , 3.14159265])\n\n Plot arccos:\n\n >>> import matplotlib.pyplot as plt\n >>> x = np.linspace(-1, 1, num=100)\n >>> plt.plot(x, np.arccos(x))\n >>> plt.axis(\'tight\')\n >>> plt.show()\n\n ') add_newdoc('numpy._core.umath', 'arccosh', '\n Inverse hyperbolic cosine, element-wise.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n arccosh : ndarray\n Array of the same shape as `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n\n cosh, arcsinh, sinh, arctanh, tanh\n\n Notes\n -----\n `arccosh` is a multivalued function: for each `x` there are infinitely\n many numbers `z` such that `cosh(z) = x`. The convention is to return the\n `z` whose imaginary part lies in ``[-pi, pi]`` and the real part in\n ``[0, inf]``.\n\n For real-valued input data types, `arccosh` always returns real output.\n For each value that cannot be expressed as a real number or infinity, it\n yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arccosh` is a complex analytical function that\n has a branch cut `[-inf, 1]` and is continuous from above on it.\n\n References\n ----------\n .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",\n 10th printing, 1964, pp. 86.\n https://personal.math.ubc.ca/~cbm/aands/page_86.htm\n .. [2] Wikipedia, "Inverse hyperbolic function",\n https://en.wikipedia.org/wiki/Arccosh\n\n Examples\n --------\n >>> import numpy as np\n >>> np.arccosh([np.e, 10.0])\n array([ 1.65745445, 2.99322285])\n >>> np.arccosh(1)\n 0.0\n\n ') add_newdoc('numpy._core.umath', 'arcsin', '\n Inverse sine, element-wise.\n\n Parameters\n ----------\n x : array_like\n `y`-coordinate on the unit circle.\n $PARAMS\n\n Returns\n -------\n angle : ndarray\n The inverse sine of each element in `x`, in radians and in the\n closed interval ``[-pi/2, pi/2]``.\n $OUT_SCALAR_1\n\n See Also\n --------\n sin, cos, arccos, tan, arctan, arctan2, emath.arcsin\n\n Notes\n -----\n `arcsin` is a multivalued function: for each `x` there are infinitely\n many numbers `z` such that :math:`sin(z) = x`. The convention is to\n return the angle `z` whose real part lies in [-pi/2, pi/2].\n\n For real-valued input data types, *arcsin* always returns real output.\n For each value that cannot be expressed as a real number or infinity,\n it yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arcsin` is a complex analytic function that\n has, by convention, the branch cuts [-inf, -1] and [1, inf] and is\n continuous from above on the former and from below on the latter.\n\n The inverse sine is also known as `asin` or sin^{-1}.\n\n References\n ----------\n Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*,\n 10th printing, New York: Dover, 1964, pp. 79ff.\n https://personal.math.ubc.ca/~cbm/aands/page_79.htm\n\n Examples\n --------\n >>> import numpy as np\n >>> np.arcsin(1) # pi/2\n 1.5707963267948966\n >>> np.arcsin(-1) # -pi/2\n -1.5707963267948966\n >>> np.arcsin(0)\n 0.0\n\n ') add_newdoc('numpy._core.umath', 'arcsinh', '\n Inverse hyperbolic sine element-wise.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Array of the same shape as `x`.\n $OUT_SCALAR_1\n\n Notes\n -----\n `arcsinh` is a multivalued function: for each `x` there are infinitely\n many numbers `z` such that `sinh(z) = x`. The convention is to return the\n `z` whose imaginary part lies in `[-pi/2, pi/2]`.\n\n For real-valued input data types, `arcsinh` always returns real output.\n For each value that cannot be expressed as a real number or infinity, it\n returns ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arcsinh` is a complex analytical function that\n has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from\n the right on the former and from the left on the latter.\n\n The inverse hyperbolic sine is also known as `asinh` or ``sinh^-1``.\n\n References\n ----------\n .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",\n 10th printing, 1964, pp. 86.\n https://personal.math.ubc.ca/~cbm/aands/page_86.htm\n .. [2] Wikipedia, "Inverse hyperbolic function",\n https://en.wikipedia.org/wiki/Arcsinh\n\n Examples\n --------\n >>> import numpy as np\n >>> np.arcsinh(np.array([np.e, 10.0]))\n array([ 1.72538256, 2.99822295])\n\n ') add_newdoc('numpy._core.umath', 'arctan', '\n Trigonometric inverse tangent, element-wise.\n\n The inverse of tan, so that if ``y = tan(x)`` then ``x = arctan(y)``.\n\n Parameters\n ----------\n x : array_like\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Out has the same shape as `x`. Its real part is in\n ``[-pi/2, pi/2]`` (``arctan(+/-inf)`` returns ``+/-pi/2``).\n $OUT_SCALAR_1\n\n See Also\n --------\n arctan2 : The "four quadrant" arctan of the angle formed by (`x`, `y`)\n and the positive `x`-axis.\n angle : Argument of complex values.\n\n Notes\n -----\n `arctan` is a multi-valued function: for each `x` there are infinitely\n many numbers `z` such that tan(`z`) = `x`. The convention is to return\n the angle `z` whose real part lies in [-pi/2, pi/2].\n\n For real-valued input data types, `arctan` always returns real output.\n For each value that cannot be expressed as a real number or infinity,\n it yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arctan` is a complex analytic function that\n has [``1j, infj``] and [``-1j, -infj``] as branch cuts, and is continuous\n from the left on the former and from the right on the latter.\n\n The inverse tangent is also known as `atan` or tan^{-1}.\n\n References\n ----------\n Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*,\n 10th printing, New York: Dover, 1964, pp. 79.\n https://personal.math.ubc.ca/~cbm/aands/page_79.htm\n\n Examples\n --------\n We expect the arctan of 0 to be 0, and of 1 to be pi/4:\n\n >>> import numpy as np\n\n >>> np.arctan([0, 1])\n array([ 0. , 0.78539816])\n\n >>> np.pi/4\n 0.78539816339744828\n\n Plot arctan:\n\n >>> import matplotlib.pyplot as plt\n >>> x = np.linspace(-10, 10)\n >>> plt.plot(x, np.arctan(x))\n >>> plt.axis(\'tight\')\n >>> plt.show()\n\n ') add_newdoc('numpy._core.umath', 'arctan2', '\n Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly.\n\n The quadrant (i.e., branch) is chosen so that ``arctan2(x1, x2)`` is\n the signed angle in radians between the ray ending at the origin and\n passing through the point (1,0), and the ray ending at the origin and\n passing through the point (`x2`, `x1`). (Note the role reversal: the\n "`y`-coordinate" is the first function parameter, the "`x`-coordinate"\n is the second.) By IEEE convention, this function is defined for\n `x2` = +/-0 and for either or both of `x1` and `x2` = +/-inf (see\n Notes for specific values).\n\n This function is not defined for complex-valued arguments; for the\n so-called argument of complex values, use `angle`.\n\n Parameters\n ----------\n x1 : array_like, real-valued\n `y`-coordinates.\n x2 : array_like, real-valued\n `x`-coordinates.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n angle : ndarray\n Array of angles in radians, in the range ``[-pi, pi]``.\n $OUT_SCALAR_2\n\n See Also\n --------\n arctan, tan, angle\n\n Notes\n -----\n *arctan2* is identical to the `atan2` function of the underlying\n C library. The following special values are defined in the C\n standard: [1]_\n\n ====== ====== ================\n `x1` `x2` `arctan2(x1,x2)`\n ====== ====== ================\n +/- 0 +0 +/- 0\n +/- 0 -0 +/- pi\n > 0 +/-inf +0 / +pi\n < 0 +/-inf -0 / -pi\n +/-inf +inf +/- (pi/4)\n +/-inf -inf +/- (3*pi/4)\n ====== ====== ================\n\n Note that +0 and -0 are distinct floating point numbers, as are +inf\n and -inf.\n\n References\n ----------\n .. [1] ISO/IEC standard 9899:1999, "Programming language C."\n\n Examples\n --------\n Consider four points in different quadrants:\n\n >>> import numpy as np\n\n >>> x = np.array([-1, +1, +1, -1])\n >>> y = np.array([-1, -1, +1, +1])\n >>> np.arctan2(y, x) * 180 / np.pi\n array([-135., -45., 45., 135.])\n\n Note the order of the parameters. `arctan2` is defined also when `x2` = 0\n and at several other special points, obtaining values in\n the range ``[-pi, pi]``:\n\n >>> np.arctan2([1., -1.], [0., 0.])\n array([ 1.57079633, -1.57079633])\n >>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf])\n array([0. , 3.14159265, 0.78539816])\n\n ') add_newdoc('numpy._core.umath', '_arg', '\n DO NOT USE, ONLY FOR TESTING\n ') add_newdoc('numpy._core.umath', 'arctanh', '\n Inverse hyperbolic tangent element-wise.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Array of the same shape as `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n emath.arctanh\n\n Notes\n -----\n `arctanh` is a multivalued function: for each `x` there are infinitely\n many numbers `z` such that ``tanh(z) = x``. The convention is to return\n the `z` whose imaginary part lies in `[-pi/2, pi/2]`.\n\n For real-valued input data types, `arctanh` always returns real output.\n For each value that cannot be expressed as a real number or infinity,\n it yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arctanh` is a complex analytical function\n that has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from\n above on the former and from below on the latter.\n\n The inverse hyperbolic tangent is also known as `atanh` or ``tanh^-1``.\n\n References\n ----------\n .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",\n 10th printing, 1964, pp. 86.\n https://personal.math.ubc.ca/~cbm/aands/page_86.htm\n .. [2] Wikipedia, "Inverse hyperbolic function",\n https://en.wikipedia.org/wiki/Arctanh\n\n Examples\n --------\n >>> import numpy as np\n >>> np.arctanh([0, -0.5])\n array([ 0. , -0.54930614])\n\n ') add_newdoc('numpy._core.umath', 'bitwise_and', "\n Compute the bit-wise AND of two arrays element-wise.\n\n Computes the bit-wise AND of the underlying binary representation of\n the integers in the input arrays. This ufunc implements the C/Python\n operator ``&``.\n\n Parameters\n ----------\n x1, x2 : array_like\n Only integer and boolean types are handled.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Result.\n $OUT_SCALAR_2\n\n See Also\n --------\n logical_and\n bitwise_or\n bitwise_xor\n binary_repr :\n Return the binary representation of the input number as a string.\n\n Examples\n --------\n >>> import numpy as np\n\n The number 13 is represented by ``00001101``. Likewise, 17 is\n represented by ``00010001``. The bit-wise AND of 13 and 17 is\n therefore ``000000001``, or 1:\n\n >>> np.bitwise_and(13, 17)\n 1\n\n >>> np.bitwise_and(14, 13)\n 12\n >>> np.binary_repr(12)\n '1100'\n >>> np.bitwise_and([14,3], 13)\n array([12, 1])\n\n >>> np.bitwise_and([11,7], [4,25])\n array([0, 1])\n >>> np.bitwise_and(np.array([2,5,255]), np.array([3,14,16]))\n array([ 2, 4, 16])\n >>> np.bitwise_and([True, True], [False, True])\n array([False, True])\n\n The ``&`` operator can be used as a shorthand for ``np.bitwise_and`` on\n ndarrays.\n\n >>> x1 = np.array([2, 5, 255])\n >>> x2 = np.array([3, 14, 16])\n >>> x1 & x2\n array([ 2, 4, 16])\n\n ") add_newdoc('numpy._core.umath', 'bitwise_or', "\n Compute the bit-wise OR of two arrays element-wise.\n\n Computes the bit-wise OR of the underlying binary representation of\n the integers in the input arrays. This ufunc implements the C/Python\n operator ``|``.\n\n Parameters\n ----------\n x1, x2 : array_like\n Only integer and boolean types are handled.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Result.\n $OUT_SCALAR_2\n\n See Also\n --------\n logical_or\n bitwise_and\n bitwise_xor\n binary_repr :\n Return the binary representation of the input number as a string.\n\n Examples\n --------\n >>> import numpy as np\n\n The number 13 has the binary representation ``00001101``. Likewise,\n 16 is represented by ``00010000``. The bit-wise OR of 13 and 16 is\n then ``00011101``, or 29:\n\n >>> np.bitwise_or(13, 16)\n 29\n >>> np.binary_repr(29)\n '11101'\n\n >>> np.bitwise_or(32, 2)\n 34\n >>> np.bitwise_or([33, 4], 1)\n array([33, 5])\n >>> np.bitwise_or([33, 4], [1, 2])\n array([33, 6])\n\n >>> np.bitwise_or(np.array([2, 5, 255]), np.array([4, 4, 4]))\n array([ 6, 5, 255])\n >>> np.array([2, 5, 255]) | np.array([4, 4, 4])\n array([ 6, 5, 255])\n >>> np.bitwise_or(np.array([2, 5, 255, 2147483647], dtype=np.int32),\n ... np.array([4, 4, 4, 2147483647], dtype=np.int32))\n array([ 6, 5, 255, 2147483647], dtype=int32)\n >>> np.bitwise_or([True, True], [False, True])\n array([ True, True])\n\n The ``|`` operator can be used as a shorthand for ``np.bitwise_or`` on\n ndarrays.\n\n >>> x1 = np.array([2, 5, 255])\n >>> x2 = np.array([4, 4, 4])\n >>> x1 | x2\n array([ 6, 5, 255])\n\n ") add_newdoc('numpy._core.umath', 'bitwise_xor', "\n Compute the bit-wise XOR of two arrays element-wise.\n\n Computes the bit-wise XOR of the underlying binary representation of\n the integers in the input arrays. This ufunc implements the C/Python\n operator ``^``.\n\n Parameters\n ----------\n x1, x2 : array_like\n Only integer and boolean types are handled.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Result.\n $OUT_SCALAR_2\n\n See Also\n --------\n logical_xor\n bitwise_and\n bitwise_or\n binary_repr :\n Return the binary representation of the input number as a string.\n\n Examples\n --------\n >>> import numpy as np\n\n The number 13 is represented by ``00001101``. Likewise, 17 is\n represented by ``00010001``. The bit-wise XOR of 13 and 17 is\n therefore ``00011100``, or 28:\n\n >>> np.bitwise_xor(13, 17)\n 28\n >>> np.binary_repr(28)\n '11100'\n\n >>> np.bitwise_xor(31, 5)\n 26\n >>> np.bitwise_xor([31,3], 5)\n array([26, 6])\n\n >>> np.bitwise_xor([31,3], [5,6])\n array([26, 5])\n >>> np.bitwise_xor([True, True], [False, True])\n array([ True, False])\n\n The ``^`` operator can be used as a shorthand for ``np.bitwise_xor`` on\n ndarrays.\n\n >>> x1 = np.array([True, True])\n >>> x2 = np.array([False, True])\n >>> x1 ^ x2\n array([ True, False])\n\n ") add_newdoc('numpy._core.umath', 'ceil', '\n Return the ceiling of the input, element-wise.\n\n The ceil of the scalar `x` is the smallest integer `i`, such that\n ``i >= x``. It is often denoted as :math:`\\lceil x \\rceil`.\n\n Parameters\n ----------\n x : array_like\n Input data.\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n The ceiling of each element in `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n floor, trunc, rint, fix\n\n Examples\n --------\n >>> import numpy as np\n\n >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])\n >>> np.ceil(a)\n array([-1., -1., -0., 1., 2., 2., 2.])\n\n ') add_newdoc('numpy._core.umath', 'trunc', '\n Return the truncated value of the input, element-wise.\n\n The truncated value of the scalar `x` is the nearest integer `i` which\n is closer to zero than `x` is. In short, the fractional part of the\n signed number `x` is discarded.\n\n Parameters\n ----------\n x : array_like\n Input data.\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n The truncated value of each element in `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n ceil, floor, rint, fix\n\n Notes\n -----\n .. versionadded:: 1.3.0\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])\n >>> np.trunc(a)\n array([-1., -1., -0., 0., 1., 1., 2.])\n\n ') add_newdoc('numpy._core.umath', 'conjugate', '\n Return the complex conjugate, element-wise.\n\n The complex conjugate of a complex number is obtained by changing the\n sign of its imaginary part.\n\n Parameters\n ----------\n x : array_like\n Input value.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The complex conjugate of `x`, with same dtype as `y`.\n $OUT_SCALAR_1\n\n Notes\n -----\n `conj` is an alias for `conjugate`:\n\n >>> np.conj is np.conjugate\n True\n\n Examples\n --------\n >>> import numpy as np\n >>> np.conjugate(1+2j)\n (1-2j)\n\n >>> x = np.eye(2) + 1j * np.eye(2)\n >>> np.conjugate(x)\n array([[ 1.-1.j, 0.-0.j],\n [ 0.-0.j, 1.-1.j]])\n\n ') add_newdoc('numpy._core.umath', 'cos', '\n Cosine element-wise.\n\n Parameters\n ----------\n x : array_like\n Input array in radians.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The corresponding cosine values.\n $OUT_SCALAR_1\n\n Notes\n -----\n If `out` is provided, the function writes the result into it,\n and returns a reference to `out`. (See Examples)\n\n References\n ----------\n M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.\n New York, NY: Dover, 1972.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.cos(np.array([0, np.pi/2, np.pi]))\n array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00])\n >>>\n >>> # Example of providing the optional output parameter\n >>> out1 = np.array([0], dtype=\'d\')\n >>> out2 = np.cos([0.1], out1)\n >>> out2 is out1\n True\n >>>\n >>> # Example of ValueError due to provision of shape mis-matched `out`\n >>> np.cos(np.zeros((3,3)),np.zeros((2,2)))\n Traceback (most recent call last):\n File "", line 1, in \n ValueError: operands could not be broadcast together with shapes (3,3) (2,2)\n\n ') add_newdoc('numpy._core.umath', 'cosh', '\n Hyperbolic cosine, element-wise.\n\n Equivalent to ``1/2 * (np.exp(x) + np.exp(-x))`` and ``np.cos(1j*x)``.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Output array of same shape as `x`.\n $OUT_SCALAR_1\n\n Examples\n --------\n >>> import numpy as np\n >>> np.cosh(0)\n 1.0\n\n The hyperbolic cosine describes the shape of a hanging cable:\n\n >>> import matplotlib.pyplot as plt\n >>> x = np.linspace(-4, 4, 1000)\n >>> plt.plot(x, np.cosh(x))\n >>> plt.show()\n\n ') add_newdoc('numpy._core.umath', 'degrees', '\n Convert angles from radians to degrees.\n\n Parameters\n ----------\n x : array_like\n Input array in radians.\n $PARAMS\n\n Returns\n -------\n y : ndarray of floats\n The corresponding degree values; if `out` was supplied this is a\n reference to it.\n $OUT_SCALAR_1\n\n See Also\n --------\n rad2deg : equivalent function\n\n Examples\n --------\n Convert a radian array to degrees\n\n >>> import numpy as np\n\n >>> rad = np.arange(12.)*np.pi/6\n >>> np.degrees(rad)\n array([ 0., 30., 60., 90., 120., 150., 180., 210., 240.,\n 270., 300., 330.])\n\n >>> out = np.zeros((rad.shape))\n >>> r = np.degrees(rad, out)\n >>> np.all(r == out)\n True\n\n ') add_newdoc('numpy._core.umath', 'rad2deg', '\n Convert angles from radians to degrees.\n\n Parameters\n ----------\n x : array_like\n Angle in radians.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The corresponding angle in degrees.\n $OUT_SCALAR_1\n\n See Also\n --------\n deg2rad : Convert angles from degrees to radians.\n unwrap : Remove large jumps in angle by wrapping.\n\n Notes\n -----\n .. versionadded:: 1.3.0\n\n rad2deg(x) is ``180 * x / pi``.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.rad2deg(np.pi/2)\n 90.0\n\n ') add_newdoc('numpy._core.umath', 'heaviside', '\n Compute the Heaviside step function.\n\n The Heaviside step function [1]_ is defined as::\n\n 0 if x1 < 0\n heaviside(x1, x2) = x2 if x1 == 0\n 1 if x1 > 0\n\n where `x2` is often taken to be 0.5, but 0 and 1 are also sometimes used.\n\n Parameters\n ----------\n x1 : array_like\n Input values.\n x2 : array_like\n The value of the function when x1 is 0.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n The output array, element-wise Heaviside step function of `x1`.\n $OUT_SCALAR_2\n\n Notes\n -----\n .. versionadded:: 1.13.0\n\n References\n ----------\n .. [1] Wikipedia, "Heaviside step function",\n https://en.wikipedia.org/wiki/Heaviside_step_function\n\n Examples\n --------\n >>> import numpy as np\n >>> np.heaviside([-1.5, 0, 2.0], 0.5)\n array([ 0. , 0.5, 1. ])\n >>> np.heaviside([-1.5, 0, 2.0], 1)\n array([ 0., 1., 1.])\n ') add_newdoc('numpy._core.umath', 'divide', '\n Divide arguments element-wise.\n\n Parameters\n ----------\n x1 : array_like\n Dividend array.\n x2 : array_like\n Divisor array.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n The quotient ``x1/x2``, element-wise.\n $OUT_SCALAR_2\n\n See Also\n --------\n seterr : Set whether to raise or warn on overflow, underflow and\n division by zero.\n\n Notes\n -----\n Equivalent to ``x1`` / ``x2`` in terms of array-broadcasting.\n\n The ``true_divide(x1, x2)`` function is an alias for\n ``divide(x1, x2)``.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.divide(2.0, 4.0)\n 0.5\n >>> x1 = np.arange(9.0).reshape((3, 3))\n >>> x2 = np.arange(3.0)\n >>> np.divide(x1, x2)\n array([[nan, 1. , 1. ],\n [inf, 4. , 2.5],\n [inf, 7. , 4. ]])\n\n The ``/`` operator can be used as a shorthand for ``np.divide`` on\n ndarrays.\n\n >>> x1 = np.arange(9.0).reshape((3, 3))\n >>> x2 = 2 * np.ones(3)\n >>> x1 / x2\n array([[0. , 0.5, 1. ],\n [1.5, 2. , 2.5],\n [3. , 3.5, 4. ]])\n\n ') add_newdoc('numpy._core.umath', 'equal', '\n Return (x1 == x2) element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input arrays.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Output array, element-wise comparison of `x1` and `x2`.\n Typically of type bool, unless ``dtype=object`` is passed.\n $OUT_SCALAR_2\n\n See Also\n --------\n not_equal, greater_equal, less_equal, greater, less\n\n Examples\n --------\n >>> import numpy as np\n >>> np.equal([0, 1, 3], np.arange(3))\n array([ True, True, False])\n\n What is compared are values, not types. So an int (1) and an array of\n length one can evaluate as True:\n\n >>> np.equal(1, np.ones(1))\n array([ True])\n\n The ``==`` operator can be used as a shorthand for ``np.equal`` on\n ndarrays.\n\n >>> a = np.array([2, 4, 6])\n >>> b = np.array([2, 4, 2])\n >>> a == b\n array([ True, True, False])\n\n ') add_newdoc('numpy._core.umath', 'exp', '\n Calculate the exponential of all elements in the input array.\n\n Parameters\n ----------\n x : array_like\n Input values.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Output array, element-wise exponential of `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n expm1 : Calculate ``exp(x) - 1`` for all elements in the array.\n exp2 : Calculate ``2**x`` for all elements in the array.\n\n Notes\n -----\n The irrational number ``e`` is also known as Euler\'s number. It is\n approximately 2.718281, and is the base of the natural logarithm,\n ``ln`` (this means that, if :math:`x = \\ln y = \\log_e y`,\n then :math:`e^x = y`. For real input, ``exp(x)`` is always positive.\n\n For complex arguments, ``x = a + ib``, we can write\n :math:`e^x = e^a e^{ib}`. The first term, :math:`e^a`, is already\n known (it is the real argument, described above). The second term,\n :math:`e^{ib}`, is :math:`\\cos b + i \\sin b`, a function with\n magnitude 1 and a periodic phase.\n\n References\n ----------\n .. [1] Wikipedia, "Exponential function",\n https://en.wikipedia.org/wiki/Exponential_function\n .. [2] M. Abramovitz and I. A. Stegun, "Handbook of Mathematical Functions\n with Formulas, Graphs, and Mathematical Tables," Dover, 1964, p. 69,\n https://personal.math.ubc.ca/~cbm/aands/page_69.htm\n\n Examples\n --------\n Plot the magnitude and phase of ``exp(x)`` in the complex plane:\n\n >>> import numpy as np\n\n >>> import matplotlib.pyplot as plt\n\n >>> x = np.linspace(-2*np.pi, 2*np.pi, 100)\n >>> xx = x + 1j * x[:, np.newaxis] # a + ib over complex plane\n >>> out = np.exp(xx)\n\n >>> plt.subplot(121)\n >>> plt.imshow(np.abs(out),\n ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap=\'gray\')\n >>> plt.title(\'Magnitude of exp(x)\')\n\n >>> plt.subplot(122)\n >>> plt.imshow(np.angle(out),\n ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap=\'hsv\')\n >>> plt.title(\'Phase (angle) of exp(x)\')\n >>> plt.show()\n\n ') add_newdoc('numpy._core.umath', 'exp2', '\n Calculate `2**p` for all `p` in the input array.\n\n Parameters\n ----------\n x : array_like\n Input values.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Element-wise 2 to the power `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n power\n\n Notes\n -----\n .. versionadded:: 1.3.0\n\n\n\n Examples\n --------\n >>> import numpy as np\n >>> np.exp2([2, 3])\n array([ 4., 8.])\n\n ') add_newdoc('numpy._core.umath', 'expm1', '\n Calculate ``exp(x) - 1`` for all elements in the array.\n\n Parameters\n ----------\n x : array_like\n Input values.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Element-wise exponential minus one: ``out = exp(x) - 1``.\n $OUT_SCALAR_1\n\n See Also\n --------\n log1p : ``log(1 + x)``, the inverse of expm1.\n\n\n Notes\n -----\n This function provides greater precision than ``exp(x) - 1``\n for small values of ``x``.\n\n Examples\n --------\n The true value of ``exp(1e-10) - 1`` is ``1.00000000005e-10`` to\n about 32 significant digits. This example shows the superiority of\n expm1 in this case.\n\n >>> import numpy as np\n\n >>> np.expm1(1e-10)\n 1.00000000005e-10\n >>> np.exp(1e-10) - 1\n 1.000000082740371e-10\n\n ') add_newdoc('numpy._core.umath', 'fabs', '\n Compute the absolute values element-wise.\n\n This function returns the absolute values (positive magnitude) of the\n data in `x`. Complex values are not handled, use `absolute` to find the\n absolute values of complex data.\n\n Parameters\n ----------\n x : array_like\n The array of numbers for which the absolute values are required. If\n `x` is a scalar, the result `y` will also be a scalar.\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n The absolute values of `x`, the returned values are always floats.\n $OUT_SCALAR_1\n\n See Also\n --------\n absolute : Absolute values including `complex` types.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.fabs(-1)\n 1.0\n >>> np.fabs([-1.2, 1.2])\n array([ 1.2, 1.2])\n\n ') add_newdoc('numpy._core.umath', 'floor', '\n Return the floor of the input, element-wise.\n\n The floor of the scalar `x` is the largest integer `i`, such that\n `i <= x`. It is often denoted as :math:`\\lfloor x \\rfloor`.\n\n Parameters\n ----------\n x : array_like\n Input data.\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n The floor of each element in `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n ceil, trunc, rint, fix\n\n Notes\n -----\n Some spreadsheet programs calculate the "floor-towards-zero", where\n ``floor(-2.5) == -2``. NumPy instead uses the definition of\n `floor` where `floor(-2.5) == -3`. The "floor-towards-zero"\n function is called ``fix`` in NumPy.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])\n >>> np.floor(a)\n array([-2., -2., -1., 0., 1., 1., 2.])\n\n ') add_newdoc('numpy._core.umath', 'floor_divide', '\n Return the largest integer smaller or equal to the division of the inputs.\n It is equivalent to the Python ``//`` operator and pairs with the\n Python ``%`` (`remainder`), function so that ``a = a % b + b * (a // b)``\n up to roundoff.\n\n Parameters\n ----------\n x1 : array_like\n Numerator.\n x2 : array_like\n Denominator.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray\n y = floor(`x1`/`x2`)\n $OUT_SCALAR_2\n\n See Also\n --------\n remainder : Remainder complementary to floor_divide.\n divmod : Simultaneous floor division and remainder.\n divide : Standard division.\n floor : Round a number to the nearest integer toward minus infinity.\n ceil : Round a number to the nearest integer toward infinity.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.floor_divide(7,3)\n 2\n >>> np.floor_divide([1., 2., 3., 4.], 2.5)\n array([ 0., 0., 1., 1.])\n\n The ``//`` operator can be used as a shorthand for ``np.floor_divide``\n on ndarrays.\n\n >>> x1 = np.array([1., 2., 3., 4.])\n >>> x1 // 2.5\n array([0., 0., 1., 1.])\n\n ') add_newdoc('numpy._core.umath', 'fmod', '\n Returns the element-wise remainder of division.\n\n This is the NumPy implementation of the C library function fmod, the\n remainder has the same sign as the dividend `x1`. It is equivalent to\n the Matlab(TM) ``rem`` function and should not be confused with the\n Python modulus operator ``x1 % x2``.\n\n Parameters\n ----------\n x1 : array_like\n Dividend.\n x2 : array_like\n Divisor.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : array_like\n The remainder of the division of `x1` by `x2`.\n $OUT_SCALAR_2\n\n See Also\n --------\n remainder : Equivalent to the Python ``%`` operator.\n divide\n\n Notes\n -----\n The result of the modulo operation for negative dividend and divisors\n is bound by conventions. For `fmod`, the sign of result is the sign of\n the dividend, while for `remainder` the sign of the result is the sign\n of the divisor. The `fmod` function is equivalent to the Matlab(TM)\n ``rem`` function.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.fmod([-3, -2, -1, 1, 2, 3], 2)\n array([-1, 0, -1, 1, 0, 1])\n >>> np.remainder([-3, -2, -1, 1, 2, 3], 2)\n array([1, 0, 1, 1, 0, 1])\n\n >>> np.fmod([5, 3], [2, 2.])\n array([ 1., 1.])\n >>> a = np.arange(-3, 3).reshape(3, 2)\n >>> a\n array([[-3, -2],\n [-1, 0],\n [ 1, 2]])\n >>> np.fmod(a, [2,2])\n array([[-1, 0],\n [-1, 0],\n [ 1, 0]])\n\n ') add_newdoc('numpy._core.umath', 'greater', '\n Return the truth value of (x1 > x2) element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input arrays.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Output array, element-wise comparison of `x1` and `x2`.\n Typically of type bool, unless ``dtype=object`` is passed.\n $OUT_SCALAR_2\n\n\n See Also\n --------\n greater_equal, less, less_equal, equal, not_equal\n\n Examples\n --------\n >>> import numpy as np\n >>> np.greater([4,2],[2,2])\n array([ True, False])\n\n The ``>`` operator can be used as a shorthand for ``np.greater`` on\n ndarrays.\n\n >>> a = np.array([4, 2])\n >>> b = np.array([2, 2])\n >>> a > b\n array([ True, False])\n\n ') add_newdoc('numpy._core.umath', 'greater_equal', '\n Return the truth value of (x1 >= x2) element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input arrays.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : bool or ndarray of bool\n Output array, element-wise comparison of `x1` and `x2`.\n Typically of type bool, unless ``dtype=object`` is passed.\n $OUT_SCALAR_2\n\n See Also\n --------\n greater, less, less_equal, equal, not_equal\n\n Examples\n --------\n >>> import numpy as np\n >>> np.greater_equal([4, 2, 1], [2, 2, 2])\n array([ True, True, False])\n\n The ``>=`` operator can be used as a shorthand for ``np.greater_equal``\n on ndarrays.\n\n >>> a = np.array([4, 2, 1])\n >>> b = np.array([2, 2, 2])\n >>> a >= b\n array([ True, True, False])\n\n ') add_newdoc('numpy._core.umath', 'hypot', '\n Given the "legs" of a right triangle, return its hypotenuse.\n\n Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or\n `x2` is scalar_like (i.e., unambiguously cast-able to a scalar type),\n it is broadcast for use with each element of the other argument.\n (See Examples)\n\n Parameters\n ----------\n x1, x2 : array_like\n Leg of the triangle(s).\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n z : ndarray\n The hypotenuse of the triangle(s).\n $OUT_SCALAR_2\n\n Examples\n --------\n >>> import numpy as np\n >>> np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3)))\n array([[ 5., 5., 5.],\n [ 5., 5., 5.],\n [ 5., 5., 5.]])\n\n Example showing broadcast of scalar_like argument:\n\n >>> np.hypot(3*np.ones((3, 3)), [4])\n array([[ 5., 5., 5.],\n [ 5., 5., 5.],\n [ 5., 5., 5.]])\n\n ') add_newdoc('numpy._core.umath', 'invert', '\n Compute bit-wise inversion, or bit-wise NOT, element-wise.\n\n Computes the bit-wise NOT of the underlying binary representation of\n the integers in the input arrays. This ufunc implements the C/Python\n operator ``~``.\n\n For signed integer inputs, the bit-wise NOT of the absolute value is\n returned. In a two\'s-complement system, this operation effectively flips\n all the bits, resulting in a representation that corresponds to the\n negative of the input plus one. This is the most common method of\n representing signed integers on computers [1]_. A N-bit two\'s-complement\n system can represent every integer in the range :math:`-2^{N-1}` to\n :math:`+2^{N-1}-1`.\n\n Parameters\n ----------\n x : array_like\n Only integer and boolean types are handled.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Result.\n $OUT_SCALAR_1\n\n See Also\n --------\n bitwise_and, bitwise_or, bitwise_xor\n logical_not\n binary_repr :\n Return the binary representation of the input number as a string.\n\n Notes\n -----\n ``numpy.bitwise_not`` is an alias for `invert`:\n\n >>> np.bitwise_not is np.invert\n True\n\n References\n ----------\n .. [1] Wikipedia, "Two\'s complement",\n https://en.wikipedia.org/wiki/Two\'s_complement\n\n Examples\n --------\n >>> import numpy as np\n\n We\'ve seen that 13 is represented by ``00001101``.\n The invert or bit-wise NOT of 13 is then:\n\n >>> x = np.invert(np.array(13, dtype=np.uint8))\n >>> x\n np.uint8(242)\n >>> np.binary_repr(x, width=8)\n \'11110010\'\n\n The result depends on the bit-width:\n\n >>> x = np.invert(np.array(13, dtype=np.uint16))\n >>> x\n np.uint16(65522)\n >>> np.binary_repr(x, width=16)\n \'1111111111110010\'\n\n When using signed integer types, the result is the bit-wise NOT of\n the unsigned type, interpreted as a signed integer:\n\n >>> np.invert(np.array([13], dtype=np.int8))\n array([-14], dtype=int8)\n >>> np.binary_repr(-14, width=8)\n \'11110010\'\n\n Booleans are accepted as well:\n\n >>> np.invert(np.array([True, False]))\n array([False, True])\n\n The ``~`` operator can be used as a shorthand for ``np.invert`` on\n ndarrays.\n\n >>> x1 = np.array([True, False])\n >>> ~x1\n array([False, True])\n\n ') add_newdoc('numpy._core.umath', 'isfinite', '\n Test element-wise for finiteness (not infinity and not Not a Number).\n\n The result is returned as a boolean array.\n\n Parameters\n ----------\n x : array_like\n Input values.\n $PARAMS\n\n Returns\n -------\n y : ndarray, bool\n True where ``x`` is not positive infinity, negative infinity,\n or NaN; false otherwise.\n $OUT_SCALAR_1\n\n See Also\n --------\n isinf, isneginf, isposinf, isnan\n\n Notes\n -----\n Not a Number, positive infinity and negative infinity are considered\n to be non-finite.\n\n NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic\n (IEEE 754). This means that Not a Number is not equivalent to infinity.\n Also that positive infinity is not equivalent to negative infinity. But\n infinity is equivalent to positive infinity. Errors result if the\n second argument is also supplied when `x` is a scalar input, or if\n first and second arguments have different shapes.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.isfinite(1)\n True\n >>> np.isfinite(0)\n True\n >>> np.isfinite(np.nan)\n False\n >>> np.isfinite(np.inf)\n False\n >>> np.isfinite(-np.inf)\n False\n >>> np.isfinite([np.log(-1.),1.,np.log(0)])\n array([False, True, False])\n\n >>> x = np.array([-np.inf, 0., np.inf])\n >>> y = np.array([2, 2, 2])\n >>> np.isfinite(x, y)\n array([0, 1, 0])\n >>> y\n array([0, 1, 0])\n\n ') add_newdoc('numpy._core.umath', 'isinf', '\n Test element-wise for positive or negative infinity.\n\n Returns a boolean array of the same shape as `x`, True where ``x ==\n +/-inf``, otherwise False.\n\n Parameters\n ----------\n x : array_like\n Input values\n $PARAMS\n\n Returns\n -------\n y : bool (scalar) or boolean ndarray\n True where ``x`` is positive or negative infinity, false otherwise.\n $OUT_SCALAR_1\n\n See Also\n --------\n isneginf, isposinf, isnan, isfinite\n\n Notes\n -----\n NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic\n (IEEE 754).\n\n Errors result if the second argument is supplied when the first\n argument is a scalar, or if the first and second arguments have\n different shapes.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.isinf(np.inf)\n True\n >>> np.isinf(np.nan)\n False\n >>> np.isinf(-np.inf)\n True\n >>> np.isinf([np.inf, -np.inf, 1.0, np.nan])\n array([ True, True, False, False])\n\n >>> x = np.array([-np.inf, 0., np.inf])\n >>> y = np.array([2, 2, 2])\n >>> np.isinf(x, y)\n array([1, 0, 1])\n >>> y\n array([1, 0, 1])\n\n ') add_newdoc('numpy._core.umath', 'isnan', '\n Test element-wise for NaN and return result as a boolean array.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n y : ndarray or bool\n True where ``x`` is NaN, false otherwise.\n $OUT_SCALAR_1\n\n See Also\n --------\n isinf, isneginf, isposinf, isfinite, isnat\n\n Notes\n -----\n NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic\n (IEEE 754). This means that Not a Number is not equivalent to infinity.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.isnan(np.nan)\n True\n >>> np.isnan(np.inf)\n False\n >>> np.isnan([np.log(-1.),1.,np.log(0)])\n array([ True, False, False])\n\n ') add_newdoc('numpy._core.umath', 'isnat', '\n Test element-wise for NaT (not a time) and return result as a boolean array.\n\n .. versionadded:: 1.13.0\n\n Parameters\n ----------\n x : array_like\n Input array with datetime or timedelta data type.\n $PARAMS\n\n Returns\n -------\n y : ndarray or bool\n True where ``x`` is NaT, false otherwise.\n $OUT_SCALAR_1\n\n See Also\n --------\n isnan, isinf, isneginf, isposinf, isfinite\n\n Examples\n --------\n >>> import numpy as np\n >>> np.isnat(np.datetime64("NaT"))\n True\n >>> np.isnat(np.datetime64("2016-01-01"))\n False\n >>> np.isnat(np.array(["NaT", "2016-01-01"], dtype="datetime64[ns]"))\n array([ True, False])\n\n ') add_newdoc('numpy._core.umath', 'left_shift', "\n Shift the bits of an integer to the left.\n\n Bits are shifted to the left by appending `x2` 0s at the right of `x1`.\n Since the internal representation of numbers is in binary format, this\n operation is equivalent to multiplying `x1` by ``2**x2``.\n\n Parameters\n ----------\n x1 : array_like of integer type\n Input values.\n x2 : array_like of integer type\n Number of zeros to append to `x1`. Has to be non-negative.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : array of integer type\n Return `x1` with bits shifted `x2` times to the left.\n $OUT_SCALAR_2\n\n See Also\n --------\n right_shift : Shift the bits of an integer to the right.\n binary_repr : Return the binary representation of the input number\n as a string.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.binary_repr(5)\n '101'\n >>> np.left_shift(5, 2)\n 20\n >>> np.binary_repr(20)\n '10100'\n\n >>> np.left_shift(5, [1,2,3])\n array([10, 20, 40])\n\n Note that the dtype of the second argument may change the dtype of the\n result and can lead to unexpected results in some cases (see\n :ref:`Casting Rules `):\n\n >>> a = np.left_shift(np.uint8(255), np.int64(1)) # Expect 254\n >>> print(a, type(a)) # Unexpected result due to upcasting\n 510 \n >>> b = np.left_shift(np.uint8(255), np.uint8(1))\n >>> print(b, type(b))\n 254 \n\n The ``<<`` operator can be used as a shorthand for ``np.left_shift`` on\n ndarrays.\n\n >>> x1 = 5\n >>> x2 = np.array([1, 2, 3])\n >>> x1 << x2\n array([10, 20, 40])\n\n ") add_newdoc('numpy._core.umath', 'less', '\n Return the truth value of (x1 < x2) element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input arrays.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Output array, element-wise comparison of `x1` and `x2`.\n Typically of type bool, unless ``dtype=object`` is passed.\n $OUT_SCALAR_2\n\n See Also\n --------\n greater, less_equal, greater_equal, equal, not_equal\n\n Examples\n --------\n >>> import numpy as np\n >>> np.less([1, 2], [2, 2])\n array([ True, False])\n\n The ``<`` operator can be used as a shorthand for ``np.less`` on ndarrays.\n\n >>> a = np.array([1, 2])\n >>> b = np.array([2, 2])\n >>> a < b\n array([ True, False])\n\n ') add_newdoc('numpy._core.umath', 'less_equal', '\n Return the truth value of (x1 <= x2) element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input arrays.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Output array, element-wise comparison of `x1` and `x2`.\n Typically of type bool, unless ``dtype=object`` is passed.\n $OUT_SCALAR_2\n\n See Also\n --------\n greater, less, greater_equal, equal, not_equal\n\n Examples\n --------\n >>> import numpy as np\n >>> np.less_equal([4, 2, 1], [2, 2, 2])\n array([False, True, True])\n\n The ``<=`` operator can be used as a shorthand for ``np.less_equal`` on\n ndarrays.\n\n >>> a = np.array([4, 2, 1])\n >>> b = np.array([2, 2, 2])\n >>> a <= b\n array([False, True, True])\n\n ') add_newdoc('numpy._core.umath', 'log', '\n Natural logarithm, element-wise.\n\n The natural logarithm `log` is the inverse of the exponential function,\n so that `log(exp(x)) = x`. The natural logarithm is logarithm in base\n `e`.\n\n Parameters\n ----------\n x : array_like\n Input value.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The natural logarithm of `x`, element-wise.\n $OUT_SCALAR_1\n\n See Also\n --------\n log10, log2, log1p, emath.log\n\n Notes\n -----\n Logarithm is a multivalued function: for each `x` there is an infinite\n number of `z` such that `exp(z) = x`. The convention is to return the\n `z` whose imaginary part lies in `(-pi, pi]`.\n\n For real-valued input data types, `log` always returns real output. For\n each value that cannot be expressed as a real number or infinity, it\n yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `log` is a complex analytical function that\n has a branch cut `[-inf, 0]` and is continuous from above on it. `log`\n handles the floating-point negative zero as an infinitesimal negative\n number, conforming to the C99 standard.\n\n In the cases where the input has a negative real part and a very small\n negative complex part (approaching 0), the result is so close to `-pi`\n that it evaluates to exactly `-pi`.\n\n References\n ----------\n .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",\n 10th printing, 1964, pp. 67.\n https://personal.math.ubc.ca/~cbm/aands/page_67.htm\n .. [2] Wikipedia, "Logarithm". https://en.wikipedia.org/wiki/Logarithm\n\n Examples\n --------\n >>> import numpy as np\n >>> np.log([1, np.e, np.e**2, 0])\n array([ 0., 1., 2., -inf])\n\n ') add_newdoc('numpy._core.umath', 'log10', '\n Return the base 10 logarithm of the input array, element-wise.\n\n Parameters\n ----------\n x : array_like\n Input values.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The logarithm to the base 10 of `x`, element-wise. NaNs are\n returned where x is negative.\n $OUT_SCALAR_1\n\n See Also\n --------\n emath.log10\n\n Notes\n -----\n Logarithm is a multivalued function: for each `x` there is an infinite\n number of `z` such that `10**z = x`. The convention is to return the\n `z` whose imaginary part lies in `(-pi, pi]`.\n\n For real-valued input data types, `log10` always returns real output.\n For each value that cannot be expressed as a real number or infinity,\n it yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `log10` is a complex analytical function that\n has a branch cut `[-inf, 0]` and is continuous from above on it.\n `log10` handles the floating-point negative zero as an infinitesimal\n negative number, conforming to the C99 standard.\n\n In the cases where the input has a negative real part and a very small\n negative complex part (approaching 0), the result is so close to `-pi`\n that it evaluates to exactly `-pi`.\n\n References\n ----------\n .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",\n 10th printing, 1964, pp. 67.\n https://personal.math.ubc.ca/~cbm/aands/page_67.htm\n .. [2] Wikipedia, "Logarithm". https://en.wikipedia.org/wiki/Logarithm\n\n Examples\n --------\n >>> import numpy as np\n >>> np.log10([1e-15, -3.])\n array([-15., nan])\n\n ') add_newdoc('numpy._core.umath', 'log2', '\n Base-2 logarithm of `x`.\n\n Parameters\n ----------\n x : array_like\n Input values.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n Base-2 logarithm of `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n log, log10, log1p, emath.log2\n\n Notes\n -----\n .. versionadded:: 1.3.0\n\n Logarithm is a multivalued function: for each `x` there is an infinite\n number of `z` such that `2**z = x`. The convention is to return the `z`\n whose imaginary part lies in `(-pi, pi]`.\n\n For real-valued input data types, `log2` always returns real output.\n For each value that cannot be expressed as a real number or infinity,\n it yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `log2` is a complex analytical function that\n has a branch cut `[-inf, 0]` and is continuous from above on it. `log2`\n handles the floating-point negative zero as an infinitesimal negative\n number, conforming to the C99 standard.\n\n In the cases where the input has a negative real part and a very small\n negative complex part (approaching 0), the result is so close to `-pi`\n that it evaluates to exactly `-pi`.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.array([0, 1, 2, 2**4])\n >>> np.log2(x)\n array([-inf, 0., 1., 4.])\n\n >>> xi = np.array([0+1.j, 1, 2+0.j, 4.j])\n >>> np.log2(xi)\n array([ 0.+2.26618007j, 0.+0.j , 1.+0.j , 2.+2.26618007j])\n\n ') add_newdoc('numpy._core.umath', 'logaddexp', '\n Logarithm of the sum of exponentiations of the inputs.\n\n Calculates ``log(exp(x1) + exp(x2))``. This function is useful in\n statistics where the calculated probabilities of events may be so small\n as to exceed the range of normal floating point numbers. In such cases\n the logarithm of the calculated probability is stored. This function\n allows adding probabilities stored in such a fashion.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input values.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n result : ndarray\n Logarithm of ``exp(x1) + exp(x2)``.\n $OUT_SCALAR_2\n\n See Also\n --------\n logaddexp2: Logarithm of the sum of exponentiations of inputs in base 2.\n\n Notes\n -----\n .. versionadded:: 1.3.0\n\n Examples\n --------\n >>> import numpy as np\n >>> prob1 = np.log(1e-50)\n >>> prob2 = np.log(2.5e-50)\n >>> prob12 = np.logaddexp(prob1, prob2)\n >>> prob12\n -113.87649168120691\n >>> np.exp(prob12)\n 3.5000000000000057e-50\n\n ') add_newdoc('numpy._core.umath', 'logaddexp2', '\n Logarithm of the sum of exponentiations of the inputs in base-2.\n\n Calculates ``log2(2**x1 + 2**x2)``. This function is useful in machine\n learning when the calculated probabilities of events may be so small as\n to exceed the range of normal floating point numbers. In such cases\n the base-2 logarithm of the calculated probability can be used instead.\n This function allows adding probabilities stored in such a fashion.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input values.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n result : ndarray\n Base-2 logarithm of ``2**x1 + 2**x2``.\n $OUT_SCALAR_2\n\n See Also\n --------\n logaddexp: Logarithm of the sum of exponentiations of the inputs.\n\n Notes\n -----\n .. versionadded:: 1.3.0\n\n Examples\n --------\n >>> import numpy as np\n >>> prob1 = np.log2(1e-50)\n >>> prob2 = np.log2(2.5e-50)\n >>> prob12 = np.logaddexp2(prob1, prob2)\n >>> prob1, prob2, prob12\n (-166.09640474436813, -164.77447664948076, -164.28904982231052)\n >>> 2**prob12\n 3.4999999999999914e-50\n\n ') add_newdoc('numpy._core.umath', 'log1p', '\n Return the natural logarithm of one plus the input array, element-wise.\n\n Calculates ``log(1 + x)``.\n\n Parameters\n ----------\n x : array_like\n Input values.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n Natural logarithm of `1 + x`, element-wise.\n $OUT_SCALAR_1\n\n See Also\n --------\n expm1 : ``exp(x) - 1``, the inverse of `log1p`.\n\n Notes\n -----\n For real-valued input, `log1p` is accurate also for `x` so small\n that `1 + x == 1` in floating-point accuracy.\n\n Logarithm is a multivalued function: for each `x` there is an infinite\n number of `z` such that `exp(z) = 1 + x`. The convention is to return\n the `z` whose imaginary part lies in `[-pi, pi]`.\n\n For real-valued input data types, `log1p` always returns real output.\n For each value that cannot be expressed as a real number or infinity,\n it yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `log1p` is a complex analytical function that\n has a branch cut `[-inf, -1]` and is continuous from above on it.\n `log1p` handles the floating-point negative zero as an infinitesimal\n negative number, conforming to the C99 standard.\n\n References\n ----------\n .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",\n 10th printing, 1964, pp. 67.\n https://personal.math.ubc.ca/~cbm/aands/page_67.htm\n .. [2] Wikipedia, "Logarithm". https://en.wikipedia.org/wiki/Logarithm\n\n Examples\n --------\n >>> import numpy as np\n >>> np.log1p(1e-99)\n 1e-99\n >>> np.log(1 + 1e-99)\n 0.0\n\n ') add_newdoc('numpy._core.umath', 'logical_and', '\n Compute the truth value of x1 AND x2 element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input arrays.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray or bool\n Boolean result of the logical AND operation applied to the elements\n of `x1` and `x2`; the shape is determined by broadcasting.\n $OUT_SCALAR_2\n\n See Also\n --------\n logical_or, logical_not, logical_xor\n bitwise_and\n\n Examples\n --------\n >>> import numpy as np\n >>> np.logical_and(True, False)\n False\n >>> np.logical_and([True, False], [False, False])\n array([False, False])\n\n >>> x = np.arange(5)\n >>> np.logical_and(x>1, x<4)\n array([False, False, True, True, False])\n\n\n The ``&`` operator can be used as a shorthand for ``np.logical_and`` on\n boolean ndarrays.\n\n >>> a = np.array([True, False])\n >>> b = np.array([False, False])\n >>> a & b\n array([False, False])\n\n ') add_newdoc('numpy._core.umath', 'logical_not', '\n Compute the truth value of NOT x element-wise.\n\n Parameters\n ----------\n x : array_like\n Logical NOT is applied to the elements of `x`.\n $PARAMS\n\n Returns\n -------\n y : bool or ndarray of bool\n Boolean result with the same shape as `x` of the NOT operation\n on elements of `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n logical_and, logical_or, logical_xor\n\n Examples\n --------\n >>> import numpy as np\n >>> np.logical_not(3)\n False\n >>> np.logical_not([True, False, 0, 1])\n array([False, True, True, False])\n\n >>> x = np.arange(5)\n >>> np.logical_not(x<3)\n array([False, False, False, True, True])\n\n ') add_newdoc('numpy._core.umath', 'logical_or', '\n Compute the truth value of x1 OR x2 element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Logical OR is applied to the elements of `x1` and `x2`.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray or bool\n Boolean result of the logical OR operation applied to the elements\n of `x1` and `x2`; the shape is determined by broadcasting.\n $OUT_SCALAR_2\n\n See Also\n --------\n logical_and, logical_not, logical_xor\n bitwise_or\n\n Examples\n --------\n >>> import numpy as np\n >>> np.logical_or(True, False)\n True\n >>> np.logical_or([True, False], [False, False])\n array([ True, False])\n\n >>> x = np.arange(5)\n >>> np.logical_or(x < 1, x > 3)\n array([ True, False, False, False, True])\n\n The ``|`` operator can be used as a shorthand for ``np.logical_or`` on\n boolean ndarrays.\n\n >>> a = np.array([True, False])\n >>> b = np.array([False, False])\n >>> a | b\n array([ True, False])\n\n ') add_newdoc('numpy._core.umath', 'logical_xor', '\n Compute the truth value of x1 XOR x2, element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Logical XOR is applied to the elements of `x1` and `x2`.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : bool or ndarray of bool\n Boolean result of the logical XOR operation applied to the elements\n of `x1` and `x2`; the shape is determined by broadcasting.\n $OUT_SCALAR_2\n\n See Also\n --------\n logical_and, logical_or, logical_not, bitwise_xor\n\n Examples\n --------\n >>> import numpy as np\n >>> np.logical_xor(True, False)\n True\n >>> np.logical_xor([True, True, False, False], [True, False, True, False])\n array([False, True, True, False])\n\n >>> x = np.arange(5)\n >>> np.logical_xor(x < 1, x > 3)\n array([ True, False, False, False, True])\n\n Simple example showing support of broadcasting\n\n >>> np.logical_xor(0, np.eye(2))\n array([[ True, False],\n [False, True]])\n\n ') add_newdoc('numpy._core.umath', 'maximum', '\n Element-wise maximum of array elements.\n\n Compare two arrays and return a new array containing the element-wise\n maxima. If one of the elements being compared is a NaN, then that\n element is returned. If both elements are NaNs then the first is\n returned. The latter distinction is important for complex NaNs, which\n are defined as at least one of the real or imaginary parts being a NaN.\n The net effect is that NaNs are propagated.\n\n Parameters\n ----------\n x1, x2 : array_like\n The arrays holding the elements to be compared.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n The maximum of `x1` and `x2`, element-wise.\n $OUT_SCALAR_2\n\n See Also\n --------\n minimum :\n Element-wise minimum of two arrays, propagates NaNs.\n fmax :\n Element-wise maximum of two arrays, ignores NaNs.\n amax :\n The maximum value of an array along a given axis, propagates NaNs.\n nanmax :\n The maximum value of an array along a given axis, ignores NaNs.\n\n fmin, amin, nanmin\n\n Notes\n -----\n The maximum is equivalent to ``np.where(x1 >= x2, x1, x2)`` when\n neither x1 nor x2 are nans, but it is faster and does proper\n broadcasting.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.maximum([2, 3, 4], [1, 5, 2])\n array([2, 5, 4])\n\n >>> np.maximum(np.eye(2), [0.5, 2]) # broadcasting\n array([[ 1. , 2. ],\n [ 0.5, 2. ]])\n\n >>> np.maximum([np.nan, 0, np.nan], [0, np.nan, np.nan])\n array([nan, nan, nan])\n >>> np.maximum(np.inf, 1)\n inf\n\n ') add_newdoc('numpy._core.umath', 'minimum', '\n Element-wise minimum of array elements.\n\n Compare two arrays and return a new array containing the element-wise\n minima. If one of the elements being compared is a NaN, then that\n element is returned. If both elements are NaNs then the first is\n returned. The latter distinction is important for complex NaNs, which\n are defined as at least one of the real or imaginary parts being a NaN.\n The net effect is that NaNs are propagated.\n\n Parameters\n ----------\n x1, x2 : array_like\n The arrays holding the elements to be compared.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n The minimum of `x1` and `x2`, element-wise.\n $OUT_SCALAR_2\n\n See Also\n --------\n maximum :\n Element-wise maximum of two arrays, propagates NaNs.\n fmin :\n Element-wise minimum of two arrays, ignores NaNs.\n amin :\n The minimum value of an array along a given axis, propagates NaNs.\n nanmin :\n The minimum value of an array along a given axis, ignores NaNs.\n\n fmax, amax, nanmax\n\n Notes\n -----\n The minimum is equivalent to ``np.where(x1 <= x2, x1, x2)`` when\n neither x1 nor x2 are NaNs, but it is faster and does proper\n broadcasting.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.minimum([2, 3, 4], [1, 5, 2])\n array([1, 3, 2])\n\n >>> np.minimum(np.eye(2), [0.5, 2]) # broadcasting\n array([[ 0.5, 0. ],\n [ 0. , 1. ]])\n\n >>> np.minimum([np.nan, 0, np.nan],[0, np.nan, np.nan])\n array([nan, nan, nan])\n >>> np.minimum(-np.inf, 1)\n -inf\n\n ') add_newdoc('numpy._core.umath', 'fmax', '\n Element-wise maximum of array elements.\n\n Compare two arrays and return a new array containing the element-wise\n maxima. If one of the elements being compared is a NaN, then the\n non-nan element is returned. If both elements are NaNs then the first\n is returned. The latter distinction is important for complex NaNs,\n which are defined as at least one of the real or imaginary parts being\n a NaN. The net effect is that NaNs are ignored when possible.\n\n Parameters\n ----------\n x1, x2 : array_like\n The arrays holding the elements to be compared.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n The maximum of `x1` and `x2`, element-wise.\n $OUT_SCALAR_2\n\n See Also\n --------\n fmin :\n Element-wise minimum of two arrays, ignores NaNs.\n maximum :\n Element-wise maximum of two arrays, propagates NaNs.\n amax :\n The maximum value of an array along a given axis, propagates NaNs.\n nanmax :\n The maximum value of an array along a given axis, ignores NaNs.\n\n minimum, amin, nanmin\n\n Notes\n -----\n .. versionadded:: 1.3.0\n\n The fmax is equivalent to ``np.where(x1 >= x2, x1, x2)`` when neither\n x1 nor x2 are NaNs, but it is faster and does proper broadcasting.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.fmax([2, 3, 4], [1, 5, 2])\n array([ 2, 5, 4])\n\n >>> np.fmax(np.eye(2), [0.5, 2])\n array([[ 1. , 2. ],\n [ 0.5, 2. ]])\n\n >>> np.fmax([np.nan, 0, np.nan],[0, np.nan, np.nan])\n array([ 0., 0., nan])\n\n ') add_newdoc('numpy._core.umath', 'fmin', '\n Element-wise minimum of array elements.\n\n Compare two arrays and return a new array containing the element-wise\n minima. If one of the elements being compared is a NaN, then the\n non-nan element is returned. If both elements are NaNs then the first\n is returned. The latter distinction is important for complex NaNs,\n which are defined as at least one of the real or imaginary parts being\n a NaN. The net effect is that NaNs are ignored when possible.\n\n Parameters\n ----------\n x1, x2 : array_like\n The arrays holding the elements to be compared.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n The minimum of `x1` and `x2`, element-wise.\n $OUT_SCALAR_2\n\n See Also\n --------\n fmax :\n Element-wise maximum of two arrays, ignores NaNs.\n minimum :\n Element-wise minimum of two arrays, propagates NaNs.\n amin :\n The minimum value of an array along a given axis, propagates NaNs.\n nanmin :\n The minimum value of an array along a given axis, ignores NaNs.\n\n maximum, amax, nanmax\n\n Notes\n -----\n .. versionadded:: 1.3.0\n\n The fmin is equivalent to ``np.where(x1 <= x2, x1, x2)`` when neither\n x1 nor x2 are NaNs, but it is faster and does proper broadcasting.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.fmin([2, 3, 4], [1, 5, 2])\n array([1, 3, 2])\n\n >>> np.fmin(np.eye(2), [0.5, 2])\n array([[ 0.5, 0. ],\n [ 0. , 1. ]])\n\n >>> np.fmin([np.nan, 0, np.nan],[0, np.nan, np.nan])\n array([ 0., 0., nan])\n\n ') add_newdoc('numpy._core.umath', 'clip', '\n Clip (limit) the values in an array.\n\n Given an interval, values outside the interval are clipped to\n the interval edges. For example, if an interval of ``[0, 1]``\n is specified, values smaller than 0 become 0, and values larger\n than 1 become 1.\n\n Equivalent to but faster than ``np.minimum(np.maximum(a, a_min), a_max)``.\n\n Parameters\n ----------\n a : array_like\n Array containing elements to clip.\n a_min : array_like\n Minimum value.\n a_max : array_like\n Maximum value.\n out : ndarray, optional\n The results will be placed in this array. It may be the input\n array for in-place clipping. `out` must be of the right shape\n to hold the output. Its type is preserved.\n $PARAMS\n\n See Also\n --------\n numpy.clip :\n Wrapper that makes the ``a_min`` and ``a_max`` arguments optional,\n dispatching to one of `~numpy._core.umath.clip`,\n `~numpy._core.umath.minimum`, and `~numpy._core.umath.maximum`.\n\n Returns\n -------\n clipped_array : ndarray\n An array with the elements of `a`, but where values\n < `a_min` are replaced with `a_min`, and those > `a_max`\n with `a_max`.\n ') add_newdoc('numpy._core.umath', 'matmul', '\n Matrix product of two arrays.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input arrays, scalars not allowed.\n out : ndarray, optional\n A location into which the result is stored. If provided, it must have\n a shape that matches the signature `(n,k),(k,m)->(n,m)`. If not\n provided or None, a freshly-allocated array is returned.\n **kwargs\n For other keyword-only arguments, see the\n :ref:`ufunc docs `.\n\n .. versionadded:: 1.16\n Now handles ufunc kwargs\n\n Returns\n -------\n y : ndarray\n The matrix product of the inputs.\n This is a scalar only when both x1, x2 are 1-d vectors.\n\n Raises\n ------\n ValueError\n If the last dimension of `x1` is not the same size as\n the second-to-last dimension of `x2`.\n\n If a scalar value is passed in.\n\n See Also\n --------\n vdot : Complex-conjugating dot product.\n tensordot : Sum products over arbitrary axes.\n einsum : Einstein summation convention.\n dot : alternative matrix product with different broadcasting rules.\n\n Notes\n -----\n\n The behavior depends on the arguments in the following way.\n\n - If both arguments are 2-D they are multiplied like conventional\n matrices.\n - If either argument is N-D, N > 2, it is treated as a stack of\n matrices residing in the last two indexes and broadcast accordingly.\n - If the first argument is 1-D, it is promoted to a matrix by\n prepending a 1 to its dimensions. After matrix multiplication\n the prepended 1 is removed.\n - If the second argument is 1-D, it is promoted to a matrix by\n appending a 1 to its dimensions. After matrix multiplication\n the appended 1 is removed.\n\n ``matmul`` differs from ``dot`` in two important ways:\n\n - Multiplication by scalars is not allowed, use ``*`` instead.\n - Stacks of matrices are broadcast together as if the matrices\n were elements, respecting the signature ``(n,k),(k,m)->(n,m)``:\n\n >>> a = np.ones([9, 5, 7, 4])\n >>> c = np.ones([9, 5, 4, 3])\n >>> np.dot(a, c).shape\n (9, 5, 7, 9, 5, 3)\n >>> np.matmul(a, c).shape\n (9, 5, 7, 3)\n >>> # n is 7, k is 4, m is 3\n\n The matmul function implements the semantics of the ``@`` operator\n introduced in Python 3.5 following :pep:`465`.\n\n It uses an optimized BLAS library when possible (see `numpy.linalg`).\n\n Examples\n --------\n For 2-D arrays it is the matrix product:\n\n >>> import numpy as np\n\n >>> a = np.array([[1, 0],\n ... [0, 1]])\n >>> b = np.array([[4, 1],\n ... [2, 2]])\n >>> np.matmul(a, b)\n array([[4, 1],\n [2, 2]])\n\n For 2-D mixed with 1-D, the result is the usual.\n\n >>> a = np.array([[1, 0],\n ... [0, 1]])\n >>> b = np.array([1, 2])\n >>> np.matmul(a, b)\n array([1, 2])\n >>> np.matmul(b, a)\n array([1, 2])\n\n\n Broadcasting is conventional for stacks of arrays\n\n >>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4))\n >>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2))\n >>> np.matmul(a,b).shape\n (2, 2, 2)\n >>> np.matmul(a, b)[0, 1, 1]\n 98\n >>> sum(a[0, 1, :] * b[0 , :, 1])\n 98\n\n Vector, vector returns the scalar inner product, but neither argument\n is complex-conjugated:\n\n >>> np.matmul([2j, 3j], [2j, 3j])\n (-13+0j)\n\n Scalar multiplication raises an error.\n\n >>> np.matmul([1,2], 3)\n Traceback (most recent call last):\n ...\n ValueError: matmul: Input operand 1 does not have enough dimensions ...\n\n The ``@`` operator can be used as a shorthand for ``np.matmul`` on\n ndarrays.\n\n >>> x1 = np.array([2j, 3j])\n >>> x2 = np.array([2j, 3j])\n >>> x1 @ x2\n (-13+0j)\n\n .. versionadded:: 1.10.0\n ') add_newdoc('numpy._core.umath', 'vecdot', '\n Vector dot product of two arrays.\n\n Let :math:`\\mathbf{a}` be a vector in `x1` and :math:`\\mathbf{b}` be\n a corresponding vector in `x2`. The dot product is defined as:\n\n .. math::\n \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i\n\n where the sum is over the last dimension (unless `axis` is specified) and\n where :math:`\\overline{a_i}` denotes the complex conjugate if :math:`a_i`\n is complex and the identity otherwise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input arrays, scalars not allowed.\n out : ndarray, optional\n A location into which the result is stored. If provided, it must have\n a shape that the broadcasted shape of `x1` and `x2` with the last axis\n removed. If not provided or None, a freshly-allocated array is used.\n **kwargs\n For other keyword-only arguments, see the\n :ref:`ufunc docs `.\n\n Returns\n -------\n y : ndarray\n The vector dot product of the inputs.\n This is a scalar only when both x1, x2 are 1-d vectors.\n\n Raises\n ------\n ValueError\n If the last dimension of `x1` is not the same size as\n the last dimension of `x2`.\n\n If a scalar value is passed in.\n\n See Also\n --------\n vdot : same but flattens arguments first\n einsum : Einstein summation convention.\n\n Examples\n --------\n >>> import numpy as np\n\n Get the projected size along a given normal for an array of vectors.\n\n >>> v = np.array([[0., 5., 0.], [0., 0., 10.], [0., 6., 8.]])\n >>> n = np.array([0., 0.6, 0.8])\n >>> np.vecdot(v, n)\n array([ 3., 8., 10.])\n\n .. versionadded:: 2.0.0\n ') add_newdoc('numpy._core.umath', 'modf', '\n Return the fractional and integral parts of an array, element-wise.\n\n The fractional and integral parts are negative if the given number is\n negative.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n y1 : ndarray\n Fractional part of `x`.\n $OUT_SCALAR_1\n y2 : ndarray\n Integral part of `x`.\n $OUT_SCALAR_1\n\n Notes\n -----\n For integer input the return values are floats.\n\n See Also\n --------\n divmod : ``divmod(x, 1)`` is equivalent to ``modf`` with the return values\n switched, except it always has a positive remainder.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.modf([0, 3.5])\n (array([ 0. , 0.5]), array([ 0., 3.]))\n >>> np.modf(-0.5)\n (-0.5, -0)\n\n ') add_newdoc('numpy._core.umath', 'multiply', '\n Multiply arguments element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input arrays to be multiplied.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The product of `x1` and `x2`, element-wise.\n $OUT_SCALAR_2\n\n Notes\n -----\n Equivalent to `x1` * `x2` in terms of array broadcasting.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.multiply(2.0, 4.0)\n 8.0\n\n >>> x1 = np.arange(9.0).reshape((3, 3))\n >>> x2 = np.arange(3.0)\n >>> np.multiply(x1, x2)\n array([[ 0., 1., 4.],\n [ 0., 4., 10.],\n [ 0., 7., 16.]])\n\n The ``*`` operator can be used as a shorthand for ``np.multiply`` on\n ndarrays.\n\n >>> x1 = np.arange(9.0).reshape((3, 3))\n >>> x2 = np.arange(3.0)\n >>> x1 * x2\n array([[ 0., 1., 4.],\n [ 0., 4., 10.],\n [ 0., 7., 16.]])\n\n ') add_newdoc('numpy._core.umath', 'negative', '\n Numerical negative, element-wise.\n\n Parameters\n ----------\n x : array_like or scalar\n Input array.\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n Returned array or scalar: `y = -x`.\n $OUT_SCALAR_1\n\n Examples\n --------\n >>> import numpy as np\n >>> np.negative([1.,-1.])\n array([-1., 1.])\n\n The unary ``-`` operator can be used as a shorthand for ``np.negative`` on\n ndarrays.\n\n >>> x1 = np.array(([1., -1.]))\n >>> -x1\n array([-1., 1.])\n\n ') add_newdoc('numpy._core.umath', 'positive', '\n Numerical positive, element-wise.\n\n .. versionadded:: 1.13.0\n\n Parameters\n ----------\n x : array_like or scalar\n Input array.\n\n Returns\n -------\n y : ndarray or scalar\n Returned array or scalar: `y = +x`.\n $OUT_SCALAR_1\n\n Notes\n -----\n Equivalent to `x.copy()`, but only defined for types that support\n arithmetic.\n\n Examples\n --------\n >>> import numpy as np\n\n >>> x1 = np.array(([1., -1.]))\n >>> np.positive(x1)\n array([ 1., -1.])\n\n The unary ``+`` operator can be used as a shorthand for ``np.positive`` on\n ndarrays.\n\n >>> x1 = np.array(([1., -1.]))\n >>> +x1\n array([ 1., -1.])\n\n ') add_newdoc('numpy._core.umath', 'not_equal', '\n Return (x1 != x2) element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n Input arrays.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Output array, element-wise comparison of `x1` and `x2`.\n Typically of type bool, unless ``dtype=object`` is passed.\n $OUT_SCALAR_2\n\n See Also\n --------\n equal, greater, greater_equal, less, less_equal\n\n Examples\n --------\n >>> import numpy as np\n >>> np.not_equal([1.,2.], [1., 3.])\n array([False, True])\n >>> np.not_equal([1, 2], [[1, 3],[1, 4]])\n array([[False, True],\n [False, True]])\n\n The ``!=`` operator can be used as a shorthand for ``np.not_equal`` on\n ndarrays.\n\n >>> a = np.array([1., 2.])\n >>> b = np.array([1., 3.])\n >>> a != b\n array([False, True])\n\n\n ') add_newdoc('numpy._core.umath', '_ones_like', '\n This function used to be the numpy.ones_like, but now a specific\n function for that has been written for consistency with the other\n *_like functions. It is only used internally in a limited fashion now.\n\n See Also\n --------\n ones_like\n\n ') add_newdoc('numpy._core.umath', 'power', "\n First array elements raised to powers from second array, element-wise.\n\n Raise each base in `x1` to the positionally-corresponding power in\n `x2`. `x1` and `x2` must be broadcastable to the same shape.\n\n An integer type raised to a negative integer power will raise a\n ``ValueError``.\n\n Negative values raised to a non-integral value will return ``nan``.\n To get complex results, cast the input to complex, or specify the\n ``dtype`` to be ``complex`` (see the example below).\n\n Parameters\n ----------\n x1 : array_like\n The bases.\n x2 : array_like\n The exponents.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The bases in `x1` raised to the exponents in `x2`.\n $OUT_SCALAR_2\n\n See Also\n --------\n float_power : power function that promotes integers to float\n\n Examples\n --------\n >>> import numpy as np\n\n Cube each element in an array.\n\n >>> x1 = np.arange(6)\n >>> x1\n [0, 1, 2, 3, 4, 5]\n >>> np.power(x1, 3)\n array([ 0, 1, 8, 27, 64, 125])\n\n Raise the bases to different exponents.\n\n >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]\n >>> np.power(x1, x2)\n array([ 0., 1., 8., 27., 16., 5.])\n\n The effect of broadcasting.\n\n >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])\n >>> x2\n array([[1, 2, 3, 3, 2, 1],\n [1, 2, 3, 3, 2, 1]])\n >>> np.power(x1, x2)\n array([[ 0, 1, 8, 27, 16, 5],\n [ 0, 1, 8, 27, 16, 5]])\n\n The ``**`` operator can be used as a shorthand for ``np.power`` on\n ndarrays.\n\n >>> x2 = np.array([1, 2, 3, 3, 2, 1])\n >>> x1 = np.arange(6)\n >>> x1 ** x2\n array([ 0, 1, 8, 27, 16, 5])\n\n Negative values raised to a non-integral value will result in ``nan``\n (and a warning will be generated).\n\n >>> x3 = np.array([-1.0, -4.0])\n >>> with np.errstate(invalid='ignore'):\n ... p = np.power(x3, 1.5)\n ...\n >>> p\n array([nan, nan])\n\n To get complex results, give the argument ``dtype=complex``.\n\n >>> np.power(x3, 1.5, dtype=complex)\n array([-1.83697020e-16-1.j, -1.46957616e-15-8.j])\n\n ") add_newdoc('numpy._core.umath', 'float_power', "\n First array elements raised to powers from second array, element-wise.\n\n Raise each base in `x1` to the positionally-corresponding power in `x2`.\n `x1` and `x2` must be broadcastable to the same shape. This differs from\n the power function in that integers, float16, and float32 are promoted to\n floats with a minimum precision of float64 so that the result is always\n inexact. The intent is that the function will return a usable result for\n negative powers and seldom overflow for positive powers.\n\n Negative values raised to a non-integral value will return ``nan``.\n To get complex results, cast the input to complex, or specify the\n ``dtype`` to be ``complex`` (see the example below).\n\n .. versionadded:: 1.12.0\n\n Parameters\n ----------\n x1 : array_like\n The bases.\n x2 : array_like\n The exponents.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The bases in `x1` raised to the exponents in `x2`.\n $OUT_SCALAR_2\n\n See Also\n --------\n power : power function that preserves type\n\n Examples\n --------\n >>> import numpy as np\n\n Cube each element in a list.\n\n >>> x1 = range(6)\n >>> x1\n [0, 1, 2, 3, 4, 5]\n >>> np.float_power(x1, 3)\n array([ 0., 1., 8., 27., 64., 125.])\n\n Raise the bases to different exponents.\n\n >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]\n >>> np.float_power(x1, x2)\n array([ 0., 1., 8., 27., 16., 5.])\n\n The effect of broadcasting.\n\n >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])\n >>> x2\n array([[1, 2, 3, 3, 2, 1],\n [1, 2, 3, 3, 2, 1]])\n >>> np.float_power(x1, x2)\n array([[ 0., 1., 8., 27., 16., 5.],\n [ 0., 1., 8., 27., 16., 5.]])\n\n Negative values raised to a non-integral value will result in ``nan``\n (and a warning will be generated).\n\n >>> x3 = np.array([-1, -4])\n >>> with np.errstate(invalid='ignore'):\n ... p = np.float_power(x3, 1.5)\n ...\n >>> p\n array([nan, nan])\n\n To get complex results, give the argument ``dtype=complex``.\n\n >>> np.float_power(x3, 1.5, dtype=complex)\n array([-1.83697020e-16-1.j, -1.46957616e-15-8.j])\n\n ") add_newdoc('numpy._core.umath', 'radians', '\n Convert angles from degrees to radians.\n\n Parameters\n ----------\n x : array_like\n Input array in degrees.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The corresponding radian values.\n $OUT_SCALAR_1\n\n See Also\n --------\n deg2rad : equivalent function\n\n Examples\n --------\n >>> import numpy as np\n\n Convert a degree array to radians\n\n >>> deg = np.arange(12.) * 30.\n >>> np.radians(deg)\n array([ 0. , 0.52359878, 1.04719755, 1.57079633, 2.0943951 ,\n 2.61799388, 3.14159265, 3.66519143, 4.1887902 , 4.71238898,\n 5.23598776, 5.75958653])\n\n >>> out = np.zeros((deg.shape))\n >>> ret = np.radians(deg, out)\n >>> ret is out\n True\n\n ') add_newdoc('numpy._core.umath', 'deg2rad', '\n Convert angles from degrees to radians.\n\n Parameters\n ----------\n x : array_like\n Angles in degrees.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The corresponding angle in radians.\n $OUT_SCALAR_1\n\n See Also\n --------\n rad2deg : Convert angles from radians to degrees.\n unwrap : Remove large jumps in angle by wrapping.\n\n Notes\n -----\n .. versionadded:: 1.3.0\n\n ``deg2rad(x)`` is ``x * pi / 180``.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.deg2rad(180)\n 3.1415926535897931\n\n ') add_newdoc('numpy._core.umath', 'reciprocal', '\n Return the reciprocal of the argument, element-wise.\n\n Calculates ``1/x``.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n Return array.\n $OUT_SCALAR_1\n\n Notes\n -----\n .. note::\n This function is not designed to work with integers.\n\n For integer arguments with absolute value larger than 1 the result is\n always zero because of the way Python handles integer division. For\n integer zero the result is an overflow.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.reciprocal(2.)\n 0.5\n >>> np.reciprocal([1, 2., 3.33])\n array([ 1. , 0.5 , 0.3003003])\n\n ') add_newdoc('numpy._core.umath', 'remainder', "\n Returns the element-wise remainder of division.\n\n Computes the remainder complementary to the `floor_divide` function. It is\n equivalent to the Python modulus operator ``x1 % x2`` and has the same sign\n as the divisor `x2`. The MATLAB function equivalent to ``np.remainder``\n is ``mod``.\n\n .. warning::\n\n This should not be confused with:\n\n * Python 3.7's `math.remainder` and C's ``remainder``, which\n computes the IEEE remainder, which are the complement to\n ``round(x1 / x2)``.\n * The MATLAB ``rem`` function and or the C ``%`` operator which is the\n complement to ``int(x1 / x2)``.\n\n Parameters\n ----------\n x1 : array_like\n Dividend array.\n x2 : array_like\n Divisor array.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The element-wise remainder of the quotient ``floor_divide(x1, x2)``.\n $OUT_SCALAR_2\n\n See Also\n --------\n floor_divide : Equivalent of Python ``//`` operator.\n divmod : Simultaneous floor division and remainder.\n fmod : Equivalent of the MATLAB ``rem`` function.\n divide, floor\n\n Notes\n -----\n Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of)\n integers.\n ``mod`` is an alias of ``remainder``.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.remainder([4, 7], [2, 3])\n array([0, 1])\n >>> np.remainder(np.arange(7), 5)\n array([0, 1, 2, 3, 4, 0, 1])\n\n The ``%`` operator can be used as a shorthand for ``np.remainder`` on\n ndarrays.\n\n >>> x1 = np.arange(7)\n >>> x1 % 5\n array([0, 1, 2, 3, 4, 0, 1])\n\n ") add_newdoc('numpy._core.umath', 'divmod', "\n Return element-wise quotient and remainder simultaneously.\n\n .. versionadded:: 1.13.0\n\n ``np.divmod(x, y)`` is equivalent to ``(x // y, x % y)``, but faster\n because it avoids redundant work. It is used to implement the Python\n built-in function ``divmod`` on NumPy arrays.\n\n Parameters\n ----------\n x1 : array_like\n Dividend array.\n x2 : array_like\n Divisor array.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out1 : ndarray\n Element-wise quotient resulting from floor division.\n $OUT_SCALAR_2\n out2 : ndarray\n Element-wise remainder from floor division.\n $OUT_SCALAR_2\n\n See Also\n --------\n floor_divide : Equivalent to Python's ``//`` operator.\n remainder : Equivalent to Python's ``%`` operator.\n modf : Equivalent to ``divmod(x, 1)`` for positive ``x`` with the return\n values switched.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.divmod(np.arange(5), 3)\n (array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))\n\n The `divmod` function can be used as a shorthand for ``np.divmod`` on\n ndarrays.\n\n >>> x = np.arange(5)\n >>> divmod(x, 3)\n (array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))\n\n ") add_newdoc('numpy._core.umath', 'right_shift', "\n Shift the bits of an integer to the right.\n\n Bits are shifted to the right `x2`. Because the internal\n representation of numbers is in binary format, this operation is\n equivalent to dividing `x1` by ``2**x2``.\n\n Parameters\n ----------\n x1 : array_like, int\n Input values.\n x2 : array_like, int\n Number of bits to remove at the right of `x1`.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray, int\n Return `x1` with bits shifted `x2` times to the right.\n $OUT_SCALAR_2\n\n See Also\n --------\n left_shift : Shift the bits of an integer to the left.\n binary_repr : Return the binary representation of the input number\n as a string.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.binary_repr(10)\n '1010'\n >>> np.right_shift(10, 1)\n 5\n >>> np.binary_repr(5)\n '101'\n\n >>> np.right_shift(10, [1,2,3])\n array([5, 2, 1])\n\n The ``>>`` operator can be used as a shorthand for ``np.right_shift`` on\n ndarrays.\n\n >>> x1 = 10\n >>> x2 = np.array([1,2,3])\n >>> x1 >> x2\n array([5, 2, 1])\n\n ") add_newdoc('numpy._core.umath', 'rint', '\n Round elements of the array to the nearest integer.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Output array is same shape and type as `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n fix, ceil, floor, trunc\n\n Notes\n -----\n For values exactly halfway between rounded decimal values, NumPy\n rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,\n -0.5 and 0.5 round to 0.0, etc.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])\n >>> np.rint(a)\n array([-2., -2., -0., 0., 2., 2., 2.])\n\n ') add_newdoc('numpy._core.umath', 'sign', '\n Returns an element-wise indication of the sign of a number.\n\n The `sign` function returns ``-1 if x < 0, 0 if x==0, 1 if x > 0``. nan\n is returned for nan inputs.\n\n For complex inputs, the `sign` function returns ``x / abs(x)``, the\n generalization of the above (and ``0 if x==0``).\n\n .. versionchanged:: 2.0.0\n Definition of complex sign changed to follow the Array API standard.\n\n Parameters\n ----------\n x : array_like\n Input values.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The sign of `x`.\n $OUT_SCALAR_1\n\n Notes\n -----\n There is more than one definition of sign in common use for complex\n numbers. The definition used here, :math:`x/|x|`, is the more common\n and useful one, but is different from the one used in numpy prior to\n version 2.0, :math:`x/\\sqrt{x*x}`, which is equivalent to\n ``sign(x.real) + 0j if x.real != 0 else sign(x.imag) + 0j``.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.sign([-5., 4.5])\n array([-1., 1.])\n >>> np.sign(0)\n 0\n >>> np.sign([3-4j, 8j])\n array([0.6-0.8j, 0. +1.j ])\n\n ') add_newdoc('numpy._core.umath', 'signbit', '\n Returns element-wise True where signbit is set (less than zero).\n\n Parameters\n ----------\n x : array_like\n The input value(s).\n $PARAMS\n\n Returns\n -------\n result : ndarray of bool\n Output array, or reference to `out` if that was supplied.\n $OUT_SCALAR_1\n\n Examples\n --------\n >>> import numpy as np\n >>> np.signbit(-1.2)\n True\n >>> np.signbit(np.array([1, -2.3, 2.1]))\n array([False, True, False])\n\n ') add_newdoc('numpy._core.umath', 'copysign', '\n Change the sign of x1 to that of x2, element-wise.\n\n If `x2` is a scalar, its sign will be copied to all elements of `x1`.\n\n Parameters\n ----------\n x1 : array_like\n Values to change the sign of.\n x2 : array_like\n The sign of `x2` is copied to `x1`.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n The values of `x1` with the sign of `x2`.\n $OUT_SCALAR_2\n\n Examples\n --------\n >>> import numpy as np\n >>> np.copysign(1.3, -1)\n -1.3\n >>> 1/np.copysign(0, 1)\n inf\n >>> 1/np.copysign(0, -1)\n -inf\n\n >>> np.copysign([-1, 0, 1], -1.1)\n array([-1., -0., -1.])\n >>> np.copysign([-1, 0, 1], np.arange(3)-1)\n array([-1., 0., 1.])\n\n ') add_newdoc('numpy._core.umath', 'nextafter', '\n Return the next floating-point value after x1 towards x2, element-wise.\n\n Parameters\n ----------\n x1 : array_like\n Values to find the next representable value of.\n x2 : array_like\n The direction where to look for the next representable value of `x1`.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n The next representable values of `x1` in the direction of `x2`.\n $OUT_SCALAR_2\n\n Examples\n --------\n >>> import numpy as np\n >>> eps = np.finfo(np.float64).eps\n >>> np.nextafter(1, 2) == eps + 1\n True\n >>> np.nextafter([1, 2], [2, 1]) == [eps + 1, 2 - eps]\n array([ True, True])\n\n ') add_newdoc('numpy._core.umath', 'spacing', '\n Return the distance between x and the nearest adjacent number.\n\n Parameters\n ----------\n x : array_like\n Values to find the spacing of.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n The spacing of values of `x`.\n $OUT_SCALAR_1\n\n Notes\n -----\n It can be considered as a generalization of EPS:\n ``spacing(np.float64(1)) == np.finfo(np.float64).eps``, and there\n should not be any representable number between ``x + spacing(x)`` and\n x for any finite x.\n\n Spacing of +- inf and NaN is NaN.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.spacing(1) == np.finfo(np.float64).eps\n True\n\n ') add_newdoc('numpy._core.umath', 'sin', "\n Trigonometric sine, element-wise.\n\n Parameters\n ----------\n x : array_like\n Angle, in radians (:math:`2 \\pi` rad equals 360 degrees).\n $PARAMS\n\n Returns\n -------\n y : array_like\n The sine of each element of x.\n $OUT_SCALAR_1\n\n See Also\n --------\n arcsin, sinh, cos\n\n Notes\n -----\n The sine is one of the fundamental functions of trigonometry (the\n mathematical study of triangles). Consider a circle of radius 1\n centered on the origin. A ray comes in from the :math:`+x` axis, makes\n an angle at the origin (measured counter-clockwise from that axis), and\n departs from the origin. The :math:`y` coordinate of the outgoing\n ray's intersection with the unit circle is the sine of that angle. It\n ranges from -1 for :math:`x=3\\pi / 2` to +1 for :math:`\\pi / 2.` The\n function has zeroes where the angle is a multiple of :math:`\\pi`.\n Sines of angles between :math:`\\pi` and :math:`2\\pi` are negative.\n The numerous properties of the sine and related functions are included\n in any standard trigonometry text.\n\n Examples\n --------\n >>> import numpy as np\n\n Print sine of one angle:\n\n >>> np.sin(np.pi/2.)\n 1.0\n\n Print sines of an array of angles given in degrees:\n\n >>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )\n array([ 0. , 0.5 , 0.70710678, 0.8660254 , 1. ])\n\n Plot the sine function:\n\n >>> import matplotlib.pylab as plt\n >>> x = np.linspace(-np.pi, np.pi, 201)\n >>> plt.plot(x, np.sin(x))\n >>> plt.xlabel('Angle [rad]')\n >>> plt.ylabel('sin(x)')\n >>> plt.axis('tight')\n >>> plt.show()\n\n ") add_newdoc('numpy._core.umath', 'sinh', '\n Hyperbolic sine, element-wise.\n\n Equivalent to ``1/2 * (np.exp(x) - np.exp(-x))`` or\n ``-1j * np.sin(1j*x)``.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The corresponding hyperbolic sine values.\n $OUT_SCALAR_1\n\n Notes\n -----\n If `out` is provided, the function writes the result into it,\n and returns a reference to `out`. (See Examples)\n\n References\n ----------\n M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.\n New York, NY: Dover, 1972, pg. 83.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.sinh(0)\n 0.0\n >>> np.sinh(np.pi*1j/2)\n 1j\n >>> np.sinh(np.pi*1j) # (exact value is 0)\n 1.2246063538223773e-016j\n >>> # Discrepancy due to vagaries of floating point arithmetic.\n\n >>> # Example of providing the optional output parameter\n >>> out1 = np.array([0], dtype=\'d\')\n >>> out2 = np.sinh([0.1], out1)\n >>> out2 is out1\n True\n\n >>> # Example of ValueError due to provision of shape mis-matched `out`\n >>> np.sinh(np.zeros((3,3)),np.zeros((2,2)))\n Traceback (most recent call last):\n File "", line 1, in \n ValueError: operands could not be broadcast together with shapes (3,3) (2,2)\n\n ') add_newdoc('numpy._core.umath', 'sqrt', '\n Return the non-negative square-root of an array, element-wise.\n\n Parameters\n ----------\n x : array_like\n The values whose square-roots are required.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n An array of the same shape as `x`, containing the positive\n square-root of each element in `x`. If any element in `x` is\n complex, a complex array is returned (and the square-roots of\n negative reals are calculated). If all of the elements in `x`\n are real, so is `y`, with negative elements returning ``nan``.\n If `out` was provided, `y` is a reference to it.\n $OUT_SCALAR_1\n\n See Also\n --------\n emath.sqrt\n A version which returns complex numbers when given negative reals.\n Note that 0.0 and -0.0 are handled differently for complex inputs.\n\n Notes\n -----\n *sqrt* has--consistent with common convention--as its branch cut the\n real "interval" [`-inf`, 0), and is continuous from above on it.\n A branch cut is a curve in the complex plane across which a given\n complex function fails to be continuous.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.sqrt([1,4,9])\n array([ 1., 2., 3.])\n\n >>> np.sqrt([4, -1, -3+4J])\n array([ 2.+0.j, 0.+1.j, 1.+2.j])\n\n >>> np.sqrt([4, -1, np.inf])\n array([ 2., nan, inf])\n\n ') add_newdoc('numpy._core.umath', 'cbrt', '\n Return the cube-root of an array, element-wise.\n\n .. versionadded:: 1.10.0\n\n Parameters\n ----------\n x : array_like\n The values whose cube-roots are required.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n An array of the same shape as `x`, containing the\n cube root of each element in `x`.\n If `out` was provided, `y` is a reference to it.\n $OUT_SCALAR_1\n\n\n Examples\n --------\n >>> import numpy as np\n >>> np.cbrt([1,8,27])\n array([ 1., 2., 3.])\n\n ') add_newdoc('numpy._core.umath', 'square', '\n Return the element-wise square of the input.\n\n Parameters\n ----------\n x : array_like\n Input data.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Element-wise `x*x`, of the same shape and dtype as `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n numpy.linalg.matrix_power\n sqrt\n power\n\n Examples\n --------\n >>> import numpy as np\n >>> np.square([-1j, 1])\n array([-1.-0.j, 1.+0.j])\n\n ') add_newdoc('numpy._core.umath', 'subtract', '\n Subtract arguments, element-wise.\n\n Parameters\n ----------\n x1, x2 : array_like\n The arrays to be subtracted from each other.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The difference of `x1` and `x2`, element-wise.\n $OUT_SCALAR_2\n\n Notes\n -----\n Equivalent to ``x1 - x2`` in terms of array broadcasting.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.subtract(1.0, 4.0)\n -3.0\n\n >>> x1 = np.arange(9.0).reshape((3, 3))\n >>> x2 = np.arange(3.0)\n >>> np.subtract(x1, x2)\n array([[ 0., 0., 0.],\n [ 3., 3., 3.],\n [ 6., 6., 6.]])\n\n The ``-`` operator can be used as a shorthand for ``np.subtract`` on\n ndarrays.\n\n >>> x1 = np.arange(9.0).reshape((3, 3))\n >>> x2 = np.arange(3.0)\n >>> x1 - x2\n array([[0., 0., 0.],\n [3., 3., 3.],\n [6., 6., 6.]])\n\n ') add_newdoc('numpy._core.umath', 'tan', '\n Compute tangent element-wise.\n\n Equivalent to ``np.sin(x)/np.cos(x)`` element-wise.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The corresponding tangent values.\n $OUT_SCALAR_1\n\n Notes\n -----\n If `out` is provided, the function writes the result into it,\n and returns a reference to `out`. (See Examples)\n\n References\n ----------\n M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.\n New York, NY: Dover, 1972.\n\n Examples\n --------\n >>> import numpy as np\n >>> from math import pi\n >>> np.tan(np.array([-pi,pi/2,pi]))\n array([ 1.22460635e-16, 1.63317787e+16, -1.22460635e-16])\n >>>\n >>> # Example of providing the optional output parameter illustrating\n >>> # that what is returned is a reference to said parameter\n >>> out1 = np.array([0], dtype=\'d\')\n >>> out2 = np.cos([0.1], out1)\n >>> out2 is out1\n True\n >>>\n >>> # Example of ValueError due to provision of shape mis-matched `out`\n >>> np.cos(np.zeros((3,3)),np.zeros((2,2)))\n Traceback (most recent call last):\n File "", line 1, in \n ValueError: operands could not be broadcast together with shapes (3,3) (2,2)\n\n ') add_newdoc('numpy._core.umath', 'tanh', '\n Compute hyperbolic tangent element-wise.\n\n Equivalent to ``np.sinh(x)/np.cosh(x)`` or ``-1j * np.tan(1j*x)``.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The corresponding hyperbolic tangent values.\n $OUT_SCALAR_1\n\n Notes\n -----\n If `out` is provided, the function writes the result into it,\n and returns a reference to `out`. (See Examples)\n\n References\n ----------\n .. [1] M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.\n New York, NY: Dover, 1972, pg. 83.\n https://personal.math.ubc.ca/~cbm/aands/page_83.htm\n\n .. [2] Wikipedia, "Hyperbolic function",\n https://en.wikipedia.org/wiki/Hyperbolic_function\n\n Examples\n --------\n >>> import numpy as np\n >>> np.tanh((0, np.pi*1j, np.pi*1j/2))\n array([ 0. +0.00000000e+00j, 0. -1.22460635e-16j, 0. +1.63317787e+16j])\n\n >>> # Example of providing the optional output parameter illustrating\n >>> # that what is returned is a reference to said parameter\n >>> out1 = np.array([0], dtype=\'d\')\n >>> out2 = np.tanh([0.1], out1)\n >>> out2 is out1\n True\n\n >>> # Example of ValueError due to provision of shape mis-matched `out`\n >>> np.tanh(np.zeros((3,3)),np.zeros((2,2)))\n Traceback (most recent call last):\n File "", line 1, in \n ValueError: operands could not be broadcast together with shapes (3,3) (2,2)\n\n ') add_newdoc('numpy._core.umath', 'frexp', '\n Decompose the elements of x into mantissa and twos exponent.\n\n Returns (`mantissa`, `exponent`), where ``x = mantissa * 2**exponent``.\n The mantissa lies in the open interval(-1, 1), while the twos\n exponent is a signed integer.\n\n Parameters\n ----------\n x : array_like\n Array of numbers to be decomposed.\n out1 : ndarray, optional\n Output array for the mantissa. Must have the same shape as `x`.\n out2 : ndarray, optional\n Output array for the exponent. Must have the same shape as `x`.\n $PARAMS\n\n Returns\n -------\n mantissa : ndarray\n Floating values between -1 and 1.\n $OUT_SCALAR_1\n exponent : ndarray\n Integer exponents of 2.\n $OUT_SCALAR_1\n\n See Also\n --------\n ldexp : Compute ``y = x1 * 2**x2``, the inverse of `frexp`.\n\n Notes\n -----\n Complex dtypes are not supported, they will raise a TypeError.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = np.arange(9)\n >>> y1, y2 = np.frexp(x)\n >>> y1\n array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875,\n 0.5 ])\n >>> y2\n array([0, 1, 2, 2, 3, 3, 3, 3, 4], dtype=int32)\n >>> y1 * 2**y2\n array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.])\n\n ') add_newdoc('numpy._core.umath', 'ldexp', '\n Returns x1 * 2**x2, element-wise.\n\n The mantissas `x1` and twos exponents `x2` are used to construct\n floating point numbers ``x1 * 2**x2``.\n\n Parameters\n ----------\n x1 : array_like\n Array of multipliers.\n x2 : array_like, int\n Array of twos exponents.\n $BROADCASTABLE_2\n $PARAMS\n\n Returns\n -------\n y : ndarray or scalar\n The result of ``x1 * 2**x2``.\n $OUT_SCALAR_2\n\n See Also\n --------\n frexp : Return (y1, y2) from ``x = y1 * 2**y2``, inverse to `ldexp`.\n\n Notes\n -----\n Complex dtypes are not supported, they will raise a TypeError.\n\n `ldexp` is useful as the inverse of `frexp`, if used by itself it is\n more clear to simply use the expression ``x1 * 2**x2``.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.ldexp(5, np.arange(4))\n array([ 5., 10., 20., 40.], dtype=float16)\n\n >>> x = np.arange(6)\n >>> np.ldexp(*np.frexp(x))\n array([ 0., 1., 2., 3., 4., 5.])\n\n ') add_newdoc('numpy._core.umath', 'gcd', '\n Returns the greatest common divisor of ``|x1|`` and ``|x2|``\n\n Parameters\n ----------\n x1, x2 : array_like, int\n Arrays of values.\n $BROADCASTABLE_2\n\n Returns\n -------\n y : ndarray or scalar\n The greatest common divisor of the absolute value of the inputs\n $OUT_SCALAR_2\n\n See Also\n --------\n lcm : The lowest common multiple\n\n Examples\n --------\n >>> import numpy as np\n >>> np.gcd(12, 20)\n 4\n >>> np.gcd.reduce([15, 25, 35])\n 5\n >>> np.gcd(np.arange(6), 20)\n array([20, 1, 2, 1, 4, 5])\n\n ') add_newdoc('numpy._core.umath', 'lcm', '\n Returns the lowest common multiple of ``|x1|`` and ``|x2|``\n\n Parameters\n ----------\n x1, x2 : array_like, int\n Arrays of values.\n $BROADCASTABLE_2\n\n Returns\n -------\n y : ndarray or scalar\n The lowest common multiple of the absolute value of the inputs\n $OUT_SCALAR_2\n\n See Also\n --------\n gcd : The greatest common divisor\n\n Examples\n --------\n >>> import numpy as np\n >>> np.lcm(12, 20)\n 60\n >>> np.lcm.reduce([3, 12, 20])\n 60\n >>> np.lcm.reduce([40, 12, 20])\n 120\n >>> np.lcm(np.arange(6), 20)\n array([ 0, 20, 20, 60, 20, 20])\n\n ') add_newdoc('numpy._core.umath', 'bitwise_count', '\n Computes the number of 1-bits in the absolute value of ``x``.\n Analogous to the builtin `int.bit_count` or ``popcount`` in C++.\n\n Parameters\n ----------\n x : array_like, unsigned int\n Input array.\n $PARAMS\n\n Returns\n -------\n y : ndarray\n The corresponding number of 1-bits in the input.\n Returns uint8 for all integer types\n $OUT_SCALAR_1\n\n References\n ----------\n .. [1] https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel\n\n .. [2] Wikipedia, "Hamming weight",\n https://en.wikipedia.org/wiki/Hamming_weight\n\n .. [3] http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20(Ones%20Count)\n\n Examples\n --------\n >>> import numpy as np\n >>> np.bitwise_count(1023)\n np.uint8(10)\n >>> a = np.array([2**i - 1 for i in range(16)])\n >>> np.bitwise_count(a)\n array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],\n dtype=uint8)\n\n ') add_newdoc('numpy._core.umath', 'str_len', "\n Returns the length of each element. For byte strings,\n this is the number of bytes, while, for Unicode strings,\n it is the number of Unicode code points.\n\n Parameters\n ----------\n x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n $PARAMS\n\n Returns\n -------\n y : ndarray\n Output array of ints\n $OUT_SCALAR_1\n\n See Also\n --------\n len\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array(['Grace Hopper Conference', 'Open Source Day'])\n >>> np.strings.str_len(a)\n array([23, 15])\n >>> a = np.array(['Р', 'о'])\n >>> np.strings.str_len(a)\n array([1, 1])\n >>> a = np.array([['hello', 'world'], ['Р', 'о']])\n >>> np.strings.str_len(a)\n array([[5, 5], [1, 1]])\n\n ") add_newdoc('numpy._core.umath', 'isalpha', "\n Returns true for each element if all characters in the data\n interpreted as a string are alphabetic and there is at least\n one character, false otherwise.\n\n For byte strings (i.e. ``bytes``), alphabetic characters are\n those byte values in the sequence\n b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. For\n Unicode strings, alphabetic characters are those characters\n defined in the Unicode character database as “Letter”.\n\n Parameters\n ----------\n x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n $PARAMS\n\n Returns\n -------\n y : ndarray\n Output array of bools\n $OUT_SCALAR_1\n\n See Also\n --------\n str.isalpha\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array(['a', 'b', '0'])\n >>> np.strings.isalpha(a)\n array([ True, True, False])\n\n >>> a = np.array([['a', 'b', '0'], ['c', '1', '2']])\n >>> np.strings.isalpha(a)\n array([[ True, True, False], [ True, False, False]])\n\n ") add_newdoc('numpy._core.umath', 'isdigit', "\n Returns true for each element if all characters in the string are\n digits and there is at least one character, false otherwise.\n\n For byte strings, digits are the byte values in the sequence\n b'0123456789'. For Unicode strings, digits include decimal\n characters and digits that need special handling, such as the\n compatibility superscript digits. This also covers digits which\n cannot be used to form numbers in base 10, like the Kharosthi numbers.\n\n Parameters\n ----------\n x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n $PARAMS\n\n Returns\n -------\n y : ndarray\n Output array of bools\n $OUT_SCALAR_1\n\n See Also\n --------\n str.isdigit\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array(['a', 'b', '0'])\n >>> np.strings.isdigit(a)\n array([False, False, True])\n >>> a = np.array([['a', 'b', '0'], ['c', '1', '2']])\n >>> np.strings.isdigit(a)\n array([[False, False, True], [False, True, True]])\n\n ") add_newdoc('numpy._core.umath', 'isspace', "\n Returns true for each element if there are only whitespace\n characters in the string and there is at least one character,\n false otherwise.\n\n For byte strings, whitespace characters are the ones in the\n sequence b' \\t\\n\\r\\x0b\\f'. For Unicode strings, a character is\n whitespace, if, in the Unicode character database, its general\n category is Zs (“Separator, space”), or its bidirectional class\n is one of WS, B, or S.\n\n Parameters\n ----------\n x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n $PARAMS\n\n Returns\n -------\n y : ndarray\n Output array of bools\n $OUT_SCALAR_1\n\n See Also\n --------\n str.isspace\n\n ") add_newdoc('numpy._core.umath', 'isalnum', "\n Returns true for each element if all characters in the string are\n alphanumeric and there is at least one character, false otherwise.\n\n Parameters\n ----------\n x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype\n $PARAMS\n\n Returns\n -------\n out : ndarray\n Output array of bool\n $OUT_SCALAR_1\n\n See Also\n --------\n str.isalnum\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array(['a', '1', 'a1', '(', ''])\n >>> np.strings.isalnum(a)\n array([ True, True, True, False, False])\n\n ") add_newdoc('numpy._core.umath', 'islower', '\n Returns true for each element if all cased characters in the\n string are lowercase and there is at least one cased character,\n false otherwise.\n\n Parameters\n ----------\n x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype\n $PARAMS\n\n Returns\n -------\n out : ndarray\n Output array of bools\n $OUT_SCALAR_1\n\n See Also\n --------\n str.islower\n\n Examples\n --------\n >>> import numpy as np\n >>> np.strings.islower("GHC")\n array(False)\n >>> np.strings.islower("ghc")\n array(True)\n\n ') add_newdoc('numpy._core.umath', 'isupper', '\n Return true for each element if all cased characters in the\n string are uppercase and there is at least one character, false\n otherwise.\n\n Parameters\n ----------\n x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype\n $PARAMS\n\n Returns\n -------\n out : ndarray\n Output array of bools\n $OUT_SCALAR_1\n\n See Also\n --------\n str.isupper\n\n Examples\n --------\n >>> import numpy as np\n >>> np.strings.isupper("GHC")\n array(True)\n >>> a = np.array(["hello", "HELLO", "Hello"])\n >>> np.strings.isupper(a)\n array([False, True, False])\n\n ') add_newdoc('numpy._core.umath', 'istitle', '\n Returns true for each element if the element is a titlecased\n string and there is at least one character, false otherwise.\n\n Parameters\n ----------\n x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype\n $PARAMS\n\n Returns\n -------\n out : ndarray\n Output array of bools\n $OUT_SCALAR_1\n\n See Also\n --------\n str.istitle\n\n Examples\n --------\n >>> import numpy as np\n >>> np.strings.istitle("Numpy Is Great")\n array(True)\n\n >>> np.strings.istitle("Numpy is great")\n array(False)\n\n ') add_newdoc('numpy._core.umath', 'isdecimal', "\n For each element, return True if there are only decimal\n characters in the element.\n\n Decimal characters include digit characters, and all characters\n that can be used to form decimal-radix numbers,\n e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``.\n\n Parameters\n ----------\n x : array_like, with ``StringDType`` or ``str_`` dtype\n $PARAMS\n\n Returns\n -------\n y : ndarray\n Output array of bools\n $OUT_SCALAR_1\n\n See Also\n --------\n str.isdecimal\n\n Examples\n --------\n >>> import numpy as np\n >>> np.strings.isdecimal(['12345', '4.99', '123ABC', ''])\n array([ True, False, False, False])\n\n ") add_newdoc('numpy._core.umath', 'isnumeric', "\n For each element, return True if there are only numeric\n characters in the element.\n\n Numeric characters include digit characters, and all characters\n that have the Unicode numeric value property, e.g. ``U+2155,\n VULGAR FRACTION ONE FIFTH``.\n\n Parameters\n ----------\n x : array_like, with ``StringDType`` or ``str_`` dtype\n $PARAMS\n\n Returns\n -------\n y : ndarray\n Output array of bools\n $OUT_SCALAR_1\n\n See Also\n --------\n str.isnumeric\n\n Examples\n --------\n >>> import numpy as np\n >>> np.strings.isnumeric(['123', '123abc', '9.0', '1/4', 'VIII'])\n array([ True, False, False, False, False])\n\n ") add_newdoc('numpy._core.umath', 'find', '\n For each element, return the lowest index in the string where\n substring `x2` is found, such that `x2` is contained in the\n range [`x3`, `x4`].\n\n Parameters\n ----------\n x1 : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n\n x2 : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n\n x3 : array_like, with ``int_`` dtype\n\n x4 : array_like, with ``int_`` dtype\n $PARAMS\n\n `x3` and `x4` are interpreted as in slice notation.\n\n Returns\n -------\n y : ndarray\n Output array of ints\n $OUT_SCALAR_2\n\n See Also\n --------\n str.find\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array(["NumPy is a Python library"])\n >>> np.strings.find(a, "Python", 0, None)\n array([11])\n\n ') add_newdoc('numpy._core.umath', 'rfind', '\n For each element, return the highest index in the string where\n substring `x2` is found, such that `x2` is contained in the\n range [`x3`, `x4`].\n\n Parameters\n ----------\n x1 : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n\n x2 : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n\n x3 : array_like, with ``int_`` dtype\n\n x4 : array_like, with ``int_`` dtype\n $PARAMS\n\n `x3` and `x4` are interpreted as in slice notation.\n\n Returns\n -------\n y : ndarray\n Output array of ints\n $OUT_SCALAR_2\n\n See Also\n --------\n str.rfind\n\n ') add_newdoc('numpy._core.umath', 'count', "\n Returns an array with the number of non-overlapping occurrences of\n substring `x2` in the range [`x3`, `x4`].\n\n Parameters\n ----------\n x1 : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n\n x2 : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n The substring to search for.\n\n x3 : array_like, with ``int_`` dtype\n\n x4 : array_like, with ``int_`` dtype\n $PARAMS\n\n `x3` and `x4` are interpreted as in slice notation.\n\n Returns\n -------\n y : ndarray\n Output array of ints\n $OUT_SCALAR_2\n\n See Also\n --------\n str.count\n\n Examples\n --------\n >>> import numpy as np\n >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])\n >>> c\n array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.count(c, 'A')\n array([3, 1, 1])\n >>> np.strings.count(c, 'aA')\n array([3, 1, 0])\n >>> np.strings.count(c, 'A', start=1, end=4)\n array([2, 1, 1])\n >>> np.strings.count(c, 'A', start=1, end=3)\n array([1, 0, 0])\n\n ") add_newdoc('numpy._core.umath', 'index', '\n Like `find`, but raises :exc:`ValueError` when the substring is not found.\n\n Parameters\n ----------\n x1 : array_like, with ``StringDType``, ``bytes_`` or ``unicode_`` dtype\n\n x2 : array_like, with ``StringDType``, ``bytes_`` or ``unicode_`` dtype\n\n x3, x4 : array_like, with any integer dtype\n The range to look in, interpreted as in slice notation.\n $PARAMS\n\n Returns\n -------\n out : ndarray\n Output array of ints. Raises :exc:`ValueError` if `x2` is not found.\n $OUT_SCALAR_2\n\n See Also\n --------\n find, str.find\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array(["Computer Science"])\n >>> np.strings.index(a, "Science")\n array([9])\n\n ') add_newdoc('numpy._core.umath', 'rindex', '\n Like `rfind`, but raises :exc:`ValueError` when the substring is not found.\n\n Parameters\n ----------\n x1 : array_like, with ``StringDType``, ``bytes_`` or ``unicode_`` dtype\n\n x2 : array_like, with ``StringDType``, ``bytes_`` or ``unicode_`` dtype\n\n x3, x4 : array_like, with any integer dtype\n The range to look in, interpreted as in slice notation.\n $PARAMS\n\n Returns\n -------\n out : ndarray\n Output array of ints. Raises :exc:`ValueError` if `x2` is not found.\n $OUT_SCALAR_2\n\n See Also\n --------\n rfind, str.rfind\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array(["Computer Science"])\n >>> np.strings.rindex(a, "Science")\n array([9])\n\n ') add_newdoc('numpy._core.umath', '_replace', '\n UFunc implementation of ``replace``. This internal function\n is called by ``replace`` with ``out`` set, so that the\n size of the resulting string buffer is known.\n ') add_newdoc('numpy._core.umath', 'startswith', '\n Returns a boolean array which is `True` where the string element\n in `x1` starts with `x2`, otherwise `False`.\n\n Parameters\n ----------\n x1 : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n\n x2 : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n\n x3 : array_like, with ``int_`` dtype\n\n x4 : array_like, with ``int_`` dtype\n $PARAMS\n With `x3`, test beginning at that position. With `x4`,\n stop comparing at that position.\n\n Returns\n -------\n out : ndarray\n Output array of bools\n $OUT_SCALAR_2\n\n See Also\n --------\n str.startswith\n\n ') add_newdoc('numpy._core.umath', 'endswith', "\n Returns a boolean array which is `True` where the string element\n in `x1` ends with `x2`, otherwise `False`.\n\n Parameters\n ----------\n x1 : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n\n x2 : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype\n\n x3 : array_like, with ``int_`` dtype\n\n x4 : array_like, with ``int_`` dtype\n $PARAMS\n With `x3`, test beginning at that position. With `x4`,\n stop comparing at that position.\n\n Returns\n -------\n out : ndarray\n Output array of bools\n $OUT_SCALAR_2\n\n See Also\n --------\n str.endswith\n\n Examples\n --------\n >>> import numpy as np\n >>> s = np.array(['foo', 'bar'])\n >>> s\n array(['foo', 'bar'], dtype='>> np.strings.endswith(s, 'ar')\n array([False, True])\n >>> np.strings.endswith(s, 'a', start=1, end=2)\n array([False, True])\n\n ") add_newdoc('numpy._core.umath', '_strip_chars', '') add_newdoc('numpy._core.umath', '_lstrip_chars', '') add_newdoc('numpy._core.umath', '_rstrip_chars', '') add_newdoc('numpy._core.umath', '_strip_whitespace', '') add_newdoc('numpy._core.umath', '_lstrip_whitespace', '') add_newdoc('numpy._core.umath', '_rstrip_whitespace', '') add_newdoc('numpy._core.umath', '_expandtabs_length', '') add_newdoc('numpy._core.umath', '_expandtabs', '') add_newdoc('numpy._core.umath', '_center', "\n Return a copy of `x1` with its elements centered in a string of\n length `x2`.\n\n Parameters\n ----------\n x1 : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype\n\n x2 : array_like, with any integer dtype\n The length of the resulting strings, unless ``width < str_len(a)``.\n x3 : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype\n The padding character to use.\n $PARAMS\n\n Returns\n -------\n out : ndarray\n Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,\n depending on input types\n $OUT_SCALAR_2\n\n See Also\n --------\n str.center\n\n Examples\n --------\n >>> import numpy as np\n >>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c\n array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='>> np.strings.center(c, width=9)\n array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='>> np.strings.center(c, width=9, fillchar='*')\n array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='>> np.strings.center(c, width=1)\n array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='>> import numpy as np\n >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])\n >>> np.strings.ljust(c, width=3)\n array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.ljust(c, width=9)\n array(['aAaAaA ', ' aA ', 'abBABba '], dtype='>> import numpy as np\n >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])\n >>> np.strings.rjust(a, width=3)\n array(['aAaAaA', ' aA ', 'abBABba'], dtype='>> np.strings.rjust(a, width=9)\n array([' aAaAaA', ' aA ', ' abBABba'], dtype='>> import numpy as np\n >>> np.strings.zfill(['1', '-1', '+1'], 3)\n array(['001', '-01', '+01'], dtype='>> import numpy as np\n\n The ufunc is used most easily via ``np.strings.partition``,\n which calls it after calculating the indices::\n\n >>> x = np.array(["Numpy is nice!"])\n >>> np.strings.partition(x, " ")\n (array([\'Numpy\'], dtype=\'>> import numpy as np\n\n The ufunc is used most easily via ``np.strings.rpartition``,\n which calls it after calculating the indices::\n\n >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])\n >>> np.strings.rpartition(a, 'A')\n (array(['aAaAa', ' a', 'abB'], dtype='>> import numpy as np\n\n The ufunc is used most easily via ``np.strings.partition``,\n which calls it under the hood::\n\n >>> x = np.array(["Numpy is nice!"], dtype="T")\n >>> np.strings.partition(x, " ")\n (array([\'Numpy\'], dtype=StringDType()),\n array([\' \'], dtype=StringDType()),\n array([\'is nice!\'], dtype=StringDType()))\n\n ') add_newdoc('numpy._core.umath', '_rpartition', '\n Partition each element in ``x1`` around the right-most separator,\n ``x2``.\n\n For each element in ``x1``, split the element at the last\n occurrence of ``x2`` at location ``x3``, and return a 3-tuple\n containing the part before the separator, the separator itself,\n and the part after the separator. If the separator is not found,\n the third item of the tuple will contain the whole string, and\n the first and second ones will be the empty string.\n\n Parameters\n ----------\n x1 : array-like, with ``StringDType`` dtype\n Input array\n x2 : array-like, with ``StringDType`` dtype\n Separator to split each string element in ``x1``.\n\n Returns\n -------\n out : 3-tuple:\n - ``StringDType`` array with the part before the separator\n - ``StringDType`` array with the separator\n - ``StringDType`` array with the part after the separator\n\n See Also\n --------\n str.rpartition\n\n Examples\n --------\n >>> import numpy as np\n\n The ufunc is used most easily via ``np.strings.rpartition``,\n which calls it after calculating the indices::\n\n >>> a = np.array([\'aAaAaA\', \' aA \', \'abBABba\'], dtype="T")\n >>> np.strings.rpartition(a, \'A\')\n (array([\'aAaAa\', \' a\', \'abB\'], dtype=StringDType()),\n array([\'A\', \'A\', \'A\'], dtype=StringDType()),\n array([\'\', \' \', \'Bba\'], dtype=StringDType()))\n\n ') # File: numpy-main/numpy/_core/code_generators/verify_c_api_version.py import os import sys import argparse class MismatchCAPIError(ValueError): pass def get_api_versions(apiversion): sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) try: m = __import__('genapi') numpy_api = __import__('numpy_api') curapi_hash = m.fullapi_hash(numpy_api.full_api) apis_hash = m.get_versions_hash() finally: del sys.path[0] return (curapi_hash, apis_hash[apiversion]) def check_api_version(apiversion): (curapi_hash, api_hash) = get_api_versions(apiversion) if not curapi_hash == api_hash: msg = f'API mismatch detected, the C API version numbers have to be updated. Current C api version is {apiversion}, with checksum {curapi_hash}, but recorded checksum in _core/codegen_dir/cversions.txt is {api_hash}. If functions were added in the C API, you have to update C_API_VERSION in {__file__}.' raise MismatchCAPIError(msg) def main(): parser = argparse.ArgumentParser() parser.add_argument('--api-version', type=str, help='C API version to verify (as a hex string)') args = parser.parse_args() check_api_version(int(args.api_version, base=16)) if __name__ == '__main__': main() # File: numpy-main/numpy/_core/defchararray.py """""" import functools import numpy as np from .._utils import set_module from .numerictypes import bytes_, str_, character from .numeric import ndarray, array as narray, asarray as asnarray from numpy._core.multiarray import compare_chararrays from numpy._core import overrides from numpy.strings import * from numpy.strings import multiply as strings_multiply, partition as strings_partition, rpartition as strings_rpartition from numpy._core.strings import _split as split, _rsplit as rsplit, _splitlines as splitlines, _join as join __all__ = ['equal', 'not_equal', 'greater_equal', 'less_equal', 'greater', 'less', 'str_len', 'add', 'multiply', 'mod', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill', 'isnumeric', 'isdecimal', 'array', 'asarray', 'compare_chararrays', 'chararray'] array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy.char') def _binary_op_dispatcher(x1, x2): return (x1, x2) @array_function_dispatch(_binary_op_dispatcher) def equal(x1, x2): return compare_chararrays(x1, x2, '==', True) @array_function_dispatch(_binary_op_dispatcher) def not_equal(x1, x2): return compare_chararrays(x1, x2, '!=', True) @array_function_dispatch(_binary_op_dispatcher) def greater_equal(x1, x2): return compare_chararrays(x1, x2, '>=', True) @array_function_dispatch(_binary_op_dispatcher) def less_equal(x1, x2): return compare_chararrays(x1, x2, '<=', True) @array_function_dispatch(_binary_op_dispatcher) def greater(x1, x2): return compare_chararrays(x1, x2, '>', True) @array_function_dispatch(_binary_op_dispatcher) def less(x1, x2): return compare_chararrays(x1, x2, '<', True) def multiply(a, i): try: return strings_multiply(a, i) except TypeError: raise ValueError('Can only multiply by integers') def partition(a, sep): return np.stack(strings_partition(a, sep), axis=-1) def rpartition(a, sep): return np.stack(strings_rpartition(a, sep), axis=-1) @set_module('numpy.char') class chararray(ndarray): def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order='C'): if unicode: dtype = str_ else: dtype = bytes_ itemsize = int(itemsize) if isinstance(buffer, str): filler = buffer buffer = None else: filler = None if buffer is None: self = ndarray.__new__(subtype, shape, (dtype, itemsize), order=order) else: self = ndarray.__new__(subtype, shape, (dtype, itemsize), buffer=buffer, offset=offset, strides=strides, order=order) if filler is not None: self[...] = filler return self def __array_wrap__(self, arr, context=None, return_scalar=False): if arr.dtype.char in 'SUbc': return arr.view(type(self)) return arr def __array_finalize__(self, obj): if self.dtype.char not in 'VSUbc': raise ValueError('Can only create a chararray from string data.') def __getitem__(self, obj): val = ndarray.__getitem__(self, obj) if isinstance(val, character): return val.rstrip() return val def __eq__(self, other): return equal(self, other) def __ne__(self, other): return not_equal(self, other) def __ge__(self, other): return greater_equal(self, other) def __le__(self, other): return less_equal(self, other) def __gt__(self, other): return greater(self, other) def __lt__(self, other): return less(self, other) def __add__(self, other): return add(self, other) def __radd__(self, other): return add(other, self) def __mul__(self, i): return asarray(multiply(self, i)) def __rmul__(self, i): return asarray(multiply(self, i)) def __mod__(self, i): return asarray(mod(self, i)) def __rmod__(self, other): return NotImplemented def argsort(self, axis=-1, kind=None, order=None): return self.__array__().argsort(axis, kind, order) argsort.__doc__ = ndarray.argsort.__doc__ def capitalize(self): return asarray(capitalize(self)) def center(self, width, fillchar=' '): return asarray(center(self, width, fillchar)) def count(self, sub, start=0, end=None): return count(self, sub, start, end) def decode(self, encoding=None, errors=None): return decode(self, encoding, errors) def encode(self, encoding=None, errors=None): return encode(self, encoding, errors) def endswith(self, suffix, start=0, end=None): return endswith(self, suffix, start, end) def expandtabs(self, tabsize=8): return asarray(expandtabs(self, tabsize)) def find(self, sub, start=0, end=None): return find(self, sub, start, end) def index(self, sub, start=0, end=None): return index(self, sub, start, end) def isalnum(self): return isalnum(self) def isalpha(self): return isalpha(self) def isdigit(self): return isdigit(self) def islower(self): return islower(self) def isspace(self): return isspace(self) def istitle(self): return istitle(self) def isupper(self): return isupper(self) def join(self, seq): return join(self, seq) def ljust(self, width, fillchar=' '): return asarray(ljust(self, width, fillchar)) def lower(self): return asarray(lower(self)) def lstrip(self, chars=None): return lstrip(self, chars) def partition(self, sep): return asarray(partition(self, sep)) def replace(self, old, new, count=None): return replace(self, old, new, count if count is not None else -1) def rfind(self, sub, start=0, end=None): return rfind(self, sub, start, end) def rindex(self, sub, start=0, end=None): return rindex(self, sub, start, end) def rjust(self, width, fillchar=' '): return asarray(rjust(self, width, fillchar)) def rpartition(self, sep): return asarray(rpartition(self, sep)) def rsplit(self, sep=None, maxsplit=None): return rsplit(self, sep, maxsplit) def rstrip(self, chars=None): return rstrip(self, chars) def split(self, sep=None, maxsplit=None): return split(self, sep, maxsplit) def splitlines(self, keepends=None): return splitlines(self, keepends) def startswith(self, prefix, start=0, end=None): return startswith(self, prefix, start, end) def strip(self, chars=None): return strip(self, chars) def swapcase(self): return asarray(swapcase(self)) def title(self): return asarray(title(self)) def translate(self, table, deletechars=None): return asarray(translate(self, table, deletechars)) def upper(self): return asarray(upper(self)) def zfill(self, width): return asarray(zfill(self, width)) def isnumeric(self): return isnumeric(self) def isdecimal(self): return isdecimal(self) @set_module('numpy.char') def array(obj, itemsize=None, copy=True, unicode=None, order=None): if isinstance(obj, (bytes, str)): if unicode is None: if isinstance(obj, str): unicode = True else: unicode = False if itemsize is None: itemsize = len(obj) shape = len(obj) // itemsize return chararray(shape, itemsize=itemsize, unicode=unicode, buffer=obj, order=order) if isinstance(obj, (list, tuple)): obj = asnarray(obj) if isinstance(obj, ndarray) and issubclass(obj.dtype.type, character): if not isinstance(obj, chararray): obj = obj.view(chararray) if itemsize is None: itemsize = obj.itemsize if issubclass(obj.dtype.type, str_): itemsize //= 4 if unicode is None: if issubclass(obj.dtype.type, str_): unicode = True else: unicode = False if unicode: dtype = str_ else: dtype = bytes_ if order is not None: obj = asnarray(obj, order=order) if copy or itemsize != obj.itemsize or (not unicode and isinstance(obj, str_)) or (unicode and isinstance(obj, bytes_)): obj = obj.astype((dtype, int(itemsize))) return obj if isinstance(obj, ndarray) and issubclass(obj.dtype.type, object): if itemsize is None: obj = obj.tolist() if unicode: dtype = str_ else: dtype = bytes_ if itemsize is None: val = narray(obj, dtype=dtype, order=order, subok=True) else: val = narray(obj, dtype=(dtype, itemsize), order=order, subok=True) return val.view(chararray) @set_module('numpy.char') def asarray(obj, itemsize=None, unicode=None, order=None): return array(obj, itemsize, copy=False, unicode=unicode, order=order) # File: numpy-main/numpy/_core/einsumfunc.py """""" import itertools import operator from numpy._core.multiarray import c_einsum from numpy._core.numeric import asanyarray, tensordot from numpy._core.overrides import array_function_dispatch __all__ = ['einsum', 'einsum_path'] einsum_symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' einsum_symbols_set = set(einsum_symbols) def _flop_count(idx_contraction, inner, num_terms, size_dictionary): overall_size = _compute_size_by_dict(idx_contraction, size_dictionary) op_factor = max(1, num_terms - 1) if inner: op_factor += 1 return overall_size * op_factor def _compute_size_by_dict(indices, idx_dict): ret = 1 for i in indices: ret *= idx_dict[i] return ret def _find_contraction(positions, input_sets, output_set): idx_contract = set() idx_remain = output_set.copy() remaining = [] for (ind, value) in enumerate(input_sets): if ind in positions: idx_contract |= value else: remaining.append(value) idx_remain |= value new_result = idx_remain & idx_contract idx_removed = idx_contract - new_result remaining.append(new_result) return (new_result, remaining, idx_removed, idx_contract) def _optimal_path(input_sets, output_set, idx_dict, memory_limit): full_results = [(0, [], input_sets)] for iteration in range(len(input_sets) - 1): iter_results = [] for curr in full_results: (cost, positions, remaining) = curr for con in itertools.combinations(range(len(input_sets) - iteration), 2): cont = _find_contraction(con, remaining, output_set) (new_result, new_input_sets, idx_removed, idx_contract) = cont new_size = _compute_size_by_dict(new_result, idx_dict) if new_size > memory_limit: continue total_cost = cost + _flop_count(idx_contract, idx_removed, len(con), idx_dict) new_pos = positions + [con] iter_results.append((total_cost, new_pos, new_input_sets)) if iter_results: full_results = iter_results else: path = min(full_results, key=lambda x: x[0])[1] path += [tuple(range(len(input_sets) - iteration))] return path if len(full_results) == 0: return [tuple(range(len(input_sets)))] path = min(full_results, key=lambda x: x[0])[1] return path def _parse_possible_contraction(positions, input_sets, output_set, idx_dict, memory_limit, path_cost, naive_cost): contract = _find_contraction(positions, input_sets, output_set) (idx_result, new_input_sets, idx_removed, idx_contract) = contract new_size = _compute_size_by_dict(idx_result, idx_dict) if new_size > memory_limit: return None old_sizes = (_compute_size_by_dict(input_sets[p], idx_dict) for p in positions) removed_size = sum(old_sizes) - new_size cost = _flop_count(idx_contract, idx_removed, len(positions), idx_dict) sort = (-removed_size, cost) if path_cost + cost > naive_cost: return None return [sort, positions, new_input_sets] def _update_other_results(results, best): best_con = best[1] (bx, by) = best_con mod_results = [] for (cost, (x, y), con_sets) in results: if x in best_con or y in best_con: continue del con_sets[by - int(by > x) - int(by > y)] del con_sets[bx - int(bx > x) - int(bx > y)] con_sets.insert(-1, best[2][-1]) mod_con = (x - int(x > bx) - int(x > by), y - int(y > bx) - int(y > by)) mod_results.append((cost, mod_con, con_sets)) return mod_results def _greedy_path(input_sets, output_set, idx_dict, memory_limit): if len(input_sets) == 1: return [(0,)] elif len(input_sets) == 2: return [(0, 1)] contract = _find_contraction(range(len(input_sets)), input_sets, output_set) (idx_result, new_input_sets, idx_removed, idx_contract) = contract naive_cost = _flop_count(idx_contract, idx_removed, len(input_sets), idx_dict) comb_iter = itertools.combinations(range(len(input_sets)), 2) known_contractions = [] path_cost = 0 path = [] for iteration in range(len(input_sets) - 1): for positions in comb_iter: if input_sets[positions[0]].isdisjoint(input_sets[positions[1]]): continue result = _parse_possible_contraction(positions, input_sets, output_set, idx_dict, memory_limit, path_cost, naive_cost) if result is not None: known_contractions.append(result) if len(known_contractions) == 0: for positions in itertools.combinations(range(len(input_sets)), 2): result = _parse_possible_contraction(positions, input_sets, output_set, idx_dict, memory_limit, path_cost, naive_cost) if result is not None: known_contractions.append(result) if len(known_contractions) == 0: path.append(tuple(range(len(input_sets)))) break best = min(known_contractions, key=lambda x: x[0]) known_contractions = _update_other_results(known_contractions, best) input_sets = best[2] new_tensor_pos = len(input_sets) - 1 comb_iter = ((i, new_tensor_pos) for i in range(new_tensor_pos)) path.append(best[1]) path_cost += best[0][1] return path def _can_dot(inputs, result, idx_removed): if len(idx_removed) == 0: return False if len(inputs) != 2: return False (input_left, input_right) = inputs for c in set(input_left + input_right): (nl, nr) = (input_left.count(c), input_right.count(c)) if nl > 1 or nr > 1 or nl + nr > 2: return False if nl + nr - 1 == int(c in result): return False set_left = set(input_left) set_right = set(input_right) keep_left = set_left - idx_removed keep_right = set_right - idx_removed rs = len(idx_removed) if input_left == input_right: return True if set_left == set_right: return False if input_left[-rs:] == input_right[:rs]: return True if input_left[:rs] == input_right[-rs:]: return True if input_left[-rs:] == input_right[-rs:]: return True if input_left[:rs] == input_right[:rs]: return True if not keep_left or not keep_right: return False return True def _parse_einsum_input(operands): if len(operands) == 0: raise ValueError('No input operands') if isinstance(operands[0], str): subscripts = operands[0].replace(' ', '') operands = [asanyarray(v) for v in operands[1:]] for s in subscripts: if s in '.,->': continue if s not in einsum_symbols: raise ValueError('Character %s is not a valid symbol.' % s) else: tmp_operands = list(operands) operand_list = [] subscript_list = [] for p in range(len(operands) // 2): operand_list.append(tmp_operands.pop(0)) subscript_list.append(tmp_operands.pop(0)) output_list = tmp_operands[-1] if len(tmp_operands) else None operands = [asanyarray(v) for v in operand_list] subscripts = '' last = len(subscript_list) - 1 for (num, sub) in enumerate(subscript_list): for s in sub: if s is Ellipsis: subscripts += '...' else: try: s = operator.index(s) except TypeError as e: raise TypeError('For this input type lists must contain either int or Ellipsis') from e subscripts += einsum_symbols[s] if num != last: subscripts += ',' if output_list is not None: subscripts += '->' for s in output_list: if s is Ellipsis: subscripts += '...' else: try: s = operator.index(s) except TypeError as e: raise TypeError('For this input type lists must contain either int or Ellipsis') from e subscripts += einsum_symbols[s] if '-' in subscripts or '>' in subscripts: invalid = subscripts.count('-') > 1 or subscripts.count('>') > 1 if invalid or subscripts.count('->') != 1: raise ValueError("Subscripts can only contain one '->'.") if '.' in subscripts: used = subscripts.replace('.', '').replace(',', '').replace('->', '') unused = list(einsum_symbols_set - set(used)) ellipse_inds = ''.join(unused) longest = 0 if '->' in subscripts: (input_tmp, output_sub) = subscripts.split('->') split_subscripts = input_tmp.split(',') out_sub = True else: split_subscripts = subscripts.split(',') out_sub = False for (num, sub) in enumerate(split_subscripts): if '.' in sub: if sub.count('.') != 3 or sub.count('...') != 1: raise ValueError('Invalid Ellipses.') if operands[num].shape == (): ellipse_count = 0 else: ellipse_count = max(operands[num].ndim, 1) ellipse_count -= len(sub) - 3 if ellipse_count > longest: longest = ellipse_count if ellipse_count < 0: raise ValueError('Ellipses lengths do not match.') elif ellipse_count == 0: split_subscripts[num] = sub.replace('...', '') else: rep_inds = ellipse_inds[-ellipse_count:] split_subscripts[num] = sub.replace('...', rep_inds) subscripts = ','.join(split_subscripts) if longest == 0: out_ellipse = '' else: out_ellipse = ellipse_inds[-longest:] if out_sub: subscripts += '->' + output_sub.replace('...', out_ellipse) else: output_subscript = '' tmp_subscripts = subscripts.replace(',', '') for s in sorted(set(tmp_subscripts)): if s not in einsum_symbols: raise ValueError('Character %s is not a valid symbol.' % s) if tmp_subscripts.count(s) == 1: output_subscript += s normal_inds = ''.join(sorted(set(output_subscript) - set(out_ellipse))) subscripts += '->' + out_ellipse + normal_inds if '->' in subscripts: (input_subscripts, output_subscript) = subscripts.split('->') else: input_subscripts = subscripts tmp_subscripts = subscripts.replace(',', '') output_subscript = '' for s in sorted(set(tmp_subscripts)): if s not in einsum_symbols: raise ValueError('Character %s is not a valid symbol.' % s) if tmp_subscripts.count(s) == 1: output_subscript += s for char in output_subscript: if output_subscript.count(char) != 1: raise ValueError('Output character %s appeared more than once in the output.' % char) if char not in input_subscripts: raise ValueError('Output character %s did not appear in the input' % char) if len(input_subscripts.split(',')) != len(operands): raise ValueError('Number of einsum subscripts must be equal to the number of operands.') return (input_subscripts, output_subscript, operands) def _einsum_path_dispatcher(*operands, optimize=None, einsum_call=None): return operands @array_function_dispatch(_einsum_path_dispatcher, module='numpy') def einsum_path(*operands, optimize='greedy', einsum_call=False): path_type = optimize if path_type is True: path_type = 'greedy' if path_type is None: path_type = False explicit_einsum_path = False memory_limit = None if path_type is False or isinstance(path_type, str): pass elif len(path_type) and path_type[0] == 'einsum_path': explicit_einsum_path = True elif len(path_type) == 2 and isinstance(path_type[0], str) and isinstance(path_type[1], (int, float)): memory_limit = int(path_type[1]) path_type = path_type[0] else: raise TypeError('Did not understand the path: %s' % str(path_type)) einsum_call_arg = einsum_call (input_subscripts, output_subscript, operands) = _parse_einsum_input(operands) input_list = input_subscripts.split(',') input_sets = [set(x) for x in input_list] output_set = set(output_subscript) indices = set(input_subscripts.replace(',', '')) dimension_dict = {} broadcast_indices = [[] for x in range(len(input_list))] for (tnum, term) in enumerate(input_list): sh = operands[tnum].shape if len(sh) != len(term): raise ValueError('Einstein sum subscript %s does not contain the correct number of indices for operand %d.' % (input_subscripts[tnum], tnum)) for (cnum, char) in enumerate(term): dim = sh[cnum] if dim == 1: broadcast_indices[tnum].append(char) if char in dimension_dict.keys(): if dimension_dict[char] == 1: dimension_dict[char] = dim elif dim not in (1, dimension_dict[char]): raise ValueError("Size of label '%s' for operand %d (%d) does not match previous terms (%d)." % (char, tnum, dimension_dict[char], dim)) else: dimension_dict[char] = dim broadcast_indices = [set(x) for x in broadcast_indices] size_list = [_compute_size_by_dict(term, dimension_dict) for term in input_list + [output_subscript]] max_size = max(size_list) if memory_limit is None: memory_arg = max_size else: memory_arg = memory_limit inner_product = sum((len(x) for x in input_sets)) - len(indices) > 0 naive_cost = _flop_count(indices, inner_product, len(input_list), dimension_dict) if explicit_einsum_path: path = path_type[1:] elif path_type is False or len(input_list) in [1, 2] or indices == output_set: path = [tuple(range(len(input_list)))] elif path_type == 'greedy': path = _greedy_path(input_sets, output_set, dimension_dict, memory_arg) elif path_type == 'optimal': path = _optimal_path(input_sets, output_set, dimension_dict, memory_arg) else: raise KeyError('Path name %s not found', path_type) (cost_list, scale_list, size_list, contraction_list) = ([], [], [], []) for (cnum, contract_inds) in enumerate(path): contract_inds = tuple(sorted(contract_inds, reverse=True)) contract = _find_contraction(contract_inds, input_sets, output_set) (out_inds, input_sets, idx_removed, idx_contract) = contract cost = _flop_count(idx_contract, idx_removed, len(contract_inds), dimension_dict) cost_list.append(cost) scale_list.append(len(idx_contract)) size_list.append(_compute_size_by_dict(out_inds, dimension_dict)) bcast = set() tmp_inputs = [] for x in contract_inds: tmp_inputs.append(input_list.pop(x)) bcast |= broadcast_indices.pop(x) new_bcast_inds = bcast - idx_removed if not len(idx_removed & bcast): do_blas = _can_dot(tmp_inputs, out_inds, idx_removed) else: do_blas = False if cnum - len(path) == -1: idx_result = output_subscript else: sort_result = [(dimension_dict[ind], ind) for ind in out_inds] idx_result = ''.join([x[1] for x in sorted(sort_result)]) input_list.append(idx_result) broadcast_indices.append(new_bcast_inds) einsum_str = ','.join(tmp_inputs) + '->' + idx_result contraction = (contract_inds, idx_removed, einsum_str, input_list[:], do_blas) contraction_list.append(contraction) opt_cost = sum(cost_list) + 1 if len(input_list) != 1: raise RuntimeError('Invalid einsum_path is specified: {} more operands has to be contracted.'.format(len(input_list) - 1)) if einsum_call_arg: return (operands, contraction_list) overall_contraction = input_subscripts + '->' + output_subscript header = ('scaling', 'current', 'remaining') speedup = naive_cost / opt_cost max_i = max(size_list) path_print = ' Complete contraction: %s\n' % overall_contraction path_print += ' Naive scaling: %d\n' % len(indices) path_print += ' Optimized scaling: %d\n' % max(scale_list) path_print += ' Naive FLOP count: %.3e\n' % naive_cost path_print += ' Optimized FLOP count: %.3e\n' % opt_cost path_print += ' Theoretical speedup: %3.3f\n' % speedup path_print += ' Largest intermediate: %.3e elements\n' % max_i path_print += '-' * 74 + '\n' path_print += '%6s %24s %40s\n' % header path_print += '-' * 74 for (n, contraction) in enumerate(contraction_list): (inds, idx_rm, einsum_str, remaining, blas) = contraction remaining_str = ','.join(remaining) + '->' + output_subscript path_run = (scale_list[n], einsum_str, remaining_str) path_print += '\n%4d %24s %40s' % path_run path = ['einsum_path'] + path return (path, path_print) def _einsum_dispatcher(*operands, out=None, optimize=None, **kwargs): yield from operands yield out @array_function_dispatch(_einsum_dispatcher, module='numpy') def einsum(*operands, out=None, optimize=False, **kwargs): specified_out = out is not None if optimize is False: if specified_out: kwargs['out'] = out return c_einsum(*operands, **kwargs) valid_einsum_kwargs = ['dtype', 'order', 'casting'] unknown_kwargs = [k for (k, v) in kwargs.items() if k not in valid_einsum_kwargs] if len(unknown_kwargs): raise TypeError('Did not understand the following kwargs: %s' % unknown_kwargs) (operands, contraction_list) = einsum_path(*operands, optimize=optimize, einsum_call=True) output_order = kwargs.pop('order', 'K') if output_order.upper() == 'A': if all((arr.flags.f_contiguous for arr in operands)): output_order = 'F' else: output_order = 'C' for (num, contraction) in enumerate(contraction_list): (inds, idx_rm, einsum_str, remaining, blas) = contraction tmp_operands = [operands.pop(x) for x in inds] handle_out = specified_out and num + 1 == len(contraction_list) if blas: (input_str, results_index) = einsum_str.split('->') (input_left, input_right) = input_str.split(',') tensor_result = input_left + input_right for s in idx_rm: tensor_result = tensor_result.replace(s, '') (left_pos, right_pos) = ([], []) for s in sorted(idx_rm): left_pos.append(input_left.find(s)) right_pos.append(input_right.find(s)) new_view = tensordot(*tmp_operands, axes=(tuple(left_pos), tuple(right_pos))) if tensor_result != results_index or handle_out: if handle_out: kwargs['out'] = out new_view = c_einsum(tensor_result + '->' + results_index, new_view, **kwargs) else: if handle_out: kwargs['out'] = out new_view = c_einsum(einsum_str, *tmp_operands, **kwargs) operands.append(new_view) del tmp_operands, new_view if specified_out: return out else: return asanyarray(operands[0], order=output_order) # File: numpy-main/numpy/_core/fromnumeric.py """""" import functools import types import warnings import numpy as np from .._utils import set_module from . import multiarray as mu from . import overrides from . import umath as um from . import numerictypes as nt from .multiarray import asarray, array, asanyarray, concatenate from ._multiarray_umath import _array_converter from . import _methods _dt_ = nt.sctype2char __all__ = ['all', 'amax', 'amin', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip', 'compress', 'cumprod', 'cumsum', 'cumulative_prod', 'cumulative_sum', 'diagonal', 'mean', 'max', 'min', 'matrix_transpose', 'ndim', 'nonzero', 'partition', 'prod', 'ptp', 'put', 'ravel', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'shape', 'size', 'sort', 'squeeze', 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var'] _gentype = types.GeneratorType _sum_ = sum array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') def _wrapit(obj, method, *args, **kwds): conv = _array_converter(obj) (arr,) = conv.as_arrays(subok=False) result = getattr(arr, method)(*args, **kwds) return conv.wrap(result, to_scalar=False) def _wrapfunc(obj, method, *args, **kwds): bound = getattr(obj, method, None) if bound is None: return _wrapit(obj, method, *args, **kwds) try: return bound(*args, **kwds) except TypeError: return _wrapit(obj, method, *args, **kwds) def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs): passkwargs = {k: v for (k, v) in kwargs.items() if v is not np._NoValue} if type(obj) is not mu.ndarray: try: reduction = getattr(obj, method) except AttributeError: pass else: if dtype is not None: return reduction(axis=axis, dtype=dtype, out=out, **passkwargs) else: return reduction(axis=axis, out=out, **passkwargs) return ufunc.reduce(obj, axis, dtype, out, **passkwargs) def _wrapreduction_any_all(obj, ufunc, method, axis, out, **kwargs): passkwargs = {k: v for (k, v) in kwargs.items() if v is not np._NoValue} if type(obj) is not mu.ndarray: try: reduction = getattr(obj, method) except AttributeError: pass else: return reduction(axis=axis, out=out, **passkwargs) return ufunc.reduce(obj, axis, bool, out, **passkwargs) def _take_dispatcher(a, indices, axis=None, out=None, mode=None): return (a, out) @array_function_dispatch(_take_dispatcher) def take(a, indices, axis=None, out=None, mode='raise'): return _wrapfunc(a, 'take', indices, axis=axis, out=out, mode=mode) def _reshape_dispatcher(a, /, shape=None, order=None, *, newshape=None, copy=None): return (a,) @array_function_dispatch(_reshape_dispatcher) def reshape(a, /, shape=None, order='C', *, newshape=None, copy=None): if newshape is None and shape is None: raise TypeError("reshape() missing 1 required positional argument: 'shape'") if newshape is not None: if shape is not None: raise TypeError("You cannot specify 'newshape' and 'shape' arguments at the same time.") warnings.warn('`newshape` keyword argument is deprecated, use `shape=...` or pass shape positionally instead. (deprecated in NumPy 2.1)', DeprecationWarning, stacklevel=2) shape = newshape if copy is not None: return _wrapfunc(a, 'reshape', shape, order=order, copy=copy) return _wrapfunc(a, 'reshape', shape, order=order) def _choose_dispatcher(a, choices, out=None, mode=None): yield a yield from choices yield out @array_function_dispatch(_choose_dispatcher) def choose(a, choices, out=None, mode='raise'): return _wrapfunc(a, 'choose', choices, out=out, mode=mode) def _repeat_dispatcher(a, repeats, axis=None): return (a,) @array_function_dispatch(_repeat_dispatcher) def repeat(a, repeats, axis=None): return _wrapfunc(a, 'repeat', repeats, axis=axis) def _put_dispatcher(a, ind, v, mode=None): return (a, ind, v) @array_function_dispatch(_put_dispatcher) def put(a, ind, v, mode='raise'): try: put = a.put except AttributeError as e: raise TypeError('argument 1 must be numpy.ndarray, not {name}'.format(name=type(a).__name__)) from e return put(ind, v, mode=mode) def _swapaxes_dispatcher(a, axis1, axis2): return (a,) @array_function_dispatch(_swapaxes_dispatcher) def swapaxes(a, axis1, axis2): return _wrapfunc(a, 'swapaxes', axis1, axis2) def _transpose_dispatcher(a, axes=None): return (a,) @array_function_dispatch(_transpose_dispatcher) def transpose(a, axes=None): return _wrapfunc(a, 'transpose', axes) def _matrix_transpose_dispatcher(x): return (x,) @array_function_dispatch(_matrix_transpose_dispatcher) def matrix_transpose(x, /): x = asanyarray(x) if x.ndim < 2: raise ValueError(f'Input array must be at least 2-dimensional, but it is {x.ndim}') return swapaxes(x, -1, -2) def _partition_dispatcher(a, kth, axis=None, kind=None, order=None): return (a,) @array_function_dispatch(_partition_dispatcher) def partition(a, kth, axis=-1, kind='introselect', order=None): if axis is None: a = asanyarray(a).flatten() axis = -1 else: a = asanyarray(a).copy(order='K') a.partition(kth, axis=axis, kind=kind, order=order) return a def _argpartition_dispatcher(a, kth, axis=None, kind=None, order=None): return (a,) @array_function_dispatch(_argpartition_dispatcher) def argpartition(a, kth, axis=-1, kind='introselect', order=None): return _wrapfunc(a, 'argpartition', kth, axis=axis, kind=kind, order=order) def _sort_dispatcher(a, axis=None, kind=None, order=None, *, stable=None): return (a,) @array_function_dispatch(_sort_dispatcher) def sort(a, axis=-1, kind=None, order=None, *, stable=None): if axis is None: a = asanyarray(a).flatten() axis = -1 else: a = asanyarray(a).copy(order='K') a.sort(axis=axis, kind=kind, order=order, stable=stable) return a def _argsort_dispatcher(a, axis=None, kind=None, order=None, *, stable=None): return (a,) @array_function_dispatch(_argsort_dispatcher) def argsort(a, axis=-1, kind=None, order=None, *, stable=None): return _wrapfunc(a, 'argsort', axis=axis, kind=kind, order=order, stable=stable) def _argmax_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue): return (a, out) @array_function_dispatch(_argmax_dispatcher) def argmax(a, axis=None, out=None, *, keepdims=np._NoValue): kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {} return _wrapfunc(a, 'argmax', axis=axis, out=out, **kwds) def _argmin_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue): return (a, out) @array_function_dispatch(_argmin_dispatcher) def argmin(a, axis=None, out=None, *, keepdims=np._NoValue): kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {} return _wrapfunc(a, 'argmin', axis=axis, out=out, **kwds) def _searchsorted_dispatcher(a, v, side=None, sorter=None): return (a, v, sorter) @array_function_dispatch(_searchsorted_dispatcher) def searchsorted(a, v, side='left', sorter=None): return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter) def _resize_dispatcher(a, new_shape): return (a,) @array_function_dispatch(_resize_dispatcher) def resize(a, new_shape): if isinstance(new_shape, (int, nt.integer)): new_shape = (new_shape,) a = ravel(a) new_size = 1 for dim_length in new_shape: new_size *= dim_length if dim_length < 0: raise ValueError('all elements of `new_shape` must be non-negative') if a.size == 0 or new_size == 0: return np.zeros_like(a, shape=new_shape) repeats = -(-new_size // a.size) a = concatenate((a,) * repeats)[:new_size] return reshape(a, new_shape) def _squeeze_dispatcher(a, axis=None): return (a,) @array_function_dispatch(_squeeze_dispatcher) def squeeze(a, axis=None): try: squeeze = a.squeeze except AttributeError: return _wrapit(a, 'squeeze', axis=axis) if axis is None: return squeeze() else: return squeeze(axis=axis) def _diagonal_dispatcher(a, offset=None, axis1=None, axis2=None): return (a,) @array_function_dispatch(_diagonal_dispatcher) def diagonal(a, offset=0, axis1=0, axis2=1): if isinstance(a, np.matrix): return asarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2) else: return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2) def _trace_dispatcher(a, offset=None, axis1=None, axis2=None, dtype=None, out=None): return (a, out) @array_function_dispatch(_trace_dispatcher) def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): if isinstance(a, np.matrix): return asarray(a).trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out) else: return asanyarray(a).trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out) def _ravel_dispatcher(a, order=None): return (a,) @array_function_dispatch(_ravel_dispatcher) def ravel(a, order='C'): if isinstance(a, np.matrix): return asarray(a).ravel(order=order) else: return asanyarray(a).ravel(order=order) def _nonzero_dispatcher(a): return (a,) @array_function_dispatch(_nonzero_dispatcher) def nonzero(a): return _wrapfunc(a, 'nonzero') def _shape_dispatcher(a): return (a,) @array_function_dispatch(_shape_dispatcher) def shape(a): try: result = a.shape except AttributeError: result = asarray(a).shape return result def _compress_dispatcher(condition, a, axis=None, out=None): return (condition, a, out) @array_function_dispatch(_compress_dispatcher) def compress(condition, a, axis=None, out=None): return _wrapfunc(a, 'compress', condition, axis=axis, out=out) def _clip_dispatcher(a, a_min=None, a_max=None, out=None, *, min=None, max=None, **kwargs): return (a, a_min, a_max, out, min, max) @array_function_dispatch(_clip_dispatcher) def clip(a, a_min=np._NoValue, a_max=np._NoValue, out=None, *, min=np._NoValue, max=np._NoValue, **kwargs): if a_min is np._NoValue and a_max is np._NoValue: a_min = None if min is np._NoValue else min a_max = None if max is np._NoValue else max elif a_min is np._NoValue: raise TypeError("clip() missing 1 required positional argument: 'a_min'") elif a_max is np._NoValue: raise TypeError("clip() missing 1 required positional argument: 'a_max'") elif min is not np._NoValue or max is not np._NoValue: raise ValueError('Passing `min` or `max` keyword argument when `a_min` and `a_max` are provided is forbidden.') return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs) def _sum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, initial=None, where=None): return (a, out) @array_function_dispatch(_sum_dispatcher) def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue): if isinstance(a, _gentype): warnings.warn('Calling np.sum(generator) is deprecated, and in the future will give a different result. Use np.sum(np.fromiter(generator)) or the python sum builtin instead.', DeprecationWarning, stacklevel=2) res = _sum_(a) if out is not None: out[...] = res return out return res return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims, initial=initial, where=where) def _any_dispatcher(a, axis=None, out=None, keepdims=None, *, where=np._NoValue): return (a, where, out) @array_function_dispatch(_any_dispatcher) def any(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue): return _wrapreduction_any_all(a, np.logical_or, 'any', axis, out, keepdims=keepdims, where=where) def _all_dispatcher(a, axis=None, out=None, keepdims=None, *, where=None): return (a, where, out) @array_function_dispatch(_all_dispatcher) def all(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue): return _wrapreduction_any_all(a, np.logical_and, 'all', axis, out, keepdims=keepdims, where=where) def _cumulative_func(x, func, axis, dtype, out, include_initial): x = np.atleast_1d(x) x_ndim = x.ndim if axis is None: if x_ndim >= 2: raise ValueError('For arrays which have more than one dimension ``axis`` argument is required.') axis = 0 if out is not None and include_initial: item = [slice(None)] * x_ndim item[axis] = slice(1, None) func.accumulate(x, axis=axis, dtype=dtype, out=out[tuple(item)]) item[axis] = 0 out[tuple(item)] = func.identity return out res = func.accumulate(x, axis=axis, dtype=dtype, out=out) if include_initial: initial_shape = list(x.shape) initial_shape[axis] = 1 res = np.concat([np.full_like(res, func.identity, shape=initial_shape), res], axis=axis) return res def _cumulative_prod_dispatcher(x, /, *, axis=None, dtype=None, out=None, include_initial=None): return (x, out) @array_function_dispatch(_cumulative_prod_dispatcher) def cumulative_prod(x, /, *, axis=None, dtype=None, out=None, include_initial=False): return _cumulative_func(x, um.multiply, axis, dtype, out, include_initial) def _cumulative_sum_dispatcher(x, /, *, axis=None, dtype=None, out=None, include_initial=None): return (x, out) @array_function_dispatch(_cumulative_sum_dispatcher) def cumulative_sum(x, /, *, axis=None, dtype=None, out=None, include_initial=False): return _cumulative_func(x, um.add, axis, dtype, out, include_initial) def _cumsum_dispatcher(a, axis=None, dtype=None, out=None): return (a, out) @array_function_dispatch(_cumsum_dispatcher) def cumsum(a, axis=None, dtype=None, out=None): return _wrapfunc(a, 'cumsum', axis=axis, dtype=dtype, out=out) def _ptp_dispatcher(a, axis=None, out=None, keepdims=None): return (a, out) @array_function_dispatch(_ptp_dispatcher) def ptp(a, axis=None, out=None, keepdims=np._NoValue): kwargs = {} if keepdims is not np._NoValue: kwargs['keepdims'] = keepdims return _methods._ptp(a, axis=axis, out=out, **kwargs) def _max_dispatcher(a, axis=None, out=None, keepdims=None, initial=None, where=None): return (a, out) @array_function_dispatch(_max_dispatcher) @set_module('numpy') def max(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue): return _wrapreduction(a, np.maximum, 'max', axis, None, out, keepdims=keepdims, initial=initial, where=where) @array_function_dispatch(_max_dispatcher) def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue): return _wrapreduction(a, np.maximum, 'max', axis, None, out, keepdims=keepdims, initial=initial, where=where) def _min_dispatcher(a, axis=None, out=None, keepdims=None, initial=None, where=None): return (a, out) @array_function_dispatch(_min_dispatcher) def min(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue): return _wrapreduction(a, np.minimum, 'min', axis, None, out, keepdims=keepdims, initial=initial, where=where) @array_function_dispatch(_min_dispatcher) def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue): return _wrapreduction(a, np.minimum, 'min', axis, None, out, keepdims=keepdims, initial=initial, where=where) def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, initial=None, where=None): return (a, out) @array_function_dispatch(_prod_dispatcher) def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue): return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out, keepdims=keepdims, initial=initial, where=where) def _cumprod_dispatcher(a, axis=None, dtype=None, out=None): return (a, out) @array_function_dispatch(_cumprod_dispatcher) def cumprod(a, axis=None, dtype=None, out=None): return _wrapfunc(a, 'cumprod', axis=axis, dtype=dtype, out=out) def _ndim_dispatcher(a): return (a,) @array_function_dispatch(_ndim_dispatcher) def ndim(a): try: return a.ndim except AttributeError: return asarray(a).ndim def _size_dispatcher(a, axis=None): return (a,) @array_function_dispatch(_size_dispatcher) def size(a, axis=None): if axis is None: try: return a.size except AttributeError: return asarray(a).size else: try: return a.shape[axis] except AttributeError: return asarray(a).shape[axis] def _round_dispatcher(a, decimals=None, out=None): return (a, out) @array_function_dispatch(_round_dispatcher) def round(a, decimals=0, out=None): return _wrapfunc(a, 'round', decimals=decimals, out=out) @array_function_dispatch(_round_dispatcher) def around(a, decimals=0, out=None): return _wrapfunc(a, 'round', decimals=decimals, out=out) def _mean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, *, where=None): return (a, where, out) @array_function_dispatch(_mean_dispatcher) def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, *, where=np._NoValue): kwargs = {} if keepdims is not np._NoValue: kwargs['keepdims'] = keepdims if where is not np._NoValue: kwargs['where'] = where if type(a) is not mu.ndarray: try: mean = a.mean except AttributeError: pass else: return mean(axis=axis, dtype=dtype, out=out, **kwargs) return _methods._mean(a, axis=axis, dtype=dtype, out=out, **kwargs) def _std_dispatcher(a, axis=None, dtype=None, out=None, ddof=None, keepdims=None, *, where=None, mean=None, correction=None): return (a, where, out, mean) @array_function_dispatch(_std_dispatcher) def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *, where=np._NoValue, mean=np._NoValue, correction=np._NoValue): kwargs = {} if keepdims is not np._NoValue: kwargs['keepdims'] = keepdims if where is not np._NoValue: kwargs['where'] = where if mean is not np._NoValue: kwargs['mean'] = mean if correction != np._NoValue: if ddof != 0: raise ValueError("ddof and correction can't be provided simultaneously.") else: ddof = correction if type(a) is not mu.ndarray: try: std = a.std except AttributeError: pass else: return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs) return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs) def _var_dispatcher(a, axis=None, dtype=None, out=None, ddof=None, keepdims=None, *, where=None, mean=None, correction=None): return (a, where, out, mean) @array_function_dispatch(_var_dispatcher) def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *, where=np._NoValue, mean=np._NoValue, correction=np._NoValue): kwargs = {} if keepdims is not np._NoValue: kwargs['keepdims'] = keepdims if where is not np._NoValue: kwargs['where'] = where if mean is not np._NoValue: kwargs['mean'] = mean if correction != np._NoValue: if ddof != 0: raise ValueError("ddof and correction can't be provided simultaneously.") else: ddof = correction if type(a) is not mu.ndarray: try: var = a.var except AttributeError: pass else: return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs) return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs) # File: numpy-main/numpy/_core/function_base.py import functools import warnings import operator import types import numpy as np from . import numeric as _nx from .numeric import result_type, nan, asanyarray, ndim from numpy._core.multiarray import add_docstring from numpy._core._multiarray_umath import _array_converter from numpy._core import overrides __all__ = ['logspace', 'linspace', 'geomspace'] array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') def _linspace_dispatcher(start, stop, num=None, endpoint=None, retstep=None, dtype=None, axis=None, *, device=None): return (start, stop) @array_function_dispatch(_linspace_dispatcher) def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0, *, device=None): num = operator.index(num) if num < 0: raise ValueError('Number of samples, %s, must be non-negative.' % num) div = num - 1 if endpoint else num conv = _array_converter(start, stop) (start, stop) = conv.as_arrays() dt = conv.result_type(ensure_inexact=True) if dtype is None: dtype = dt integer_dtype = False else: integer_dtype = _nx.issubdtype(dtype, _nx.integer) delta = np.subtract(stop, start, dtype=type(dt)) y = _nx.arange(0, num, dtype=dt, device=device).reshape((-1,) + (1,) * ndim(delta)) if div > 0: _mult_inplace = _nx.isscalar(delta) step = delta / div any_step_zero = step == 0 if _mult_inplace else _nx.asanyarray(step == 0).any() if any_step_zero: y /= div if _mult_inplace: y *= delta else: y = y * delta elif _mult_inplace: y *= step else: y = y * step else: step = nan y = y * delta y += start if endpoint and num > 1: y[-1, ...] = stop if axis != 0: y = _nx.moveaxis(y, 0, axis) if integer_dtype: _nx.floor(y, out=y) y = conv.wrap(y.astype(dtype, copy=False)) if retstep: return (y, step) else: return y def _logspace_dispatcher(start, stop, num=None, endpoint=None, base=None, dtype=None, axis=None): return (start, stop, base) @array_function_dispatch(_logspace_dispatcher) def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0): if not isinstance(base, (float, int)) and np.ndim(base): ndmax = np.broadcast(start, stop, base).ndim (start, stop, base) = (np.array(a, copy=None, subok=True, ndmin=ndmax) for a in (start, stop, base)) base = np.expand_dims(base, axis=axis) y = linspace(start, stop, num=num, endpoint=endpoint, axis=axis) if dtype is None: return _nx.power(base, y) return _nx.power(base, y).astype(dtype, copy=False) def _geomspace_dispatcher(start, stop, num=None, endpoint=None, dtype=None, axis=None): return (start, stop) @array_function_dispatch(_geomspace_dispatcher) def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0): start = asanyarray(start) stop = asanyarray(stop) if _nx.any(start == 0) or _nx.any(stop == 0): raise ValueError('Geometric sequence cannot include zero') dt = result_type(start, stop, float(num), _nx.zeros((), dtype)) if dtype is None: dtype = dt else: dtype = _nx.dtype(dtype) start = start.astype(dt, copy=True) stop = stop.astype(dt, copy=True) out_sign = _nx.sign(start) start /= out_sign stop = stop / out_sign log_start = _nx.log10(start) log_stop = _nx.log10(stop) result = logspace(log_start, log_stop, num=num, endpoint=endpoint, base=10.0, dtype=dt) if num > 0: result[0] = start if num > 1 and endpoint: result[-1] = stop result *= out_sign if axis != 0: result = _nx.moveaxis(result, 0, axis) return result.astype(dtype, copy=False) def _needs_add_docstring(obj): Py_TPFLAGS_HEAPTYPE = 1 << 9 if isinstance(obj, (types.FunctionType, types.MethodType, property)): return False if isinstance(obj, type) and obj.__flags__ & Py_TPFLAGS_HEAPTYPE: return False return True def _add_docstring(obj, doc, warn_on_python): if warn_on_python and (not _needs_add_docstring(obj)): warnings.warn('add_newdoc was used on a pure-python object {}. Prefer to attach it directly to the source.'.format(obj), UserWarning, stacklevel=3) try: add_docstring(obj, doc) except Exception: pass def add_newdoc(place, obj, doc, warn_on_python=True): new = getattr(__import__(place, globals(), {}, [obj]), obj) if isinstance(doc, str): _add_docstring(new, doc.strip(), warn_on_python) elif isinstance(doc, tuple): (attr, docstring) = doc _add_docstring(getattr(new, attr), docstring.strip(), warn_on_python) elif isinstance(doc, list): for (attr, docstring) in doc: _add_docstring(getattr(new, attr), docstring.strip(), warn_on_python) # File: numpy-main/numpy/_core/getlimits.py """""" __all__ = ['finfo', 'iinfo'] import types import warnings from .._utils import set_module from ._machar import MachAr from . import numeric from . import numerictypes as ntypes from .numeric import array, inf, nan from .umath import log10, exp2, nextafter, isnan def _fr0(a): if a.ndim == 0: a = a.copy() a.shape = (1,) return a def _fr1(a): if a.size == 1: a = a.copy() a.shape = () return a class MachArLike: def __init__(self, ftype, *, eps, epsneg, huge, tiny, ibeta, smallest_subnormal=None, **kwargs): self.params = _MACHAR_PARAMS[ftype] self.ftype = ftype self.title = self.params['title'] if not smallest_subnormal: self._smallest_subnormal = nextafter(self.ftype(0), self.ftype(1), dtype=self.ftype) else: self._smallest_subnormal = smallest_subnormal self.epsilon = self.eps = self._float_to_float(eps) self.epsneg = self._float_to_float(epsneg) self.xmax = self.huge = self._float_to_float(huge) self.xmin = self._float_to_float(tiny) self.smallest_normal = self.tiny = self._float_to_float(tiny) self.ibeta = self.params['itype'](ibeta) self.__dict__.update(kwargs) self.precision = int(-log10(self.eps)) self.resolution = self._float_to_float(self._float_conv(10) ** (-self.precision)) self._str_eps = self._float_to_str(self.eps) self._str_epsneg = self._float_to_str(self.epsneg) self._str_xmin = self._float_to_str(self.xmin) self._str_xmax = self._float_to_str(self.xmax) self._str_resolution = self._float_to_str(self.resolution) self._str_smallest_normal = self._float_to_str(self.xmin) @property def smallest_subnormal(self): value = self._smallest_subnormal if self.ftype(0) == value: warnings.warn('The value of the smallest subnormal for {} type is zero.'.format(self.ftype), UserWarning, stacklevel=2) return self._float_to_float(value) @property def _str_smallest_subnormal(self): return self._float_to_str(self.smallest_subnormal) def _float_to_float(self, value): return _fr1(self._float_conv(value)) def _float_conv(self, value): return array([value], self.ftype) def _float_to_str(self, value): return self.params['fmt'] % array(_fr0(value)[0], self.ftype) _convert_to_float = {ntypes.csingle: ntypes.single, ntypes.complex128: ntypes.float64, ntypes.clongdouble: ntypes.longdouble} _title_fmt = 'numpy {} precision floating point number' _MACHAR_PARAMS = {ntypes.double: dict(itype=ntypes.int64, fmt='%24.16e', title=_title_fmt.format('double')), ntypes.single: dict(itype=ntypes.int32, fmt='%15.7e', title=_title_fmt.format('single')), ntypes.longdouble: dict(itype=ntypes.longlong, fmt='%s', title=_title_fmt.format('long double')), ntypes.half: dict(itype=ntypes.int16, fmt='%12.5e', title=_title_fmt.format('half'))} _KNOWN_TYPES = {} def _register_type(machar, bytepat): _KNOWN_TYPES[bytepat] = machar _float_ma = {} def _register_known_types(): f16 = ntypes.float16 float16_ma = MachArLike(f16, machep=-10, negep=-11, minexp=-14, maxexp=16, it=10, iexp=5, ibeta=2, irnd=5, ngrd=0, eps=exp2(f16(-10)), epsneg=exp2(f16(-11)), huge=f16(65504), tiny=f16(2 ** (-14))) _register_type(float16_ma, b'f\xae') _float_ma[16] = float16_ma f32 = ntypes.float32 float32_ma = MachArLike(f32, machep=-23, negep=-24, minexp=-126, maxexp=128, it=23, iexp=8, ibeta=2, irnd=5, ngrd=0, eps=exp2(f32(-23)), epsneg=exp2(f32(-24)), huge=f32((1 - 2 ** (-24)) * 2 ** 128), tiny=exp2(f32(-126))) _register_type(float32_ma, b'\xcd\xcc\xcc\xbd') _float_ma[32] = float32_ma f64 = ntypes.float64 epsneg_f64 = 2.0 ** (-53.0) tiny_f64 = 2.0 ** (-1022.0) float64_ma = MachArLike(f64, machep=-52, negep=-53, minexp=-1022, maxexp=1024, it=52, iexp=11, ibeta=2, irnd=5, ngrd=0, eps=2.0 ** (-52.0), epsneg=epsneg_f64, huge=(1.0 - epsneg_f64) / tiny_f64 * f64(4), tiny=tiny_f64) _register_type(float64_ma, b'\x9a\x99\x99\x99\x99\x99\xb9\xbf') _float_ma[64] = float64_ma ld = ntypes.longdouble epsneg_f128 = exp2(ld(-113)) tiny_f128 = exp2(ld(-16382)) with numeric.errstate(all='ignore'): huge_f128 = (ld(1) - epsneg_f128) / tiny_f128 * ld(4) float128_ma = MachArLike(ld, machep=-112, negep=-113, minexp=-16382, maxexp=16384, it=112, iexp=15, ibeta=2, irnd=5, ngrd=0, eps=exp2(ld(-112)), epsneg=epsneg_f128, huge=huge_f128, tiny=tiny_f128) _register_type(float128_ma, b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf') _float_ma[128] = float128_ma epsneg_f80 = exp2(ld(-64)) tiny_f80 = exp2(ld(-16382)) with numeric.errstate(all='ignore'): huge_f80 = (ld(1) - epsneg_f80) / tiny_f80 * ld(4) float80_ma = MachArLike(ld, machep=-63, negep=-64, minexp=-16382, maxexp=16384, it=63, iexp=15, ibeta=2, irnd=5, ngrd=0, eps=exp2(ld(-63)), epsneg=epsneg_f80, huge=huge_f80, tiny=tiny_f80) _register_type(float80_ma, b'\xcd\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xfb\xbf') _float_ma[80] = float80_ma huge_dd = nextafter(ld(inf), ld(0), dtype=ld) smallest_normal_dd = nan smallest_subnormal_dd = ld(nextafter(0.0, 1.0)) float_dd_ma = MachArLike(ld, machep=-105, negep=-106, minexp=-1022, maxexp=1024, it=105, iexp=11, ibeta=2, irnd=5, ngrd=0, eps=exp2(ld(-105)), epsneg=exp2(ld(-106)), huge=huge_dd, tiny=smallest_normal_dd, smallest_subnormal=smallest_subnormal_dd) _register_type(float_dd_ma, b'\x9a\x99\x99\x99\x99\x99Y<\x9a\x99\x99\x99\x99\x99\xb9\xbf') _register_type(float_dd_ma, b'\x9a\x99\x99\x99\x99\x99\xb9\xbf\x9a\x99\x99\x99\x99\x99Y<') _float_ma['dd'] = float_dd_ma def _get_machar(ftype): params = _MACHAR_PARAMS.get(ftype) if params is None: raise ValueError(repr(ftype)) key = ftype(-1.0) / ftype(10.0) key = key.view(key.dtype.newbyteorder('<')).tobytes() ma_like = None if ftype == ntypes.longdouble: ma_like = _KNOWN_TYPES.get(key[:10]) if ma_like is None: ma_like = _KNOWN_TYPES.get(key) if ma_like is None and len(key) == 16: _kt = {k[:10]: v for (k, v) in _KNOWN_TYPES.items() if len(k) == 16} ma_like = _kt.get(key[:10]) if ma_like is not None: return ma_like warnings.warn(f'Signature {key} for {ftype} does not match any known type: falling back to type probe function.\nThis warnings indicates broken support for the dtype!', UserWarning, stacklevel=2) return _discovered_machar(ftype) def _discovered_machar(ftype): params = _MACHAR_PARAMS[ftype] return MachAr(lambda v: array([v], ftype), lambda v: _fr0(v.astype(params['itype']))[0], lambda v: array(_fr0(v)[0], ftype), lambda v: params['fmt'] % array(_fr0(v)[0], ftype), params['title']) @set_module('numpy') class finfo: _finfo_cache = {} __class_getitem__ = classmethod(types.GenericAlias) def __new__(cls, dtype): try: obj = cls._finfo_cache.get(dtype) if obj is not None: return obj except TypeError: pass if dtype is None: warnings.warn('finfo() dtype cannot be None. This behavior will raise an error in the future. (Deprecated in NumPy 1.25)', DeprecationWarning, stacklevel=2) try: dtype = numeric.dtype(dtype) except TypeError: dtype = numeric.dtype(type(dtype)) obj = cls._finfo_cache.get(dtype) if obj is not None: return obj dtypes = [dtype] newdtype = ntypes.obj2sctype(dtype) if newdtype is not dtype: dtypes.append(newdtype) dtype = newdtype if not issubclass(dtype, numeric.inexact): raise ValueError('data type %r not inexact' % dtype) obj = cls._finfo_cache.get(dtype) if obj is not None: return obj if not issubclass(dtype, numeric.floating): newdtype = _convert_to_float[dtype] if newdtype is not dtype: dtypes.append(newdtype) dtype = newdtype obj = cls._finfo_cache.get(dtype, None) if obj is not None: for dt in dtypes: cls._finfo_cache[dt] = obj return obj obj = object.__new__(cls)._init(dtype) for dt in dtypes: cls._finfo_cache[dt] = obj return obj def _init(self, dtype): self.dtype = numeric.dtype(dtype) machar = _get_machar(dtype) for word in ['precision', 'iexp', 'maxexp', 'minexp', 'negep', 'machep']: setattr(self, word, getattr(machar, word)) for word in ['resolution', 'epsneg', 'smallest_subnormal']: setattr(self, word, getattr(machar, word).flat[0]) self.bits = self.dtype.itemsize * 8 self.max = machar.huge.flat[0] self.min = -self.max self.eps = machar.eps.flat[0] self.nexp = machar.iexp self.nmant = machar.it self._machar = machar self._str_tiny = machar._str_xmin.strip() self._str_max = machar._str_xmax.strip() self._str_epsneg = machar._str_epsneg.strip() self._str_eps = machar._str_eps.strip() self._str_resolution = machar._str_resolution.strip() self._str_smallest_normal = machar._str_smallest_normal.strip() self._str_smallest_subnormal = machar._str_smallest_subnormal.strip() return self def __str__(self): fmt = 'Machine parameters for %(dtype)s\n---------------------------------------------------------------\nprecision = %(precision)3s resolution = %(_str_resolution)s\nmachep = %(machep)6s eps = %(_str_eps)s\nnegep = %(negep)6s epsneg = %(_str_epsneg)s\nminexp = %(minexp)6s tiny = %(_str_tiny)s\nmaxexp = %(maxexp)6s max = %(_str_max)s\nnexp = %(nexp)6s min = -max\nsmallest_normal = %(_str_smallest_normal)s smallest_subnormal = %(_str_smallest_subnormal)s\n---------------------------------------------------------------\n' return fmt % self.__dict__ def __repr__(self): c = self.__class__.__name__ d = self.__dict__.copy() d['klass'] = c return '%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s, max=%(_str_max)s, dtype=%(dtype)s)' % d @property def smallest_normal(self): if isnan(self._machar.smallest_normal.flat[0]): warnings.warn('The value of smallest normal is undefined for double double', UserWarning, stacklevel=2) return self._machar.smallest_normal.flat[0] @property def tiny(self): return self.smallest_normal @set_module('numpy') class iinfo: _min_vals = {} _max_vals = {} __class_getitem__ = classmethod(types.GenericAlias) def __init__(self, int_type): try: self.dtype = numeric.dtype(int_type) except TypeError: self.dtype = numeric.dtype(type(int_type)) self.kind = self.dtype.kind self.bits = self.dtype.itemsize * 8 self.key = '%s%d' % (self.kind, self.bits) if self.kind not in 'iu': raise ValueError('Invalid integer data type %r.' % (self.kind,)) @property def min(self): if self.kind == 'u': return 0 else: try: val = iinfo._min_vals[self.key] except KeyError: val = int(-(1 << self.bits - 1)) iinfo._min_vals[self.key] = val return val @property def max(self): try: val = iinfo._max_vals[self.key] except KeyError: if self.kind == 'u': val = int((1 << self.bits) - 1) else: val = int((1 << self.bits - 1) - 1) iinfo._max_vals[self.key] = val return val def __str__(self): fmt = 'Machine parameters for %(dtype)s\n---------------------------------------------------------------\nmin = %(min)s\nmax = %(max)s\n---------------------------------------------------------------\n' return fmt % {'dtype': self.dtype, 'min': self.min, 'max': self.max} def __repr__(self): return '%s(min=%s, max=%s, dtype=%s)' % (self.__class__.__name__, self.min, self.max, self.dtype) # File: numpy-main/numpy/_core/memmap.py from contextlib import nullcontext import operator import numpy as np from .._utils import set_module from .numeric import uint8, ndarray, dtype __all__ = ['memmap'] dtypedescr = dtype valid_filemodes = ['r', 'c', 'r+', 'w+'] writeable_filemodes = ['r+', 'w+'] mode_equivalents = {'readonly': 'r', 'copyonwrite': 'c', 'readwrite': 'r+', 'write': 'w+'} @set_module('numpy') class memmap(ndarray): __array_priority__ = -100.0 def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0, shape=None, order='C'): import mmap import os.path try: mode = mode_equivalents[mode] except KeyError as e: if mode not in valid_filemodes: raise ValueError('mode must be one of {!r} (got {!r})'.format(valid_filemodes + list(mode_equivalents.keys()), mode)) from None if mode == 'w+' and shape is None: raise ValueError("shape must be given if mode == 'w+'") if hasattr(filename, 'read'): f_ctx = nullcontext(filename) else: f_ctx = open(os.fspath(filename), ('r' if mode == 'c' else mode) + 'b') with f_ctx as fid: fid.seek(0, 2) flen = fid.tell() descr = dtypedescr(dtype) _dbytes = descr.itemsize if shape is None: bytes = flen - offset if bytes % _dbytes: raise ValueError('Size of available data is not a multiple of the data-type size.') size = bytes // _dbytes shape = (size,) else: if type(shape) not in (tuple, list): try: shape = [operator.index(shape)] except TypeError: pass shape = tuple(shape) size = np.intp(1) for k in shape: size *= k bytes = int(offset + size * _dbytes) if mode in ('w+', 'r+') and flen < bytes: fid.seek(bytes - 1, 0) fid.write(b'\x00') fid.flush() if mode == 'c': acc = mmap.ACCESS_COPY elif mode == 'r': acc = mmap.ACCESS_READ else: acc = mmap.ACCESS_WRITE start = offset - offset % mmap.ALLOCATIONGRANULARITY bytes -= start array_offset = offset - start mm = mmap.mmap(fid.fileno(), bytes, access=acc, offset=start) self = ndarray.__new__(subtype, shape, dtype=descr, buffer=mm, offset=array_offset, order=order) self._mmap = mm self.offset = offset self.mode = mode if isinstance(filename, os.PathLike): self.filename = filename.resolve() elif hasattr(fid, 'name') and isinstance(fid.name, str): self.filename = os.path.abspath(fid.name) else: self.filename = None return self def __array_finalize__(self, obj): if hasattr(obj, '_mmap') and np.may_share_memory(self, obj): self._mmap = obj._mmap self.filename = obj.filename self.offset = obj.offset self.mode = obj.mode else: self._mmap = None self.filename = None self.offset = None self.mode = None def flush(self): if self.base is not None and hasattr(self.base, 'flush'): self.base.flush() def __array_wrap__(self, arr, context=None, return_scalar=False): arr = super().__array_wrap__(arr, context) if self is arr or type(self) is not memmap: return arr if return_scalar: return arr[()] return arr.view(np.ndarray) def __getitem__(self, index): res = super().__getitem__(index) if type(res) is memmap and res._mmap is None: return res.view(type=ndarray) return res # File: numpy-main/numpy/_core/multiarray.py """""" import functools from . import overrides from . import _multiarray_umath from ._multiarray_umath import * from ._multiarray_umath import _flagdict, from_dlpack, _place, _reconstruct, _vec_string, _ARRAY_API, _monotonicity, _get_ndarray_c_version, _get_madvise_hugepage, _set_madvise_hugepage __all__ = ['_ARRAY_API', 'ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DATETIMEUNITS', 'ITEM_HASOBJECT', 'ITEM_IS_POINTER', 'LIST_PICKLE', 'MAXDIMS', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'NEEDS_INIT', 'NEEDS_PYAPI', 'RAISE', 'USE_GETITEM', 'USE_SETITEM', 'WRAP', '_flagdict', 'from_dlpack', '_place', '_reconstruct', '_vec_string', '_monotonicity', 'add_docstring', 'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'bincount', 'broadcast', 'busday_count', 'busday_offset', 'busdaycalendar', 'can_cast', 'compare_chararrays', 'concatenate', 'copyto', 'correlate', 'correlate2', 'count_nonzero', 'c_einsum', 'datetime_as_string', 'datetime_data', 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype', 'empty', 'empty_like', 'error', 'flagsobj', 'flatiter', 'format_longfloat', 'frombuffer', 'fromfile', 'fromiter', 'fromstring', 'get_handler_name', 'get_handler_version', 'inner', 'interp', 'interp_complex', 'is_busday', 'lexsort', 'matmul', 'vecdot', 'may_share_memory', 'min_scalar_type', 'ndarray', 'nditer', 'nested_iters', 'normalize_axis_index', 'packbits', 'promote_types', 'putmask', 'ravel_multi_index', 'result_type', 'scalar', 'set_datetimeparse_function', 'set_typeDict', 'shares_memory', 'typeinfo', 'unpackbits', 'unravel_index', 'vdot', 'where', 'zeros'] _reconstruct.__module__ = 'numpy._core.multiarray' scalar.__module__ = 'numpy._core.multiarray' from_dlpack.__module__ = 'numpy' arange.__module__ = 'numpy' array.__module__ = 'numpy' asarray.__module__ = 'numpy' asanyarray.__module__ = 'numpy' ascontiguousarray.__module__ = 'numpy' asfortranarray.__module__ = 'numpy' datetime_data.__module__ = 'numpy' empty.__module__ = 'numpy' frombuffer.__module__ = 'numpy' fromfile.__module__ = 'numpy' fromiter.__module__ = 'numpy' frompyfunc.__module__ = 'numpy' fromstring.__module__ = 'numpy' may_share_memory.__module__ = 'numpy' nested_iters.__module__ = 'numpy' promote_types.__module__ = 'numpy' zeros.__module__ = 'numpy' normalize_axis_index.__module__ = 'numpy.lib.array_utils' array_function_from_c_func_and_dispatcher = functools.partial(overrides.array_function_from_dispatcher, module='numpy', docs_from_dispatcher=True, verify=False) @array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like) def empty_like(prototype, dtype=None, order=None, subok=None, shape=None, *, device=None): return (prototype,) @array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate) def concatenate(arrays, axis=None, out=None, *, dtype=None, casting=None): if out is not None: arrays = list(arrays) arrays.append(out) return arrays @array_function_from_c_func_and_dispatcher(_multiarray_umath.inner) def inner(a, b): return (a, b) @array_function_from_c_func_and_dispatcher(_multiarray_umath.where) def where(condition, x=None, y=None): return (condition, x, y) @array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort) def lexsort(keys, axis=None): if isinstance(keys, tuple): return keys else: return (keys,) @array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast) def can_cast(from_, to, casting=None): return (from_,) @array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type) def min_scalar_type(a): return (a,) @array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type) def result_type(*arrays_and_dtypes): return arrays_and_dtypes @array_function_from_c_func_and_dispatcher(_multiarray_umath.dot) def dot(a, b, out=None): return (a, b, out) @array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot) def vdot(a, b): return (a, b) @array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount) def bincount(x, weights=None, minlength=None): return (x, weights) @array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index) def ravel_multi_index(multi_index, dims, mode=None, order=None): return multi_index @array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index) def unravel_index(indices, shape=None, order=None): return (indices,) @array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto) def copyto(dst, src, casting=None, where=None): return (dst, src, where) @array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask) def putmask(a, /, mask, values): return (a, mask, values) @array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits) def packbits(a, axis=None, bitorder='big'): return (a,) @array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits) def unpackbits(a, axis=None, count=None, bitorder='big'): return (a,) @array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory) def shares_memory(a, b, max_work=None): return (a, b) @array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory) def may_share_memory(a, b, max_work=None): return (a, b) @array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday) def is_busday(dates, weekmask=None, holidays=None, busdaycal=None, out=None): return (dates, weekmask, holidays, out) @array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset) def busday_offset(dates, offsets, roll=None, weekmask=None, holidays=None, busdaycal=None, out=None): return (dates, offsets, weekmask, holidays, out) @array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count) def busday_count(begindates, enddates, weekmask=None, holidays=None, busdaycal=None, out=None): return (begindates, enddates, weekmask, holidays, out) @array_function_from_c_func_and_dispatcher(_multiarray_umath.datetime_as_string) def datetime_as_string(arr, unit=None, timezone=None, casting=None): return (arr,) # File: numpy-main/numpy/_core/numeric.py import functools import itertools import operator import sys import warnings import numbers import builtins import math import numpy as np from . import multiarray from . import numerictypes as nt from .multiarray import ALLOW_THREADS, BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT, RAISE, WRAP, arange, array, asarray, asanyarray, ascontiguousarray, asfortranarray, broadcast, can_cast, concatenate, copyto, dot, dtype, empty, empty_like, flatiter, frombuffer, from_dlpack, fromfile, fromiter, fromstring, inner, lexsort, matmul, may_share_memory, min_scalar_type, ndarray, nditer, nested_iters, promote_types, putmask, result_type, shares_memory, vdot, where, zeros, normalize_axis_index, vecdot from . import overrides from . import umath from . import shape_base from .overrides import set_array_function_like_doc, set_module from .umath import multiply, invert, sin, PINF, NAN from . import numerictypes from ..exceptions import AxisError from ._ufunc_config import errstate bitwise_not = invert ufunc = type(sin) newaxis = None array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') __all__ = ['newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc', 'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype', 'fromstring', 'fromfile', 'frombuffer', 'from_dlpack', 'where', 'argwhere', 'copyto', 'concatenate', 'lexsort', 'astype', 'can_cast', 'promote_types', 'min_scalar_type', 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like', 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll', 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones', 'identity', 'allclose', 'putmask', 'flatnonzero', 'inf', 'nan', 'False_', 'True_', 'bitwise_not', 'full', 'full_like', 'matmul', 'vecdot', 'shares_memory', 'may_share_memory'] def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None, *, device=None): return (a,) @array_function_dispatch(_zeros_like_dispatcher) def zeros_like(a, dtype=None, order='K', subok=True, shape=None, *, device=None): res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape, device=device) z = zeros(1, dtype=res.dtype) multiarray.copyto(res, z, casting='unsafe') return res @set_array_function_like_doc @set_module('numpy') def ones(shape, dtype=None, order='C', *, device=None, like=None): if like is not None: return _ones_with_like(like, shape, dtype=dtype, order=order, device=device) a = empty(shape, dtype, order, device=device) multiarray.copyto(a, 1, casting='unsafe') return a _ones_with_like = array_function_dispatch()(ones) def _ones_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None, *, device=None): return (a,) @array_function_dispatch(_ones_like_dispatcher) def ones_like(a, dtype=None, order='K', subok=True, shape=None, *, device=None): res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape, device=device) multiarray.copyto(res, 1, casting='unsafe') return res def _full_dispatcher(shape, fill_value, dtype=None, order=None, *, device=None, like=None): return (like,) @set_array_function_like_doc @set_module('numpy') def full(shape, fill_value, dtype=None, order='C', *, device=None, like=None): if like is not None: return _full_with_like(like, shape, fill_value, dtype=dtype, order=order, device=device) if dtype is None: fill_value = asarray(fill_value) dtype = fill_value.dtype a = empty(shape, dtype, order, device=device) multiarray.copyto(a, fill_value, casting='unsafe') return a _full_with_like = array_function_dispatch()(full) def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None, shape=None, *, device=None): return (a,) @array_function_dispatch(_full_like_dispatcher) def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None, *, device=None): res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape, device=device) multiarray.copyto(res, fill_value, casting='unsafe') return res def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None): return (a,) @array_function_dispatch(_count_nonzero_dispatcher) def count_nonzero(a, axis=None, *, keepdims=False): if axis is None and (not keepdims): return multiarray.count_nonzero(a) a = asanyarray(a) if np.issubdtype(a.dtype, np.character): a_bool = a != a.dtype.type() else: a_bool = a.astype(np.bool, copy=False) return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims) @set_module('numpy') def isfortran(a): return a.flags.fnc def _argwhere_dispatcher(a): return (a,) @array_function_dispatch(_argwhere_dispatcher) def argwhere(a): if np.ndim(a) == 0: a = shape_base.atleast_1d(a) return argwhere(a)[:, :0] return transpose(nonzero(a)) def _flatnonzero_dispatcher(a): return (a,) @array_function_dispatch(_flatnonzero_dispatcher) def flatnonzero(a): return np.nonzero(np.ravel(a))[0] def _correlate_dispatcher(a, v, mode=None): return (a, v) @array_function_dispatch(_correlate_dispatcher) def correlate(a, v, mode='valid'): return multiarray.correlate2(a, v, mode) def _convolve_dispatcher(a, v, mode=None): return (a, v) @array_function_dispatch(_convolve_dispatcher) def convolve(a, v, mode='full'): (a, v) = (array(a, copy=None, ndmin=1), array(v, copy=None, ndmin=1)) if len(v) > len(a): (a, v) = (v, a) if len(a) == 0: raise ValueError('a cannot be empty') if len(v) == 0: raise ValueError('v cannot be empty') return multiarray.correlate(a, v[::-1], mode) def _outer_dispatcher(a, b, out=None): return (a, b, out) @array_function_dispatch(_outer_dispatcher) def outer(a, b, out=None): a = asarray(a) b = asarray(b) return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out) def _tensordot_dispatcher(a, b, axes=None): return (a, b) @array_function_dispatch(_tensordot_dispatcher) def tensordot(a, b, axes=2): try: iter(axes) except Exception: axes_a = list(range(-axes, 0)) axes_b = list(range(0, axes)) else: (axes_a, axes_b) = axes try: na = len(axes_a) axes_a = list(axes_a) except TypeError: axes_a = [axes_a] na = 1 try: nb = len(axes_b) axes_b = list(axes_b) except TypeError: axes_b = [axes_b] nb = 1 (a, b) = (asarray(a), asarray(b)) as_ = a.shape nda = a.ndim bs = b.shape ndb = b.ndim equal = True if na != nb: equal = False else: for k in range(na): if as_[axes_a[k]] != bs[axes_b[k]]: equal = False break if axes_a[k] < 0: axes_a[k] += nda if axes_b[k] < 0: axes_b[k] += ndb if not equal: raise ValueError('shape-mismatch for sum') notin = [k for k in range(nda) if k not in axes_a] newaxes_a = notin + axes_a N2 = math.prod((as_[axis] for axis in axes_a)) newshape_a = (math.prod([as_[ax] for ax in notin]), N2) olda = [as_[axis] for axis in notin] notin = [k for k in range(ndb) if k not in axes_b] newaxes_b = axes_b + notin N2 = math.prod((bs[axis] for axis in axes_b)) newshape_b = (N2, math.prod([bs[ax] for ax in notin])) oldb = [bs[axis] for axis in notin] at = a.transpose(newaxes_a).reshape(newshape_a) bt = b.transpose(newaxes_b).reshape(newshape_b) res = dot(at, bt) return res.reshape(olda + oldb) def _roll_dispatcher(a, shift, axis=None): return (a,) @array_function_dispatch(_roll_dispatcher) def roll(a, shift, axis=None): a = asanyarray(a) if axis is None: return roll(a.ravel(), shift, 0).reshape(a.shape) else: axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True) broadcasted = broadcast(shift, axis) if broadcasted.ndim > 1: raise ValueError("'shift' and 'axis' should be scalars or 1D sequences") shifts = {ax: 0 for ax in range(a.ndim)} for (sh, ax) in broadcasted: shifts[ax] += sh rolls = [((slice(None), slice(None)),)] * a.ndim for (ax, offset) in shifts.items(): offset %= a.shape[ax] or 1 if offset: rolls[ax] = ((slice(None, -offset), slice(offset, None)), (slice(-offset, None), slice(None, offset))) result = empty_like(a) for indices in itertools.product(*rolls): (arr_index, res_index) = zip(*indices) result[res_index] = a[arr_index] return result def _rollaxis_dispatcher(a, axis, start=None): return (a,) @array_function_dispatch(_rollaxis_dispatcher) def rollaxis(a, axis, start=0): n = a.ndim axis = normalize_axis_index(axis, n) if start < 0: start += n msg = "'%s' arg requires %d <= %s < %d, but %d was passed in" if not 0 <= start < n + 1: raise AxisError(msg % ('start', -n, 'start', n + 1, start)) if axis < start: start -= 1 if axis == start: return a[...] axes = list(range(0, n)) axes.remove(axis) axes.insert(start, axis) return a.transpose(axes) @set_module('numpy.lib.array_utils') def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False): if type(axis) not in (tuple, list): try: axis = [operator.index(axis)] except TypeError: pass axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis]) if not allow_duplicate and len(set(axis)) != len(axis): if argname: raise ValueError('repeated axis in `{}` argument'.format(argname)) else: raise ValueError('repeated axis') return axis def _moveaxis_dispatcher(a, source, destination): return (a,) @array_function_dispatch(_moveaxis_dispatcher) def moveaxis(a, source, destination): try: transpose = a.transpose except AttributeError: a = asarray(a) transpose = a.transpose source = normalize_axis_tuple(source, a.ndim, 'source') destination = normalize_axis_tuple(destination, a.ndim, 'destination') if len(source) != len(destination): raise ValueError('`source` and `destination` arguments must have the same number of elements') order = [n for n in range(a.ndim) if n not in source] for (dest, src) in sorted(zip(destination, source)): order.insert(dest, src) result = transpose(order) return result def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None): return (a, b) @array_function_dispatch(_cross_dispatcher) def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): if axis is not None: (axisa, axisb, axisc) = (axis,) * 3 a = asarray(a) b = asarray(b) if a.ndim < 1 or b.ndim < 1: raise ValueError('At least one array has zero dimension') axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa') axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb') a = moveaxis(a, axisa, -1) b = moveaxis(b, axisb, -1) msg = 'incompatible dimensions for cross product\n(dimension must be 2 or 3)' if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3): raise ValueError(msg) if a.shape[-1] == 2 or b.shape[-1] == 2: warnings.warn('Arrays of 2-dimensional vectors are deprecated. Use arrays of 3-dimensional vectors instead. (deprecated in NumPy 2.0)', DeprecationWarning, stacklevel=2) shape = broadcast(a[..., 0], b[..., 0]).shape if a.shape[-1] == 3 or b.shape[-1] == 3: shape += (3,) axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc') dtype = promote_types(a.dtype, b.dtype) cp = empty(shape, dtype) a = a.astype(dtype) b = b.astype(dtype) a0 = a[..., 0] a1 = a[..., 1] if a.shape[-1] == 3: a2 = a[..., 2] b0 = b[..., 0] b1 = b[..., 1] if b.shape[-1] == 3: b2 = b[..., 2] if cp.ndim != 0 and cp.shape[-1] == 3: cp0 = cp[..., 0] cp1 = cp[..., 1] cp2 = cp[..., 2] if a.shape[-1] == 2: if b.shape[-1] == 2: multiply(a0, b1, out=cp) cp -= a1 * b0 return cp else: assert b.shape[-1] == 3 multiply(a1, b2, out=cp0) multiply(a0, b2, out=cp1) negative(cp1, out=cp1) multiply(a0, b1, out=cp2) cp2 -= a1 * b0 else: assert a.shape[-1] == 3 if b.shape[-1] == 3: multiply(a1, b2, out=cp0) tmp = array(a2 * b1) cp0 -= tmp multiply(a2, b0, out=cp1) multiply(a0, b2, out=tmp) cp1 -= tmp multiply(a0, b1, out=cp2) multiply(a1, b0, out=tmp) cp2 -= tmp else: assert b.shape[-1] == 2 multiply(a2, b1, out=cp0) negative(cp0, out=cp0) multiply(a2, b0, out=cp1) multiply(a0, b1, out=cp2) cp2 -= a1 * b0 return moveaxis(cp, -1, axisc) little_endian = sys.byteorder == 'little' @set_module('numpy') def indices(dimensions, dtype=int, sparse=False): dimensions = tuple(dimensions) N = len(dimensions) shape = (1,) * N if sparse: res = tuple() else: res = empty((N,) + dimensions, dtype=dtype) for (i, dim) in enumerate(dimensions): idx = arange(dim, dtype=dtype).reshape(shape[:i] + (dim,) + shape[i + 1:]) if sparse: res = res + (idx,) else: res[i] = idx return res @set_array_function_like_doc @set_module('numpy') def fromfunction(function, shape, *, dtype=float, like=None, **kwargs): if like is not None: return _fromfunction_with_like(like, function, shape, dtype=dtype, **kwargs) args = indices(shape, dtype=dtype) return function(*args, **kwargs) _fromfunction_with_like = array_function_dispatch()(fromfunction) def _frombuffer(buf, dtype, shape, order): return frombuffer(buf, dtype=dtype).reshape(shape, order=order) @set_module('numpy') def isscalar(element): return isinstance(element, generic) or type(element) in ScalarType or isinstance(element, numbers.Number) @set_module('numpy') def binary_repr(num, width=None): def err_if_insufficient(width, binwidth): if width is not None and width < binwidth: raise ValueError(f'Insufficient bit width={width!r} provided for binwidth={binwidth!r}') num = operator.index(num) if num == 0: return '0' * (width or 1) elif num > 0: binary = bin(num)[2:] binwidth = len(binary) outwidth = binwidth if width is None else builtins.max(binwidth, width) err_if_insufficient(width, binwidth) return binary.zfill(outwidth) elif width is None: return '-' + bin(-num)[2:] else: poswidth = len(bin(-num)[2:]) if 2 ** (poswidth - 1) == -num: poswidth -= 1 twocomp = 2 ** (poswidth + 1) + num binary = bin(twocomp)[2:] binwidth = len(binary) outwidth = builtins.max(binwidth, width) err_if_insufficient(width, binwidth) return '1' * (outwidth - binwidth) + binary @set_module('numpy') def base_repr(number, base=2, padding=0): digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if base > len(digits): raise ValueError('Bases greater than 36 not handled in base_repr.') elif base < 2: raise ValueError('Bases less than 2 not handled in base_repr.') num = abs(int(number)) res = [] while num: res.append(digits[num % base]) num //= base if padding: res.append('0' * padding) if number < 0: res.append('-') return ''.join(reversed(res or '0')) def _maketup(descr, val): dt = dtype(descr) fields = dt.fields if fields is None: return val else: res = [_maketup(fields[name][0], val) for name in dt.names] return tuple(res) @set_array_function_like_doc @set_module('numpy') def identity(n, dtype=None, *, like=None): if like is not None: return _identity_with_like(like, n, dtype=dtype) from numpy import eye return eye(n, dtype=dtype, like=like) _identity_with_like = array_function_dispatch()(identity) def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None): return (a, b, rtol, atol) @array_function_dispatch(_allclose_dispatcher) def allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)) return builtins.bool(res) def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None): return (a, b, rtol, atol) @array_function_dispatch(_isclose_dispatcher) def isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): (x, y, atol, rtol) = (a if isinstance(a, (int, float, complex)) else asanyarray(a) for a in (a, b, atol, rtol)) if (dtype := getattr(y, 'dtype', None)) is not None and dtype.kind != 'm': dt = multiarray.result_type(y, 1.0) y = asanyarray(y, dtype=dt) elif isinstance(y, int): y = float(y) with errstate(invalid='ignore'): result = less_equal(abs(x - y), atol + rtol * abs(y)) & isfinite(y) | (x == y) if equal_nan: result |= isnan(x) & isnan(y) return result[()] def _array_equal_dispatcher(a1, a2, equal_nan=None): return (a1, a2) _no_nan_types = {type(dtype(nt.bool)), type(dtype(nt.int8)), type(dtype(nt.int16)), type(dtype(nt.int32)), type(dtype(nt.int64))} def _dtype_cannot_hold_nan(dtype): return type(dtype) in _no_nan_types @array_function_dispatch(_array_equal_dispatcher) def array_equal(a1, a2, equal_nan=False): try: (a1, a2) = (asarray(a1), asarray(a2)) except Exception: return False if a1.shape != a2.shape: return False if not equal_nan: return builtins.bool(asanyarray(a1 == a2).all()) if a1 is a2: return True cannot_have_nan = _dtype_cannot_hold_nan(a1.dtype) and _dtype_cannot_hold_nan(a2.dtype) if cannot_have_nan: return builtins.bool(asarray(a1 == a2).all()) (a1nan, a2nan) = (isnan(a1), isnan(a2)) if not (a1nan == a2nan).all(): return False return builtins.bool((a1[~a1nan] == a2[~a1nan]).all()) def _array_equiv_dispatcher(a1, a2): return (a1, a2) @array_function_dispatch(_array_equiv_dispatcher) def array_equiv(a1, a2): try: (a1, a2) = (asarray(a1), asarray(a2)) except Exception: return False try: multiarray.broadcast(a1, a2) except Exception: return False return builtins.bool(asanyarray(a1 == a2).all()) def _astype_dispatcher(x, dtype, /, *, copy=None, device=None): return (x, dtype) @array_function_dispatch(_astype_dispatcher) def astype(x, dtype, /, *, copy=True, device=None): if not (isinstance(x, np.ndarray) or isscalar(x)): raise TypeError(f'Input should be a NumPy array or scalar. It is a {type(x)} instead.') if device is not None and device != 'cpu': raise ValueError(f'Device not understood. Only "cpu" is allowed, but received: {device}') return x.astype(dtype, copy=copy) inf = PINF nan = NAN False_ = nt.bool(False) True_ = nt.bool(True) def extend_all(module): existing = set(__all__) mall = module.__all__ for a in mall: if a not in existing: __all__.append(a) from .umath import * from .numerictypes import * from . import fromnumeric from .fromnumeric import * from . import arrayprint from .arrayprint import * from . import _asarray from ._asarray import * from . import _ufunc_config from ._ufunc_config import * extend_all(fromnumeric) extend_all(umath) extend_all(numerictypes) extend_all(arrayprint) extend_all(_asarray) extend_all(_ufunc_config) # File: numpy-main/numpy/_core/numerictypes.py """""" import numbers import warnings from . import multiarray as ma from .multiarray import ndarray, dtype, datetime_data, datetime_as_string, busday_offset, busday_count, is_busday, busdaycalendar from .._utils import set_module __all__ = ['ScalarType', 'typecodes', 'issubdtype', 'datetime_data', 'datetime_as_string', 'busday_offset', 'busday_count', 'is_busday', 'busdaycalendar', 'isdtype'] from ._string_helpers import english_lower, english_upper, english_capitalize, LOWER_TABLE, UPPER_TABLE from ._type_aliases import sctypeDict, allTypes, sctypes from ._dtype import _kind_name from builtins import bool, int, float, complex, object, str, bytes generic = allTypes['generic'] genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'int128', 'uint128', 'float16', 'float32', 'float64', 'float80', 'float96', 'float128', 'float256', 'complex32', 'complex64', 'complex128', 'complex160', 'complex192', 'complex256', 'complex512', 'object'] @set_module('numpy') def maximum_sctype(t): warnings.warn('`maximum_sctype` is deprecated. Use an explicit dtype like int64 or float64 instead. (deprecated in NumPy 2.0)', DeprecationWarning, stacklevel=2) g = obj2sctype(t) if g is None: return t t = g base = _kind_name(dtype(t)) if base in sctypes: return sctypes[base][-1] else: return t @set_module('numpy') def issctype(rep): if not isinstance(rep, (type, dtype)): return False try: res = obj2sctype(rep) if res and res != object_: return True else: return False except Exception: return False @set_module('numpy') def obj2sctype(rep, default=None): if isinstance(rep, type) and issubclass(rep, generic): return rep if isinstance(rep, ndarray): return rep.dtype.type try: res = dtype(rep) except Exception: return default else: return res.type @set_module('numpy') def issubclass_(arg1, arg2): try: return issubclass(arg1, arg2) except TypeError: return False @set_module('numpy') def issubsctype(arg1, arg2): return issubclass(obj2sctype(arg1), obj2sctype(arg2)) class _PreprocessDTypeError(Exception): pass def _preprocess_dtype(dtype): if isinstance(dtype, ma.dtype): dtype = dtype.type if isinstance(dtype, ndarray) or dtype not in allTypes.values(): raise _PreprocessDTypeError return dtype @set_module('numpy') def isdtype(dtype, kind): try: dtype = _preprocess_dtype(dtype) except _PreprocessDTypeError: raise TypeError(f'dtype argument must be a NumPy dtype, but it is a {type(dtype)}.') from None input_kinds = kind if isinstance(kind, tuple) else (kind,) processed_kinds = set() for kind in input_kinds: if kind == 'bool': processed_kinds.add(allTypes['bool']) elif kind == 'signed integer': processed_kinds.update(sctypes['int']) elif kind == 'unsigned integer': processed_kinds.update(sctypes['uint']) elif kind == 'integral': processed_kinds.update(sctypes['int'] + sctypes['uint']) elif kind == 'real floating': processed_kinds.update(sctypes['float']) elif kind == 'complex floating': processed_kinds.update(sctypes['complex']) elif kind == 'numeric': processed_kinds.update(sctypes['int'] + sctypes['uint'] + sctypes['float'] + sctypes['complex']) elif isinstance(kind, str): raise ValueError(f'kind argument is a string, but {kind!r} is not a known kind name.') else: try: kind = _preprocess_dtype(kind) except _PreprocessDTypeError: raise TypeError(f'kind argument must be comprised of NumPy dtypes or strings only, but is a {type(kind)}.') from None processed_kinds.add(kind) return dtype in processed_kinds @set_module('numpy') def issubdtype(arg1, arg2): if not issubclass_(arg1, generic): arg1 = dtype(arg1).type if not issubclass_(arg2, generic): arg2 = dtype(arg2).type return issubclass(arg1, arg2) @set_module('numpy') def sctype2char(sctype): sctype = obj2sctype(sctype) if sctype is None: raise ValueError('unrecognized type') if sctype not in sctypeDict.values(): raise KeyError(sctype) return dtype(sctype).char def _scalar_type_key(typ): dt = dtype(typ) return (dt.kind.lower(), dt.itemsize) ScalarType = [int, float, complex, bool, bytes, str, memoryview] ScalarType += sorted(set(sctypeDict.values()), key=_scalar_type_key) ScalarType = tuple(ScalarType) for key in allTypes: globals()[key] = allTypes[key] __all__.append(key) del key typecodes = {'Character': 'c', 'Integer': 'bhilqnp', 'UnsignedInteger': 'BHILQNP', 'Float': 'efdg', 'Complex': 'FDG', 'AllInteger': 'bBhHiIlLqQnNpP', 'AllFloat': 'efdgFDG', 'Datetime': 'Mm', 'All': '?bhilqnpBHILQNPefdgFDGSUVOMm'} typeDict = sctypeDict def _register_types(): numbers.Integral.register(integer) numbers.Complex.register(inexact) numbers.Real.register(floating) numbers.Number.register(number) _register_types() # File: numpy-main/numpy/_core/overrides.py """""" import collections import functools from .._utils import set_module from .._utils._inspect import getargspec from numpy._core._multiarray_umath import add_docstring, _get_implementing_args, _ArrayFunctionDispatcher ARRAY_FUNCTIONS = set() array_function_like_doc = 'like : array_like, optional\n Reference object to allow the creation of arrays which are not\n NumPy arrays. If an array-like passed in as ``like`` supports\n the ``__array_function__`` protocol, the result will be defined\n by it. In this case, it ensures the creation of an array object\n compatible with that passed in via this argument.' def set_array_function_like_doc(public_api): if public_api.__doc__ is not None: public_api.__doc__ = public_api.__doc__.replace('${ARRAY_FUNCTION_LIKE}', array_function_like_doc) return public_api add_docstring(_ArrayFunctionDispatcher, '\n Class to wrap functions with checks for __array_function__ overrides.\n\n All arguments are required, and can only be passed by position.\n\n Parameters\n ----------\n dispatcher : function or None\n The dispatcher function that returns a single sequence-like object\n of all arguments relevant. It must have the same signature (except\n the default values) as the actual implementation.\n If ``None``, this is a ``like=`` dispatcher and the\n ``_ArrayFunctionDispatcher`` must be called with ``like`` as the\n first (additional and positional) argument.\n implementation : function\n Function that implements the operation on NumPy arrays without\n overrides. Arguments passed calling the ``_ArrayFunctionDispatcher``\n will be forwarded to this (and the ``dispatcher``) as if using\n ``*args, **kwargs``.\n\n Attributes\n ----------\n _implementation : function\n The original implementation passed in.\n ') add_docstring(_get_implementing_args, '\n Collect arguments on which to call __array_function__.\n\n Parameters\n ----------\n relevant_args : iterable of array-like\n Iterable of possibly array-like arguments to check for\n __array_function__ methods.\n\n Returns\n -------\n Sequence of arguments with __array_function__ methods, in the order in\n which they should be called.\n ') ArgSpec = collections.namedtuple('ArgSpec', 'args varargs keywords defaults') def verify_matching_signatures(implementation, dispatcher): implementation_spec = ArgSpec(*getargspec(implementation)) dispatcher_spec = ArgSpec(*getargspec(dispatcher)) if implementation_spec.args != dispatcher_spec.args or implementation_spec.varargs != dispatcher_spec.varargs or implementation_spec.keywords != dispatcher_spec.keywords or (bool(implementation_spec.defaults) != bool(dispatcher_spec.defaults)) or (implementation_spec.defaults is not None and len(implementation_spec.defaults) != len(dispatcher_spec.defaults)): raise RuntimeError('implementation and dispatcher for %s have different function signatures' % implementation) if implementation_spec.defaults is not None: if dispatcher_spec.defaults != (None,) * len(dispatcher_spec.defaults): raise RuntimeError('dispatcher functions can only use None for default argument values') def array_function_dispatch(dispatcher=None, module=None, verify=True, docs_from_dispatcher=False): def decorator(implementation): if verify: if dispatcher is not None: verify_matching_signatures(implementation, dispatcher) else: co = implementation.__code__ last_arg = co.co_argcount + co.co_kwonlyargcount - 1 last_arg = co.co_varnames[last_arg] if last_arg != 'like' or co.co_kwonlyargcount == 0: raise RuntimeError(f'__array_function__ expects `like=` to be the last argument and a keyword-only argument. {implementation} does not seem to comply.') if docs_from_dispatcher: add_docstring(implementation, dispatcher.__doc__) public_api = _ArrayFunctionDispatcher(dispatcher, implementation) public_api = functools.wraps(implementation)(public_api) if module is not None: public_api.__module__ = module ARRAY_FUNCTIONS.add(public_api) return public_api return decorator def array_function_from_dispatcher(implementation, module=None, verify=True, docs_from_dispatcher=True): def decorator(dispatcher): return array_function_dispatch(dispatcher, module, verify=verify, docs_from_dispatcher=docs_from_dispatcher)(implementation) return decorator # File: numpy-main/numpy/_core/printoptions.py """""" import sys from contextvars import ContextVar __all__ = ['format_options'] default_format_options_dict = {'edgeitems': 3, 'threshold': 1000, 'floatmode': 'maxprec', 'precision': 8, 'suppress': False, 'linewidth': 75, 'nanstr': 'nan', 'infstr': 'inf', 'sign': '-', 'formatter': None, 'legacy': sys.maxsize, 'override_repr': None} format_options = ContextVar('format_options', default=default_format_options_dict.copy()) # File: numpy-main/numpy/_core/records.py """""" import os import warnings from collections import Counter from contextlib import nullcontext from .._utils import set_module from . import numeric as sb from . import numerictypes as nt from .arrayprint import _get_legacy_print_mode __all__ = ['record', 'recarray', 'format_parser', 'fromarrays', 'fromrecords', 'fromstring', 'fromfile', 'array', 'find_duplicate'] ndarray = sb.ndarray _byteorderconv = {'b': '>', 'l': '<', 'n': '=', 'B': '>', 'L': '<', 'N': '=', 'S': 's', 's': 's', '>': '>', '<': '<', '=': '=', '|': '|', 'I': '|', 'i': '|'} numfmt = nt.sctypeDict @set_module('numpy.rec') def find_duplicate(list): return [item for (item, counts) in Counter(list).items() if counts > 1] @set_module('numpy.rec') class format_parser: def __init__(self, formats, names, titles, aligned=False, byteorder=None): self._parseFormats(formats, aligned) self._setfieldnames(names, titles) self._createdtype(byteorder) def _parseFormats(self, formats, aligned=False): if formats is None: raise ValueError('Need formats argument') if isinstance(formats, list): dtype = sb.dtype([('f{}'.format(i), format_) for (i, format_) in enumerate(formats)], aligned) else: dtype = sb.dtype(formats, aligned) fields = dtype.fields if fields is None: dtype = sb.dtype([('f1', dtype)], aligned) fields = dtype.fields keys = dtype.names self._f_formats = [fields[key][0] for key in keys] self._offsets = [fields[key][1] for key in keys] self._nfields = len(keys) def _setfieldnames(self, names, titles): if names: if type(names) in [list, tuple]: pass elif isinstance(names, str): names = names.split(',') else: raise NameError('illegal input names %s' % repr(names)) self._names = [n.strip() for n in names[:self._nfields]] else: self._names = [] self._names += ['f%d' % i for i in range(len(self._names), self._nfields)] _dup = find_duplicate(self._names) if _dup: raise ValueError('Duplicate field names: %s' % _dup) if titles: self._titles = [n.strip() for n in titles[:self._nfields]] else: self._titles = [] titles = [] if self._nfields > len(titles): self._titles += [None] * (self._nfields - len(titles)) def _createdtype(self, byteorder): dtype = sb.dtype({'names': self._names, 'formats': self._f_formats, 'offsets': self._offsets, 'titles': self._titles}) if byteorder is not None: byteorder = _byteorderconv[byteorder[0]] dtype = dtype.newbyteorder(byteorder) self.dtype = dtype class record(nt.void): __name__ = 'record' __module__ = 'numpy' def __repr__(self): if _get_legacy_print_mode() <= 113: return self.__str__() return super().__repr__() def __str__(self): if _get_legacy_print_mode() <= 113: return str(self.item()) return super().__str__() def __getattribute__(self, attr): if attr in ('setfield', 'getfield', 'dtype'): return nt.void.__getattribute__(self, attr) try: return nt.void.__getattribute__(self, attr) except AttributeError: pass fielddict = nt.void.__getattribute__(self, 'dtype').fields res = fielddict.get(attr, None) if res: obj = self.getfield(*res[:2]) try: dt = obj.dtype except AttributeError: return obj if dt.names is not None: return obj.view((self.__class__, obj.dtype)) return obj else: raise AttributeError("'record' object has no attribute '%s'" % attr) def __setattr__(self, attr, val): if attr in ('setfield', 'getfield', 'dtype'): raise AttributeError("Cannot set '%s' attribute" % attr) fielddict = nt.void.__getattribute__(self, 'dtype').fields res = fielddict.get(attr, None) if res: return self.setfield(val, *res[:2]) elif getattr(self, attr, None): return nt.void.__setattr__(self, attr, val) else: raise AttributeError("'record' object has no attribute '%s'" % attr) def __getitem__(self, indx): obj = nt.void.__getitem__(self, indx) if isinstance(obj, nt.void) and obj.dtype.names is not None: return obj.view((self.__class__, obj.dtype)) else: return obj def pprint(self): names = self.dtype.names maxlen = max((len(name) for name in names)) fmt = '%% %ds: %%s' % maxlen rows = [fmt % (name, getattr(self, name)) for name in names] return '\n'.join(rows) @set_module('numpy.rec') class recarray(ndarray): def __new__(subtype, shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, order='C'): if dtype is not None: descr = sb.dtype(dtype) else: descr = format_parser(formats, names, titles, aligned, byteorder).dtype if buf is None: self = ndarray.__new__(subtype, shape, (record, descr), order=order) else: self = ndarray.__new__(subtype, shape, (record, descr), buffer=buf, offset=offset, strides=strides, order=order) return self def __array_finalize__(self, obj): if self.dtype.type is not record and self.dtype.names is not None: self.dtype = self.dtype def __getattribute__(self, attr): try: return object.__getattribute__(self, attr) except AttributeError: pass fielddict = ndarray.__getattribute__(self, 'dtype').fields try: res = fielddict[attr][:2] except (TypeError, KeyError) as e: raise AttributeError('recarray has no attribute %s' % attr) from e obj = self.getfield(*res) if obj.dtype.names is not None: if issubclass(obj.dtype.type, nt.void): return obj.view(dtype=(self.dtype.type, obj.dtype)) return obj else: return obj.view(ndarray) def __setattr__(self, attr, val): if attr == 'dtype' and issubclass(val.type, nt.void) and (val.names is not None): val = sb.dtype((record, val)) newattr = attr not in self.__dict__ try: ret = object.__setattr__(self, attr, val) except Exception: fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} if attr not in fielddict: raise else: fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} if attr not in fielddict: return ret if newattr: try: object.__delattr__(self, attr) except Exception: return ret try: res = fielddict[attr][:2] except (TypeError, KeyError) as e: raise AttributeError('record array has no attribute %s' % attr) from e return self.setfield(val, *res) def __getitem__(self, indx): obj = super().__getitem__(indx) if isinstance(obj, ndarray): if obj.dtype.names is not None: obj = obj.view(type(self)) if issubclass(obj.dtype.type, nt.void): return obj.view(dtype=(self.dtype.type, obj.dtype)) return obj else: return obj.view(type=ndarray) else: return obj def __repr__(self): repr_dtype = self.dtype if self.dtype.type is record or not issubclass(self.dtype.type, nt.void): if repr_dtype.type is record: repr_dtype = sb.dtype((nt.void, repr_dtype)) prefix = 'rec.array(' fmt = 'rec.array(%s,%sdtype=%s)' else: prefix = 'array(' fmt = 'array(%s,%sdtype=%s).view(numpy.recarray)' if self.size > 0 or self.shape == (0,): lst = sb.array2string(self, separator=', ', prefix=prefix, suffix=',') else: lst = '[], shape=%s' % (repr(self.shape),) lf = '\n' + ' ' * len(prefix) if _get_legacy_print_mode() <= 113: lf = ' ' + lf return fmt % (lst, lf, repr_dtype) def field(self, attr, val=None): if isinstance(attr, int): names = ndarray.__getattribute__(self, 'dtype').names attr = names[attr] fielddict = ndarray.__getattribute__(self, 'dtype').fields res = fielddict[attr][:2] if val is None: obj = self.getfield(*res) if obj.dtype.names is not None: return obj return obj.view(ndarray) else: return self.setfield(val, *res) def _deprecate_shape_0_as_None(shape): if shape == 0: warnings.warn('Passing `shape=0` to have the shape be inferred is deprecated, and in future will be equivalent to `shape=(0,)`. To infer the shape and suppress this warning, pass `shape=None` instead.', FutureWarning, stacklevel=3) return None else: return shape @set_module('numpy.rec') def fromarrays(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None): arrayList = [sb.asarray(x) for x in arrayList] shape = _deprecate_shape_0_as_None(shape) if shape is None: shape = arrayList[0].shape elif isinstance(shape, int): shape = (shape,) if formats is None and dtype is None: formats = [obj.dtype for obj in arrayList] if dtype is not None: descr = sb.dtype(dtype) else: descr = format_parser(formats, names, titles, aligned, byteorder).dtype _names = descr.names if len(descr) != len(arrayList): raise ValueError('mismatch between the number of fields and the number of arrays') d0 = descr[0].shape nn = len(d0) if nn > 0: shape = shape[:-nn] _array = recarray(shape, descr) for (k, obj) in enumerate(arrayList): nn = descr[k].ndim testshape = obj.shape[:obj.ndim - nn] name = _names[k] if testshape != shape: raise ValueError(f'array-shape mismatch in array {k} ("{name}")') _array[name] = obj return _array @set_module('numpy.rec') def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None): if formats is None and dtype is None: obj = sb.array(recList, dtype=object) arrlist = [sb.array(obj[..., i].tolist()) for i in range(obj.shape[-1])] return fromarrays(arrlist, formats=formats, shape=shape, names=names, titles=titles, aligned=aligned, byteorder=byteorder) if dtype is not None: descr = sb.dtype((record, dtype)) else: descr = format_parser(formats, names, titles, aligned, byteorder).dtype try: retval = sb.array(recList, dtype=descr) except (TypeError, ValueError): shape = _deprecate_shape_0_as_None(shape) if shape is None: shape = len(recList) if isinstance(shape, int): shape = (shape,) if len(shape) > 1: raise ValueError('Can only deal with 1-d array.') _array = recarray(shape, descr) for k in range(_array.size): _array[k] = tuple(recList[k]) warnings.warn('fromrecords expected a list of tuples, may have received a list of lists instead. In the future that will raise an error', FutureWarning, stacklevel=2) return _array else: if shape is not None and retval.shape != shape: retval.shape = shape res = retval.view(recarray) return res @set_module('numpy.rec') def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None): if dtype is None and formats is None: raise TypeError("fromstring() needs a 'dtype' or 'formats' argument") if dtype is not None: descr = sb.dtype(dtype) else: descr = format_parser(formats, names, titles, aligned, byteorder).dtype itemsize = descr.itemsize shape = _deprecate_shape_0_as_None(shape) if shape in (None, -1): shape = (len(datastring) - offset) // itemsize _array = recarray(shape, descr, buf=datastring, offset=offset) return _array def get_remaining_size(fd): pos = fd.tell() try: fd.seek(0, 2) return fd.tell() - pos finally: fd.seek(pos, 0) @set_module('numpy.rec') def fromfile(fd, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None): if dtype is None and formats is None: raise TypeError("fromfile() needs a 'dtype' or 'formats' argument") shape = _deprecate_shape_0_as_None(shape) if shape is None: shape = (-1,) elif isinstance(shape, int): shape = (shape,) if hasattr(fd, 'readinto'): ctx = nullcontext(fd) else: ctx = open(os.fspath(fd), 'rb') with ctx as fd: if offset > 0: fd.seek(offset, 1) size = get_remaining_size(fd) if dtype is not None: descr = sb.dtype(dtype) else: descr = format_parser(formats, names, titles, aligned, byteorder).dtype itemsize = descr.itemsize shapeprod = sb.array(shape).prod(dtype=nt.intp) shapesize = shapeprod * itemsize if shapesize < 0: shape = list(shape) shape[shape.index(-1)] = size // -shapesize shape = tuple(shape) shapeprod = sb.array(shape).prod(dtype=nt.intp) nbytes = shapeprod * itemsize if nbytes > size: raise ValueError('Not enough bytes left in file for specified shape and type.') _array = recarray(shape, descr) nbytesread = fd.readinto(_array.data) if nbytesread != nbytes: raise OSError("Didn't read as many bytes as expected") return _array @set_module('numpy.rec') def array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, copy=True): if (isinstance(obj, (type(None), str)) or hasattr(obj, 'readinto')) and formats is None and (dtype is None): raise ValueError('Must define formats (or dtype) if object is None, string, or an open file') kwds = {} if dtype is not None: dtype = sb.dtype(dtype) elif formats is not None: dtype = format_parser(formats, names, titles, aligned, byteorder).dtype else: kwds = {'formats': formats, 'names': names, 'titles': titles, 'aligned': aligned, 'byteorder': byteorder} if obj is None: if shape is None: raise ValueError('Must define a shape if obj is None') return recarray(shape, dtype, buf=obj, offset=offset, strides=strides) elif isinstance(obj, bytes): return fromstring(obj, dtype, shape=shape, offset=offset, **kwds) elif isinstance(obj, (list, tuple)): if isinstance(obj[0], (tuple, list)): return fromrecords(obj, dtype=dtype, shape=shape, **kwds) else: return fromarrays(obj, dtype=dtype, shape=shape, **kwds) elif isinstance(obj, recarray): if dtype is not None and obj.dtype != dtype: new = obj.view(dtype) else: new = obj if copy: new = new.copy() return new elif hasattr(obj, 'readinto'): return fromfile(obj, dtype=dtype, shape=shape, offset=offset) elif isinstance(obj, ndarray): if dtype is not None and obj.dtype != dtype: new = obj.view(dtype) else: new = obj if copy: new = new.copy() return new.view(recarray) else: interface = getattr(obj, '__array_interface__', None) if interface is None or not isinstance(interface, dict): raise ValueError('Unknown input type') obj = sb.array(obj) if dtype is not None and obj.dtype != dtype: obj = obj.view(dtype) return obj.view(recarray) # File: numpy-main/numpy/_core/shape_base.py __all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'block', 'hstack', 'stack', 'unstack', 'vstack'] import functools import itertools import operator from . import numeric as _nx from . import overrides from .multiarray import array, asanyarray, normalize_axis_index from . import fromnumeric as _from_nx array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') def _atleast_1d_dispatcher(*arys): return arys @array_function_dispatch(_atleast_1d_dispatcher) def atleast_1d(*arys): if len(arys) == 1: result = asanyarray(arys[0]) if result.ndim == 0: result = result.reshape(1) return result res = [] for ary in arys: result = asanyarray(ary) if result.ndim == 0: result = result.reshape(1) res.append(result) return tuple(res) def _atleast_2d_dispatcher(*arys): return arys @array_function_dispatch(_atleast_2d_dispatcher) def atleast_2d(*arys): res = [] for ary in arys: ary = asanyarray(ary) if ary.ndim == 0: result = ary.reshape(1, 1) elif ary.ndim == 1: result = ary[_nx.newaxis, :] else: result = ary res.append(result) if len(res) == 1: return res[0] else: return tuple(res) def _atleast_3d_dispatcher(*arys): return arys @array_function_dispatch(_atleast_3d_dispatcher) def atleast_3d(*arys): res = [] for ary in arys: ary = asanyarray(ary) if ary.ndim == 0: result = ary.reshape(1, 1, 1) elif ary.ndim == 1: result = ary[_nx.newaxis, :, _nx.newaxis] elif ary.ndim == 2: result = ary[:, :, _nx.newaxis] else: result = ary res.append(result) if len(res) == 1: return res[0] else: return tuple(res) def _arrays_for_stack_dispatcher(arrays): if not hasattr(arrays, '__getitem__'): raise TypeError('arrays to stack must be passed as a "sequence" type such as list or tuple.') return tuple(arrays) def _vhstack_dispatcher(tup, *, dtype=None, casting=None): return _arrays_for_stack_dispatcher(tup) @array_function_dispatch(_vhstack_dispatcher) def vstack(tup, *, dtype=None, casting='same_kind'): arrs = atleast_2d(*tup) if not isinstance(arrs, tuple): arrs = (arrs,) return _nx.concatenate(arrs, 0, dtype=dtype, casting=casting) @array_function_dispatch(_vhstack_dispatcher) def hstack(tup, *, dtype=None, casting='same_kind'): arrs = atleast_1d(*tup) if not isinstance(arrs, tuple): arrs = (arrs,) if arrs and arrs[0].ndim == 1: return _nx.concatenate(arrs, 0, dtype=dtype, casting=casting) else: return _nx.concatenate(arrs, 1, dtype=dtype, casting=casting) def _stack_dispatcher(arrays, axis=None, out=None, *, dtype=None, casting=None): arrays = _arrays_for_stack_dispatcher(arrays) if out is not None: arrays = list(arrays) arrays.append(out) return arrays @array_function_dispatch(_stack_dispatcher) def stack(arrays, axis=0, out=None, *, dtype=None, casting='same_kind'): arrays = [asanyarray(arr) for arr in arrays] if not arrays: raise ValueError('need at least one array to stack') shapes = {arr.shape for arr in arrays} if len(shapes) != 1: raise ValueError('all input arrays must have the same shape') result_ndim = arrays[0].ndim + 1 axis = normalize_axis_index(axis, result_ndim) sl = (slice(None),) * axis + (_nx.newaxis,) expanded_arrays = [arr[sl] for arr in arrays] return _nx.concatenate(expanded_arrays, axis=axis, out=out, dtype=dtype, casting=casting) def _unstack_dispatcher(x, /, *, axis=None): return (x,) @array_function_dispatch(_unstack_dispatcher) def unstack(x, /, *, axis=0): if x.ndim == 0: raise ValueError('Input array must be at least 1-d.') return tuple(_nx.moveaxis(x, axis, 0)) _size = getattr(_from_nx.size, '__wrapped__', _from_nx.size) _ndim = getattr(_from_nx.ndim, '__wrapped__', _from_nx.ndim) _concatenate = getattr(_from_nx.concatenate, '__wrapped__', _from_nx.concatenate) def _block_format_index(index): idx_str = ''.join(('[{}]'.format(i) for i in index if i is not None)) return 'arrays' + idx_str def _block_check_depths_match(arrays, parent_index=[]): if type(arrays) is tuple: raise TypeError('{} is a tuple. Only lists can be used to arrange blocks, and np.block does not allow implicit conversion from tuple to ndarray.'.format(_block_format_index(parent_index))) elif type(arrays) is list and len(arrays) > 0: idxs_ndims = (_block_check_depths_match(arr, parent_index + [i]) for (i, arr) in enumerate(arrays)) (first_index, max_arr_ndim, final_size) = next(idxs_ndims) for (index, ndim, size) in idxs_ndims: final_size += size if ndim > max_arr_ndim: max_arr_ndim = ndim if len(index) != len(first_index): raise ValueError('List depths are mismatched. First element was at depth {}, but there is an element at depth {} ({})'.format(len(first_index), len(index), _block_format_index(index))) if index[-1] is None: first_index = index return (first_index, max_arr_ndim, final_size) elif type(arrays) is list and len(arrays) == 0: return (parent_index + [None], 0, 0) else: size = _size(arrays) return (parent_index, _ndim(arrays), size) def _atleast_nd(a, ndim): return array(a, ndmin=ndim, copy=None, subok=True) def _accumulate(values): return list(itertools.accumulate(values)) def _concatenate_shapes(shapes, axis): shape_at_axis = [shape[axis] for shape in shapes] first_shape = shapes[0] first_shape_pre = first_shape[:axis] first_shape_post = first_shape[axis + 1:] if any((shape[:axis] != first_shape_pre or shape[axis + 1:] != first_shape_post for shape in shapes)): raise ValueError('Mismatched array shapes in block along axis {}.'.format(axis)) shape = first_shape_pre + (sum(shape_at_axis),) + first_shape[axis + 1:] offsets_at_axis = _accumulate(shape_at_axis) slice_prefixes = [(slice(start, end),) for (start, end) in zip([0] + offsets_at_axis, offsets_at_axis)] return (shape, slice_prefixes) def _block_info_recursion(arrays, max_depth, result_ndim, depth=0): if depth < max_depth: (shapes, slices, arrays) = zip(*[_block_info_recursion(arr, max_depth, result_ndim, depth + 1) for arr in arrays]) axis = result_ndim - max_depth + depth (shape, slice_prefixes) = _concatenate_shapes(shapes, axis) slices = [slice_prefix + the_slice for (slice_prefix, inner_slices) in zip(slice_prefixes, slices) for the_slice in inner_slices] arrays = functools.reduce(operator.add, arrays) return (shape, slices, arrays) else: arr = _atleast_nd(arrays, result_ndim) return (arr.shape, [()], [arr]) def _block(arrays, max_depth, result_ndim, depth=0): if depth < max_depth: arrs = [_block(arr, max_depth, result_ndim, depth + 1) for arr in arrays] return _concatenate(arrs, axis=-(max_depth - depth)) else: return _atleast_nd(arrays, result_ndim) def _block_dispatcher(arrays): if type(arrays) is list: for subarrays in arrays: yield from _block_dispatcher(subarrays) else: yield arrays @array_function_dispatch(_block_dispatcher) def block(arrays): (arrays, list_ndim, result_ndim, final_size) = _block_setup(arrays) if list_ndim * final_size > 2 * 512 * 512: return _block_slicing(arrays, list_ndim, result_ndim) else: return _block_concatenate(arrays, list_ndim, result_ndim) def _block_setup(arrays): (bottom_index, arr_ndim, final_size) = _block_check_depths_match(arrays) list_ndim = len(bottom_index) if bottom_index and bottom_index[-1] is None: raise ValueError('List at {} cannot be empty'.format(_block_format_index(bottom_index))) result_ndim = max(arr_ndim, list_ndim) return (arrays, list_ndim, result_ndim, final_size) def _block_slicing(arrays, list_ndim, result_ndim): (shape, slices, arrays) = _block_info_recursion(arrays, list_ndim, result_ndim) dtype = _nx.result_type(*[arr.dtype for arr in arrays]) F_order = all((arr.flags['F_CONTIGUOUS'] for arr in arrays)) C_order = all((arr.flags['C_CONTIGUOUS'] for arr in arrays)) order = 'F' if F_order and (not C_order) else 'C' result = _nx.empty(shape=shape, dtype=dtype, order=order) for (the_slice, arr) in zip(slices, arrays): result[(Ellipsis,) + the_slice] = arr return result def _block_concatenate(arrays, list_ndim, result_ndim): result = _block(arrays, list_ndim, result_ndim) if list_ndim == 0: result = result.copy() return result # File: numpy-main/numpy/_core/strings.py """""" import sys import numpy as np from numpy import equal, not_equal, less, less_equal, greater, greater_equal, add, multiply as _multiply_ufunc from numpy._core.multiarray import _vec_string from numpy._core.umath import isalpha, isdigit, isspace, isalnum, islower, isupper, istitle, isdecimal, isnumeric, str_len, find as _find_ufunc, rfind as _rfind_ufunc, index as _index_ufunc, rindex as _rindex_ufunc, count as _count_ufunc, startswith as _startswith_ufunc, endswith as _endswith_ufunc, _lstrip_whitespace, _lstrip_chars, _rstrip_whitespace, _rstrip_chars, _strip_whitespace, _strip_chars, _replace, _expandtabs_length, _expandtabs, _center, _ljust, _rjust, _zfill, _partition, _partition_index, _rpartition, _rpartition_index __all__ = ['equal', 'not_equal', 'less', 'less_equal', 'greater', 'greater_equal', 'add', 'multiply', 'isalpha', 'isdigit', 'isspace', 'isalnum', 'islower', 'isupper', 'istitle', 'isdecimal', 'isnumeric', 'str_len', 'find', 'rfind', 'index', 'rindex', 'count', 'startswith', 'endswith', 'lstrip', 'rstrip', 'strip', 'replace', 'expandtabs', 'center', 'ljust', 'rjust', 'zfill', 'partition', 'rpartition', 'upper', 'lower', 'swapcase', 'capitalize', 'title', 'mod', 'decode', 'encode', 'translate'] MAX = np.iinfo(np.int64).max def _get_num_chars(a): if issubclass(a.dtype.type, np.str_): return a.itemsize // 4 return a.itemsize def _to_bytes_or_str_array(result, output_dtype_like): output_dtype_like = np.asarray(output_dtype_like) if result.size == 0: return result.astype(output_dtype_like.dtype) ret = np.asarray(result.tolist()) if isinstance(output_dtype_like.dtype, np.dtypes.StringDType): return ret.astype(type(output_dtype_like.dtype)) return ret.astype(type(output_dtype_like.dtype)(_get_num_chars(ret))) def _clean_args(*args): newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs def multiply(a, i): a = np.asanyarray(a) i = np.asanyarray(i) if not np.issubdtype(i.dtype, np.integer): raise TypeError(f"unsupported type {i.dtype} for operand 'i'") i = np.maximum(i, 0) if a.dtype.char == 'T': return a * i a_len = str_len(a) if np.any(a_len > sys.maxsize / np.maximum(i, 1)): raise MemoryError('repeated string is too long') buffersizes = a_len * i out_dtype = f'{a.dtype.char}{buffersizes.max()}' out = np.empty_like(a, shape=buffersizes.shape, dtype=out_dtype) return _multiply_ufunc(a, i, out=out) def mod(a, values): return _to_bytes_or_str_array(_vec_string(a, np.object_, '__mod__', (values,)), a) def find(a, sub, start=0, end=None): end = end if end is not None else MAX return _find_ufunc(a, sub, start, end) def rfind(a, sub, start=0, end=None): end = end if end is not None else MAX return _rfind_ufunc(a, sub, start, end) def index(a, sub, start=0, end=None): end = end if end is not None else MAX return _index_ufunc(a, sub, start, end) def rindex(a, sub, start=0, end=None): end = end if end is not None else MAX return _rindex_ufunc(a, sub, start, end) def count(a, sub, start=0, end=None): end = end if end is not None else MAX return _count_ufunc(a, sub, start, end) def startswith(a, prefix, start=0, end=None): end = end if end is not None else MAX return _startswith_ufunc(a, prefix, start, end) def endswith(a, suffix, start=0, end=None): end = end if end is not None else MAX return _endswith_ufunc(a, suffix, start, end) def decode(a, encoding=None, errors=None): return _to_bytes_or_str_array(_vec_string(a, np.object_, 'decode', _clean_args(encoding, errors)), np.str_('')) def encode(a, encoding=None, errors=None): return _to_bytes_or_str_array(_vec_string(a, np.object_, 'encode', _clean_args(encoding, errors)), np.bytes_(b'')) def expandtabs(a, tabsize=8): a = np.asanyarray(a) tabsize = np.asanyarray(tabsize) if a.dtype.char == 'T': return _expandtabs(a, tabsize) buffersizes = _expandtabs_length(a, tabsize) out_dtype = f'{a.dtype.char}{buffersizes.max()}' out = np.empty_like(a, shape=buffersizes.shape, dtype=out_dtype) return _expandtabs(a, tabsize, out=out) def center(a, width, fillchar=' '): a = np.asanyarray(a) fillchar = np.asanyarray(fillchar, dtype=a.dtype) if np.any(str_len(fillchar) != 1): raise TypeError('The fill character must be exactly one character long') if a.dtype.char == 'T': return _center(a, width, fillchar) width = np.maximum(str_len(a), width) out_dtype = f'{a.dtype.char}{width.max()}' shape = np.broadcast_shapes(a.shape, width.shape, fillchar.shape) out = np.empty_like(a, shape=shape, dtype=out_dtype) return _center(a, width, fillchar, out=out) def ljust(a, width, fillchar=' '): a = np.asanyarray(a) fillchar = np.asanyarray(fillchar, dtype=a.dtype) if np.any(str_len(fillchar) != 1): raise TypeError('The fill character must be exactly one character long') if a.dtype.char == 'T': return _ljust(a, width, fillchar) width = np.maximum(str_len(a), width) shape = np.broadcast_shapes(a.shape, width.shape, fillchar.shape) out_dtype = f'{a.dtype.char}{width.max()}' out = np.empty_like(a, shape=shape, dtype=out_dtype) return _ljust(a, width, fillchar, out=out) def rjust(a, width, fillchar=' '): a = np.asanyarray(a) fillchar = np.asanyarray(fillchar, dtype=a.dtype) if np.any(str_len(fillchar) != 1): raise TypeError('The fill character must be exactly one character long') if a.dtype.char == 'T': return _rjust(a, width, fillchar) width = np.maximum(str_len(a), width) shape = np.broadcast_shapes(a.shape, width.shape, fillchar.shape) out_dtype = f'{a.dtype.char}{width.max()}' out = np.empty_like(a, shape=shape, dtype=out_dtype) return _rjust(a, width, fillchar, out=out) def zfill(a, width): a = np.asanyarray(a) if a.dtype.char == 'T': return _zfill(a, width) width = np.maximum(str_len(a), width) shape = np.broadcast_shapes(a.shape, width.shape) out_dtype = f'{a.dtype.char}{width.max()}' out = np.empty_like(a, shape=shape, dtype=out_dtype) return _zfill(a, width, out=out) def lstrip(a, chars=None): if chars is None: return _lstrip_whitespace(a) return _lstrip_chars(a, chars) def rstrip(a, chars=None): if chars is None: return _rstrip_whitespace(a) return _rstrip_chars(a, chars) def strip(a, chars=None): if chars is None: return _strip_whitespace(a) return _strip_chars(a, chars) def upper(a): a_arr = np.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'upper') def lower(a): a_arr = np.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'lower') def swapcase(a): a_arr = np.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'swapcase') def capitalize(a): a_arr = np.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'capitalize') def title(a): a_arr = np.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'title') def replace(a, old, new, count=-1): arr = np.asanyarray(a) a_dt = arr.dtype old = np.asanyarray(old, dtype=getattr(old, 'dtype', a_dt)) new = np.asanyarray(new, dtype=getattr(new, 'dtype', a_dt)) count = np.asanyarray(count) if arr.dtype.char == 'T': return _replace(arr, old, new, count) max_int64 = np.iinfo(np.int64).max counts = _count_ufunc(arr, old, 0, max_int64) counts = np.where(count < 0, counts, np.minimum(counts, count)) buffersizes = str_len(arr) + counts * (str_len(new) - str_len(old)) out_dtype = f'{arr.dtype.char}{buffersizes.max()}' out = np.empty_like(arr, shape=buffersizes.shape, dtype=out_dtype) return _replace(arr, old, new, counts, out=out) def _join(sep, seq): return _to_bytes_or_str_array(_vec_string(sep, np.object_, 'join', (seq,)), seq) def _split(a, sep=None, maxsplit=None): return _vec_string(a, np.object_, 'split', [sep] + _clean_args(maxsplit)) def _rsplit(a, sep=None, maxsplit=None): return _vec_string(a, np.object_, 'rsplit', [sep] + _clean_args(maxsplit)) def _splitlines(a, keepends=None): return _vec_string(a, np.object_, 'splitlines', _clean_args(keepends)) def partition(a, sep): a = np.asanyarray(a) sep = np.array(sep, dtype=a.dtype, copy=True, subok=True) if a.dtype.char == 'T': return _partition(a, sep) pos = _find_ufunc(a, sep, 0, MAX) a_len = str_len(a) sep_len = str_len(sep) not_found = pos < 0 buffersizes1 = np.where(not_found, a_len, pos) buffersizes3 = np.where(not_found, 0, a_len - pos - sep_len) out_dtype = ','.join([f'{a.dtype.char}{n}' for n in (buffersizes1.max(), 1 if np.all(not_found) else sep_len.max(), buffersizes3.max())]) shape = np.broadcast_shapes(a.shape, sep.shape) out = np.empty_like(a, shape=shape, dtype=out_dtype) return _partition_index(a, sep, pos, out=(out['f0'], out['f1'], out['f2'])) def rpartition(a, sep): a = np.asanyarray(a) sep = np.array(sep, dtype=a.dtype, copy=True, subok=True) if a.dtype.char == 'T': return _rpartition(a, sep) pos = _rfind_ufunc(a, sep, 0, MAX) a_len = str_len(a) sep_len = str_len(sep) not_found = pos < 0 buffersizes1 = np.where(not_found, 0, pos) buffersizes3 = np.where(not_found, a_len, a_len - pos - sep_len) out_dtype = ','.join([f'{a.dtype.char}{n}' for n in (buffersizes1.max(), 1 if np.all(not_found) else sep_len.max(), buffersizes3.max())]) shape = np.broadcast_shapes(a.shape, sep.shape) out = np.empty_like(a, shape=shape, dtype=out_dtype) return _rpartition_index(a, sep, pos, out=(out['f0'], out['f1'], out['f2'])) def translate(a, table, deletechars=None): a_arr = np.asarray(a) if issubclass(a_arr.dtype.type, np.str_): return _vec_string(a_arr, a_arr.dtype, 'translate', (table,)) else: return _vec_string(a_arr, a_arr.dtype, 'translate', [table] + _clean_args(deletechars)) # File: numpy-main/numpy/_core/umath.py """""" import numpy from . import _multiarray_umath from ._multiarray_umath import * from ._multiarray_umath import _UFUNC_API, _add_newdoc_ufunc, _ones_like, _get_extobj_dict, _make_extobj, _extobj_contextvar from ._multiarray_umath import _replace, _strip_whitespace, _lstrip_whitespace, _rstrip_whitespace, _strip_chars, _lstrip_chars, _rstrip_chars, _expandtabs_length, _expandtabs, _center, _ljust, _rjust, _zfill, _partition, _partition_index, _rpartition, _rpartition_index __all__ = ['absolute', 'add', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_or', 'bitwise_xor', 'cbrt', 'ceil', 'conj', 'conjugate', 'copysign', 'cos', 'cosh', 'bitwise_count', 'deg2rad', 'degrees', 'divide', 'divmod', 'e', 'equal', 'euler_gamma', 'exp', 'exp2', 'expm1', 'fabs', 'floor', 'floor_divide', 'float_power', 'fmax', 'fmin', 'fmod', 'frexp', 'frompyfunc', 'gcd', 'greater', 'greater_equal', 'heaviside', 'hypot', 'invert', 'isfinite', 'isinf', 'isnan', 'isnat', 'lcm', 'ldexp', 'left_shift', 'less', 'less_equal', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'maximum', 'minimum', 'mod', 'modf', 'multiply', 'negative', 'nextafter', 'not_equal', 'pi', 'positive', 'power', 'rad2deg', 'radians', 'reciprocal', 'remainder', 'right_shift', 'rint', 'sign', 'signbit', 'sin', 'sinh', 'spacing', 'sqrt', 'square', 'subtract', 'tan', 'tanh', 'true_divide', 'trunc'] # File: numpy-main/numpy/_distributor_init.py """""" try: from . import _distributor_init_local except ImportError: pass # File: numpy-main/numpy/_expired_attrs_2_0.py """""" __expired_attributes__ = {'geterrobj': 'Use the np.errstate context manager instead.', 'seterrobj': 'Use the np.errstate context manager instead.', 'cast': 'Use `np.asarray(arr, dtype=dtype)` instead.', 'source': 'Use `inspect.getsource` instead.', 'lookfor': "Search NumPy's documentation directly.", 'who': 'Use an IDE variable explorer or `locals()` instead.', 'fastCopyAndTranspose': 'Use `arr.T.copy()` instead.', 'set_numeric_ops': 'For the general case, use `PyUFunc_ReplaceLoopBySignature`. For ndarray subclasses, define the ``__array_ufunc__`` method and override the relevant ufunc.', 'NINF': 'Use `-np.inf` instead.', 'PINF': 'Use `np.inf` instead.', 'NZERO': 'Use `-0.0` instead.', 'PZERO': 'Use `0.0` instead.', 'add_newdoc': "It's still available as `np.lib.add_newdoc`.", 'add_docstring': "It's still available as `np.lib.add_docstring`.", 'add_newdoc_ufunc': "It's an internal function and doesn't have a replacement.", 'compat': "There's no replacement, as Python 2 is no longer supported.", 'safe_eval': 'Use `ast.literal_eval` instead.', 'float_': 'Use `np.float64` instead.', 'complex_': 'Use `np.complex128` instead.', 'longfloat': 'Use `np.longdouble` instead.', 'singlecomplex': 'Use `np.complex64` instead.', 'cfloat': 'Use `np.complex128` instead.', 'longcomplex': 'Use `np.clongdouble` instead.', 'clongfloat': 'Use `np.clongdouble` instead.', 'string_': 'Use `np.bytes_` instead.', 'unicode_': 'Use `np.str_` instead.', 'Inf': 'Use `np.inf` instead.', 'Infinity': 'Use `np.inf` instead.', 'NaN': 'Use `np.nan` instead.', 'infty': 'Use `np.inf` instead.', 'issctype': 'Use `issubclass(rep, np.generic)` instead.', 'maximum_sctype': 'Use a specific dtype instead. You should avoid relying on any implicit mechanism and select the largest dtype of a kind explicitly in the code.', 'obj2sctype': 'Use `np.dtype(obj).type` instead.', 'sctype2char': 'Use `np.dtype(obj).char` instead.', 'sctypes': 'Access dtypes explicitly instead.', 'issubsctype': 'Use `np.issubdtype` instead.', 'set_string_function': 'Use `np.set_printoptions` instead with a formatter for custom printing of NumPy objects.', 'asfarray': 'Use `np.asarray` with a proper dtype instead.', 'issubclass_': 'Use `issubclass` builtin instead.', 'tracemalloc_domain': "It's now available from `np.lib`.", 'mat': 'Use `np.asmatrix` instead.', 'recfromcsv': 'Use `np.genfromtxt` with comma delimiter instead.', 'recfromtxt': 'Use `np.genfromtxt` instead.', 'deprecate': 'Emit `DeprecationWarning` with `warnings.warn` directly, or use `typing.deprecated`.', 'deprecate_with_doc': 'Emit `DeprecationWarning` with `warnings.warn` directly, or use `typing.deprecated`.', 'disp': 'Use your own printing function instead.', 'find_common_type': 'Use `numpy.promote_types` or `numpy.result_type` instead. To achieve semantics for the `scalar_types` argument, use `numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.', 'round_': 'Use `np.round` instead.', 'get_array_wrap': '', 'DataSource': "It's still available as `np.lib.npyio.DataSource`.", 'nbytes': 'Use `np.dtype().itemsize` instead.', 'byte_bounds': "Now it's available under `np.lib.array_utils.byte_bounds`", 'compare_chararrays': "It's still available as `np.char.compare_chararrays`.", 'format_parser': "It's still available as `np.rec.format_parser`.", 'alltrue': 'Use `np.all` instead.', 'sometrue': 'Use `np.any` instead.'} # File: numpy-main/numpy/_globals.py """""" import enum from ._utils import set_module as _set_module __all__ = ['_NoValue', '_CopyMode'] if '_is_loaded' in globals(): raise RuntimeError('Reloading numpy._globals is not allowed') _is_loaded = True class _NoValueType: __instance = None def __new__(cls): if not cls.__instance: cls.__instance = super().__new__(cls) return cls.__instance def __repr__(self): return '' _NoValue = _NoValueType() @_set_module('numpy') class _CopyMode(enum.Enum): ALWAYS = True NEVER = False IF_NEEDED = 2 def __bool__(self): if self == _CopyMode.ALWAYS: return True if self == _CopyMode.NEVER: return False raise ValueError(f'{self} is neither True nor False.') # File: numpy-main/numpy/_pyinstaller/hook-numpy.py """""" from PyInstaller.compat import is_conda, is_pure_conda from PyInstaller.utils.hooks import collect_dynamic_libs, is_module_satisfies binaries = collect_dynamic_libs('numpy', '.') if is_pure_conda: from PyInstaller.utils.hooks import conda_support datas = conda_support.collect_dynamic_libs('numpy', dependencies=True) hiddenimports = ['numpy._core._dtype_ctypes', 'numpy._core._multiarray_tests'] excludedimports = ['scipy', 'pytest', 'f2py', 'setuptools', 'distutils', 'numpy.distutils'] # File: numpy-main/numpy/_typing/__init__.py """""" from __future__ import annotations from ._nested_sequence import _NestedSequence as _NestedSequence from ._nbit_base import NBitBase as NBitBase, _8Bit as _8Bit, _16Bit as _16Bit, _32Bit as _32Bit, _64Bit as _64Bit, _80Bit as _80Bit, _96Bit as _96Bit, _128Bit as _128Bit, _256Bit as _256Bit from ._nbit import _NBitByte as _NBitByte, _NBitShort as _NBitShort, _NBitIntC as _NBitIntC, _NBitIntP as _NBitIntP, _NBitInt as _NBitInt, _NBitLong as _NBitLong, _NBitLongLong as _NBitLongLong, _NBitHalf as _NBitHalf, _NBitSingle as _NBitSingle, _NBitDouble as _NBitDouble, _NBitLongDouble as _NBitLongDouble from ._char_codes import _BoolCodes as _BoolCodes, _UInt8Codes as _UInt8Codes, _UInt16Codes as _UInt16Codes, _UInt32Codes as _UInt32Codes, _UInt64Codes as _UInt64Codes, _Int8Codes as _Int8Codes, _Int16Codes as _Int16Codes, _Int32Codes as _Int32Codes, _Int64Codes as _Int64Codes, _Float16Codes as _Float16Codes, _Float32Codes as _Float32Codes, _Float64Codes as _Float64Codes, _Complex64Codes as _Complex64Codes, _Complex128Codes as _Complex128Codes, _ByteCodes as _ByteCodes, _ShortCodes as _ShortCodes, _IntCCodes as _IntCCodes, _IntPCodes as _IntPCodes, _IntCodes as _IntCodes, _LongCodes as _LongCodes, _LongLongCodes as _LongLongCodes, _UByteCodes as _UByteCodes, _UShortCodes as _UShortCodes, _UIntCCodes as _UIntCCodes, _UIntPCodes as _UIntPCodes, _UIntCodes as _UIntCodes, _ULongCodes as _ULongCodes, _ULongLongCodes as _ULongLongCodes, _HalfCodes as _HalfCodes, _SingleCodes as _SingleCodes, _DoubleCodes as _DoubleCodes, _LongDoubleCodes as _LongDoubleCodes, _CSingleCodes as _CSingleCodes, _CDoubleCodes as _CDoubleCodes, _CLongDoubleCodes as _CLongDoubleCodes, _DT64Codes as _DT64Codes, _TD64Codes as _TD64Codes, _StrCodes as _StrCodes, _BytesCodes as _BytesCodes, _VoidCodes as _VoidCodes, _ObjectCodes as _ObjectCodes, _StringCodes as _StringCodes, _UnsignedIntegerCodes as _UnsignedIntegerCodes, _SignedIntegerCodes as _SignedIntegerCodes, _IntegerCodes as _IntegerCodes, _FloatingCodes as _FloatingCodes, _ComplexFloatingCodes as _ComplexFloatingCodes, _InexactCodes as _InexactCodes, _NumberCodes as _NumberCodes, _CharacterCodes as _CharacterCodes, _FlexibleCodes as _FlexibleCodes, _GenericCodes as _GenericCodes from ._scalars import _CharLike_co as _CharLike_co, _BoolLike_co as _BoolLike_co, _UIntLike_co as _UIntLike_co, _IntLike_co as _IntLike_co, _FloatLike_co as _FloatLike_co, _ComplexLike_co as _ComplexLike_co, _TD64Like_co as _TD64Like_co, _NumberLike_co as _NumberLike_co, _ScalarLike_co as _ScalarLike_co, _VoidLike_co as _VoidLike_co from ._shape import _Shape as _Shape, _ShapeLike as _ShapeLike from ._dtype_like import DTypeLike as DTypeLike, _DTypeLike as _DTypeLike, _SupportsDType as _SupportsDType, _VoidDTypeLike as _VoidDTypeLike, _DTypeLikeBool as _DTypeLikeBool, _DTypeLikeUInt as _DTypeLikeUInt, _DTypeLikeInt as _DTypeLikeInt, _DTypeLikeFloat as _DTypeLikeFloat, _DTypeLikeComplex as _DTypeLikeComplex, _DTypeLikeTD64 as _DTypeLikeTD64, _DTypeLikeDT64 as _DTypeLikeDT64, _DTypeLikeObject as _DTypeLikeObject, _DTypeLikeVoid as _DTypeLikeVoid, _DTypeLikeStr as _DTypeLikeStr, _DTypeLikeBytes as _DTypeLikeBytes, _DTypeLikeComplex_co as _DTypeLikeComplex_co from ._array_like import NDArray as NDArray, ArrayLike as ArrayLike, _ArrayLike as _ArrayLike, _FiniteNestedSequence as _FiniteNestedSequence, _SupportsArray as _SupportsArray, _SupportsArrayFunc as _SupportsArrayFunc, _ArrayLikeInt as _ArrayLikeInt, _ArrayLikeBool_co as _ArrayLikeBool_co, _ArrayLikeUInt_co as _ArrayLikeUInt_co, _ArrayLikeInt_co as _ArrayLikeInt_co, _ArrayLikeFloat_co as _ArrayLikeFloat_co, _ArrayLikeComplex_co as _ArrayLikeComplex_co, _ArrayLikeNumber_co as _ArrayLikeNumber_co, _ArrayLikeTD64_co as _ArrayLikeTD64_co, _ArrayLikeDT64_co as _ArrayLikeDT64_co, _ArrayLikeObject_co as _ArrayLikeObject_co, _ArrayLikeVoid_co as _ArrayLikeVoid_co, _ArrayLikeStr_co as _ArrayLikeStr_co, _ArrayLikeBytes_co as _ArrayLikeBytes_co, _ArrayLikeUnknown as _ArrayLikeUnknown, _UnknownType as _UnknownType from ._ufunc import _UFunc_Nin1_Nout1 as _UFunc_Nin1_Nout1, _UFunc_Nin2_Nout1 as _UFunc_Nin2_Nout1, _UFunc_Nin1_Nout2 as _UFunc_Nin1_Nout2, _UFunc_Nin2_Nout2 as _UFunc_Nin2_Nout2, _GUFunc_Nin2_Nout1 as _GUFunc_Nin2_Nout1 # File: numpy-main/numpy/_typing/_add_docstring.py """""" import re import textwrap from ._array_like import NDArray _docstrings_list = [] def add_newdoc(name: str, value: str, doc: str) -> None: _docstrings_list.append((name, value, doc)) def _parse_docstrings() -> str: type_list_ret = [] for (name, value, doc) in _docstrings_list: s = textwrap.dedent(doc).replace('\n', '\n ') lines = s.split('\n') new_lines = [] indent = '' for line in lines: m = re.match('^(\\s+)[-=]+\\s*$', line) if m and new_lines: prev = textwrap.dedent(new_lines.pop()) if prev == 'Examples': indent = '' new_lines.append(f'{m.group(1)}.. rubric:: {prev}') else: indent = 4 * ' ' new_lines.append(f'{m.group(1)}.. admonition:: {prev}') new_lines.append('') else: new_lines.append(f'{indent}{line}') s = '\n'.join(new_lines) s_block = f'.. data:: {name}\n :value: {value}\n {s}' type_list_ret.append(s_block) return '\n'.join(type_list_ret) add_newdoc('ArrayLike', 'typing.Union[...]', '\n A `~typing.Union` representing objects that can be coerced\n into an `~numpy.ndarray`.\n\n Among others this includes the likes of:\n\n * Scalars.\n * (Nested) sequences.\n * Objects implementing the `~class.__array__` protocol.\n\n .. versionadded:: 1.20\n\n See Also\n --------\n :term:`array_like`:\n Any scalar or sequence that can be interpreted as an ndarray.\n\n Examples\n --------\n .. code-block:: python\n\n >>> import numpy as np\n >>> import numpy.typing as npt\n\n >>> def as_array(a: npt.ArrayLike) -> np.ndarray:\n ... return np.array(a)\n\n ') add_newdoc('DTypeLike', 'typing.Union[...]', '\n A `~typing.Union` representing objects that can be coerced\n into a `~numpy.dtype`.\n\n Among others this includes the likes of:\n\n * :class:`type` objects.\n * Character codes or the names of :class:`type` objects.\n * Objects with the ``.dtype`` attribute.\n\n .. versionadded:: 1.20\n\n See Also\n --------\n :ref:`Specifying and constructing data types `\n A comprehensive overview of all objects that can be coerced\n into data types.\n\n Examples\n --------\n .. code-block:: python\n\n >>> import numpy as np\n >>> import numpy.typing as npt\n\n >>> def as_dtype(d: npt.DTypeLike) -> np.dtype:\n ... return np.dtype(d)\n\n ') add_newdoc('NDArray', repr(NDArray), '\n A `np.ndarray[tuple[int, ...], np.dtype[+ScalarType]] `\n type alias :term:`generic ` w.r.t. its\n `dtype.type `.\n\n Can be used during runtime for typing arrays with a given dtype\n and unspecified shape.\n\n .. versionadded:: 1.21\n\n Examples\n --------\n .. code-block:: python\n\n >>> import numpy as np\n >>> import numpy.typing as npt\n\n >>> print(npt.NDArray)\n numpy.ndarray[tuple[int, ...], numpy.dtype[+_ScalarType_co]]\n\n >>> print(npt.NDArray[np.float64])\n numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.float64]]\n\n >>> NDArrayInt = npt.NDArray[np.int_]\n >>> a: NDArrayInt = np.arange(10)\n\n >>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:\n ... return np.array(a)\n\n ') _docstrings = _parse_docstrings() # File: numpy-main/numpy/_typing/_array_like.py from __future__ import annotations import sys from collections.abc import Collection, Callable, Sequence from typing import Any, Protocol, TypeAlias, TypeVar, runtime_checkable import numpy as np from numpy import ndarray, dtype, generic, unsignedinteger, integer, floating, complexfloating, number, timedelta64, datetime64, object_, void, str_, bytes_ from ._nested_sequence import _NestedSequence from ._shape import _Shape _T = TypeVar('_T') _ScalarType = TypeVar('_ScalarType', bound=generic) _ScalarType_co = TypeVar('_ScalarType_co', bound=generic, covariant=True) _DType = TypeVar('_DType', bound=dtype[Any]) _DType_co = TypeVar('_DType_co', covariant=True, bound=dtype[Any]) NDArray: TypeAlias = ndarray[_Shape, dtype[_ScalarType_co]] @runtime_checkable class _SupportsArray(Protocol[_DType_co]): def __array__(self) -> ndarray[Any, _DType_co]: ... @runtime_checkable class _SupportsArrayFunc(Protocol): def __array_function__(self, func: Callable[..., Any], types: Collection[type[Any]], args: tuple[Any, ...], kwargs: dict[str, Any]) -> object: ... _FiniteNestedSequence: TypeAlias = _T | Sequence[_T] | Sequence[Sequence[_T]] | Sequence[Sequence[Sequence[_T]]] | Sequence[Sequence[Sequence[Sequence[_T]]]] _ArrayLike: TypeAlias = _SupportsArray[dtype[_ScalarType]] | _NestedSequence[_SupportsArray[dtype[_ScalarType]]] _DualArrayLike: TypeAlias = _SupportsArray[_DType] | _NestedSequence[_SupportsArray[_DType]] | _T | _NestedSequence[_T] if sys.version_info >= (3, 12): from collections.abc import Buffer ArrayLike: TypeAlias = Buffer | _DualArrayLike[dtype[Any], bool | int | float | complex | str | bytes] else: ArrayLike: TypeAlias = _DualArrayLike[dtype[Any], bool | int | float | complex | str | bytes] _ArrayLikeBool_co: TypeAlias = _DualArrayLike[dtype[np.bool], bool] _ArrayLikeUInt_co: TypeAlias = _DualArrayLike[dtype[np.bool] | dtype[unsignedinteger[Any]], bool] _ArrayLikeInt_co: TypeAlias = _DualArrayLike[dtype[np.bool] | dtype[integer[Any]], bool | int] _ArrayLikeFloat_co: TypeAlias = _DualArrayLike[dtype[np.bool] | dtype[integer[Any]] | dtype[floating[Any]], bool | int | float] _ArrayLikeComplex_co: TypeAlias = _DualArrayLike[dtype[np.bool] | dtype[integer[Any]] | dtype[floating[Any]] | dtype[complexfloating[Any, Any]], bool | int | float | complex] _ArrayLikeNumber_co: TypeAlias = _DualArrayLike[dtype[np.bool] | dtype[number[Any]], bool | int | float | complex] _ArrayLikeTD64_co: TypeAlias = _DualArrayLike[dtype[np.bool] | dtype[integer[Any]] | dtype[timedelta64], bool | int] _ArrayLikeDT64_co: TypeAlias = _SupportsArray[dtype[datetime64]] | _NestedSequence[_SupportsArray[dtype[datetime64]]] _ArrayLikeObject_co: TypeAlias = _SupportsArray[dtype[object_]] | _NestedSequence[_SupportsArray[dtype[object_]]] _ArrayLikeVoid_co: TypeAlias = _SupportsArray[dtype[void]] | _NestedSequence[_SupportsArray[dtype[void]]] _ArrayLikeStr_co: TypeAlias = _DualArrayLike[dtype[str_], str] _ArrayLikeBytes_co: TypeAlias = _DualArrayLike[dtype[bytes_], bytes] _ArrayLikeInt: TypeAlias = _DualArrayLike[dtype[integer[Any]], int] if sys.version_info >= (3, 11): from typing import Never as _UnknownType else: from typing import NoReturn as _UnknownType _ArrayLikeUnknown: TypeAlias = _DualArrayLike[dtype[_UnknownType], _UnknownType] # File: numpy-main/numpy/_typing/_char_codes.py from typing import Literal _BoolCodes = Literal['bool', 'bool_', '?', '|?', '=?', '?'] _UInt8Codes = Literal['uint8', 'u1', '|u1', '=u1', 'u1'] _UInt16Codes = Literal['uint16', 'u2', '|u2', '=u2', 'u2'] _UInt32Codes = Literal['uint32', 'u4', '|u4', '=u4', 'u4'] _UInt64Codes = Literal['uint64', 'u8', '|u8', '=u8', 'u8'] _Int8Codes = Literal['int8', 'i1', '|i1', '=i1', 'i1'] _Int16Codes = Literal['int16', 'i2', '|i2', '=i2', 'i2'] _Int32Codes = Literal['int32', 'i4', '|i4', '=i4', 'i4'] _Int64Codes = Literal['int64', 'i8', '|i8', '=i8', 'i8'] _Float16Codes = Literal['float16', 'f2', '|f2', '=f2', 'f2'] _Float32Codes = Literal['float32', 'f4', '|f4', '=f4', 'f4'] _Float64Codes = Literal['float64', 'f8', '|f8', '=f8', 'f8'] _Complex64Codes = Literal['complex64', 'c8', '|c8', '=c8', 'c8'] _Complex128Codes = Literal['complex128', 'c16', '|c16', '=c16', 'c16'] _ByteCodes = Literal['byte', 'b', '|b', '=b', 'b'] _ShortCodes = Literal['short', 'h', '|h', '=h', 'h'] _IntCCodes = Literal['intc', 'i', '|i', '=i', 'i'] _IntPCodes = Literal['intp', 'int', 'int_', 'n', '|n', '=n', 'n'] _LongCodes = Literal['long', 'l', '|l', '=l', 'l'] _IntCodes = _IntPCodes _LongLongCodes = Literal['longlong', 'q', '|q', '=q', 'q'] _UByteCodes = Literal['ubyte', 'B', '|B', '=B', 'B'] _UShortCodes = Literal['ushort', 'H', '|H', '=H', 'H'] _UIntCCodes = Literal['uintc', 'I', '|I', '=I', 'I'] _UIntPCodes = Literal['uintp', 'uint', 'N', '|N', '=N', 'N'] _ULongCodes = Literal['ulong', 'L', '|L', '=L', 'L'] _UIntCodes = _UIntPCodes _ULongLongCodes = Literal['ulonglong', 'Q', '|Q', '=Q', 'Q'] _HalfCodes = Literal['half', 'e', '|e', '=e', 'e'] _SingleCodes = Literal['single', 'f', '|f', '=f', 'f'] _DoubleCodes = Literal['double', 'float', 'd', '|d', '=d', 'd'] _LongDoubleCodes = Literal['longdouble', 'g', '|g', '=g', 'g'] _CSingleCodes = Literal['csingle', 'F', '|F', '=F', 'F'] _CDoubleCodes = Literal['cdouble', 'complex', 'D', '|D', '=D', 'D'] _CLongDoubleCodes = Literal['clongdouble', 'G', '|G', '=G', 'G'] _StrCodes = Literal['str', 'str_', 'unicode', 'U', '|U', '=U', 'U'] _BytesCodes = Literal['bytes', 'bytes_', 'S', '|S', '=S', 'S'] _VoidCodes = Literal['void', 'V', '|V', '=V', 'V'] _ObjectCodes = Literal['object', 'object_', 'O', '|O', '=O', 'O'] _DT64Codes = Literal['datetime64', '|datetime64', '=datetime64', 'datetime64', 'datetime64[Y]', '|datetime64[Y]', '=datetime64[Y]', 'datetime64[Y]', 'datetime64[M]', '|datetime64[M]', '=datetime64[M]', 'datetime64[M]', 'datetime64[W]', '|datetime64[W]', '=datetime64[W]', 'datetime64[W]', 'datetime64[D]', '|datetime64[D]', '=datetime64[D]', 'datetime64[D]', 'datetime64[h]', '|datetime64[h]', '=datetime64[h]', 'datetime64[h]', 'datetime64[m]', '|datetime64[m]', '=datetime64[m]', 'datetime64[m]', 'datetime64[s]', '|datetime64[s]', '=datetime64[s]', 'datetime64[s]', 'datetime64[ms]', '|datetime64[ms]', '=datetime64[ms]', 'datetime64[ms]', 'datetime64[us]', '|datetime64[us]', '=datetime64[us]', 'datetime64[us]', 'datetime64[ns]', '|datetime64[ns]', '=datetime64[ns]', 'datetime64[ns]', 'datetime64[ps]', '|datetime64[ps]', '=datetime64[ps]', 'datetime64[ps]', 'datetime64[fs]', '|datetime64[fs]', '=datetime64[fs]', 'datetime64[fs]', 'datetime64[as]', '|datetime64[as]', '=datetime64[as]', 'datetime64[as]', 'M', '|M', '=M', 'M', 'M8', '|M8', '=M8', 'M8', 'M8[Y]', '|M8[Y]', '=M8[Y]', 'M8[Y]', 'M8[M]', '|M8[M]', '=M8[M]', 'M8[M]', 'M8[W]', '|M8[W]', '=M8[W]', 'M8[W]', 'M8[D]', '|M8[D]', '=M8[D]', 'M8[D]', 'M8[h]', '|M8[h]', '=M8[h]', 'M8[h]', 'M8[m]', '|M8[m]', '=M8[m]', 'M8[m]', 'M8[s]', '|M8[s]', '=M8[s]', 'M8[s]', 'M8[ms]', '|M8[ms]', '=M8[ms]', 'M8[ms]', 'M8[us]', '|M8[us]', '=M8[us]', 'M8[us]', 'M8[ns]', '|M8[ns]', '=M8[ns]', 'M8[ns]', 'M8[ps]', '|M8[ps]', '=M8[ps]', 'M8[ps]', 'M8[fs]', '|M8[fs]', '=M8[fs]', 'M8[fs]', 'M8[as]', '|M8[as]', '=M8[as]', 'M8[as]'] _TD64Codes = Literal['timedelta64', '|timedelta64', '=timedelta64', 'timedelta64', 'timedelta64[Y]', '|timedelta64[Y]', '=timedelta64[Y]', 'timedelta64[Y]', 'timedelta64[M]', '|timedelta64[M]', '=timedelta64[M]', 'timedelta64[M]', 'timedelta64[W]', '|timedelta64[W]', '=timedelta64[W]', 'timedelta64[W]', 'timedelta64[D]', '|timedelta64[D]', '=timedelta64[D]', 'timedelta64[D]', 'timedelta64[h]', '|timedelta64[h]', '=timedelta64[h]', 'timedelta64[h]', 'timedelta64[m]', '|timedelta64[m]', '=timedelta64[m]', 'timedelta64[m]', 'timedelta64[s]', '|timedelta64[s]', '=timedelta64[s]', 'timedelta64[s]', 'timedelta64[ms]', '|timedelta64[ms]', '=timedelta64[ms]', 'timedelta64[ms]', 'timedelta64[us]', '|timedelta64[us]', '=timedelta64[us]', 'timedelta64[us]', 'timedelta64[ns]', '|timedelta64[ns]', '=timedelta64[ns]', 'timedelta64[ns]', 'timedelta64[ps]', '|timedelta64[ps]', '=timedelta64[ps]', 'timedelta64[ps]', 'timedelta64[fs]', '|timedelta64[fs]', '=timedelta64[fs]', 'timedelta64[fs]', 'timedelta64[as]', '|timedelta64[as]', '=timedelta64[as]', 'timedelta64[as]', 'm', '|m', '=m', 'm', 'm8', '|m8', '=m8', 'm8', 'm8[Y]', '|m8[Y]', '=m8[Y]', 'm8[Y]', 'm8[M]', '|m8[M]', '=m8[M]', 'm8[M]', 'm8[W]', '|m8[W]', '=m8[W]', 'm8[W]', 'm8[D]', '|m8[D]', '=m8[D]', 'm8[D]', 'm8[h]', '|m8[h]', '=m8[h]', 'm8[h]', 'm8[m]', '|m8[m]', '=m8[m]', 'm8[m]', 'm8[s]', '|m8[s]', '=m8[s]', 'm8[s]', 'm8[ms]', '|m8[ms]', '=m8[ms]', 'm8[ms]', 'm8[us]', '|m8[us]', '=m8[us]', 'm8[us]', 'm8[ns]', '|m8[ns]', '=m8[ns]', 'm8[ns]', 'm8[ps]', '|m8[ps]', '=m8[ps]', 'm8[ps]', 'm8[fs]', '|m8[fs]', '=m8[fs]', 'm8[fs]', 'm8[as]', '|m8[as]', '=m8[as]', 'm8[as]'] _StringCodes = Literal['T', '|T', '=T', 'T'] _UnsignedIntegerCodes = Literal[_UInt8Codes, _UInt16Codes, _UInt32Codes, _UInt64Codes, _UIntCodes, _UByteCodes, _UShortCodes, _UIntCCodes, _ULongCodes, _ULongLongCodes] _SignedIntegerCodes = Literal[_Int8Codes, _Int16Codes, _Int32Codes, _Int64Codes, _IntCodes, _ByteCodes, _ShortCodes, _IntCCodes, _LongCodes, _LongLongCodes] _FloatingCodes = Literal[_Float16Codes, _Float32Codes, _Float64Codes, _LongDoubleCodes, _HalfCodes, _SingleCodes, _DoubleCodes, _LongDoubleCodes] _ComplexFloatingCodes = Literal[_Complex64Codes, _Complex128Codes, _CSingleCodes, _CDoubleCodes, _CLongDoubleCodes] _IntegerCodes = Literal[_UnsignedIntegerCodes, _SignedIntegerCodes] _InexactCodes = Literal[_FloatingCodes, _ComplexFloatingCodes] _NumberCodes = Literal[_IntegerCodes, _InexactCodes] _CharacterCodes = Literal[_StrCodes, _BytesCodes] _FlexibleCodes = Literal[_VoidCodes, _CharacterCodes] _GenericCodes = Literal[_BoolCodes, _NumberCodes, _FlexibleCodes, _DT64Codes, _TD64Codes, _ObjectCodes] # File: numpy-main/numpy/_typing/_dtype_like.py from collections.abc import Sequence from typing import Any, TypeAlias, TypeVar, Protocol, TypedDict, runtime_checkable import numpy as np from ._shape import _ShapeLike from ._char_codes import _BoolCodes, _UInt8Codes, _UInt16Codes, _UInt32Codes, _UInt64Codes, _Int8Codes, _Int16Codes, _Int32Codes, _Int64Codes, _Float16Codes, _Float32Codes, _Float64Codes, _Complex64Codes, _Complex128Codes, _ByteCodes, _ShortCodes, _IntCCodes, _LongCodes, _LongLongCodes, _IntPCodes, _IntCodes, _UByteCodes, _UShortCodes, _UIntCCodes, _ULongCodes, _ULongLongCodes, _UIntPCodes, _UIntCodes, _HalfCodes, _SingleCodes, _DoubleCodes, _LongDoubleCodes, _CSingleCodes, _CDoubleCodes, _CLongDoubleCodes, _DT64Codes, _TD64Codes, _StrCodes, _BytesCodes, _VoidCodes, _ObjectCodes _SCT = TypeVar('_SCT', bound=np.generic) _DType_co = TypeVar('_DType_co', covariant=True, bound=np.dtype[Any]) _DTypeLikeNested: TypeAlias = Any class _DTypeDictBase(TypedDict): names: Sequence[str] formats: Sequence[_DTypeLikeNested] class _DTypeDict(_DTypeDictBase, total=False): offsets: Sequence[int] titles: Sequence[Any] itemsize: int aligned: bool @runtime_checkable class _SupportsDType(Protocol[_DType_co]): @property def dtype(self) -> _DType_co: ... _DTypeLike: TypeAlias = np.dtype[_SCT] | type[_SCT] | _SupportsDType[np.dtype[_SCT]] _VoidDTypeLike: TypeAlias = tuple[_DTypeLikeNested, int] | tuple[_DTypeLikeNested, _ShapeLike] | list[Any] | _DTypeDict | tuple[_DTypeLikeNested, _DTypeLikeNested] DTypeLike: TypeAlias = np.dtype[Any] | None | type[Any] | _SupportsDType[np.dtype[Any]] | str | _VoidDTypeLike _DTypeLikeBool: TypeAlias = type[bool] | type[np.bool] | np.dtype[np.bool] | _SupportsDType[np.dtype[np.bool]] | _BoolCodes _DTypeLikeUInt: TypeAlias = type[np.unsignedinteger] | np.dtype[np.unsignedinteger] | _SupportsDType[np.dtype[np.unsignedinteger]] | _UInt8Codes | _UInt16Codes | _UInt32Codes | _UInt64Codes | _UByteCodes | _UShortCodes | _UIntCCodes | _LongCodes | _ULongLongCodes | _UIntPCodes | _UIntCodes _DTypeLikeInt: TypeAlias = type[int] | type[np.signedinteger] | np.dtype[np.signedinteger] | _SupportsDType[np.dtype[np.signedinteger]] | _Int8Codes | _Int16Codes | _Int32Codes | _Int64Codes | _ByteCodes | _ShortCodes | _IntCCodes | _LongCodes | _LongLongCodes | _IntPCodes | _IntCodes _DTypeLikeFloat: TypeAlias = type[float] | type[np.floating] | np.dtype[np.floating] | _SupportsDType[np.dtype[np.floating]] | _Float16Codes | _Float32Codes | _Float64Codes | _HalfCodes | _SingleCodes | _DoubleCodes | _LongDoubleCodes _DTypeLikeComplex: TypeAlias = type[complex] | type[np.complexfloating] | np.dtype[np.complexfloating] | _SupportsDType[np.dtype[np.complexfloating]] | _Complex64Codes | _Complex128Codes | _CSingleCodes | _CDoubleCodes | _CLongDoubleCodes _DTypeLikeDT64: TypeAlias = type[np.timedelta64] | np.dtype[np.timedelta64] | _SupportsDType[np.dtype[np.timedelta64]] | _TD64Codes _DTypeLikeTD64: TypeAlias = type[np.datetime64] | np.dtype[np.datetime64] | _SupportsDType[np.dtype[np.datetime64]] | _DT64Codes _DTypeLikeStr: TypeAlias = type[str] | type[np.str_] | np.dtype[np.str_] | _SupportsDType[np.dtype[np.str_]] | _StrCodes _DTypeLikeBytes: TypeAlias = type[bytes] | type[np.bytes_] | np.dtype[np.bytes_] | _SupportsDType[np.dtype[np.bytes_]] | _BytesCodes _DTypeLikeVoid: TypeAlias = type[np.void] | np.dtype[np.void] | _SupportsDType[np.dtype[np.void]] | _VoidCodes | _VoidDTypeLike _DTypeLikeObject: TypeAlias = type | np.dtype[np.object_] | _SupportsDType[np.dtype[np.object_]] | _ObjectCodes _DTypeLikeComplex_co: TypeAlias = _DTypeLikeBool | _DTypeLikeUInt | _DTypeLikeInt | _DTypeLikeFloat | _DTypeLikeComplex # File: numpy-main/numpy/_typing/_extended_precision.py """""" import numpy as np from . import _80Bit, _96Bit, _128Bit, _256Bit uint128 = np.unsignedinteger[_128Bit] uint256 = np.unsignedinteger[_256Bit] int128 = np.signedinteger[_128Bit] int256 = np.signedinteger[_256Bit] float80 = np.floating[_80Bit] float96 = np.floating[_96Bit] float128 = np.floating[_128Bit] float256 = np.floating[_256Bit] complex160 = np.complexfloating[_80Bit, _80Bit] complex192 = np.complexfloating[_96Bit, _96Bit] complex256 = np.complexfloating[_128Bit, _128Bit] complex512 = np.complexfloating[_256Bit, _256Bit] # File: numpy-main/numpy/_typing/_nbit.py """""" from typing import TypeAlias from ._nbit_base import _8Bit, _16Bit, _32Bit, _64Bit, _96Bit, _128Bit _NBitByte: TypeAlias = _8Bit _NBitShort: TypeAlias = _16Bit _NBitIntC: TypeAlias = _32Bit _NBitIntP: TypeAlias = _32Bit | _64Bit _NBitInt: TypeAlias = _NBitIntP _NBitLong: TypeAlias = _32Bit | _64Bit _NBitLongLong: TypeAlias = _64Bit _NBitHalf: TypeAlias = _16Bit _NBitSingle: TypeAlias = _32Bit _NBitDouble: TypeAlias = _64Bit _NBitLongDouble: TypeAlias = _64Bit | _96Bit | _128Bit # File: numpy-main/numpy/_typing/_nbit_base.py """""" from .._utils import set_module from typing import final @final @set_module('numpy.typing') class NBitBase: def __init_subclass__(cls) -> None: allowed_names = {'NBitBase', '_256Bit', '_128Bit', '_96Bit', '_80Bit', '_64Bit', '_32Bit', '_16Bit', '_8Bit'} if cls.__name__ not in allowed_names: raise TypeError('cannot inherit from final class "NBitBase"') super().__init_subclass__() @final @set_module('numpy._typing') class _256Bit(NBitBase): pass @final @set_module('numpy._typing') class _128Bit(_256Bit): pass @final @set_module('numpy._typing') class _96Bit(_128Bit): pass @final @set_module('numpy._typing') class _80Bit(_96Bit): pass @final @set_module('numpy._typing') class _64Bit(_80Bit): pass @final @set_module('numpy._typing') class _32Bit(_64Bit): pass @final @set_module('numpy._typing') class _16Bit(_32Bit): pass @final @set_module('numpy._typing') class _8Bit(_16Bit): pass # File: numpy-main/numpy/_typing/_nested_sequence.py """""" from __future__ import annotations from typing import Any, TypeVar, Protocol, runtime_checkable, TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Iterator __all__ = ['_NestedSequence'] _T_co = TypeVar('_T_co', covariant=True) @runtime_checkable class _NestedSequence(Protocol[_T_co]): def __len__(self, /) -> int: raise NotImplementedError def __getitem__(self, index: int, /) -> _T_co | _NestedSequence[_T_co]: raise NotImplementedError def __contains__(self, x: object, /) -> bool: raise NotImplementedError def __iter__(self, /) -> Iterator[_T_co | _NestedSequence[_T_co]]: raise NotImplementedError def __reversed__(self, /) -> Iterator[_T_co | _NestedSequence[_T_co]]: raise NotImplementedError def count(self, value: Any, /) -> int: raise NotImplementedError def index(self, value: Any, /) -> int: raise NotImplementedError # File: numpy-main/numpy/_typing/_scalars.py from typing import Any, TypeAlias import numpy as np _CharLike_co: TypeAlias = str | bytes _BoolLike_co: TypeAlias = bool | np.bool _UIntLike_co: TypeAlias = np.unsignedinteger[Any] | _BoolLike_co _IntLike_co: TypeAlias = int | np.integer[Any] | _BoolLike_co _FloatLike_co: TypeAlias = float | np.floating[Any] | _IntLike_co _ComplexLike_co: TypeAlias = complex | np.complexfloating[Any, Any] | _FloatLike_co _TD64Like_co: TypeAlias = np.timedelta64 | _IntLike_co _NumberLike_co: TypeAlias = int | float | complex | np.number[Any] | np.bool _ScalarLike_co: TypeAlias = int | float | complex | str | bytes | np.generic _VoidLike_co: TypeAlias = tuple[Any, ...] | np.void # File: numpy-main/numpy/_utils/__init__.py """""" import functools import warnings from ._convertions import asunicode, asbytes def set_module(module): def decorator(func): if module is not None: func.__module__ = module return func return decorator def _rename_parameter(old_names, new_names, dep_version=None): def decorator(fun): @functools.wraps(fun) def wrapper(*args, **kwargs): for (old_name, new_name) in zip(old_names, new_names): if old_name in kwargs: if dep_version: end_version = dep_version.split('.') end_version[1] = str(int(end_version[1]) + 2) end_version = '.'.join(end_version) msg = f'Use of keyword argument `{old_name}` is deprecated and replaced by `{new_name}`. Support for `{old_name}` will be removed in NumPy {end_version}.' warnings.warn(msg, DeprecationWarning, stacklevel=2) if new_name in kwargs: msg = f'{fun.__name__}() got multiple values for argument now known as `{new_name}`' raise TypeError(msg) kwargs[new_name] = kwargs.pop(old_name) return fun(*args, **kwargs) return wrapper return decorator # File: numpy-main/numpy/_utils/_convertions.py """""" __all__ = ['asunicode', 'asbytes'] def asunicode(s): if isinstance(s, bytes): return s.decode('latin1') return str(s) def asbytes(s): if isinstance(s, bytes): return s return str(s).encode('latin1') # File: numpy-main/numpy/_utils/_inspect.py """""" import types __all__ = ['getargspec', 'formatargspec'] def ismethod(object): return isinstance(object, types.MethodType) def isfunction(object): return isinstance(object, types.FunctionType) def iscode(object): return isinstance(object, types.CodeType) (CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS) = (1, 2, 4, 8) def getargs(co): if not iscode(co): raise TypeError('arg is not a code object') nargs = co.co_argcount names = co.co_varnames args = list(names[:nargs]) for i in range(nargs): if args[i][:1] in ['', '.']: raise TypeError('tuple function arguments are not supported') varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return (args, varargs, varkw) def getargspec(func): if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError('arg is not a Python function') (args, varargs, varkw) = getargs(func.__code__) return (args, varargs, varkw, func.__defaults__) def getargvalues(frame): (args, varargs, varkw) = getargs(frame.f_code) return (args, varargs, varkw, frame.f_locals) def joinseq(seq): if len(seq) == 1: return '(' + seq[0] + ',)' else: return '(' + ', '.join(seq) + ')' def strseq(object, convert, join=joinseq): if type(object) in [list, tuple]: return join([strseq(_o, convert, join) for _o in object]) else: return convert(object) def formatargspec(args, varargs=None, varkw=None, defaults=None, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): specs = [] if defaults: firstdefault = len(args) - len(defaults) for i in range(len(args)): spec = strseq(args[i], formatarg, join) if defaults and i >= firstdefault: spec = spec + formatvalue(defaults[i - firstdefault]) specs.append(spec) if varargs is not None: specs.append(formatvarargs(varargs)) if varkw is not None: specs.append(formatvarkw(varkw)) return '(' + ', '.join(specs) + ')' def formatargvalues(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): def convert(name, locals=locals, formatarg=formatarg, formatvalue=formatvalue): return formatarg(name) + formatvalue(locals[name]) specs = [strseq(arg, convert, join) for arg in args] if varargs: specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) if varkw: specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) return '(' + ', '.join(specs) + ')' # File: numpy-main/numpy/_utils/_pep440.py """""" import collections import itertools import re __all__ = ['parse', 'Version', 'LegacyVersion', 'InvalidVersion', 'VERSION_PATTERN'] class Infinity: def __repr__(self): return 'Infinity' def __hash__(self): return hash(repr(self)) def __lt__(self, other): return False def __le__(self, other): return False def __eq__(self, other): return isinstance(other, self.__class__) def __ne__(self, other): return not isinstance(other, self.__class__) def __gt__(self, other): return True def __ge__(self, other): return True def __neg__(self): return NegativeInfinity Infinity = Infinity() class NegativeInfinity: def __repr__(self): return '-Infinity' def __hash__(self): return hash(repr(self)) def __lt__(self, other): return True def __le__(self, other): return True def __eq__(self, other): return isinstance(other, self.__class__) def __ne__(self, other): return not isinstance(other, self.__class__) def __gt__(self, other): return False def __ge__(self, other): return False def __neg__(self): return Infinity NegativeInfinity = NegativeInfinity() _Version = collections.namedtuple('_Version', ['epoch', 'release', 'dev', 'pre', 'post', 'local']) def parse(version): try: return Version(version) except InvalidVersion: return LegacyVersion(version) class InvalidVersion(ValueError): class _BaseVersion: def __hash__(self): return hash(self._key) def __lt__(self, other): return self._compare(other, lambda s, o: s < o) def __le__(self, other): return self._compare(other, lambda s, o: s <= o) def __eq__(self, other): return self._compare(other, lambda s, o: s == o) def __ge__(self, other): return self._compare(other, lambda s, o: s >= o) def __gt__(self, other): return self._compare(other, lambda s, o: s > o) def __ne__(self, other): return self._compare(other, lambda s, o: s != o) def _compare(self, other, method): if not isinstance(other, _BaseVersion): return NotImplemented return method(self._key, other._key) class LegacyVersion(_BaseVersion): def __init__(self, version): self._version = str(version) self._key = _legacy_cmpkey(self._version) def __str__(self): return self._version def __repr__(self): return ''.format(repr(str(self))) @property def public(self): return self._version @property def base_version(self): return self._version @property def local(self): return None @property def is_prerelease(self): return False @property def is_postrelease(self): return False _legacy_version_component_re = re.compile('(\\d+ | [a-z]+ | \\.| -)', re.VERBOSE) _legacy_version_replacement_map = {'pre': 'c', 'preview': 'c', '-': 'final-', 'rc': 'c', 'dev': '@'} def _parse_version_parts(s): for part in _legacy_version_component_re.split(s): part = _legacy_version_replacement_map.get(part, part) if not part or part == '.': continue if part[:1] in '0123456789': yield part.zfill(8) else: yield ('*' + part) yield '*final' def _legacy_cmpkey(version): epoch = -1 parts = [] for part in _parse_version_parts(version.lower()): if part.startswith('*'): if part < '*final': while parts and parts[-1] == '*final-': parts.pop() while parts and parts[-1] == '00000000': parts.pop() parts.append(part) parts = tuple(parts) return (epoch, parts) VERSION_PATTERN = '\n v?\n (?:\n (?:(?P[0-9]+)!)? # epoch\n (?P[0-9]+(?:\\.[0-9]+)*) # release segment\n (?P
                                          # pre-release\n            [-_\\.]?\n            (?P(a|b|c|rc|alpha|beta|pre|preview))\n            [-_\\.]?\n            (?P[0-9]+)?\n        )?\n        (?P                                         # post release\n            (?:-(?P[0-9]+))\n            |\n            (?:\n                [-_\\.]?\n                (?Ppost|rev|r)\n                [-_\\.]?\n                (?P[0-9]+)?\n            )\n        )?\n        (?P                                          # dev release\n            [-_\\.]?\n            (?Pdev)\n            [-_\\.]?\n            (?P[0-9]+)?\n        )?\n    )\n    (?:\\+(?P[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))?       # local version\n'

class Version(_BaseVersion):
    _regex = re.compile('^\\s*' + VERSION_PATTERN + '\\s*$', re.VERBOSE | re.IGNORECASE)

    def __init__(self, version):
        match = self._regex.search(version)
        if not match:
            raise InvalidVersion("Invalid version: '{0}'".format(version))
        self._version = _Version(epoch=int(match.group('epoch')) if match.group('epoch') else 0, release=tuple((int(i) for i in match.group('release').split('.'))), pre=_parse_letter_version(match.group('pre_l'), match.group('pre_n')), post=_parse_letter_version(match.group('post_l'), match.group('post_n1') or match.group('post_n2')), dev=_parse_letter_version(match.group('dev_l'), match.group('dev_n')), local=_parse_local_version(match.group('local')))
        self._key = _cmpkey(self._version.epoch, self._version.release, self._version.pre, self._version.post, self._version.dev, self._version.local)

    def __repr__(self):
        return ''.format(repr(str(self)))

    def __str__(self):
        parts = []
        if self._version.epoch != 0:
            parts.append('{0}!'.format(self._version.epoch))
        parts.append('.'.join((str(x) for x in self._version.release)))
        if self._version.pre is not None:
            parts.append(''.join((str(x) for x in self._version.pre)))
        if self._version.post is not None:
            parts.append('.post{0}'.format(self._version.post[1]))
        if self._version.dev is not None:
            parts.append('.dev{0}'.format(self._version.dev[1]))
        if self._version.local is not None:
            parts.append('+{0}'.format('.'.join((str(x) for x in self._version.local))))
        return ''.join(parts)

    @property
    def public(self):
        return str(self).split('+', 1)[0]

    @property
    def base_version(self):
        parts = []
        if self._version.epoch != 0:
            parts.append('{0}!'.format(self._version.epoch))
        parts.append('.'.join((str(x) for x in self._version.release)))
        return ''.join(parts)

    @property
    def local(self):
        version_string = str(self)
        if '+' in version_string:
            return version_string.split('+', 1)[1]

    @property
    def is_prerelease(self):
        return bool(self._version.dev or self._version.pre)

    @property
    def is_postrelease(self):
        return bool(self._version.post)

def _parse_letter_version(letter, number):
    if letter:
        if number is None:
            number = 0
        letter = letter.lower()
        if letter == 'alpha':
            letter = 'a'
        elif letter == 'beta':
            letter = 'b'
        elif letter in ['c', 'pre', 'preview']:
            letter = 'rc'
        elif letter in ['rev', 'r']:
            letter = 'post'
        return (letter, int(number))
    if not letter and number:
        letter = 'post'
        return (letter, int(number))
_local_version_seperators = re.compile('[\\._-]')

def _parse_local_version(local):
    if local is not None:
        return tuple((part.lower() if not part.isdigit() else int(part) for part in _local_version_seperators.split(local)))

def _cmpkey(epoch, release, pre, post, dev, local):
    release = tuple(reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release)))))
    if pre is None and post is None and (dev is not None):
        pre = -Infinity
    elif pre is None:
        pre = Infinity
    if post is None:
        post = -Infinity
    if dev is None:
        dev = Infinity
    if local is None:
        local = -Infinity
    else:
        local = tuple(((i, '') if isinstance(i, int) else (-Infinity, i) for i in local))
    return (epoch, release, pre, post, dev, local)

# File: numpy-main/numpy/compat/__init__.py
""""""
import warnings
from .._utils import _inspect
from .._utils._inspect import getargspec, formatargspec
from . import py3k
from .py3k import *
warnings.warn('`np.compat`, which was used during the Python 2 to 3 transition, is deprecated since 1.26.0, and will be removed', DeprecationWarning, stacklevel=2)
__all__ = []
__all__.extend(_inspect.__all__)
__all__.extend(py3k.__all__)

# File: numpy-main/numpy/compat/py3k.py
""""""
__all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar', 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested', 'asstr', 'open_latin1', 'long', 'basestring', 'sixu', 'integer_types', 'is_pathlib_path', 'npy_load_module', 'Path', 'pickle', 'contextlib_nullcontext', 'os_fspath', 'os_PathLike']
import sys
import os
from pathlib import Path
import io
try:
    import pickle5 as pickle
except ImportError:
    import pickle
long = int
integer_types = (int,)
basestring = str
unicode = str
bytes = bytes

def asunicode(s):
    if isinstance(s, bytes):
        return s.decode('latin1')
    return str(s)

def asbytes(s):
    if isinstance(s, bytes):
        return s
    return str(s).encode('latin1')

def asstr(s):
    if isinstance(s, bytes):
        return s.decode('latin1')
    return str(s)

def isfileobj(f):
    if not isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter)):
        return False
    try:
        f.fileno()
        return True
    except OSError:
        return False

def open_latin1(filename, mode='r'):
    return open(filename, mode=mode, encoding='iso-8859-1')

def sixu(s):
    return s
strchar = 'U'

def getexception():
    return sys.exc_info()[1]

def asbytes_nested(x):
    if hasattr(x, '__iter__') and (not isinstance(x, (bytes, unicode))):
        return [asbytes_nested(y) for y in x]
    else:
        return asbytes(x)

def asunicode_nested(x):
    if hasattr(x, '__iter__') and (not isinstance(x, (bytes, unicode))):
        return [asunicode_nested(y) for y in x]
    else:
        return asunicode(x)

def is_pathlib_path(obj):
    return isinstance(obj, Path)

class contextlib_nullcontext:

    def __init__(self, enter_result=None):
        self.enter_result = enter_result

    def __enter__(self):
        return self.enter_result

    def __exit__(self, *excinfo):
        pass

def npy_load_module(name, fn, info=None):
    from importlib.machinery import SourceFileLoader
    return SourceFileLoader(name, fn).load_module()
os_fspath = os.fspath
os_PathLike = os.PathLike

# File: numpy-main/numpy/core/__init__.py
""""""
from numpy import _core
from ._utils import _raise_warning

def _ufunc_reconstruct(module, name):
    mod = __import__(module, fromlist=[name])
    return getattr(mod, name)
__all__ = ['arrayprint', 'defchararray', '_dtype_ctypes', '_dtype', 'einsumfunc', 'fromnumeric', 'function_base', 'getlimits', '_internal', 'multiarray', '_multiarray_umath', 'numeric', 'numerictypes', 'overrides', 'records', 'shape_base', 'umath']

def __getattr__(attr_name):
    attr = getattr(_core, attr_name)
    _raise_warning(attr_name)
    return attr

# File: numpy-main/numpy/core/_internal.py
from numpy._core import _internal

def _reconstruct(subtype, shape, dtype):
    from numpy import ndarray
    return ndarray.__new__(subtype, shape, dtype)
_dtype_from_pep3118 = _internal._dtype_from_pep3118

def __getattr__(attr_name):
    from numpy._core import _internal
    from ._utils import _raise_warning
    ret = getattr(_internal, attr_name, None)
    if ret is None:
        raise AttributeError(f"module 'numpy.core._internal' has no attribute {attr_name}")
    _raise_warning(attr_name, '_internal')
    return ret

# File: numpy-main/numpy/core/_multiarray_umath.py
from numpy._core import _multiarray_umath
from numpy import ufunc
for item in _multiarray_umath.__dir__():
    attr = getattr(_multiarray_umath, item)
    if isinstance(attr, ufunc):
        globals()[item] = attr

def __getattr__(attr_name):
    from numpy._core import _multiarray_umath
    from ._utils import _raise_warning
    if attr_name in {'_ARRAY_API', '_UFUNC_API'}:
        from numpy.version import short_version
        import textwrap
        import traceback
        import sys
        msg = textwrap.dedent(f"\n            A module that was compiled using NumPy 1.x cannot be run in\n            NumPy {short_version} as it may crash. To support both 1.x and 2.x\n            versions of NumPy, modules must be compiled with NumPy 2.0.\n            Some module may need to rebuild instead e.g. with 'pybind11>=2.12'.\n\n            If you are a user of the module, the easiest solution will be to\n            downgrade to 'numpy<2' or try to upgrade the affected module.\n            We expect that some modules will need time to support NumPy 2.\n\n            ")
        tb_msg = 'Traceback (most recent call last):'
        for line in traceback.format_stack()[:-1]:
            if 'frozen importlib' in line:
                continue
            tb_msg += line
        sys.stderr.write(msg + tb_msg)
        raise ImportError(msg)
    ret = getattr(_multiarray_umath, attr_name, None)
    if ret is None:
        raise AttributeError(f"module 'numpy.core._multiarray_umath' has no attribute {attr_name}")
    _raise_warning(attr_name, '_multiarray_umath')
    return ret
del _multiarray_umath, ufunc

# File: numpy-main/numpy/core/_utils.py
import warnings

def _raise_warning(attr: str, submodule: str | None=None) -> None:
    new_module = 'numpy._core'
    old_module = 'numpy.core'
    if submodule is not None:
        new_module = f'{new_module}.{submodule}'
        old_module = f'{old_module}.{submodule}'
    warnings.warn(f'{old_module} is deprecated and has been renamed to {new_module}. The numpy._core namespace contains private NumPy internals and its use is discouraged, as NumPy internals can change without warning in any release. In practice, most real-world usage of numpy.core is to access functionality in the public NumPy API. If that is the case, use the public NumPy API. If not, you are using NumPy internals. If you would still like to access an internal attribute, use {new_module}.{attr}.', DeprecationWarning, stacklevel=3)

# File: numpy-main/numpy/core/multiarray.py
from numpy._core import multiarray
for item in ['_reconstruct', 'scalar']:
    globals()[item] = getattr(multiarray, item)
_ARRAY_API = multiarray._ARRAY_API

def __getattr__(attr_name):
    from numpy._core import multiarray
    from ._utils import _raise_warning
    ret = getattr(multiarray, attr_name, None)
    if ret is None:
        raise AttributeError(f"module 'numpy.core.multiarray' has no attribute {attr_name}")
    _raise_warning(attr_name, 'multiarray')
    return ret
del multiarray

# File: numpy-main/numpy/core/numeric.py
def __getattr__(attr_name):
    from numpy._core import numeric
    from ._utils import _raise_warning
    sentinel = object()
    ret = getattr(numeric, attr_name, sentinel)
    if ret is sentinel:
        raise AttributeError(f"module 'numpy.core.numeric' has no attribute {attr_name}")
    _raise_warning(attr_name, 'numeric')
    return ret

# File: numpy-main/numpy/ctypeslib.py
""""""
__all__ = ['load_library', 'ndpointer', 'c_intp', 'as_ctypes', 'as_array', 'as_ctypes_type']
import os
from numpy import integer, ndarray, dtype as _dtype, asarray, frombuffer
from numpy._core.multiarray import _flagdict, flagsobj
try:
    import ctypes
except ImportError:
    ctypes = None
if ctypes is None:

    def _dummy(*args, **kwds):
        raise ImportError('ctypes is not available.')
    load_library = _dummy
    as_ctypes = _dummy
    as_array = _dummy
    from numpy import intp as c_intp
    _ndptr_base = object
else:
    import numpy._core._internal as nic
    c_intp = nic._getintp_ctype()
    del nic
    _ndptr_base = ctypes.c_void_p

    def load_library(libname, loader_path):
        libname = os.fsdecode(libname)
        loader_path = os.fsdecode(loader_path)
        ext = os.path.splitext(libname)[1]
        if not ext:
            import sys
            import sysconfig
            base_ext = '.so'
            if sys.platform.startswith('darwin'):
                base_ext = '.dylib'
            elif sys.platform.startswith('win'):
                base_ext = '.dll'
            libname_ext = [libname + base_ext]
            so_ext = sysconfig.get_config_var('EXT_SUFFIX')
            if not so_ext == base_ext:
                libname_ext.insert(0, libname + so_ext)
        else:
            libname_ext = [libname]
        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path
        for ln in libname_ext:
            libpath = os.path.join(libdir, ln)
            if os.path.exists(libpath):
                try:
                    return ctypes.cdll[libpath]
                except OSError:
                    raise
        raise OSError('no file with expected extension')

def _num_fromflags(flaglist):
    num = 0
    for val in flaglist:
        num += _flagdict[val]
    return num
_flagnames = ['C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE', 'OWNDATA', 'WRITEBACKIFCOPY']

def _flags_fromnum(num):
    res = []
    for key in _flagnames:
        value = _flagdict[key]
        if num & value:
            res.append(key)
    return res

class _ndptr(_ndptr_base):

    @classmethod
    def from_param(cls, obj):
        if not isinstance(obj, ndarray):
            raise TypeError('argument must be an ndarray')
        if cls._dtype_ is not None and obj.dtype != cls._dtype_:
            raise TypeError('array must have data type %s' % cls._dtype_)
        if cls._ndim_ is not None and obj.ndim != cls._ndim_:
            raise TypeError('array must have %d dimension(s)' % cls._ndim_)
        if cls._shape_ is not None and obj.shape != cls._shape_:
            raise TypeError('array must have shape %s' % str(cls._shape_))
        if cls._flags_ is not None and obj.flags.num & cls._flags_ != cls._flags_:
            raise TypeError('array must have flags %s' % _flags_fromnum(cls._flags_))
        return obj.ctypes

class _concrete_ndptr(_ndptr):

    def _check_retval_(self):
        return self.contents

    @property
    def contents(self):
        full_dtype = _dtype((self._dtype_, self._shape_))
        full_ctype = ctypes.c_char * full_dtype.itemsize
        buffer = ctypes.cast(self, ctypes.POINTER(full_ctype)).contents
        return frombuffer(buffer, dtype=full_dtype).squeeze(axis=0)
_pointer_type_cache = {}

def ndpointer(dtype=None, ndim=None, shape=None, flags=None):
    if dtype is not None:
        dtype = _dtype(dtype)
    num = None
    if flags is not None:
        if isinstance(flags, str):
            flags = flags.split(',')
        elif isinstance(flags, (int, integer)):
            num = flags
            flags = _flags_fromnum(num)
        elif isinstance(flags, flagsobj):
            num = flags.num
            flags = _flags_fromnum(num)
        if num is None:
            try:
                flags = [x.strip().upper() for x in flags]
            except Exception as e:
                raise TypeError('invalid flags specification') from e
            num = _num_fromflags(flags)
    if shape is not None:
        try:
            shape = tuple(shape)
        except TypeError:
            shape = (shape,)
    cache_key = (dtype, ndim, shape, num)
    try:
        return _pointer_type_cache[cache_key]
    except KeyError:
        pass
    if dtype is None:
        name = 'any'
    elif dtype.names is not None:
        name = str(id(dtype))
    else:
        name = dtype.str
    if ndim is not None:
        name += '_%dd' % ndim
    if shape is not None:
        name += '_' + 'x'.join((str(x) for x in shape))
    if flags is not None:
        name += '_' + '_'.join(flags)
    if dtype is not None and shape is not None:
        base = _concrete_ndptr
    else:
        base = _ndptr
    klass = type('ndpointer_%s' % name, (base,), {'_dtype_': dtype, '_shape_': shape, '_ndim_': ndim, '_flags_': num})
    _pointer_type_cache[cache_key] = klass
    return klass
if ctypes is not None:

    def _ctype_ndarray(element_type, shape):
        for dim in shape[::-1]:
            element_type = dim * element_type
            element_type.__module__ = None
        return element_type

    def _get_scalar_type_map():
        ct = ctypes
        simple_types = [ct.c_byte, ct.c_short, ct.c_int, ct.c_long, ct.c_longlong, ct.c_ubyte, ct.c_ushort, ct.c_uint, ct.c_ulong, ct.c_ulonglong, ct.c_float, ct.c_double, ct.c_bool]
        return {_dtype(ctype): ctype for ctype in simple_types}
    _scalar_type_map = _get_scalar_type_map()

    def _ctype_from_dtype_scalar(dtype):
        dtype_with_endian = dtype.newbyteorder('S').newbyteorder('S')
        dtype_native = dtype.newbyteorder('=')
        try:
            ctype = _scalar_type_map[dtype_native]
        except KeyError as e:
            raise NotImplementedError('Converting {!r} to a ctypes type'.format(dtype)) from None
        if dtype_with_endian.byteorder == '>':
            ctype = ctype.__ctype_be__
        elif dtype_with_endian.byteorder == '<':
            ctype = ctype.__ctype_le__
        return ctype

    def _ctype_from_dtype_subarray(dtype):
        (element_dtype, shape) = dtype.subdtype
        ctype = _ctype_from_dtype(element_dtype)
        return _ctype_ndarray(ctype, shape)

    def _ctype_from_dtype_structured(dtype):
        field_data = []
        for name in dtype.names:
            (field_dtype, offset) = dtype.fields[name][:2]
            field_data.append((offset, name, _ctype_from_dtype(field_dtype)))
        field_data = sorted(field_data, key=lambda f: f[0])
        if len(field_data) > 1 and all((offset == 0 for (offset, name, ctype) in field_data)):
            size = 0
            _fields_ = []
            for (offset, name, ctype) in field_data:
                _fields_.append((name, ctype))
                size = max(size, ctypes.sizeof(ctype))
            if dtype.itemsize != size:
                _fields_.append(('', ctypes.c_char * dtype.itemsize))
            return type('union', (ctypes.Union,), dict(_fields_=_fields_, _pack_=1, __module__=None))
        else:
            last_offset = 0
            _fields_ = []
            for (offset, name, ctype) in field_data:
                padding = offset - last_offset
                if padding < 0:
                    raise NotImplementedError('Overlapping fields')
                if padding > 0:
                    _fields_.append(('', ctypes.c_char * padding))
                _fields_.append((name, ctype))
                last_offset = offset + ctypes.sizeof(ctype)
            padding = dtype.itemsize - last_offset
            if padding > 0:
                _fields_.append(('', ctypes.c_char * padding))
            return type('struct', (ctypes.Structure,), dict(_fields_=_fields_, _pack_=1, __module__=None))

    def _ctype_from_dtype(dtype):
        if dtype.fields is not None:
            return _ctype_from_dtype_structured(dtype)
        elif dtype.subdtype is not None:
            return _ctype_from_dtype_subarray(dtype)
        else:
            return _ctype_from_dtype_scalar(dtype)

    def as_ctypes_type(dtype):
        return _ctype_from_dtype(_dtype(dtype))

    def as_array(obj, shape=None):
        if isinstance(obj, ctypes._Pointer):
            if shape is None:
                raise TypeError('as_array() requires a shape argument when called on a pointer')
            p_arr_type = ctypes.POINTER(_ctype_ndarray(obj._type_, shape))
            obj = ctypes.cast(obj, p_arr_type).contents
        return asarray(obj)

    def as_ctypes(obj):
        ai = obj.__array_interface__
        if ai['strides']:
            raise TypeError('strided arrays not supported')
        if ai['version'] != 3:
            raise TypeError('only __array_interface__ version 3 supported')
        (addr, readonly) = ai['data']
        if readonly:
            raise TypeError('readonly arrays unsupported')
        ctype_scalar = as_ctypes_type(ai['typestr'])
        result_type = _ctype_ndarray(ctype_scalar, ai['shape'])
        result = result_type.from_address(addr)
        result.__keep = obj
        return result

# File: numpy-main/numpy/distutils/__init__.py
""""""
import warnings
from . import ccompiler
from . import unixccompiler
from .npy_pkg_config import *
warnings.warn('\n\n  `numpy.distutils` is deprecated since NumPy 1.23.0, as a result\n  of the deprecation of `distutils` itself. It will be removed for\n  Python >= 3.12. For older Python versions it will remain present.\n  It is recommended to use `setuptools < 60.0` for those Python versions.\n  For more details, see:\n    https://numpy.org/devdocs/reference/distutils_status_migration.html \n\n', DeprecationWarning, stacklevel=2)
del warnings
try:
    from . import __config__
    from numpy._pytesttester import PytestTester
    test = PytestTester(__name__)
    del PytestTester
except ImportError:
    pass

def customized_fcompiler(plat=None, compiler=None):
    from numpy.distutils.fcompiler import new_fcompiler
    c = new_fcompiler(plat=plat, compiler=compiler)
    c.customize()
    return c

def customized_ccompiler(plat=None, compiler=None, verbose=1):
    c = ccompiler.new_compiler(plat=plat, compiler=compiler, verbose=verbose)
    c.customize('')
    return c

# File: numpy-main/numpy/distutils/_shell_utils.py
""""""
import os
import shlex
import subprocess
__all__ = ['WindowsParser', 'PosixParser', 'NativeParser']

class CommandLineParser:

    @staticmethod
    def join(argv):
        raise NotImplementedError

    @staticmethod
    def split(cmd):
        raise NotImplementedError

class WindowsParser:

    @staticmethod
    def join(argv):
        return subprocess.list2cmdline(argv)

    @staticmethod
    def split(cmd):
        import ctypes
        try:
            ctypes.windll
        except AttributeError:
            raise NotImplementedError
        if not cmd:
            return []
        cmd = 'dummy ' + cmd
        CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
        CommandLineToArgvW.restype = ctypes.POINTER(ctypes.c_wchar_p)
        CommandLineToArgvW.argtypes = (ctypes.c_wchar_p, ctypes.POINTER(ctypes.c_int))
        nargs = ctypes.c_int()
        lpargs = CommandLineToArgvW(cmd, ctypes.byref(nargs))
        args = [lpargs[i] for i in range(nargs.value)]
        assert not ctypes.windll.kernel32.LocalFree(lpargs)
        assert args[0] == 'dummy'
        return args[1:]

class PosixParser:

    @staticmethod
    def join(argv):
        return ' '.join((shlex.quote(arg) for arg in argv))

    @staticmethod
    def split(cmd):
        return shlex.split(cmd, posix=True)
if os.name == 'nt':
    NativeParser = WindowsParser
elif os.name == 'posix':
    NativeParser = PosixParser

# File: numpy-main/numpy/distutils/armccompiler.py
from distutils.unixccompiler import UnixCCompiler

class ArmCCompiler(UnixCCompiler):
    compiler_type = 'arm'
    cc_exe = 'armclang'
    cxx_exe = 'armclang++'

    def __init__(self, verbose=0, dry_run=0, force=0):
        UnixCCompiler.__init__(self, verbose, dry_run, force)
        cc_compiler = self.cc_exe
        cxx_compiler = self.cxx_exe
        self.set_executables(compiler=cc_compiler + ' -O3 -fPIC', compiler_so=cc_compiler + ' -O3 -fPIC', compiler_cxx=cxx_compiler + ' -O3 -fPIC', linker_exe=cc_compiler + ' -lamath', linker_so=cc_compiler + ' -lamath -shared')

# File: numpy-main/numpy/distutils/ccompiler.py
import os
import re
import sys
import platform
import shlex
import time
import subprocess
from copy import copy
from pathlib import Path
from distutils import ccompiler
from distutils.ccompiler import compiler_class, gen_lib_options, get_default_compiler, new_compiler, CCompiler
from distutils.errors import DistutilsExecError, DistutilsModuleError, DistutilsPlatformError, CompileError, UnknownFileError
from distutils.sysconfig import customize_compiler
from distutils.version import LooseVersion
from numpy.distutils import log
from numpy.distutils.exec_command import filepath_from_subprocess_output, forward_bytes_to_stdout
from numpy.distutils.misc_util import cyg2win32, is_sequence, mingw32, get_num_build_jobs, _commandline_dep_string, sanitize_cxx_flags
import threading
_job_semaphore = None
_global_lock = threading.Lock()
_processing_files = set()

def _needs_build(obj, cc_args, extra_postargs, pp_opts):
    dep_file = obj + '.d'
    if not os.path.exists(dep_file):
        return True
    with open(dep_file) as f:
        lines = f.readlines()
    cmdline = _commandline_dep_string(cc_args, extra_postargs, pp_opts)
    last_cmdline = lines[-1]
    if last_cmdline != cmdline:
        return True
    contents = ''.join(lines[:-1])
    deps = [x for x in shlex.split(contents, posix=True) if x != '\n' and (not x.endswith(':'))]
    try:
        t_obj = os.stat(obj).st_mtime
        for f in deps:
            if os.stat(f).st_mtime > t_obj:
                return True
    except OSError:
        return True
    return False

def replace_method(klass, method_name, func):
    m = lambda self, *args, **kw: func(self, *args, **kw)
    setattr(klass, method_name, m)

def CCompiler_find_executables(self):
    pass
replace_method(CCompiler, 'find_executables', CCompiler_find_executables)

def CCompiler_spawn(self, cmd, display=None, env=None):
    env = env if env is not None else dict(os.environ)
    if display is None:
        display = cmd
        if is_sequence(display):
            display = ' '.join(list(display))
    log.info(display)
    try:
        if self.verbose:
            subprocess.check_output(cmd, env=env)
        else:
            subprocess.check_output(cmd, stderr=subprocess.STDOUT, env=env)
    except subprocess.CalledProcessError as exc:
        o = exc.output
        s = exc.returncode
    except OSError as e:
        o = f'\n\n{e}\n\n\n'
        try:
            o = o.encode(sys.stdout.encoding)
        except AttributeError:
            o = o.encode('utf8')
        s = 127
    else:
        return None
    if is_sequence(cmd):
        cmd = ' '.join(list(cmd))
    if self.verbose:
        forward_bytes_to_stdout(o)
    if re.search(b'Too many open files', o):
        msg = '\nTry rerunning setup command until build succeeds.'
    else:
        msg = ''
    raise DistutilsExecError('Command "%s" failed with exit status %d%s' % (cmd, s, msg))
replace_method(CCompiler, 'spawn', CCompiler_spawn)

def CCompiler_object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
    if output_dir is None:
        output_dir = ''
    obj_names = []
    for src_name in source_filenames:
        (base, ext) = os.path.splitext(os.path.normpath(src_name))
        base = os.path.splitdrive(base)[1]
        base = base[os.path.isabs(base):]
        if base.startswith('..'):
            i = base.rfind('..') + 2
            d = base[:i]
            d = os.path.basename(os.path.abspath(d))
            base = d + base[i:]
        if ext not in self.src_extensions:
            raise UnknownFileError("unknown file type '%s' (from '%s')" % (ext, src_name))
        if strip_dir:
            base = os.path.basename(base)
        obj_name = os.path.join(output_dir, base + self.obj_extension)
        obj_names.append(obj_name)
    return obj_names
replace_method(CCompiler, 'object_filenames', CCompiler_object_filenames)

def CCompiler_compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None):
    global _job_semaphore
    jobs = get_num_build_jobs()
    with _global_lock:
        if _job_semaphore is None:
            _job_semaphore = threading.Semaphore(jobs)
    if not sources:
        return []
    from numpy.distutils.fcompiler import FCompiler, FORTRAN_COMMON_FIXED_EXTENSIONS, has_f90_header
    if isinstance(self, FCompiler):
        display = []
        for fc in ['f77', 'f90', 'fix']:
            fcomp = getattr(self, 'compiler_' + fc)
            if fcomp is None:
                continue
            display.append('Fortran %s compiler: %s' % (fc, ' '.join(fcomp)))
        display = '\n'.join(display)
    else:
        ccomp = self.compiler_so
        display = 'C compiler: %s\n' % (' '.join(ccomp),)
    log.info(display)
    (macros, objects, extra_postargs, pp_opts, build) = self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs)
    cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
    display = "compile options: '%s'" % ' '.join(cc_args)
    if extra_postargs:
        display += "\nextra options: '%s'" % ' '.join(extra_postargs)
    log.info(display)

    def single_compile(args):
        (obj, (src, ext)) = args
        if not _needs_build(obj, cc_args, extra_postargs, pp_opts):
            return
        while True:
            with _global_lock:
                if obj not in _processing_files:
                    _processing_files.add(obj)
                    break
            time.sleep(0.1)
        try:
            with _job_semaphore:
                self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
        finally:
            with _global_lock:
                _processing_files.remove(obj)
    if isinstance(self, FCompiler):
        objects_to_build = list(build.keys())
        (f77_objects, other_objects) = ([], [])
        for obj in objects:
            if obj in objects_to_build:
                (src, ext) = build[obj]
                if self.compiler_type == 'absoft':
                    obj = cyg2win32(obj)
                    src = cyg2win32(src)
                if Path(src).suffix.lower() in FORTRAN_COMMON_FIXED_EXTENSIONS and (not has_f90_header(src)):
                    f77_objects.append((obj, (src, ext)))
                else:
                    other_objects.append((obj, (src, ext)))
        build_items = f77_objects
        for o in other_objects:
            single_compile(o)
    else:
        build_items = build.items()
    if len(build) > 1 and jobs > 1:
        from concurrent.futures import ThreadPoolExecutor
        with ThreadPoolExecutor(jobs) as pool:
            res = pool.map(single_compile, build_items)
        list(res)
    else:
        for o in build_items:
            single_compile(o)
    return objects
replace_method(CCompiler, 'compile', CCompiler_compile)

def CCompiler_customize_cmd(self, cmd, ignore=()):
    log.info('customize %s using %s' % (self.__class__.__name__, cmd.__class__.__name__))
    if hasattr(self, 'compiler') and 'clang' in self.compiler[0] and (not (platform.machine() == 'arm64' and sys.platform == 'darwin')):
        self.compiler.append('-ftrapping-math')
        self.compiler_so.append('-ftrapping-math')

    def allow(attr):
        return getattr(cmd, attr, None) is not None and attr not in ignore
    if allow('include_dirs'):
        self.set_include_dirs(cmd.include_dirs)
    if allow('define'):
        for (name, value) in cmd.define:
            self.define_macro(name, value)
    if allow('undef'):
        for macro in cmd.undef:
            self.undefine_macro(macro)
    if allow('libraries'):
        self.set_libraries(self.libraries + cmd.libraries)
    if allow('library_dirs'):
        self.set_library_dirs(self.library_dirs + cmd.library_dirs)
    if allow('rpath'):
        self.set_runtime_library_dirs(cmd.rpath)
    if allow('link_objects'):
        self.set_link_objects(cmd.link_objects)
replace_method(CCompiler, 'customize_cmd', CCompiler_customize_cmd)

def _compiler_to_string(compiler):
    props = []
    mx = 0
    keys = list(compiler.executables.keys())
    for key in ['version', 'libraries', 'library_dirs', 'object_switch', 'compile_switch', 'include_dirs', 'define', 'undef', 'rpath', 'link_objects']:
        if key not in keys:
            keys.append(key)
    for key in keys:
        if hasattr(compiler, key):
            v = getattr(compiler, key)
            mx = max(mx, len(key))
            props.append((key, repr(v)))
    fmt = '%-' + repr(mx + 1) + 's = %s'
    lines = [fmt % prop for prop in props]
    return '\n'.join(lines)

def CCompiler_show_customization(self):
    try:
        self.get_version()
    except Exception:
        pass
    if log._global_log.threshold < 2:
        print('*' * 80)
        print(self.__class__)
        print(_compiler_to_string(self))
        print('*' * 80)
replace_method(CCompiler, 'show_customization', CCompiler_show_customization)

def CCompiler_customize(self, dist, need_cxx=0):
    log.info('customize %s' % self.__class__.__name__)
    customize_compiler(self)
    if need_cxx:
        try:
            self.compiler_so.remove('-Wstrict-prototypes')
        except (AttributeError, ValueError):
            pass
        if hasattr(self, 'compiler') and 'cc' in self.compiler[0]:
            if not self.compiler_cxx:
                if self.compiler[0].startswith('gcc'):
                    (a, b) = ('gcc', 'g++')
                else:
                    (a, b) = ('cc', 'c++')
                self.compiler_cxx = [self.compiler[0].replace(a, b)] + self.compiler[1:]
        else:
            if hasattr(self, 'compiler'):
                log.warn('#### %s #######' % (self.compiler,))
            if not hasattr(self, 'compiler_cxx'):
                log.warn('Missing compiler_cxx fix for ' + self.__class__.__name__)
    if hasattr(self, 'compiler') and ('gcc' in self.compiler[0] or 'g++' in self.compiler[0] or 'clang' in self.compiler[0]):
        self._auto_depends = True
    elif os.name == 'posix':
        import tempfile
        import shutil
        tmpdir = tempfile.mkdtemp()
        try:
            fn = os.path.join(tmpdir, 'file.c')
            with open(fn, 'w') as f:
                f.write('int a;\n')
            self.compile([fn], output_dir=tmpdir, extra_preargs=['-MMD', '-MF', fn + '.d'])
            self._auto_depends = True
        except CompileError:
            self._auto_depends = False
        finally:
            shutil.rmtree(tmpdir)
    return
replace_method(CCompiler, 'customize', CCompiler_customize)

def simple_version_match(pat='[-.\\d]+', ignore='', start=''):

    def matcher(self, version_string):
        version_string = version_string.replace('\n', ' ')
        pos = 0
        if start:
            m = re.match(start, version_string)
            if not m:
                return None
            pos = m.end()
        while True:
            m = re.search(pat, version_string[pos:])
            if not m:
                return None
            if ignore and re.match(ignore, m.group(0)):
                pos = m.end()
                continue
            break
        return m.group(0)
    return matcher

def CCompiler_get_version(self, force=False, ok_status=[0]):
    if not force and hasattr(self, 'version'):
        return self.version
    self.find_executables()
    try:
        version_cmd = self.version_cmd
    except AttributeError:
        return None
    if not version_cmd or not version_cmd[0]:
        return None
    try:
        matcher = self.version_match
    except AttributeError:
        try:
            pat = self.version_pattern
        except AttributeError:
            return None

        def matcher(version_string):
            m = re.match(pat, version_string)
            if not m:
                return None
            version = m.group('version')
            return version
    try:
        output = subprocess.check_output(version_cmd, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as exc:
        output = exc.output
        status = exc.returncode
    except OSError:
        status = 127
        output = b''
    else:
        output = filepath_from_subprocess_output(output)
        status = 0
    version = None
    if status in ok_status:
        version = matcher(output)
        if version:
            version = LooseVersion(version)
    self.version = version
    return version
replace_method(CCompiler, 'get_version', CCompiler_get_version)

def CCompiler_cxx_compiler(self):
    if self.compiler_type in ('msvc', 'intelw', 'intelemw'):
        return self
    cxx = copy(self)
    cxx.compiler_cxx = cxx.compiler_cxx
    cxx.compiler_so = [cxx.compiler_cxx[0]] + sanitize_cxx_flags(cxx.compiler_so[1:])
    if sys.platform.startswith(('aix', 'os400')) and 'ld_so_aix' in cxx.linker_so[0]:
        cxx.linker_so = [cxx.linker_so[0], cxx.compiler_cxx[0]] + cxx.linker_so[2:]
    if sys.platform.startswith('os400'):
        cxx.compiler_so.append('-D__STDC_FORMAT_MACROS')
        cxx.compiler_so.append('-fno-extern-tls-init')
        cxx.linker_so.append('-fno-extern-tls-init')
    else:
        cxx.linker_so = [cxx.compiler_cxx[0]] + cxx.linker_so[1:]
    return cxx
replace_method(CCompiler, 'cxx_compiler', CCompiler_cxx_compiler)
compiler_class['intel'] = ('intelccompiler', 'IntelCCompiler', 'Intel C Compiler for 32-bit applications')
compiler_class['intele'] = ('intelccompiler', 'IntelItaniumCCompiler', 'Intel C Itanium Compiler for Itanium-based applications')
compiler_class['intelem'] = ('intelccompiler', 'IntelEM64TCCompiler', 'Intel C Compiler for 64-bit applications')
compiler_class['intelw'] = ('intelccompiler', 'IntelCCompilerW', 'Intel C Compiler for 32-bit applications on Windows')
compiler_class['intelemw'] = ('intelccompiler', 'IntelEM64TCCompilerW', 'Intel C Compiler for 64-bit applications on Windows')
compiler_class['pathcc'] = ('pathccompiler', 'PathScaleCCompiler', 'PathScale Compiler for SiCortex-based applications')
compiler_class['arm'] = ('armccompiler', 'ArmCCompiler', 'Arm C Compiler')
compiler_class['fujitsu'] = ('fujitsuccompiler', 'FujitsuCCompiler', 'Fujitsu C Compiler')
ccompiler._default_compilers += (('linux.*', 'intel'), ('linux.*', 'intele'), ('linux.*', 'intelem'), ('linux.*', 'pathcc'), ('nt', 'intelw'), ('nt', 'intelemw'))
if sys.platform == 'win32':
    compiler_class['mingw32'] = ('mingw32ccompiler', 'Mingw32CCompiler', 'Mingw32 port of GNU C Compiler for Win32(for MSC built Python)')
    if mingw32():
        log.info('Setting mingw32 as default compiler for nt.')
        ccompiler._default_compilers = (('nt', 'mingw32'),) + ccompiler._default_compilers
_distutils_new_compiler = new_compiler

def new_compiler(plat=None, compiler=None, verbose=None, dry_run=0, force=0):
    if verbose is None:
        verbose = log.get_threshold() <= log.INFO
    if plat is None:
        plat = os.name
    try:
        if compiler is None:
            compiler = get_default_compiler(plat)
        (module_name, class_name, long_description) = compiler_class[compiler]
    except KeyError:
        msg = "don't know how to compile C/C++ code on platform '%s'" % plat
        if compiler is not None:
            msg = msg + " with '%s' compiler" % compiler
        raise DistutilsPlatformError(msg)
    module_name = 'numpy.distutils.' + module_name
    try:
        __import__(module_name)
    except ImportError as e:
        msg = str(e)
        log.info('%s in numpy.distutils; trying from distutils', str(msg))
        module_name = module_name[6:]
        try:
            __import__(module_name)
        except ImportError as e:
            msg = str(e)
            raise DistutilsModuleError("can't compile C/C++ code: unable to load module '%s'" % module_name)
    try:
        module = sys.modules[module_name]
        klass = vars(module)[class_name]
    except KeyError:
        raise DistutilsModuleError(("can't compile C/C++ code: unable to find class '%s' " + "in module '%s'") % (class_name, module_name))
    compiler = klass(None, dry_run, force)
    compiler.verbose = verbose
    log.debug('new_compiler returns %s' % klass)
    return compiler
ccompiler.new_compiler = new_compiler
_distutils_gen_lib_options = gen_lib_options

def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
    r = _distutils_gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries)
    lib_opts = []
    for i in r:
        if is_sequence(i):
            lib_opts.extend(list(i))
        else:
            lib_opts.append(i)
    return lib_opts
ccompiler.gen_lib_options = gen_lib_options
for _cc in ['msvc9', 'msvc', '_msvc', 'bcpp', 'cygwinc', 'emxc', 'unixc']:
    _m = sys.modules.get('distutils.' + _cc + 'compiler')
    if _m is not None:
        setattr(_m, 'gen_lib_options', gen_lib_options)

# File: numpy-main/numpy/distutils/ccompiler_opt.py
""""""
import atexit
import inspect
import os
import pprint
import re
import subprocess
import textwrap

class _Config:
    conf_nocache = False
    conf_noopt = False
    conf_cache_factors = None
    conf_tmp_path = None
    conf_check_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'checks')
    conf_target_groups = {}
    conf_c_prefix = 'NPY_'
    conf_c_prefix_ = 'NPY__'
    conf_cc_flags = dict(gcc=dict(native='-march=native', opt='-O3', werror='-Werror'), clang=dict(native='-march=native', opt='-O3', werror='-Werror=switch -Werror'), icc=dict(native='-xHost', opt='-O3', werror='-Werror'), iccw=dict(native='/QxHost', opt='/O3', werror='/Werror'), msvc=dict(native=None, opt='/O2', werror='/WX'), fcc=dict(native='-mcpu=a64fx', opt=None, werror=None))
    conf_min_features = dict(x86='SSE SSE2', x64='SSE SSE2 SSE3', ppc64='', ppc64le='VSX VSX2', s390x='', armhf='', aarch64='NEON NEON_FP16 NEON_VFPV4 ASIMD')
    conf_features = dict(SSE=dict(interest=1, headers='xmmintrin.h', implies='SSE2'), SSE2=dict(interest=2, implies='SSE', headers='emmintrin.h'), SSE3=dict(interest=3, implies='SSE2', headers='pmmintrin.h'), SSSE3=dict(interest=4, implies='SSE3', headers='tmmintrin.h'), SSE41=dict(interest=5, implies='SSSE3', headers='smmintrin.h'), POPCNT=dict(interest=6, implies='SSE41', headers='popcntintrin.h'), SSE42=dict(interest=7, implies='POPCNT'), AVX=dict(interest=8, implies='SSE42', headers='immintrin.h', implies_detect=False), XOP=dict(interest=9, implies='AVX', headers='x86intrin.h'), FMA4=dict(interest=10, implies='AVX', headers='x86intrin.h'), F16C=dict(interest=11, implies='AVX'), FMA3=dict(interest=12, implies='F16C'), AVX2=dict(interest=13, implies='F16C'), AVX512F=dict(interest=20, implies='FMA3 AVX2', implies_detect=False, extra_checks='AVX512F_REDUCE'), AVX512CD=dict(interest=21, implies='AVX512F'), AVX512_KNL=dict(interest=40, implies='AVX512CD', group='AVX512ER AVX512PF', detect='AVX512_KNL', implies_detect=False), AVX512_KNM=dict(interest=41, implies='AVX512_KNL', group='AVX5124FMAPS AVX5124VNNIW AVX512VPOPCNTDQ', detect='AVX512_KNM', implies_detect=False), AVX512_SKX=dict(interest=42, implies='AVX512CD', group='AVX512VL AVX512BW AVX512DQ', detect='AVX512_SKX', implies_detect=False, extra_checks='AVX512BW_MASK AVX512DQ_MASK'), AVX512_CLX=dict(interest=43, implies='AVX512_SKX', group='AVX512VNNI', detect='AVX512_CLX'), AVX512_CNL=dict(interest=44, implies='AVX512_SKX', group='AVX512IFMA AVX512VBMI', detect='AVX512_CNL', implies_detect=False), AVX512_ICL=dict(interest=45, implies='AVX512_CLX AVX512_CNL', group='AVX512VBMI2 AVX512BITALG AVX512VPOPCNTDQ', detect='AVX512_ICL', implies_detect=False), AVX512_SPR=dict(interest=46, implies='AVX512_ICL', group='AVX512FP16', detect='AVX512_SPR', implies_detect=False), VSX=dict(interest=1, headers='altivec.h', extra_checks='VSX_ASM'), VSX2=dict(interest=2, implies='VSX', implies_detect=False), VSX3=dict(interest=3, implies='VSX2', implies_detect=False, extra_checks='VSX3_HALF_DOUBLE'), VSX4=dict(interest=4, implies='VSX3', implies_detect=False, extra_checks='VSX4_MMA'), VX=dict(interest=1, headers='vecintrin.h'), VXE=dict(interest=2, implies='VX', implies_detect=False), VXE2=dict(interest=3, implies='VXE', implies_detect=False), NEON=dict(interest=1, headers='arm_neon.h'), NEON_FP16=dict(interest=2, implies='NEON'), NEON_VFPV4=dict(interest=3, implies='NEON_FP16'), ASIMD=dict(interest=4, implies='NEON_FP16 NEON_VFPV4', implies_detect=False), ASIMDHP=dict(interest=5, implies='ASIMD'), ASIMDDP=dict(interest=6, implies='ASIMD'), ASIMDFHM=dict(interest=7, implies='ASIMDHP'))

    def conf_features_partial(self):
        if self.cc_noopt:
            return {}
        on_x86 = self.cc_on_x86 or self.cc_on_x64
        is_unix = self.cc_is_gcc or self.cc_is_clang or self.cc_is_fcc
        if on_x86 and is_unix:
            return dict(SSE=dict(flags='-msse'), SSE2=dict(flags='-msse2'), SSE3=dict(flags='-msse3'), SSSE3=dict(flags='-mssse3'), SSE41=dict(flags='-msse4.1'), POPCNT=dict(flags='-mpopcnt'), SSE42=dict(flags='-msse4.2'), AVX=dict(flags='-mavx'), F16C=dict(flags='-mf16c'), XOP=dict(flags='-mxop'), FMA4=dict(flags='-mfma4'), FMA3=dict(flags='-mfma'), AVX2=dict(flags='-mavx2'), AVX512F=dict(flags='-mavx512f -mno-mmx'), AVX512CD=dict(flags='-mavx512cd'), AVX512_KNL=dict(flags='-mavx512er -mavx512pf'), AVX512_KNM=dict(flags='-mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdq'), AVX512_SKX=dict(flags='-mavx512vl -mavx512bw -mavx512dq'), AVX512_CLX=dict(flags='-mavx512vnni'), AVX512_CNL=dict(flags='-mavx512ifma -mavx512vbmi'), AVX512_ICL=dict(flags='-mavx512vbmi2 -mavx512bitalg -mavx512vpopcntdq'), AVX512_SPR=dict(flags='-mavx512fp16'))
        if on_x86 and self.cc_is_icc:
            return dict(SSE=dict(flags='-msse'), SSE2=dict(flags='-msse2'), SSE3=dict(flags='-msse3'), SSSE3=dict(flags='-mssse3'), SSE41=dict(flags='-msse4.1'), POPCNT={}, SSE42=dict(flags='-msse4.2'), AVX=dict(flags='-mavx'), F16C={}, XOP=dict(disable="Intel Compiler doesn't support it"), FMA4=dict(disable="Intel Compiler doesn't support it"), FMA3=dict(implies='F16C AVX2', flags='-march=core-avx2'), AVX2=dict(implies='FMA3', flags='-march=core-avx2'), AVX512F=dict(implies='AVX2 AVX512CD', flags='-march=common-avx512'), AVX512CD=dict(implies='AVX2 AVX512F', flags='-march=common-avx512'), AVX512_KNL=dict(flags='-xKNL'), AVX512_KNM=dict(flags='-xKNM'), AVX512_SKX=dict(flags='-xSKYLAKE-AVX512'), AVX512_CLX=dict(flags='-xCASCADELAKE'), AVX512_CNL=dict(flags='-xCANNONLAKE'), AVX512_ICL=dict(flags='-xICELAKE-CLIENT'), AVX512_SPR=dict(disable='Not supported yet'))
        if on_x86 and self.cc_is_iccw:
            return dict(SSE=dict(flags='/arch:SSE'), SSE2=dict(flags='/arch:SSE2'), SSE3=dict(flags='/arch:SSE3'), SSSE3=dict(flags='/arch:SSSE3'), SSE41=dict(flags='/arch:SSE4.1'), POPCNT={}, SSE42=dict(flags='/arch:SSE4.2'), AVX=dict(flags='/arch:AVX'), F16C={}, XOP=dict(disable="Intel Compiler doesn't support it"), FMA4=dict(disable="Intel Compiler doesn't support it"), FMA3=dict(implies='F16C AVX2', flags='/arch:CORE-AVX2'), AVX2=dict(implies='FMA3', flags='/arch:CORE-AVX2'), AVX512F=dict(implies='AVX2 AVX512CD', flags='/Qx:COMMON-AVX512'), AVX512CD=dict(implies='AVX2 AVX512F', flags='/Qx:COMMON-AVX512'), AVX512_KNL=dict(flags='/Qx:KNL'), AVX512_KNM=dict(flags='/Qx:KNM'), AVX512_SKX=dict(flags='/Qx:SKYLAKE-AVX512'), AVX512_CLX=dict(flags='/Qx:CASCADELAKE'), AVX512_CNL=dict(flags='/Qx:CANNONLAKE'), AVX512_ICL=dict(flags='/Qx:ICELAKE-CLIENT'), AVX512_SPR=dict(disable='Not supported yet'))
        if on_x86 and self.cc_is_msvc:
            return dict(SSE=dict(flags='/arch:SSE') if self.cc_on_x86 else {}, SSE2=dict(flags='/arch:SSE2') if self.cc_on_x86 else {}, SSE3={}, SSSE3={}, SSE41={}, POPCNT=dict(headers='nmmintrin.h'), SSE42={}, AVX=dict(flags='/arch:AVX'), F16C={}, XOP=dict(headers='ammintrin.h'), FMA4=dict(headers='ammintrin.h'), FMA3=dict(implies='F16C AVX2', flags='/arch:AVX2'), AVX2=dict(implies='F16C FMA3', flags='/arch:AVX2'), AVX512F=dict(implies='AVX2 AVX512CD AVX512_SKX', flags='/arch:AVX512'), AVX512CD=dict(implies='AVX512F AVX512_SKX', flags='/arch:AVX512'), AVX512_KNL=dict(disable="MSVC compiler doesn't support it"), AVX512_KNM=dict(disable="MSVC compiler doesn't support it"), AVX512_SKX=dict(flags='/arch:AVX512'), AVX512_CLX={}, AVX512_CNL={}, AVX512_ICL={}, AVX512_SPR=dict(disable="MSVC compiler doesn't support it"))
        on_power = self.cc_on_ppc64le or self.cc_on_ppc64
        if on_power:
            partial = dict(VSX=dict(implies='VSX2' if self.cc_on_ppc64le else '', flags='-mvsx'), VSX2=dict(flags='-mcpu=power8', implies_detect=False), VSX3=dict(flags='-mcpu=power9 -mtune=power9', implies_detect=False), VSX4=dict(flags='-mcpu=power10 -mtune=power10', implies_detect=False))
            if self.cc_is_clang:
                partial['VSX']['flags'] = '-maltivec -mvsx'
                partial['VSX2']['flags'] = '-mcpu=power8'
                partial['VSX3']['flags'] = '-mcpu=power9'
                partial['VSX4']['flags'] = '-mcpu=power10'
            return partial
        on_zarch = self.cc_on_s390x
        if on_zarch:
            partial = dict(VX=dict(flags='-march=arch11 -mzvector'), VXE=dict(flags='-march=arch12', implies_detect=False), VXE2=dict(flags='-march=arch13', implies_detect=False))
            return partial
        if self.cc_on_aarch64 and is_unix:
            return dict(NEON=dict(implies='NEON_FP16 NEON_VFPV4 ASIMD', autovec=True), NEON_FP16=dict(implies='NEON NEON_VFPV4 ASIMD', autovec=True), NEON_VFPV4=dict(implies='NEON NEON_FP16 ASIMD', autovec=True), ASIMD=dict(implies='NEON NEON_FP16 NEON_VFPV4', autovec=True), ASIMDHP=dict(flags='-march=armv8.2-a+fp16'), ASIMDDP=dict(flags='-march=armv8.2-a+dotprod'), ASIMDFHM=dict(flags='-march=armv8.2-a+fp16fml'))
        if self.cc_on_armhf and is_unix:
            return dict(NEON=dict(flags='-mfpu=neon'), NEON_FP16=dict(flags='-mfpu=neon-fp16 -mfp16-format=ieee'), NEON_VFPV4=dict(flags='-mfpu=neon-vfpv4'), ASIMD=dict(flags='-mfpu=neon-fp-armv8 -march=armv8-a+simd'), ASIMDHP=dict(flags='-march=armv8.2-a+fp16'), ASIMDDP=dict(flags='-march=armv8.2-a+dotprod'), ASIMDFHM=dict(flags='-march=armv8.2-a+fp16fml'))
        return {}

    def __init__(self):
        if self.conf_tmp_path is None:
            import shutil
            import tempfile
            tmp = tempfile.mkdtemp()

            def rm_temp():
                try:
                    shutil.rmtree(tmp)
                except OSError:
                    pass
            atexit.register(rm_temp)
            self.conf_tmp_path = tmp
        if self.conf_cache_factors is None:
            self.conf_cache_factors = [os.path.getmtime(__file__), self.conf_nocache]

class _Distutils:

    def __init__(self, ccompiler):
        self._ccompiler = ccompiler

    def dist_compile(self, sources, flags, ccompiler=None, **kwargs):
        assert isinstance(sources, list)
        assert isinstance(flags, list)
        flags = kwargs.pop('extra_postargs', []) + flags
        if not ccompiler:
            ccompiler = self._ccompiler
        return ccompiler.compile(sources, extra_postargs=flags, **kwargs)

    def dist_test(self, source, flags, macros=[]):
        assert isinstance(source, str)
        from distutils.errors import CompileError
        cc = self._ccompiler
        bk_spawn = getattr(cc, 'spawn', None)
        if bk_spawn:
            cc_type = getattr(self._ccompiler, 'compiler_type', '')
            if cc_type in ('msvc',):
                setattr(cc, 'spawn', self._dist_test_spawn_paths)
            else:
                setattr(cc, 'spawn', self._dist_test_spawn)
        test = False
        try:
            self.dist_compile([source], flags, macros=macros, output_dir=self.conf_tmp_path)
            test = True
        except CompileError as e:
            self.dist_log(str(e), stderr=True)
        if bk_spawn:
            setattr(cc, 'spawn', bk_spawn)
        return test

    def dist_info(self):
        if hasattr(self, '_dist_info'):
            return self._dist_info
        cc_type = getattr(self._ccompiler, 'compiler_type', '')
        if cc_type in ('intelem', 'intelemw'):
            platform = 'x86_64'
        elif cc_type in ('intel', 'intelw', 'intele'):
            platform = 'x86'
        else:
            from distutils.util import get_platform
            platform = get_platform()
        cc_info = getattr(self._ccompiler, 'compiler', getattr(self._ccompiler, 'compiler_so', ''))
        if not cc_type or cc_type == 'unix':
            if hasattr(cc_info, '__iter__'):
                compiler = cc_info[0]
            else:
                compiler = str(cc_info)
        else:
            compiler = cc_type
        if hasattr(cc_info, '__iter__') and len(cc_info) > 1:
            extra_args = ' '.join(cc_info[1:])
        else:
            extra_args = os.environ.get('CFLAGS', '')
            extra_args += os.environ.get('CPPFLAGS', '')
        self._dist_info = (platform, compiler, extra_args)
        return self._dist_info

    @staticmethod
    def dist_error(*args):
        from distutils.errors import CompileError
        raise CompileError(_Distutils._dist_str(*args))

    @staticmethod
    def dist_fatal(*args):
        from distutils.errors import DistutilsError
        raise DistutilsError(_Distutils._dist_str(*args))

    @staticmethod
    def dist_log(*args, stderr=False):
        from numpy.distutils import log
        out = _Distutils._dist_str(*args)
        if stderr:
            log.warn(out)
        else:
            log.info(out)

    @staticmethod
    def dist_load_module(name, path):
        from .misc_util import exec_mod_from_location
        try:
            return exec_mod_from_location(name, path)
        except Exception as e:
            _Distutils.dist_log(e, stderr=True)
        return None

    @staticmethod
    def _dist_str(*args):

        def to_str(arg):
            if not isinstance(arg, str) and hasattr(arg, '__iter__'):
                ret = []
                for a in arg:
                    ret.append(to_str(a))
                return '(' + ' '.join(ret) + ')'
            return str(arg)
        stack = inspect.stack()[2]
        start = 'CCompilerOpt.%s[%d] : ' % (stack.function, stack.lineno)
        out = ' '.join([to_str(a) for a in (*args,)])
        return start + out

    def _dist_test_spawn_paths(self, cmd, display=None):
        if not hasattr(self._ccompiler, '_paths'):
            self._dist_test_spawn(cmd)
            return
        old_path = os.getenv('path')
        try:
            os.environ['path'] = self._ccompiler._paths
            self._dist_test_spawn(cmd)
        finally:
            os.environ['path'] = old_path
    _dist_warn_regex = re.compile('.*(warning D9002|invalid argument for option).*')

    @staticmethod
    def _dist_test_spawn(cmd, display=None):
        try:
            o = subprocess.check_output(cmd, stderr=subprocess.STDOUT, text=True)
            if o and re.match(_Distutils._dist_warn_regex, o):
                _Distutils.dist_error('Flags in command', cmd, "aren't supported by the compiler, output -> \n%s" % o)
        except subprocess.CalledProcessError as exc:
            o = exc.output
            s = exc.returncode
        except OSError as e:
            o = e
            s = 127
        else:
            return None
        _Distutils.dist_error('Command', cmd, 'failed with exit status %d output -> \n%s' % (s, o))
_share_cache = {}

class _Cache:
    _cache_ignore = re.compile('^(_|conf_)')

    def __init__(self, cache_path=None, *factors):
        self.cache_me = {}
        self.cache_private = set()
        self.cache_infile = False
        self._cache_path = None
        if self.conf_nocache:
            self.dist_log('cache is disabled by `Config`')
            return
        self._cache_hash = self.cache_hash(*factors, *self.conf_cache_factors)
        self._cache_path = cache_path
        if cache_path:
            if os.path.exists(cache_path):
                self.dist_log('load cache from file ->', cache_path)
                cache_mod = self.dist_load_module('cache', cache_path)
                if not cache_mod:
                    self.dist_log('unable to load the cache file as a module', stderr=True)
                elif not hasattr(cache_mod, 'hash') or not hasattr(cache_mod, 'data'):
                    self.dist_log('invalid cache file', stderr=True)
                elif self._cache_hash == cache_mod.hash:
                    self.dist_log('hit the file cache')
                    for (attr, val) in cache_mod.data.items():
                        setattr(self, attr, val)
                    self.cache_infile = True
                else:
                    self.dist_log('miss the file cache')
        if not self.cache_infile:
            other_cache = _share_cache.get(self._cache_hash)
            if other_cache:
                self.dist_log('hit the memory cache')
                for (attr, val) in other_cache.__dict__.items():
                    if attr in other_cache.cache_private or re.match(self._cache_ignore, attr):
                        continue
                    setattr(self, attr, val)
        _share_cache[self._cache_hash] = self
        atexit.register(self.cache_flush)

    def __del__(self):
        for (h, o) in _share_cache.items():
            if o == self:
                _share_cache.pop(h)
                break

    def cache_flush(self):
        if not self._cache_path:
            return
        self.dist_log('write cache to path ->', self._cache_path)
        cdict = self.__dict__.copy()
        for attr in self.__dict__.keys():
            if re.match(self._cache_ignore, attr):
                cdict.pop(attr)
        d = os.path.dirname(self._cache_path)
        if not os.path.exists(d):
            os.makedirs(d)
        repr_dict = pprint.pformat(cdict, compact=True)
        with open(self._cache_path, 'w') as f:
            f.write(textwrap.dedent("            # AUTOGENERATED DON'T EDIT\n            # Please make changes to the code generator             (distutils/ccompiler_opt.py)\n            hash = {}\n            data = \\\n            ").format(self._cache_hash))
            f.write(repr_dict)

    def cache_hash(self, *factors):
        chash = 0
        for f in factors:
            for char in str(f):
                chash = ord(char) + (chash << 6) + (chash << 16) - chash
                chash &= 4294967295
        return chash

    @staticmethod
    def me(cb):

        def cache_wrap_me(self, *args, **kwargs):
            cache_key = str((cb.__name__, *args, *kwargs.keys(), *kwargs.values()))
            if cache_key in self.cache_me:
                return self.cache_me[cache_key]
            ccb = cb(self, *args, **kwargs)
            self.cache_me[cache_key] = ccb
            return ccb
        return cache_wrap_me

class _CCompiler:

    def __init__(self):
        if hasattr(self, 'cc_is_cached'):
            return
        detect_arch = (('cc_on_x64', '.*(x|x86_|amd)64.*', ''), ('cc_on_x86', '.*(win32|x86|i386|i686).*', ''), ('cc_on_ppc64le', '.*(powerpc|ppc)64(el|le).*|.*powerpc.*', 'defined(__powerpc64__) && defined(__LITTLE_ENDIAN__)'), ('cc_on_ppc64', '.*(powerpc|ppc).*|.*powerpc.*', 'defined(__powerpc64__) && defined(__BIG_ENDIAN__)'), ('cc_on_aarch64', '.*(aarch64|arm64).*', ''), ('cc_on_armhf', '.*arm.*', 'defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__)'), ('cc_on_s390x', '.*s390x.*', ''), ('cc_on_noarch', '', ''))
        detect_compiler = (('cc_is_gcc', '.*(gcc|gnu\\-g).*', ''), ('cc_is_clang', '.*clang.*', ''), ('cc_is_iccw', '.*(intelw|intelemw|iccw).*', ''), ('cc_is_icc', '.*(intel|icc).*', ''), ('cc_is_msvc', '.*msvc.*', ''), ('cc_is_fcc', '.*fcc.*', ''), ('cc_is_nocc', '', ''))
        detect_args = (('cc_has_debug', '.*(O0|Od|ggdb|coverage|debug:full).*', ''), ('cc_has_native', '.*(-march=native|-xHost|/QxHost|-mcpu=a64fx).*', ''), ('cc_noopt', '.*DISABLE_OPT.*', ''))
        dist_info = self.dist_info()
        (platform, compiler_info, extra_args) = dist_info
        for section in (detect_arch, detect_compiler, detect_args):
            for (attr, rgex, cexpr) in section:
                setattr(self, attr, False)
        for (detect, searchin) in ((detect_arch, platform), (detect_compiler, compiler_info)):
            for (attr, rgex, cexpr) in detect:
                if rgex and (not re.match(rgex, searchin, re.IGNORECASE)):
                    continue
                if cexpr and (not self.cc_test_cexpr(cexpr)):
                    continue
                setattr(self, attr, True)
                break
        for (attr, rgex, cexpr) in detect_args:
            if rgex and (not re.match(rgex, extra_args, re.IGNORECASE)):
                continue
            if cexpr and (not self.cc_test_cexpr(cexpr)):
                continue
            setattr(self, attr, True)
        if self.cc_on_noarch:
            self.dist_log(f'unable to detect CPU architecture which lead to disable the optimization. check dist_info:<<\n{dist_info}\n>>', stderr=True)
            self.cc_noopt = True
        if self.conf_noopt:
            self.dist_log('Optimization is disabled by the Config', stderr=True)
            self.cc_noopt = True
        if self.cc_is_nocc:
            ''
            self.dist_log(f"unable to detect compiler type which leads to treating it as GCC. this is a normal behavior if you're using gcc-like compiler such as MinGW or IBM/XLC.check dist_info:<<\n{dist_info}\n>>", stderr=True)
            self.cc_is_gcc = True
        self.cc_march = 'unknown'
        for arch in ('x86', 'x64', 'ppc64', 'ppc64le', 'armhf', 'aarch64', 's390x'):
            if getattr(self, 'cc_on_' + arch):
                self.cc_march = arch
                break
        self.cc_name = 'unknown'
        for name in ('gcc', 'clang', 'iccw', 'icc', 'msvc', 'fcc'):
            if getattr(self, 'cc_is_' + name):
                self.cc_name = name
                break
        self.cc_flags = {}
        compiler_flags = self.conf_cc_flags.get(self.cc_name)
        if compiler_flags is None:
            self.dist_fatal("undefined flag for compiler '%s', leave an empty dict instead" % self.cc_name)
        for (name, flags) in compiler_flags.items():
            self.cc_flags[name] = nflags = []
            if flags:
                assert isinstance(flags, str)
                flags = flags.split()
                for f in flags:
                    if self.cc_test_flags([f]):
                        nflags.append(f)
        self.cc_is_cached = True

    @_Cache.me
    def cc_test_flags(self, flags):
        assert isinstance(flags, list)
        self.dist_log('testing flags', flags)
        test_path = os.path.join(self.conf_check_path, 'test_flags.c')
        test = self.dist_test(test_path, flags)
        if not test:
            self.dist_log('testing failed', stderr=True)
        return test

    @_Cache.me
    def cc_test_cexpr(self, cexpr, flags=[]):
        self.dist_log('testing compiler expression', cexpr)
        test_path = os.path.join(self.conf_tmp_path, 'npy_dist_test_cexpr.c')
        with open(test_path, 'w') as fd:
            fd.write(textwrap.dedent(f'               #if !({cexpr})\n                   #error "unsupported expression"\n               #endif\n               int dummy;\n            '))
        test = self.dist_test(test_path, flags)
        if not test:
            self.dist_log('testing failed', stderr=True)
        return test

    def cc_normalize_flags(self, flags):
        assert isinstance(flags, list)
        if self.cc_is_gcc or self.cc_is_clang or self.cc_is_icc:
            return self._cc_normalize_unix(flags)
        if self.cc_is_msvc or self.cc_is_iccw:
            return self._cc_normalize_win(flags)
        return flags
    _cc_normalize_unix_mrgx = re.compile('^(-mcpu=|-march=|-x[A-Z0-9\\-])')
    _cc_normalize_unix_frgx = re.compile('^(?!(-mcpu=|-march=|-x[A-Z0-9\\-]|-m[a-z0-9\\-\\.]*.$))|(?:-mzvector)')
    _cc_normalize_unix_krgx = re.compile('^(-mfpu|-mtune)')
    _cc_normalize_arch_ver = re.compile('[0-9.]')

    def _cc_normalize_unix(self, flags):

        def ver_flags(f):
            tokens = f.split('+')
            ver = float('0' + ''.join(re.findall(self._cc_normalize_arch_ver, tokens[0])))
            return (ver, tokens[0], tokens[1:])
        if len(flags) <= 1:
            return flags
        for (i, cur_flag) in enumerate(reversed(flags)):
            if not re.match(self._cc_normalize_unix_mrgx, cur_flag):
                continue
            lower_flags = flags[:-(i + 1)]
            upper_flags = flags[-i:]
            filtered = list(filter(self._cc_normalize_unix_frgx.search, lower_flags))
            (ver, arch, subflags) = ver_flags(cur_flag)
            if ver > 0 and len(subflags) > 0:
                for xflag in lower_flags:
                    (xver, _, xsubflags) = ver_flags(xflag)
                    if ver == xver:
                        subflags = xsubflags + subflags
                cur_flag = arch + '+' + '+'.join(subflags)
            flags = filtered + [cur_flag]
            if i > 0:
                flags += upper_flags
            break
        final_flags = []
        matched = set()
        for f in reversed(flags):
            match = re.match(self._cc_normalize_unix_krgx, f)
            if not match:
                pass
            elif match[0] in matched:
                continue
            else:
                matched.add(match[0])
            final_flags.insert(0, f)
        return final_flags
    _cc_normalize_win_frgx = re.compile('^(?!(/arch\\:|/Qx\\:))')
    _cc_normalize_win_mrgx = re.compile('^(/arch|/Qx:)')

    def _cc_normalize_win(self, flags):
        for (i, f) in enumerate(reversed(flags)):
            if not re.match(self._cc_normalize_win_mrgx, f):
                continue
            i += 1
            return list(filter(self._cc_normalize_win_frgx.search, flags[:-i])) + flags[-i:]
        return flags

class _Feature:

    def __init__(self):
        if hasattr(self, 'feature_is_cached'):
            return
        self.feature_supported = pfeatures = self.conf_features_partial()
        for feature_name in list(pfeatures.keys()):
            feature = pfeatures[feature_name]
            cfeature = self.conf_features[feature_name]
            feature.update({k: v for (k, v) in cfeature.items() if k not in feature})
            disabled = feature.get('disable')
            if disabled is not None:
                pfeatures.pop(feature_name)
                self.dist_log("feature '%s' is disabled," % feature_name, disabled, stderr=True)
                continue
            for option in ('implies', 'group', 'detect', 'headers', 'flags', 'extra_checks'):
                oval = feature.get(option)
                if isinstance(oval, str):
                    feature[option] = oval.split()
        self.feature_min = set()
        min_f = self.conf_min_features.get(self.cc_march, '')
        for F in min_f.upper().split():
            if F in self.feature_supported:
                self.feature_min.add(F)
        self.feature_is_cached = True

    def feature_names(self, names=None, force_flags=None, macros=[]):
        assert names is None or (not isinstance(names, str) and hasattr(names, '__iter__'))
        assert force_flags is None or isinstance(force_flags, list)
        if names is None:
            names = self.feature_supported.keys()
        supported_names = set()
        for f in names:
            if self.feature_is_supported(f, force_flags=force_flags, macros=macros):
                supported_names.add(f)
        return supported_names

    def feature_is_exist(self, name):
        assert name.isupper()
        return name in self.conf_features

    def feature_sorted(self, names, reverse=False):

        def sort_cb(k):
            if isinstance(k, str):
                return self.feature_supported[k]['interest']
            rank = max([self.feature_supported[f]['interest'] for f in k])
            rank += len(k) - 1
            return rank
        return sorted(names, reverse=reverse, key=sort_cb)

    def feature_implies(self, names, keep_origins=False):

        def get_implies(name, _caller=set()):
            implies = set()
            d = self.feature_supported[name]
            for i in d.get('implies', []):
                implies.add(i)
                if i in _caller:
                    continue
                _caller.add(name)
                implies = implies.union(get_implies(i, _caller))
            return implies
        if isinstance(names, str):
            implies = get_implies(names)
            names = [names]
        else:
            assert hasattr(names, '__iter__')
            implies = set()
            for n in names:
                implies = implies.union(get_implies(n))
        if not keep_origins:
            implies.difference_update(names)
        return implies

    def feature_implies_c(self, names):
        if isinstance(names, str):
            names = set((names,))
        else:
            names = set(names)
        return names.union(self.feature_implies(names))

    def feature_ahead(self, names):
        assert not isinstance(names, str) and hasattr(names, '__iter__')
        implies = self.feature_implies(names, keep_origins=True)
        ahead = [n for n in names if n not in implies]
        if len(ahead) == 0:
            ahead = self.feature_sorted(names, reverse=True)[:1]
        return ahead

    def feature_untied(self, names):
        assert not isinstance(names, str) and hasattr(names, '__iter__')
        final = []
        for n in names:
            implies = self.feature_implies(n)
            tied = [nn for nn in final if nn in implies and n in self.feature_implies(nn)]
            if tied:
                tied = self.feature_sorted(tied + [n])
                if n not in tied[1:]:
                    continue
                final.remove(tied[:1][0])
            final.append(n)
        return final

    def feature_get_til(self, names, keyisfalse):

        def til(tnames):
            tnames = self.feature_implies_c(tnames)
            tnames = self.feature_sorted(tnames, reverse=True)
            for (i, n) in enumerate(tnames):
                if not self.feature_supported[n].get(keyisfalse, True):
                    tnames = tnames[:i + 1]
                    break
            return tnames
        if isinstance(names, str) or len(names) <= 1:
            names = til(names)
            names.reverse()
            return names
        names = self.feature_ahead(names)
        names = {t for n in names for t in til(n)}
        return self.feature_sorted(names)

    def feature_detect(self, names):
        names = self.feature_get_til(names, 'implies_detect')
        detect = []
        for n in names:
            d = self.feature_supported[n]
            detect += d.get('detect', d.get('group', [n]))
        return detect

    @_Cache.me
    def feature_flags(self, names):
        names = self.feature_sorted(self.feature_implies_c(names))
        flags = []
        for n in names:
            d = self.feature_supported[n]
            f = d.get('flags', [])
            if not f or not self.cc_test_flags(f):
                continue
            flags += f
        return self.cc_normalize_flags(flags)

    @_Cache.me
    def feature_test(self, name, force_flags=None, macros=[]):
        if force_flags is None:
            force_flags = self.feature_flags(name)
        self.dist_log("testing feature '%s' with flags (%s)" % (name, ' '.join(force_flags)))
        test_path = os.path.join(self.conf_check_path, 'cpu_%s.c' % name.lower())
        if not os.path.exists(test_path):
            self.dist_fatal('feature test file is not exist', test_path)
        test = self.dist_test(test_path, force_flags + self.cc_flags['werror'], macros=macros)
        if not test:
            self.dist_log('testing failed', stderr=True)
        return test

    @_Cache.me
    def feature_is_supported(self, name, force_flags=None, macros=[]):
        assert name.isupper()
        assert force_flags is None or isinstance(force_flags, list)
        supported = name in self.feature_supported
        if supported:
            for impl in self.feature_implies(name):
                if not self.feature_test(impl, force_flags, macros=macros):
                    return False
            if not self.feature_test(name, force_flags, macros=macros):
                return False
        return supported

    @_Cache.me
    def feature_can_autovec(self, name):
        assert isinstance(name, str)
        d = self.feature_supported[name]
        can = d.get('autovec', None)
        if can is None:
            valid_flags = [self.cc_test_flags([f]) for f in d.get('flags', [])]
            can = valid_flags and any(valid_flags)
        return can

    @_Cache.me
    def feature_extra_checks(self, name):
        assert isinstance(name, str)
        d = self.feature_supported[name]
        extra_checks = d.get('extra_checks', [])
        if not extra_checks:
            return []
        self.dist_log("Testing extra checks for feature '%s'" % name, extra_checks)
        flags = self.feature_flags(name)
        available = []
        not_available = []
        for chk in extra_checks:
            test_path = os.path.join(self.conf_check_path, 'extra_%s.c' % chk.lower())
            if not os.path.exists(test_path):
                self.dist_fatal('extra check file does not exist', test_path)
            is_supported = self.dist_test(test_path, flags + self.cc_flags['werror'])
            if is_supported:
                available.append(chk)
            else:
                not_available.append(chk)
        if not_available:
            self.dist_log('testing failed for checks', not_available, stderr=True)
        return available

    def feature_c_preprocessor(self, feature_name, tabs=0):
        assert feature_name.isupper()
        feature = self.feature_supported.get(feature_name)
        assert feature is not None
        prepr = ['/** %s **/' % feature_name, '#define %sHAVE_%s 1' % (self.conf_c_prefix, feature_name)]
        prepr += ['#include <%s>' % h for h in feature.get('headers', [])]
        extra_defs = feature.get('group', [])
        extra_defs += self.feature_extra_checks(feature_name)
        for edef in extra_defs:
            prepr += ['#ifndef %sHAVE_%s' % (self.conf_c_prefix, edef), '\t#define %sHAVE_%s 1' % (self.conf_c_prefix, edef), '#endif']
        if tabs > 0:
            prepr = ['\t' * tabs + l for l in prepr]
        return '\n'.join(prepr)

class _Parse:

    def __init__(self, cpu_baseline, cpu_dispatch):
        self._parse_policies = dict(KEEP_BASELINE=(None, self._parse_policy_not_keepbase, []), KEEP_SORT=(self._parse_policy_keepsort, self._parse_policy_not_keepsort, []), MAXOPT=(self._parse_policy_maxopt, None, []), WERROR=(self._parse_policy_werror, None, []), AUTOVEC=(self._parse_policy_autovec, None, ['MAXOPT']))
        if hasattr(self, 'parse_is_cached'):
            return
        self.parse_baseline_names = []
        self.parse_baseline_flags = []
        self.parse_dispatch_names = []
        self.parse_target_groups = {}
        if self.cc_noopt:
            cpu_baseline = cpu_dispatch = None
        self.dist_log('check requested baseline')
        if cpu_baseline is not None:
            cpu_baseline = self._parse_arg_features('cpu_baseline', cpu_baseline)
            baseline_names = self.feature_names(cpu_baseline)
            self.parse_baseline_flags = self.feature_flags(baseline_names)
            self.parse_baseline_names = self.feature_sorted(self.feature_implies_c(baseline_names))
        self.dist_log('check requested dispatch-able features')
        if cpu_dispatch is not None:
            cpu_dispatch_ = self._parse_arg_features('cpu_dispatch', cpu_dispatch)
            cpu_dispatch = {f for f in cpu_dispatch_ if f not in self.parse_baseline_names}
            conflict_baseline = cpu_dispatch_.difference(cpu_dispatch)
            self.parse_dispatch_names = self.feature_sorted(self.feature_names(cpu_dispatch))
            if len(conflict_baseline) > 0:
                self.dist_log('skip features', conflict_baseline, 'since its part of baseline')
        self.dist_log('initialize targets groups')
        for (group_name, tokens) in self.conf_target_groups.items():
            self.dist_log('parse target group', group_name)
            GROUP_NAME = group_name.upper()
            if not tokens or not tokens.strip():
                self.parse_target_groups[GROUP_NAME] = (False, [], [])
                continue
            (has_baseline, features, extra_flags) = self._parse_target_tokens(tokens)
            self.parse_target_groups[GROUP_NAME] = (has_baseline, features, extra_flags)
        self.parse_is_cached = True

    def parse_targets(self, source):
        self.dist_log("looking for '@targets' inside -> ", source)
        with open(source) as fd:
            tokens = ''
            max_to_reach = 1000
            start_with = '@targets'
            start_pos = -1
            end_with = '*/'
            end_pos = -1
            for (current_line, line) in enumerate(fd):
                if current_line == max_to_reach:
                    self.dist_fatal('reached the max of lines')
                    break
                if start_pos == -1:
                    start_pos = line.find(start_with)
                    if start_pos == -1:
                        continue
                    start_pos += len(start_with)
                tokens += line
                end_pos = line.find(end_with)
                if end_pos != -1:
                    end_pos += len(tokens) - len(line)
                    break
        if start_pos == -1:
            self.dist_fatal("expected to find '%s' within a C comment" % start_with)
        if end_pos == -1:
            self.dist_fatal("expected to end with '%s'" % end_with)
        tokens = tokens[start_pos:end_pos]
        return self._parse_target_tokens(tokens)
    _parse_regex_arg = re.compile('\\s|,|([+-])')

    def _parse_arg_features(self, arg_name, req_features):
        if not isinstance(req_features, str):
            self.dist_fatal("expected a string in '%s'" % arg_name)
        final_features = set()
        tokens = list(filter(None, re.split(self._parse_regex_arg, req_features)))
        append = True
        for tok in tokens:
            if tok[0] in ('#', '$'):
                self.dist_fatal(arg_name, "target groups and policies aren't allowed from arguments, only from dispatch-able sources")
            if tok == '+':
                append = True
                continue
            if tok == '-':
                append = False
                continue
            TOK = tok.upper()
            features_to = set()
            if TOK == 'NONE':
                pass
            elif TOK == 'NATIVE':
                native = self.cc_flags['native']
                if not native:
                    self.dist_fatal(arg_name, "native option isn't supported by the compiler")
                features_to = self.feature_names(force_flags=native, macros=[('DETECT_FEATURES', 1)])
            elif TOK == 'MAX':
                features_to = self.feature_supported.keys()
            elif TOK == 'MIN':
                features_to = self.feature_min
            elif TOK in self.feature_supported:
                features_to.add(TOK)
            elif not self.feature_is_exist(TOK):
                self.dist_fatal(arg_name, ", '%s' isn't a known feature or option" % tok)
            if append:
                final_features = final_features.union(features_to)
            else:
                final_features = final_features.difference(features_to)
            append = True
        return final_features
    _parse_regex_target = re.compile('\\s|[*,/]|([()])')

    def _parse_target_tokens(self, tokens):
        assert isinstance(tokens, str)
        final_targets = []
        extra_flags = []
        has_baseline = False
        skipped = set()
        policies = set()
        multi_target = None
        tokens = list(filter(None, re.split(self._parse_regex_target, tokens)))
        if not tokens:
            self.dist_fatal('expected one token at least')
        for tok in tokens:
            TOK = tok.upper()
            ch = tok[0]
            if ch in ('+', '-'):
                self.dist_fatal("+/- are 'not' allowed from target's groups or @targets, only from cpu_baseline and cpu_dispatch parms")
            elif ch == '$':
                if multi_target is not None:
                    self.dist_fatal("policies aren't allowed inside multi-target '()', only CPU features")
                policies.add(self._parse_token_policy(TOK))
            elif ch == '#':
                if multi_target is not None:
                    self.dist_fatal("target groups aren't allowed inside multi-target '()', only CPU features")
                (has_baseline, final_targets, extra_flags) = self._parse_token_group(TOK, has_baseline, final_targets, extra_flags)
            elif ch == '(':
                if multi_target is not None:
                    self.dist_fatal("unclosed multi-target, missing ')'")
                multi_target = set()
            elif ch == ')':
                if multi_target is None:
                    self.dist_fatal("multi-target opener '(' wasn't found")
                targets = self._parse_multi_target(multi_target)
                if targets is None:
                    skipped.add(tuple(multi_target))
                else:
                    if len(targets) == 1:
                        targets = targets[0]
                    if targets and targets not in final_targets:
                        final_targets.append(targets)
                multi_target = None
            else:
                if TOK == 'BASELINE':
                    if multi_target is not None:
                        self.dist_fatal("baseline isn't allowed inside multi-target '()'")
                    has_baseline = True
                    continue
                if multi_target is not None:
                    multi_target.add(TOK)
                    continue
                if not self.feature_is_exist(TOK):
                    self.dist_fatal("invalid target name '%s'" % TOK)
                is_enabled = TOK in self.parse_baseline_names or TOK in self.parse_dispatch_names
                if is_enabled:
                    if TOK not in final_targets:
                        final_targets.append(TOK)
                    continue
                skipped.add(TOK)
        if multi_target is not None:
            self.dist_fatal("unclosed multi-target, missing ')'")
        if skipped:
            self.dist_log('skip targets', skipped, 'not part of baseline or dispatch-able features')
        final_targets = self.feature_untied(final_targets)
        for p in list(policies):
            (_, _, deps) = self._parse_policies[p]
            for d in deps:
                if d in policies:
                    continue
                self.dist_log("policy '%s' force enables '%s'" % (p, d))
                policies.add(d)
        for (p, (have, nhave, _)) in self._parse_policies.items():
            func = None
            if p in policies:
                func = have
                self.dist_log("policy '%s' is ON" % p)
            else:
                func = nhave
            if not func:
                continue
            (has_baseline, final_targets, extra_flags) = func(has_baseline, final_targets, extra_flags)
        return (has_baseline, final_targets, extra_flags)

    def _parse_token_policy(self, token):
        if len(token) <= 1 or token[-1:] == token[0]:
            self.dist_fatal("'$' must stuck in the begin of policy name")
        token = token[1:]
        if token not in self._parse_policies:
            self.dist_fatal("'%s' is an invalid policy name, available policies are" % token, self._parse_policies.keys())
        return token

    def _parse_token_group(self, token, has_baseline, final_targets, extra_flags):
        if len(token) <= 1 or token[-1:] == token[0]:
            self.dist_fatal("'#' must stuck in the begin of group name")
        token = token[1:]
        (ghas_baseline, gtargets, gextra_flags) = self.parse_target_groups.get(token, (False, None, []))
        if gtargets is None:
            self.dist_fatal("'%s' is an invalid target group name, " % token + 'available target groups are', self.parse_target_groups.keys())
        if ghas_baseline:
            has_baseline = True
        final_targets += [f for f in gtargets if f not in final_targets]
        extra_flags += [f for f in gextra_flags if f not in extra_flags]
        return (has_baseline, final_targets, extra_flags)

    def _parse_multi_target(self, targets):
        if not targets:
            self.dist_fatal("empty multi-target '()'")
        if not all([self.feature_is_exist(tar) for tar in targets]):
            self.dist_fatal('invalid target name in multi-target', targets)
        if not all([tar in self.parse_baseline_names or tar in self.parse_dispatch_names for tar in targets]):
            return None
        targets = self.feature_ahead(targets)
        if not targets:
            return None
        targets = self.feature_sorted(targets)
        targets = tuple(targets)
        return targets

    def _parse_policy_not_keepbase(self, has_baseline, final_targets, extra_flags):
        skipped = []
        for tar in final_targets[:]:
            is_base = False
            if isinstance(tar, str):
                is_base = tar in self.parse_baseline_names
            else:
                is_base = all([f in self.parse_baseline_names for f in tar])
            if is_base:
                skipped.append(tar)
                final_targets.remove(tar)
        if skipped:
            self.dist_log('skip baseline features', skipped)
        return (has_baseline, final_targets, extra_flags)

    def _parse_policy_keepsort(self, has_baseline, final_targets, extra_flags):
        self.dist_log("policy 'keep_sort' is on, dispatch-able targets", final_targets, "\nare 'not' sorted depend on the highest interest butas specified in the dispatch-able source or the extra group")
        return (has_baseline, final_targets, extra_flags)

    def _parse_policy_not_keepsort(self, has_baseline, final_targets, extra_flags):
        final_targets = self.feature_sorted(final_targets, reverse=True)
        return (has_baseline, final_targets, extra_flags)

    def _parse_policy_maxopt(self, has_baseline, final_targets, extra_flags):
        if self.cc_has_debug:
            self.dist_log("debug mode is detected, policy 'maxopt' is skipped.")
        elif self.cc_noopt:
            self.dist_log("optimization is disabled, policy 'maxopt' is skipped.")
        else:
            flags = self.cc_flags['opt']
            if not flags:
                self.dist_log("current compiler doesn't support optimization flags, policy 'maxopt' is skipped", stderr=True)
            else:
                extra_flags += flags
        return (has_baseline, final_targets, extra_flags)

    def _parse_policy_werror(self, has_baseline, final_targets, extra_flags):
        flags = self.cc_flags['werror']
        if not flags:
            self.dist_log("current compiler doesn't support werror flags, warnings will 'not' treated as errors", stderr=True)
        else:
            self.dist_log('compiler warnings are treated as errors')
            extra_flags += flags
        return (has_baseline, final_targets, extra_flags)

    def _parse_policy_autovec(self, has_baseline, final_targets, extra_flags):
        skipped = []
        for tar in final_targets[:]:
            if isinstance(tar, str):
                can = self.feature_can_autovec(tar)
            else:
                can = all([self.feature_can_autovec(t) for t in tar])
            if not can:
                final_targets.remove(tar)
                skipped.append(tar)
        if skipped:
            self.dist_log('skip non auto-vectorized features', skipped)
        return (has_baseline, final_targets, extra_flags)

class CCompilerOpt(_Config, _Distutils, _Cache, _CCompiler, _Feature, _Parse):

    def __init__(self, ccompiler, cpu_baseline='min', cpu_dispatch='max', cache_path=None):
        _Config.__init__(self)
        _Distutils.__init__(self, ccompiler)
        _Cache.__init__(self, cache_path, self.dist_info(), cpu_baseline, cpu_dispatch)
        _CCompiler.__init__(self)
        _Feature.__init__(self)
        if not self.cc_noopt and self.cc_has_native:
            self.dist_log("native flag is specified through environment variables. force cpu-baseline='native'")
            cpu_baseline = 'native'
        _Parse.__init__(self, cpu_baseline, cpu_dispatch)
        self._requested_baseline = cpu_baseline
        self._requested_dispatch = cpu_dispatch
        self.sources_status = getattr(self, 'sources_status', {})
        self.cache_private.add('sources_status')
        self.hit_cache = hasattr(self, 'hit_cache')

    def is_cached(self):
        return self.cache_infile and self.hit_cache

    def cpu_baseline_flags(self):
        return self.parse_baseline_flags

    def cpu_baseline_names(self):
        return self.parse_baseline_names

    def cpu_dispatch_names(self):
        return self.parse_dispatch_names

    def try_dispatch(self, sources, src_dir=None, ccompiler=None, **kwargs):
        to_compile = {}
        baseline_flags = self.cpu_baseline_flags()
        include_dirs = kwargs.setdefault('include_dirs', [])
        for src in sources:
            output_dir = os.path.dirname(src)
            if src_dir:
                if not output_dir.startswith(src_dir):
                    output_dir = os.path.join(src_dir, output_dir)
                if output_dir not in include_dirs:
                    include_dirs.append(output_dir)
            (has_baseline, targets, extra_flags) = self.parse_targets(src)
            nochange = self._generate_config(output_dir, src, targets, has_baseline)
            for tar in targets:
                tar_src = self._wrap_target(output_dir, src, tar, nochange=nochange)
                flags = tuple(extra_flags + self.feature_flags(tar))
                to_compile.setdefault(flags, []).append(tar_src)
            if has_baseline:
                flags = tuple(extra_flags + baseline_flags)
                to_compile.setdefault(flags, []).append(src)
            self.sources_status[src] = (has_baseline, targets)
        objects = []
        for (flags, srcs) in to_compile.items():
            objects += self.dist_compile(srcs, list(flags), ccompiler=ccompiler, **kwargs)
        return objects

    def generate_dispatch_header(self, header_path):
        self.dist_log('generate CPU dispatch header: (%s)' % header_path)
        baseline_names = self.cpu_baseline_names()
        dispatch_names = self.cpu_dispatch_names()
        baseline_len = len(baseline_names)
        dispatch_len = len(dispatch_names)
        header_dir = os.path.dirname(header_path)
        if not os.path.exists(header_dir):
            self.dist_log(f'dispatch header dir {header_dir} does not exist, creating it', stderr=True)
            os.makedirs(header_dir)
        with open(header_path, 'w') as f:
            baseline_calls = ' \\\n'.join(['\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))' % (self.conf_c_prefix, f) for f in baseline_names])
            dispatch_calls = ' \\\n'.join(['\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))' % (self.conf_c_prefix, f) for f in dispatch_names])
            f.write(textwrap.dedent('                /*\n                 * AUTOGENERATED DON\'T EDIT\n                 * Please make changes to the code generator (distutils/ccompiler_opt.py)\n                */\n                #define {pfx}WITH_CPU_BASELINE  "{baseline_str}"\n                #define {pfx}WITH_CPU_DISPATCH  "{dispatch_str}"\n                #define {pfx}WITH_CPU_BASELINE_N {baseline_len}\n                #define {pfx}WITH_CPU_DISPATCH_N {dispatch_len}\n                #define {pfx}WITH_CPU_EXPAND_(X) X\n                #define {pfx}WITH_CPU_BASELINE_CALL(MACRO_TO_CALL, ...) \\\n                {baseline_calls}\n                #define {pfx}WITH_CPU_DISPATCH_CALL(MACRO_TO_CALL, ...) \\\n                {dispatch_calls}\n            ').format(pfx=self.conf_c_prefix, baseline_str=' '.join(baseline_names), dispatch_str=' '.join(dispatch_names), baseline_len=baseline_len, dispatch_len=dispatch_len, baseline_calls=baseline_calls, dispatch_calls=dispatch_calls))
            baseline_pre = ''
            for name in baseline_names:
                baseline_pre += self.feature_c_preprocessor(name, tabs=1) + '\n'
            dispatch_pre = ''
            for name in dispatch_names:
                dispatch_pre += textwrap.dedent('                #ifdef {pfx}CPU_TARGET_{name}\n                {pre}\n                #endif /*{pfx}CPU_TARGET_{name}*/\n                ').format(pfx=self.conf_c_prefix_, name=name, pre=self.feature_c_preprocessor(name, tabs=1))
            f.write(textwrap.dedent('            /******* baseline features *******/\n            {baseline_pre}\n            /******* dispatch features *******/\n            {dispatch_pre}\n            ').format(pfx=self.conf_c_prefix_, baseline_pre=baseline_pre, dispatch_pre=dispatch_pre))

    def report(self, full=False):
        report = []
        platform_rows = []
        baseline_rows = []
        dispatch_rows = []
        report.append(('Platform', platform_rows))
        report.append(('', ''))
        report.append(('CPU baseline', baseline_rows))
        report.append(('', ''))
        report.append(('CPU dispatch', dispatch_rows))
        platform_rows.append(('Architecture', 'unsupported' if self.cc_on_noarch else self.cc_march))
        platform_rows.append(('Compiler', 'unix-like' if self.cc_is_nocc else self.cc_name))
        if self.cc_noopt:
            baseline_rows.append(('Requested', 'optimization disabled'))
        else:
            baseline_rows.append(('Requested', repr(self._requested_baseline)))
        baseline_names = self.cpu_baseline_names()
        baseline_rows.append(('Enabled', ' '.join(baseline_names) if baseline_names else 'none'))
        baseline_flags = self.cpu_baseline_flags()
        baseline_rows.append(('Flags', ' '.join(baseline_flags) if baseline_flags else 'none'))
        extra_checks = []
        for name in baseline_names:
            extra_checks += self.feature_extra_checks(name)
        baseline_rows.append(('Extra checks', ' '.join(extra_checks) if extra_checks else 'none'))
        if self.cc_noopt:
            baseline_rows.append(('Requested', 'optimization disabled'))
        else:
            dispatch_rows.append(('Requested', repr(self._requested_dispatch)))
        dispatch_names = self.cpu_dispatch_names()
        dispatch_rows.append(('Enabled', ' '.join(dispatch_names) if dispatch_names else 'none'))
        target_sources = {}
        for (source, (_, targets)) in self.sources_status.items():
            for tar in targets:
                target_sources.setdefault(tar, []).append(source)
        if not full or not target_sources:
            generated = ''
            for tar in self.feature_sorted(target_sources):
                sources = target_sources[tar]
                name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar)
                generated += name + '[%d] ' % len(sources)
            dispatch_rows.append(('Generated', generated[:-1] if generated else 'none'))
        else:
            dispatch_rows.append(('Generated', ''))
            for tar in self.feature_sorted(target_sources):
                sources = target_sources[tar]
                pretty_name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar)
                flags = ' '.join(self.feature_flags(tar))
                implies = ' '.join(self.feature_sorted(self.feature_implies(tar)))
                detect = ' '.join(self.feature_detect(tar))
                extra_checks = []
                for name in (tar,) if isinstance(tar, str) else tar:
                    extra_checks += self.feature_extra_checks(name)
                extra_checks = ' '.join(extra_checks) if extra_checks else 'none'
                dispatch_rows.append(('', ''))
                dispatch_rows.append((pretty_name, implies))
                dispatch_rows.append(('Flags', flags))
                dispatch_rows.append(('Extra checks', extra_checks))
                dispatch_rows.append(('Detect', detect))
                for src in sources:
                    dispatch_rows.append(('', src))
        text = []
        secs_len = [len(secs) for (secs, _) in report]
        cols_len = [len(col) for (_, rows) in report for (col, _) in rows]
        tab = ' ' * 2
        pad = max(max(secs_len), max(cols_len))
        for (sec, rows) in report:
            if not sec:
                text.append('')
                continue
            sec += ' ' * (pad - len(sec))
            text.append(sec + tab + ': ')
            for (col, val) in rows:
                col += ' ' * (pad - len(col))
                text.append(tab + col + ': ' + val)
        return '\n'.join(text)

    def _wrap_target(self, output_dir, dispatch_src, target, nochange=False):
        assert isinstance(target, (str, tuple))
        if isinstance(target, str):
            ext_name = target_name = target
        else:
            ext_name = '.'.join(target)
            target_name = '__'.join(target)
        wrap_path = os.path.join(output_dir, os.path.basename(dispatch_src))
        wrap_path = '{0}.{2}{1}'.format(*os.path.splitext(wrap_path), ext_name.lower())
        if nochange and os.path.exists(wrap_path):
            return wrap_path
        self.dist_log('wrap dispatch-able target -> ', wrap_path)
        features = self.feature_sorted(self.feature_implies_c(target))
        target_join = '#define %sCPU_TARGET_' % self.conf_c_prefix_
        target_defs = [target_join + f for f in features]
        target_defs = '\n'.join(target_defs)
        with open(wrap_path, 'w') as fd:
            fd.write(textwrap.dedent('            /**\n             * AUTOGENERATED DON\'T EDIT\n             * Please make changes to the code generator              (distutils/ccompiler_opt.py)\n             */\n            #define {pfx}CPU_TARGET_MODE\n            #define {pfx}CPU_TARGET_CURRENT {target_name}\n            {target_defs}\n            #include "{path}"\n            ').format(pfx=self.conf_c_prefix_, target_name=target_name, path=os.path.abspath(dispatch_src), target_defs=target_defs))
        return wrap_path

    def _generate_config(self, output_dir, dispatch_src, targets, has_baseline=False):
        config_path = os.path.basename(dispatch_src)
        config_path = os.path.splitext(config_path)[0] + '.h'
        config_path = os.path.join(output_dir, config_path)
        cache_hash = self.cache_hash(targets, has_baseline)
        try:
            with open(config_path) as f:
                last_hash = f.readline().split('cache_hash:')
                if len(last_hash) == 2 and int(last_hash[1]) == cache_hash:
                    return True
        except OSError:
            pass
        os.makedirs(os.path.dirname(config_path), exist_ok=True)
        self.dist_log('generate dispatched config -> ', config_path)
        dispatch_calls = []
        for tar in targets:
            if isinstance(tar, str):
                target_name = tar
            else:
                target_name = '__'.join([t for t in tar])
            req_detect = self.feature_detect(tar)
            req_detect = '&&'.join(['CHK(%s)' % f for f in req_detect])
            dispatch_calls.append('\t%sCPU_DISPATCH_EXPAND_(CB((%s), %s, __VA_ARGS__))' % (self.conf_c_prefix_, req_detect, target_name))
        dispatch_calls = ' \\\n'.join(dispatch_calls)
        if has_baseline:
            baseline_calls = '\t%sCPU_DISPATCH_EXPAND_(CB(__VA_ARGS__))' % self.conf_c_prefix_
        else:
            baseline_calls = ''
        with open(config_path, 'w') as fd:
            fd.write(textwrap.dedent("            // cache_hash:{cache_hash}\n            /**\n             * AUTOGENERATED DON'T EDIT\n             * Please make changes to the code generator (distutils/ccompiler_opt.py)\n             */\n            #ifndef {pfx}CPU_DISPATCH_EXPAND_\n                #define {pfx}CPU_DISPATCH_EXPAND_(X) X\n            #endif\n            #undef {pfx}CPU_DISPATCH_BASELINE_CALL\n            #undef {pfx}CPU_DISPATCH_CALL\n            #define {pfx}CPU_DISPATCH_BASELINE_CALL(CB, ...) \\\n            {baseline_calls}\n            #define {pfx}CPU_DISPATCH_CALL(CHK, CB, ...) \\\n            {dispatch_calls}\n            ").format(pfx=self.conf_c_prefix_, baseline_calls=baseline_calls, dispatch_calls=dispatch_calls, cache_hash=cache_hash))
        return False

def new_ccompiler_opt(compiler, dispatch_hpath, **kwargs):
    opt = CCompilerOpt(compiler, **kwargs)
    if not os.path.exists(dispatch_hpath) or not opt.is_cached():
        opt.generate_dispatch_header(dispatch_hpath)
    return opt

# File: numpy-main/numpy/distutils/command/__init__.py
""""""

def test_na_writable_attributes_deletion():
    a = np.NA(2)
    attr = ['payload', 'dtype']
    for s in attr:
        assert_raises(AttributeError, delattr, a, s)
__revision__ = '$Id: __init__.py,v 1.3 2005/05/16 11:08:49 pearu Exp $'
distutils_all = ['clean', 'install_clib', 'install_scripts', 'bdist', 'bdist_dumb', 'bdist_wininst']
__import__('distutils.command', globals(), locals(), distutils_all)
__all__ = ['build', 'config_compiler', 'config', 'build_src', 'build_py', 'build_ext', 'build_clib', 'build_scripts', 'install', 'install_data', 'install_headers', 'install_lib', 'bdist_rpm', 'sdist'] + distutils_all

# File: numpy-main/numpy/distutils/command/autodist.py
""""""
import textwrap

def check_inline(cmd):
    cmd._check_compiler()
    body = textwrap.dedent('\n        #ifndef __cplusplus\n        static %(inline)s int static_func (void)\n        {\n            return 0;\n        }\n        %(inline)s int nostatic_func (void)\n        {\n            return 0;\n        }\n        #endif')
    for kw in ['inline', '__inline__', '__inline']:
        st = cmd.try_compile(body % {'inline': kw}, None, None)
        if st:
            return kw
    return ''

def check_restrict(cmd):
    cmd._check_compiler()
    body = textwrap.dedent('\n        static int static_func (char * %(restrict)s a)\n        {\n            return 0;\n        }\n        ')
    for kw in ['restrict', '__restrict__', '__restrict']:
        st = cmd.try_compile(body % {'restrict': kw}, None, None)
        if st:
            return kw
    return ''

def check_compiler_gcc(cmd):
    cmd._check_compiler()
    body = textwrap.dedent('\n        int\n        main()\n        {\n        #if (! defined __GNUC__)\n        #error gcc required\n        #endif\n            return 0;\n        }\n        ')
    return cmd.try_compile(body, None, None)

def check_gcc_version_at_least(cmd, major, minor=0, patchlevel=0):
    cmd._check_compiler()
    version = '.'.join([str(major), str(minor), str(patchlevel)])
    body = textwrap.dedent('\n        int\n        main()\n        {\n        #if (! defined __GNUC__) || (__GNUC__ < %(major)d) || \\\n                (__GNUC_MINOR__ < %(minor)d) || \\\n                (__GNUC_PATCHLEVEL__ < %(patchlevel)d)\n        #error gcc >= %(version)s required\n        #endif\n            return 0;\n        }\n        ')
    kw = {'version': version, 'major': major, 'minor': minor, 'patchlevel': patchlevel}
    return cmd.try_compile(body % kw, None, None)

def check_gcc_function_attribute(cmd, attribute, name):
    cmd._check_compiler()
    body = textwrap.dedent('\n        #pragma GCC diagnostic error "-Wattributes"\n        #pragma clang diagnostic error "-Wattributes"\n\n        int %s %s(void* unused)\n        {\n            return 0;\n        }\n\n        int\n        main()\n        {\n            return 0;\n        }\n        ') % (attribute, name)
    return cmd.try_compile(body, None, None) != 0

def check_gcc_function_attribute_with_intrinsics(cmd, attribute, name, code, include):
    cmd._check_compiler()
    body = textwrap.dedent('\n        #include<%s>\n        int %s %s(void)\n        {\n            %s;\n            return 0;\n        }\n\n        int\n        main()\n        {\n            return 0;\n        }\n        ') % (include, attribute, name, code)
    return cmd.try_compile(body, None, None) != 0

def check_gcc_variable_attribute(cmd, attribute):
    cmd._check_compiler()
    body = textwrap.dedent('\n        #pragma GCC diagnostic error "-Wattributes"\n        #pragma clang diagnostic error "-Wattributes"\n\n        int %s foo;\n\n        int\n        main()\n        {\n            return 0;\n        }\n        ') % (attribute,)
    return cmd.try_compile(body, None, None) != 0

# File: numpy-main/numpy/distutils/command/bdist_rpm.py
import os
import sys
if 'setuptools' in sys.modules:
    from setuptools.command.bdist_rpm import bdist_rpm as old_bdist_rpm
else:
    from distutils.command.bdist_rpm import bdist_rpm as old_bdist_rpm

class bdist_rpm(old_bdist_rpm):

    def _make_spec_file(self):
        spec_file = old_bdist_rpm._make_spec_file(self)
        setup_py = os.path.basename(sys.argv[0])
        if setup_py == 'setup.py':
            return spec_file
        new_spec_file = []
        for line in spec_file:
            line = line.replace('setup.py', setup_py)
            new_spec_file.append(line)
        return new_spec_file

# File: numpy-main/numpy/distutils/command/build.py
import os
import sys
from distutils.command.build import build as old_build
from distutils.util import get_platform
from numpy.distutils.command.config_compiler import show_fortran_compilers

class build(old_build):
    sub_commands = [('config_cc', lambda *args: True), ('config_fc', lambda *args: True), ('build_src', old_build.has_ext_modules)] + old_build.sub_commands
    user_options = old_build.user_options + [('fcompiler=', None, 'specify the Fortran compiler type'), ('warn-error', None, 'turn all warnings into errors (-Werror)'), ('cpu-baseline=', None, 'specify a list of enabled baseline CPU optimizations'), ('cpu-dispatch=', None, 'specify a list of dispatched CPU optimizations'), ('disable-optimization', None, 'disable CPU optimized code(dispatch,simd,fast...)'), ('simd-test=', None, 'specify a list of CPU optimizations to be tested against NumPy SIMD interface')]
    help_options = old_build.help_options + [('help-fcompiler', None, 'list available Fortran compilers', show_fortran_compilers)]

    def initialize_options(self):
        old_build.initialize_options(self)
        self.fcompiler = None
        self.warn_error = False
        self.cpu_baseline = 'min'
        self.cpu_dispatch = 'max -xop -fma4'
        self.disable_optimization = False
        ''
        self.simd_test = 'BASELINE SSE2 SSE42 XOP FMA4 (FMA3 AVX2) AVX512F AVX512_SKX VSX VSX2 VSX3 VSX4 NEON ASIMD VX VXE VXE2'

    def finalize_options(self):
        build_scripts = self.build_scripts
        old_build.finalize_options(self)
        plat_specifier = '.{}-{}.{}'.format(get_platform(), *sys.version_info[:2])
        if build_scripts is None:
            self.build_scripts = os.path.join(self.build_base, 'scripts' + plat_specifier)

    def run(self):
        old_build.run(self)

# File: numpy-main/numpy/distutils/command/build_clib.py
""""""
import os
from glob import glob
import shutil
from distutils.command.build_clib import build_clib as old_build_clib
from distutils.errors import DistutilsSetupError, DistutilsError, DistutilsFileError
from numpy.distutils import log
from distutils.dep_util import newer_group
from numpy.distutils.misc_util import filter_sources, get_lib_source_files, get_numpy_include_dirs, has_cxx_sources, has_f_sources, is_sequence
from numpy.distutils.ccompiler_opt import new_ccompiler_opt
_l = old_build_clib.user_options
for _i in range(len(_l)):
    if _l[_i][0] in ['build-clib', 'build-temp']:
        _l[_i] = (_l[_i][0] + '=',) + _l[_i][1:]

class build_clib(old_build_clib):
    description = 'build C/C++/F libraries used by Python extensions'
    user_options = old_build_clib.user_options + [('fcompiler=', None, 'specify the Fortran compiler type'), ('inplace', 'i', 'Build in-place'), ('parallel=', 'j', 'number of parallel jobs'), ('warn-error', None, 'turn all warnings into errors (-Werror)'), ('cpu-baseline=', None, 'specify a list of enabled baseline CPU optimizations'), ('cpu-dispatch=', None, 'specify a list of dispatched CPU optimizations'), ('disable-optimization', None, 'disable CPU optimized code(dispatch,simd,fast...)')]
    boolean_options = old_build_clib.boolean_options + ['inplace', 'warn-error', 'disable-optimization']

    def initialize_options(self):
        old_build_clib.initialize_options(self)
        self.fcompiler = None
        self.inplace = 0
        self.parallel = None
        self.warn_error = None
        self.cpu_baseline = None
        self.cpu_dispatch = None
        self.disable_optimization = None

    def finalize_options(self):
        if self.parallel:
            try:
                self.parallel = int(self.parallel)
            except ValueError as e:
                raise ValueError('--parallel/-j argument must be an integer') from e
        old_build_clib.finalize_options(self)
        self.set_undefined_options('build', ('parallel', 'parallel'), ('warn_error', 'warn_error'), ('cpu_baseline', 'cpu_baseline'), ('cpu_dispatch', 'cpu_dispatch'), ('disable_optimization', 'disable_optimization'))

    def have_f_sources(self):
        for (lib_name, build_info) in self.libraries:
            if has_f_sources(build_info.get('sources', [])):
                return True
        return False

    def have_cxx_sources(self):
        for (lib_name, build_info) in self.libraries:
            if has_cxx_sources(build_info.get('sources', [])):
                return True
        return False

    def run(self):
        if not self.libraries:
            return
        languages = []
        self.run_command('build_src')
        for (lib_name, build_info) in self.libraries:
            l = build_info.get('language', None)
            if l and l not in languages:
                languages.append(l)
        from distutils.ccompiler import new_compiler
        self.compiler = new_compiler(compiler=self.compiler, dry_run=self.dry_run, force=self.force)
        self.compiler.customize(self.distribution, need_cxx=self.have_cxx_sources())
        if self.warn_error:
            self.compiler.compiler.append('-Werror')
            self.compiler.compiler_so.append('-Werror')
        libraries = self.libraries
        self.libraries = None
        self.compiler.customize_cmd(self)
        self.libraries = libraries
        self.compiler.show_customization()
        if not self.disable_optimization:
            dispatch_hpath = os.path.join('numpy', 'distutils', 'include', 'npy_cpu_dispatch_config.h')
            dispatch_hpath = os.path.join(self.get_finalized_command('build_src').build_src, dispatch_hpath)
            opt_cache_path = os.path.abspath(os.path.join(self.build_temp, 'ccompiler_opt_cache_clib.py'))
            if hasattr(self, 'compiler_opt'):
                self.compiler_opt.cache_flush()
            self.compiler_opt = new_ccompiler_opt(compiler=self.compiler, dispatch_hpath=dispatch_hpath, cpu_baseline=self.cpu_baseline, cpu_dispatch=self.cpu_dispatch, cache_path=opt_cache_path)

            def report(copt):
                log.info('\n########### CLIB COMPILER OPTIMIZATION ###########')
                log.info(copt.report(full=True))
            import atexit
            atexit.register(report, self.compiler_opt)
        if self.have_f_sources():
            from numpy.distutils.fcompiler import new_fcompiler
            self._f_compiler = new_fcompiler(compiler=self.fcompiler, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90='f90' in languages, c_compiler=self.compiler)
            if self._f_compiler is not None:
                self._f_compiler.customize(self.distribution)
                libraries = self.libraries
                self.libraries = None
                self._f_compiler.customize_cmd(self)
                self.libraries = libraries
                self._f_compiler.show_customization()
        else:
            self._f_compiler = None
        self.build_libraries(self.libraries)
        if self.inplace:
            for l in self.distribution.installed_libraries:
                libname = self.compiler.library_filename(l.name)
                source = os.path.join(self.build_clib, libname)
                target = os.path.join(l.target_dir, libname)
                self.mkpath(l.target_dir)
                shutil.copy(source, target)

    def get_source_files(self):
        self.check_library_list(self.libraries)
        filenames = []
        for lib in self.libraries:
            filenames.extend(get_lib_source_files(lib))
        return filenames

    def build_libraries(self, libraries):
        for (lib_name, build_info) in libraries:
            self.build_a_library(build_info, lib_name, libraries)

    def assemble_flags(self, in_flags):
        if in_flags is None:
            return []
        out_flags = []
        for in_flag in in_flags:
            if callable(in_flag):
                out_flags += in_flag(self)
            else:
                out_flags.append(in_flag)
        return out_flags

    def build_a_library(self, build_info, lib_name, libraries):
        compiler = self.compiler
        fcompiler = self._f_compiler
        sources = build_info.get('sources')
        if sources is None or not is_sequence(sources):
            raise DistutilsSetupError(("in 'libraries' option (library '%s'), " + "'sources' must be present and must be " + 'a list of source filenames') % lib_name)
        sources = list(sources)
        (c_sources, cxx_sources, f_sources, fmodule_sources) = filter_sources(sources)
        requiref90 = not not fmodule_sources or build_info.get('language', 'c') == 'f90'
        source_languages = []
        if c_sources:
            source_languages.append('c')
        if cxx_sources:
            source_languages.append('c++')
        if requiref90:
            source_languages.append('f90')
        elif f_sources:
            source_languages.append('f77')
        build_info['source_languages'] = source_languages
        lib_file = compiler.library_filename(lib_name, output_dir=self.build_clib)
        depends = sources + build_info.get('depends', [])
        force_rebuild = self.force
        if not self.disable_optimization and (not self.compiler_opt.is_cached()):
            log.debug('Detected changes on compiler optimizations')
            force_rebuild = True
        if not (force_rebuild or newer_group(depends, lib_file, 'newer')):
            log.debug("skipping '%s' library (up-to-date)", lib_name)
            return
        else:
            log.info("building '%s' library", lib_name)
        config_fc = build_info.get('config_fc', {})
        if fcompiler is not None and config_fc:
            log.info('using additional config_fc from setup script for fortran compiler: %s' % (config_fc,))
            from numpy.distutils.fcompiler import new_fcompiler
            fcompiler = new_fcompiler(compiler=fcompiler.compiler_type, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90=requiref90, c_compiler=self.compiler)
            if fcompiler is not None:
                dist = self.distribution
                base_config_fc = dist.get_option_dict('config_fc').copy()
                base_config_fc.update(config_fc)
                fcompiler.customize(base_config_fc)
        if (f_sources or fmodule_sources) and fcompiler is None:
            raise DistutilsError('library %s has Fortran sources but no Fortran compiler found' % lib_name)
        if fcompiler is not None:
            fcompiler.extra_f77_compile_args = build_info.get('extra_f77_compile_args') or []
            fcompiler.extra_f90_compile_args = build_info.get('extra_f90_compile_args') or []
        macros = build_info.get('macros')
        if macros is None:
            macros = []
        include_dirs = build_info.get('include_dirs')
        if include_dirs is None:
            include_dirs = []
        extra_postargs = self.assemble_flags(build_info.get('extra_compiler_args'))
        extra_cflags = self.assemble_flags(build_info.get('extra_cflags'))
        extra_cxxflags = self.assemble_flags(build_info.get('extra_cxxflags'))
        include_dirs.extend(get_numpy_include_dirs())
        module_dirs = build_info.get('module_dirs') or []
        module_build_dir = os.path.dirname(lib_file)
        if requiref90:
            self.mkpath(module_build_dir)
        if compiler.compiler_type == 'msvc':
            c_sources += cxx_sources
            cxx_sources = []
            extra_cflags += extra_cxxflags
        copt_c_sources = []
        copt_cxx_sources = []
        copt_baseline_flags = []
        copt_macros = []
        if not self.disable_optimization:
            bsrc_dir = self.get_finalized_command('build_src').build_src
            dispatch_hpath = os.path.join('numpy', 'distutils', 'include')
            dispatch_hpath = os.path.join(bsrc_dir, dispatch_hpath)
            include_dirs.append(dispatch_hpath)
            copt_build_src = bsrc_dir
            for (_srcs, _dst, _ext) in (((c_sources,), copt_c_sources, ('.dispatch.c',)), ((c_sources, cxx_sources), copt_cxx_sources, ('.dispatch.cpp', '.dispatch.cxx'))):
                for _src in _srcs:
                    _dst += [_src.pop(_src.index(s)) for s in _src[:] if s.endswith(_ext)]
            copt_baseline_flags = self.compiler_opt.cpu_baseline_flags()
        else:
            copt_macros.append(('NPY_DISABLE_OPTIMIZATION', 1))
        objects = []
        if copt_cxx_sources:
            log.info('compiling C++ dispatch-able sources')
            objects += self.compiler_opt.try_dispatch(copt_c_sources, output_dir=self.build_temp, src_dir=copt_build_src, macros=macros + copt_macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs + extra_cxxflags, ccompiler=cxx_compiler)
        if copt_c_sources:
            log.info('compiling C dispatch-able sources')
            objects += self.compiler_opt.try_dispatch(copt_c_sources, output_dir=self.build_temp, src_dir=copt_build_src, macros=macros + copt_macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs + extra_cflags)
        if c_sources:
            log.info('compiling C sources')
            objects += compiler.compile(c_sources, output_dir=self.build_temp, macros=macros + copt_macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs + copt_baseline_flags + extra_cflags)
        if cxx_sources:
            log.info('compiling C++ sources')
            cxx_compiler = compiler.cxx_compiler()
            cxx_objects = cxx_compiler.compile(cxx_sources, output_dir=self.build_temp, macros=macros + copt_macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs + copt_baseline_flags + extra_cxxflags)
            objects.extend(cxx_objects)
        if f_sources or fmodule_sources:
            extra_postargs = []
            f_objects = []
            if requiref90:
                if fcompiler.module_dir_switch is None:
                    existing_modules = glob('*.mod')
                extra_postargs += fcompiler.module_options(module_dirs, module_build_dir)
            if fmodule_sources:
                log.info('compiling Fortran 90 module sources')
                f_objects += fcompiler.compile(fmodule_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs)
            if requiref90 and self._f_compiler.module_dir_switch is None:
                for f in glob('*.mod'):
                    if f in existing_modules:
                        continue
                    t = os.path.join(module_build_dir, f)
                    if os.path.abspath(f) == os.path.abspath(t):
                        continue
                    if os.path.isfile(t):
                        os.remove(t)
                    try:
                        self.move_file(f, module_build_dir)
                    except DistutilsFileError:
                        log.warn('failed to move %r to %r' % (f, module_build_dir))
            if f_sources:
                log.info('compiling Fortran sources')
                f_objects += fcompiler.compile(f_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs)
        else:
            f_objects = []
        if f_objects and (not fcompiler.can_ccompiler_link(compiler)):
            listfn = os.path.join(self.build_clib, lib_name + '.fobjects')
            with open(listfn, 'w') as f:
                f.write('\n'.join((os.path.abspath(obj) for obj in f_objects)))
            listfn = os.path.join(self.build_clib, lib_name + '.cobjects')
            with open(listfn, 'w') as f:
                f.write('\n'.join((os.path.abspath(obj) for obj in objects)))
            lib_fname = os.path.join(self.build_clib, lib_name + compiler.static_lib_extension)
            with open(lib_fname, 'wb') as f:
                pass
        else:
            objects.extend(f_objects)
            compiler.create_static_lib(objects, lib_name, output_dir=self.build_clib, debug=self.debug)
        clib_libraries = build_info.get('libraries', [])
        for (lname, binfo) in libraries:
            if lname in clib_libraries:
                clib_libraries.extend(binfo.get('libraries', []))
        if clib_libraries:
            build_info['libraries'] = clib_libraries

# File: numpy-main/numpy/distutils/command/build_ext.py
""""""
import os
import subprocess
from glob import glob
from distutils.dep_util import newer_group
from distutils.command.build_ext import build_ext as old_build_ext
from distutils.errors import DistutilsFileError, DistutilsSetupError, DistutilsError
from distutils.file_util import copy_file
from numpy.distutils import log
from numpy.distutils.exec_command import filepath_from_subprocess_output
from numpy.distutils.system_info import combine_paths
from numpy.distutils.misc_util import filter_sources, get_ext_source_files, get_numpy_include_dirs, has_cxx_sources, has_f_sources, is_sequence
from numpy.distutils.command.config_compiler import show_fortran_compilers
from numpy.distutils.ccompiler_opt import new_ccompiler_opt, CCompilerOpt

class build_ext(old_build_ext):
    description = 'build C/C++/F extensions (compile/link to build directory)'
    user_options = old_build_ext.user_options + [('fcompiler=', None, 'specify the Fortran compiler type'), ('parallel=', 'j', 'number of parallel jobs'), ('warn-error', None, 'turn all warnings into errors (-Werror)'), ('cpu-baseline=', None, 'specify a list of enabled baseline CPU optimizations'), ('cpu-dispatch=', None, 'specify a list of dispatched CPU optimizations'), ('disable-optimization', None, 'disable CPU optimized code(dispatch,simd,fast...)'), ('simd-test=', None, 'specify a list of CPU optimizations to be tested against NumPy SIMD interface')]
    help_options = old_build_ext.help_options + [('help-fcompiler', None, 'list available Fortran compilers', show_fortran_compilers)]
    boolean_options = old_build_ext.boolean_options + ['warn-error', 'disable-optimization']

    def initialize_options(self):
        old_build_ext.initialize_options(self)
        self.fcompiler = None
        self.parallel = None
        self.warn_error = None
        self.cpu_baseline = None
        self.cpu_dispatch = None
        self.disable_optimization = None
        self.simd_test = None

    def finalize_options(self):
        if self.parallel:
            try:
                self.parallel = int(self.parallel)
            except ValueError as e:
                raise ValueError('--parallel/-j argument must be an integer') from e
        if isinstance(self.include_dirs, str):
            self.include_dirs = self.include_dirs.split(os.pathsep)
        incl_dirs = self.include_dirs or []
        if self.distribution.include_dirs is None:
            self.distribution.include_dirs = []
        self.include_dirs = self.distribution.include_dirs
        self.include_dirs.extend(incl_dirs)
        old_build_ext.finalize_options(self)
        self.set_undefined_options('build', ('parallel', 'parallel'), ('warn_error', 'warn_error'), ('cpu_baseline', 'cpu_baseline'), ('cpu_dispatch', 'cpu_dispatch'), ('disable_optimization', 'disable_optimization'), ('simd_test', 'simd_test'))
        CCompilerOpt.conf_target_groups['simd_test'] = self.simd_test

    def run(self):
        if not self.extensions:
            return
        self.run_command('build_src')
        if self.distribution.has_c_libraries():
            if self.inplace:
                if self.distribution.have_run.get('build_clib'):
                    log.warn('build_clib already run, it is too late to ensure in-place build of build_clib')
                    build_clib = self.distribution.get_command_obj('build_clib')
                else:
                    build_clib = self.distribution.get_command_obj('build_clib')
                    build_clib.inplace = 1
                    build_clib.ensure_finalized()
                    build_clib.run()
                    self.distribution.have_run['build_clib'] = 1
            else:
                self.run_command('build_clib')
                build_clib = self.get_finalized_command('build_clib')
            self.library_dirs.append(build_clib.build_clib)
        else:
            build_clib = None
        from distutils.ccompiler import new_compiler
        from numpy.distutils.fcompiler import new_fcompiler
        compiler_type = self.compiler
        self.compiler = new_compiler(compiler=compiler_type, verbose=self.verbose, dry_run=self.dry_run, force=self.force)
        self.compiler.customize(self.distribution)
        self.compiler.customize_cmd(self)
        if self.warn_error:
            self.compiler.compiler.append('-Werror')
            self.compiler.compiler_so.append('-Werror')
        self.compiler.show_customization()
        if not self.disable_optimization:
            dispatch_hpath = os.path.join('numpy', 'distutils', 'include', 'npy_cpu_dispatch_config.h')
            dispatch_hpath = os.path.join(self.get_finalized_command('build_src').build_src, dispatch_hpath)
            opt_cache_path = os.path.abspath(os.path.join(self.build_temp, 'ccompiler_opt_cache_ext.py'))
            if hasattr(self, 'compiler_opt'):
                self.compiler_opt.cache_flush()
            self.compiler_opt = new_ccompiler_opt(compiler=self.compiler, dispatch_hpath=dispatch_hpath, cpu_baseline=self.cpu_baseline, cpu_dispatch=self.cpu_dispatch, cache_path=opt_cache_path)

            def report(copt):
                log.info('\n########### EXT COMPILER OPTIMIZATION ###########')
                log.info(copt.report(full=True))
            import atexit
            atexit.register(report, self.compiler_opt)
        self.extra_dll_dir = os.path.join(self.build_temp, '.libs')
        if not os.path.isdir(self.extra_dll_dir):
            os.makedirs(self.extra_dll_dir)
        clibs = {}
        if build_clib is not None:
            for (libname, build_info) in build_clib.libraries or []:
                if libname in clibs and clibs[libname] != build_info:
                    log.warn('library %r defined more than once, overwriting build_info\n%s... \nwith\n%s...' % (libname, repr(clibs[libname])[:300], repr(build_info)[:300]))
                clibs[libname] = build_info
        for (libname, build_info) in self.distribution.libraries or []:
            if libname in clibs:
                continue
            clibs[libname] = build_info
        all_languages = set()
        for ext in self.extensions:
            ext_languages = set()
            c_libs = []
            c_lib_dirs = []
            macros = []
            for libname in ext.libraries:
                if libname in clibs:
                    binfo = clibs[libname]
                    c_libs += binfo.get('libraries', [])
                    c_lib_dirs += binfo.get('library_dirs', [])
                    for m in binfo.get('macros', []):
                        if m not in macros:
                            macros.append(m)
                for l in clibs.get(libname, {}).get('source_languages', []):
                    ext_languages.add(l)
            if c_libs:
                new_c_libs = ext.libraries + c_libs
                log.info('updating extension %r libraries from %r to %r' % (ext.name, ext.libraries, new_c_libs))
                ext.libraries = new_c_libs
                ext.library_dirs = ext.library_dirs + c_lib_dirs
            if macros:
                log.info('extending extension %r defined_macros with %r' % (ext.name, macros))
                ext.define_macros = ext.define_macros + macros
            if has_f_sources(ext.sources):
                ext_languages.add('f77')
            if has_cxx_sources(ext.sources):
                ext_languages.add('c++')
            l = ext.language or self.compiler.detect_language(ext.sources)
            if l:
                ext_languages.add(l)
            if 'c++' in ext_languages:
                ext_language = 'c++'
            else:
                ext_language = 'c'
            has_fortran = False
            if 'f90' in ext_languages:
                ext_language = 'f90'
                has_fortran = True
            elif 'f77' in ext_languages:
                ext_language = 'f77'
                has_fortran = True
            if not ext.language or has_fortran:
                if l and l != ext_language and ext.language:
                    log.warn('resetting extension %r language from %r to %r.' % (ext.name, l, ext_language))
            ext.language = ext_language
            all_languages.update(ext_languages)
        need_f90_compiler = 'f90' in all_languages
        need_f77_compiler = 'f77' in all_languages
        need_cxx_compiler = 'c++' in all_languages
        if need_cxx_compiler:
            self._cxx_compiler = new_compiler(compiler=compiler_type, verbose=self.verbose, dry_run=self.dry_run, force=self.force)
            compiler = self._cxx_compiler
            compiler.customize(self.distribution, need_cxx=need_cxx_compiler)
            compiler.customize_cmd(self)
            compiler.show_customization()
            self._cxx_compiler = compiler.cxx_compiler()
        else:
            self._cxx_compiler = None
        if need_f77_compiler:
            ctype = self.fcompiler
            self._f77_compiler = new_fcompiler(compiler=self.fcompiler, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90=False, c_compiler=self.compiler)
            fcompiler = self._f77_compiler
            if fcompiler:
                ctype = fcompiler.compiler_type
                fcompiler.customize(self.distribution)
            if fcompiler and fcompiler.get_version():
                fcompiler.customize_cmd(self)
                fcompiler.show_customization()
            else:
                self.warn('f77_compiler=%s is not available.' % ctype)
                self._f77_compiler = None
        else:
            self._f77_compiler = None
        if need_f90_compiler:
            ctype = self.fcompiler
            self._f90_compiler = new_fcompiler(compiler=self.fcompiler, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90=True, c_compiler=self.compiler)
            fcompiler = self._f90_compiler
            if fcompiler:
                ctype = fcompiler.compiler_type
                fcompiler.customize(self.distribution)
            if fcompiler and fcompiler.get_version():
                fcompiler.customize_cmd(self)
                fcompiler.show_customization()
            else:
                self.warn('f90_compiler=%s is not available.' % ctype)
                self._f90_compiler = None
        else:
            self._f90_compiler = None
        self.build_extensions()
        pkg_roots = {self.get_ext_fullname(ext.name).split('.')[0] for ext in self.extensions}
        for pkg_root in pkg_roots:
            shared_lib_dir = os.path.join(pkg_root, '.libs')
            if not self.inplace:
                shared_lib_dir = os.path.join(self.build_lib, shared_lib_dir)
            for fn in os.listdir(self.extra_dll_dir):
                if not os.path.isdir(shared_lib_dir):
                    os.makedirs(shared_lib_dir)
                if not fn.lower().endswith('.dll'):
                    continue
                runtime_lib = os.path.join(self.extra_dll_dir, fn)
                copy_file(runtime_lib, shared_lib_dir)

    def swig_sources(self, sources, extensions=None):
        return sources

    def build_extension(self, ext):
        sources = ext.sources
        if sources is None or not is_sequence(sources):
            raise DistutilsSetupError(("in 'ext_modules' option (extension '%s'), " + "'sources' must be present and must be " + 'a list of source filenames') % ext.name)
        sources = list(sources)
        if not sources:
            return
        fullname = self.get_ext_fullname(ext.name)
        if self.inplace:
            modpath = fullname.split('.')
            package = '.'.join(modpath[0:-1])
            base = modpath[-1]
            build_py = self.get_finalized_command('build_py')
            package_dir = build_py.get_package_dir(package)
            ext_filename = os.path.join(package_dir, self.get_ext_filename(base))
        else:
            ext_filename = os.path.join(self.build_lib, self.get_ext_filename(fullname))
        depends = sources + ext.depends
        force_rebuild = self.force
        if not self.disable_optimization and (not self.compiler_opt.is_cached()):
            log.debug('Detected changes on compiler optimizations')
            force_rebuild = True
        if not (force_rebuild or newer_group(depends, ext_filename, 'newer')):
            log.debug("skipping '%s' extension (up-to-date)", ext.name)
            return
        else:
            log.info("building '%s' extension", ext.name)
        extra_args = ext.extra_compile_args or []
        extra_cflags = getattr(ext, 'extra_c_compile_args', None) or []
        extra_cxxflags = getattr(ext, 'extra_cxx_compile_args', None) or []
        macros = ext.define_macros[:]
        for undef in ext.undef_macros:
            macros.append((undef,))
        (c_sources, cxx_sources, f_sources, fmodule_sources) = filter_sources(ext.sources)
        if self.compiler.compiler_type == 'msvc':
            if cxx_sources:
                extra_args.append('/Zm1000')
                extra_cflags += extra_cxxflags
            c_sources += cxx_sources
            cxx_sources = []
        if ext.language == 'f90':
            fcompiler = self._f90_compiler
        elif ext.language == 'f77':
            fcompiler = self._f77_compiler
        else:
            fcompiler = self._f90_compiler or self._f77_compiler
        if fcompiler is not None:
            fcompiler.extra_f77_compile_args = ext.extra_f77_compile_args or [] if hasattr(ext, 'extra_f77_compile_args') else []
            fcompiler.extra_f90_compile_args = ext.extra_f90_compile_args or [] if hasattr(ext, 'extra_f90_compile_args') else []
        cxx_compiler = self._cxx_compiler
        if cxx_sources and cxx_compiler is None:
            raise DistutilsError('extension %r has C++ sourcesbut no C++ compiler found' % ext.name)
        if (f_sources or fmodule_sources) and fcompiler is None:
            raise DistutilsError('extension %r has Fortran sources but no Fortran compiler found' % ext.name)
        if ext.language in ['f77', 'f90'] and fcompiler is None:
            self.warn('extension %r has Fortran libraries but no Fortran linker found, using default linker' % ext.name)
        if ext.language == 'c++' and cxx_compiler is None:
            self.warn('extension %r has C++ libraries but no C++ linker found, using default linker' % ext.name)
        kws = {'depends': ext.depends}
        output_dir = self.build_temp
        include_dirs = ext.include_dirs + get_numpy_include_dirs()
        copt_c_sources = []
        copt_cxx_sources = []
        copt_baseline_flags = []
        copt_macros = []
        if not self.disable_optimization:
            bsrc_dir = self.get_finalized_command('build_src').build_src
            dispatch_hpath = os.path.join('numpy', 'distutils', 'include')
            dispatch_hpath = os.path.join(bsrc_dir, dispatch_hpath)
            include_dirs.append(dispatch_hpath)
            copt_build_src = bsrc_dir
            for (_srcs, _dst, _ext) in (((c_sources,), copt_c_sources, ('.dispatch.c',)), ((c_sources, cxx_sources), copt_cxx_sources, ('.dispatch.cpp', '.dispatch.cxx'))):
                for _src in _srcs:
                    _dst += [_src.pop(_src.index(s)) for s in _src[:] if s.endswith(_ext)]
            copt_baseline_flags = self.compiler_opt.cpu_baseline_flags()
        else:
            copt_macros.append(('NPY_DISABLE_OPTIMIZATION', 1))
        c_objects = []
        if copt_cxx_sources:
            log.info('compiling C++ dispatch-able sources')
            c_objects += self.compiler_opt.try_dispatch(copt_cxx_sources, output_dir=output_dir, src_dir=copt_build_src, macros=macros + copt_macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_args + extra_cxxflags, ccompiler=cxx_compiler, **kws)
        if copt_c_sources:
            log.info('compiling C dispatch-able sources')
            c_objects += self.compiler_opt.try_dispatch(copt_c_sources, output_dir=output_dir, src_dir=copt_build_src, macros=macros + copt_macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_args + extra_cflags, **kws)
        if c_sources:
            log.info('compiling C sources')
            c_objects += self.compiler.compile(c_sources, output_dir=output_dir, macros=macros + copt_macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_args + copt_baseline_flags + extra_cflags, **kws)
        if cxx_sources:
            log.info('compiling C++ sources')
            c_objects += cxx_compiler.compile(cxx_sources, output_dir=output_dir, macros=macros + copt_macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_args + copt_baseline_flags + extra_cxxflags, **kws)
        extra_postargs = []
        f_objects = []
        if fmodule_sources:
            log.info('compiling Fortran 90 module sources')
            module_dirs = ext.module_dirs[:]
            module_build_dir = os.path.join(self.build_temp, os.path.dirname(self.get_ext_filename(fullname)))
            self.mkpath(module_build_dir)
            if fcompiler.module_dir_switch is None:
                existing_modules = glob('*.mod')
            extra_postargs += fcompiler.module_options(module_dirs, module_build_dir)
            f_objects += fcompiler.compile(fmodule_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs, depends=ext.depends)
            if fcompiler.module_dir_switch is None:
                for f in glob('*.mod'):
                    if f in existing_modules:
                        continue
                    t = os.path.join(module_build_dir, f)
                    if os.path.abspath(f) == os.path.abspath(t):
                        continue
                    if os.path.isfile(t):
                        os.remove(t)
                    try:
                        self.move_file(f, module_build_dir)
                    except DistutilsFileError:
                        log.warn('failed to move %r to %r' % (f, module_build_dir))
        if f_sources:
            log.info('compiling Fortran sources')
            f_objects += fcompiler.compile(f_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs, depends=ext.depends)
        if f_objects and (not fcompiler.can_ccompiler_link(self.compiler)):
            unlinkable_fobjects = f_objects
            objects = c_objects
        else:
            unlinkable_fobjects = []
            objects = c_objects + f_objects
        if ext.extra_objects:
            objects.extend(ext.extra_objects)
        extra_args = ext.extra_link_args or []
        libraries = self.get_libraries(ext)[:]
        library_dirs = ext.library_dirs[:]
        linker = self.compiler.link_shared_object
        if self.compiler.compiler_type in ('msvc', 'intelw', 'intelemw'):
            self._libs_with_msvc_and_fortran(fcompiler, libraries, library_dirs)
            if ext.runtime_library_dirs:
                for d in ext.runtime_library_dirs:
                    for f in glob(d + '/*.dll'):
                        copy_file(f, self.extra_dll_dir)
                ext.runtime_library_dirs = []
        elif ext.language in ['f77', 'f90'] and fcompiler is not None:
            linker = fcompiler.link_shared_object
        if ext.language == 'c++' and cxx_compiler is not None:
            linker = cxx_compiler.link_shared_object
        if fcompiler is not None:
            (objects, libraries) = self._process_unlinkable_fobjects(objects, libraries, fcompiler, library_dirs, unlinkable_fobjects)
        linker(objects, ext_filename, libraries=libraries, library_dirs=library_dirs, runtime_library_dirs=ext.runtime_library_dirs, extra_postargs=extra_args, export_symbols=self.get_export_symbols(ext), debug=self.debug, build_temp=self.build_temp, target_lang=ext.language)

    def _add_dummy_mingwex_sym(self, c_sources):
        build_src = self.get_finalized_command('build_src').build_src
        build_clib = self.get_finalized_command('build_clib').build_clib
        objects = self.compiler.compile([os.path.join(build_src, 'gfortran_vs2003_hack.c')], output_dir=self.build_temp)
        self.compiler.create_static_lib(objects, '_gfortran_workaround', output_dir=build_clib, debug=self.debug)

    def _process_unlinkable_fobjects(self, objects, libraries, fcompiler, library_dirs, unlinkable_fobjects):
        libraries = list(libraries)
        objects = list(objects)
        unlinkable_fobjects = list(unlinkable_fobjects)
        for lib in libraries[:]:
            for libdir in library_dirs:
                fake_lib = os.path.join(libdir, lib + '.fobjects')
                if os.path.isfile(fake_lib):
                    libraries.remove(lib)
                    with open(fake_lib) as f:
                        unlinkable_fobjects.extend(f.read().splitlines())
                    c_lib = os.path.join(libdir, lib + '.cobjects')
                    with open(c_lib) as f:
                        objects.extend(f.read().splitlines())
        if unlinkable_fobjects:
            fobjects = [os.path.abspath(obj) for obj in unlinkable_fobjects]
            wrapped = fcompiler.wrap_unlinkable_objects(fobjects, output_dir=self.build_temp, extra_dll_dir=self.extra_dll_dir)
            objects.extend(wrapped)
        return (objects, libraries)

    def _libs_with_msvc_and_fortran(self, fcompiler, c_libraries, c_library_dirs):
        if fcompiler is None:
            return
        for libname in c_libraries:
            if libname.startswith('msvc'):
                continue
            fileexists = False
            for libdir in c_library_dirs or []:
                libfile = os.path.join(libdir, '%s.lib' % libname)
                if os.path.isfile(libfile):
                    fileexists = True
                    break
            if fileexists:
                continue
            fileexists = False
            for libdir in c_library_dirs:
                libfile = os.path.join(libdir, 'lib%s.a' % libname)
                if os.path.isfile(libfile):
                    libfile2 = os.path.join(self.build_temp, libname + '.lib')
                    copy_file(libfile, libfile2)
                    if self.build_temp not in c_library_dirs:
                        c_library_dirs.append(self.build_temp)
                    fileexists = True
                    break
            if fileexists:
                continue
            log.warn('could not find library %r in directories %s' % (libname, c_library_dirs))
        f_lib_dirs = []
        for dir in fcompiler.library_dirs:
            if dir.startswith('/usr/lib'):
                try:
                    dir = subprocess.check_output(['cygpath', '-w', dir])
                except (OSError, subprocess.CalledProcessError):
                    pass
                else:
                    dir = filepath_from_subprocess_output(dir)
            f_lib_dirs.append(dir)
        c_library_dirs.extend(f_lib_dirs)
        for lib in fcompiler.libraries:
            if not lib.startswith('msvc'):
                c_libraries.append(lib)
                p = combine_paths(f_lib_dirs, 'lib' + lib + '.a')
                if p:
                    dst_name = os.path.join(self.build_temp, lib + '.lib')
                    if not os.path.isfile(dst_name):
                        copy_file(p[0], dst_name)
                    if self.build_temp not in c_library_dirs:
                        c_library_dirs.append(self.build_temp)

    def get_source_files(self):
        self.check_extensions_list(self.extensions)
        filenames = []
        for ext in self.extensions:
            filenames.extend(get_ext_source_files(ext))
        return filenames

    def get_outputs(self):
        self.check_extensions_list(self.extensions)
        outputs = []
        for ext in self.extensions:
            if not ext.sources:
                continue
            fullname = self.get_ext_fullname(ext.name)
            outputs.append(os.path.join(self.build_lib, self.get_ext_filename(fullname)))
        return outputs

# File: numpy-main/numpy/distutils/command/build_py.py
from distutils.command.build_py import build_py as old_build_py
from numpy.distutils.misc_util import is_string

class build_py(old_build_py):

    def run(self):
        build_src = self.get_finalized_command('build_src')
        if build_src.py_modules_dict and self.packages is None:
            self.packages = list(build_src.py_modules_dict.keys())
        old_build_py.run(self)

    def find_package_modules(self, package, package_dir):
        modules = old_build_py.find_package_modules(self, package, package_dir)
        build_src = self.get_finalized_command('build_src')
        modules += build_src.py_modules_dict.get(package, [])
        return modules

    def find_modules(self):
        old_py_modules = self.py_modules[:]
        new_py_modules = [_m for _m in self.py_modules if is_string(_m)]
        self.py_modules[:] = new_py_modules
        modules = old_build_py.find_modules(self)
        self.py_modules[:] = old_py_modules
        return modules

# File: numpy-main/numpy/distutils/command/build_scripts.py
""""""
from distutils.command.build_scripts import build_scripts as old_build_scripts
from numpy.distutils import log
from numpy.distutils.misc_util import is_string

class build_scripts(old_build_scripts):

    def generate_scripts(self, scripts):
        new_scripts = []
        func_scripts = []
        for script in scripts:
            if is_string(script):
                new_scripts.append(script)
            else:
                func_scripts.append(script)
        if not func_scripts:
            return new_scripts
        build_dir = self.build_dir
        self.mkpath(build_dir)
        for func in func_scripts:
            script = func(build_dir)
            if not script:
                continue
            if is_string(script):
                log.info("  adding '%s' to scripts" % (script,))
                new_scripts.append(script)
            else:
                [log.info("  adding '%s' to scripts" % (s,)) for s in script]
                new_scripts.extend(list(script))
        return new_scripts

    def run(self):
        if not self.scripts:
            return
        self.scripts = self.generate_scripts(self.scripts)
        self.distribution.scripts = self.scripts
        return old_build_scripts.run(self)

    def get_source_files(self):
        from numpy.distutils.misc_util import get_script_files
        return get_script_files(self.scripts)

# File: numpy-main/numpy/distutils/command/build_src.py
""""""
import os
import re
import sys
import shlex
import copy
from distutils.command import build_ext
from distutils.dep_util import newer_group, newer
from distutils.util import get_platform
from distutils.errors import DistutilsError, DistutilsSetupError
from numpy.distutils import log
from numpy.distutils.misc_util import fortran_ext_match, appendpath, is_string, is_sequence, get_cmd
from numpy.distutils.from_template import process_file as process_f_file
from numpy.distutils.conv_template import process_file as process_c_file

def subst_vars(target, source, d):
    var = re.compile('@([a-zA-Z_]+)@')
    with open(source, 'r') as fs:
        with open(target, 'w') as ft:
            for l in fs:
                m = var.search(l)
                if m:
                    ft.write(l.replace('@%s@' % m.group(1), d[m.group(1)]))
                else:
                    ft.write(l)

class build_src(build_ext.build_ext):
    description = 'build sources from SWIG, F2PY files or a function'
    user_options = [('build-src=', 'd', 'directory to "build" sources to'), ('f2py-opts=', None, 'list of f2py command line options'), ('swig=', None, 'path to the SWIG executable'), ('swig-opts=', None, 'list of SWIG command line options'), ('swig-cpp', None, 'make SWIG create C++ files (default is autodetected from sources)'), ('f2pyflags=', None, 'additional flags to f2py (use --f2py-opts= instead)'), ('swigflags=', None, 'additional flags to swig (use --swig-opts= instead)'), ('force', 'f', 'forcibly build everything (ignore file timestamps)'), ('inplace', 'i', 'ignore build-lib and put compiled extensions into the source ' + 'directory alongside your pure Python modules'), ('verbose-cfg', None, 'change logging level from WARN to INFO which will show all ' + 'compiler output')]
    boolean_options = ['force', 'inplace', 'verbose-cfg']
    help_options = []

    def initialize_options(self):
        self.extensions = None
        self.package = None
        self.py_modules = None
        self.py_modules_dict = None
        self.build_src = None
        self.build_lib = None
        self.build_base = None
        self.force = None
        self.inplace = None
        self.package_dir = None
        self.f2pyflags = None
        self.f2py_opts = None
        self.swigflags = None
        self.swig_opts = None
        self.swig_cpp = None
        self.swig = None
        self.verbose_cfg = None

    def finalize_options(self):
        self.set_undefined_options('build', ('build_base', 'build_base'), ('build_lib', 'build_lib'), ('force', 'force'))
        if self.package is None:
            self.package = self.distribution.ext_package
        self.extensions = self.distribution.ext_modules
        self.libraries = self.distribution.libraries or []
        self.py_modules = self.distribution.py_modules or []
        self.data_files = self.distribution.data_files or []
        if self.build_src is None:
            plat_specifier = '.{}-{}.{}'.format(get_platform(), *sys.version_info[:2])
            self.build_src = os.path.join(self.build_base, 'src' + plat_specifier)
        self.py_modules_dict = {}
        if self.f2pyflags:
            if self.f2py_opts:
                log.warn('ignoring --f2pyflags as --f2py-opts already used')
            else:
                self.f2py_opts = self.f2pyflags
            self.f2pyflags = None
        if self.f2py_opts is None:
            self.f2py_opts = []
        else:
            self.f2py_opts = shlex.split(self.f2py_opts)
        if self.swigflags:
            if self.swig_opts:
                log.warn('ignoring --swigflags as --swig-opts already used')
            else:
                self.swig_opts = self.swigflags
            self.swigflags = None
        if self.swig_opts is None:
            self.swig_opts = []
        else:
            self.swig_opts = shlex.split(self.swig_opts)
        build_ext = self.get_finalized_command('build_ext')
        if self.inplace is None:
            self.inplace = build_ext.inplace
        if self.swig_cpp is None:
            self.swig_cpp = build_ext.swig_cpp
        for c in ['swig', 'swig_opt']:
            o = '--' + c.replace('_', '-')
            v = getattr(build_ext, c, None)
            if v:
                if getattr(self, c):
                    log.warn('both build_src and build_ext define %s option' % o)
                else:
                    log.info('using "%s=%s" option from build_ext command' % (o, v))
                    setattr(self, c, v)

    def run(self):
        log.info('build_src')
        if not (self.extensions or self.libraries):
            return
        self.build_sources()

    def build_sources(self):
        if self.inplace:
            self.get_package_dir = self.get_finalized_command('build_py').get_package_dir
        self.build_py_modules_sources()
        for libname_info in self.libraries:
            self.build_library_sources(*libname_info)
        if self.extensions:
            self.check_extensions_list(self.extensions)
            for ext in self.extensions:
                self.build_extension_sources(ext)
        self.build_data_files_sources()
        self.build_npy_pkg_config()

    def build_data_files_sources(self):
        if not self.data_files:
            return
        log.info('building data_files sources')
        from numpy.distutils.misc_util import get_data_files
        new_data_files = []
        for data in self.data_files:
            if isinstance(data, str):
                new_data_files.append(data)
            elif isinstance(data, tuple):
                (d, files) = data
                if self.inplace:
                    build_dir = self.get_package_dir('.'.join(d.split(os.sep)))
                else:
                    build_dir = os.path.join(self.build_src, d)
                funcs = [f for f in files if hasattr(f, '__call__')]
                files = [f for f in files if not hasattr(f, '__call__')]
                for f in funcs:
                    if f.__code__.co_argcount == 1:
                        s = f(build_dir)
                    else:
                        s = f()
                    if s is not None:
                        if isinstance(s, list):
                            files.extend(s)
                        elif isinstance(s, str):
                            files.append(s)
                        else:
                            raise TypeError(repr(s))
                filenames = get_data_files((d, files))
                new_data_files.append((d, filenames))
            else:
                raise TypeError(repr(data))
        self.data_files[:] = new_data_files

    def _build_npy_pkg_config(self, info, gd):
        (template, install_dir, subst_dict) = info
        template_dir = os.path.dirname(template)
        for (k, v) in gd.items():
            subst_dict[k] = v
        if self.inplace == 1:
            generated_dir = os.path.join(template_dir, install_dir)
        else:
            generated_dir = os.path.join(self.build_src, template_dir, install_dir)
        generated = os.path.basename(os.path.splitext(template)[0])
        generated_path = os.path.join(generated_dir, generated)
        if not os.path.exists(generated_dir):
            os.makedirs(generated_dir)
        subst_vars(generated_path, template, subst_dict)
        full_install_dir = os.path.join(template_dir, install_dir)
        return (full_install_dir, generated_path)

    def build_npy_pkg_config(self):
        log.info('build_src: building npy-pkg config files')
        install_cmd = copy.copy(get_cmd('install'))
        if not install_cmd.finalized == 1:
            install_cmd.finalize_options()
        build_npkg = False
        if self.inplace == 1:
            top_prefix = '.'
            build_npkg = True
        elif hasattr(install_cmd, 'install_libbase'):
            top_prefix = install_cmd.install_libbase
            build_npkg = True
        if build_npkg:
            for (pkg, infos) in self.distribution.installed_pkg_config.items():
                pkg_path = self.distribution.package_dir[pkg]
                prefix = os.path.join(os.path.abspath(top_prefix), pkg_path)
                d = {'prefix': prefix}
                for info in infos:
                    (install_dir, generated) = self._build_npy_pkg_config(info, d)
                    self.distribution.data_files.append((install_dir, [generated]))

    def build_py_modules_sources(self):
        if not self.py_modules:
            return
        log.info('building py_modules sources')
        new_py_modules = []
        for source in self.py_modules:
            if is_sequence(source) and len(source) == 3:
                (package, module_base, source) = source
                if self.inplace:
                    build_dir = self.get_package_dir(package)
                else:
                    build_dir = os.path.join(self.build_src, os.path.join(*package.split('.')))
                if hasattr(source, '__call__'):
                    target = os.path.join(build_dir, module_base + '.py')
                    source = source(target)
                if source is None:
                    continue
                modules = [(package, module_base, source)]
                if package not in self.py_modules_dict:
                    self.py_modules_dict[package] = []
                self.py_modules_dict[package] += modules
            else:
                new_py_modules.append(source)
        self.py_modules[:] = new_py_modules

    def build_library_sources(self, lib_name, build_info):
        sources = list(build_info.get('sources', []))
        if not sources:
            return
        log.info('building library "%s" sources' % lib_name)
        sources = self.generate_sources(sources, (lib_name, build_info))
        sources = self.template_sources(sources, (lib_name, build_info))
        (sources, h_files) = self.filter_h_files(sources)
        if h_files:
            log.info('%s - nothing done with h_files = %s', self.package, h_files)
        build_info['sources'] = sources
        return

    def build_extension_sources(self, ext):
        sources = list(ext.sources)
        log.info('building extension "%s" sources' % ext.name)
        fullname = self.get_ext_fullname(ext.name)
        modpath = fullname.split('.')
        package = '.'.join(modpath[0:-1])
        if self.inplace:
            self.ext_target_dir = self.get_package_dir(package)
        sources = self.generate_sources(sources, ext)
        sources = self.template_sources(sources, ext)
        sources = self.swig_sources(sources, ext)
        sources = self.f2py_sources(sources, ext)
        sources = self.pyrex_sources(sources, ext)
        (sources, py_files) = self.filter_py_files(sources)
        if package not in self.py_modules_dict:
            self.py_modules_dict[package] = []
        modules = []
        for f in py_files:
            module = os.path.splitext(os.path.basename(f))[0]
            modules.append((package, module, f))
        self.py_modules_dict[package] += modules
        (sources, h_files) = self.filter_h_files(sources)
        if h_files:
            log.info('%s - nothing done with h_files = %s', package, h_files)
        ext.sources = sources

    def generate_sources(self, sources, extension):
        new_sources = []
        func_sources = []
        for source in sources:
            if is_string(source):
                new_sources.append(source)
            else:
                func_sources.append(source)
        if not func_sources:
            return new_sources
        if self.inplace and (not is_sequence(extension)):
            build_dir = self.ext_target_dir
        else:
            if is_sequence(extension):
                name = extension[0]
            else:
                name = extension.name
            build_dir = os.path.join(*[self.build_src] + name.split('.')[:-1])
        self.mkpath(build_dir)
        if self.verbose_cfg:
            new_level = log.INFO
        else:
            new_level = log.WARN
        old_level = log.set_threshold(new_level)
        for func in func_sources:
            source = func(extension, build_dir)
            if not source:
                continue
            if is_sequence(source):
                [log.info("  adding '%s' to sources." % (s,)) for s in source]
                new_sources.extend(source)
            else:
                log.info("  adding '%s' to sources." % (source,))
                new_sources.append(source)
        log.set_threshold(old_level)
        return new_sources

    def filter_py_files(self, sources):
        return self.filter_files(sources, ['.py'])

    def filter_h_files(self, sources):
        return self.filter_files(sources, ['.h', '.hpp', '.inc'])

    def filter_files(self, sources, exts=[]):
        new_sources = []
        files = []
        for source in sources:
            (base, ext) = os.path.splitext(source)
            if ext in exts:
                files.append(source)
            else:
                new_sources.append(source)
        return (new_sources, files)

    def template_sources(self, sources, extension):
        new_sources = []
        if is_sequence(extension):
            depends = extension[1].get('depends')
            include_dirs = extension[1].get('include_dirs')
        else:
            depends = extension.depends
            include_dirs = extension.include_dirs
        for source in sources:
            (base, ext) = os.path.splitext(source)
            if ext == '.src':
                if self.inplace:
                    target_dir = os.path.dirname(base)
                else:
                    target_dir = appendpath(self.build_src, os.path.dirname(base))
                self.mkpath(target_dir)
                target_file = os.path.join(target_dir, os.path.basename(base))
                if self.force or newer_group([source] + depends, target_file):
                    if _f_pyf_ext_match(base):
                        log.info('from_template:> %s' % target_file)
                        outstr = process_f_file(source)
                    else:
                        log.info('conv_template:> %s' % target_file)
                        outstr = process_c_file(source)
                    with open(target_file, 'w') as fid:
                        fid.write(outstr)
                if _header_ext_match(target_file):
                    d = os.path.dirname(target_file)
                    if d not in include_dirs:
                        log.info("  adding '%s' to include_dirs." % d)
                        include_dirs.append(d)
                new_sources.append(target_file)
            else:
                new_sources.append(source)
        return new_sources

    def pyrex_sources(self, sources, extension):
        new_sources = []
        ext_name = extension.name.split('.')[-1]
        for source in sources:
            (base, ext) = os.path.splitext(source)
            if ext == '.pyx':
                target_file = self.generate_a_pyrex_source(base, ext_name, source, extension)
                new_sources.append(target_file)
            else:
                new_sources.append(source)
        return new_sources

    def generate_a_pyrex_source(self, base, ext_name, source, extension):
        return []

    def f2py_sources(self, sources, extension):
        new_sources = []
        f2py_sources = []
        f_sources = []
        f2py_targets = {}
        target_dirs = []
        ext_name = extension.name.split('.')[-1]
        skip_f2py = 0
        for source in sources:
            (base, ext) = os.path.splitext(source)
            if ext == '.pyf':
                if self.inplace:
                    target_dir = os.path.dirname(base)
                else:
                    target_dir = appendpath(self.build_src, os.path.dirname(base))
                if os.path.isfile(source):
                    name = get_f2py_modulename(source)
                    if name != ext_name:
                        raise DistutilsSetupError('mismatch of extension names: %s provides %r but expected %r' % (source, name, ext_name))
                    target_file = os.path.join(target_dir, name + 'module.c')
                else:
                    log.debug("  source %s does not exist: skipping f2py'ing." % source)
                    name = ext_name
                    skip_f2py = 1
                    target_file = os.path.join(target_dir, name + 'module.c')
                    if not os.path.isfile(target_file):
                        log.warn('  target %s does not exist:\n   Assuming %smodule.c was generated with "build_src --inplace" command.' % (target_file, name))
                        target_dir = os.path.dirname(base)
                        target_file = os.path.join(target_dir, name + 'module.c')
                        if not os.path.isfile(target_file):
                            raise DistutilsSetupError('%r missing' % (target_file,))
                        log.info('   Yes! Using %r as up-to-date target.' % target_file)
                target_dirs.append(target_dir)
                f2py_sources.append(source)
                f2py_targets[source] = target_file
                new_sources.append(target_file)
            elif fortran_ext_match(ext):
                f_sources.append(source)
            else:
                new_sources.append(source)
        if not (f2py_sources or f_sources):
            return new_sources
        for d in target_dirs:
            self.mkpath(d)
        f2py_options = extension.f2py_options + self.f2py_opts
        if self.distribution.libraries:
            for (name, build_info) in self.distribution.libraries:
                if name in extension.libraries:
                    f2py_options.extend(build_info.get('f2py_options', []))
        log.info('f2py options: %s' % f2py_options)
        if f2py_sources:
            if len(f2py_sources) != 1:
                raise DistutilsSetupError('only one .pyf file is allowed per extension module but got more: %r' % (f2py_sources,))
            source = f2py_sources[0]
            target_file = f2py_targets[source]
            target_dir = os.path.dirname(target_file) or '.'
            depends = [source] + extension.depends
            if (self.force or newer_group(depends, target_file, 'newer')) and (not skip_f2py):
                log.info('f2py: %s' % source)
                from numpy.f2py import f2py2e
                f2py2e.run_main(f2py_options + ['--build-dir', target_dir, source])
            else:
                log.debug("  skipping '%s' f2py interface (up-to-date)" % source)
        else:
            if is_sequence(extension):
                name = extension[0]
            else:
                name = extension.name
            target_dir = os.path.join(*[self.build_src] + name.split('.')[:-1])
            target_file = os.path.join(target_dir, ext_name + 'module.c')
            new_sources.append(target_file)
            depends = f_sources + extension.depends
            if (self.force or newer_group(depends, target_file, 'newer')) and (not skip_f2py):
                log.info('f2py:> %s' % target_file)
                self.mkpath(target_dir)
                from numpy.f2py import f2py2e
                f2py2e.run_main(f2py_options + ['--lower', '--build-dir', target_dir] + ['-m', ext_name] + f_sources)
            else:
                log.debug("  skipping f2py fortran files for '%s' (up-to-date)" % target_file)
        if not os.path.isfile(target_file):
            raise DistutilsError('f2py target file %r not generated' % (target_file,))
        build_dir = os.path.join(self.build_src, target_dir)
        target_c = os.path.join(build_dir, 'fortranobject.c')
        target_h = os.path.join(build_dir, 'fortranobject.h')
        log.info("  adding '%s' to sources." % target_c)
        new_sources.append(target_c)
        if build_dir not in extension.include_dirs:
            log.info("  adding '%s' to include_dirs." % build_dir)
            extension.include_dirs.append(build_dir)
        if not skip_f2py:
            import numpy.f2py
            d = os.path.dirname(numpy.f2py.__file__)
            source_c = os.path.join(d, 'src', 'fortranobject.c')
            source_h = os.path.join(d, 'src', 'fortranobject.h')
            if newer(source_c, target_c) or newer(source_h, target_h):
                self.mkpath(os.path.dirname(target_c))
                self.copy_file(source_c, target_c)
                self.copy_file(source_h, target_h)
        else:
            if not os.path.isfile(target_c):
                raise DistutilsSetupError('f2py target_c file %r not found' % (target_c,))
            if not os.path.isfile(target_h):
                raise DistutilsSetupError('f2py target_h file %r not found' % (target_h,))
        for name_ext in ['-f2pywrappers.f', '-f2pywrappers2.f90']:
            filename = os.path.join(target_dir, ext_name + name_ext)
            if os.path.isfile(filename):
                log.info("  adding '%s' to sources." % filename)
                f_sources.append(filename)
        return new_sources + f_sources

    def swig_sources(self, sources, extension):
        new_sources = []
        swig_sources = []
        swig_targets = {}
        target_dirs = []
        py_files = []
        target_ext = '.c'
        if '-c++' in extension.swig_opts:
            typ = 'c++'
            is_cpp = True
            extension.swig_opts.remove('-c++')
        elif self.swig_cpp:
            typ = 'c++'
            is_cpp = True
        else:
            typ = None
            is_cpp = False
        skip_swig = 0
        ext_name = extension.name.split('.')[-1]
        for source in sources:
            (base, ext) = os.path.splitext(source)
            if ext == '.i':
                if self.inplace:
                    target_dir = os.path.dirname(base)
                    py_target_dir = self.ext_target_dir
                else:
                    target_dir = appendpath(self.build_src, os.path.dirname(base))
                    py_target_dir = target_dir
                if os.path.isfile(source):
                    name = get_swig_modulename(source)
                    if name != ext_name[1:]:
                        raise DistutilsSetupError('mismatch of extension names: %s provides %r but expected %r' % (source, name, ext_name[1:]))
                    if typ is None:
                        typ = get_swig_target(source)
                        is_cpp = typ == 'c++'
                    else:
                        typ2 = get_swig_target(source)
                        if typ2 is None:
                            log.warn('source %r does not define swig target, assuming %s swig target' % (source, typ))
                        elif typ != typ2:
                            log.warn('expected %r but source %r defines %r swig target' % (typ, source, typ2))
                            if typ2 == 'c++':
                                log.warn('resetting swig target to c++ (some targets may have .c extension)')
                                is_cpp = True
                            else:
                                log.warn('assuming that %r has c++ swig target' % source)
                    if is_cpp:
                        target_ext = '.cpp'
                    target_file = os.path.join(target_dir, '%s_wrap%s' % (name, target_ext))
                else:
                    log.warn("  source %s does not exist: skipping swig'ing." % source)
                    name = ext_name[1:]
                    skip_swig = 1
                    target_file = _find_swig_target(target_dir, name)
                    if not os.path.isfile(target_file):
                        log.warn('  target %s does not exist:\n   Assuming %s_wrap.{c,cpp} was generated with "build_src --inplace" command.' % (target_file, name))
                        target_dir = os.path.dirname(base)
                        target_file = _find_swig_target(target_dir, name)
                        if not os.path.isfile(target_file):
                            raise DistutilsSetupError('%r missing' % (target_file,))
                        log.warn('   Yes! Using %r as up-to-date target.' % target_file)
                target_dirs.append(target_dir)
                new_sources.append(target_file)
                py_files.append(os.path.join(py_target_dir, name + '.py'))
                swig_sources.append(source)
                swig_targets[source] = new_sources[-1]
            else:
                new_sources.append(source)
        if not swig_sources:
            return new_sources
        if skip_swig:
            return new_sources + py_files
        for d in target_dirs:
            self.mkpath(d)
        swig = self.swig or self.find_swig()
        swig_cmd = [swig, '-python'] + extension.swig_opts
        if is_cpp:
            swig_cmd.append('-c++')
        for d in extension.include_dirs:
            swig_cmd.append('-I' + d)
        for source in swig_sources:
            target = swig_targets[source]
            depends = [source] + extension.depends
            if self.force or newer_group(depends, target, 'newer'):
                log.info('%s: %s' % (os.path.basename(swig) + (is_cpp and '++' or ''), source))
                self.spawn(swig_cmd + self.swig_opts + ['-o', target, '-outdir', py_target_dir, source])
            else:
                log.debug("  skipping '%s' swig interface (up-to-date)" % source)
        return new_sources + py_files
_f_pyf_ext_match = re.compile('.*\\.(f90|f95|f77|for|ftn|f|pyf)\\Z', re.I).match
_header_ext_match = re.compile('.*\\.(inc|h|hpp)\\Z', re.I).match
_swig_module_name_match = re.compile('\\s*%module\\s*(.*\\(\\s*package\\s*=\\s*"(?P[\\w_]+)".*\\)|)\\s*(?P[\\w_]+)', re.I).match
_has_c_header = re.compile('-\\*-\\s*c\\s*-\\*-', re.I).search
_has_cpp_header = re.compile('-\\*-\\s*c\\+\\+\\s*-\\*-', re.I).search

def get_swig_target(source):
    with open(source) as f:
        result = None
        line = f.readline()
        if _has_cpp_header(line):
            result = 'c++'
        if _has_c_header(line):
            result = 'c'
    return result

def get_swig_modulename(source):
    with open(source) as f:
        name = None
        for line in f:
            m = _swig_module_name_match(line)
            if m:
                name = m.group('name')
                break
    return name

def _find_swig_target(target_dir, name):
    for ext in ['.cpp', '.c']:
        target = os.path.join(target_dir, '%s_wrap%s' % (name, ext))
        if os.path.isfile(target):
            break
    return target
_f2py_module_name_match = re.compile('\\s*python\\s*module\\s*(?P[\\w_]+)', re.I).match
_f2py_user_module_name_match = re.compile('\\s*python\\s*module\\s*(?P[\\w_]*?__user__[\\w_]*)', re.I).match

def get_f2py_modulename(source):
    name = None
    with open(source) as f:
        for line in f:
            m = _f2py_module_name_match(line)
            if m:
                if _f2py_user_module_name_match(line):
                    continue
                name = m.group('name')
                break
    return name

# File: numpy-main/numpy/distutils/command/config.py
import os
import signal
import subprocess
import sys
import textwrap
import warnings
from distutils.command.config import config as old_config
from distutils.command.config import LANG_EXT
from distutils import log
from distutils.file_util import copy_file
from distutils.ccompiler import CompileError, LinkError
import distutils
from numpy.distutils.exec_command import filepath_from_subprocess_output
from numpy.distutils.mingw32ccompiler import generate_manifest
from numpy.distutils.command.autodist import check_gcc_function_attribute, check_gcc_function_attribute_with_intrinsics, check_gcc_variable_attribute, check_gcc_version_at_least, check_inline, check_restrict, check_compiler_gcc
LANG_EXT['f77'] = '.f'
LANG_EXT['f90'] = '.f90'

class config(old_config):
    old_config.user_options += [('fcompiler=', None, 'specify the Fortran compiler type')]

    def initialize_options(self):
        self.fcompiler = None
        old_config.initialize_options(self)

    def _check_compiler(self):
        old_config._check_compiler(self)
        from numpy.distutils.fcompiler import FCompiler, new_fcompiler
        if sys.platform == 'win32' and self.compiler.compiler_type in ('msvc', 'intelw', 'intelemw'):
            if not self.compiler.initialized:
                try:
                    self.compiler.initialize()
                except OSError as e:
                    msg = textwrap.dedent('                        Could not initialize compiler instance: do you have Visual Studio\n                        installed?  If you are trying to build with MinGW, please use "python setup.py\n                        build -c mingw32" instead.  If you have Visual Studio installed, check it is\n                        correctly installed, and the right version (VS 2015 as of this writing).\n\n                        Original exception was: %s, and the Compiler class was %s\n                        ============================================================================') % (e, self.compiler.__class__.__name__)
                    print(textwrap.dedent('                        ============================================================================'))
                    raise distutils.errors.DistutilsPlatformError(msg) from e
            from distutils import msvc9compiler
            if msvc9compiler.get_build_version() >= 10:
                for ldflags in [self.compiler.ldflags_shared, self.compiler.ldflags_shared_debug]:
                    if '/MANIFEST' not in ldflags:
                        ldflags.append('/MANIFEST')
        if not isinstance(self.fcompiler, FCompiler):
            self.fcompiler = new_fcompiler(compiler=self.fcompiler, dry_run=self.dry_run, force=1, c_compiler=self.compiler)
            if self.fcompiler is not None:
                self.fcompiler.customize(self.distribution)
                if self.fcompiler.get_version():
                    self.fcompiler.customize_cmd(self)
                    self.fcompiler.show_customization()

    def _wrap_method(self, mth, lang, args):
        from distutils.ccompiler import CompileError
        from distutils.errors import DistutilsExecError
        save_compiler = self.compiler
        if lang in ['f77', 'f90']:
            self.compiler = self.fcompiler
        if self.compiler is None:
            raise CompileError('%s compiler is not set' % (lang,))
        try:
            ret = mth(*(self,) + args)
        except (DistutilsExecError, CompileError) as e:
            self.compiler = save_compiler
            raise CompileError from e
        self.compiler = save_compiler
        return ret

    def _compile(self, body, headers, include_dirs, lang):
        (src, obj) = self._wrap_method(old_config._compile, lang, (body, headers, include_dirs, lang))
        self.temp_files.append(obj + '.d')
        return (src, obj)

    def _link(self, body, headers, include_dirs, libraries, library_dirs, lang):
        if self.compiler.compiler_type == 'msvc':
            libraries = (libraries or [])[:]
            library_dirs = (library_dirs or [])[:]
            if lang in ['f77', 'f90']:
                lang = 'c'
                if self.fcompiler:
                    for d in self.fcompiler.library_dirs or []:
                        if d.startswith('/usr/lib'):
                            try:
                                d = subprocess.check_output(['cygpath', '-w', d])
                            except (OSError, subprocess.CalledProcessError):
                                pass
                            else:
                                d = filepath_from_subprocess_output(d)
                        library_dirs.append(d)
                    for libname in self.fcompiler.libraries or []:
                        if libname not in libraries:
                            libraries.append(libname)
            for libname in libraries:
                if libname.startswith('msvc'):
                    continue
                fileexists = False
                for libdir in library_dirs or []:
                    libfile = os.path.join(libdir, '%s.lib' % libname)
                    if os.path.isfile(libfile):
                        fileexists = True
                        break
                if fileexists:
                    continue
                fileexists = False
                for libdir in library_dirs:
                    libfile = os.path.join(libdir, 'lib%s.a' % libname)
                    if os.path.isfile(libfile):
                        libfile2 = os.path.join(libdir, '%s.lib' % libname)
                        copy_file(libfile, libfile2)
                        self.temp_files.append(libfile2)
                        fileexists = True
                        break
                if fileexists:
                    continue
                log.warn('could not find library %r in directories %s' % (libname, library_dirs))
        elif self.compiler.compiler_type == 'mingw32':
            generate_manifest(self)
        return self._wrap_method(old_config._link, lang, (body, headers, include_dirs, libraries, library_dirs, lang))

    def check_header(self, header, include_dirs=None, library_dirs=None, lang='c'):
        self._check_compiler()
        return self.try_compile('/* we need a dummy line to make distutils happy */', [header], include_dirs)

    def check_decl(self, symbol, headers=None, include_dirs=None):
        self._check_compiler()
        body = textwrap.dedent('\n            int main(void)\n            {\n            #ifndef %s\n                (void) %s;\n            #endif\n                ;\n                return 0;\n            }') % (symbol, symbol)
        return self.try_compile(body, headers, include_dirs)

    def check_macro_true(self, symbol, headers=None, include_dirs=None):
        self._check_compiler()
        body = textwrap.dedent('\n            int main(void)\n            {\n            #if %s\n            #else\n            #error false or undefined macro\n            #endif\n                ;\n                return 0;\n            }') % (symbol,)
        return self.try_compile(body, headers, include_dirs)

    def check_type(self, type_name, headers=None, include_dirs=None, library_dirs=None):
        self._check_compiler()
        body = textwrap.dedent('\n            int main(void) {\n              if ((%(name)s *) 0)\n                return 0;\n              if (sizeof (%(name)s))\n                return 0;\n            }\n            ') % {'name': type_name}
        st = False
        try:
            try:
                self._compile(body % {'type': type_name}, headers, include_dirs, 'c')
                st = True
            except distutils.errors.CompileError:
                st = False
        finally:
            self._clean()
        return st

    def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None):
        self._check_compiler()
        body = textwrap.dedent('\n            typedef %(type)s npy_check_sizeof_type;\n            int main (void)\n            {\n                static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)];\n                test_array [0] = 0\n\n                ;\n                return 0;\n            }\n            ')
        self._compile(body % {'type': type_name}, headers, include_dirs, 'c')
        self._clean()
        if expected:
            body = textwrap.dedent('\n                typedef %(type)s npy_check_sizeof_type;\n                int main (void)\n                {\n                    static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)];\n                    test_array [0] = 0\n\n                    ;\n                    return 0;\n                }\n                ')
            for size in expected:
                try:
                    self._compile(body % {'type': type_name, 'size': size}, headers, include_dirs, 'c')
                    self._clean()
                    return size
                except CompileError:
                    pass
        body = textwrap.dedent('\n            typedef %(type)s npy_check_sizeof_type;\n            int main (void)\n            {\n                static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)];\n                test_array [0] = 0\n\n                ;\n                return 0;\n            }\n            ')
        low = 0
        mid = 0
        while True:
            try:
                self._compile(body % {'type': type_name, 'size': mid}, headers, include_dirs, 'c')
                self._clean()
                break
            except CompileError:
                low = mid + 1
                mid = 2 * mid + 1
        high = mid
        while low != high:
            mid = (high - low) // 2 + low
            try:
                self._compile(body % {'type': type_name, 'size': mid}, headers, include_dirs, 'c')
                self._clean()
                high = mid
            except CompileError:
                low = mid + 1
        return low

    def check_func(self, func, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None):
        self._check_compiler()
        body = []
        if decl:
            if type(decl) == str:
                body.append(decl)
            else:
                body.append('int %s (void);' % func)
        body.append('#ifdef _MSC_VER')
        body.append('#pragma function(%s)' % func)
        body.append('#endif')
        body.append('int main (void) {')
        if call:
            if call_args is None:
                call_args = ''
            body.append('  %s(%s);' % (func, call_args))
        else:
            body.append('  %s;' % func)
        body.append('  return 0;')
        body.append('}')
        body = '\n'.join(body) + '\n'
        return self.try_link(body, headers, include_dirs, libraries, library_dirs)

    def check_funcs_once(self, funcs, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None):
        self._check_compiler()
        body = []
        if decl:
            for (f, v) in decl.items():
                if v:
                    body.append('int %s (void);' % f)
        body.append('#ifdef _MSC_VER')
        for func in funcs:
            body.append('#pragma function(%s)' % func)
        body.append('#endif')
        body.append('int main (void) {')
        if call:
            for f in funcs:
                if f in call and call[f]:
                    if not (call_args and f in call_args and call_args[f]):
                        args = ''
                    else:
                        args = call_args[f]
                    body.append('  %s(%s);' % (f, args))
                else:
                    body.append('  %s;' % f)
        else:
            for f in funcs:
                body.append('  %s;' % f)
        body.append('  return 0;')
        body.append('}')
        body = '\n'.join(body) + '\n'
        return self.try_link(body, headers, include_dirs, libraries, library_dirs)

    def check_inline(self):
        return check_inline(self)

    def check_restrict(self):
        return check_restrict(self)

    def check_compiler_gcc(self):
        return check_compiler_gcc(self)

    def check_gcc_function_attribute(self, attribute, name):
        return check_gcc_function_attribute(self, attribute, name)

    def check_gcc_function_attribute_with_intrinsics(self, attribute, name, code, include):
        return check_gcc_function_attribute_with_intrinsics(self, attribute, name, code, include)

    def check_gcc_variable_attribute(self, attribute):
        return check_gcc_variable_attribute(self, attribute)

    def check_gcc_version_at_least(self, major, minor=0, patchlevel=0):
        return check_gcc_version_at_least(self, major, minor, patchlevel)

    def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang='c', use_tee=None):
        warnings.warn('\n+++++++++++++++++++++++++++++++++++++++++++++++++\nUsage of get_output is deprecated: please do not \nuse it anymore, and avoid configuration checks \ninvolving running executable on the target machine.\n+++++++++++++++++++++++++++++++++++++++++++++++++\n', DeprecationWarning, stacklevel=2)
        self._check_compiler()
        (exitcode, output) = (255, '')
        try:
            grabber = GrabStdout()
            try:
                (src, obj, exe) = self._link(body, headers, include_dirs, libraries, library_dirs, lang)
                grabber.restore()
            except Exception:
                output = grabber.data
                grabber.restore()
                raise
            exe = os.path.join('.', exe)
            try:
                output = subprocess.check_output([exe], cwd='.')
            except subprocess.CalledProcessError as exc:
                exitstatus = exc.returncode
                output = ''
            except OSError:
                exitstatus = 127
                output = ''
            else:
                output = filepath_from_subprocess_output(output)
            if hasattr(os, 'WEXITSTATUS'):
                exitcode = os.WEXITSTATUS(exitstatus)
                if os.WIFSIGNALED(exitstatus):
                    sig = os.WTERMSIG(exitstatus)
                    log.error('subprocess exited with signal %d' % (sig,))
                    if sig == signal.SIGINT:
                        raise KeyboardInterrupt
            else:
                exitcode = exitstatus
            log.info('success!')
        except (CompileError, LinkError):
            log.info('failure.')
        self._clean()
        return (exitcode, output)

class GrabStdout:

    def __init__(self):
        self.sys_stdout = sys.stdout
        self.data = ''
        sys.stdout = self

    def write(self, data):
        self.sys_stdout.write(data)
        self.data += data

    def flush(self):
        self.sys_stdout.flush()

    def restore(self):
        sys.stdout = self.sys_stdout

# File: numpy-main/numpy/distutils/command/config_compiler.py
from distutils.core import Command
from numpy.distutils import log

def show_fortran_compilers(_cache=None):
    if _cache:
        return
    elif _cache is None:
        _cache = []
    _cache.append(1)
    from numpy.distutils.fcompiler import show_fcompilers
    import distutils.core
    dist = distutils.core._setup_distribution
    show_fcompilers(dist)

class config_fc(Command):
    description = 'specify Fortran 77/Fortran 90 compiler information'
    user_options = [('fcompiler=', None, 'specify Fortran compiler type'), ('f77exec=', None, 'specify F77 compiler command'), ('f90exec=', None, 'specify F90 compiler command'), ('f77flags=', None, 'specify F77 compiler flags'), ('f90flags=', None, 'specify F90 compiler flags'), ('opt=', None, 'specify optimization flags'), ('arch=', None, 'specify architecture specific optimization flags'), ('debug', 'g', 'compile with debugging information'), ('noopt', None, 'compile without optimization'), ('noarch', None, 'compile without arch-dependent optimization')]
    help_options = [('help-fcompiler', None, 'list available Fortran compilers', show_fortran_compilers)]
    boolean_options = ['debug', 'noopt', 'noarch']

    def initialize_options(self):
        self.fcompiler = None
        self.f77exec = None
        self.f90exec = None
        self.f77flags = None
        self.f90flags = None
        self.opt = None
        self.arch = None
        self.debug = None
        self.noopt = None
        self.noarch = None

    def finalize_options(self):
        log.info('unifying config_fc, config, build_clib, build_ext, build commands --fcompiler options')
        build_clib = self.get_finalized_command('build_clib')
        build_ext = self.get_finalized_command('build_ext')
        config = self.get_finalized_command('config')
        build = self.get_finalized_command('build')
        cmd_list = [self, config, build_clib, build_ext, build]
        for a in ['fcompiler']:
            l = []
            for c in cmd_list:
                v = getattr(c, a)
                if v is not None:
                    if not isinstance(v, str):
                        v = v.compiler_type
                    if v not in l:
                        l.append(v)
            if not l:
                v1 = None
            else:
                v1 = l[0]
            if len(l) > 1:
                log.warn('  commands have different --%s options: %s, using first in list as default' % (a, l))
            if v1:
                for c in cmd_list:
                    if getattr(c, a) is None:
                        setattr(c, a, v1)

    def run(self):
        return

class config_cc(Command):
    description = 'specify C/C++ compiler information'
    user_options = [('compiler=', None, 'specify C/C++ compiler type')]

    def initialize_options(self):
        self.compiler = None

    def finalize_options(self):
        log.info('unifying config_cc, config, build_clib, build_ext, build commands --compiler options')
        build_clib = self.get_finalized_command('build_clib')
        build_ext = self.get_finalized_command('build_ext')
        config = self.get_finalized_command('config')
        build = self.get_finalized_command('build')
        cmd_list = [self, config, build_clib, build_ext, build]
        for a in ['compiler']:
            l = []
            for c in cmd_list:
                v = getattr(c, a)
                if v is not None:
                    if not isinstance(v, str):
                        v = v.compiler_type
                    if v not in l:
                        l.append(v)
            if not l:
                v1 = None
            else:
                v1 = l[0]
            if len(l) > 1:
                log.warn('  commands have different --%s options: %s, using first in list as default' % (a, l))
            if v1:
                for c in cmd_list:
                    if getattr(c, a) is None:
                        setattr(c, a, v1)
        return

    def run(self):
        return

# File: numpy-main/numpy/distutils/command/develop.py
""""""
from setuptools.command.develop import develop as old_develop

class develop(old_develop):
    __doc__ = old_develop.__doc__

    def install_for_development(self):
        self.reinitialize_command('build_src', inplace=1)
        self.run_command('build_scripts')
        old_develop.install_for_development(self)

# File: numpy-main/numpy/distutils/command/egg_info.py
import sys
from setuptools.command.egg_info import egg_info as _egg_info

class egg_info(_egg_info):

    def run(self):
        if 'sdist' in sys.argv:
            import warnings
            import textwrap
            msg = textwrap.dedent('\n                `build_src` is being run, this may lead to missing\n                files in your sdist!  You want to use distutils.sdist\n                instead of the setuptools version:\n\n                    from distutils.command.sdist import sdist\n                    cmdclass={\'sdist\': sdist}"\n\n                See numpy\'s setup.py or gh-7131 for details.')
            warnings.warn(msg, UserWarning, stacklevel=2)
        self.run_command('build_src')
        _egg_info.run(self)

# File: numpy-main/numpy/distutils/command/install.py
import sys
if 'setuptools' in sys.modules:
    import setuptools.command.install as old_install_mod
    have_setuptools = True
else:
    import distutils.command.install as old_install_mod
    have_setuptools = False
from distutils.file_util import write_file
old_install = old_install_mod.install

class install(old_install):
    sub_commands = old_install.sub_commands + [('install_clib', lambda x: True)]

    def finalize_options(self):
        old_install.finalize_options(self)
        self.install_lib = self.install_libbase

    def setuptools_run(self):
        from distutils.command.install import install as distutils_install
        if self.old_and_unmanageable or self.single_version_externally_managed:
            return distutils_install.run(self)
        caller = sys._getframe(3)
        caller_module = caller.f_globals.get('__name__', '')
        caller_name = caller.f_code.co_name
        if caller_module != 'distutils.dist' or caller_name != 'run_commands':
            distutils_install.run(self)
        else:
            self.do_egg_install()

    def run(self):
        if not have_setuptools:
            r = old_install.run(self)
        else:
            r = self.setuptools_run()
        if self.record:
            with open(self.record) as f:
                lines = []
                need_rewrite = False
                for l in f:
                    l = l.rstrip()
                    if ' ' in l:
                        need_rewrite = True
                        l = '"%s"' % l
                    lines.append(l)
            if need_rewrite:
                self.execute(write_file, (self.record, lines), "re-writing list of installed files to '%s'" % self.record)
        return r

# File: numpy-main/numpy/distutils/command/install_clib.py
import os
from distutils.core import Command
from distutils.ccompiler import new_compiler
from numpy.distutils.misc_util import get_cmd

class install_clib(Command):
    description = 'Command to install installable C libraries'
    user_options = []

    def initialize_options(self):
        self.install_dir = None
        self.outfiles = []

    def finalize_options(self):
        self.set_undefined_options('install', ('install_lib', 'install_dir'))

    def run(self):
        build_clib_cmd = get_cmd('build_clib')
        if not build_clib_cmd.build_clib:
            build_clib_cmd.finalize_options()
        build_dir = build_clib_cmd.build_clib
        if not build_clib_cmd.compiler:
            compiler = new_compiler(compiler=None)
            compiler.customize(self.distribution)
        else:
            compiler = build_clib_cmd.compiler
        for l in self.distribution.installed_libraries:
            target_dir = os.path.join(self.install_dir, l.target_dir)
            name = compiler.library_filename(l.name)
            source = os.path.join(build_dir, name)
            self.mkpath(target_dir)
            self.outfiles.append(self.copy_file(source, target_dir)[0])

    def get_outputs(self):
        return self.outfiles

# File: numpy-main/numpy/distutils/command/install_data.py
import sys
have_setuptools = 'setuptools' in sys.modules
from distutils.command.install_data import install_data as old_install_data

class install_data(old_install_data):

    def run(self):
        old_install_data.run(self)
        if have_setuptools:
            self.run_command('install_clib')

    def finalize_options(self):
        self.set_undefined_options('install', ('install_lib', 'install_dir'), ('root', 'root'), ('force', 'force'))

# File: numpy-main/numpy/distutils/command/install_headers.py
import os
from distutils.command.install_headers import install_headers as old_install_headers

class install_headers(old_install_headers):

    def run(self):
        headers = self.distribution.headers
        if not headers:
            return
        prefix = os.path.dirname(self.install_dir)
        for header in headers:
            if isinstance(header, tuple):
                if header[0] == 'numpy._core':
                    header = ('numpy', header[1])
                    if os.path.splitext(header[1])[1] == '.inc':
                        continue
                d = os.path.join(*[prefix] + header[0].split('.'))
                header = header[1]
            else:
                d = self.install_dir
            self.mkpath(d)
            (out, _) = self.copy_file(header, d)
            self.outfiles.append(out)

# File: numpy-main/numpy/distutils/command/sdist.py
import sys
if 'setuptools' in sys.modules:
    from setuptools.command.sdist import sdist as old_sdist
else:
    from distutils.command.sdist import sdist as old_sdist
from numpy.distutils.misc_util import get_data_files

class sdist(old_sdist):

    def add_defaults(self):
        old_sdist.add_defaults(self)
        dist = self.distribution
        if dist.has_data_files():
            for data in dist.data_files:
                self.filelist.extend(get_data_files(data))
        if dist.has_headers():
            headers = []
            for h in dist.headers:
                if isinstance(h, str):
                    headers.append(h)
                else:
                    headers.append(h[1])
            self.filelist.extend(headers)
        return

# File: numpy-main/numpy/distutils/conv_template.py
""""""
__all__ = ['process_str', 'process_file']
import os
import sys
import re
global_names = {}
header = '\n/*\n *****************************************************************************\n **       This file was autogenerated from a template  DO NOT EDIT!!!!      **\n **       Changes should be made to the original source (.src) file         **\n *****************************************************************************\n */\n\n'

def parse_structure(astr, level):
    if level == 0:
        loopbeg = '/**begin repeat'
        loopend = '/**end repeat**/'
    else:
        loopbeg = '/**begin repeat%d' % level
        loopend = '/**end repeat%d**/' % level
    ind = 0
    line = 0
    spanlist = []
    while True:
        start = astr.find(loopbeg, ind)
        if start == -1:
            break
        start2 = astr.find('*/', start)
        start2 = astr.find('\n', start2)
        fini1 = astr.find(loopend, start2)
        fini2 = astr.find('\n', fini1)
        line += astr.count('\n', ind, start2 + 1)
        spanlist.append((start, start2 + 1, fini1, fini2 + 1, line))
        line += astr.count('\n', start2 + 1, fini2)
        ind = fini2
    spanlist.sort()
    return spanlist

def paren_repl(obj):
    torep = obj.group(1)
    numrep = obj.group(2)
    return ','.join([torep] * int(numrep))
parenrep = re.compile('\\(([^)]*)\\)\\*(\\d+)')
plainrep = re.compile('([^*]+)\\*(\\d+)')

def parse_values(astr):
    astr = parenrep.sub(paren_repl, astr)
    astr = ','.join([plainrep.sub(paren_repl, x.strip()) for x in astr.split(',')])
    return astr.split(',')
stripast = re.compile('\\n\\s*\\*?')
named_re = re.compile('#\\s*(\\w*)\\s*=([^#]*)#')
exclude_vars_re = re.compile('(\\w*)=(\\w*)')
exclude_re = re.compile(':exclude:')

def parse_loop_header(loophead):
    loophead = stripast.sub('', loophead)
    names = []
    reps = named_re.findall(loophead)
    nsub = None
    for rep in reps:
        name = rep[0]
        vals = parse_values(rep[1])
        size = len(vals)
        if nsub is None:
            nsub = size
        elif nsub != size:
            msg = 'Mismatch in number of values, %d != %d\n%s = %s'
            raise ValueError(msg % (nsub, size, name, vals))
        names.append((name, vals))
    excludes = []
    for obj in exclude_re.finditer(loophead):
        span = obj.span()
        endline = loophead.find('\n', span[1])
        substr = loophead[span[1]:endline]
        ex_names = exclude_vars_re.findall(substr)
        excludes.append(dict(ex_names))
    dlist = []
    if nsub is None:
        raise ValueError('No substitution variables found')
    for i in range(nsub):
        tmp = {name: vals[i] for (name, vals) in names}
        dlist.append(tmp)
    return dlist
replace_re = re.compile('@(\\w+)@')

def parse_string(astr, env, level, line):
    lineno = '#line %d\n' % line

    def replace(match):
        name = match.group(1)
        try:
            val = env[name]
        except KeyError:
            msg = 'line %d: no definition of key "%s"' % (line, name)
            raise ValueError(msg) from None
        return val
    code = [lineno]
    struct = parse_structure(astr, level)
    if struct:
        oldend = 0
        newlevel = level + 1
        for sub in struct:
            pref = astr[oldend:sub[0]]
            head = astr[sub[0]:sub[1]]
            text = astr[sub[1]:sub[2]]
            oldend = sub[3]
            newline = line + sub[4]
            code.append(replace_re.sub(replace, pref))
            try:
                envlist = parse_loop_header(head)
            except ValueError as e:
                msg = 'line %d: %s' % (newline, e)
                raise ValueError(msg)
            for newenv in envlist:
                newenv.update(env)
                newcode = parse_string(text, newenv, newlevel, newline)
                code.extend(newcode)
        suff = astr[oldend:]
        code.append(replace_re.sub(replace, suff))
    else:
        code.append(replace_re.sub(replace, astr))
    code.append('\n')
    return ''.join(code)

def process_str(astr):
    code = [header]
    code.extend(parse_string(astr, global_names, 0, 1))
    return ''.join(code)
include_src_re = re.compile('(\\n|\\A)#include\\s*[\'\\"](?P[\\w\\d./\\\\]+[.]src)[\'\\"]', re.I)

def resolve_includes(source):
    d = os.path.dirname(source)
    with open(source) as fid:
        lines = []
        for line in fid:
            m = include_src_re.match(line)
            if m:
                fn = m.group('name')
                if not os.path.isabs(fn):
                    fn = os.path.join(d, fn)
                if os.path.isfile(fn):
                    lines.extend(resolve_includes(fn))
                else:
                    lines.append(line)
            else:
                lines.append(line)
    return lines

def process_file(source):
    lines = resolve_includes(source)
    sourcefile = os.path.normcase(source).replace('\\', '\\\\')
    try:
        code = process_str(''.join(lines))
    except ValueError as e:
        raise ValueError('In "%s" loop at %s' % (sourcefile, e)) from None
    return '#line 1 "%s"\n%s' % (sourcefile, code)

def unique_key(adict):
    allkeys = list(adict.keys())
    done = False
    n = 1
    while not done:
        newkey = ''.join([x[:n] for x in allkeys])
        if newkey in allkeys:
            n += 1
        else:
            done = True
    return newkey

def main():
    try:
        file = sys.argv[1]
    except IndexError:
        fid = sys.stdin
        outfile = sys.stdout
    else:
        fid = open(file, 'r')
        (base, ext) = os.path.splitext(file)
        newname = base
        outfile = open(newname, 'w')
    allstr = fid.read()
    try:
        writestr = process_str(allstr)
    except ValueError as e:
        raise ValueError('In %s loop at %s' % (file, e)) from None
    outfile.write(writestr)
if __name__ == '__main__':
    main()

# File: numpy-main/numpy/distutils/core.py
import sys
from distutils.core import Distribution
if 'setuptools' in sys.modules:
    have_setuptools = True
    from setuptools import setup as old_setup
    from setuptools.command import easy_install
    try:
        from setuptools.command import bdist_egg
    except ImportError:
        have_setuptools = False
else:
    from distutils.core import setup as old_setup
    have_setuptools = False
import warnings
import distutils.core
import distutils.dist
from numpy.distutils.extension import Extension
from numpy.distutils.numpy_distribution import NumpyDistribution
from numpy.distutils.command import config, config_compiler, build, build_py, build_ext, build_clib, build_src, build_scripts, sdist, install_data, install_headers, install, bdist_rpm, install_clib
from numpy.distutils.misc_util import is_sequence, is_string
numpy_cmdclass = {'build': build.build, 'build_src': build_src.build_src, 'build_scripts': build_scripts.build_scripts, 'config_cc': config_compiler.config_cc, 'config_fc': config_compiler.config_fc, 'config': config.config, 'build_ext': build_ext.build_ext, 'build_py': build_py.build_py, 'build_clib': build_clib.build_clib, 'sdist': sdist.sdist, 'install_data': install_data.install_data, 'install_headers': install_headers.install_headers, 'install_clib': install_clib.install_clib, 'install': install.install, 'bdist_rpm': bdist_rpm.bdist_rpm}
if have_setuptools:
    from numpy.distutils.command import develop, egg_info
    numpy_cmdclass['bdist_egg'] = bdist_egg.bdist_egg
    numpy_cmdclass['develop'] = develop.develop
    numpy_cmdclass['easy_install'] = easy_install.easy_install
    numpy_cmdclass['egg_info'] = egg_info.egg_info

def _dict_append(d, **kws):
    for (k, v) in kws.items():
        if k not in d:
            d[k] = v
            continue
        dv = d[k]
        if isinstance(dv, tuple):
            d[k] = dv + tuple(v)
        elif isinstance(dv, list):
            d[k] = dv + list(v)
        elif isinstance(dv, dict):
            _dict_append(dv, **v)
        elif is_string(dv):
            d[k] = dv + v
        else:
            raise TypeError(repr(type(dv)))

def _command_line_ok(_cache=None):
    if _cache:
        return _cache[0]
    elif _cache is None:
        _cache = []
    ok = True
    display_opts = ['--' + n for n in Distribution.display_option_names]
    for o in Distribution.display_options:
        if o[1]:
            display_opts.append('-' + o[1])
    for arg in sys.argv:
        if arg.startswith('--help') or arg == '-h' or arg in display_opts:
            ok = False
            break
    _cache.append(ok)
    return ok

def get_distribution(always=False):
    dist = distutils.core._setup_distribution
    if dist is not None and 'DistributionWithoutHelpCommands' in repr(dist):
        dist = None
    if always and dist is None:
        dist = NumpyDistribution()
    return dist

def setup(**attr):
    cmdclass = numpy_cmdclass.copy()
    new_attr = attr.copy()
    if 'cmdclass' in new_attr:
        cmdclass.update(new_attr['cmdclass'])
    new_attr['cmdclass'] = cmdclass
    if 'configuration' in new_attr:
        configuration = new_attr.pop('configuration')
        old_dist = distutils.core._setup_distribution
        old_stop = distutils.core._setup_stop_after
        distutils.core._setup_distribution = None
        distutils.core._setup_stop_after = 'commandline'
        try:
            dist = setup(**new_attr)
        finally:
            distutils.core._setup_distribution = old_dist
            distutils.core._setup_stop_after = old_stop
        if dist.help or not _command_line_ok():
            return dist
        config = configuration()
        if hasattr(config, 'todict'):
            config = config.todict()
        _dict_append(new_attr, **config)
    libraries = []
    for ext in new_attr.get('ext_modules', []):
        new_libraries = []
        for item in ext.libraries:
            if is_sequence(item):
                (lib_name, build_info) = item
                _check_append_ext_library(libraries, lib_name, build_info)
                new_libraries.append(lib_name)
            elif is_string(item):
                new_libraries.append(item)
            else:
                raise TypeError('invalid description of extension module library %r' % (item,))
        ext.libraries = new_libraries
    if libraries:
        if 'libraries' not in new_attr:
            new_attr['libraries'] = []
        for item in libraries:
            _check_append_library(new_attr['libraries'], item)
    if ('ext_modules' in new_attr or 'libraries' in new_attr) and 'headers' not in new_attr:
        new_attr['headers'] = []
    new_attr['distclass'] = NumpyDistribution
    return old_setup(**new_attr)

def _check_append_library(libraries, item):
    for libitem in libraries:
        if is_sequence(libitem):
            if is_sequence(item):
                if item[0] == libitem[0]:
                    if item[1] is libitem[1]:
                        return
                    warnings.warn('[0] libraries list contains %r with different build_info' % (item[0],), stacklevel=2)
                    break
            elif item == libitem[0]:
                warnings.warn('[1] libraries list contains %r with no build_info' % (item[0],), stacklevel=2)
                break
        elif is_sequence(item):
            if item[0] == libitem:
                warnings.warn('[2] libraries list contains %r with no build_info' % (item[0],), stacklevel=2)
                break
        elif item == libitem:
            return
    libraries.append(item)

def _check_append_ext_library(libraries, lib_name, build_info):
    for item in libraries:
        if is_sequence(item):
            if item[0] == lib_name:
                if item[1] is build_info:
                    return
                warnings.warn('[3] libraries list contains %r with different build_info' % (lib_name,), stacklevel=2)
                break
        elif item == lib_name:
            warnings.warn('[4] libraries list contains %r with no build_info' % (lib_name,), stacklevel=2)
            break
    libraries.append((lib_name, build_info))

# File: numpy-main/numpy/distutils/cpuinfo.py
""""""
__all__ = ['cpu']
import os
import platform
import re
import sys
import types
import warnings
from subprocess import getstatusoutput

def getoutput(cmd, successful_status=(0,), stacklevel=1):
    try:
        (status, output) = getstatusoutput(cmd)
    except OSError as e:
        warnings.warn(str(e), UserWarning, stacklevel=stacklevel)
        return (False, '')
    if os.WIFEXITED(status) and os.WEXITSTATUS(status) in successful_status:
        return (True, output)
    return (False, output)

def command_info(successful_status=(0,), stacklevel=1, **kw):
    info = {}
    for key in kw:
        (ok, output) = getoutput(kw[key], successful_status=successful_status, stacklevel=stacklevel + 1)
        if ok:
            info[key] = output.strip()
    return info

def command_by_line(cmd, successful_status=(0,), stacklevel=1):
    (ok, output) = getoutput(cmd, successful_status=successful_status, stacklevel=stacklevel + 1)
    if not ok:
        return
    for line in output.splitlines():
        yield line.strip()

def key_value_from_command(cmd, sep, successful_status=(0,), stacklevel=1):
    d = {}
    for line in command_by_line(cmd, successful_status=successful_status, stacklevel=stacklevel + 1):
        l = [s.strip() for s in line.split(sep, 1)]
        if len(l) == 2:
            d[l[0]] = l[1]
    return d

class CPUInfoBase:

    def _try_call(self, func):
        try:
            return func()
        except Exception:
            pass

    def __getattr__(self, name):
        if not name.startswith('_'):
            if hasattr(self, '_' + name):
                attr = getattr(self, '_' + name)
                if isinstance(attr, types.MethodType):
                    return lambda func=self._try_call, attr=attr: func(attr)
            else:
                return lambda : None
        raise AttributeError(name)

    def _getNCPUs(self):
        return 1

    def __get_nbits(self):
        abits = platform.architecture()[0]
        nbits = re.compile('(\\d+)bit').search(abits).group(1)
        return nbits

    def _is_32bit(self):
        return self.__get_nbits() == '32'

    def _is_64bit(self):
        return self.__get_nbits() == '64'

class LinuxCPUInfo(CPUInfoBase):
    info = None

    def __init__(self):
        if self.info is not None:
            return
        info = [{}]
        (ok, output) = getoutput('uname -m')
        if ok:
            info[0]['uname_m'] = output.strip()
        try:
            fo = open('/proc/cpuinfo')
        except OSError as e:
            warnings.warn(str(e), UserWarning, stacklevel=2)
        else:
            for line in fo:
                name_value = [s.strip() for s in line.split(':', 1)]
                if len(name_value) != 2:
                    continue
                (name, value) = name_value
                if not info or name in info[-1]:
                    info.append({})
                info[-1][name] = value
            fo.close()
        self.__class__.info = info

    def _not_impl(self):
        pass

    def _is_AMD(self):
        return self.info[0]['vendor_id'] == 'AuthenticAMD'

    def _is_AthlonK6_2(self):
        return self._is_AMD() and self.info[0]['model'] == '2'

    def _is_AthlonK6_3(self):
        return self._is_AMD() and self.info[0]['model'] == '3'

    def _is_AthlonK6(self):
        return re.match('.*?AMD-K6', self.info[0]['model name']) is not None

    def _is_AthlonK7(self):
        return re.match('.*?AMD-K7', self.info[0]['model name']) is not None

    def _is_AthlonMP(self):
        return re.match('.*?Athlon\\(tm\\) MP\\b', self.info[0]['model name']) is not None

    def _is_AMD64(self):
        return self.is_AMD() and self.info[0]['family'] == '15'

    def _is_Athlon64(self):
        return re.match('.*?Athlon\\(tm\\) 64\\b', self.info[0]['model name']) is not None

    def _is_AthlonHX(self):
        return re.match('.*?Athlon HX\\b', self.info[0]['model name']) is not None

    def _is_Opteron(self):
        return re.match('.*?Opteron\\b', self.info[0]['model name']) is not None

    def _is_Hammer(self):
        return re.match('.*?Hammer\\b', self.info[0]['model name']) is not None

    def _is_Alpha(self):
        return self.info[0]['cpu'] == 'Alpha'

    def _is_EV4(self):
        return self.is_Alpha() and self.info[0]['cpu model'] == 'EV4'

    def _is_EV5(self):
        return self.is_Alpha() and self.info[0]['cpu model'] == 'EV5'

    def _is_EV56(self):
        return self.is_Alpha() and self.info[0]['cpu model'] == 'EV56'

    def _is_PCA56(self):
        return self.is_Alpha() and self.info[0]['cpu model'] == 'PCA56'
    _is_i386 = _not_impl

    def _is_Intel(self):
        return self.info[0]['vendor_id'] == 'GenuineIntel'

    def _is_i486(self):
        return self.info[0]['cpu'] == 'i486'

    def _is_i586(self):
        return self.is_Intel() and self.info[0]['cpu family'] == '5'

    def _is_i686(self):
        return self.is_Intel() and self.info[0]['cpu family'] == '6'

    def _is_Celeron(self):
        return re.match('.*?Celeron', self.info[0]['model name']) is not None

    def _is_Pentium(self):
        return re.match('.*?Pentium', self.info[0]['model name']) is not None

    def _is_PentiumII(self):
        return re.match('.*?Pentium.*?II\\b', self.info[0]['model name']) is not None

    def _is_PentiumPro(self):
        return re.match('.*?PentiumPro\\b', self.info[0]['model name']) is not None

    def _is_PentiumMMX(self):
        return re.match('.*?Pentium.*?MMX\\b', self.info[0]['model name']) is not None

    def _is_PentiumIII(self):
        return re.match('.*?Pentium.*?III\\b', self.info[0]['model name']) is not None

    def _is_PentiumIV(self):
        return re.match('.*?Pentium.*?(IV|4)\\b', self.info[0]['model name']) is not None

    def _is_PentiumM(self):
        return re.match('.*?Pentium.*?M\\b', self.info[0]['model name']) is not None

    def _is_Prescott(self):
        return self.is_PentiumIV() and self.has_sse3()

    def _is_Nocona(self):
        return self.is_Intel() and (self.info[0]['cpu family'] == '6' or self.info[0]['cpu family'] == '15') and (self.has_sse3() and (not self.has_ssse3())) and (re.match('.*?\\blm\\b', self.info[0]['flags']) is not None)

    def _is_Core2(self):
        return self.is_64bit() and self.is_Intel() and (re.match('.*?Core\\(TM\\)2\\b', self.info[0]['model name']) is not None)

    def _is_Itanium(self):
        return re.match('.*?Itanium\\b', self.info[0]['family']) is not None

    def _is_XEON(self):
        return re.match('.*?XEON\\b', self.info[0]['model name'], re.IGNORECASE) is not None
    _is_Xeon = _is_XEON

    def _is_singleCPU(self):
        return len(self.info) == 1

    def _getNCPUs(self):
        return len(self.info)

    def _has_fdiv_bug(self):
        return self.info[0]['fdiv_bug'] == 'yes'

    def _has_f00f_bug(self):
        return self.info[0]['f00f_bug'] == 'yes'

    def _has_mmx(self):
        return re.match('.*?\\bmmx\\b', self.info[0]['flags']) is not None

    def _has_sse(self):
        return re.match('.*?\\bsse\\b', self.info[0]['flags']) is not None

    def _has_sse2(self):
        return re.match('.*?\\bsse2\\b', self.info[0]['flags']) is not None

    def _has_sse3(self):
        return re.match('.*?\\bpni\\b', self.info[0]['flags']) is not None

    def _has_ssse3(self):
        return re.match('.*?\\bssse3\\b', self.info[0]['flags']) is not None

    def _has_3dnow(self):
        return re.match('.*?\\b3dnow\\b', self.info[0]['flags']) is not None

    def _has_3dnowext(self):
        return re.match('.*?\\b3dnowext\\b', self.info[0]['flags']) is not None

class IRIXCPUInfo(CPUInfoBase):
    info = None

    def __init__(self):
        if self.info is not None:
            return
        info = key_value_from_command('sysconf', sep=' ', successful_status=(0, 1))
        self.__class__.info = info

    def _not_impl(self):
        pass

    def _is_singleCPU(self):
        return self.info.get('NUM_PROCESSORS') == '1'

    def _getNCPUs(self):
        return int(self.info.get('NUM_PROCESSORS', 1))

    def __cputype(self, n):
        return self.info.get('PROCESSORS').split()[0].lower() == 'r%s' % n

    def _is_r2000(self):
        return self.__cputype(2000)

    def _is_r3000(self):
        return self.__cputype(3000)

    def _is_r3900(self):
        return self.__cputype(3900)

    def _is_r4000(self):
        return self.__cputype(4000)

    def _is_r4100(self):
        return self.__cputype(4100)

    def _is_r4300(self):
        return self.__cputype(4300)

    def _is_r4400(self):
        return self.__cputype(4400)

    def _is_r4600(self):
        return self.__cputype(4600)

    def _is_r4650(self):
        return self.__cputype(4650)

    def _is_r5000(self):
        return self.__cputype(5000)

    def _is_r6000(self):
        return self.__cputype(6000)

    def _is_r8000(self):
        return self.__cputype(8000)

    def _is_r10000(self):
        return self.__cputype(10000)

    def _is_r12000(self):
        return self.__cputype(12000)

    def _is_rorion(self):
        return self.__cputype('orion')

    def get_ip(self):
        try:
            return self.info.get('MACHINE')
        except Exception:
            pass

    def __machine(self, n):
        return self.info.get('MACHINE').lower() == 'ip%s' % n

    def _is_IP19(self):
        return self.__machine(19)

    def _is_IP20(self):
        return self.__machine(20)

    def _is_IP21(self):
        return self.__machine(21)

    def _is_IP22(self):
        return self.__machine(22)

    def _is_IP22_4k(self):
        return self.__machine(22) and self._is_r4000()

    def _is_IP22_5k(self):
        return self.__machine(22) and self._is_r5000()

    def _is_IP24(self):
        return self.__machine(24)

    def _is_IP25(self):
        return self.__machine(25)

    def _is_IP26(self):
        return self.__machine(26)

    def _is_IP27(self):
        return self.__machine(27)

    def _is_IP28(self):
        return self.__machine(28)

    def _is_IP30(self):
        return self.__machine(30)

    def _is_IP32(self):
        return self.__machine(32)

    def _is_IP32_5k(self):
        return self.__machine(32) and self._is_r5000()

    def _is_IP32_10k(self):
        return self.__machine(32) and self._is_r10000()

class DarwinCPUInfo(CPUInfoBase):
    info = None

    def __init__(self):
        if self.info is not None:
            return
        info = command_info(arch='arch', machine='machine')
        info['sysctl_hw'] = key_value_from_command('sysctl hw', sep='=')
        self.__class__.info = info

    def _not_impl(self):
        pass

    def _getNCPUs(self):
        return int(self.info['sysctl_hw'].get('hw.ncpu', 1))

    def _is_Power_Macintosh(self):
        return self.info['sysctl_hw']['hw.machine'] == 'Power Macintosh'

    def _is_i386(self):
        return self.info['arch'] == 'i386'

    def _is_ppc(self):
        return self.info['arch'] == 'ppc'

    def __machine(self, n):
        return self.info['machine'] == 'ppc%s' % n

    def _is_ppc601(self):
        return self.__machine(601)

    def _is_ppc602(self):
        return self.__machine(602)

    def _is_ppc603(self):
        return self.__machine(603)

    def _is_ppc603e(self):
        return self.__machine('603e')

    def _is_ppc604(self):
        return self.__machine(604)

    def _is_ppc604e(self):
        return self.__machine('604e')

    def _is_ppc620(self):
        return self.__machine(620)

    def _is_ppc630(self):
        return self.__machine(630)

    def _is_ppc740(self):
        return self.__machine(740)

    def _is_ppc7400(self):
        return self.__machine(7400)

    def _is_ppc7450(self):
        return self.__machine(7450)

    def _is_ppc750(self):
        return self.__machine(750)

    def _is_ppc403(self):
        return self.__machine(403)

    def _is_ppc505(self):
        return self.__machine(505)

    def _is_ppc801(self):
        return self.__machine(801)

    def _is_ppc821(self):
        return self.__machine(821)

    def _is_ppc823(self):
        return self.__machine(823)

    def _is_ppc860(self):
        return self.__machine(860)

class SunOSCPUInfo(CPUInfoBase):
    info = None

    def __init__(self):
        if self.info is not None:
            return
        info = command_info(arch='arch', mach='mach', uname_i='uname_i', isainfo_b='isainfo -b', isainfo_n='isainfo -n')
        info['uname_X'] = key_value_from_command('uname -X', sep='=')
        for line in command_by_line('psrinfo -v 0'):
            m = re.match('\\s*The (?P

[\\w\\d]+) processor operates at', line) if m: info['processor'] = m.group('p') break self.__class__.info = info def _not_impl(self): pass def _is_i386(self): return self.info['isainfo_n'] == 'i386' def _is_sparc(self): return self.info['isainfo_n'] == 'sparc' def _is_sparcv9(self): return self.info['isainfo_n'] == 'sparcv9' def _getNCPUs(self): return int(self.info['uname_X'].get('NumCPU', 1)) def _is_sun4(self): return self.info['arch'] == 'sun4' def _is_SUNW(self): return re.match('SUNW', self.info['uname_i']) is not None def _is_sparcstation5(self): return re.match('.*SPARCstation-5', self.info['uname_i']) is not None def _is_ultra1(self): return re.match('.*Ultra-1', self.info['uname_i']) is not None def _is_ultra250(self): return re.match('.*Ultra-250', self.info['uname_i']) is not None def _is_ultra2(self): return re.match('.*Ultra-2', self.info['uname_i']) is not None def _is_ultra30(self): return re.match('.*Ultra-30', self.info['uname_i']) is not None def _is_ultra4(self): return re.match('.*Ultra-4', self.info['uname_i']) is not None def _is_ultra5_10(self): return re.match('.*Ultra-5_10', self.info['uname_i']) is not None def _is_ultra5(self): return re.match('.*Ultra-5', self.info['uname_i']) is not None def _is_ultra60(self): return re.match('.*Ultra-60', self.info['uname_i']) is not None def _is_ultra80(self): return re.match('.*Ultra-80', self.info['uname_i']) is not None def _is_ultraenterprice(self): return re.match('.*Ultra-Enterprise', self.info['uname_i']) is not None def _is_ultraenterprice10k(self): return re.match('.*Ultra-Enterprise-10000', self.info['uname_i']) is not None def _is_sunfire(self): return re.match('.*Sun-Fire', self.info['uname_i']) is not None def _is_ultra(self): return re.match('.*Ultra', self.info['uname_i']) is not None def _is_cpusparcv7(self): return self.info['processor'] == 'sparcv7' def _is_cpusparcv8(self): return self.info['processor'] == 'sparcv8' def _is_cpusparcv9(self): return self.info['processor'] == 'sparcv9' class Win32CPUInfo(CPUInfoBase): info = None pkey = 'HARDWARE\\DESCRIPTION\\System\\CentralProcessor' def __init__(self): if self.info is not None: return info = [] try: import winreg prgx = re.compile('family\\s+(?P\\d+)\\s+model\\s+(?P\\d+)\\s+stepping\\s+(?P\\d+)', re.IGNORECASE) chnd = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum = 0 while True: try: proc = winreg.EnumKey(chnd, pnum) except winreg.error: break else: pnum += 1 info.append({'Processor': proc}) phnd = winreg.OpenKey(chnd, proc) pidx = 0 while True: try: (name, value, vtpe) = winreg.EnumValue(phnd, pidx) except winreg.error: break else: pidx = pidx + 1 info[-1][name] = value if name == 'Identifier': srch = prgx.search(value) if srch: info[-1]['Family'] = int(srch.group('FML')) info[-1]['Model'] = int(srch.group('MDL')) info[-1]['Stepping'] = int(srch.group('STP')) except Exception as e: print(e, '(ignoring)') self.__class__.info = info def _not_impl(self): pass def _is_AMD(self): return self.info[0]['VendorIdentifier'] == 'AuthenticAMD' def _is_Am486(self): return self.is_AMD() and self.info[0]['Family'] == 4 def _is_Am5x86(self): return self.is_AMD() and self.info[0]['Family'] == 4 def _is_AMDK5(self): return self.is_AMD() and self.info[0]['Family'] == 5 and (self.info[0]['Model'] in [0, 1, 2, 3]) def _is_AMDK6(self): return self.is_AMD() and self.info[0]['Family'] == 5 and (self.info[0]['Model'] in [6, 7]) def _is_AMDK6_2(self): return self.is_AMD() and self.info[0]['Family'] == 5 and (self.info[0]['Model'] == 8) def _is_AMDK6_3(self): return self.is_AMD() and self.info[0]['Family'] == 5 and (self.info[0]['Model'] == 9) def _is_AMDK7(self): return self.is_AMD() and self.info[0]['Family'] == 6 def _is_AMD64(self): return self.is_AMD() and self.info[0]['Family'] == 15 def _is_Intel(self): return self.info[0]['VendorIdentifier'] == 'GenuineIntel' def _is_i386(self): return self.info[0]['Family'] == 3 def _is_i486(self): return self.info[0]['Family'] == 4 def _is_i586(self): return self.is_Intel() and self.info[0]['Family'] == 5 def _is_i686(self): return self.is_Intel() and self.info[0]['Family'] == 6 def _is_Pentium(self): return self.is_Intel() and self.info[0]['Family'] == 5 def _is_PentiumMMX(self): return self.is_Intel() and self.info[0]['Family'] == 5 and (self.info[0]['Model'] == 4) def _is_PentiumPro(self): return self.is_Intel() and self.info[0]['Family'] == 6 and (self.info[0]['Model'] == 1) def _is_PentiumII(self): return self.is_Intel() and self.info[0]['Family'] == 6 and (self.info[0]['Model'] in [3, 5, 6]) def _is_PentiumIII(self): return self.is_Intel() and self.info[0]['Family'] == 6 and (self.info[0]['Model'] in [7, 8, 9, 10, 11]) def _is_PentiumIV(self): return self.is_Intel() and self.info[0]['Family'] == 15 def _is_PentiumM(self): return self.is_Intel() and self.info[0]['Family'] == 6 and (self.info[0]['Model'] in [9, 13, 14]) def _is_Core2(self): return self.is_Intel() and self.info[0]['Family'] == 6 and (self.info[0]['Model'] in [15, 16, 17]) def _is_singleCPU(self): return len(self.info) == 1 def _getNCPUs(self): return len(self.info) def _has_mmx(self): if self.is_Intel(): return self.info[0]['Family'] == 5 and self.info[0]['Model'] == 4 or self.info[0]['Family'] in [6, 15] elif self.is_AMD(): return self.info[0]['Family'] in [5, 6, 15] else: return False def _has_sse(self): if self.is_Intel(): return self.info[0]['Family'] == 6 and self.info[0]['Model'] in [7, 8, 9, 10, 11] or self.info[0]['Family'] == 15 elif self.is_AMD(): return self.info[0]['Family'] == 6 and self.info[0]['Model'] in [6, 7, 8, 10] or self.info[0]['Family'] == 15 else: return False def _has_sse2(self): if self.is_Intel(): return self.is_Pentium4() or self.is_PentiumM() or self.is_Core2() elif self.is_AMD(): return self.is_AMD64() else: return False def _has_3dnow(self): return self.is_AMD() and self.info[0]['Family'] in [5, 6, 15] def _has_3dnowext(self): return self.is_AMD() and self.info[0]['Family'] in [6, 15] if sys.platform.startswith('linux'): cpuinfo = LinuxCPUInfo elif sys.platform.startswith('irix'): cpuinfo = IRIXCPUInfo elif sys.platform == 'darwin': cpuinfo = DarwinCPUInfo elif sys.platform.startswith('sunos'): cpuinfo = SunOSCPUInfo elif sys.platform.startswith('win32'): cpuinfo = Win32CPUInfo elif sys.platform.startswith('cygwin'): cpuinfo = LinuxCPUInfo else: cpuinfo = CPUInfoBase cpu = cpuinfo() # File: numpy-main/numpy/distutils/exec_command.py """""" __all__ = ['exec_command', 'find_executable'] import os import sys import subprocess import locale import warnings from numpy.distutils.misc_util import is_sequence, make_temp_file from numpy.distutils import log def filepath_from_subprocess_output(output): mylocale = locale.getpreferredencoding(False) if mylocale is None: mylocale = 'ascii' output = output.decode(mylocale, errors='replace') output = output.replace('\r\n', '\n') if output[-1:] == '\n': output = output[:-1] return output def forward_bytes_to_stdout(val): if hasattr(sys.stdout, 'buffer'): sys.stdout.buffer.write(val) elif hasattr(sys.stdout, 'encoding'): sys.stdout.write(val.decode(sys.stdout.encoding)) else: sys.stdout.write(val.decode('utf8', errors='replace')) def temp_file_name(): warnings.warn('temp_file_name is deprecated since NumPy v1.17, use tempfile.mkstemp instead', DeprecationWarning, stacklevel=1) (fo, name) = make_temp_file() fo.close() return name def get_pythonexe(): pythonexe = sys.executable if os.name in ['nt', 'dos']: (fdir, fn) = os.path.split(pythonexe) fn = fn.upper().replace('PYTHONW', 'PYTHON') pythonexe = os.path.join(fdir, fn) assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,) return pythonexe def find_executable(exe, path=None, _cache={}): key = (exe, path) try: return _cache[key] except KeyError: pass log.debug('find_executable(%r)' % exe) orig_exe = exe if path is None: path = os.environ.get('PATH', os.defpath) if os.name == 'posix': realpath = os.path.realpath else: realpath = lambda a: a if exe.startswith('"'): exe = exe[1:-1] suffixes = [''] if os.name in ['nt', 'dos', 'os2']: (fn, ext) = os.path.splitext(exe) extra_suffixes = ['.exe', '.com', '.bat'] if ext.lower() not in extra_suffixes: suffixes = extra_suffixes if os.path.isabs(exe): paths = [''] else: paths = [os.path.abspath(p) for p in path.split(os.pathsep)] for path in paths: fn = os.path.join(path, exe) for s in suffixes: f_ext = fn + s if not os.path.islink(f_ext): f_ext = realpath(f_ext) if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK): log.info('Found executable %s' % f_ext) _cache[key] = f_ext return f_ext log.warn('Could not locate executable %s' % orig_exe) return None def _preserve_environment(names): log.debug('_preserve_environment(%r)' % names) env = {name: os.environ.get(name) for name in names} return env def _update_environment(**env): log.debug('_update_environment(...)') for (name, value) in env.items(): os.environ[name] = value or '' def exec_command(command, execute_in='', use_shell=None, use_tee=None, _with_python=1, **env): warnings.warn('exec_command is deprecated since NumPy v1.17, use subprocess.Popen instead', DeprecationWarning, stacklevel=1) log.debug('exec_command(%r,%s)' % (command, ','.join(['%s=%r' % kv for kv in env.items()]))) if use_tee is None: use_tee = os.name == 'posix' if use_shell is None: use_shell = os.name == 'posix' execute_in = os.path.abspath(execute_in) oldcwd = os.path.abspath(os.getcwd()) if __name__[-12:] == 'exec_command': exec_dir = os.path.dirname(os.path.abspath(__file__)) elif os.path.isfile('exec_command.py'): exec_dir = os.path.abspath('.') else: exec_dir = os.path.abspath(sys.argv[0]) if os.path.isfile(exec_dir): exec_dir = os.path.dirname(exec_dir) if oldcwd != execute_in: os.chdir(execute_in) log.debug('New cwd: %s' % execute_in) else: log.debug('Retaining cwd: %s' % oldcwd) oldenv = _preserve_environment(list(env.keys())) _update_environment(**env) try: st = _exec_command(command, use_shell=use_shell, use_tee=use_tee, **env) finally: if oldcwd != execute_in: os.chdir(oldcwd) log.debug('Restored cwd to %s' % oldcwd) _update_environment(**oldenv) return st def _exec_command(command, use_shell=None, use_tee=None, **env): if use_shell is None: use_shell = os.name == 'posix' if use_tee is None: use_tee = os.name == 'posix' if os.name == 'posix' and use_shell: sh = os.environ.get('SHELL', '/bin/sh') if is_sequence(command): command = [sh, '-c', ' '.join(command)] else: command = [sh, '-c', command] use_shell = False elif os.name == 'nt' and is_sequence(command): command = ' '.join((_quote_arg(arg) for arg in command)) env = env or None try: proc = subprocess.Popen(command, shell=use_shell, env=env, text=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except OSError: return (127, '') (text, err) = proc.communicate() mylocale = locale.getpreferredencoding(False) if mylocale is None: mylocale = 'ascii' text = text.decode(mylocale, errors='replace') text = text.replace('\r\n', '\n') if text[-1:] == '\n': text = text[:-1] if use_tee and text: print(text) return (proc.returncode, text) def _quote_arg(arg): if '"' not in arg and ' ' in arg: return '"%s"' % arg return arg # File: numpy-main/numpy/distutils/extension.py """""" import re from distutils.extension import Extension as old_Extension cxx_ext_re = re.compile('.*\\.(cpp|cxx|cc)\\Z', re.I).match fortran_pyf_ext_re = re.compile('.*\\.(f90|f95|f77|for|ftn|f|pyf)\\Z', re.I).match class Extension(old_Extension): def __init__(self, name, sources, include_dirs=None, define_macros=None, undef_macros=None, library_dirs=None, libraries=None, runtime_library_dirs=None, extra_objects=None, extra_compile_args=None, extra_link_args=None, export_symbols=None, swig_opts=None, depends=None, language=None, f2py_options=None, module_dirs=None, extra_c_compile_args=None, extra_cxx_compile_args=None, extra_f77_compile_args=None, extra_f90_compile_args=None): old_Extension.__init__(self, name, [], include_dirs=include_dirs, define_macros=define_macros, undef_macros=undef_macros, library_dirs=library_dirs, libraries=libraries, runtime_library_dirs=runtime_library_dirs, extra_objects=extra_objects, extra_compile_args=extra_compile_args, extra_link_args=extra_link_args, export_symbols=export_symbols) self.sources = sources self.swig_opts = swig_opts or [] if isinstance(self.swig_opts, str): import warnings msg = 'swig_opts is specified as a string instead of a list' warnings.warn(msg, SyntaxWarning, stacklevel=2) self.swig_opts = self.swig_opts.split() self.depends = depends or [] self.language = language self.f2py_options = f2py_options or [] self.module_dirs = module_dirs or [] self.extra_c_compile_args = extra_c_compile_args or [] self.extra_cxx_compile_args = extra_cxx_compile_args or [] self.extra_f77_compile_args = extra_f77_compile_args or [] self.extra_f90_compile_args = extra_f90_compile_args or [] return def has_cxx_sources(self): return any((cxx_ext_re(str(source)) for source in self.sources)) def has_f2py_sources(self): return any((fortran_pyf_ext_re(source) for source in self.sources)) # File: numpy-main/numpy/distutils/fcompiler/__init__.py """""" __all__ = ['FCompiler', 'new_fcompiler', 'show_fcompilers', 'dummy_fortran_file'] import os import sys import re from pathlib import Path from distutils.sysconfig import get_python_lib from distutils.fancy_getopt import FancyGetopt from distutils.errors import DistutilsModuleError, DistutilsExecError, CompileError, LinkError, DistutilsPlatformError from distutils.util import split_quoted, strtobool from numpy.distutils.ccompiler import CCompiler, gen_lib_options from numpy.distutils import log from numpy.distutils.misc_util import is_string, all_strings, is_sequence, make_temp_file, get_shared_lib_extension from numpy.distutils.exec_command import find_executable from numpy.distutils import _shell_utils from .environment import EnvironmentConfig __metaclass__ = type FORTRAN_COMMON_FIXED_EXTENSIONS = ['.for', '.ftn', '.f77', '.f'] class CompilerNotFound(Exception): pass def flaglist(s): if is_string(s): return split_quoted(s) else: return s def str2bool(s): if is_string(s): return strtobool(s) return bool(s) def is_sequence_of_strings(seq): return is_sequence(seq) and all_strings(seq) class FCompiler(CCompiler): distutils_vars = EnvironmentConfig(distutils_section='config_fc', noopt=(None, None, 'noopt', str2bool, False), noarch=(None, None, 'noarch', str2bool, False), debug=(None, None, 'debug', str2bool, False), verbose=(None, None, 'verbose', str2bool, False)) command_vars = EnvironmentConfig(distutils_section='config_fc', compiler_f77=('exe.compiler_f77', 'F77', 'f77exec', None, False), compiler_f90=('exe.compiler_f90', 'F90', 'f90exec', None, False), compiler_fix=('exe.compiler_fix', 'F90', 'f90exec', None, False), version_cmd=('exe.version_cmd', None, None, None, False), linker_so=('exe.linker_so', 'LDSHARED', 'ldshared', None, False), linker_exe=('exe.linker_exe', 'LD', 'ld', None, False), archiver=(None, 'AR', 'ar', None, False), ranlib=(None, 'RANLIB', 'ranlib', None, False)) flag_vars = EnvironmentConfig(distutils_section='config_fc', f77=('flags.f77', 'F77FLAGS', 'f77flags', flaglist, True), f90=('flags.f90', 'F90FLAGS', 'f90flags', flaglist, True), free=('flags.free', 'FREEFLAGS', 'freeflags', flaglist, True), fix=('flags.fix', None, None, flaglist, False), opt=('flags.opt', 'FOPT', 'opt', flaglist, True), opt_f77=('flags.opt_f77', None, None, flaglist, False), opt_f90=('flags.opt_f90', None, None, flaglist, False), arch=('flags.arch', 'FARCH', 'arch', flaglist, False), arch_f77=('flags.arch_f77', None, None, flaglist, False), arch_f90=('flags.arch_f90', None, None, flaglist, False), debug=('flags.debug', 'FDEBUG', 'fdebug', flaglist, True), debug_f77=('flags.debug_f77', None, None, flaglist, False), debug_f90=('flags.debug_f90', None, None, flaglist, False), flags=('self.get_flags', 'FFLAGS', 'fflags', flaglist, True), linker_so=('flags.linker_so', 'LDFLAGS', 'ldflags', flaglist, True), linker_exe=('flags.linker_exe', 'LDFLAGS', 'ldflags', flaglist, True), ar=('flags.ar', 'ARFLAGS', 'arflags', flaglist, True)) language_map = {'.f': 'f77', '.for': 'f77', '.F': 'f77', '.ftn': 'f77', '.f77': 'f77', '.f90': 'f90', '.F90': 'f90', '.f95': 'f90'} language_order = ['f90', 'f77'] compiler_type = None compiler_aliases = () version_pattern = None possible_executables = [] executables = {'version_cmd': ['f77', '-v'], 'compiler_f77': ['f77'], 'compiler_f90': ['f90'], 'compiler_fix': ['f90', '-fixed'], 'linker_so': ['f90', '-shared'], 'linker_exe': ['f90'], 'archiver': ['ar', '-cr'], 'ranlib': None} suggested_f90_compiler = None compile_switch = '-c' object_switch = '-o ' library_switch = '-o ' module_dir_switch = None module_include_switch = '-I' pic_flags = [] src_extensions = ['.for', '.ftn', '.f77', '.f', '.f90', '.f95', '.F', '.F90', '.FOR'] obj_extension = '.o' shared_lib_extension = get_shared_lib_extension() static_lib_extension = '.a' static_lib_format = 'lib%s%s' shared_lib_format = '%s%s' exe_extension = '' _exe_cache = {} _executable_keys = ['version_cmd', 'compiler_f77', 'compiler_f90', 'compiler_fix', 'linker_so', 'linker_exe', 'archiver', 'ranlib'] c_compiler = None extra_f77_compile_args = [] extra_f90_compile_args = [] def __init__(self, *args, **kw): CCompiler.__init__(self, *args, **kw) self.distutils_vars = self.distutils_vars.clone(self._environment_hook) self.command_vars = self.command_vars.clone(self._environment_hook) self.flag_vars = self.flag_vars.clone(self._environment_hook) self.executables = self.executables.copy() for e in self._executable_keys: if e not in self.executables: self.executables[e] = None self._is_customised = False def __copy__(self): obj = self.__new__(self.__class__) obj.__dict__.update(self.__dict__) obj.distutils_vars = obj.distutils_vars.clone(obj._environment_hook) obj.command_vars = obj.command_vars.clone(obj._environment_hook) obj.flag_vars = obj.flag_vars.clone(obj._environment_hook) obj.executables = obj.executables.copy() return obj def copy(self): return self.__copy__() def _command_property(key): def fget(self): assert self._is_customised return self.executables[key] return property(fget=fget) version_cmd = _command_property('version_cmd') compiler_f77 = _command_property('compiler_f77') compiler_f90 = _command_property('compiler_f90') compiler_fix = _command_property('compiler_fix') linker_so = _command_property('linker_so') linker_exe = _command_property('linker_exe') archiver = _command_property('archiver') ranlib = _command_property('ranlib') def set_executable(self, key, value): self.set_command(key, value) def set_commands(self, **kw): for (k, v) in kw.items(): self.set_command(k, v) def set_command(self, key, value): if not key in self._executable_keys: raise ValueError("unknown executable '%s' for class %s" % (key, self.__class__.__name__)) if is_string(value): value = split_quoted(value) assert value is None or is_sequence_of_strings(value[1:]), (key, value) self.executables[key] = value def find_executables(self): assert self._is_customised exe_cache = self._exe_cache def cached_find_executable(exe): if exe in exe_cache: return exe_cache[exe] fc_exe = find_executable(exe) exe_cache[exe] = exe_cache[fc_exe] = fc_exe return fc_exe def verify_command_form(name, value): if value is not None and (not is_sequence_of_strings(value)): raise ValueError('%s value %r is invalid in class %s' % (name, value, self.__class__.__name__)) def set_exe(exe_key, f77=None, f90=None): cmd = self.executables.get(exe_key, None) if not cmd: return None exe_from_environ = getattr(self.command_vars, exe_key) if not exe_from_environ: possibles = [f90, f77] + self.possible_executables else: possibles = [exe_from_environ] + self.possible_executables seen = set() unique_possibles = [] for e in possibles: if e == '': e = f77 elif e == '': e = f90 if not e or e in seen: continue seen.add(e) unique_possibles.append(e) for exe in unique_possibles: fc_exe = cached_find_executable(exe) if fc_exe: cmd[0] = fc_exe return fc_exe self.set_command(exe_key, None) return None ctype = self.compiler_type f90 = set_exe('compiler_f90') if not f90: f77 = set_exe('compiler_f77') if f77: log.warn('%s: no Fortran 90 compiler found' % ctype) else: raise CompilerNotFound('%s: f90 nor f77' % ctype) else: f77 = set_exe('compiler_f77', f90=f90) if not f77: log.warn('%s: no Fortran 77 compiler found' % ctype) set_exe('compiler_fix', f90=f90) set_exe('linker_so', f77=f77, f90=f90) set_exe('linker_exe', f77=f77, f90=f90) set_exe('version_cmd', f77=f77, f90=f90) set_exe('archiver') set_exe('ranlib') def update_executables(self): pass def get_flags(self): return [] + self.pic_flags def _get_command_flags(self, key): cmd = self.executables.get(key, None) if cmd is None: return [] return cmd[1:] def get_flags_f77(self): return self._get_command_flags('compiler_f77') def get_flags_f90(self): return self._get_command_flags('compiler_f90') def get_flags_free(self): return [] def get_flags_fix(self): return self._get_command_flags('compiler_fix') def get_flags_linker_so(self): return self._get_command_flags('linker_so') def get_flags_linker_exe(self): return self._get_command_flags('linker_exe') def get_flags_ar(self): return self._get_command_flags('archiver') def get_flags_opt(self): return [] def get_flags_arch(self): return [] def get_flags_debug(self): return [] get_flags_opt_f77 = get_flags_opt_f90 = get_flags_opt get_flags_arch_f77 = get_flags_arch_f90 = get_flags_arch get_flags_debug_f77 = get_flags_debug_f90 = get_flags_debug def get_libraries(self): return self.libraries[:] def get_library_dirs(self): return self.library_dirs[:] def get_version(self, force=False, ok_status=[0]): assert self._is_customised version = CCompiler.get_version(self, force=force, ok_status=ok_status) if version is None: raise CompilerNotFound() return version def customize(self, dist=None): log.info('customize %s' % self.__class__.__name__) self._is_customised = True self.distutils_vars.use_distribution(dist) self.command_vars.use_distribution(dist) self.flag_vars.use_distribution(dist) self.update_executables() self.find_executables() noopt = self.distutils_vars.get('noopt', False) noarch = self.distutils_vars.get('noarch', noopt) debug = self.distutils_vars.get('debug', False) f77 = self.command_vars.compiler_f77 f90 = self.command_vars.compiler_f90 f77flags = [] f90flags = [] freeflags = [] fixflags = [] if f77: f77 = _shell_utils.NativeParser.split(f77) f77flags = self.flag_vars.f77 if f90: f90 = _shell_utils.NativeParser.split(f90) f90flags = self.flag_vars.f90 freeflags = self.flag_vars.free fix = self.command_vars.compiler_fix if fix: fix = _shell_utils.NativeParser.split(fix) fixflags = self.flag_vars.fix + f90flags (oflags, aflags, dflags) = ([], [], []) def get_flags(tag, flags): flags.extend(getattr(self.flag_vars, tag)) this_get = getattr(self, 'get_flags_' + tag) for (name, c, flagvar) in [('f77', f77, f77flags), ('f90', f90, f90flags), ('f90', fix, fixflags)]: t = '%s_%s' % (tag, name) if c and this_get is not getattr(self, 'get_flags_' + t): flagvar.extend(getattr(self.flag_vars, t)) if not noopt: get_flags('opt', oflags) if not noarch: get_flags('arch', aflags) if debug: get_flags('debug', dflags) fflags = self.flag_vars.flags + dflags + oflags + aflags if f77: self.set_commands(compiler_f77=f77 + f77flags + fflags) if f90: self.set_commands(compiler_f90=f90 + freeflags + f90flags + fflags) if fix: self.set_commands(compiler_fix=fix + fixflags + fflags) linker_so = self.linker_so if linker_so: linker_so_flags = self.flag_vars.linker_so if sys.platform.startswith('aix'): python_lib = get_python_lib(standard_lib=1) ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix') python_exp = os.path.join(python_lib, 'config', 'python.exp') linker_so = [ld_so_aix] + linker_so + ['-bI:' + python_exp] if sys.platform.startswith('os400'): from distutils.sysconfig import get_config_var python_config = get_config_var('LIBPL') ld_so_aix = os.path.join(python_config, 'ld_so_aix') python_exp = os.path.join(python_config, 'python.exp') linker_so = [ld_so_aix] + linker_so + ['-bI:' + python_exp] self.set_commands(linker_so=linker_so + linker_so_flags) linker_exe = self.linker_exe if linker_exe: linker_exe_flags = self.flag_vars.linker_exe self.set_commands(linker_exe=linker_exe + linker_exe_flags) ar = self.command_vars.archiver if ar: arflags = self.flag_vars.ar self.set_commands(archiver=[ar] + arflags) self.set_library_dirs(self.get_library_dirs()) self.set_libraries(self.get_libraries()) def dump_properties(self): props = [] for key in list(self.executables.keys()) + ['version', 'libraries', 'library_dirs', 'object_switch', 'compile_switch']: if hasattr(self, key): v = getattr(self, key) props.append((key, None, '= ' + repr(v))) props.sort() pretty_printer = FancyGetopt(props) for l in pretty_printer.generate_help('%s instance properties:' % self.__class__.__name__): if l[:4] == ' --': l = ' ' + l[4:] print(l) def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): src_flags = {} if Path(src).suffix.lower() in FORTRAN_COMMON_FIXED_EXTENSIONS and (not has_f90_header(src)): flavor = ':f77' compiler = self.compiler_f77 src_flags = get_f77flags(src) extra_compile_args = self.extra_f77_compile_args or [] elif is_free_format(src): flavor = ':f90' compiler = self.compiler_f90 if compiler is None: raise DistutilsExecError('f90 not supported by %s needed for %s' % (self.__class__.__name__, src)) extra_compile_args = self.extra_f90_compile_args or [] else: flavor = ':fix' compiler = self.compiler_fix if compiler is None: raise DistutilsExecError('f90 (fixed) not supported by %s needed for %s' % (self.__class__.__name__, src)) extra_compile_args = self.extra_f90_compile_args or [] if self.object_switch[-1] == ' ': o_args = [self.object_switch.strip(), obj] else: o_args = [self.object_switch.strip() + obj] assert self.compile_switch.strip() s_args = [self.compile_switch, src] if extra_compile_args: log.info('extra %s options: %r' % (flavor[1:], ' '.join(extra_compile_args))) extra_flags = src_flags.get(self.compiler_type, []) if extra_flags: log.info('using compile options from source: %r' % ' '.join(extra_flags)) command = compiler + cc_args + extra_flags + s_args + o_args + extra_postargs + extra_compile_args display = '%s: %s' % (os.path.basename(compiler[0]) + flavor, src) try: self.spawn(command, display=display) except DistutilsExecError as e: msg = str(e) raise CompileError(msg) from None def module_options(self, module_dirs, module_build_dir): options = [] if self.module_dir_switch is not None: if self.module_dir_switch[-1] == ' ': options.extend([self.module_dir_switch.strip(), module_build_dir]) else: options.append(self.module_dir_switch.strip() + module_build_dir) else: print('XXX: module_build_dir=%r option ignored' % module_build_dir) print('XXX: Fix module_dir_switch for ', self.__class__.__name__) if self.module_include_switch is not None: for d in [module_build_dir] + module_dirs: options.append('%s%s' % (self.module_include_switch, d)) else: print('XXX: module_dirs=%r option ignored' % module_dirs) print('XXX: Fix module_include_switch for ', self.__class__.__name__) return options def library_option(self, lib): return '-l' + lib def library_dir_option(self, dir): return '-L' + dir def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): (objects, output_dir) = self._fix_object_args(objects, output_dir) (libraries, library_dirs, runtime_library_dirs) = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) if is_string(output_dir): output_filename = os.path.join(output_dir, output_filename) elif output_dir is not None: raise TypeError("'output_dir' must be a string or None") if self._need_link(objects, output_filename): if self.library_switch[-1] == ' ': o_args = [self.library_switch.strip(), output_filename] else: o_args = [self.library_switch.strip() + output_filename] if is_string(self.objects): ld_args = objects + [self.objects] else: ld_args = objects + self.objects ld_args = ld_args + lib_opts + o_args if debug: ld_args[:0] = ['-g'] if extra_preargs: ld_args[:0] = extra_preargs if extra_postargs: ld_args.extend(extra_postargs) self.mkpath(os.path.dirname(output_filename)) if target_desc == CCompiler.EXECUTABLE: linker = self.linker_exe[:] else: linker = self.linker_so[:] command = linker + ld_args try: self.spawn(command) except DistutilsExecError as e: msg = str(e) raise LinkError(msg) from None else: log.debug('skipping %s (up-to-date)', output_filename) def _environment_hook(self, name, hook_name): if hook_name is None: return None if is_string(hook_name): if hook_name.startswith('self.'): hook_name = hook_name[5:] hook = getattr(self, hook_name) return hook() elif hook_name.startswith('exe.'): hook_name = hook_name[4:] var = self.executables[hook_name] if var: return var[0] else: return None elif hook_name.startswith('flags.'): hook_name = hook_name[6:] hook = getattr(self, 'get_flags_' + hook_name) return hook() else: return hook_name() def can_ccompiler_link(self, ccompiler): return True def wrap_unlinkable_objects(self, objects, output_dir, extra_dll_dir): raise NotImplementedError() _default_compilers = (('win32', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang')), ('cygwin.*', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95')), ('linux.*', ('arm', 'gnu95', 'intel', 'lahey', 'pg', 'nv', 'absoft', 'nag', 'vast', 'compaq', 'intele', 'intelem', 'gnu', 'g95', 'pathf95', 'nagfor', 'fujitsu')), ('darwin.*', ('gnu95', 'nag', 'nagfor', 'absoft', 'ibm', 'intel', 'gnu', 'g95', 'pg')), ('sunos.*', ('sun', 'gnu', 'gnu95', 'g95')), ('irix.*', ('mips', 'gnu', 'gnu95')), ('aix.*', ('ibm', 'gnu', 'gnu95')), ('posix', ('gnu', 'gnu95')), ('nt', ('gnu', 'gnu95')), ('mac', ('gnu95', 'gnu', 'pg'))) fcompiler_class = None fcompiler_aliases = None def load_all_fcompiler_classes(): from glob import glob global fcompiler_class, fcompiler_aliases if fcompiler_class is not None: return pys = os.path.join(os.path.dirname(__file__), '*.py') fcompiler_class = {} fcompiler_aliases = {} for fname in glob(pys): (module_name, ext) = os.path.splitext(os.path.basename(fname)) module_name = 'numpy.distutils.fcompiler.' + module_name __import__(module_name) module = sys.modules[module_name] if hasattr(module, 'compilers'): for cname in module.compilers: klass = getattr(module, cname) desc = (klass.compiler_type, klass, klass.description) fcompiler_class[klass.compiler_type] = desc for alias in klass.compiler_aliases: if alias in fcompiler_aliases: raise ValueError('alias %r defined for both %s and %s' % (alias, klass.__name__, fcompiler_aliases[alias][1].__name__)) fcompiler_aliases[alias] = desc def _find_existing_fcompiler(compiler_types, osname=None, platform=None, requiref90=False, c_compiler=None): from numpy.distutils.core import get_distribution dist = get_distribution(always=True) for compiler_type in compiler_types: v = None try: c = new_fcompiler(plat=platform, compiler=compiler_type, c_compiler=c_compiler) c.customize(dist) v = c.get_version() if requiref90 and c.compiler_f90 is None: v = None new_compiler = c.suggested_f90_compiler if new_compiler: log.warn('Trying %r compiler as suggested by %r compiler for f90 support.' % (compiler_type, new_compiler)) c = new_fcompiler(plat=platform, compiler=new_compiler, c_compiler=c_compiler) c.customize(dist) v = c.get_version() if v is not None: compiler_type = new_compiler if requiref90 and c.compiler_f90 is None: raise ValueError('%s does not support compiling f90 codes, skipping.' % c.__class__.__name__) except DistutilsModuleError: log.debug("_find_existing_fcompiler: compiler_type='%s' raised DistutilsModuleError", compiler_type) except CompilerNotFound: log.debug("_find_existing_fcompiler: compiler_type='%s' not found", compiler_type) if v is not None: return compiler_type return None def available_fcompilers_for_platform(osname=None, platform=None): if osname is None: osname = os.name if platform is None: platform = sys.platform matching_compiler_types = [] for (pattern, compiler_type) in _default_compilers: if re.match(pattern, platform) or re.match(pattern, osname): for ct in compiler_type: if ct not in matching_compiler_types: matching_compiler_types.append(ct) if not matching_compiler_types: matching_compiler_types.append('gnu') return matching_compiler_types def get_default_fcompiler(osname=None, platform=None, requiref90=False, c_compiler=None): matching_compiler_types = available_fcompilers_for_platform(osname, platform) log.info("get_default_fcompiler: matching types: '%s'", matching_compiler_types) compiler_type = _find_existing_fcompiler(matching_compiler_types, osname=osname, platform=platform, requiref90=requiref90, c_compiler=c_compiler) return compiler_type failed_fcompilers = set() def new_fcompiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0, requiref90=False, c_compiler=None): global failed_fcompilers fcompiler_key = (plat, compiler) if fcompiler_key in failed_fcompilers: return None load_all_fcompiler_classes() if plat is None: plat = os.name if compiler is None: compiler = get_default_fcompiler(plat, requiref90=requiref90, c_compiler=c_compiler) if compiler in fcompiler_class: (module_name, klass, long_description) = fcompiler_class[compiler] elif compiler in fcompiler_aliases: (module_name, klass, long_description) = fcompiler_aliases[compiler] else: msg = "don't know how to compile Fortran code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler." % compiler msg = msg + ' Supported compilers are: %s)' % ','.join(fcompiler_class.keys()) log.warn(msg) failed_fcompilers.add(fcompiler_key) return None compiler = klass(verbose=verbose, dry_run=dry_run, force=force) compiler.c_compiler = c_compiler return compiler def show_fcompilers(dist=None): if dist is None: from distutils.dist import Distribution from numpy.distutils.command.config_compiler import config_fc dist = Distribution() dist.script_name = os.path.basename(sys.argv[0]) dist.script_args = ['config_fc'] + sys.argv[1:] try: dist.script_args.remove('--help-fcompiler') except ValueError: pass dist.cmdclass['config_fc'] = config_fc dist.parse_config_files() dist.parse_command_line() compilers = [] compilers_na = [] compilers_ni = [] if not fcompiler_class: load_all_fcompiler_classes() platform_compilers = available_fcompilers_for_platform() for compiler in platform_compilers: v = None log.set_verbosity(-2) try: c = new_fcompiler(compiler=compiler, verbose=dist.verbose) c.customize(dist) v = c.get_version() except (DistutilsModuleError, CompilerNotFound) as e: log.debug('show_fcompilers: %s not found' % (compiler,)) log.debug(repr(e)) if v is None: compilers_na.append(('fcompiler=' + compiler, None, fcompiler_class[compiler][2])) else: c.dump_properties() compilers.append(('fcompiler=' + compiler, None, fcompiler_class[compiler][2] + ' (%s)' % v)) compilers_ni = list(set(fcompiler_class.keys()) - set(platform_compilers)) compilers_ni = [('fcompiler=' + fc, None, fcompiler_class[fc][2]) for fc in compilers_ni] compilers.sort() compilers_na.sort() compilers_ni.sort() pretty_printer = FancyGetopt(compilers) pretty_printer.print_help('Fortran compilers found:') pretty_printer = FancyGetopt(compilers_na) pretty_printer.print_help('Compilers available for this platform, but not found:') if compilers_ni: pretty_printer = FancyGetopt(compilers_ni) pretty_printer.print_help('Compilers not available on this platform:') print("For compiler details, run 'config_fc --verbose' setup command.") def dummy_fortran_file(): (fo, name) = make_temp_file(suffix='.f') fo.write(' subroutine dummy()\n end\n') fo.close() return name[:-2] _has_f_header = re.compile('-\\*-\\s*fortran\\s*-\\*-', re.I).search _has_f90_header = re.compile('-\\*-\\s*f90\\s*-\\*-', re.I).search _has_fix_header = re.compile('-\\*-\\s*fix\\s*-\\*-', re.I).search _free_f90_start = re.compile('[^c*!]\\s*[^\\s\\d\\t]', re.I).match def is_free_format(file): result = 0 with open(file, encoding='latin1') as f: line = f.readline() n = 10000 if _has_f_header(line) or _has_fix_header(line): n = 0 elif _has_f90_header(line): n = 0 result = 1 while n > 0 and line: line = line.rstrip() if line and line[0] != '!': n -= 1 if line[0] != '\t' and _free_f90_start(line[:5]) or line[-1:] == '&': result = 1 break line = f.readline() return result def has_f90_header(src): with open(src, encoding='latin1') as f: line = f.readline() return _has_f90_header(line) or _has_fix_header(line) _f77flags_re = re.compile('(c|)f77flags\\s*\\(\\s*(?P\\w+)\\s*\\)\\s*=\\s*(?P.*)', re.I) def get_f77flags(src): flags = {} with open(src, encoding='latin1') as f: i = 0 for line in f: i += 1 if i > 20: break m = _f77flags_re.match(line) if not m: continue fcname = m.group('fcname').strip() fflags = m.group('fflags').strip() flags[fcname] = split_quoted(fflags) return flags if __name__ == '__main__': show_fcompilers() # File: numpy-main/numpy/distutils/fcompiler/absoft.py import os from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file from numpy.distutils.misc_util import cyg2win32 compilers = ['AbsoftFCompiler'] class AbsoftFCompiler(FCompiler): compiler_type = 'absoft' description = 'Absoft Corp Fortran Compiler' version_pattern = '(f90:.*?(Absoft Pro FORTRAN Version|FORTRAN 77 Compiler|Absoft Fortran Compiler Version|Copyright Absoft Corporation.*?Version))' + ' (?P[^\\s*,]*)(.*?Absoft Corp|)' executables = {'version_cmd': None, 'compiler_f77': ['f77'], 'compiler_fix': ['f90'], 'compiler_f90': ['f90'], 'linker_so': [''], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} if os.name == 'nt': library_switch = '/out:' module_dir_switch = None module_include_switch = '-p' def update_executables(self): f = cyg2win32(dummy_fortran_file()) self.executables['version_cmd'] = ['', '-V', '-c', f + '.f', '-o', f + '.o'] def get_flags_linker_so(self): if os.name == 'nt': opt = ['/dll'] elif self.get_version() >= '9.0': opt = ['-shared'] else: opt = ['-K', 'shared'] return opt def library_dir_option(self, dir): if os.name == 'nt': return ['-link', '/PATH:%s' % dir] return '-L' + dir def library_option(self, lib): if os.name == 'nt': return '%s.lib' % lib return '-l' + lib def get_library_dirs(self): opt = FCompiler.get_library_dirs(self) d = os.environ.get('ABSOFT') if d: if self.get_version() >= '10.0': prefix = 'sh' else: prefix = '' if cpu.is_64bit(): suffix = '64' else: suffix = '' opt.append(os.path.join(d, '%slib%s' % (prefix, suffix))) return opt def get_libraries(self): opt = FCompiler.get_libraries(self) if self.get_version() >= '11.0': opt.extend(['af90math', 'afio', 'af77math', 'amisc']) elif self.get_version() >= '10.0': opt.extend(['af90math', 'afio', 'af77math', 'U77']) elif self.get_version() >= '8.0': opt.extend(['f90math', 'fio', 'f77math', 'U77']) else: opt.extend(['fio', 'f90math', 'fmath', 'U77']) if os.name == 'nt': opt.append('COMDLG32') return opt def get_flags(self): opt = FCompiler.get_flags(self) if os.name != 'nt': opt.extend(['-s']) if self.get_version(): if self.get_version() >= '8.2': opt.append('-fpic') return opt def get_flags_f77(self): opt = FCompiler.get_flags_f77(self) opt.extend(['-N22', '-N90', '-N110']) v = self.get_version() if os.name == 'nt': if v and v >= '8.0': opt.extend(['-f', '-N15']) else: opt.append('-f') if v: if v <= '4.6': opt.append('-B108') else: opt.append('-N15') return opt def get_flags_f90(self): opt = FCompiler.get_flags_f90(self) opt.extend(['-YCFRL=1', '-YCOM_NAMES=LCS', '-YCOM_PFX', '-YEXT_PFX', '-YCOM_SFX=_', '-YEXT_SFX=_', '-YEXT_NAMES=LCS']) if self.get_version(): if self.get_version() > '4.6': opt.extend(['-YDEALLOC=ALL']) return opt def get_flags_fix(self): opt = FCompiler.get_flags_fix(self) opt.extend(['-YCFRL=1', '-YCOM_NAMES=LCS', '-YCOM_PFX', '-YEXT_PFX', '-YCOM_SFX=_', '-YEXT_SFX=_', '-YEXT_NAMES=LCS']) opt.extend(['-f', 'fixed']) return opt def get_flags_opt(self): opt = ['-O'] return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='absoft').get_version()) # File: numpy-main/numpy/distutils/fcompiler/arm.py import sys from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file from sys import platform from os.path import join, dirname, normpath compilers = ['ArmFlangCompiler'] import functools class ArmFlangCompiler(FCompiler): compiler_type = 'arm' description = 'Arm Compiler' version_pattern = '\\s*Arm.*version (?P[\\d.-]+).*' ar_exe = 'lib.exe' possible_executables = ['armflang'] executables = {'version_cmd': ['', '--version'], 'compiler_f77': ['armflang', '-fPIC'], 'compiler_fix': ['armflang', '-fPIC', '-ffixed-form'], 'compiler_f90': ['armflang', '-fPIC'], 'linker_so': ['armflang', '-fPIC', '-shared'], 'archiver': ['ar', '-cr'], 'ranlib': None} pic_flags = ['-fPIC', '-DPIC'] c_compiler = 'arm' module_dir_switch = '-module ' def get_libraries(self): opt = FCompiler.get_libraries(self) opt.extend(['flang', 'flangrti', 'ompstub']) return opt @functools.lru_cache(maxsize=128) def get_library_dirs(self): opt = FCompiler.get_library_dirs(self) flang_dir = dirname(self.executables['compiler_f77'][0]) opt.append(normpath(join(flang_dir, '..', 'lib'))) return opt def get_flags(self): return [] def get_flags_free(self): return [] def get_flags_debug(self): return ['-g'] def get_flags_opt(self): return ['-O3'] def get_flags_arch(self): return [] def runtime_library_dir_option(self, dir): return '-Wl,-rpath=%s' % dir if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='armflang').get_version()) # File: numpy-main/numpy/distutils/fcompiler/compaq.py import os import sys from numpy.distutils.fcompiler import FCompiler from distutils.errors import DistutilsPlatformError compilers = ['CompaqFCompiler'] if os.name != 'posix' or sys.platform[:6] == 'cygwin': compilers.append('CompaqVisualFCompiler') class CompaqFCompiler(FCompiler): compiler_type = 'compaq' description = 'Compaq Fortran Compiler' version_pattern = 'Compaq Fortran (?P[^\\s]*).*' if sys.platform[:5] == 'linux': fc_exe = 'fort' else: fc_exe = 'f90' executables = {'version_cmd': ['', '-version'], 'compiler_f77': [fc_exe, '-f77rtl', '-fixed'], 'compiler_fix': [fc_exe, '-fixed'], 'compiler_f90': [fc_exe], 'linker_so': [''], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} module_dir_switch = '-module ' module_include_switch = '-I' def get_flags(self): return ['-assume no2underscore', '-nomixed_str_len_arg'] def get_flags_debug(self): return ['-g', '-check bounds'] def get_flags_opt(self): return ['-O4', '-align dcommons', '-assume bigarrays', '-assume nozsize', '-math_library fast'] def get_flags_arch(self): return ['-arch host', '-tune host'] def get_flags_linker_so(self): if sys.platform[:5] == 'linux': return ['-shared'] return ['-shared', '-Wl,-expect_unresolved,*'] class CompaqVisualFCompiler(FCompiler): compiler_type = 'compaqv' description = 'DIGITAL or Compaq Visual Fortran Compiler' version_pattern = '(DIGITAL|Compaq) Visual Fortran Optimizing Compiler Version (?P[^\\s]*).*' compile_switch = '/compile_only' object_switch = '/object:' library_switch = '/OUT:' static_lib_extension = '.lib' static_lib_format = '%s%s' module_dir_switch = '/module:' module_include_switch = '/I' ar_exe = 'lib.exe' fc_exe = 'DF' if sys.platform == 'win32': from numpy.distutils.msvccompiler import MSVCCompiler try: m = MSVCCompiler() m.initialize() ar_exe = m.lib except DistutilsPlatformError: pass except AttributeError as e: if '_MSVCCompiler__root' in str(e): print('Ignoring "%s" (I think it is msvccompiler.py bug)' % e) else: raise except OSError as e: if not 'vcvarsall.bat' in str(e): print('Unexpected OSError in', __file__) raise except ValueError as e: if not "'path'" in str(e): print('Unexpected ValueError in', __file__) raise executables = {'version_cmd': ['', '/what'], 'compiler_f77': [fc_exe, '/f77rtl', '/fixed'], 'compiler_fix': [fc_exe, '/fixed'], 'compiler_f90': [fc_exe], 'linker_so': [''], 'archiver': [ar_exe, '/OUT:'], 'ranlib': None} def get_flags(self): return ['/nologo', '/MD', '/WX', '/iface=(cref,nomixed_str_len_arg)', '/names:lowercase', '/assume:underscore'] def get_flags_opt(self): return ['/Ox', '/fast', '/optimize:5', '/unroll:0', '/math_library:fast'] def get_flags_arch(self): return ['/threads'] def get_flags_debug(self): return ['/debug'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='compaq').get_version()) # File: numpy-main/numpy/distutils/fcompiler/environment.py import os from distutils.dist import Distribution __metaclass__ = type class EnvironmentConfig: def __init__(self, distutils_section='ALL', **kw): self._distutils_section = distutils_section self._conf_keys = kw self._conf = None self._hook_handler = None def dump_variable(self, name): conf_desc = self._conf_keys[name] (hook, envvar, confvar, convert, append) = conf_desc if not convert: convert = lambda x: x print('%s.%s:' % (self._distutils_section, name)) v = self._hook_handler(name, hook) print(' hook : %s' % (convert(v),)) if envvar: v = os.environ.get(envvar, None) print(' environ: %s' % (convert(v),)) if confvar and self._conf: v = self._conf.get(confvar, (None, None))[1] print(' config : %s' % (convert(v),)) def dump_variables(self): for name in self._conf_keys: self.dump_variable(name) def __getattr__(self, name): try: conf_desc = self._conf_keys[name] except KeyError: raise AttributeError(f"'EnvironmentConfig' object has no attribute '{name}'") from None return self._get_var(name, conf_desc) def get(self, name, default=None): try: conf_desc = self._conf_keys[name] except KeyError: return default var = self._get_var(name, conf_desc) if var is None: var = default return var def _get_var(self, name, conf_desc): (hook, envvar, confvar, convert, append) = conf_desc if convert is None: convert = lambda x: x var = self._hook_handler(name, hook) if envvar is not None: envvar_contents = os.environ.get(envvar) if envvar_contents is not None: envvar_contents = convert(envvar_contents) if var and append: if os.environ.get('NPY_DISTUTILS_APPEND_FLAGS', '1') == '1': var.extend(envvar_contents) else: var = envvar_contents else: var = envvar_contents if confvar is not None and self._conf: if confvar in self._conf: (source, confvar_contents) = self._conf[confvar] var = convert(confvar_contents) return var def clone(self, hook_handler): ec = self.__class__(distutils_section=self._distutils_section, **self._conf_keys) ec._hook_handler = hook_handler return ec def use_distribution(self, dist): if isinstance(dist, Distribution): self._conf = dist.get_option_dict(self._distutils_section) else: self._conf = dist # File: numpy-main/numpy/distutils/fcompiler/fujitsu.py """""" from numpy.distutils.fcompiler import FCompiler compilers = ['FujitsuFCompiler'] class FujitsuFCompiler(FCompiler): compiler_type = 'fujitsu' description = 'Fujitsu Fortran Compiler' possible_executables = ['frt'] version_pattern = 'frt \\(FRT\\) (?P[a-z\\d.]+)' executables = {'version_cmd': ['', '--version'], 'compiler_f77': ['frt', '-Fixed'], 'compiler_fix': ['frt', '-Fixed'], 'compiler_f90': ['frt'], 'linker_so': ['frt', '-shared'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} pic_flags = ['-KPIC'] module_dir_switch = '-M' module_include_switch = '-I' def get_flags_opt(self): return ['-O3'] def get_flags_debug(self): return ['-g'] def runtime_library_dir_option(self, dir): return f'-Wl,-rpath={dir}' def get_libraries(self): return ['fj90f', 'fj90i', 'fjsrcinfo'] if __name__ == '__main__': from distutils import log from numpy.distutils import customized_fcompiler log.set_verbosity(2) print(customized_fcompiler('fujitsu').get_version()) # File: numpy-main/numpy/distutils/fcompiler/g95.py from numpy.distutils.fcompiler import FCompiler compilers = ['G95FCompiler'] class G95FCompiler(FCompiler): compiler_type = 'g95' description = 'G95 Fortran Compiler' version_pattern = 'G95 \\((GCC (?P[\\d.]+)|.*?) \\(g95 (?P.*)!\\) (?P.*)\\).*' executables = {'version_cmd': ['', '--version'], 'compiler_f77': ['g95', '-ffixed-form'], 'compiler_fix': ['g95', '-ffixed-form'], 'compiler_f90': ['g95'], 'linker_so': ['', '-shared'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} pic_flags = ['-fpic'] module_dir_switch = '-fmod=' module_include_switch = '-I' def get_flags(self): return ['-fno-second-underscore'] def get_flags_opt(self): return ['-O'] def get_flags_debug(self): return ['-g'] if __name__ == '__main__': from distutils import log from numpy.distutils import customized_fcompiler log.set_verbosity(2) print(customized_fcompiler('g95').get_version()) # File: numpy-main/numpy/distutils/fcompiler/gnu.py import re import os import sys import warnings import platform import tempfile import hashlib import base64 import subprocess from subprocess import Popen, PIPE, STDOUT from numpy.distutils.exec_command import filepath_from_subprocess_output from numpy.distutils.fcompiler import FCompiler from distutils.version import LooseVersion compilers = ['GnuFCompiler', 'Gnu95FCompiler'] TARGET_R = re.compile('Target: ([a-zA-Z0-9_\\-]*)') def is_win64(): return sys.platform == 'win32' and platform.architecture()[0] == '64bit' class GnuFCompiler(FCompiler): compiler_type = 'gnu' compiler_aliases = ('g77',) description = 'GNU Fortran 77 compiler' def gnu_version_match(self, version_string): while version_string.startswith('gfortran: warning'): version_string = version_string[version_string.find('\n') + 1:].strip() if len(version_string) <= 20: m = re.search('([0-9.]+)', version_string) if m: if version_string.startswith('GNU Fortran'): return ('g77', m.group(1)) elif m.start() == 0: return ('gfortran', m.group(1)) else: m = re.search('GNU Fortran\\s+95.*?([0-9-.]+)', version_string) if m: return ('gfortran', m.group(1)) m = re.search('GNU Fortran.*?\\-?([0-9-.]+\\.[0-9-.]+)', version_string) if m: v = m.group(1) if v.startswith('0') or v.startswith('2') or v.startswith('3'): return ('g77', v) else: return ('gfortran', v) err = 'A valid Fortran version was not found in this string:\n' raise ValueError(err + version_string) def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'g77': return None return v[1] possible_executables = ['g77', 'f77'] executables = {'version_cmd': [None, '-dumpversion'], 'compiler_f77': [None, '-g', '-Wall', '-fno-second-underscore'], 'compiler_f90': None, 'compiler_fix': None, 'linker_so': [None, '-g', '-Wall'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib'], 'linker_exe': [None, '-g', '-Wall']} module_dir_switch = None module_include_switch = None if os.name != 'nt' and sys.platform != 'cygwin': pic_flags = ['-fPIC'] if sys.platform == 'win32': for key in ['version_cmd', 'compiler_f77', 'linker_so', 'linker_exe']: executables[key].append('-mno-cygwin') g2c = 'g2c' suggested_f90_compiler = 'gnu95' def get_flags_linker_so(self): opt = self.linker_so[1:] if sys.platform == 'darwin': target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) if not target: import sysconfig target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') if not target: target = '10.9' s = f'Env. variable MACOSX_DEPLOYMENT_TARGET set to {target}' warnings.warn(s, stacklevel=2) os.environ['MACOSX_DEPLOYMENT_TARGET'] = str(target) opt.extend(['-undefined', 'dynamic_lookup', '-bundle']) else: opt.append('-shared') if sys.platform.startswith('sunos'): opt.append('-mimpure-text') return opt def get_libgcc_dir(self): try: output = subprocess.check_output(self.compiler_f77 + ['-print-libgcc-file-name']) except (OSError, subprocess.CalledProcessError): pass else: output = filepath_from_subprocess_output(output) return os.path.dirname(output) return None def get_libgfortran_dir(self): if sys.platform[:5] == 'linux': libgfortran_name = 'libgfortran.so' elif sys.platform == 'darwin': libgfortran_name = 'libgfortran.dylib' else: libgfortran_name = None libgfortran_dir = None if libgfortran_name: find_lib_arg = ['-print-file-name={0}'.format(libgfortran_name)] try: output = subprocess.check_output(self.compiler_f77 + find_lib_arg) except (OSError, subprocess.CalledProcessError): pass else: output = filepath_from_subprocess_output(output) libgfortran_dir = os.path.dirname(output) return libgfortran_dir def get_library_dirs(self): opt = [] if sys.platform[:5] != 'linux': d = self.get_libgcc_dir() if d: if sys.platform == 'win32' and (not d.startswith('/usr/lib')): d = os.path.normpath(d) path = os.path.join(d, 'lib%s.a' % self.g2c) if not os.path.exists(path): root = os.path.join(d, *(os.pardir,) * 4) d2 = os.path.abspath(os.path.join(root, 'lib')) path = os.path.join(d2, 'lib%s.a' % self.g2c) if os.path.exists(path): opt.append(d2) opt.append(d) lib_gfortran_dir = self.get_libgfortran_dir() if lib_gfortran_dir: opt.append(lib_gfortran_dir) return opt def get_libraries(self): opt = [] d = self.get_libgcc_dir() if d is not None: g2c = self.g2c + '-pic' f = self.static_lib_format % (g2c, self.static_lib_extension) if not os.path.isfile(os.path.join(d, f)): g2c = self.g2c else: g2c = self.g2c if g2c is not None: opt.append(g2c) c_compiler = self.c_compiler if sys.platform == 'win32' and c_compiler and (c_compiler.compiler_type == 'msvc'): opt.append('gcc') if sys.platform == 'darwin': opt.append('cc_dynamic') return opt def get_flags_debug(self): return ['-g'] def get_flags_opt(self): v = self.get_version() if v and v <= '3.3.3': opt = ['-O2'] else: opt = ['-O3'] opt.append('-funroll-loops') return opt def _c_arch_flags(self): import sysconfig try: cflags = sysconfig.get_config_vars()['CFLAGS'] except KeyError: return [] arch_re = re.compile('-arch\\s+(\\w+)') arch_flags = [] for arch in arch_re.findall(cflags): arch_flags += ['-arch', arch] return arch_flags def get_flags_arch(self): return [] def runtime_library_dir_option(self, dir): if sys.platform == 'win32' or sys.platform == 'cygwin': raise NotImplementedError assert ',' not in dir if sys.platform == 'darwin': return f'-Wl,-rpath,{dir}' elif sys.platform.startswith(('aix', 'os400')): return f'-Wl,-blibpath:{dir}' else: return f'-Wl,-rpath={dir}' class Gnu95FCompiler(GnuFCompiler): compiler_type = 'gnu95' compiler_aliases = ('gfortran',) description = 'GNU Fortran 95 compiler' def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'gfortran': return None v = v[1] if LooseVersion(v) >= '4': pass elif sys.platform == 'win32': for key in ['version_cmd', 'compiler_f77', 'compiler_f90', 'compiler_fix', 'linker_so', 'linker_exe']: self.executables[key].append('-mno-cygwin') return v possible_executables = ['gfortran', 'f95'] executables = {'version_cmd': ['', '-dumpversion'], 'compiler_f77': [None, '-Wall', '-g', '-ffixed-form', '-fno-second-underscore'], 'compiler_f90': [None, '-Wall', '-g', '-fno-second-underscore'], 'compiler_fix': [None, '-Wall', '-g', '-ffixed-form', '-fno-second-underscore'], 'linker_so': ['', '-Wall', '-g'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib'], 'linker_exe': [None, '-Wall']} module_dir_switch = '-J' module_include_switch = '-I' if sys.platform.startswith(('aix', 'os400')): executables['linker_so'].append('-lpthread') if platform.architecture()[0][:2] == '64': for key in ['compiler_f77', 'compiler_f90', 'compiler_fix', 'linker_so', 'linker_exe']: executables[key].append('-maix64') g2c = 'gfortran' def _universal_flags(self, cmd): if not sys.platform == 'darwin': return [] arch_flags = [] c_archs = self._c_arch_flags() if 'i386' in c_archs: c_archs[c_archs.index('i386')] = 'i686' for arch in ['ppc', 'i686', 'x86_64', 'ppc64', 's390x']: if _can_target(cmd, arch) and arch in c_archs: arch_flags.extend(['-arch', arch]) return arch_flags def get_flags(self): flags = GnuFCompiler.get_flags(self) arch_flags = self._universal_flags(self.compiler_f90) if arch_flags: flags[:0] = arch_flags return flags def get_flags_linker_so(self): flags = GnuFCompiler.get_flags_linker_so(self) arch_flags = self._universal_flags(self.linker_so) if arch_flags: flags[:0] = arch_flags return flags def get_library_dirs(self): opt = GnuFCompiler.get_library_dirs(self) if sys.platform == 'win32': c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == 'msvc': target = self.get_target() if target: d = os.path.normpath(self.get_libgcc_dir()) root = os.path.join(d, *(os.pardir,) * 4) path = os.path.join(root, 'lib') mingwdir = os.path.normpath(path) if os.path.exists(os.path.join(mingwdir, 'libmingwex.a')): opt.append(mingwdir) lib_gfortran_dir = self.get_libgfortran_dir() if lib_gfortran_dir: opt.append(lib_gfortran_dir) return opt def get_libraries(self): opt = GnuFCompiler.get_libraries(self) if sys.platform == 'darwin': opt.remove('cc_dynamic') if sys.platform == 'win32': c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == 'msvc': if 'gcc' in opt: i = opt.index('gcc') opt.insert(i + 1, 'mingwex') opt.insert(i + 1, 'mingw32') c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == 'msvc': return [] else: pass return opt def get_target(self): try: p = subprocess.Popen(self.compiler_f77 + ['-v'], stdin=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() output = (stdout or b'') + (stderr or b'') except (OSError, subprocess.CalledProcessError): pass else: output = filepath_from_subprocess_output(output) m = TARGET_R.search(output) if m: return m.group(1) return '' def _hash_files(self, filenames): h = hashlib.sha1() for fn in filenames: with open(fn, 'rb') as f: while True: block = f.read(131072) if not block: break h.update(block) text = base64.b32encode(h.digest()) text = text.decode('ascii') return text.rstrip('=') def _link_wrapper_lib(self, objects, output_dir, extra_dll_dir, chained_dlls, is_archive): c_compiler = self.c_compiler if c_compiler.compiler_type != 'msvc': raise ValueError('This method only supports MSVC') object_hash = self._hash_files(list(objects) + list(chained_dlls)) if is_win64(): tag = 'win_amd64' else: tag = 'win32' basename = 'lib' + os.path.splitext(os.path.basename(objects[0]))[0][:8] root_name = basename + '.' + object_hash + '.gfortran-' + tag dll_name = root_name + '.dll' def_name = root_name + '.def' lib_name = root_name + '.lib' dll_path = os.path.join(extra_dll_dir, dll_name) def_path = os.path.join(output_dir, def_name) lib_path = os.path.join(output_dir, lib_name) if os.path.isfile(lib_path): return (lib_path, dll_path) if is_archive: objects = ['-Wl,--whole-archive'] + list(objects) + ['-Wl,--no-whole-archive'] self.link_shared_object(objects, dll_name, output_dir=extra_dll_dir, extra_postargs=list(chained_dlls) + ['-Wl,--allow-multiple-definition', '-Wl,--output-def,' + def_path, '-Wl,--export-all-symbols', '-Wl,--enable-auto-import', '-static', '-mlong-double-64']) if is_win64(): specifier = '/MACHINE:X64' else: specifier = '/MACHINE:X86' lib_args = ['/def:' + def_path, '/OUT:' + lib_path, specifier] if not c_compiler.initialized: c_compiler.initialize() c_compiler.spawn([c_compiler.lib] + lib_args) return (lib_path, dll_path) def can_ccompiler_link(self, compiler): return compiler.compiler_type not in ('msvc',) def wrap_unlinkable_objects(self, objects, output_dir, extra_dll_dir): if self.c_compiler.compiler_type == 'msvc': archives = [] plain_objects = [] for obj in objects: if obj.lower().endswith('.a'): archives.append(obj) else: plain_objects.append(obj) chained_libs = [] chained_dlls = [] for archive in archives[::-1]: (lib, dll) = self._link_wrapper_lib([archive], output_dir, extra_dll_dir, chained_dlls=chained_dlls, is_archive=True) chained_libs.insert(0, lib) chained_dlls.insert(0, dll) if not plain_objects: return chained_libs (lib, dll) = self._link_wrapper_lib(plain_objects, output_dir, extra_dll_dir, chained_dlls=chained_dlls, is_archive=False) return [lib] + chained_libs else: raise ValueError('Unsupported C compiler') def _can_target(cmd, arch): newcmd = cmd[:] (fid, filename) = tempfile.mkstemp(suffix='.f') os.close(fid) try: d = os.path.dirname(filename) output = os.path.splitext(filename)[0] + '.o' try: newcmd.extend(['-arch', arch, '-c', filename]) p = Popen(newcmd, stderr=STDOUT, stdout=PIPE, cwd=d) p.communicate() return p.returncode == 0 finally: if os.path.exists(output): os.remove(output) finally: os.remove(filename) if __name__ == '__main__': from distutils import log from numpy.distutils import customized_fcompiler log.set_verbosity(2) print(customized_fcompiler('gnu').get_version()) try: print(customized_fcompiler('g95').get_version()) except Exception as e: print(e) # File: numpy-main/numpy/distutils/fcompiler/hpux.py from numpy.distutils.fcompiler import FCompiler compilers = ['HPUXFCompiler'] class HPUXFCompiler(FCompiler): compiler_type = 'hpux' description = 'HP Fortran 90 Compiler' version_pattern = 'HP F90 (?P[^\\s*,]*)' executables = {'version_cmd': ['f90', '+version'], 'compiler_f77': ['f90'], 'compiler_fix': ['f90'], 'compiler_f90': ['f90'], 'linker_so': ['ld', '-b'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} module_dir_switch = None module_include_switch = None pic_flags = ['+Z'] def get_flags(self): return self.pic_flags + ['+ppu', '+DD64'] def get_flags_opt(self): return ['-O3'] def get_libraries(self): return ['m'] def get_library_dirs(self): opt = ['/usr/lib/hpux64'] return opt def get_version(self, force=0, ok_status=[256, 0, 1]): return FCompiler.get_version(self, force, ok_status) if __name__ == '__main__': from distutils import log log.set_verbosity(10) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='hpux').get_version()) # File: numpy-main/numpy/distutils/fcompiler/ibm.py import os import re import sys import subprocess from numpy.distutils.fcompiler import FCompiler from numpy.distutils.exec_command import find_executable from numpy.distutils.misc_util import make_temp_file from distutils import log compilers = ['IBMFCompiler'] class IBMFCompiler(FCompiler): compiler_type = 'ibm' description = 'IBM XL Fortran Compiler' version_pattern = '(xlf\\(1\\)\\s*|)IBM XL Fortran ((Advanced Edition |)Version |Enterprise Edition V|for AIX, V)(?P[^\\s*]*)' executables = {'version_cmd': ['', '-qversion'], 'compiler_f77': ['xlf'], 'compiler_fix': ['xlf90', '-qfixed'], 'compiler_f90': ['xlf90'], 'linker_so': ['xlf95'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} def get_version(self, *args, **kwds): version = FCompiler.get_version(self, *args, **kwds) if version is None and sys.platform.startswith('aix'): lslpp = find_executable('lslpp') xlf = find_executable('xlf') if os.path.exists(xlf) and os.path.exists(lslpp): try: o = subprocess.check_output([lslpp, '-Lc', 'xlfcmp']) except (OSError, subprocess.CalledProcessError): pass else: m = re.search('xlfcmp:(?P\\d+([.]\\d+)+)', o) if m: version = m.group('version') xlf_dir = '/etc/opt/ibmcmp/xlf' if version is None and os.path.isdir(xlf_dir): l = sorted(os.listdir(xlf_dir)) l.reverse() l = [d for d in l if os.path.isfile(os.path.join(xlf_dir, d, 'xlf.cfg'))] if l: from distutils.version import LooseVersion self.version = version = LooseVersion(l[0]) return version def get_flags(self): return ['-qextname'] def get_flags_debug(self): return ['-g'] def get_flags_linker_so(self): opt = [] if sys.platform == 'darwin': opt.append('-Wl,-bundle,-flat_namespace,-undefined,suppress') else: opt.append('-bshared') version = self.get_version(ok_status=[0, 40]) if version is not None: if sys.platform.startswith('aix'): xlf_cfg = '/etc/xlf.cfg' else: xlf_cfg = '/etc/opt/ibmcmp/xlf/%s/xlf.cfg' % version (fo, new_cfg) = make_temp_file(suffix='_xlf.cfg') log.info('Creating ' + new_cfg) with open(xlf_cfg) as fi: crt1_match = re.compile('\\s*crt\\s*=\\s*(?P.*)/crt1.o').match for line in fi: m = crt1_match(line) if m: fo.write('crt = %s/bundle1.o\n' % m.group('path')) else: fo.write(line) fo.close() opt.append('-F' + new_cfg) return opt def get_flags_opt(self): return ['-O3'] if __name__ == '__main__': from numpy.distutils import customized_fcompiler log.set_verbosity(2) print(customized_fcompiler(compiler='ibm').get_version()) # File: numpy-main/numpy/distutils/fcompiler/intel.py import sys from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file compilers = ['IntelFCompiler', 'IntelVisualFCompiler', 'IntelItaniumFCompiler', 'IntelItaniumVisualFCompiler', 'IntelEM64VisualFCompiler', 'IntelEM64TFCompiler'] def intel_version_match(type): return simple_version_match(start='Intel.*?Fortran.*?(?:%s).*?Version' % (type,)) class BaseIntelFCompiler(FCompiler): def update_executables(self): f = dummy_fortran_file() self.executables['version_cmd'] = ['', '-FI', '-V', '-c', f + '.f', '-o', f + '.o'] def runtime_library_dir_option(self, dir): assert ',' not in dir return '-Wl,-rpath=%s' % dir class IntelFCompiler(BaseIntelFCompiler): compiler_type = 'intel' compiler_aliases = ('ifort',) description = 'Intel Fortran Compiler for 32-bit apps' version_match = intel_version_match('32-bit|IA-32') possible_executables = ['ifort', 'ifc'] executables = {'version_cmd': None, 'compiler_f77': [None, '-72', '-w90', '-w95'], 'compiler_f90': [None], 'compiler_fix': [None, '-FI'], 'linker_so': ['', '-shared'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} pic_flags = ['-fPIC'] module_dir_switch = '-module ' module_include_switch = '-I' def get_flags_free(self): return ['-FR'] def get_flags(self): return ['-fPIC'] def get_flags_opt(self): v = self.get_version() mpopt = 'openmp' if v and v < '15' else 'qopenmp' return ['-fp-model', 'strict', '-O1', '-assume', 'minus0', '-{}'.format(mpopt)] def get_flags_arch(self): return [] def get_flags_linker_so(self): opt = FCompiler.get_flags_linker_so(self) v = self.get_version() if v and v >= '8.0': opt.append('-nofor_main') if sys.platform == 'darwin': try: idx = opt.index('-shared') opt.remove('-shared') except ValueError: idx = 0 opt[idx:idx] = ['-dynamiclib', '-Wl,-undefined,dynamic_lookup'] return opt class IntelItaniumFCompiler(IntelFCompiler): compiler_type = 'intele' compiler_aliases = () description = 'Intel Fortran Compiler for Itanium apps' version_match = intel_version_match('Itanium|IA-64') possible_executables = ['ifort', 'efort', 'efc'] executables = {'version_cmd': None, 'compiler_f77': [None, '-FI', '-w90', '-w95'], 'compiler_fix': [None, '-FI'], 'compiler_f90': [None], 'linker_so': ['', '-shared'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} class IntelEM64TFCompiler(IntelFCompiler): compiler_type = 'intelem' compiler_aliases = () description = 'Intel Fortran Compiler for 64-bit apps' version_match = intel_version_match('EM64T-based|Intel\\(R\\) 64|64|IA-64|64-bit') possible_executables = ['ifort', 'efort', 'efc'] executables = {'version_cmd': None, 'compiler_f77': [None, '-FI'], 'compiler_fix': [None, '-FI'], 'compiler_f90': [None], 'linker_so': ['', '-shared'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} class IntelVisualFCompiler(BaseIntelFCompiler): compiler_type = 'intelv' description = 'Intel Visual Fortran Compiler for 32-bit apps' version_match = intel_version_match('32-bit|IA-32') def update_executables(self): f = dummy_fortran_file() self.executables['version_cmd'] = ['', '/FI', '/c', f + '.f', '/o', f + '.o'] ar_exe = 'lib.exe' possible_executables = ['ifort', 'ifl'] executables = {'version_cmd': None, 'compiler_f77': [None], 'compiler_fix': [None], 'compiler_f90': [None], 'linker_so': [None], 'archiver': [ar_exe, '/verbose', '/OUT:'], 'ranlib': None} compile_switch = '/c ' object_switch = '/Fo' library_switch = '/OUT:' module_dir_switch = '/module:' module_include_switch = '/I' def get_flags(self): opt = ['/nologo', '/MD', '/nbs', '/names:lowercase', '/assume:underscore', '/fpp'] return opt def get_flags_free(self): return [] def get_flags_debug(self): return ['/4Yb', '/d2'] def get_flags_opt(self): return ['/O1', '/assume:minus0'] def get_flags_arch(self): return ['/arch:IA32', '/QaxSSE3'] def runtime_library_dir_option(self, dir): raise NotImplementedError class IntelItaniumVisualFCompiler(IntelVisualFCompiler): compiler_type = 'intelev' description = 'Intel Visual Fortran Compiler for Itanium apps' version_match = intel_version_match('Itanium') possible_executables = ['efl'] ar_exe = IntelVisualFCompiler.ar_exe executables = {'version_cmd': None, 'compiler_f77': [None, '-FI', '-w90', '-w95'], 'compiler_fix': [None, '-FI', '-4L72', '-w'], 'compiler_f90': [None], 'linker_so': ['', '-shared'], 'archiver': [ar_exe, '/verbose', '/OUT:'], 'ranlib': None} class IntelEM64VisualFCompiler(IntelVisualFCompiler): compiler_type = 'intelvem' description = 'Intel Visual Fortran Compiler for 64-bit apps' version_match = simple_version_match(start='Intel\\(R\\).*?64,') def get_flags_arch(self): return [] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='intel').get_version()) # File: numpy-main/numpy/distutils/fcompiler/lahey.py import os from numpy.distutils.fcompiler import FCompiler compilers = ['LaheyFCompiler'] class LaheyFCompiler(FCompiler): compiler_type = 'lahey' description = 'Lahey/Fujitsu Fortran 95 Compiler' version_pattern = 'Lahey/Fujitsu Fortran 95 Compiler Release (?P[^\\s*]*)' executables = {'version_cmd': ['', '--version'], 'compiler_f77': ['lf95', '--fix'], 'compiler_fix': ['lf95', '--fix'], 'compiler_f90': ['lf95'], 'linker_so': ['lf95', '-shared'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} module_dir_switch = None module_include_switch = None def get_flags_opt(self): return ['-O'] def get_flags_debug(self): return ['-g', '--chk', '--chkglobal'] def get_library_dirs(self): opt = [] d = os.environ.get('LAHEY') if d: opt.append(os.path.join(d, 'lib')) return opt def get_libraries(self): opt = [] opt.extend(['fj9f6', 'fj9i6', 'fj9ipp', 'fj9e6']) return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='lahey').get_version()) # File: numpy-main/numpy/distutils/fcompiler/mips.py from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler compilers = ['MIPSFCompiler'] class MIPSFCompiler(FCompiler): compiler_type = 'mips' description = 'MIPSpro Fortran Compiler' version_pattern = 'MIPSpro Compilers: Version (?P[^\\s*,]*)' executables = {'version_cmd': ['', '-version'], 'compiler_f77': ['f77', '-f77'], 'compiler_fix': ['f90', '-fixedform'], 'compiler_f90': ['f90'], 'linker_so': ['f90', '-shared'], 'archiver': ['ar', '-cr'], 'ranlib': None} module_dir_switch = None module_include_switch = None pic_flags = ['-KPIC'] def get_flags(self): return self.pic_flags + ['-n32'] def get_flags_opt(self): return ['-O3'] def get_flags_arch(self): opt = [] for a in '19 20 21 22_4k 22_5k 24 25 26 27 28 30 32_5k 32_10k'.split(): if getattr(cpu, 'is_IP%s' % a)(): opt.append('-TARG:platform=IP%s' % a) break return opt def get_flags_arch_f77(self): r = None if cpu.is_r10000(): r = 10000 elif cpu.is_r12000(): r = 12000 elif cpu.is_r8000(): r = 8000 elif cpu.is_r5000(): r = 5000 elif cpu.is_r4000(): r = 4000 if r is not None: return ['r%s' % r] return [] def get_flags_arch_f90(self): r = self.get_flags_arch_f77() if r: r[0] = '-' + r[0] return r if __name__ == '__main__': from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='mips').get_version()) # File: numpy-main/numpy/distutils/fcompiler/nag.py import sys import re from numpy.distutils.fcompiler import FCompiler compilers = ['NAGFCompiler', 'NAGFORCompiler'] class BaseNAGFCompiler(FCompiler): version_pattern = 'NAG.* Release (?P[^(\\s]*)' def version_match(self, version_string): m = re.search(self.version_pattern, version_string) if m: return m.group('version') else: return None def get_flags_linker_so(self): return ['-Wl,-shared'] def get_flags_opt(self): return ['-O4'] def get_flags_arch(self): return [] class NAGFCompiler(BaseNAGFCompiler): compiler_type = 'nag' description = 'NAGWare Fortran 95 Compiler' executables = {'version_cmd': ['', '-V'], 'compiler_f77': ['f95', '-fixed'], 'compiler_fix': ['f95', '-fixed'], 'compiler_f90': ['f95'], 'linker_so': [''], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} def get_flags_linker_so(self): if sys.platform == 'darwin': return ['-unsharedf95', '-Wl,-bundle,-flat_namespace,-undefined,suppress'] return BaseNAGFCompiler.get_flags_linker_so(self) def get_flags_arch(self): version = self.get_version() if version and version < '5.1': return ['-target=native'] else: return BaseNAGFCompiler.get_flags_arch(self) def get_flags_debug(self): return ['-g', '-gline', '-g90', '-nan', '-C'] class NAGFORCompiler(BaseNAGFCompiler): compiler_type = 'nagfor' description = 'NAG Fortran Compiler' executables = {'version_cmd': ['nagfor', '-V'], 'compiler_f77': ['nagfor', '-fixed'], 'compiler_fix': ['nagfor', '-fixed'], 'compiler_f90': ['nagfor'], 'linker_so': ['nagfor'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} def get_flags_linker_so(self): if sys.platform == 'darwin': return ['-unsharedrts', '-Wl,-bundle,-flat_namespace,-undefined,suppress'] return BaseNAGFCompiler.get_flags_linker_so(self) def get_flags_debug(self): version = self.get_version() if version and version > '6.1': return ['-g', '-u', '-nan', '-C=all', '-thread_safe', '-kind=unique', '-Warn=allocation', '-Warn=subnormal'] else: return ['-g', '-nan', '-C=all', '-u', '-thread_safe'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler compiler = customized_fcompiler(compiler='nagfor') print(compiler.get_version()) print(compiler.get_flags_debug()) # File: numpy-main/numpy/distutils/fcompiler/none.py from numpy.distutils.fcompiler import FCompiler from numpy.distutils import customized_fcompiler compilers = ['NoneFCompiler'] class NoneFCompiler(FCompiler): compiler_type = 'none' description = 'Fake Fortran compiler' executables = {'compiler_f77': None, 'compiler_f90': None, 'compiler_fix': None, 'linker_so': None, 'linker_exe': None, 'archiver': None, 'ranlib': None, 'version_cmd': None} def find_executables(self): pass if __name__ == '__main__': from distutils import log log.set_verbosity(2) print(customized_fcompiler(compiler='none').get_version()) # File: numpy-main/numpy/distutils/fcompiler/nv.py from numpy.distutils.fcompiler import FCompiler compilers = ['NVHPCFCompiler'] class NVHPCFCompiler(FCompiler): compiler_type = 'nv' description = 'NVIDIA HPC SDK' version_pattern = '\\s*(nvfortran|.+ \\(aka nvfortran\\)) (?P[\\d.-]+).*' executables = {'version_cmd': ['', '-V'], 'compiler_f77': ['nvfortran'], 'compiler_fix': ['nvfortran', '-Mfixed'], 'compiler_f90': ['nvfortran'], 'linker_so': [''], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} pic_flags = ['-fpic'] module_dir_switch = '-module ' module_include_switch = '-I' def get_flags(self): opt = ['-Minform=inform', '-Mnosecond_underscore'] return self.pic_flags + opt def get_flags_opt(self): return ['-fast'] def get_flags_debug(self): return ['-g'] def get_flags_linker_so(self): return ['-shared', '-fpic'] def runtime_library_dir_option(self, dir): return '-R%s' % dir if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='nv').get_version()) # File: numpy-main/numpy/distutils/fcompiler/pathf95.py from numpy.distutils.fcompiler import FCompiler compilers = ['PathScaleFCompiler'] class PathScaleFCompiler(FCompiler): compiler_type = 'pathf95' description = 'PathScale Fortran Compiler' version_pattern = 'PathScale\\(TM\\) Compiler Suite: Version (?P[\\d.]+)' executables = {'version_cmd': ['pathf95', '-version'], 'compiler_f77': ['pathf95', '-fixedform'], 'compiler_fix': ['pathf95', '-fixedform'], 'compiler_f90': ['pathf95'], 'linker_so': ['pathf95', '-shared'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} pic_flags = ['-fPIC'] module_dir_switch = '-module ' module_include_switch = '-I' def get_flags_opt(self): return ['-O3'] def get_flags_debug(self): return ['-g'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='pathf95').get_version()) # File: numpy-main/numpy/distutils/fcompiler/pg.py import sys from numpy.distutils.fcompiler import FCompiler from sys import platform from os.path import join, dirname, normpath compilers = ['PGroupFCompiler', 'PGroupFlangCompiler'] class PGroupFCompiler(FCompiler): compiler_type = 'pg' description = 'Portland Group Fortran Compiler' version_pattern = '\\s*pg(f77|f90|hpf|fortran) (?P[\\d.-]+).*' if platform == 'darwin': executables = {'version_cmd': ['', '-V'], 'compiler_f77': ['pgfortran', '-dynamiclib'], 'compiler_fix': ['pgfortran', '-Mfixed', '-dynamiclib'], 'compiler_f90': ['pgfortran', '-dynamiclib'], 'linker_so': ['libtool'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} pic_flags = [''] else: executables = {'version_cmd': ['', '-V'], 'compiler_f77': ['pgfortran'], 'compiler_fix': ['pgfortran', '-Mfixed'], 'compiler_f90': ['pgfortran'], 'linker_so': [''], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} pic_flags = ['-fpic'] module_dir_switch = '-module ' module_include_switch = '-I' def get_flags(self): opt = ['-Minform=inform', '-Mnosecond_underscore'] return self.pic_flags + opt def get_flags_opt(self): return ['-fast'] def get_flags_debug(self): return ['-g'] if platform == 'darwin': def get_flags_linker_so(self): return ['-dynamic', '-undefined', 'dynamic_lookup'] else: def get_flags_linker_so(self): return ['-shared', '-fpic'] def runtime_library_dir_option(self, dir): return '-R%s' % dir import functools class PGroupFlangCompiler(FCompiler): compiler_type = 'flang' description = 'Portland Group Fortran LLVM Compiler' version_pattern = '\\s*(flang|clang) version (?P[\\d.-]+).*' ar_exe = 'lib.exe' possible_executables = ['flang'] executables = {'version_cmd': ['', '--version'], 'compiler_f77': ['flang'], 'compiler_fix': ['flang'], 'compiler_f90': ['flang'], 'linker_so': [None], 'archiver': [ar_exe, '/verbose', '/OUT:'], 'ranlib': None} library_switch = '/OUT:' module_dir_switch = '-module ' def get_libraries(self): opt = FCompiler.get_libraries(self) opt.extend(['flang', 'flangrti', 'ompstub']) return opt @functools.lru_cache(maxsize=128) def get_library_dirs(self): opt = FCompiler.get_library_dirs(self) flang_dir = dirname(self.executables['compiler_f77'][0]) opt.append(normpath(join(flang_dir, '..', 'lib'))) return opt def get_flags(self): return [] def get_flags_free(self): return [] def get_flags_debug(self): return ['-g'] def get_flags_opt(self): return ['-O3'] def get_flags_arch(self): return [] def runtime_library_dir_option(self, dir): raise NotImplementedError if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler if 'flang' in sys.argv: print(customized_fcompiler(compiler='flang').get_version()) else: print(customized_fcompiler(compiler='pg').get_version()) # File: numpy-main/numpy/distutils/fcompiler/sun.py from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler compilers = ['SunFCompiler'] class SunFCompiler(FCompiler): compiler_type = 'sun' description = 'Sun or Forte Fortran 95 Compiler' version_match = simple_version_match(start='f9[05]: (Sun|Forte|WorkShop).*Fortran 95') executables = {'version_cmd': ['', '-V'], 'compiler_f77': ['f90'], 'compiler_fix': ['f90', '-fixed'], 'compiler_f90': ['f90'], 'linker_so': ['', '-Bdynamic', '-G'], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} module_dir_switch = '-moddir=' module_include_switch = '-M' pic_flags = ['-xcode=pic32'] def get_flags_f77(self): ret = ['-ftrap=%none'] if (self.get_version() or '') >= '7': ret.append('-f77') else: ret.append('-fixed') return ret def get_opt(self): return ['-fast', '-dalign'] def get_arch(self): return ['-xtarget=generic'] def get_libraries(self): opt = [] opt.extend(['fsu', 'sunmath', 'mvec']) return opt def runtime_library_dir_option(self, dir): return '-R%s' % dir if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='sun').get_version()) # File: numpy-main/numpy/distutils/fcompiler/vast.py import os from numpy.distutils.fcompiler.gnu import GnuFCompiler compilers = ['VastFCompiler'] class VastFCompiler(GnuFCompiler): compiler_type = 'vast' compiler_aliases = () description = 'Pacific-Sierra Research Fortran 90 Compiler' version_pattern = '\\s*Pacific-Sierra Research vf90 (Personal|Professional)\\s+(?P[^\\s]*)' object_switch = ' && function _mvfile { mv -v `basename $1` $1 ; } && _mvfile ' executables = {'version_cmd': ['vf90', '-v'], 'compiler_f77': ['g77'], 'compiler_fix': ['f90', '-Wv,-ya'], 'compiler_f90': ['f90'], 'linker_so': [''], 'archiver': ['ar', '-cr'], 'ranlib': ['ranlib']} module_dir_switch = None module_include_switch = None def find_executables(self): pass def get_version_cmd(self): f90 = self.compiler_f90[0] (d, b) = os.path.split(f90) vf90 = os.path.join(d, 'v' + b) return vf90 def get_flags_arch(self): vast_version = self.get_version() gnu = GnuFCompiler() gnu.customize(None) self.version = gnu.get_version() opt = GnuFCompiler.get_flags_arch(self) self.version = vast_version return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='vast').get_version()) # File: numpy-main/numpy/distutils/from_template.py """""" __all__ = ['process_str', 'process_file'] import os import sys import re routine_start_re = re.compile('(\\n|\\A)(( (\\$|\\*))|)\\s*(subroutine|function)\\b', re.I) routine_end_re = re.compile('\\n\\s*end\\s*(subroutine|function)\\b.*(\\n|\\Z)', re.I) function_start_re = re.compile('\\n (\\$|\\*)\\s*function\\b', re.I) def parse_structure(astr): spanlist = [] ind = 0 while True: m = routine_start_re.search(astr, ind) if m is None: break start = m.start() if function_start_re.match(astr, start, m.end()): while True: i = astr.rfind('\n', ind, start) if i == -1: break start = i if astr[i:i + 7] != '\n $': break start += 1 m = routine_end_re.search(astr, m.end()) ind = end = m and m.end() - 1 or len(astr) spanlist.append((start, end)) return spanlist template_re = re.compile('<\\s*(\\w[\\w\\d]*)\\s*>') named_re = re.compile('<\\s*(\\w[\\w\\d]*)\\s*=\\s*(.*?)\\s*>') list_re = re.compile('<\\s*((.*?))\\s*>') def find_repl_patterns(astr): reps = named_re.findall(astr) names = {} for rep in reps: name = rep[0].strip() or unique_key(names) repl = rep[1].replace('\\,', '@comma@') thelist = conv(repl) names[name] = thelist return names def find_and_remove_repl_patterns(astr): names = find_repl_patterns(astr) astr = re.subn(named_re, '', astr)[0] return (astr, names) item_re = re.compile('\\A\\\\(?P\\d+)\\Z') def conv(astr): b = astr.split(',') l = [x.strip() for x in b] for i in range(len(l)): m = item_re.match(l[i]) if m: j = int(m.group('index')) l[i] = l[j] return ','.join(l) def unique_key(adict): allkeys = list(adict.keys()) done = False n = 1 while not done: newkey = '__l%s' % n if newkey in allkeys: n += 1 else: done = True return newkey template_name_re = re.compile('\\A\\s*(\\w[\\w\\d]*)\\s*\\Z') def expand_sub(substr, names): substr = substr.replace('\\>', '@rightarrow@') substr = substr.replace('\\<', '@leftarrow@') lnames = find_repl_patterns(substr) substr = named_re.sub('<\\1>', substr) def listrepl(mobj): thelist = conv(mobj.group(1).replace('\\,', '@comma@')) if template_name_re.match(thelist): return '<%s>' % thelist name = None for key in lnames.keys(): if lnames[key] == thelist: name = key if name is None: name = unique_key(lnames) lnames[name] = thelist return '<%s>' % name substr = list_re.sub(listrepl, substr) numsubs = None base_rule = None rules = {} for r in template_re.findall(substr): if r not in rules: thelist = lnames.get(r, names.get(r, None)) if thelist is None: raise ValueError('No replicates found for <%s>' % r) if r not in names and (not thelist.startswith('_')): names[r] = thelist rule = [i.replace('@comma@', ',') for i in thelist.split(',')] num = len(rule) if numsubs is None: numsubs = num rules[r] = rule base_rule = r elif num == numsubs: rules[r] = rule else: print('Mismatch in number of replacements (base <%s=%s>) for <%s=%s>. Ignoring.' % (base_rule, ','.join(rules[base_rule]), r, thelist)) if not rules: return substr def namerepl(mobj): name = mobj.group(1) return rules.get(name, (k + 1) * [name])[k] newstr = '' for k in range(numsubs): newstr += template_re.sub(namerepl, substr) + '\n\n' newstr = newstr.replace('@rightarrow@', '>') newstr = newstr.replace('@leftarrow@', '<') return newstr def process_str(allstr): newstr = allstr writestr = '' struct = parse_structure(newstr) oldend = 0 names = {} names.update(_special_names) for sub in struct: (cleanedstr, defs) = find_and_remove_repl_patterns(newstr[oldend:sub[0]]) writestr += cleanedstr names.update(defs) writestr += expand_sub(newstr[sub[0]:sub[1]], names) oldend = sub[1] writestr += newstr[oldend:] return writestr include_src_re = re.compile('(\\n|\\A)\\s*include\\s*[\'\\"](?P[\\w\\d./\\\\]+\\.src)[\'\\"]', re.I) def resolve_includes(source): d = os.path.dirname(source) with open(source) as fid: lines = [] for line in fid: m = include_src_re.match(line) if m: fn = m.group('name') if not os.path.isabs(fn): fn = os.path.join(d, fn) if os.path.isfile(fn): lines.extend(resolve_includes(fn)) else: lines.append(line) else: lines.append(line) return lines def process_file(source): lines = resolve_includes(source) return process_str(''.join(lines)) _special_names = find_repl_patterns('\n<_c=s,d,c,z>\n<_t=real,double precision,complex,double complex>\n\n\n\n\n\n') def main(): try: file = sys.argv[1] except IndexError: fid = sys.stdin outfile = sys.stdout else: fid = open(file, 'r') (base, ext) = os.path.splitext(file) newname = base outfile = open(newname, 'w') allstr = fid.read() writestr = process_str(allstr) outfile.write(writestr) if __name__ == '__main__': main() # File: numpy-main/numpy/distutils/fujitsuccompiler.py from distutils.unixccompiler import UnixCCompiler class FujitsuCCompiler(UnixCCompiler): compiler_type = 'fujitsu' cc_exe = 'fcc' cxx_exe = 'FCC' def __init__(self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__(self, verbose, dry_run, force) cc_compiler = self.cc_exe cxx_compiler = self.cxx_exe self.set_executables(compiler=cc_compiler + ' -O3 -Nclang -fPIC', compiler_so=cc_compiler + ' -O3 -Nclang -fPIC', compiler_cxx=cxx_compiler + ' -O3 -Nclang -fPIC', linker_exe=cc_compiler + ' -lfj90i -lfj90f -lfjsrcinfo -lelf -shared', linker_so=cc_compiler + ' -lfj90i -lfj90f -lfjsrcinfo -lelf -shared') # File: numpy-main/numpy/distutils/intelccompiler.py import platform from distutils.unixccompiler import UnixCCompiler from numpy.distutils.exec_command import find_executable from numpy.distutils.ccompiler import simple_version_match if platform.system() == 'Windows': from numpy.distutils.msvc9compiler import MSVCCompiler class IntelCCompiler(UnixCCompiler): compiler_type = 'intel' cc_exe = 'icc' cc_args = 'fPIC' def __init__(self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__(self, verbose, dry_run, force) v = self.get_version() mpopt = 'openmp' if v and v < '15' else 'qopenmp' self.cc_exe = 'icc -fPIC -fp-model strict -O3 -fomit-frame-pointer -{}'.format(mpopt) compiler = self.cc_exe if platform.system() == 'Darwin': shared_flag = '-Wl,-undefined,dynamic_lookup' else: shared_flag = '-shared' self.set_executables(compiler=compiler, compiler_so=compiler, compiler_cxx=compiler, archiver='xiar' + ' cru', linker_exe=compiler + ' -shared-intel', linker_so=compiler + ' ' + shared_flag + ' -shared-intel') class IntelItaniumCCompiler(IntelCCompiler): compiler_type = 'intele' for cc_exe in map(find_executable, ['icc', 'ecc']): if cc_exe: break class IntelEM64TCCompiler(UnixCCompiler): compiler_type = 'intelem' cc_exe = 'icc -m64' cc_args = '-fPIC' def __init__(self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__(self, verbose, dry_run, force) v = self.get_version() mpopt = 'openmp' if v and v < '15' else 'qopenmp' self.cc_exe = 'icc -std=c99 -m64 -fPIC -fp-model strict -O3 -fomit-frame-pointer -{}'.format(mpopt) compiler = self.cc_exe if platform.system() == 'Darwin': shared_flag = '-Wl,-undefined,dynamic_lookup' else: shared_flag = '-shared' self.set_executables(compiler=compiler, compiler_so=compiler, compiler_cxx=compiler, archiver='xiar' + ' cru', linker_exe=compiler + ' -shared-intel', linker_so=compiler + ' ' + shared_flag + ' -shared-intel') if platform.system() == 'Windows': class IntelCCompilerW(MSVCCompiler): compiler_type = 'intelw' compiler_cxx = 'icl' def __init__(self, verbose=0, dry_run=0, force=0): MSVCCompiler.__init__(self, verbose, dry_run, force) version_match = simple_version_match(start='Intel\\(R\\).*?32,') self.__version = version_match def initialize(self, plat_name=None): MSVCCompiler.initialize(self, plat_name) self.cc = self.find_exe('icl.exe') self.lib = self.find_exe('xilib') self.linker = self.find_exe('xilink') self.compile_options = ['/nologo', '/O3', '/MD', '/W3', '/Qstd=c99'] self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/Qstd=c99', '/Z7', '/D_DEBUG'] class IntelEM64TCCompilerW(IntelCCompilerW): compiler_type = 'intelemw' def __init__(self, verbose=0, dry_run=0, force=0): MSVCCompiler.__init__(self, verbose, dry_run, force) version_match = simple_version_match(start='Intel\\(R\\).*?64,') self.__version = version_match # File: numpy-main/numpy/distutils/lib2def.py import re import sys import subprocess __doc__ = 'This module generates a DEF file from the symbols in\nan MSVC-compiled DLL import library. It correctly discriminates between\ndata and functions. The data is collected from the output of the program\nnm(1).\n\nUsage:\n python lib2def.py [libname.lib] [output.def]\nor\n python lib2def.py [libname.lib] > output.def\n\nlibname.lib defaults to python.lib and output.def defaults to stdout\n\nAuthor: Robert Kern \nLast Update: April 30, 1999\n' __version__ = '0.1a' py_ver = '%d%d' % tuple(sys.version_info[:2]) DEFAULT_NM = ['nm', '-Cs'] DEF_HEADER = 'LIBRARY python%s.dll\n;CODE PRELOAD MOVEABLE DISCARDABLE\n;DATA PRELOAD SINGLE\n\nEXPORTS\n' % py_ver FUNC_RE = re.compile('^(.*) in python%s\\.dll' % py_ver, re.MULTILINE) DATA_RE = re.compile('^_imp__(.*) in python%s\\.dll' % py_ver, re.MULTILINE) def parse_cmd(): if len(sys.argv) == 3: if sys.argv[1][-4:] == '.lib' and sys.argv[2][-4:] == '.def': (libfile, deffile) = sys.argv[1:] elif sys.argv[1][-4:] == '.def' and sys.argv[2][-4:] == '.lib': (deffile, libfile) = sys.argv[1:] else: print("I'm assuming that your first argument is the library") print('and the second is the DEF file.') elif len(sys.argv) == 2: if sys.argv[1][-4:] == '.def': deffile = sys.argv[1] libfile = 'python%s.lib' % py_ver elif sys.argv[1][-4:] == '.lib': deffile = None libfile = sys.argv[1] else: libfile = 'python%s.lib' % py_ver deffile = None return (libfile, deffile) def getnm(nm_cmd=['nm', '-Cs', 'python%s.lib' % py_ver], shell=True): p = subprocess.Popen(nm_cmd, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) (nm_output, nm_err) = p.communicate() if p.returncode != 0: raise RuntimeError('failed to run "%s": "%s"' % (' '.join(nm_cmd), nm_err)) return nm_output def parse_nm(nm_output): data = DATA_RE.findall(nm_output) func = FUNC_RE.findall(nm_output) flist = [] for sym in data: if sym in func and (sym[:2] == 'Py' or sym[:3] == '_Py' or sym[:4] == 'init'): flist.append(sym) dlist = [] for sym in data: if sym not in flist and (sym[:2] == 'Py' or sym[:3] == '_Py'): dlist.append(sym) dlist.sort() flist.sort() return (dlist, flist) def output_def(dlist, flist, header, file=sys.stdout): for data_sym in dlist: header = header + '\t%s DATA\n' % data_sym header = header + '\n' for func_sym in flist: header = header + '\t%s\n' % func_sym file.write(header) if __name__ == '__main__': (libfile, deffile) = parse_cmd() if deffile is None: deffile = sys.stdout else: deffile = open(deffile, 'w') nm_cmd = DEFAULT_NM + [str(libfile)] nm_output = getnm(nm_cmd, shell=False) (dlist, flist) = parse_nm(nm_output) output_def(dlist, flist, DEF_HEADER, deffile) # File: numpy-main/numpy/distutils/line_endings.py """""" import os import re import sys def dos2unix(file): if os.path.isdir(file): print(file, 'Directory!') return with open(file, 'rb') as fp: data = fp.read() if '\x00' in data: print(file, 'Binary!') return newdata = re.sub('\r\n', '\n', data) if newdata != data: print('dos2unix:', file) with open(file, 'wb') as f: f.write(newdata) return file else: print(file, 'ok') def dos2unix_one_dir(modified_files, dir_name, file_names): for file in file_names: full_path = os.path.join(dir_name, file) file = dos2unix(full_path) if file is not None: modified_files.append(file) def dos2unix_dir(dir_name): modified_files = [] os.path.walk(dir_name, dos2unix_one_dir, modified_files) return modified_files def unix2dos(file): if os.path.isdir(file): print(file, 'Directory!') return with open(file, 'rb') as fp: data = fp.read() if '\x00' in data: print(file, 'Binary!') return newdata = re.sub('\r\n', '\n', data) newdata = re.sub('\n', '\r\n', newdata) if newdata != data: print('unix2dos:', file) with open(file, 'wb') as f: f.write(newdata) return file else: print(file, 'ok') def unix2dos_one_dir(modified_files, dir_name, file_names): for file in file_names: full_path = os.path.join(dir_name, file) unix2dos(full_path) if file is not None: modified_files.append(file) def unix2dos_dir(dir_name): modified_files = [] os.path.walk(dir_name, unix2dos_one_dir, modified_files) return modified_files if __name__ == '__main__': dos2unix_dir(sys.argv[1]) # File: numpy-main/numpy/distutils/log.py import sys from distutils.log import * from distutils.log import Log as old_Log from distutils.log import _global_log from numpy.distutils.misc_util import red_text, default_text, cyan_text, green_text, is_sequence, is_string def _fix_args(args, flag=1): if is_string(args): return args.replace('%', '%%') if flag and is_sequence(args): return tuple([_fix_args(a, flag=0) for a in args]) return args class Log(old_Log): def _log(self, level, msg, args): if level >= self.threshold: if args: msg = msg % _fix_args(args) if 0: if msg.startswith('copying ') and msg.find(' -> ') != -1: return if msg.startswith('byte-compiling '): return print(_global_color_map[level](msg)) sys.stdout.flush() def good(self, msg, *args): if WARN >= self.threshold: if args: print(green_text(msg % _fix_args(args))) else: print(green_text(msg)) sys.stdout.flush() _global_log.__class__ = Log good = _global_log.good def set_threshold(level, force=False): prev_level = _global_log.threshold if prev_level > DEBUG or force: _global_log.threshold = level if level <= DEBUG: info('set_threshold: setting threshold to DEBUG level, it can be changed only with force argument') else: info('set_threshold: not changing threshold from DEBUG level %s to %s' % (prev_level, level)) return prev_level def get_threshold(): return _global_log.threshold def set_verbosity(v, force=False): prev_level = _global_log.threshold if v < 0: set_threshold(ERROR, force) elif v == 0: set_threshold(WARN, force) elif v == 1: set_threshold(INFO, force) elif v >= 2: set_threshold(DEBUG, force) return {FATAL: -2, ERROR: -1, WARN: 0, INFO: 1, DEBUG: 2}.get(prev_level, 1) _global_color_map = {DEBUG: cyan_text, INFO: default_text, WARN: red_text, ERROR: red_text, FATAL: red_text} set_verbosity(0, force=True) _error = error _warn = warn _info = info _debug = debug def error(msg, *a, **kw): _error(f'ERROR: {msg}', *a, **kw) def warn(msg, *a, **kw): _warn(f'WARN: {msg}', *a, **kw) def info(msg, *a, **kw): _info(f'INFO: {msg}', *a, **kw) def debug(msg, *a, **kw): _debug(f'DEBUG: {msg}', *a, **kw) # File: numpy-main/numpy/distutils/mingw32ccompiler.py """""" import os import sys import subprocess import re import textwrap import numpy.distutils.ccompiler from numpy.distutils import log import distutils.cygwinccompiler from distutils.unixccompiler import UnixCCompiler from distutils.msvccompiler import get_build_version as get_build_msvc_version from distutils.errors import UnknownFileError from numpy.distutils.misc_util import msvc_runtime_library, msvc_runtime_version, msvc_runtime_major, get_build_architecture def get_msvcr_replacement(): msvcr = msvc_runtime_library() return [] if msvcr is None else [msvcr] _START = re.compile('\\[Ordinal/Name Pointer\\] Table') _TABLE = re.compile('^\\s+\\[([\\s*[0-9]*)\\] ([a-zA-Z0-9_]*)') class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler): compiler_type = 'mingw32' def __init__(self, verbose=0, dry_run=0, force=0): distutils.cygwinccompiler.CygwinCCompiler.__init__(self, verbose, dry_run, force) build_import_library() msvcr_success = build_msvcr_library() msvcr_dbg_success = build_msvcr_library(debug=True) if msvcr_success or msvcr_dbg_success: self.define_macro('NPY_MINGW_USE_CUSTOM_MSVCR') msvcr_version = msvc_runtime_version() if msvcr_version: self.define_macro('__MSVCRT_VERSION__', '0x%04i' % msvcr_version) if get_build_architecture() == 'AMD64': self.set_executables(compiler='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall', compiler_so='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall -Wstrict-prototypes', linker_exe='gcc -g', linker_so='gcc -g -shared') else: self.set_executables(compiler='gcc -O2 -Wall', compiler_so='gcc -O2 -Wall -Wstrict-prototypes', linker_exe='g++ ', linker_so='g++ -shared') self.compiler_cxx = ['g++'] return def link(self, target_desc, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): runtime_library = msvc_runtime_library() if runtime_library: if not libraries: libraries = [] libraries.append(runtime_library) args = (self, target_desc, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, None, debug, extra_preargs, extra_postargs, build_temp, target_lang) func = UnixCCompiler.link func(*args[:func.__code__.co_argcount]) return def object_filenames(self, source_filenames, strip_dir=0, output_dir=''): if output_dir is None: output_dir = '' obj_names = [] for src_name in source_filenames: (base, ext) = os.path.splitext(os.path.normcase(src_name)) (drv, base) = os.path.splitdrive(base) if drv: base = base[1:] if ext not in self.src_extensions + ['.rc', '.res']: raise UnknownFileError("unknown file type '%s' (from '%s')" % (ext, src_name)) if strip_dir: base = os.path.basename(base) if ext == '.res' or ext == '.rc': obj_names.append(os.path.join(output_dir, base + ext + self.obj_extension)) else: obj_names.append(os.path.join(output_dir, base + self.obj_extension)) return obj_names def find_python_dll(): stems = [sys.prefix] if sys.base_prefix != sys.prefix: stems.append(sys.base_prefix) sub_dirs = ['', 'lib', 'bin'] lib_dirs = [] for stem in stems: for folder in sub_dirs: lib_dirs.append(os.path.join(stem, folder)) if 'SYSTEMROOT' in os.environ: lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'System32')) (major_version, minor_version) = tuple(sys.version_info[:2]) implementation = sys.implementation.name if implementation == 'cpython': dllname = f'python{major_version}{minor_version}.dll' elif implementation == 'pypy': dllname = f'libpypy{major_version}.{minor_version}-c.dll' else: dllname = f'Unknown platform {implementation}' print('Looking for %s' % dllname) for folder in lib_dirs: dll = os.path.join(folder, dllname) if os.path.exists(dll): return dll raise ValueError('%s not found in %s' % (dllname, lib_dirs)) def dump_table(dll): st = subprocess.check_output(['objdump.exe', '-p', dll]) return st.split(b'\n') def generate_def(dll, dfile): dump = dump_table(dll) for i in range(len(dump)): if _START.match(dump[i].decode()): break else: raise ValueError('Symbol table not found') syms = [] for j in range(i + 1, len(dump)): m = _TABLE.match(dump[j].decode()) if m: syms.append((int(m.group(1).strip()), m.group(2))) else: break if len(syms) == 0: log.warn('No symbols found in %s' % dll) with open(dfile, 'w') as d: d.write('LIBRARY %s\n' % os.path.basename(dll)) d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n') d.write(';DATA PRELOAD SINGLE\n') d.write('\nEXPORTS\n') for s in syms: d.write('%s\n' % s[1]) def find_dll(dll_name): arch = {'AMD64': 'amd64', 'Intel': 'x86'}[get_build_architecture()] def _find_dll_in_winsxs(dll_name): winsxs_path = os.path.join(os.environ.get('WINDIR', 'C:\\WINDOWS'), 'winsxs') if not os.path.exists(winsxs_path): return None for (root, dirs, files) in os.walk(winsxs_path): if dll_name in files and arch in root: return os.path.join(root, dll_name) return None def _find_dll_in_path(dll_name): for path in [sys.prefix] + os.environ['PATH'].split(';'): filepath = os.path.join(path, dll_name) if os.path.exists(filepath): return os.path.abspath(filepath) return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name) def build_msvcr_library(debug=False): if os.name != 'nt': return False msvcr_ver = msvc_runtime_major() if msvcr_ver is None: log.debug('Skip building import library: Runtime is not compiled with MSVC') return False if msvcr_ver < 80: log.debug('Skip building msvcr library: custom functionality not present') return False msvcr_name = msvc_runtime_library() if debug: msvcr_name += 'd' out_name = 'lib%s.a' % msvcr_name out_file = os.path.join(sys.prefix, 'libs', out_name) if os.path.isfile(out_file): log.debug('Skip building msvcr library: "%s" exists' % (out_file,)) return True msvcr_dll_name = msvcr_name + '.dll' dll_file = find_dll(msvcr_dll_name) if not dll_file: log.warn('Cannot build msvcr library: "%s" not found' % msvcr_dll_name) return False def_name = 'lib%s.def' % msvcr_name def_file = os.path.join(sys.prefix, 'libs', def_name) log.info('Building msvcr library: "%s" (from %s)' % (out_file, dll_file)) generate_def(dll_file, def_file) cmd = ['dlltool', '-d', def_file, '-l', out_file] retcode = subprocess.call(cmd) os.remove(def_file) return not retcode def build_import_library(): if os.name != 'nt': return arch = get_build_architecture() if arch == 'AMD64': return _build_import_library_amd64() elif arch == 'Intel': return _build_import_library_x86() else: raise ValueError('Unhandled arch %s' % arch) def _check_for_import_lib(): (major_version, minor_version) = tuple(sys.version_info[:2]) patterns = ['libpython%d%d.a', 'libpython%d%d.dll.a', 'libpython%d.%d.dll.a'] stems = [sys.prefix] if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix: stems.append(sys.base_prefix) elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix: stems.append(sys.real_prefix) sub_dirs = ['libs', 'lib'] candidates = [] for pat in patterns: filename = pat % (major_version, minor_version) for stem_dir in stems: for folder in sub_dirs: candidates.append(os.path.join(stem_dir, folder, filename)) for fullname in candidates: if os.path.isfile(fullname): return (True, fullname) return (False, candidates[0]) def _build_import_library_amd64(): (out_exists, out_file) = _check_for_import_lib() if out_exists: log.debug('Skip building import library: "%s" exists', out_file) return dll_file = find_python_dll() log.info('Building import library (arch=AMD64): "%s" (from %s)' % (out_file, dll_file)) def_name = 'python%d%d.def' % tuple(sys.version_info[:2]) def_file = os.path.join(sys.prefix, 'libs', def_name) generate_def(dll_file, def_file) cmd = ['dlltool', '-d', def_file, '-l', out_file] subprocess.check_call(cmd) def _build_import_library_x86(): (out_exists, out_file) = _check_for_import_lib() if out_exists: log.debug('Skip building import library: "%s" exists', out_file) return lib_name = 'python%d%d.lib' % tuple(sys.version_info[:2]) lib_file = os.path.join(sys.prefix, 'libs', lib_name) if not os.path.isfile(lib_file): if hasattr(sys, 'base_prefix'): base_lib = os.path.join(sys.base_prefix, 'libs', lib_name) elif hasattr(sys, 'real_prefix'): base_lib = os.path.join(sys.real_prefix, 'libs', lib_name) else: base_lib = '' if os.path.isfile(base_lib): lib_file = base_lib else: log.warn('Cannot build import library: "%s" not found', lib_file) return log.info('Building import library (ARCH=x86): "%s"', out_file) from numpy.distutils import lib2def def_name = 'python%d%d.def' % tuple(sys.version_info[:2]) def_file = os.path.join(sys.prefix, 'libs', def_name) nm_output = lib2def.getnm(lib2def.DEFAULT_NM + [lib_file], shell=False) (dlist, flist) = lib2def.parse_nm(nm_output) with open(def_file, 'w') as fid: lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, fid) dll_name = find_python_dll() cmd = ['dlltool', '--dllname', dll_name, '--def', def_file, '--output-lib', out_file] status = subprocess.check_output(cmd) if status: log.warn('Failed to build import library for gcc. Linking will fail.') return _MSVCRVER_TO_FULLVER = {} if sys.platform == 'win32': try: import msvcrt _MSVCRVER_TO_FULLVER['80'] = '8.0.50727.42' _MSVCRVER_TO_FULLVER['90'] = '9.0.21022.8' _MSVCRVER_TO_FULLVER['100'] = '10.0.30319.460' crt_ver = getattr(msvcrt, 'CRT_ASSEMBLY_VERSION', None) if crt_ver is not None: (maj, min) = re.match('(\\d+)\\.(\\d)', crt_ver).groups() _MSVCRVER_TO_FULLVER[maj + min] = crt_ver del maj, min del crt_ver except ImportError: log.warn('Cannot import msvcrt: using manifest will not be possible') def msvc_manifest_xml(maj, min): try: fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)] except KeyError: raise ValueError('Version %d,%d of MSVCRT not supported yet' % (maj, min)) from None template = textwrap.dedent(' \n \n \n \n \n \n \n \n \n \n \n \n \n ') return template % {'fullver': fullver, 'maj': maj, 'min': min} def manifest_rc(name, type='dll'): if type == 'dll': rctype = 2 elif type == 'exe': rctype = 1 else: raise ValueError('Type %s not supported' % type) return '#include "winuser.h"\n%d RT_MANIFEST %s' % (rctype, name) def check_embedded_msvcr_match_linked(msver): maj = msvc_runtime_major() if maj: if not maj == int(msver): raise ValueError('Discrepancy between linked msvcr (%d) and the one about to be embedded (%d)' % (int(msver), maj)) def configtest_name(config): base = os.path.basename(config._gen_temp_sourcefile('yo', [], 'c')) return os.path.splitext(base)[0] def manifest_name(config): root = configtest_name(config) exext = config.compiler.exe_extension return root + exext + '.manifest' def rc_name(config): root = configtest_name(config) return root + '.rc' def generate_manifest(config): msver = get_build_msvc_version() if msver is not None: if msver >= 8: check_embedded_msvcr_match_linked(msver) (ma_str, mi_str) = str(msver).split('.') manxml = msvc_manifest_xml(int(ma_str), int(mi_str)) with open(manifest_name(config), 'w') as man: config.temp_files.append(manifest_name(config)) man.write(manxml) # File: numpy-main/numpy/distutils/misc_util.py import os import re import sys import copy import glob import atexit import tempfile import subprocess import shutil import multiprocessing import textwrap import importlib.util from threading import local as tlocal from functools import reduce import distutils from distutils.errors import DistutilsError _tdata = tlocal() _tmpdirs = [] def clean_up_temporary_directory(): if _tmpdirs is not None: for d in _tmpdirs: try: shutil.rmtree(d) except OSError: pass atexit.register(clean_up_temporary_directory) __all__ = ['Configuration', 'get_numpy_include_dirs', 'default_config_dict', 'dict_append', 'appendpath', 'generate_config_py', 'get_cmd', 'allpath', 'get_mathlibs', 'terminal_has_colors', 'red_text', 'green_text', 'yellow_text', 'blue_text', 'cyan_text', 'cyg2win32', 'mingw32', 'all_strings', 'has_f_sources', 'has_cxx_sources', 'filter_sources', 'get_dependencies', 'is_local_src_dir', 'get_ext_source_files', 'get_script_files', 'get_lib_source_files', 'get_data_files', 'dot_join', 'get_frame', 'minrelpath', 'njoin', 'is_sequence', 'is_string', 'as_list', 'gpaths', 'get_language', 'get_build_architecture', 'get_info', 'get_pkg_info', 'get_num_build_jobs', 'sanitize_cxx_flags', 'exec_mod_from_location'] class InstallableLib: def __init__(self, name, build_info, target_dir): self.name = name self.build_info = build_info self.target_dir = target_dir def get_num_build_jobs(): from numpy.distutils.core import get_distribution try: cpu_count = len(os.sched_getaffinity(0)) except AttributeError: cpu_count = multiprocessing.cpu_count() cpu_count = min(cpu_count, 8) envjobs = int(os.environ.get('NPY_NUM_BUILD_JOBS', cpu_count)) dist = get_distribution() if dist is None: return envjobs cmdattr = (getattr(dist.get_command_obj('build'), 'parallel', None), getattr(dist.get_command_obj('build_ext'), 'parallel', None), getattr(dist.get_command_obj('build_clib'), 'parallel', None)) if all((x is None for x in cmdattr)): return envjobs else: return max((x for x in cmdattr if x is not None)) def quote_args(args): import warnings warnings.warn('"quote_args" is deprecated.', DeprecationWarning, stacklevel=2) args = list(args) for i in range(len(args)): a = args[i] if ' ' in a and a[0] not in '"\'': args[i] = '"%s"' % a return args def allpath(name): split = name.split('/') return os.path.join(*split) def rel_path(path, parent_path): pd = os.path.realpath(os.path.abspath(parent_path)) apath = os.path.realpath(os.path.abspath(path)) if len(apath) < len(pd): return path if apath == pd: return '' if pd == apath[:len(pd)]: assert apath[len(pd)] in [os.sep], repr((path, apath[len(pd)])) path = apath[len(pd) + 1:] return path def get_path_from_frame(frame, parent_path=None): try: caller_file = eval('__file__', frame.f_globals, frame.f_locals) d = os.path.dirname(os.path.abspath(caller_file)) except NameError: caller_name = eval('__name__', frame.f_globals, frame.f_locals) __import__(caller_name) mod = sys.modules[caller_name] if hasattr(mod, '__file__'): d = os.path.dirname(os.path.abspath(mod.__file__)) else: d = os.path.abspath('.') if parent_path is not None: d = rel_path(d, parent_path) return d or '.' def njoin(*path): paths = [] for p in path: if is_sequence(p): paths.append(njoin(*p)) else: assert is_string(p) paths.append(p) path = paths if not path: joined = '' else: joined = os.path.join(*path) if os.path.sep != '/': joined = joined.replace('/', os.path.sep) return minrelpath(joined) def get_mathlibs(path=None): if path is not None: config_file = os.path.join(path, '_numpyconfig.h') else: dirs = get_numpy_include_dirs() for path in dirs: fn = os.path.join(path, '_numpyconfig.h') if os.path.exists(fn): config_file = fn break else: raise DistutilsError('_numpyconfig.h not found in numpy include dirs %r' % (dirs,)) with open(config_file) as fid: mathlibs = [] s = '#define MATHLIB' for line in fid: if line.startswith(s): value = line[len(s):].strip() if value: mathlibs.extend(value.split(',')) return mathlibs def minrelpath(path): if not is_string(path): return path if '.' not in path: return path l = path.split(os.sep) while l: try: i = l.index('.', 1) except ValueError: break del l[i] j = 1 while l: try: i = l.index('..', j) except ValueError: break if l[i - 1] == '..': j += 1 else: del l[i], l[i - 1] j = 1 if not l: return '' return os.sep.join(l) def sorted_glob(fileglob): return sorted(glob.glob(fileglob)) def _fix_paths(paths, local_path, include_non_existing): assert is_sequence(paths), repr(type(paths)) new_paths = [] assert not is_string(paths), repr(paths) for n in paths: if is_string(n): if '*' in n or '?' in n: p = sorted_glob(n) p2 = sorted_glob(njoin(local_path, n)) if p2: new_paths.extend(p2) elif p: new_paths.extend(p) else: if include_non_existing: new_paths.append(n) print('could not resolve pattern in %r: %r' % (local_path, n)) else: n2 = njoin(local_path, n) if os.path.exists(n2): new_paths.append(n2) else: if os.path.exists(n): new_paths.append(n) elif include_non_existing: new_paths.append(n) if not os.path.exists(n): print('non-existing path in %r: %r' % (local_path, n)) elif is_sequence(n): new_paths.extend(_fix_paths(n, local_path, include_non_existing)) else: new_paths.append(n) return [minrelpath(p) for p in new_paths] def gpaths(paths, local_path='', include_non_existing=True): if is_string(paths): paths = (paths,) return _fix_paths(paths, local_path, include_non_existing) def make_temp_file(suffix='', prefix='', text=True): if not hasattr(_tdata, 'tempdir'): _tdata.tempdir = tempfile.mkdtemp() _tmpdirs.append(_tdata.tempdir) (fid, name) = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=_tdata.tempdir, text=text) fo = os.fdopen(fid, 'w') return (fo, name) def terminal_has_colors(): if sys.platform == 'cygwin' and 'USE_COLOR' not in os.environ: return 0 if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty(): try: import curses curses.setupterm() if curses.tigetnum('colors') >= 0 and curses.tigetnum('pairs') >= 0 and (curses.tigetstr('setf') is not None and curses.tigetstr('setb') is not None or (curses.tigetstr('setaf') is not None and curses.tigetstr('setab') is not None) or curses.tigetstr('scp') is not None): return 1 except Exception: pass return 0 if terminal_has_colors(): _colour_codes = dict(black=0, red=1, green=2, yellow=3, blue=4, magenta=5, cyan=6, white=7, default=9) def colour_text(s, fg=None, bg=None, bold=False): seq = [] if bold: seq.append('1') if fg: fgcode = 30 + _colour_codes.get(fg.lower(), 0) seq.append(str(fgcode)) if bg: bgcode = 40 + _colour_codes.get(bg.lower(), 7) seq.append(str(bgcode)) if seq: return '\x1b[%sm%s\x1b[0m' % (';'.join(seq), s) else: return s else: def colour_text(s, fg=None, bg=None): return s def default_text(s): return colour_text(s, 'default') def red_text(s): return colour_text(s, 'red') def green_text(s): return colour_text(s, 'green') def yellow_text(s): return colour_text(s, 'yellow') def cyan_text(s): return colour_text(s, 'cyan') def blue_text(s): return colour_text(s, 'blue') def cyg2win32(path: str) -> str: if sys.platform != 'cygwin': return path return subprocess.check_output(['/usr/bin/cygpath', '--windows', path], text=True) def mingw32(): if sys.platform == 'win32': if os.environ.get('OSTYPE', '') == 'msys': return True if os.environ.get('MSYSTEM', '') == 'MINGW32': return True return False def msvc_runtime_version(): msc_pos = sys.version.find('MSC v.') if msc_pos != -1: msc_ver = int(sys.version[msc_pos + 6:msc_pos + 10]) else: msc_ver = None return msc_ver def msvc_runtime_library(): ver = msvc_runtime_major() if ver: if ver < 140: return 'msvcr%i' % ver else: return 'vcruntime%i' % ver else: return None def msvc_runtime_major(): major = {1300: 70, 1310: 71, 1400: 80, 1500: 90, 1600: 100, 1900: 140}.get(msvc_runtime_version(), None) return major cxx_ext_match = re.compile('.*\\.(cpp|cxx|cc)\\Z', re.I).match fortran_ext_match = re.compile('.*\\.(f90|f95|f77|for|ftn|f)\\Z', re.I).match f90_ext_match = re.compile('.*\\.(f90|f95)\\Z', re.I).match f90_module_name_match = re.compile('\\s*module\\s*(?P[\\w_]+)', re.I).match def _get_f90_modules(source): if not f90_ext_match(source): return [] modules = [] with open(source) as f: for line in f: m = f90_module_name_match(line) if m: name = m.group('name') modules.append(name) return modules def is_string(s): return isinstance(s, str) def all_strings(lst): return all((is_string(item) for item in lst)) def is_sequence(seq): if is_string(seq): return False try: len(seq) except Exception: return False return True def is_glob_pattern(s): return is_string(s) and ('*' in s or '?' in s) def as_list(seq): if is_sequence(seq): return list(seq) else: return [seq] def get_language(sources): language = None for source in sources: if isinstance(source, str): if f90_ext_match(source): language = 'f90' break elif fortran_ext_match(source): language = 'f77' return language def has_f_sources(sources): return any((fortran_ext_match(source) for source in sources)) def has_cxx_sources(sources): return any((cxx_ext_match(source) for source in sources)) def filter_sources(sources): c_sources = [] cxx_sources = [] f_sources = [] fmodule_sources = [] for source in sources: if fortran_ext_match(source): modules = _get_f90_modules(source) if modules: fmodule_sources.append(source) else: f_sources.append(source) elif cxx_ext_match(source): cxx_sources.append(source) else: c_sources.append(source) return (c_sources, cxx_sources, f_sources, fmodule_sources) def _get_headers(directory_list): headers = [] for d in directory_list: head = sorted_glob(os.path.join(d, '*.h')) headers.extend(head) return headers def _get_directories(list_of_sources): direcs = [] for f in list_of_sources: d = os.path.split(f) if d[0] != '' and (not d[0] in direcs): direcs.append(d[0]) return direcs def _commandline_dep_string(cc_args, extra_postargs, pp_opts): cmdline = 'commandline: ' cmdline += ' '.join(cc_args) cmdline += ' '.join(extra_postargs) cmdline += ' '.join(pp_opts) + '\n' return cmdline def get_dependencies(sources): return _get_headers(_get_directories(sources)) def is_local_src_dir(directory): if not is_string(directory): return False abs_dir = os.path.abspath(directory) c = os.path.commonprefix([os.getcwd(), abs_dir]) new_dir = abs_dir[len(c):].split(os.sep) if new_dir and (not new_dir[0]): new_dir = new_dir[1:] if new_dir and new_dir[0] == 'build': return False new_dir = os.sep.join(new_dir) return os.path.isdir(new_dir) def general_source_files(top_path): pruned_directories = {'CVS': 1, '.svn': 1, 'build': 1} prune_file_pat = re.compile('(?:[~#]|\\.py[co]|\\.o)$') for (dirpath, dirnames, filenames) in os.walk(top_path, topdown=True): pruned = [d for d in dirnames if d not in pruned_directories] dirnames[:] = pruned for f in filenames: if not prune_file_pat.search(f): yield os.path.join(dirpath, f) def general_source_directories_files(top_path): pruned_directories = ['CVS', '.svn', 'build'] prune_file_pat = re.compile('(?:[~#]|\\.py[co]|\\.o)$') for (dirpath, dirnames, filenames) in os.walk(top_path, topdown=True): pruned = [d for d in dirnames if d not in pruned_directories] dirnames[:] = pruned for d in dirnames: dpath = os.path.join(dirpath, d) rpath = rel_path(dpath, top_path) files = [] for f in os.listdir(dpath): fn = os.path.join(dpath, f) if os.path.isfile(fn) and (not prune_file_pat.search(fn)): files.append(fn) yield (rpath, files) dpath = top_path rpath = rel_path(dpath, top_path) filenames = [os.path.join(dpath, f) for f in os.listdir(dpath) if not prune_file_pat.search(f)] files = [f for f in filenames if os.path.isfile(f)] yield (rpath, files) def get_ext_source_files(ext): filenames = [] sources = [_m for _m in ext.sources if is_string(_m)] filenames.extend(sources) filenames.extend(get_dependencies(sources)) for d in ext.depends: if is_local_src_dir(d): filenames.extend(list(general_source_files(d))) elif os.path.isfile(d): filenames.append(d) return filenames def get_script_files(scripts): scripts = [_m for _m in scripts if is_string(_m)] return scripts def get_lib_source_files(lib): filenames = [] sources = lib[1].get('sources', []) sources = [_m for _m in sources if is_string(_m)] filenames.extend(sources) filenames.extend(get_dependencies(sources)) depends = lib[1].get('depends', []) for d in depends: if is_local_src_dir(d): filenames.extend(list(general_source_files(d))) elif os.path.isfile(d): filenames.append(d) return filenames def get_shared_lib_extension(is_python_ext=False): confvars = distutils.sysconfig.get_config_vars() so_ext = confvars.get('EXT_SUFFIX', '') if not is_python_ext: if sys.platform.startswith('linux') or sys.platform.startswith('gnukfreebsd'): so_ext = '.so' elif sys.platform.startswith('darwin'): so_ext = '.dylib' elif sys.platform.startswith('win'): so_ext = '.dll' elif 'SOABI' in confvars: so_ext = so_ext.replace('.' + confvars.get('SOABI'), '', 1) return so_ext def get_data_files(data): if is_string(data): return [data] sources = data[1] filenames = [] for s in sources: if hasattr(s, '__call__'): continue if is_local_src_dir(s): filenames.extend(list(general_source_files(s))) elif is_string(s): if os.path.isfile(s): filenames.append(s) else: print('Not existing data file:', s) else: raise TypeError(repr(s)) return filenames def dot_join(*args): return '.'.join([a for a in args if a]) def get_frame(level=0): try: return sys._getframe(level + 1) except AttributeError: frame = sys.exc_info()[2].tb_frame for _ in range(level + 1): frame = frame.f_back return frame class Configuration: _list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs', 'libraries', 'headers', 'scripts', 'py_modules', 'installed_libraries', 'define_macros'] _dict_keys = ['package_dir', 'installed_pkg_config'] _extra_keys = ['name', 'version'] numpy_include_dirs = [] def __init__(self, package_name=None, parent_name=None, top_path=None, package_path=None, caller_level=1, setup_name='setup.py', **attrs): self.name = dot_join(parent_name, package_name) self.version = None caller_frame = get_frame(caller_level) self.local_path = get_path_from_frame(caller_frame, top_path) if top_path is None: top_path = self.local_path self.local_path = '' if package_path is None: package_path = self.local_path elif os.path.isdir(njoin(self.local_path, package_path)): package_path = njoin(self.local_path, package_path) if not os.path.isdir(package_path or '.'): raise ValueError('%r is not a directory' % (package_path,)) self.top_path = top_path self.package_path = package_path self.path_in_package = os.path.join(*self.name.split('.')) self.list_keys = self._list_keys[:] self.dict_keys = self._dict_keys[:] for n in self.list_keys: v = copy.copy(attrs.get(n, [])) setattr(self, n, as_list(v)) for n in self.dict_keys: v = copy.copy(attrs.get(n, {})) setattr(self, n, v) known_keys = self.list_keys + self.dict_keys self.extra_keys = self._extra_keys[:] for n in attrs.keys(): if n in known_keys: continue a = attrs[n] setattr(self, n, a) if isinstance(a, list): self.list_keys.append(n) elif isinstance(a, dict): self.dict_keys.append(n) else: self.extra_keys.append(n) if os.path.exists(njoin(package_path, '__init__.py')): self.packages.append(self.name) self.package_dir[self.name] = package_path self.options = dict(ignore_setup_xxx_py=False, assume_default_configuration=False, delegate_options_to_subpackages=False, quiet=False) caller_instance = None for i in range(1, 3): try: f = get_frame(i) except ValueError: break try: caller_instance = eval('self', f.f_globals, f.f_locals) break except NameError: pass if isinstance(caller_instance, self.__class__): if caller_instance.options['delegate_options_to_subpackages']: self.set_options(**caller_instance.options) self.setup_name = setup_name def todict(self): self._optimize_data_files() d = {} known_keys = self.list_keys + self.dict_keys + self.extra_keys for n in known_keys: a = getattr(self, n) if a: d[n] = a return d def info(self, message): if not self.options['quiet']: print(message) def warn(self, message): sys.stderr.write('Warning: %s\n' % (message,)) def set_options(self, **options): for (key, value) in options.items(): if key in self.options: self.options[key] = value else: raise ValueError('Unknown option: ' + key) def get_distribution(self): from numpy.distutils.core import get_distribution return get_distribution() def _wildcard_get_subpackage(self, subpackage_name, parent_name, caller_level=1): l = subpackage_name.split('.') subpackage_path = njoin([self.local_path] + l) dirs = [_m for _m in sorted_glob(subpackage_path) if os.path.isdir(_m)] config_list = [] for d in dirs: if not os.path.isfile(njoin(d, '__init__.py')): continue if 'build' in d.split(os.sep): continue n = '.'.join(d.split(os.sep)[-len(l):]) c = self.get_subpackage(n, parent_name=parent_name, caller_level=caller_level + 1) config_list.extend(c) return config_list def _get_configuration_from_setup_py(self, setup_py, subpackage_name, subpackage_path, parent_name, caller_level=1): sys.path.insert(0, os.path.dirname(setup_py)) try: setup_name = os.path.splitext(os.path.basename(setup_py))[0] n = dot_join(self.name, subpackage_name, setup_name) setup_module = exec_mod_from_location('_'.join(n.split('.')), setup_py) if not hasattr(setup_module, 'configuration'): if not self.options['assume_default_configuration']: self.warn('Assuming default configuration (%s does not define configuration())' % setup_module) config = Configuration(subpackage_name, parent_name, self.top_path, subpackage_path, caller_level=caller_level + 1) else: pn = dot_join(*[parent_name] + subpackage_name.split('.')[:-1]) args = (pn,) if setup_module.configuration.__code__.co_argcount > 1: args = args + (self.top_path,) config = setup_module.configuration(*args) if config.name != dot_join(parent_name, subpackage_name): self.warn('Subpackage %r configuration returned as %r' % (dot_join(parent_name, subpackage_name), config.name)) finally: del sys.path[0] return config def get_subpackage(self, subpackage_name, subpackage_path=None, parent_name=None, caller_level=1): if subpackage_name is None: if subpackage_path is None: raise ValueError('either subpackage_name or subpackage_path must be specified') subpackage_name = os.path.basename(subpackage_path) l = subpackage_name.split('.') if subpackage_path is None and '*' in subpackage_name: return self._wildcard_get_subpackage(subpackage_name, parent_name, caller_level=caller_level + 1) assert '*' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name)) if subpackage_path is None: subpackage_path = njoin([self.local_path] + l) else: subpackage_path = njoin([subpackage_path] + l[:-1]) subpackage_path = self.paths([subpackage_path])[0] setup_py = njoin(subpackage_path, self.setup_name) if not self.options['ignore_setup_xxx_py']: if not os.path.isfile(setup_py): setup_py = njoin(subpackage_path, 'setup_%s.py' % subpackage_name) if not os.path.isfile(setup_py): if not self.options['assume_default_configuration']: self.warn('Assuming default configuration (%s/{setup_%s,setup}.py was not found)' % (os.path.dirname(setup_py), subpackage_name)) config = Configuration(subpackage_name, parent_name, self.top_path, subpackage_path, caller_level=caller_level + 1) else: config = self._get_configuration_from_setup_py(setup_py, subpackage_name, subpackage_path, parent_name, caller_level=caller_level + 1) if config: return [config] else: return [] def add_subpackage(self, subpackage_name, subpackage_path=None, standalone=False): if standalone: parent_name = None else: parent_name = self.name config_list = self.get_subpackage(subpackage_name, subpackage_path, parent_name=parent_name, caller_level=2) if not config_list: self.warn('No configuration returned, assuming unavailable.') for config in config_list: d = config if isinstance(config, Configuration): d = config.todict() assert isinstance(d, dict), repr(type(d)) self.info('Appending %s configuration to %s' % (d.get('name'), self.name)) self.dict_append(**d) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized, it may be too late to add a subpackage ' + subpackage_name) def add_data_dir(self, data_path): if is_sequence(data_path): (d, data_path) = data_path else: d = None if is_sequence(data_path): [self.add_data_dir((d, p)) for p in data_path] return if not is_string(data_path): raise TypeError('not a string: %r' % (data_path,)) if d is None: if os.path.isabs(data_path): return self.add_data_dir((os.path.basename(data_path), data_path)) return self.add_data_dir((data_path, data_path)) paths = self.paths(data_path, include_non_existing=False) if is_glob_pattern(data_path): if is_glob_pattern(d): pattern_list = allpath(d).split(os.sep) pattern_list.reverse() rl = list(range(len(pattern_list) - 1)) rl.reverse() for i in rl: if not pattern_list[i]: del pattern_list[i] for path in paths: if not os.path.isdir(path): print('Not a directory, skipping', path) continue rpath = rel_path(path, self.local_path) path_list = rpath.split(os.sep) path_list.reverse() target_list = [] i = 0 for s in pattern_list: if is_glob_pattern(s): if i >= len(path_list): raise ValueError('cannot fill pattern %r with %r' % (d, path)) target_list.append(path_list[i]) else: assert s == path_list[i], repr((s, path_list[i], data_path, d, path, rpath)) target_list.append(s) i += 1 if path_list[i:]: self.warn('mismatch of pattern_list=%s and path_list=%s' % (pattern_list, path_list)) target_list.reverse() self.add_data_dir((os.sep.join(target_list), path)) else: for path in paths: self.add_data_dir((d, path)) return assert not is_glob_pattern(d), repr(d) dist = self.get_distribution() if dist is not None and dist.data_files is not None: data_files = dist.data_files else: data_files = self.data_files for path in paths: for (d1, f) in list(general_source_directories_files(path)): target_path = os.path.join(self.path_in_package, d, d1) data_files.append((target_path, f)) def _optimize_data_files(self): data_dict = {} for (p, files) in self.data_files: if p not in data_dict: data_dict[p] = set() for f in files: data_dict[p].add(f) self.data_files[:] = [(p, list(files)) for (p, files) in data_dict.items()] def add_data_files(self, *files): if len(files) > 1: for f in files: self.add_data_files(f) return assert len(files) == 1 if is_sequence(files[0]): (d, files) = files[0] else: d = None if is_string(files): filepat = files elif is_sequence(files): if len(files) == 1: filepat = files[0] else: for f in files: self.add_data_files((d, f)) return else: raise TypeError(repr(type(files))) if d is None: if hasattr(filepat, '__call__'): d = '' elif os.path.isabs(filepat): d = '' else: d = os.path.dirname(filepat) self.add_data_files((d, files)) return paths = self.paths(filepat, include_non_existing=False) if is_glob_pattern(filepat): if is_glob_pattern(d): pattern_list = d.split(os.sep) pattern_list.reverse() for path in paths: path_list = path.split(os.sep) path_list.reverse() path_list.pop() target_list = [] i = 0 for s in pattern_list: if is_glob_pattern(s): target_list.append(path_list[i]) i += 1 else: target_list.append(s) target_list.reverse() self.add_data_files((os.sep.join(target_list), path)) else: self.add_data_files((d, paths)) return assert not is_glob_pattern(d), repr((d, filepat)) dist = self.get_distribution() if dist is not None and dist.data_files is not None: data_files = dist.data_files else: data_files = self.data_files data_files.append((os.path.join(self.path_in_package, d), paths)) def add_define_macros(self, macros): dist = self.get_distribution() if dist is not None: if not hasattr(dist, 'define_macros'): dist.define_macros = [] dist.define_macros.extend(macros) else: self.define_macros.extend(macros) def add_include_dirs(self, *paths): include_dirs = self.paths(paths) dist = self.get_distribution() if dist is not None: if dist.include_dirs is None: dist.include_dirs = [] dist.include_dirs.extend(include_dirs) else: self.include_dirs.extend(include_dirs) def add_headers(self, *files): headers = [] for path in files: if is_string(path): [headers.append((self.name, p)) for p in self.paths(path)] else: if not isinstance(path, (tuple, list)) or len(path) != 2: raise TypeError(repr(path)) [headers.append((path[0], p)) for p in self.paths(path[1])] dist = self.get_distribution() if dist is not None: if dist.headers is None: dist.headers = [] dist.headers.extend(headers) else: self.headers.extend(headers) def paths(self, *paths, **kws): include_non_existing = kws.get('include_non_existing', True) return gpaths(paths, local_path=self.local_path, include_non_existing=include_non_existing) def _fix_paths_dict(self, kw): for k in kw.keys(): v = kw[k] if k in ['sources', 'depends', 'include_dirs', 'library_dirs', 'module_dirs', 'extra_objects']: new_v = self.paths(v) kw[k] = new_v def add_extension(self, name, sources, **kw): ext_args = copy.copy(kw) ext_args['name'] = dot_join(self.name, name) ext_args['sources'] = sources if 'extra_info' in ext_args: extra_info = ext_args['extra_info'] del ext_args['extra_info'] if isinstance(extra_info, dict): extra_info = [extra_info] for info in extra_info: assert isinstance(info, dict), repr(info) dict_append(ext_args, **info) self._fix_paths_dict(ext_args) libraries = ext_args.get('libraries', []) libnames = [] ext_args['libraries'] = [] for libname in libraries: if isinstance(libname, tuple): self._fix_paths_dict(libname[1]) if '@' in libname: (lname, lpath) = libname.split('@', 1) lpath = os.path.abspath(njoin(self.local_path, lpath)) if os.path.isdir(lpath): c = self.get_subpackage(None, lpath, caller_level=2) if isinstance(c, Configuration): c = c.todict() for l in [l[0] for l in c.get('libraries', [])]: llname = l.split('__OF__', 1)[0] if llname == lname: c.pop('name', None) dict_append(ext_args, **c) break continue libnames.append(libname) ext_args['libraries'] = libnames + ext_args['libraries'] ext_args['define_macros'] = self.define_macros + ext_args.get('define_macros', []) from numpy.distutils.core import Extension ext = Extension(**ext_args) self.ext_modules.append(ext) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized, it may be too late to add an extension ' + name) return ext def add_library(self, name, sources, **build_info): self._add_library(name, sources, None, build_info) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized, it may be too late to add a library ' + name) def _add_library(self, name, sources, install_dir, build_info): build_info = copy.copy(build_info) build_info['sources'] = sources if not 'depends' in build_info: build_info['depends'] = [] self._fix_paths_dict(build_info) self.libraries.append((name, build_info)) def add_installed_library(self, name, sources, install_dir, build_info=None): if not build_info: build_info = {} install_dir = os.path.join(self.package_path, install_dir) self._add_library(name, sources, install_dir, build_info) self.installed_libraries.append(InstallableLib(name, build_info, install_dir)) def add_npy_pkg_config(self, template, install_dir, subst_dict=None): if subst_dict is None: subst_dict = {} template = os.path.join(self.package_path, template) if self.name in self.installed_pkg_config: self.installed_pkg_config[self.name].append((template, install_dir, subst_dict)) else: self.installed_pkg_config[self.name] = [(template, install_dir, subst_dict)] def add_scripts(self, *files): scripts = self.paths(files) dist = self.get_distribution() if dist is not None: if dist.scripts is None: dist.scripts = [] dist.scripts.extend(scripts) else: self.scripts.extend(scripts) def dict_append(self, **dict): for key in self.list_keys: a = getattr(self, key) a.extend(dict.get(key, [])) for key in self.dict_keys: a = getattr(self, key) a.update(dict.get(key, {})) known_keys = self.list_keys + self.dict_keys + self.extra_keys for key in dict.keys(): if key not in known_keys: a = getattr(self, key, None) if a and a == dict[key]: continue self.warn('Inheriting attribute %r=%r from %r' % (key, dict[key], dict.get('name', '?'))) setattr(self, key, dict[key]) self.extra_keys.append(key) elif key in self.extra_keys: self.info('Ignoring attempt to set %r (from %r to %r)' % (key, getattr(self, key), dict[key])) elif key in known_keys: pass else: raise ValueError("Don't know about key=%r" % key) def __str__(self): from pprint import pformat known_keys = self.list_keys + self.dict_keys + self.extra_keys s = '<' + 5 * '-' + '\n' s += 'Configuration of ' + self.name + ':\n' known_keys.sort() for k in known_keys: a = getattr(self, k, None) if a: s += '%s = %s\n' % (k, pformat(a)) s += 5 * '-' + '>' return s def get_config_cmd(self): cmd = get_cmd('config') cmd.ensure_finalized() cmd.dump_source = 0 cmd.noisy = 0 old_path = os.environ.get('PATH') if old_path: path = os.pathsep.join(['.', old_path]) os.environ['PATH'] = path return cmd def get_build_temp_dir(self): cmd = get_cmd('build') cmd.ensure_finalized() return cmd.build_temp def have_f77c(self): simple_fortran_subroutine = '\n subroutine simple\n end\n ' config_cmd = self.get_config_cmd() flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77') return flag def have_f90c(self): simple_fortran_subroutine = '\n subroutine simple\n end\n ' config_cmd = self.get_config_cmd() flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f90') return flag def append_to(self, extlib): if is_sequence(extlib): (lib_name, build_info) = extlib dict_append(build_info, libraries=self.libraries, include_dirs=self.include_dirs) else: from numpy.distutils.core import Extension assert isinstance(extlib, Extension), repr(extlib) extlib.libraries.extend(self.libraries) extlib.include_dirs.extend(self.include_dirs) def _get_svn_revision(self, path): try: output = subprocess.check_output(['svnversion'], cwd=path) except (subprocess.CalledProcessError, OSError): pass else: m = re.match(b'(?P\\d+)', output) if m: return int(m.group('revision')) if sys.platform == 'win32' and os.environ.get('SVN_ASP_DOT_NET_HACK', None): entries = njoin(path, '_svn', 'entries') else: entries = njoin(path, '.svn', 'entries') if os.path.isfile(entries): with open(entries) as f: fstr = f.read() if fstr[:5] == '\\d+)"', fstr) if m: return int(m.group('revision')) else: m = re.search('dir[\\n\\r]+(?P\\d+)', fstr) if m: return int(m.group('revision')) return None def _get_hg_revision(self, path): try: output = subprocess.check_output(['hg', 'identify', '--num'], cwd=path) except (subprocess.CalledProcessError, OSError): pass else: m = re.match(b'(?P\\d+)', output) if m: return int(m.group('revision')) branch_fn = njoin(path, '.hg', 'branch') branch_cache_fn = njoin(path, '.hg', 'branch.cache') if os.path.isfile(branch_fn): branch0 = None with open(branch_fn) as f: revision0 = f.read().strip() branch_map = {} with open(branch_cache_fn) as f: for line in f: (branch1, revision1) = line.split()[:2] if revision1 == revision0: branch0 = branch1 try: revision1 = int(revision1) except ValueError: continue branch_map[branch1] = revision1 return branch_map.get(branch0) return None def get_version(self, version_file=None, version_variable=None): version = getattr(self, 'version', None) if version is not None: return version if version_file is None: files = ['__version__.py', self.name.split('.')[-1] + '_version.py', 'version.py', '__svn_version__.py', '__hg_version__.py'] else: files = [version_file] if version_variable is None: version_vars = ['version', '__version__', self.name.split('.')[-1] + '_version'] else: version_vars = [version_variable] for f in files: fn = njoin(self.local_path, f) if os.path.isfile(fn): info = ('.py', 'U', 1) name = os.path.splitext(os.path.basename(fn))[0] n = dot_join(self.name, name) try: version_module = exec_mod_from_location('_'.join(n.split('.')), fn) except ImportError as e: self.warn(str(e)) version_module = None if version_module is None: continue for a in version_vars: version = getattr(version_module, a, None) if version is not None: break try: version = version_module.get_versions()['version'] except AttributeError: pass if version is not None: break if version is not None: self.version = version return version revision = self._get_svn_revision(self.local_path) if revision is None: revision = self._get_hg_revision(self.local_path) if revision is not None: version = str(revision) self.version = version return version def make_svn_version_py(self, delete=True): target = njoin(self.local_path, '__svn_version__.py') revision = self._get_svn_revision(self.local_path) if os.path.isfile(target) or revision is None: return else: def generate_svn_version_py(): if not os.path.isfile(target): version = str(revision) self.info('Creating %s (version=%r)' % (target, version)) with open(target, 'w') as f: f.write('version = %r\n' % version) def rm_file(f=target, p=self.info): if delete: try: os.remove(f) p('removed ' + f) except OSError: pass try: os.remove(f + 'c') p('removed ' + f + 'c') except OSError: pass atexit.register(rm_file) return target self.add_data_files(('', generate_svn_version_py())) def make_hg_version_py(self, delete=True): target = njoin(self.local_path, '__hg_version__.py') revision = self._get_hg_revision(self.local_path) if os.path.isfile(target) or revision is None: return else: def generate_hg_version_py(): if not os.path.isfile(target): version = str(revision) self.info('Creating %s (version=%r)' % (target, version)) with open(target, 'w') as f: f.write('version = %r\n' % version) def rm_file(f=target, p=self.info): if delete: try: os.remove(f) p('removed ' + f) except OSError: pass try: os.remove(f + 'c') p('removed ' + f + 'c') except OSError: pass atexit.register(rm_file) return target self.add_data_files(('', generate_hg_version_py())) def make_config_py(self, name='__config__'): self.py_modules.append((self.name, name, generate_config_py)) def get_info(self, *names): from .system_info import get_info, dict_append info_dict = {} for a in names: dict_append(info_dict, **get_info(a)) return info_dict def get_cmd(cmdname, _cache={}): if cmdname not in _cache: import distutils.core dist = distutils.core._setup_distribution if dist is None: from distutils.errors import DistutilsInternalError raise DistutilsInternalError('setup distribution instance not initialized') cmd = dist.get_command_obj(cmdname) _cache[cmdname] = cmd return _cache[cmdname] def get_numpy_include_dirs(): include_dirs = Configuration.numpy_include_dirs[:] if not include_dirs: import numpy include_dirs = [numpy.get_include()] return include_dirs def get_npy_pkg_dir(): d = os.environ.get('NPY_PKG_CONFIG_PATH') if d is not None: return d spec = importlib.util.find_spec('numpy') d = os.path.join(os.path.dirname(spec.origin), '_core', 'lib', 'npy-pkg-config') return d def get_pkg_info(pkgname, dirs=None): from numpy.distutils.npy_pkg_config import read_config if dirs: dirs.append(get_npy_pkg_dir()) else: dirs = [get_npy_pkg_dir()] return read_config(pkgname, dirs) def get_info(pkgname, dirs=None): from numpy.distutils.npy_pkg_config import parse_flags pkg_info = get_pkg_info(pkgname, dirs) info = parse_flags(pkg_info.cflags()) for (k, v) in parse_flags(pkg_info.libs()).items(): info[k].extend(v) info['define_macros'] = info['macros'] del info['macros'] del info['ignored'] return info def is_bootstrapping(): import builtins try: builtins.__NUMPY_SETUP__ return True except AttributeError: return False def default_config_dict(name=None, parent_name=None, local_path=None): import warnings warnings.warn('Use Configuration(%r,%r,top_path=%r) instead of deprecated default_config_dict(%r,%r,%r)' % (name, parent_name, local_path, name, parent_name, local_path), stacklevel=2) c = Configuration(name, parent_name, local_path) return c.todict() def dict_append(d, **kws): for (k, v) in kws.items(): if k in d: ov = d[k] if isinstance(ov, str): d[k] = v else: d[k].extend(v) else: d[k] = v def appendpath(prefix, path): if os.path.sep != '/': prefix = prefix.replace('/', os.path.sep) path = path.replace('/', os.path.sep) drive = '' if os.path.isabs(path): drive = os.path.splitdrive(prefix)[0] absprefix = os.path.splitdrive(os.path.abspath(prefix))[1] (pathdrive, path) = os.path.splitdrive(path) d = os.path.commonprefix([absprefix, path]) if os.path.join(absprefix[:len(d)], absprefix[len(d):]) != absprefix or os.path.join(path[:len(d)], path[len(d):]) != path: d = os.path.dirname(d) subpath = path[len(d):] if os.path.isabs(subpath): subpath = subpath[1:] else: subpath = path return os.path.normpath(njoin(drive + prefix, subpath)) def generate_config_py(target): from numpy.distutils.system_info import system_info from distutils.dir_util import mkpath mkpath(os.path.dirname(target)) with open(target, 'w') as f: f.write("# This file is generated by numpy's %s\n" % os.path.basename(sys.argv[0])) f.write('# It contains system_info results at the time of building this package.\n') f.write('__all__ = ["get_info","show"]\n\n') f.write(textwrap.dedent("\n import os\n import sys\n\n extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs')\n\n if sys.platform == 'win32' and os.path.isdir(extra_dll_dir):\n os.add_dll_directory(extra_dll_dir)\n\n ")) for (k, i) in system_info.saved_results.items(): f.write('%s=%r\n' % (k, i)) f.write(textwrap.dedent('\n def get_info(name):\n g = globals()\n return g.get(name, g.get(name + "_info", {}))\n\n def show():\n """\n Show libraries in the system on which NumPy was built.\n\n Print information about various resources (libraries, library\n directories, include directories, etc.) in the system on which\n NumPy was built.\n\n See Also\n --------\n get_include : Returns the directory containing NumPy C\n header files.\n\n Notes\n -----\n 1. Classes specifying the information to be printed are defined\n in the `numpy.distutils.system_info` module.\n\n Information may include:\n\n * ``language``: language used to write the libraries (mostly\n C or f77)\n * ``libraries``: names of libraries found in the system\n * ``library_dirs``: directories containing the libraries\n * ``include_dirs``: directories containing library header files\n * ``src_dirs``: directories containing library source files\n * ``define_macros``: preprocessor macros used by\n ``distutils.setup``\n * ``baseline``: minimum CPU features required\n * ``found``: dispatched features supported in the system\n * ``not found``: dispatched features that are not supported\n in the system\n\n 2. NumPy BLAS/LAPACK Installation Notes\n\n Installing a numpy wheel (``pip install numpy`` or force it\n via ``pip install numpy --only-binary :numpy: numpy``) includes\n an OpenBLAS implementation of the BLAS and LAPACK linear algebra\n APIs. In this case, ``library_dirs`` reports the original build\n time configuration as compiled with gcc/gfortran; at run time\n the OpenBLAS library is in\n ``site-packages/numpy.libs/`` (linux), or\n ``site-packages/numpy/.dylibs/`` (macOS), or\n ``site-packages/numpy/.libs/`` (windows).\n\n Installing numpy from source\n (``pip install numpy --no-binary numpy``) searches for BLAS and\n LAPACK dynamic link libraries at build time as influenced by\n environment variables NPY_BLAS_LIBS, NPY_CBLAS_LIBS, and\n NPY_LAPACK_LIBS; or NPY_BLAS_ORDER and NPY_LAPACK_ORDER;\n or the optional file ``~/.numpy-site.cfg``.\n NumPy remembers those locations and expects to load the same\n libraries at run-time.\n In NumPy 1.21+ on macOS, \'accelerate\' (Apple\'s Accelerate BLAS\n library) is in the default build-time search order after\n \'openblas\'.\n\n Examples\n --------\n >>> import numpy as np\n >>> np.show_config()\n blas_opt_info:\n language = c\n define_macros = [(\'HAVE_CBLAS\', None)]\n libraries = [\'openblas\', \'openblas\']\n library_dirs = [\'/usr/local/lib\']\n """\n from numpy._core._multiarray_umath import (\n __cpu_features__, __cpu_baseline__, __cpu_dispatch__\n )\n for name,info_dict in globals().items():\n if name[0] == "_" or type(info_dict) is not type({}): continue\n print(name + ":")\n if not info_dict:\n print(" NOT AVAILABLE")\n for k,v in info_dict.items():\n v = str(v)\n if k == "sources" and len(v) > 200:\n v = v[:60] + " ...\\n... " + v[-60:]\n print(" %s = %s" % (k,v))\n\n features_found, features_not_found = [], []\n for feature in __cpu_dispatch__:\n if __cpu_features__[feature]:\n features_found.append(feature)\n else:\n features_not_found.append(feature)\n\n print("Supported SIMD extensions in this NumPy install:")\n print(" baseline = %s" % (\',\'.join(__cpu_baseline__)))\n print(" found = %s" % (\',\'.join(features_found)))\n print(" not found = %s" % (\',\'.join(features_not_found)))\n\n ')) return target def msvc_version(compiler): if not compiler.compiler_type == 'msvc': raise ValueError('Compiler instance is not msvc (%s)' % compiler.compiler_type) return compiler._MSVCCompiler__version def get_build_architecture(): from distutils.msvccompiler import get_build_architecture return get_build_architecture() _cxx_ignore_flags = {'-Werror=implicit-function-declaration', '-std=c99'} def sanitize_cxx_flags(cxxflags): return [flag for flag in cxxflags if flag not in _cxx_ignore_flags] def exec_mod_from_location(modname, modfile): spec = importlib.util.spec_from_file_location(modname, modfile) foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) return foo # File: numpy-main/numpy/distutils/msvc9compiler.py import os from distutils.msvc9compiler import MSVCCompiler as _MSVCCompiler from .system_info import platform_bits def _merge(old, new): if not old: return new if new in old: return old return ';'.join([old, new]) class MSVCCompiler(_MSVCCompiler): def __init__(self, verbose=0, dry_run=0, force=0): _MSVCCompiler.__init__(self, verbose, dry_run, force) def initialize(self, plat_name=None): environ_lib = os.getenv('lib') environ_include = os.getenv('include') _MSVCCompiler.initialize(self, plat_name) os.environ['lib'] = _merge(environ_lib, os.environ['lib']) os.environ['include'] = _merge(environ_include, os.environ['include']) if platform_bits == 32: self.compile_options += ['/arch:SSE2'] self.compile_options_debug += ['/arch:SSE2'] def manifest_setup_ldargs(self, output_filename, build_temp, ld_args): ld_args.append('/MANIFEST') _MSVCCompiler.manifest_setup_ldargs(self, output_filename, build_temp, ld_args) # File: numpy-main/numpy/distutils/msvccompiler.py import os from distutils.msvccompiler import MSVCCompiler as _MSVCCompiler from .system_info import platform_bits def _merge(old, new): if new in old: return old if not old: return new return ';'.join([old, new]) class MSVCCompiler(_MSVCCompiler): def __init__(self, verbose=0, dry_run=0, force=0): _MSVCCompiler.__init__(self, verbose, dry_run, force) def initialize(self): environ_lib = os.getenv('lib', '') environ_include = os.getenv('include', '') _MSVCCompiler.initialize(self) os.environ['lib'] = _merge(environ_lib, os.environ['lib']) os.environ['include'] = _merge(environ_include, os.environ['include']) if platform_bits == 32: self.compile_options += ['/arch:SSE2'] self.compile_options_debug += ['/arch:SSE2'] def lib_opts_if_msvc(build_cmd): if build_cmd.compiler.compiler_type != 'msvc': return [] flags = ['/GL-'] if build_cmd.compiler_opt.cc_test_flags(['-d2VolatileMetadata-']): flags.append('-d2VolatileMetadata-') return flags # File: numpy-main/numpy/distutils/npy_pkg_config.py import sys import re import os from configparser import RawConfigParser __all__ = ['FormatError', 'PkgNotFound', 'LibraryInfo', 'VariableSet', 'read_config', 'parse_flags'] _VAR = re.compile('\\$\\{([a-zA-Z0-9_-]+)\\}') class FormatError(OSError): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class PkgNotFound(OSError): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg def parse_flags(line): d = {'include_dirs': [], 'library_dirs': [], 'libraries': [], 'macros': [], 'ignored': []} flags = (' ' + line).split(' -') for flag in flags: flag = '-' + flag if len(flag) > 0: if flag.startswith('-I'): d['include_dirs'].append(flag[2:].strip()) elif flag.startswith('-L'): d['library_dirs'].append(flag[2:].strip()) elif flag.startswith('-l'): d['libraries'].append(flag[2:].strip()) elif flag.startswith('-D'): d['macros'].append(flag[2:].strip()) else: d['ignored'].append(flag) return d def _escape_backslash(val): return val.replace('\\', '\\\\') class LibraryInfo: def __init__(self, name, description, version, sections, vars, requires=None): self.name = name self.description = description if requires: self.requires = requires else: self.requires = [] self.version = version self._sections = sections self.vars = vars def sections(self): return list(self._sections.keys()) def cflags(self, section='default'): val = self.vars.interpolate(self._sections[section]['cflags']) return _escape_backslash(val) def libs(self, section='default'): val = self.vars.interpolate(self._sections[section]['libs']) return _escape_backslash(val) def __str__(self): m = ['Name: %s' % self.name, 'Description: %s' % self.description] if self.requires: m.append('Requires:') else: m.append('Requires: %s' % ','.join(self.requires)) m.append('Version: %s' % self.version) return '\n'.join(m) class VariableSet: def __init__(self, d): self._raw_data = dict([(k, v) for (k, v) in d.items()]) self._re = {} self._re_sub = {} self._init_parse() def _init_parse(self): for (k, v) in self._raw_data.items(): self._init_parse_var(k, v) def _init_parse_var(self, name, value): self._re[name] = re.compile('\\$\\{%s\\}' % name) self._re_sub[name] = value def interpolate(self, value): def _interpolate(value): for k in self._re.keys(): value = self._re[k].sub(self._re_sub[k], value) return value while _VAR.search(value): nvalue = _interpolate(value) if nvalue == value: break value = nvalue return value def variables(self): return list(self._raw_data.keys()) def __getitem__(self, name): return self._raw_data[name] def __setitem__(self, name, value): self._raw_data[name] = value self._init_parse_var(name, value) def parse_meta(config): if not config.has_section('meta'): raise FormatError('No meta section found !') d = dict(config.items('meta')) for k in ['name', 'description', 'version']: if not k in d: raise FormatError('Option %s (section [meta]) is mandatory, but not found' % k) if not 'requires' in d: d['requires'] = [] return d def parse_variables(config): if not config.has_section('variables'): raise FormatError('No variables section found !') d = {} for (name, value) in config.items('variables'): d[name] = value return VariableSet(d) def parse_sections(config): return (meta_d, r) def pkg_to_filename(pkg_name): return '%s.ini' % pkg_name def parse_config(filename, dirs=None): if dirs: filenames = [os.path.join(d, filename) for d in dirs] else: filenames = [filename] config = RawConfigParser() n = config.read(filenames) if not len(n) >= 1: raise PkgNotFound('Could not find file(s) %s' % str(filenames)) meta = parse_meta(config) vars = {} if config.has_section('variables'): for (name, value) in config.items('variables'): vars[name] = _escape_backslash(value) secs = [s for s in config.sections() if not s in ['meta', 'variables']] sections = {} requires = {} for s in secs: d = {} if config.has_option(s, 'requires'): requires[s] = config.get(s, 'requires') for (name, value) in config.items(s): d[name] = value sections[s] = d return (meta, vars, sections, requires) def _read_config_imp(filenames, dirs=None): def _read_config(f): (meta, vars, sections, reqs) = parse_config(f, dirs) for (rname, rvalue) in reqs.items(): (nmeta, nvars, nsections, nreqs) = _read_config(pkg_to_filename(rvalue)) for (k, v) in nvars.items(): if not k in vars: vars[k] = v for (oname, ovalue) in nsections[rname].items(): if ovalue: sections[rname][oname] += ' %s' % ovalue return (meta, vars, sections, reqs) (meta, vars, sections, reqs) = _read_config(filenames) if not 'pkgdir' in vars and 'pkgname' in vars: pkgname = vars['pkgname'] if not pkgname in sys.modules: raise ValueError('You should import %s to get information on %s' % (pkgname, meta['name'])) mod = sys.modules[pkgname] vars['pkgdir'] = _escape_backslash(os.path.dirname(mod.__file__)) return LibraryInfo(name=meta['name'], description=meta['description'], version=meta['version'], sections=sections, vars=VariableSet(vars)) _CACHE = {} def read_config(pkgname, dirs=None): try: return _CACHE[pkgname] except KeyError: v = _read_config_imp(pkg_to_filename(pkgname), dirs) _CACHE[pkgname] = v return v if __name__ == '__main__': from optparse import OptionParser import glob parser = OptionParser() parser.add_option('--cflags', dest='cflags', action='store_true', help='output all preprocessor and compiler flags') parser.add_option('--libs', dest='libs', action='store_true', help='output all linker flags') parser.add_option('--use-section', dest='section', help='use this section instead of default for options') parser.add_option('--version', dest='version', action='store_true', help='output version') parser.add_option('--atleast-version', dest='min_version', help='Minimal version') parser.add_option('--list-all', dest='list_all', action='store_true', help='Minimal version') parser.add_option('--define-variable', dest='define_variable', help='Replace variable with the given value') (options, args) = parser.parse_args(sys.argv) if len(args) < 2: raise ValueError('Expect package name on the command line:') if options.list_all: files = glob.glob('*.ini') for f in files: info = read_config(f) print('%s\t%s - %s' % (info.name, info.name, info.description)) pkg_name = args[1] d = os.environ.get('NPY_PKG_CONFIG_PATH') if d: info = read_config(pkg_name, ['numpy/_core/lib/npy-pkg-config', '.', d]) else: info = read_config(pkg_name, ['numpy/_core/lib/npy-pkg-config', '.']) if options.section: section = options.section else: section = 'default' if options.define_variable: m = re.search('([\\S]+)=([\\S]+)', options.define_variable) if not m: raise ValueError('--define-variable option should be of the form --define-variable=foo=bar') else: name = m.group(1) value = m.group(2) info.vars[name] = value if options.cflags: print(info.cflags(section)) if options.libs: print(info.libs(section)) if options.version: print(info.version) if options.min_version: print(info.version >= options.min_version) # File: numpy-main/numpy/distutils/pathccompiler.py from distutils.unixccompiler import UnixCCompiler class PathScaleCCompiler(UnixCCompiler): compiler_type = 'pathcc' cc_exe = 'pathcc' cxx_exe = 'pathCC' def __init__(self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__(self, verbose, dry_run, force) cc_compiler = self.cc_exe cxx_compiler = self.cxx_exe self.set_executables(compiler=cc_compiler, compiler_so=cc_compiler, compiler_cxx=cxx_compiler, linker_exe=cc_compiler, linker_so=cc_compiler + ' -shared') # File: numpy-main/numpy/distutils/system_info.py """""" import sys import os import re import copy import warnings import subprocess import textwrap from glob import glob from functools import reduce from configparser import NoOptionError from configparser import RawConfigParser as ConfigParser from distutils.errors import DistutilsError from distutils.dist import Distribution import sysconfig from numpy.distutils import log from distutils.util import get_platform from numpy.distutils.exec_command import find_executable, filepath_from_subprocess_output from numpy.distutils.misc_util import is_sequence, is_string, get_shared_lib_extension from numpy.distutils.command.config import config as cmd_config from numpy.distutils import customized_ccompiler as _customized_ccompiler from numpy.distutils import _shell_utils import distutils.ccompiler import tempfile import shutil __all__ = ['system_info'] import platform _bits = {'32bit': 32, '64bit': 64} platform_bits = _bits[platform.architecture()[0]] global_compiler = None def customized_ccompiler(): global global_compiler if not global_compiler: global_compiler = _customized_ccompiler() return global_compiler def _c_string_literal(s): s = s.replace('\\', '\\\\') s = s.replace('"', '\\"') s = s.replace('\n', '\\n') return '"{}"'.format(s) def libpaths(paths, bits): if bits not in (32, 64): raise ValueError('Invalid bit size in libpaths: 32 or 64 only') if bits == 32: return paths out = [] for p in paths: out.extend([p + '64', p]) return out if sys.platform == 'win32': default_lib_dirs = ['C:\\', os.path.join(sysconfig.get_config_var('exec_prefix'), 'libs')] default_runtime_dirs = [] default_include_dirs = [] default_src_dirs = ['.'] default_x11_lib_dirs = [] default_x11_include_dirs = [] _include_dirs = ['include', 'include/suitesparse'] _lib_dirs = ['lib'] _include_dirs = [d.replace('/', os.sep) for d in _include_dirs] _lib_dirs = [d.replace('/', os.sep) for d in _lib_dirs] def add_system_root(library_root): global default_lib_dirs global default_include_dirs library_root = os.path.normpath(library_root) default_lib_dirs.extend((os.path.join(library_root, d) for d in _lib_dirs)) default_include_dirs.extend((os.path.join(library_root, d) for d in _include_dirs)) vcpkg = shutil.which('vcpkg') if vcpkg: vcpkg_dir = os.path.dirname(vcpkg) if platform.architecture()[0] == '32bit': specifier = 'x86' else: specifier = 'x64' vcpkg_installed = os.path.join(vcpkg_dir, 'installed') for vcpkg_root in [os.path.join(vcpkg_installed, specifier + '-windows'), os.path.join(vcpkg_installed, specifier + '-windows-static')]: add_system_root(vcpkg_root) conda = shutil.which('conda') if conda: conda_dir = os.path.dirname(conda) add_system_root(os.path.join(conda_dir, '..', 'Library')) add_system_root(os.path.join(conda_dir, 'Library')) else: default_lib_dirs = libpaths(['/usr/local/lib', '/opt/lib', '/usr/lib', '/opt/local/lib', '/sw/lib'], platform_bits) default_runtime_dirs = [] default_include_dirs = ['/usr/local/include', '/opt/include', '/opt/local/include/ufsparse', '/opt/local/include', '/sw/include', '/usr/include/suitesparse'] default_src_dirs = ['.', '/usr/local/src', '/opt/src', '/sw/src'] default_x11_lib_dirs = libpaths(['/usr/X11R6/lib', '/usr/X11/lib', '/usr/lib'], platform_bits) default_x11_include_dirs = ['/usr/X11R6/include', '/usr/X11/include'] if os.path.exists('/usr/lib/X11'): globbed_x11_dir = glob('/usr/lib/*/libX11.so') if globbed_x11_dir: x11_so_dir = os.path.split(globbed_x11_dir[0])[0] default_x11_lib_dirs.extend([x11_so_dir, '/usr/lib/X11']) default_x11_include_dirs.extend(['/usr/lib/X11/include', '/usr/include/X11']) with open(os.devnull, 'w') as tmp: try: p = subprocess.Popen(['gcc', '-print-multiarch'], stdout=subprocess.PIPE, stderr=tmp) except (OSError, DistutilsError): pass else: triplet = str(p.communicate()[0].decode().strip()) if p.returncode == 0: default_x11_lib_dirs += [os.path.join('/usr/lib/', triplet)] default_lib_dirs += [os.path.join('/usr/lib/', triplet)] if os.path.join(sys.prefix, 'lib') not in default_lib_dirs: default_lib_dirs.insert(0, os.path.join(sys.prefix, 'lib')) default_include_dirs.append(os.path.join(sys.prefix, 'include')) default_src_dirs.append(os.path.join(sys.prefix, 'src')) default_lib_dirs = [_m for _m in default_lib_dirs if os.path.isdir(_m)] default_runtime_dirs = [_m for _m in default_runtime_dirs if os.path.isdir(_m)] default_include_dirs = [_m for _m in default_include_dirs if os.path.isdir(_m)] default_src_dirs = [_m for _m in default_src_dirs if os.path.isdir(_m)] so_ext = get_shared_lib_extension() def get_standard_file(fname): filenames = [] try: f = __file__ except NameError: f = sys.argv[0] sysfile = os.path.join(os.path.split(os.path.abspath(f))[0], fname) if os.path.isfile(sysfile): filenames.append(sysfile) try: f = os.path.expanduser('~') except KeyError: pass else: user_file = os.path.join(f, fname) if os.path.isfile(user_file): filenames.append(user_file) if os.path.isfile(fname): filenames.append(os.path.abspath(fname)) return filenames def _parse_env_order(base_order, env): order_str = os.environ.get(env, None) base_order = [order.lower() for order in base_order] if order_str is None: return (base_order, []) neg = order_str.startswith('^') or order_str.startswith('!') order_str_l = list(order_str) sum_neg = order_str_l.count('^') + order_str_l.count('!') if neg: if sum_neg > 1: raise ValueError(f"Environment variable '{env}' may only contain a single (prefixed) negation: {order_str}") order_str = order_str[1:] elif sum_neg > 0: raise ValueError(f"Environment variable '{env}' may not mix negated an non-negated items: {order_str}") orders = order_str.lower().split(',') unknown_order = [] if neg: allow_order = base_order.copy() for order in orders: if not order: continue if order not in base_order: unknown_order.append(order) continue if order in allow_order: allow_order.remove(order) else: allow_order = [] for order in orders: if not order: continue if order not in base_order: unknown_order.append(order) continue if order not in allow_order: allow_order.append(order) return (allow_order, unknown_order) def get_info(name, notfound_action=0): cl = {'armpl': armpl_info, 'blas_armpl': blas_armpl_info, 'lapack_armpl': lapack_armpl_info, 'fftw3_armpl': fftw3_armpl_info, 'atlas': atlas_info, 'atlas_threads': atlas_threads_info, 'atlas_blas': atlas_blas_info, 'atlas_blas_threads': atlas_blas_threads_info, 'lapack_atlas': lapack_atlas_info, 'lapack_atlas_threads': lapack_atlas_threads_info, 'atlas_3_10': atlas_3_10_info, 'atlas_3_10_threads': atlas_3_10_threads_info, 'atlas_3_10_blas': atlas_3_10_blas_info, 'atlas_3_10_blas_threads': atlas_3_10_blas_threads_info, 'lapack_atlas_3_10': lapack_atlas_3_10_info, 'lapack_atlas_3_10_threads': lapack_atlas_3_10_threads_info, 'flame': flame_info, 'mkl': mkl_info, 'ssl2': ssl2_info, 'openblas': openblas_info, 'openblas_lapack': openblas_lapack_info, 'openblas_clapack': openblas_clapack_info, 'blis': blis_info, 'lapack_mkl': lapack_mkl_info, 'blas_mkl': blas_mkl_info, 'lapack_ssl2': lapack_ssl2_info, 'blas_ssl2': blas_ssl2_info, 'accelerate': accelerate_info, 'accelerate_lapack': accelerate_lapack_info, 'openblas64_': openblas64__info, 'openblas64__lapack': openblas64__lapack_info, 'openblas_ilp64': openblas_ilp64_info, 'openblas_ilp64_lapack': openblas_ilp64_lapack_info, 'x11': x11_info, 'fft_opt': fft_opt_info, 'fftw': fftw_info, 'fftw2': fftw2_info, 'fftw3': fftw3_info, 'dfftw': dfftw_info, 'sfftw': sfftw_info, 'fftw_threads': fftw_threads_info, 'dfftw_threads': dfftw_threads_info, 'sfftw_threads': sfftw_threads_info, 'djbfft': djbfft_info, 'blas': blas_info, 'lapack': lapack_info, 'lapack_src': lapack_src_info, 'blas_src': blas_src_info, 'numpy': numpy_info, 'f2py': f2py_info, 'Numeric': Numeric_info, 'numeric': Numeric_info, 'numarray': numarray_info, 'numerix': numerix_info, 'lapack_opt': lapack_opt_info, 'lapack_ilp64_opt': lapack_ilp64_opt_info, 'lapack_ilp64_plain_opt': lapack_ilp64_plain_opt_info, 'lapack64__opt': lapack64__opt_info, 'blas_opt': blas_opt_info, 'blas_ilp64_opt': blas_ilp64_opt_info, 'blas_ilp64_plain_opt': blas_ilp64_plain_opt_info, 'blas64__opt': blas64__opt_info, 'boost_python': boost_python_info, 'agg2': agg2_info, 'wx': wx_info, 'gdk_pixbuf_xlib_2': gdk_pixbuf_xlib_2_info, 'gdk-pixbuf-xlib-2.0': gdk_pixbuf_xlib_2_info, 'gdk_pixbuf_2': gdk_pixbuf_2_info, 'gdk-pixbuf-2.0': gdk_pixbuf_2_info, 'gdk': gdk_info, 'gdk_2': gdk_2_info, 'gdk-2.0': gdk_2_info, 'gdk_x11_2': gdk_x11_2_info, 'gdk-x11-2.0': gdk_x11_2_info, 'gtkp_x11_2': gtkp_x11_2_info, 'gtk+-x11-2.0': gtkp_x11_2_info, 'gtkp_2': gtkp_2_info, 'gtk+-2.0': gtkp_2_info, 'xft': xft_info, 'freetype2': freetype2_info, 'umfpack': umfpack_info, 'amd': amd_info}.get(name.lower(), system_info) return cl().get_info(notfound_action) class NotFoundError(DistutilsError): class AliasedOptionError(DistutilsError): class AtlasNotFoundError(NotFoundError): class FlameNotFoundError(NotFoundError): class LapackNotFoundError(NotFoundError): class LapackSrcNotFoundError(LapackNotFoundError): class LapackILP64NotFoundError(NotFoundError): class BlasOptNotFoundError(NotFoundError): class BlasNotFoundError(NotFoundError): class BlasILP64NotFoundError(NotFoundError): class BlasSrcNotFoundError(BlasNotFoundError): class FFTWNotFoundError(NotFoundError): class DJBFFTNotFoundError(NotFoundError): class NumericNotFoundError(NotFoundError): class X11NotFoundError(NotFoundError): class UmfpackNotFoundError(NotFoundError): class system_info: dir_env_var = None search_static_first = 0 section = 'ALL' saved_results = {} notfounderror = NotFoundError def __init__(self, default_lib_dirs=default_lib_dirs, default_include_dirs=default_include_dirs): self.__class__.info = {} self.local_prefixes = [] defaults = {'library_dirs': os.pathsep.join(default_lib_dirs), 'include_dirs': os.pathsep.join(default_include_dirs), 'runtime_library_dirs': os.pathsep.join(default_runtime_dirs), 'rpath': '', 'src_dirs': os.pathsep.join(default_src_dirs), 'search_static_first': str(self.search_static_first), 'extra_compile_args': '', 'extra_link_args': ''} self.cp = ConfigParser(defaults) self.files = [] self.files.extend(get_standard_file('.numpy-site.cfg')) self.files.extend(get_standard_file('site.cfg')) self.parse_config_files() if self.section is not None: self.search_static_first = self.cp.getboolean(self.section, 'search_static_first') assert isinstance(self.search_static_first, int) def parse_config_files(self): self.cp.read(self.files) if not self.cp.has_section(self.section): if self.section is not None: self.cp.add_section(self.section) def calc_libraries_info(self): libs = self.get_libraries() dirs = self.get_lib_dirs() r_dirs = self.get_runtime_lib_dirs() r_dirs.extend(self.get_runtime_lib_dirs(key='rpath')) info = {} for lib in libs: i = self.check_libs(dirs, [lib]) if i is not None: dict_append(info, **i) else: log.info('Library %s was not found. Ignoring' % lib) if r_dirs: i = self.check_libs(r_dirs, [lib]) if i is not None: del i['libraries'] i['runtime_library_dirs'] = i.pop('library_dirs') dict_append(info, **i) else: log.info('Runtime library %s was not found. Ignoring' % lib) return info def set_info(self, **info): if info: lib_info = self.calc_libraries_info() dict_append(info, **lib_info) extra_info = self.calc_extra_info() dict_append(info, **extra_info) self.saved_results[self.__class__.__name__] = info def get_option_single(self, *options): found = [self.cp.has_option(self.section, opt) for opt in options] if sum(found) == 1: return options[found.index(True)] elif sum(found) == 0: return options[0] if AliasedOptionError.__doc__ is None: raise AliasedOptionError() raise AliasedOptionError(AliasedOptionError.__doc__.format(section=self.section, options='[{}]'.format(', '.join(options)))) def has_info(self): return self.__class__.__name__ in self.saved_results def calc_extra_info(self): info = {} for key in ['extra_compile_args', 'extra_link_args']: opt = self.cp.get(self.section, key) opt = _shell_utils.NativeParser.split(opt) if opt: tmp = {key: opt} dict_append(info, **tmp) return info def get_info(self, notfound_action=0): flag = 0 if not self.has_info(): flag = 1 log.info(self.__class__.__name__ + ':') if hasattr(self, 'calc_info'): self.calc_info() if notfound_action: if not self.has_info(): if notfound_action == 1: warnings.warn(self.notfounderror.__doc__, stacklevel=2) elif notfound_action == 2: raise self.notfounderror(self.notfounderror.__doc__) else: raise ValueError(repr(notfound_action)) if not self.has_info(): log.info(' NOT AVAILABLE') self.set_info() else: log.info(' FOUND:') res = self.saved_results.get(self.__class__.__name__) if log.get_threshold() <= log.INFO and flag: for (k, v) in res.items(): v = str(v) if k in ['sources', 'libraries'] and len(v) > 270: v = v[:120] + '...\n...\n...' + v[-120:] log.info(' %s = %s', k, v) log.info('') return copy.deepcopy(res) def get_paths(self, section, key): dirs = self.cp.get(section, key).split(os.pathsep) env_var = self.dir_env_var if env_var: if is_sequence(env_var): e0 = env_var[-1] for e in env_var: if e in os.environ: e0 = e break if not env_var[0] == e0: log.info('Setting %s=%s' % (env_var[0], e0)) env_var = e0 if env_var and env_var in os.environ: d = os.environ[env_var] if d == 'None': log.info('Disabled %s: %s', self.__class__.__name__, '(%s is None)' % (env_var,)) return [] if os.path.isfile(d): dirs = [os.path.dirname(d)] + dirs l = getattr(self, '_lib_names', []) if len(l) == 1: b = os.path.basename(d) b = os.path.splitext(b)[0] if b[:3] == 'lib': log.info('Replacing _lib_names[0]==%r with %r' % (self._lib_names[0], b[3:])) self._lib_names[0] = b[3:] else: ds = d.split(os.pathsep) ds2 = [] for d in ds: if os.path.isdir(d): ds2.append(d) for dd in ['include', 'lib']: d1 = os.path.join(d, dd) if os.path.isdir(d1): ds2.append(d1) dirs = ds2 + dirs default_dirs = self.cp.get(self.section, key).split(os.pathsep) dirs.extend(default_dirs) ret = [] for d in dirs: if len(d) > 0 and (not os.path.isdir(d)): warnings.warn('Specified path %s is invalid.' % d, stacklevel=2) continue if d not in ret: ret.append(d) log.debug('( %s = %s )', key, ':'.join(ret)) return ret def get_lib_dirs(self, key='library_dirs'): return self.get_paths(self.section, key) def get_runtime_lib_dirs(self, key='runtime_library_dirs'): path = self.get_paths(self.section, key) if path == ['']: path = [] return path def get_include_dirs(self, key='include_dirs'): return self.get_paths(self.section, key) def get_src_dirs(self, key='src_dirs'): return self.get_paths(self.section, key) def get_libs(self, key, default): try: libs = self.cp.get(self.section, key) except NoOptionError: if not default: return [] if is_string(default): return [default] return default return [b for b in [a.strip() for a in libs.split(',')] if b] def get_libraries(self, key='libraries'): if hasattr(self, '_lib_names'): return self.get_libs(key, default=self._lib_names) else: return self.get_libs(key, '') def library_extensions(self): c = customized_ccompiler() static_exts = [] if c.compiler_type != 'msvc': static_exts.append('.a') if sys.platform == 'win32': static_exts.append('.lib') if self.search_static_first: exts = static_exts + [so_ext] else: exts = [so_ext] + static_exts if sys.platform == 'cygwin': exts.append('.dll.a') if sys.platform == 'darwin': exts.append('.dylib') return exts def check_libs(self, lib_dirs, libs, opt_libs=[]): exts = self.library_extensions() info = None for ext in exts: info = self._check_libs(lib_dirs, libs, opt_libs, [ext]) if info is not None: break if not info: log.info(' libraries %s not found in %s', ','.join(libs), lib_dirs) return info def check_libs2(self, lib_dirs, libs, opt_libs=[]): exts = self.library_extensions() info = self._check_libs(lib_dirs, libs, opt_libs, exts) if not info: log.info(' libraries %s not found in %s', ','.join(libs), lib_dirs) return info def _find_lib(self, lib_dir, lib, exts): assert is_string(lib_dir) if sys.platform == 'win32': lib_prefixes = ['', 'lib'] else: lib_prefixes = ['lib'] for ext in exts: for prefix in lib_prefixes: p = self.combine_paths(lib_dir, prefix + lib + ext) if p: break if p: assert len(p) == 1 if ext == '.dll.a': lib += '.dll' if ext == '.lib': lib = prefix + lib return lib return False def _find_libs(self, lib_dirs, libs, exts): (found_dirs, found_libs) = ([], []) for lib in libs: for lib_dir in lib_dirs: found_lib = self._find_lib(lib_dir, lib, exts) if found_lib: found_libs.append(found_lib) if lib_dir not in found_dirs: found_dirs.append(lib_dir) break return (found_dirs, found_libs) def _check_libs(self, lib_dirs, libs, opt_libs, exts): if not is_sequence(lib_dirs): lib_dirs = [lib_dirs] (found_dirs, found_libs) = self._find_libs(lib_dirs, libs, exts) if len(found_libs) > 0 and len(found_libs) == len(libs): (opt_found_dirs, opt_found_libs) = self._find_libs(lib_dirs, opt_libs, exts) found_libs.extend(opt_found_libs) for lib_dir in opt_found_dirs: if lib_dir not in found_dirs: found_dirs.append(lib_dir) info = {'libraries': found_libs, 'library_dirs': found_dirs} return info else: return None def combine_paths(self, *args): return combine_paths(*args) class fft_opt_info(system_info): def calc_info(self): info = {} fftw_info = get_info('fftw3') or get_info('fftw2') or get_info('dfftw') djbfft_info = get_info('djbfft') if fftw_info: dict_append(info, **fftw_info) if djbfft_info: dict_append(info, **djbfft_info) self.set_info(**info) return class fftw_info(system_info): section = 'fftw' dir_env_var = 'FFTW' notfounderror = FFTWNotFoundError ver_info = [{'name': 'fftw3', 'libs': ['fftw3'], 'includes': ['fftw3.h'], 'macros': [('SCIPY_FFTW3_H', None)]}, {'name': 'fftw2', 'libs': ['rfftw', 'fftw'], 'includes': ['fftw.h', 'rfftw.h'], 'macros': [('SCIPY_FFTW_H', None)]}] def calc_ver_info(self, ver_param): lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() opt = self.get_option_single(self.section + '_libs', 'libraries') libs = self.get_libs(opt, ver_param['libs']) info = self.check_libs(lib_dirs, libs) if info is not None: flag = 0 for d in incl_dirs: if len(self.combine_paths(d, ver_param['includes'])) == len(ver_param['includes']): dict_append(info, include_dirs=[d]) flag = 1 break if flag: dict_append(info, define_macros=ver_param['macros']) else: info = None if info is not None: self.set_info(**info) return True else: log.info(' %s not found' % ver_param['name']) return False def calc_info(self): for i in self.ver_info: if self.calc_ver_info(i): break class fftw2_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' notfounderror = FFTWNotFoundError ver_info = [{'name': 'fftw2', 'libs': ['rfftw', 'fftw'], 'includes': ['fftw.h', 'rfftw.h'], 'macros': [('SCIPY_FFTW_H', None)]}] class fftw3_info(fftw_info): section = 'fftw3' dir_env_var = 'FFTW3' notfounderror = FFTWNotFoundError ver_info = [{'name': 'fftw3', 'libs': ['fftw3'], 'includes': ['fftw3.h'], 'macros': [('SCIPY_FFTW3_H', None)]}] class fftw3_armpl_info(fftw_info): section = 'fftw3' dir_env_var = 'ARMPL_DIR' notfounderror = FFTWNotFoundError ver_info = [{'name': 'fftw3', 'libs': ['armpl_lp64_mp'], 'includes': ['fftw3.h'], 'macros': [('SCIPY_FFTW3_H', None)]}] class dfftw_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name': 'dfftw', 'libs': ['drfftw', 'dfftw'], 'includes': ['dfftw.h', 'drfftw.h'], 'macros': [('SCIPY_DFFTW_H', None)]}] class sfftw_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name': 'sfftw', 'libs': ['srfftw', 'sfftw'], 'includes': ['sfftw.h', 'srfftw.h'], 'macros': [('SCIPY_SFFTW_H', None)]}] class fftw_threads_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name': 'fftw threads', 'libs': ['rfftw_threads', 'fftw_threads'], 'includes': ['fftw_threads.h', 'rfftw_threads.h'], 'macros': [('SCIPY_FFTW_THREADS_H', None)]}] class dfftw_threads_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name': 'dfftw threads', 'libs': ['drfftw_threads', 'dfftw_threads'], 'includes': ['dfftw_threads.h', 'drfftw_threads.h'], 'macros': [('SCIPY_DFFTW_THREADS_H', None)]}] class sfftw_threads_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name': 'sfftw threads', 'libs': ['srfftw_threads', 'sfftw_threads'], 'includes': ['sfftw_threads.h', 'srfftw_threads.h'], 'macros': [('SCIPY_SFFTW_THREADS_H', None)]}] class djbfft_info(system_info): section = 'djbfft' dir_env_var = 'DJBFFT' notfounderror = DJBFFTNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend(self.combine_paths(d, ['djbfft']) + [d]) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() info = None for d in lib_dirs: p = self.combine_paths(d, ['djbfft.a']) if p: info = {'extra_objects': p} break p = self.combine_paths(d, ['libdjbfft.a', 'libdjbfft' + so_ext]) if p: info = {'libraries': ['djbfft'], 'library_dirs': [d]} break if info is None: return for d in incl_dirs: if len(self.combine_paths(d, ['fftc8.h', 'fftfreq.h'])) == 2: dict_append(info, include_dirs=[d], define_macros=[('SCIPY_DJBFFT_H', None)]) self.set_info(**info) return return class mkl_info(system_info): section = 'mkl' dir_env_var = 'MKLROOT' _lib_mkl = ['mkl_rt'] def get_mkl_rootdir(self): mklroot = os.environ.get('MKLROOT', None) if mklroot is not None: return mklroot paths = os.environ.get('LD_LIBRARY_PATH', '').split(os.pathsep) ld_so_conf = '/etc/ld.so.conf' if os.path.isfile(ld_so_conf): with open(ld_so_conf) as f: for d in f: d = d.strip() if d: paths.append(d) intel_mkl_dirs = [] for path in paths: path_atoms = path.split(os.sep) for m in path_atoms: if m.startswith('mkl'): d = os.sep.join(path_atoms[:path_atoms.index(m) + 2]) intel_mkl_dirs.append(d) break for d in paths: dirs = glob(os.path.join(d, 'mkl', '*')) dirs += glob(os.path.join(d, 'mkl*')) for sub_dir in dirs: if os.path.isdir(os.path.join(sub_dir, 'lib')): return sub_dir return None def __init__(self): mklroot = self.get_mkl_rootdir() if mklroot is None: system_info.__init__(self) else: from .cpuinfo import cpu if cpu.is_Itanium(): plt = '64' elif cpu.is_Intel() and cpu.is_64bit(): plt = 'intel64' else: plt = '32' system_info.__init__(self, default_lib_dirs=[os.path.join(mklroot, 'lib', plt)], default_include_dirs=[os.path.join(mklroot, 'include')]) def calc_info(self): lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() opt = self.get_option_single('mkl_libs', 'libraries') mkl_libs = self.get_libs(opt, self._lib_mkl) info = self.check_libs2(lib_dirs, mkl_libs) if info is None: return dict_append(info, define_macros=[('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)], include_dirs=incl_dirs) if sys.platform == 'win32': pass else: dict_append(info, libraries=['pthread']) self.set_info(**info) class lapack_mkl_info(mkl_info): pass class blas_mkl_info(mkl_info): pass class ssl2_info(system_info): section = 'ssl2' dir_env_var = 'SSL2_DIR' _lib_ssl2 = ['fjlapackexsve'] def get_tcsds_rootdir(self): tcsdsroot = os.environ.get('TCSDS_PATH', None) if tcsdsroot is not None: return tcsdsroot return None def __init__(self): tcsdsroot = self.get_tcsds_rootdir() if tcsdsroot is None: system_info.__init__(self) else: system_info.__init__(self, default_lib_dirs=[os.path.join(tcsdsroot, 'lib64')], default_include_dirs=[os.path.join(tcsdsroot, 'clang-comp/include')]) def calc_info(self): tcsdsroot = self.get_tcsds_rootdir() lib_dirs = self.get_lib_dirs() if lib_dirs is None: lib_dirs = os.path.join(tcsdsroot, 'lib64') incl_dirs = self.get_include_dirs() if incl_dirs is None: incl_dirs = os.path.join(tcsdsroot, 'clang-comp/include') ssl2_libs = self.get_libs('ssl2_libs', self._lib_ssl2) info = self.check_libs2(lib_dirs, ssl2_libs) if info is None: return dict_append(info, define_macros=[('HAVE_CBLAS', None), ('HAVE_SSL2', 1)], include_dirs=incl_dirs) self.set_info(**info) class lapack_ssl2_info(ssl2_info): pass class blas_ssl2_info(ssl2_info): pass class armpl_info(system_info): section = 'armpl' dir_env_var = 'ARMPL_DIR' _lib_armpl = ['armpl_lp64_mp'] def calc_info(self): lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() armpl_libs = self.get_libs('armpl_libs', self._lib_armpl) info = self.check_libs2(lib_dirs, armpl_libs) if info is None: return dict_append(info, define_macros=[('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)], include_dirs=incl_dirs) self.set_info(**info) class lapack_armpl_info(armpl_info): pass class blas_armpl_info(armpl_info): pass class atlas_info(system_info): section = 'atlas' dir_env_var = 'ATLAS' _lib_names = ['f77blas', 'cblas'] if sys.platform[:7] == 'freebsd': _lib_atlas = ['atlas_r'] _lib_lapack = ['alapack_r'] else: _lib_atlas = ['atlas'] _lib_lapack = ['lapack'] notfounderror = AtlasNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend(self.combine_paths(d, ['atlas*', 'ATLAS*', 'sse', '3dnow', 'sse2']) + [d]) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): lib_dirs = self.get_lib_dirs() info = {} opt = self.get_option_single('atlas_libs', 'libraries') atlas_libs = self.get_libs(opt, self._lib_names + self._lib_atlas) lapack_libs = self.get_libs('lapack_libs', self._lib_lapack) atlas = None lapack = None atlas_1 = None for d in lib_dirs: atlas = self.check_libs2(d, atlas_libs, []) if atlas is not None: lib_dirs2 = [d] + self.combine_paths(d, ['atlas*', 'ATLAS*']) lapack = self.check_libs2(lib_dirs2, lapack_libs, []) if lapack is not None: break if atlas: atlas_1 = atlas log.info(self.__class__) if atlas is None: atlas = atlas_1 if atlas is None: return include_dirs = self.get_include_dirs() h = self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None] h = h[0] if h: h = os.path.dirname(h) dict_append(info, include_dirs=[h]) info['language'] = 'c' if lapack is not None: dict_append(info, **lapack) dict_append(info, **atlas) elif 'lapack_atlas' in atlas['libraries']: dict_append(info, **atlas) dict_append(info, define_macros=[('ATLAS_WITH_LAPACK_ATLAS', None)]) self.set_info(**info) return else: dict_append(info, **atlas) dict_append(info, define_macros=[('ATLAS_WITHOUT_LAPACK', None)]) message = textwrap.dedent('\n *********************************************************************\n Could not find lapack library within the ATLAS installation.\n *********************************************************************\n ') warnings.warn(message, stacklevel=2) self.set_info(**info) return lapack_dir = lapack['library_dirs'][0] lapack_name = lapack['libraries'][0] lapack_lib = None lib_prefixes = ['lib'] if sys.platform == 'win32': lib_prefixes.append('') for e in self.library_extensions(): for prefix in lib_prefixes: fn = os.path.join(lapack_dir, prefix + lapack_name + e) if os.path.exists(fn): lapack_lib = fn break if lapack_lib: break if lapack_lib is not None: sz = os.stat(lapack_lib)[6] if sz <= 4000 * 1024: message = textwrap.dedent('\n *********************************************************************\n Lapack library (from ATLAS) is probably incomplete:\n size of %s is %sk (expected >4000k)\n\n Follow the instructions in the KNOWN PROBLEMS section of the file\n numpy/INSTALL.txt.\n *********************************************************************\n ') % (lapack_lib, sz / 1024) warnings.warn(message, stacklevel=2) else: info['language'] = 'f77' (atlas_version, atlas_extra_info) = get_atlas_version(**atlas) dict_append(info, **atlas_extra_info) self.set_info(**info) class atlas_blas_info(atlas_info): _lib_names = ['f77blas', 'cblas'] def calc_info(self): lib_dirs = self.get_lib_dirs() info = {} opt = self.get_option_single('atlas_libs', 'libraries') atlas_libs = self.get_libs(opt, self._lib_names + self._lib_atlas) atlas = self.check_libs2(lib_dirs, atlas_libs, []) if atlas is None: return include_dirs = self.get_include_dirs() h = self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None] h = h[0] if h: h = os.path.dirname(h) dict_append(info, include_dirs=[h]) info['language'] = 'c' info['define_macros'] = [('HAVE_CBLAS', None)] (atlas_version, atlas_extra_info) = get_atlas_version(**atlas) dict_append(atlas, **atlas_extra_info) dict_append(info, **atlas) self.set_info(**info) return class atlas_threads_info(atlas_info): dir_env_var = ['PTATLAS', 'ATLAS'] _lib_names = ['ptf77blas', 'ptcblas'] class atlas_blas_threads_info(atlas_blas_info): dir_env_var = ['PTATLAS', 'ATLAS'] _lib_names = ['ptf77blas', 'ptcblas'] class lapack_atlas_info(atlas_info): _lib_names = ['lapack_atlas'] + atlas_info._lib_names class lapack_atlas_threads_info(atlas_threads_info): _lib_names = ['lapack_atlas'] + atlas_threads_info._lib_names class atlas_3_10_info(atlas_info): _lib_names = ['satlas'] _lib_atlas = _lib_names _lib_lapack = _lib_names class atlas_3_10_blas_info(atlas_3_10_info): _lib_names = ['satlas'] def calc_info(self): lib_dirs = self.get_lib_dirs() info = {} opt = self.get_option_single('atlas_lib', 'libraries') atlas_libs = self.get_libs(opt, self._lib_names) atlas = self.check_libs2(lib_dirs, atlas_libs, []) if atlas is None: return include_dirs = self.get_include_dirs() h = self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None] h = h[0] if h: h = os.path.dirname(h) dict_append(info, include_dirs=[h]) info['language'] = 'c' info['define_macros'] = [('HAVE_CBLAS', None)] (atlas_version, atlas_extra_info) = get_atlas_version(**atlas) dict_append(atlas, **atlas_extra_info) dict_append(info, **atlas) self.set_info(**info) return class atlas_3_10_threads_info(atlas_3_10_info): dir_env_var = ['PTATLAS', 'ATLAS'] _lib_names = ['tatlas'] _lib_atlas = _lib_names _lib_lapack = _lib_names class atlas_3_10_blas_threads_info(atlas_3_10_blas_info): dir_env_var = ['PTATLAS', 'ATLAS'] _lib_names = ['tatlas'] class lapack_atlas_3_10_info(atlas_3_10_info): pass class lapack_atlas_3_10_threads_info(atlas_3_10_threads_info): pass class lapack_info(system_info): section = 'lapack' dir_env_var = 'LAPACK' _lib_names = ['lapack'] notfounderror = LapackNotFoundError def calc_info(self): lib_dirs = self.get_lib_dirs() opt = self.get_option_single('lapack_libs', 'libraries') lapack_libs = self.get_libs(opt, self._lib_names) info = self.check_libs(lib_dirs, lapack_libs, []) if info is None: return info['language'] = 'f77' self.set_info(**info) class lapack_src_info(system_info): section = 'lapack_src' dir_env_var = 'LAPACK_SRC' notfounderror = LapackSrcNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['LAPACK*/SRC', 'SRC'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'dgesv.f')): src_dir = d break if not src_dir: return allaux = '\n ilaenv ieeeck lsame lsamen xerbla\n iparmq\n ' laux = '\n bdsdc bdsqr disna labad lacpy ladiv lae2 laebz laed0 laed1\n laed2 laed3 laed4 laed5 laed6 laed7 laed8 laed9 laeda laev2\n lagtf lagts lamch lamrg lanst lapy2 lapy3 larnv larrb larre\n larrf lartg laruv las2 lascl lasd0 lasd1 lasd2 lasd3 lasd4\n lasd5 lasd6 lasd7 lasd8 lasd9 lasda lasdq lasdt laset lasq1\n lasq2 lasq3 lasq4 lasq5 lasq6 lasr lasrt lassq lasv2 pttrf\n stebz stedc steqr sterf\n\n larra larrc larrd larr larrk larrj larrr laneg laisnan isnan\n lazq3 lazq4\n ' lasrc = '\n gbbrd gbcon gbequ gbrfs gbsv gbsvx gbtf2 gbtrf gbtrs gebak\n gebal gebd2 gebrd gecon geequ gees geesx geev geevx gegs gegv\n gehd2 gehrd gelq2 gelqf gels gelsd gelss gelsx gelsy geql2\n geqlf geqp3 geqpf geqr2 geqrf gerfs gerq2 gerqf gesc2 gesdd\n gesv gesvd gesvx getc2 getf2 getrf getri getrs ggbak ggbal\n gges ggesx ggev ggevx ggglm gghrd gglse ggqrf ggrqf ggsvd\n ggsvp gtcon gtrfs gtsv gtsvx gttrf gttrs gtts2 hgeqz hsein\n hseqr labrd lacon laein lags2 lagtm lahqr lahrd laic1 lals0\n lalsa lalsd langb lange langt lanhs lansb lansp lansy lantb\n lantp lantr lapll lapmt laqgb laqge laqp2 laqps laqsb laqsp\n laqsy lar1v lar2v larf larfb larfg larft larfx largv larrv\n lartv larz larzb larzt laswp lasyf latbs latdf latps latrd\n latrs latrz latzm lauu2 lauum pbcon pbequ pbrfs pbstf pbsv\n pbsvx pbtf2 pbtrf pbtrs pocon poequ porfs posv posvx potf2\n potrf potri potrs ppcon ppequ pprfs ppsv ppsvx pptrf pptri\n pptrs ptcon pteqr ptrfs ptsv ptsvx pttrs ptts2 spcon sprfs\n spsv spsvx sptrf sptri sptrs stegr stein sycon syrfs sysv\n sysvx sytf2 sytrf sytri sytrs tbcon tbrfs tbtrs tgevc tgex2\n tgexc tgsen tgsja tgsna tgsy2 tgsyl tpcon tprfs tptri tptrs\n trcon trevc trexc trrfs trsen trsna trsyl trti2 trtri trtrs\n tzrqf tzrzf\n\n lacn2 lahr2 stemr laqr0 laqr1 laqr2 laqr3 laqr4 laqr5\n ' sd_lasrc = '\n laexc lag2 lagv2 laln2 lanv2 laqtr lasy2 opgtr opmtr org2l\n org2r orgbr orghr orgl2 orglq orgql orgqr orgr2 orgrq orgtr\n orm2l orm2r ormbr ormhr orml2 ormlq ormql ormqr ormr2 ormr3\n ormrq ormrz ormtr rscl sbev sbevd sbevx sbgst sbgv sbgvd sbgvx\n sbtrd spev spevd spevx spgst spgv spgvd spgvx sptrd stev stevd\n stevr stevx syev syevd syevr syevx sygs2 sygst sygv sygvd\n sygvx sytd2 sytrd\n ' cz_lasrc = '\n bdsqr hbev hbevd hbevx hbgst hbgv hbgvd hbgvx hbtrd hecon heev\n heevd heevr heevx hegs2 hegst hegv hegvd hegvx herfs hesv\n hesvx hetd2 hetf2 hetrd hetrf hetri hetrs hpcon hpev hpevd\n hpevx hpgst hpgv hpgvd hpgvx hprfs hpsv hpsvx hptrd hptrf\n hptri hptrs lacgv lacp2 lacpy lacrm lacrt ladiv laed0 laed7\n laed8 laesy laev2 lahef lanhb lanhe lanhp lanht laqhb laqhe\n laqhp larcm larnv lartg lascl laset lasr lassq pttrf rot spmv\n spr stedc steqr symv syr ung2l ung2r ungbr unghr ungl2 unglq\n ungql ungqr ungr2 ungrq ungtr unm2l unm2r unmbr unmhr unml2\n unmlq unmql unmqr unmr2 unmr3 unmrq unmrz unmtr upgtr upmtr\n ' sclaux = laux + ' econd ' dzlaux = laux + ' secnd ' slasrc = lasrc + sd_lasrc dlasrc = lasrc + sd_lasrc clasrc = lasrc + cz_lasrc + ' srot srscl ' zlasrc = lasrc + cz_lasrc + ' drot drscl ' oclasrc = ' icmax1 scsum1 ' ozlasrc = ' izmax1 dzsum1 ' sources = ['s%s.f' % f for f in (sclaux + slasrc).split()] + ['d%s.f' % f for f in (dzlaux + dlasrc).split()] + ['c%s.f' % f for f in clasrc.split()] + ['z%s.f' % f for f in zlasrc.split()] + ['%s.f' % f for f in (allaux + oclasrc + ozlasrc).split()] sources = [os.path.join(src_dir, f) for f in sources] src_dir2 = os.path.join(src_dir, '..', 'INSTALL') sources += [os.path.join(src_dir2, p + 'lamch.f') for p in 'sdcz'] sources += [os.path.join(src_dir, p + 'larfp.f') for p in 'sdcz'] sources += [os.path.join(src_dir, 'ila' + p + 'lr.f') for p in 'sdcz'] sources += [os.path.join(src_dir, 'ila' + p + 'lc.f') for p in 'sdcz'] sources = [f for f in sources if os.path.isfile(f)] info = {'sources': sources, 'language': 'f77'} self.set_info(**info) atlas_version_c_text = '\n/* This file is generated from numpy/distutils/system_info.py */\nvoid ATL_buildinfo(void);\nint main(void) {\n ATL_buildinfo();\n return 0;\n}\n' _cached_atlas_version = {} def get_atlas_version(**config): libraries = config.get('libraries', []) library_dirs = config.get('library_dirs', []) key = (tuple(libraries), tuple(library_dirs)) if key in _cached_atlas_version: return _cached_atlas_version[key] c = cmd_config(Distribution()) atlas_version = None info = {} try: (s, o) = c.get_output(atlas_version_c_text, libraries=libraries, library_dirs=library_dirs) if s and re.search('undefined reference to `_gfortran', o, re.M): (s, o) = c.get_output(atlas_version_c_text, libraries=libraries + ['gfortran'], library_dirs=library_dirs) if not s: warnings.warn(textwrap.dedent('\n *****************************************************\n Linkage with ATLAS requires gfortran. Use\n\n python setup.py config_fc --fcompiler=gnu95 ...\n\n when building extension libraries that use ATLAS.\n Make sure that -lgfortran is used for C++ extensions.\n *****************************************************\n '), stacklevel=2) dict_append(info, language='f90', define_macros=[('ATLAS_REQUIRES_GFORTRAN', None)]) except Exception: for o in library_dirs: m = re.search('ATLAS_(?P\\d+[.]\\d+[.]\\d+)_', o) if m: atlas_version = m.group('version') if atlas_version is not None: break if atlas_version is None: atlas_version = os.environ.get('ATLAS_VERSION', None) if atlas_version: dict_append(info, define_macros=[('ATLAS_INFO', _c_string_literal(atlas_version))]) else: dict_append(info, define_macros=[('NO_ATLAS_INFO', -1)]) return (atlas_version or '?.?.?', info) if not s: m = re.search('ATLAS version (?P\\d+[.]\\d+[.]\\d+)', o) if m: atlas_version = m.group('version') if atlas_version is None: if re.search('undefined symbol: ATL_buildinfo', o, re.M): atlas_version = '3.2.1_pre3.3.6' else: log.info('Status: %d', s) log.info('Output: %s', o) elif atlas_version == '3.2.1_pre3.3.6': dict_append(info, define_macros=[('NO_ATLAS_INFO', -2)]) else: dict_append(info, define_macros=[('ATLAS_INFO', _c_string_literal(atlas_version))]) result = _cached_atlas_version[key] = (atlas_version, info) return result class lapack_opt_info(system_info): notfounderror = LapackNotFoundError lapack_order = ['armpl', 'mkl', 'ssl2', 'openblas', 'flame', 'accelerate', 'atlas', 'lapack'] order_env_var_name = 'NPY_LAPACK_ORDER' def _calc_info_armpl(self): info = get_info('lapack_armpl') if info: self.set_info(**info) return True return False def _calc_info_mkl(self): info = get_info('lapack_mkl') if info: self.set_info(**info) return True return False def _calc_info_ssl2(self): info = get_info('lapack_ssl2') if info: self.set_info(**info) return True return False def _calc_info_openblas(self): info = get_info('openblas_lapack') if info: self.set_info(**info) return True info = get_info('openblas_clapack') if info: self.set_info(**info) return True return False def _calc_info_flame(self): info = get_info('flame') if info: self.set_info(**info) return True return False def _calc_info_atlas(self): info = get_info('atlas_3_10_threads') if not info: info = get_info('atlas_3_10') if not info: info = get_info('atlas_threads') if not info: info = get_info('atlas') if info: l = info.get('define_macros', []) if ('ATLAS_WITH_LAPACK_ATLAS', None) in l or ('ATLAS_WITHOUT_LAPACK', None) in l: lapack_info = self._get_info_lapack() if not lapack_info: return False dict_append(info, **lapack_info) self.set_info(**info) return True return False def _calc_info_accelerate(self): info = get_info('accelerate') if info: self.set_info(**info) return True return False def _get_info_blas(self): info = get_info('blas_opt') if not info: warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=3) info_src = get_info('blas_src') if not info_src: warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=3) return {} dict_append(info, libraries=[('fblas_src', info_src)]) return info def _get_info_lapack(self): info = get_info('lapack') if not info: warnings.warn(LapackNotFoundError.__doc__ or '', stacklevel=3) info_src = get_info('lapack_src') if not info_src: warnings.warn(LapackSrcNotFoundError.__doc__ or '', stacklevel=3) return {} dict_append(info, libraries=[('flapack_src', info_src)]) return info def _calc_info_lapack(self): info = self._get_info_lapack() if info: info_blas = self._get_info_blas() dict_append(info, **info_blas) dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)]) self.set_info(**info) return True return False def _calc_info_from_envvar(self): info = {} info['language'] = 'f77' info['libraries'] = [] info['include_dirs'] = [] info['define_macros'] = [] info['extra_link_args'] = os.environ['NPY_LAPACK_LIBS'].split() self.set_info(**info) return True def _calc_info(self, name): return getattr(self, '_calc_info_{}'.format(name))() def calc_info(self): (lapack_order, unknown_order) = _parse_env_order(self.lapack_order, self.order_env_var_name) if len(unknown_order) > 0: raise ValueError('lapack_opt_info user defined LAPACK order has unacceptable values: {}'.format(unknown_order)) if 'NPY_LAPACK_LIBS' in os.environ: self._calc_info_from_envvar() return for lapack in lapack_order: if self._calc_info(lapack): return if 'lapack' not in lapack_order: warnings.warn(LapackNotFoundError.__doc__ or '', stacklevel=2) warnings.warn(LapackSrcNotFoundError.__doc__ or '', stacklevel=2) class _ilp64_opt_info_mixin: symbol_suffix = None symbol_prefix = None def _check_info(self, info): macros = dict(info.get('define_macros', [])) prefix = macros.get('BLAS_SYMBOL_PREFIX', '') suffix = macros.get('BLAS_SYMBOL_SUFFIX', '') if self.symbol_prefix not in (None, prefix): return False if self.symbol_suffix not in (None, suffix): return False return bool(info) class lapack_ilp64_opt_info(lapack_opt_info, _ilp64_opt_info_mixin): notfounderror = LapackILP64NotFoundError lapack_order = ['openblas64_', 'openblas_ilp64', 'accelerate'] order_env_var_name = 'NPY_LAPACK_ILP64_ORDER' def _calc_info(self, name): print('lapack_ilp64_opt_info._calc_info(name=%s)' % name) info = get_info(name + '_lapack') if self._check_info(info): self.set_info(**info) return True else: print('%s_lapack does not exist' % name) return False class lapack_ilp64_plain_opt_info(lapack_ilp64_opt_info): symbol_prefix = '' symbol_suffix = '' class lapack64__opt_info(lapack_ilp64_opt_info): symbol_prefix = '' symbol_suffix = '64_' class blas_opt_info(system_info): notfounderror = BlasNotFoundError blas_order = ['armpl', 'mkl', 'ssl2', 'blis', 'openblas', 'accelerate', 'atlas', 'blas'] order_env_var_name = 'NPY_BLAS_ORDER' def _calc_info_armpl(self): info = get_info('blas_armpl') if info: self.set_info(**info) return True return False def _calc_info_mkl(self): info = get_info('blas_mkl') if info: self.set_info(**info) return True return False def _calc_info_ssl2(self): info = get_info('blas_ssl2') if info: self.set_info(**info) return True return False def _calc_info_blis(self): info = get_info('blis') if info: self.set_info(**info) return True return False def _calc_info_openblas(self): info = get_info('openblas') if info: self.set_info(**info) return True return False def _calc_info_atlas(self): info = get_info('atlas_3_10_blas_threads') if not info: info = get_info('atlas_3_10_blas') if not info: info = get_info('atlas_blas_threads') if not info: info = get_info('atlas_blas') if info: self.set_info(**info) return True return False def _calc_info_accelerate(self): info = get_info('accelerate') if info: self.set_info(**info) return True return False def _calc_info_blas(self): warnings.warn(BlasOptNotFoundError.__doc__ or '', stacklevel=3) info = {} dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)]) blas = get_info('blas') if blas: dict_append(info, **blas) else: warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=3) blas_src = get_info('blas_src') if not blas_src: warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=3) return False dict_append(info, libraries=[('fblas_src', blas_src)]) self.set_info(**info) return True def _calc_info_from_envvar(self): info = {} info['language'] = 'f77' info['libraries'] = [] info['include_dirs'] = [] info['define_macros'] = [] info['extra_link_args'] = os.environ['NPY_BLAS_LIBS'].split() if 'NPY_CBLAS_LIBS' in os.environ: info['define_macros'].append(('HAVE_CBLAS', None)) info['extra_link_args'].extend(os.environ['NPY_CBLAS_LIBS'].split()) self.set_info(**info) return True def _calc_info(self, name): return getattr(self, '_calc_info_{}'.format(name))() def calc_info(self): (blas_order, unknown_order) = _parse_env_order(self.blas_order, self.order_env_var_name) if len(unknown_order) > 0: raise ValueError('blas_opt_info user defined BLAS order has unacceptable values: {}'.format(unknown_order)) if 'NPY_BLAS_LIBS' in os.environ: self._calc_info_from_envvar() return for blas in blas_order: if self._calc_info(blas): return if 'blas' not in blas_order: warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=2) warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=2) class blas_ilp64_opt_info(blas_opt_info, _ilp64_opt_info_mixin): notfounderror = BlasILP64NotFoundError blas_order = ['openblas64_', 'openblas_ilp64', 'accelerate'] order_env_var_name = 'NPY_BLAS_ILP64_ORDER' def _calc_info(self, name): info = get_info(name) if self._check_info(info): self.set_info(**info) return True return False class blas_ilp64_plain_opt_info(blas_ilp64_opt_info): symbol_prefix = '' symbol_suffix = '' class blas64__opt_info(blas_ilp64_opt_info): symbol_prefix = '' symbol_suffix = '64_' class cblas_info(system_info): section = 'cblas' dir_env_var = 'CBLAS' _lib_names = [] notfounderror = BlasNotFoundError class blas_info(system_info): section = 'blas' dir_env_var = 'BLAS' _lib_names = ['blas'] notfounderror = BlasNotFoundError def calc_info(self): lib_dirs = self.get_lib_dirs() opt = self.get_option_single('blas_libs', 'libraries') blas_libs = self.get_libs(opt, self._lib_names) info = self.check_libs(lib_dirs, blas_libs, []) if info is None: return else: info['include_dirs'] = self.get_include_dirs() if platform.system() == 'Windows': info['language'] = 'f77' cblas_info_obj = cblas_info() cblas_opt = cblas_info_obj.get_option_single('cblas_libs', 'libraries') cblas_libs = cblas_info_obj.get_libs(cblas_opt, None) if cblas_libs: info['libraries'] = cblas_libs + blas_libs info['define_macros'] = [('HAVE_CBLAS', None)] else: lib = self.get_cblas_libs(info) if lib is not None: info['language'] = 'c' info['libraries'] = lib info['define_macros'] = [('HAVE_CBLAS', None)] self.set_info(**info) def get_cblas_libs(self, info): c = customized_ccompiler() tmpdir = tempfile.mkdtemp() s = textwrap.dedent(' #include \n int main(int argc, const char *argv[])\n {\n double a[4] = {1,2,3,4};\n double b[4] = {5,6,7,8};\n return cblas_ddot(4, a, 1, b, 1) > 10;\n }') src = os.path.join(tmpdir, 'source.c') try: with open(src, 'w') as f: f.write(s) try: obj = c.compile([src], output_dir=tmpdir, include_dirs=self.get_include_dirs()) except (distutils.ccompiler.CompileError, distutils.ccompiler.LinkError): return None for libs in [info['libraries'], ['cblas'] + info['libraries'], ['blas'] + info['libraries'], ['cblas'], ['blas']]: try: c.link_executable(obj, os.path.join(tmpdir, 'a.out'), libraries=libs, library_dirs=info['library_dirs'], extra_postargs=info.get('extra_link_args', [])) return libs except distutils.ccompiler.LinkError: pass finally: shutil.rmtree(tmpdir) return None class openblas_info(blas_info): section = 'openblas' dir_env_var = 'OPENBLAS' _lib_names = ['openblas'] _require_symbols = [] notfounderror = BlasNotFoundError @property def symbol_prefix(self): try: return self.cp.get(self.section, 'symbol_prefix') except NoOptionError: return '' @property def symbol_suffix(self): try: return self.cp.get(self.section, 'symbol_suffix') except NoOptionError: return '' def _calc_info(self): c = customized_ccompiler() lib_dirs = self.get_lib_dirs() opt = self.get_option_single('openblas_libs', 'libraries') openblas_libs = self.get_libs(opt, self._lib_names) info = self.check_libs(lib_dirs, openblas_libs, []) if c.compiler_type == 'msvc' and info is None: from numpy.distutils.fcompiler import new_fcompiler f = new_fcompiler(c_compiler=c) if f and f.compiler_type == 'gnu95': info = self.check_msvc_gfortran_libs(lib_dirs, openblas_libs) skip_symbol_check = True elif info: skip_symbol_check = False info['language'] = 'c' if info is None: return None extra_info = self.calc_extra_info() dict_append(info, **extra_info) if not (skip_symbol_check or self.check_symbols(info)): return None info['define_macros'] = [('HAVE_CBLAS', None)] if self.symbol_prefix: info['define_macros'] += [('BLAS_SYMBOL_PREFIX', self.symbol_prefix)] if self.symbol_suffix: info['define_macros'] += [('BLAS_SYMBOL_SUFFIX', self.symbol_suffix)] return info def calc_info(self): info = self._calc_info() if info is not None: self.set_info(**info) def check_msvc_gfortran_libs(self, library_dirs, libraries): library_paths = [] for library in libraries: for library_dir in library_dirs: fullpath = os.path.join(library_dir, library + '.a') if os.path.isfile(fullpath): library_paths.append(fullpath) break else: return None basename = self.__class__.__name__ tmpdir = os.path.join(os.getcwd(), 'build', basename) if not os.path.isdir(tmpdir): os.makedirs(tmpdir) info = {'library_dirs': [tmpdir], 'libraries': [basename], 'language': 'f77'} fake_lib_file = os.path.join(tmpdir, basename + '.fobjects') fake_clib_file = os.path.join(tmpdir, basename + '.cobjects') with open(fake_lib_file, 'w') as f: f.write('\n'.join(library_paths)) with open(fake_clib_file, 'w') as f: pass return info def check_symbols(self, info): res = False c = customized_ccompiler() tmpdir = tempfile.mkdtemp() prototypes = '\n'.join(('void %s%s%s();' % (self.symbol_prefix, symbol_name, self.symbol_suffix) for symbol_name in self._require_symbols)) calls = '\n'.join(('%s%s%s();' % (self.symbol_prefix, symbol_name, self.symbol_suffix) for symbol_name in self._require_symbols)) s = textwrap.dedent(' %(prototypes)s\n int main(int argc, const char *argv[])\n {\n %(calls)s\n return 0;\n }') % dict(prototypes=prototypes, calls=calls) src = os.path.join(tmpdir, 'source.c') out = os.path.join(tmpdir, 'a.out') try: extra_args = info['extra_link_args'] except Exception: extra_args = [] try: with open(src, 'w') as f: f.write(s) obj = c.compile([src], output_dir=tmpdir) try: c.link_executable(obj, out, libraries=info['libraries'], library_dirs=info['library_dirs'], extra_postargs=extra_args) res = True except distutils.ccompiler.LinkError: res = False finally: shutil.rmtree(tmpdir) return res class openblas_lapack_info(openblas_info): section = 'openblas' dir_env_var = 'OPENBLAS' _lib_names = ['openblas'] _require_symbols = ['zungqr_'] notfounderror = BlasNotFoundError class openblas_clapack_info(openblas_lapack_info): _lib_names = ['openblas', 'lapack'] class openblas_ilp64_info(openblas_info): section = 'openblas_ilp64' dir_env_var = 'OPENBLAS_ILP64' _lib_names = ['openblas64'] _require_symbols = ['dgemm_', 'cblas_dgemm'] notfounderror = BlasILP64NotFoundError def _calc_info(self): info = super()._calc_info() if info is not None: info['define_macros'] += [('HAVE_BLAS_ILP64', None)] return info class openblas_ilp64_lapack_info(openblas_ilp64_info): _require_symbols = ['dgemm_', 'cblas_dgemm', 'zungqr_', 'LAPACKE_zungqr'] def _calc_info(self): info = super()._calc_info() if info: info['define_macros'] += [('HAVE_LAPACKE', None)] return info class openblas64__info(openblas_ilp64_info): section = 'openblas64_' dir_env_var = 'OPENBLAS64_' _lib_names = ['openblas64_'] symbol_suffix = '64_' symbol_prefix = '' class openblas64__lapack_info(openblas_ilp64_lapack_info, openblas64__info): pass class blis_info(blas_info): section = 'blis' dir_env_var = 'BLIS' _lib_names = ['blis'] notfounderror = BlasNotFoundError def calc_info(self): lib_dirs = self.get_lib_dirs() opt = self.get_option_single('blis_libs', 'libraries') blis_libs = self.get_libs(opt, self._lib_names) info = self.check_libs2(lib_dirs, blis_libs, []) if info is None: return incl_dirs = self.get_include_dirs() dict_append(info, language='c', define_macros=[('HAVE_CBLAS', None)], include_dirs=incl_dirs) self.set_info(**info) class flame_info(system_info): section = 'flame' _lib_names = ['flame'] notfounderror = FlameNotFoundError def check_embedded_lapack(self, info): c = customized_ccompiler() tmpdir = tempfile.mkdtemp() s = textwrap.dedent(' void zungqr_();\n int main(int argc, const char *argv[])\n {\n zungqr_();\n return 0;\n }') src = os.path.join(tmpdir, 'source.c') out = os.path.join(tmpdir, 'a.out') extra_args = info.get('extra_link_args', []) try: with open(src, 'w') as f: f.write(s) obj = c.compile([src], output_dir=tmpdir) try: c.link_executable(obj, out, libraries=info['libraries'], library_dirs=info['library_dirs'], extra_postargs=extra_args) return True except distutils.ccompiler.LinkError: return False finally: shutil.rmtree(tmpdir) def calc_info(self): lib_dirs = self.get_lib_dirs() flame_libs = self.get_libs('libraries', self._lib_names) info = self.check_libs2(lib_dirs, flame_libs, []) if info is None: return extra_info = self.calc_extra_info() dict_append(info, **extra_info) if self.check_embedded_lapack(info): self.set_info(**info) else: blas_info = get_info('blas_opt') if not blas_info: return for key in blas_info: if isinstance(blas_info[key], list): info[key] = info.get(key, []) + blas_info[key] elif isinstance(blas_info[key], tuple): info[key] = info.get(key, ()) + blas_info[key] else: info[key] = info.get(key, '') + blas_info[key] if self.check_embedded_lapack(info): self.set_info(**info) class accelerate_info(system_info): section = 'accelerate' _lib_names = ['accelerate', 'veclib'] notfounderror = BlasNotFoundError def calc_info(self): libraries = os.environ.get('ACCELERATE') if libraries: libraries = [libraries] else: libraries = self.get_libs('libraries', self._lib_names) libraries = [lib.strip().lower() for lib in libraries] if sys.platform == 'darwin' and (not os.getenv('_PYTHON_HOST_PLATFORM', None)): args = [] link_args = [] if get_platform()[-4:] == 'i386' or 'intel' in get_platform() or 'x86_64' in get_platform() or ('i386' in platform.platform()): intel = 1 else: intel = 0 if os.path.exists('/System/Library/Frameworks/Accelerate.framework/') and 'accelerate' in libraries: if intel: args.extend(['-msse3']) args.extend(['-I/System/Library/Frameworks/vecLib.framework/Headers']) link_args.extend(['-Wl,-framework', '-Wl,Accelerate']) elif os.path.exists('/System/Library/Frameworks/vecLib.framework/') and 'veclib' in libraries: if intel: args.extend(['-msse3']) args.extend(['-I/System/Library/Frameworks/vecLib.framework/Headers']) link_args.extend(['-Wl,-framework', '-Wl,vecLib']) if args: macros = [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None), ('ACCELERATE_NEW_LAPACK', None)] if os.getenv('NPY_USE_BLAS_ILP64', None): print('Setting HAVE_BLAS_ILP64') macros += [('HAVE_BLAS_ILP64', None), ('ACCELERATE_LAPACK_ILP64', None)] self.set_info(extra_compile_args=args, extra_link_args=link_args, define_macros=macros) return class accelerate_lapack_info(accelerate_info): def _calc_info(self): return super()._calc_info() class blas_src_info(system_info): section = 'blas_src' dir_env_var = 'BLAS_SRC' notfounderror = BlasSrcNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['blas'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'daxpy.f')): src_dir = d break if not src_dir: return blas1 = '\n caxpy csscal dnrm2 dzasum saxpy srotg zdotc ccopy cswap drot\n dznrm2 scasum srotm zdotu cdotc dasum drotg icamax scnrm2\n srotmg zdrot cdotu daxpy drotm idamax scopy sscal zdscal crotg\n dcabs1 drotmg isamax sdot sswap zrotg cscal dcopy dscal izamax\n snrm2 zaxpy zscal csrot ddot dswap sasum srot zcopy zswap\n scabs1\n ' blas2 = '\n cgbmv chpmv ctrsv dsymv dtrsv sspr2 strmv zhemv ztpmv cgemv\n chpr dgbmv dsyr lsame ssymv strsv zher ztpsv cgerc chpr2 dgemv\n dsyr2 sgbmv ssyr xerbla zher2 ztrmv cgeru ctbmv dger dtbmv\n sgemv ssyr2 zgbmv zhpmv ztrsv chbmv ctbsv dsbmv dtbsv sger\n stbmv zgemv zhpr chemv ctpmv dspmv dtpmv ssbmv stbsv zgerc\n zhpr2 cher ctpsv dspr dtpsv sspmv stpmv zgeru ztbmv cher2\n ctrmv dspr2 dtrmv sspr stpsv zhbmv ztbsv\n ' blas3 = '\n cgemm csymm ctrsm dsyrk sgemm strmm zhemm zsyr2k chemm csyr2k\n dgemm dtrmm ssymm strsm zher2k zsyrk cher2k csyrk dsymm dtrsm\n ssyr2k zherk ztrmm cherk ctrmm dsyr2k ssyrk zgemm zsymm ztrsm\n ' sources = [os.path.join(src_dir, f + '.f') for f in (blas1 + blas2 + blas3).split()] sources = [f for f in sources if os.path.isfile(f)] info = {'sources': sources, 'language': 'f77'} self.set_info(**info) class x11_info(system_info): section = 'x11' notfounderror = X11NotFoundError _lib_names = ['X11'] def __init__(self): system_info.__init__(self, default_lib_dirs=default_x11_lib_dirs, default_include_dirs=default_x11_include_dirs) def calc_info(self): if sys.platform in ['win32']: return lib_dirs = self.get_lib_dirs() include_dirs = self.get_include_dirs() opt = self.get_option_single('x11_libs', 'libraries') x11_libs = self.get_libs(opt, self._lib_names) info = self.check_libs(lib_dirs, x11_libs, []) if info is None: return inc_dir = None for d in include_dirs: if self.combine_paths(d, 'X11/X.h'): inc_dir = d break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir]) self.set_info(**info) class _numpy_info(system_info): section = 'Numeric' modulename = 'Numeric' notfounderror = NumericNotFoundError def __init__(self): include_dirs = [] try: module = __import__(self.modulename) prefix = [] for name in module.__file__.split(os.sep): if name == 'lib': break prefix.append(name) try: include_dirs.append(getattr(module, 'get_include')()) except AttributeError: pass include_dirs.append(sysconfig.get_path('include')) except ImportError: pass py_incl_dir = sysconfig.get_path('include') include_dirs.append(py_incl_dir) py_pincl_dir = sysconfig.get_path('platinclude') if py_pincl_dir not in include_dirs: include_dirs.append(py_pincl_dir) for d in default_include_dirs: d = os.path.join(d, os.path.basename(py_incl_dir)) if d not in include_dirs: include_dirs.append(d) system_info.__init__(self, default_lib_dirs=[], default_include_dirs=include_dirs) def calc_info(self): try: module = __import__(self.modulename) except ImportError: return info = {} macros = [] for v in ['__version__', 'version']: vrs = getattr(module, v, None) if vrs is None: continue macros = [(self.modulename.upper() + '_VERSION', _c_string_literal(vrs)), (self.modulename.upper(), None)] break dict_append(info, define_macros=macros) include_dirs = self.get_include_dirs() inc_dir = None for d in include_dirs: if self.combine_paths(d, os.path.join(self.modulename, 'arrayobject.h')): inc_dir = d break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir]) if info: self.set_info(**info) return class numarray_info(_numpy_info): section = 'numarray' modulename = 'numarray' class Numeric_info(_numpy_info): section = 'Numeric' modulename = 'Numeric' class numpy_info(_numpy_info): section = 'numpy' modulename = 'numpy' class numerix_info(system_info): section = 'numerix' def calc_info(self): which = (None, None) if os.getenv('NUMERIX'): which = (os.getenv('NUMERIX'), 'environment var') if which[0] is None: which = ('numpy', 'defaulted') try: import numpy which = ('numpy', 'defaulted') except ImportError as e: msg1 = str(e) try: import Numeric which = ('numeric', 'defaulted') except ImportError as e: msg2 = str(e) try: import numarray which = ('numarray', 'defaulted') except ImportError as e: msg3 = str(e) log.info(msg1) log.info(msg2) log.info(msg3) which = (which[0].strip().lower(), which[1]) if which[0] not in ['numeric', 'numarray', 'numpy']: raise ValueError("numerix selector must be either 'Numeric' or 'numarray' or 'numpy' but the value obtained from the %s was '%s'." % (which[1], which[0])) os.environ['NUMERIX'] = which[0] self.set_info(**get_info(which[0])) class f2py_info(system_info): def calc_info(self): try: import numpy.f2py as f2py except ImportError: return f2py_dir = os.path.join(os.path.dirname(f2py.__file__), 'src') self.set_info(sources=[os.path.join(f2py_dir, 'fortranobject.c')], include_dirs=[f2py_dir]) return class boost_python_info(system_info): section = 'boost_python' dir_env_var = 'BOOST' def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['boost*'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'libs', 'python', 'src', 'module.cpp')): src_dir = d break if not src_dir: return py_incl_dirs = [sysconfig.get_path('include')] py_pincl_dir = sysconfig.get_path('platinclude') if py_pincl_dir not in py_incl_dirs: py_incl_dirs.append(py_pincl_dir) srcs_dir = os.path.join(src_dir, 'libs', 'python', 'src') bpl_srcs = glob(os.path.join(srcs_dir, '*.cpp')) bpl_srcs += glob(os.path.join(srcs_dir, '*', '*.cpp')) info = {'libraries': [('boost_python_src', {'include_dirs': [src_dir] + py_incl_dirs, 'sources': bpl_srcs})], 'include_dirs': [src_dir]} if info: self.set_info(**info) return class agg2_info(system_info): section = 'agg2' dir_env_var = 'AGG2' def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['agg2*'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'src', 'agg_affine_matrix.cpp')): src_dir = d break if not src_dir: return if sys.platform == 'win32': agg2_srcs = glob(os.path.join(src_dir, 'src', 'platform', 'win32', 'agg_win32_bmp.cpp')) else: agg2_srcs = glob(os.path.join(src_dir, 'src', '*.cpp')) agg2_srcs += [os.path.join(src_dir, 'src', 'platform', 'X11', 'agg_platform_support.cpp')] info = {'libraries': [('agg2_src', {'sources': agg2_srcs, 'include_dirs': [os.path.join(src_dir, 'include')]})], 'include_dirs': [os.path.join(src_dir, 'include')]} if info: self.set_info(**info) return class _pkg_config_info(system_info): section = None config_env_var = 'PKG_CONFIG' default_config_exe = 'pkg-config' append_config_exe = '' version_macro_name = None release_macro_name = None version_flag = '--modversion' cflags_flag = '--cflags' def get_config_exe(self): if self.config_env_var in os.environ: return os.environ[self.config_env_var] return self.default_config_exe def get_config_output(self, config_exe, option): cmd = config_exe + ' ' + self.append_config_exe + ' ' + option try: o = subprocess.check_output(cmd) except (OSError, subprocess.CalledProcessError): pass else: o = filepath_from_subprocess_output(o) return o def calc_info(self): config_exe = find_executable(self.get_config_exe()) if not config_exe: log.warn('File not found: %s. Cannot determine %s info.' % (config_exe, self.section)) return info = {} macros = [] libraries = [] library_dirs = [] include_dirs = [] extra_link_args = [] extra_compile_args = [] version = self.get_config_output(config_exe, self.version_flag) if version: macros.append((self.__class__.__name__.split('.')[-1].upper(), _c_string_literal(version))) if self.version_macro_name: macros.append((self.version_macro_name + '_%s' % version.replace('.', '_'), None)) if self.release_macro_name: release = self.get_config_output(config_exe, '--release') if release: macros.append((self.release_macro_name + '_%s' % release.replace('.', '_'), None)) opts = self.get_config_output(config_exe, '--libs') if opts: for opt in opts.split(): if opt[:2] == '-l': libraries.append(opt[2:]) elif opt[:2] == '-L': library_dirs.append(opt[2:]) else: extra_link_args.append(opt) opts = self.get_config_output(config_exe, self.cflags_flag) if opts: for opt in opts.split(): if opt[:2] == '-I': include_dirs.append(opt[2:]) elif opt[:2] == '-D': if '=' in opt: (n, v) = opt[2:].split('=') macros.append((n, v)) else: macros.append((opt[2:], None)) else: extra_compile_args.append(opt) if macros: dict_append(info, define_macros=macros) if libraries: dict_append(info, libraries=libraries) if library_dirs: dict_append(info, library_dirs=library_dirs) if include_dirs: dict_append(info, include_dirs=include_dirs) if extra_link_args: dict_append(info, extra_link_args=extra_link_args) if extra_compile_args: dict_append(info, extra_compile_args=extra_compile_args) if info: self.set_info(**info) return class wx_info(_pkg_config_info): section = 'wx' config_env_var = 'WX_CONFIG' default_config_exe = 'wx-config' append_config_exe = '' version_macro_name = 'WX_VERSION' release_macro_name = 'WX_RELEASE' version_flag = '--version' cflags_flag = '--cxxflags' class gdk_pixbuf_xlib_2_info(_pkg_config_info): section = 'gdk_pixbuf_xlib_2' append_config_exe = 'gdk-pixbuf-xlib-2.0' version_macro_name = 'GDK_PIXBUF_XLIB_VERSION' class gdk_pixbuf_2_info(_pkg_config_info): section = 'gdk_pixbuf_2' append_config_exe = 'gdk-pixbuf-2.0' version_macro_name = 'GDK_PIXBUF_VERSION' class gdk_x11_2_info(_pkg_config_info): section = 'gdk_x11_2' append_config_exe = 'gdk-x11-2.0' version_macro_name = 'GDK_X11_VERSION' class gdk_2_info(_pkg_config_info): section = 'gdk_2' append_config_exe = 'gdk-2.0' version_macro_name = 'GDK_VERSION' class gdk_info(_pkg_config_info): section = 'gdk' append_config_exe = 'gdk' version_macro_name = 'GDK_VERSION' class gtkp_x11_2_info(_pkg_config_info): section = 'gtkp_x11_2' append_config_exe = 'gtk+-x11-2.0' version_macro_name = 'GTK_X11_VERSION' class gtkp_2_info(_pkg_config_info): section = 'gtkp_2' append_config_exe = 'gtk+-2.0' version_macro_name = 'GTK_VERSION' class xft_info(_pkg_config_info): section = 'xft' append_config_exe = 'xft' version_macro_name = 'XFT_VERSION' class freetype2_info(_pkg_config_info): section = 'freetype2' append_config_exe = 'freetype2' version_macro_name = 'FREETYPE2_VERSION' class amd_info(system_info): section = 'amd' dir_env_var = 'AMD' _lib_names = ['amd'] def calc_info(self): lib_dirs = self.get_lib_dirs() opt = self.get_option_single('amd_libs', 'libraries') amd_libs = self.get_libs(opt, self._lib_names) info = self.check_libs(lib_dirs, amd_libs, []) if info is None: return include_dirs = self.get_include_dirs() inc_dir = None for d in include_dirs: p = self.combine_paths(d, 'amd.h') if p: inc_dir = os.path.dirname(p[0]) break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir], define_macros=[('SCIPY_AMD_H', None)], swig_opts=['-I' + inc_dir]) self.set_info(**info) return class umfpack_info(system_info): section = 'umfpack' dir_env_var = 'UMFPACK' notfounderror = UmfpackNotFoundError _lib_names = ['umfpack'] def calc_info(self): lib_dirs = self.get_lib_dirs() opt = self.get_option_single('umfpack_libs', 'libraries') umfpack_libs = self.get_libs(opt, self._lib_names) info = self.check_libs(lib_dirs, umfpack_libs, []) if info is None: return include_dirs = self.get_include_dirs() inc_dir = None for d in include_dirs: p = self.combine_paths(d, ['', 'umfpack'], 'umfpack.h') if p: inc_dir = os.path.dirname(p[0]) break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir], define_macros=[('SCIPY_UMFPACK_H', None)], swig_opts=['-I' + inc_dir]) dict_append(info, **get_info('amd')) self.set_info(**info) return def combine_paths(*args, **kws): r = [] for a in args: if not a: continue if is_string(a): a = [a] r.append(a) args = r if not args: return [] if len(args) == 1: result = reduce(lambda a, b: a + b, map(glob, args[0]), []) elif len(args) == 2: result = [] for a0 in args[0]: for a1 in args[1]: result.extend(glob(os.path.join(a0, a1))) else: result = combine_paths(*combine_paths(args[0], args[1]) + args[2:]) log.debug('(paths: %s)', ','.join(result)) return result language_map = {'c': 0, 'c++': 1, 'f77': 2, 'f90': 3} inv_language_map = {0: 'c', 1: 'c++', 2: 'f77', 3: 'f90'} def dict_append(d, **kws): languages = [] for (k, v) in kws.items(): if k == 'language': languages.append(v) continue if k in d: if k in ['library_dirs', 'include_dirs', 'extra_compile_args', 'extra_link_args', 'runtime_library_dirs', 'define_macros']: [d[k].append(vv) for vv in v if vv not in d[k]] else: d[k].extend(v) else: d[k] = v if languages: l = inv_language_map[max([language_map.get(l, 0) for l in languages])] d['language'] = l return def parseCmdLine(argv=(None,)): import optparse parser = optparse.OptionParser('usage: %prog [-v] [info objs]') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='be verbose and print more messages') (opts, args) = parser.parse_args(args=argv[1:]) return (opts, args) def show_all(argv=None): import inspect if argv is None: argv = sys.argv (opts, args) = parseCmdLine(argv) if opts.verbose: log.set_threshold(log.DEBUG) else: log.set_threshold(log.INFO) show_only = [] for n in args: if n[-5:] != '_info': n = n + '_info' show_only.append(n) show_all = not show_only _gdict_ = globals().copy() for (name, c) in _gdict_.items(): if not inspect.isclass(c): continue if not issubclass(c, system_info) or c is system_info: continue if not show_all: if name not in show_only: continue del show_only[show_only.index(name)] conf = c() conf.verbosity = 2 conf.get_info() if show_only: log.info('Info classes not defined: %s', ','.join(show_only)) if __name__ == '__main__': show_all() # File: numpy-main/numpy/distutils/unixccompiler.py """""" import os import sys import subprocess import shlex from distutils.errors import CompileError, DistutilsExecError, LibError from distutils.unixccompiler import UnixCCompiler from numpy.distutils.ccompiler import replace_method from numpy.distutils.misc_util import _commandline_dep_string from numpy.distutils import log def UnixCCompiler__compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): ccomp = self.compiler_so if ccomp[0] == 'aCC': if '-Ae' in ccomp: ccomp.remove('-Ae') if '-Aa' in ccomp: ccomp.remove('-Aa') ccomp += ['-AA'] self.compiler_so = ccomp if 'OPT' in os.environ: from sysconfig import get_config_vars opt = shlex.join(shlex.split(os.environ['OPT'])) gcv_opt = shlex.join(shlex.split(get_config_vars('OPT')[0])) ccomp_s = shlex.join(self.compiler_so) if opt not in ccomp_s: ccomp_s = ccomp_s.replace(gcv_opt, opt) self.compiler_so = shlex.split(ccomp_s) llink_s = shlex.join(self.linker_so) if opt not in llink_s: self.linker_so = self.linker_so + shlex.split(opt) display = '%s: %s' % (os.path.basename(self.compiler_so[0]), src) if getattr(self, '_auto_depends', False): deps = ['-MMD', '-MF', obj + '.d'] else: deps = [] try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + deps + extra_postargs, display=display) except DistutilsExecError as e: msg = str(e) raise CompileError(msg) from None if deps: if sys.platform == 'zos': subprocess.check_output(['chtag', '-tc', 'IBM1047', obj + '.d']) with open(obj + '.d', 'a') as f: f.write(_commandline_dep_string(cc_args, extra_postargs, pp_opts)) replace_method(UnixCCompiler, '_compile', UnixCCompiler__compile) def UnixCCompiler_create_static_lib(self, objects, output_libname, output_dir=None, debug=0, target_lang=None): (objects, output_dir) = self._fix_object_args(objects, output_dir) output_filename = self.library_filename(output_libname, output_dir=output_dir) if self._need_link(objects, output_filename): try: os.unlink(output_filename) except OSError: pass self.mkpath(os.path.dirname(output_filename)) tmp_objects = objects + self.objects while tmp_objects: objects = tmp_objects[:50] tmp_objects = tmp_objects[50:] display = '%s: adding %d object files to %s' % (os.path.basename(self.archiver[0]), len(objects), output_filename) self.spawn(self.archiver + [output_filename] + objects, display=display) if self.ranlib: display = '%s:@ %s' % (os.path.basename(self.ranlib[0]), output_filename) try: self.spawn(self.ranlib + [output_filename], display=display) except DistutilsExecError as e: msg = str(e) raise LibError(msg) from None else: log.debug('skipping %s (up-to-date)', output_filename) return replace_method(UnixCCompiler, 'create_static_lib', UnixCCompiler_create_static_lib) # File: numpy-main/numpy/doc/ufuncs.py """""" # File: numpy-main/numpy/dtypes.py """""" __all__ = [] def _add_dtype_helper(DType, alias): from numpy import dtypes setattr(dtypes, DType.__name__, DType) __all__.append(DType.__name__) if alias: alias = alias.removeprefix('numpy.dtypes.') setattr(dtypes, alias, DType) __all__.append(alias) # File: numpy-main/numpy/exceptions.py """""" __all__ = ['ComplexWarning', 'VisibleDeprecationWarning', 'ModuleDeprecationWarning', 'TooHardError', 'AxisError', 'DTypePromotionError'] if '_is_loaded' in globals(): raise RuntimeError('Reloading numpy._globals is not allowed') _is_loaded = True class ComplexWarning(RuntimeWarning): pass class ModuleDeprecationWarning(DeprecationWarning): pass class VisibleDeprecationWarning(UserWarning): pass class RankWarning(RuntimeWarning): pass class TooHardError(RuntimeError): pass class AxisError(ValueError, IndexError): __slots__ = ('axis', 'ndim', '_msg') def __init__(self, axis, ndim=None, msg_prefix=None): if ndim is msg_prefix is None: self._msg = axis self.axis = None self.ndim = None else: self._msg = msg_prefix self.axis = axis self.ndim = ndim def __str__(self): axis = self.axis ndim = self.ndim if axis is ndim is None: return self._msg else: msg = f'axis {axis} is out of bounds for array of dimension {ndim}' if self._msg is not None: msg = f'{self._msg}: {msg}' return msg class DTypePromotionError(TypeError): pass # File: numpy-main/numpy/f2py/__init__.py """""" __all__ = ['run_main', 'get_include'] import sys import subprocess import os import warnings from numpy.exceptions import VisibleDeprecationWarning from . import f2py2e from . import diagnose run_main = f2py2e.run_main main = f2py2e.main def get_include(): return os.path.join(os.path.dirname(__file__), 'src') def __getattr__(attr): if attr == 'test': from numpy._pytesttester import PytestTester test = PytestTester(__name__) return test else: raise AttributeError('module {!r} has no attribute {!r}'.format(__name__, attr)) def __dir__(): return list(globals().keys() | {'test'}) # File: numpy-main/numpy/f2py/_backends/_backend.py from __future__ import annotations from abc import ABC, abstractmethod class Backend(ABC): def __init__(self, modulename, sources, extra_objects, build_dir, include_dirs, library_dirs, libraries, define_macros, undef_macros, f2py_flags, sysinfo_flags, fc_flags, flib_flags, setup_flags, remove_build_dir, extra_dat): self.modulename = modulename self.sources = sources self.extra_objects = extra_objects self.build_dir = build_dir self.include_dirs = include_dirs self.library_dirs = library_dirs self.libraries = libraries self.define_macros = define_macros self.undef_macros = undef_macros self.f2py_flags = f2py_flags self.sysinfo_flags = sysinfo_flags self.fc_flags = fc_flags self.flib_flags = flib_flags self.setup_flags = setup_flags self.remove_build_dir = remove_build_dir self.extra_dat = extra_dat @abstractmethod def compile(self) -> None: pass # File: numpy-main/numpy/f2py/_backends/_distutils.py from ._backend import Backend from numpy.distutils.core import setup, Extension from numpy.distutils.system_info import get_info from numpy.distutils.misc_util import dict_append from numpy.exceptions import VisibleDeprecationWarning import os import sys import shutil import warnings class DistutilsBackend(Backend): def __init__(sef, *args, **kwargs): warnings.warn('\ndistutils has been deprecated since NumPy 1.26.x\nUse the Meson backend instead, or generate wrappers without -c and use a custom build script', VisibleDeprecationWarning, stacklevel=2) super().__init__(*args, **kwargs) def compile(self): num_info = {} if num_info: self.include_dirs.extend(num_info.get('include_dirs', [])) ext_args = {'name': self.modulename, 'sources': self.sources, 'include_dirs': self.include_dirs, 'library_dirs': self.library_dirs, 'libraries': self.libraries, 'define_macros': self.define_macros, 'undef_macros': self.undef_macros, 'extra_objects': self.extra_objects, 'f2py_options': self.f2py_flags} if self.sysinfo_flags: for n in self.sysinfo_flags: i = get_info(n) if not i: print(f'No {n!r} resources foundin system (try `f2py --help-link`)') dict_append(ext_args, **i) ext = Extension(**ext_args) sys.argv = [sys.argv[0]] + self.setup_flags sys.argv.extend(['build', '--build-temp', self.build_dir, '--build-base', self.build_dir, '--build-platlib', '.', '--disable-optimization']) if self.fc_flags: sys.argv.extend(['config_fc'] + self.fc_flags) if self.flib_flags: sys.argv.extend(['build_ext'] + self.flib_flags) setup(ext_modules=[ext]) if self.remove_build_dir and os.path.exists(self.build_dir): print(f'Removing build directory {self.build_dir}') shutil.rmtree(self.build_dir) # File: numpy-main/numpy/f2py/_backends/_meson.py from __future__ import annotations import os import errno import shutil import subprocess import sys import re from pathlib import Path from ._backend import Backend from string import Template from itertools import chain class MesonTemplate: def __init__(self, modulename: str, sources: list[Path], deps: list[str], libraries: list[str], library_dirs: list[Path], include_dirs: list[Path], object_files: list[Path], linker_args: list[str], fortran_args: list[str], build_type: str, python_exe: str): self.modulename = modulename self.build_template_path = Path(__file__).parent.absolute() / 'meson.build.template' self.sources = sources self.deps = deps self.libraries = libraries self.library_dirs = library_dirs if include_dirs is not None: self.include_dirs = include_dirs else: self.include_dirs = [] self.substitutions = {} self.objects = object_files self.fortran_args = [f"'{x}'" if not (x.startswith("'") and x.endswith("'")) else x for x in fortran_args] self.pipeline = [self.initialize_template, self.sources_substitution, self.deps_substitution, self.include_substitution, self.libraries_substitution, self.fortran_args_substitution] self.build_type = build_type self.python_exe = python_exe self.indent = ' ' * 21 def meson_build_template(self) -> str: if not self.build_template_path.is_file(): raise FileNotFoundError(errno.ENOENT, f'Meson build template {self.build_template_path.absolute()} does not exist.') return self.build_template_path.read_text() def initialize_template(self) -> None: self.substitutions['modulename'] = self.modulename self.substitutions['buildtype'] = self.build_type self.substitutions['python'] = self.python_exe def sources_substitution(self) -> None: self.substitutions['source_list'] = ',\n'.join([f"{self.indent}'''{source}'''," for source in self.sources]) def deps_substitution(self) -> None: self.substitutions['dep_list'] = f',\n{self.indent}'.join([f"{self.indent}dependency('{dep}')," for dep in self.deps]) def libraries_substitution(self) -> None: self.substitutions['lib_dir_declarations'] = '\n'.join([f"lib_dir_{i} = declare_dependency(link_args : ['''-L{lib_dir}'''])" for (i, lib_dir) in enumerate(self.library_dirs)]) self.substitutions['lib_declarations'] = '\n'.join([f"{lib.replace('.', '_')} = declare_dependency(link_args : ['-l{lib}'])" for lib in self.libraries]) self.substitutions['lib_list'] = f'\n{self.indent}'.join([f"{self.indent}{lib.replace('.', '_')}," for lib in self.libraries]) self.substitutions['lib_dir_list'] = f'\n{self.indent}'.join([f'{self.indent}lib_dir_{i},' for i in range(len(self.library_dirs))]) def include_substitution(self) -> None: self.substitutions['inc_list'] = f',\n{self.indent}'.join([f"{self.indent}'''{inc}'''," for inc in self.include_dirs]) def fortran_args_substitution(self) -> None: if self.fortran_args: self.substitutions['fortran_args'] = f"{self.indent}fortran_args: [{', '.join(list(self.fortran_args))}]," else: self.substitutions['fortran_args'] = '' def generate_meson_build(self): for node in self.pipeline: node() template = Template(self.meson_build_template()) meson_build = template.substitute(self.substitutions) meson_build = re.sub(',,', ',', meson_build) return meson_build class MesonBackend(Backend): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.dependencies = self.extra_dat.get('dependencies', []) self.meson_build_dir = 'bbdir' self.build_type = 'debug' if any(('debug' in flag for flag in self.fc_flags)) else 'release' self.fc_flags = _get_flags(self.fc_flags) def _move_exec_to_root(self, build_dir: Path): walk_dir = Path(build_dir) / self.meson_build_dir path_objects = chain(walk_dir.glob(f'{self.modulename}*.so'), walk_dir.glob(f'{self.modulename}*.pyd')) for path_object in path_objects: dest_path = Path.cwd() / path_object.name if dest_path.exists(): dest_path.unlink() shutil.copy2(path_object, dest_path) os.remove(path_object) def write_meson_build(self, build_dir: Path) -> None: meson_template = MesonTemplate(self.modulename, self.sources, self.dependencies, self.libraries, self.library_dirs, self.include_dirs, self.extra_objects, self.flib_flags, self.fc_flags, self.build_type, sys.executable) src = meson_template.generate_meson_build() Path(build_dir).mkdir(parents=True, exist_ok=True) meson_build_file = Path(build_dir) / 'meson.build' meson_build_file.write_text(src) return meson_build_file def _run_subprocess_command(self, command, cwd): subprocess.run(command, cwd=cwd, check=True) def run_meson(self, build_dir: Path): setup_command = ['meson', 'setup', self.meson_build_dir] self._run_subprocess_command(setup_command, build_dir) compile_command = ['meson', 'compile', '-C', self.meson_build_dir] self._run_subprocess_command(compile_command, build_dir) def compile(self) -> None: self.sources = _prepare_sources(self.modulename, self.sources, self.build_dir) self.write_meson_build(self.build_dir) self.run_meson(self.build_dir) self._move_exec_to_root(self.build_dir) def _prepare_sources(mname, sources, bdir): extended_sources = sources.copy() Path(bdir).mkdir(parents=True, exist_ok=True) for source in sources: if Path(source).exists() and Path(source).is_file(): shutil.copy(source, bdir) generated_sources = [Path(f'{mname}module.c'), Path(f'{mname}-f2pywrappers2.f90'), Path(f'{mname}-f2pywrappers.f')] bdir = Path(bdir) for generated_source in generated_sources: if generated_source.exists(): shutil.copy(generated_source, bdir / generated_source.name) extended_sources.append(generated_source.name) generated_source.unlink() extended_sources = [Path(source).name for source in extended_sources if not Path(source).suffix == '.pyf'] return extended_sources def _get_flags(fc_flags): flag_values = [] flag_pattern = re.compile('--f(77|90)flags=(.*)') for flag in fc_flags: match_result = flag_pattern.match(flag) if match_result: values = match_result.group(2).strip().split() values = [val.strip('\'"') for val in values] flag_values.extend(values) unique_flags = list(dict.fromkeys(flag_values)) return unique_flags # File: numpy-main/numpy/f2py/_isocbind.py """""" iso_c_binding_map = {'integer': {'c_int': 'int', 'c_short': 'short', 'c_long': 'long', 'c_long_long': 'long_long', 'c_signed_char': 'signed_char', 'c_size_t': 'unsigned', 'c_int8_t': 'signed_char', 'c_int16_t': 'short', 'c_int32_t': 'int', 'c_int64_t': 'long_long', 'c_int_least8_t': 'signed_char', 'c_int_least16_t': 'short', 'c_int_least32_t': 'int', 'c_int_least64_t': 'long_long', 'c_int_fast8_t': 'signed_char', 'c_int_fast16_t': 'short', 'c_int_fast32_t': 'int', 'c_int_fast64_t': 'long_long', 'c_intmax_t': 'long_long', 'c_intptr_t': 'long', 'c_ptrdiff_t': 'long'}, 'real': {'c_float': 'float', 'c_double': 'double', 'c_long_double': 'long_double'}, 'complex': {'c_float_complex': 'complex_float', 'c_double_complex': 'complex_double', 'c_long_double_complex': 'complex_long_double'}, 'logical': {'c_bool': 'unsigned_char'}, 'character': {'c_char': 'char'}} isoc_c2pycode_map = {} iso_c2py_map = {} isoc_kindmap = {} for (fortran_type, c_type_dict) in iso_c_binding_map.items(): for c_type in c_type_dict.keys(): isoc_kindmap[c_type] = fortran_type # File: numpy-main/numpy/f2py/_src_pyf.py import os import re '' routine_start_re = re.compile('(\\n|\\A)(( (\\$|\\*))|)\\s*(subroutine|function)\\b', re.I) routine_end_re = re.compile('\\n\\s*end\\s*(subroutine|function)\\b.*(\\n|\\Z)', re.I) function_start_re = re.compile('\\n (\\$|\\*)\\s*function\\b', re.I) def parse_structure(astr): spanlist = [] ind = 0 while True: m = routine_start_re.search(astr, ind) if m is None: break start = m.start() if function_start_re.match(astr, start, m.end()): while True: i = astr.rfind('\n', ind, start) if i == -1: break start = i if astr[i:i + 7] != '\n $': break start += 1 m = routine_end_re.search(astr, m.end()) ind = end = m and m.end() - 1 or len(astr) spanlist.append((start, end)) return spanlist template_re = re.compile('<\\s*(\\w[\\w\\d]*)\\s*>') named_re = re.compile('<\\s*(\\w[\\w\\d]*)\\s*=\\s*(.*?)\\s*>') list_re = re.compile('<\\s*((.*?))\\s*>') def find_repl_patterns(astr): reps = named_re.findall(astr) names = {} for rep in reps: name = rep[0].strip() or unique_key(names) repl = rep[1].replace('\\,', '@comma@') thelist = conv(repl) names[name] = thelist return names def find_and_remove_repl_patterns(astr): names = find_repl_patterns(astr) astr = re.subn(named_re, '', astr)[0] return (astr, names) item_re = re.compile('\\A\\\\(?P\\d+)\\Z') def conv(astr): b = astr.split(',') l = [x.strip() for x in b] for i in range(len(l)): m = item_re.match(l[i]) if m: j = int(m.group('index')) l[i] = l[j] return ','.join(l) def unique_key(adict): allkeys = list(adict.keys()) done = False n = 1 while not done: newkey = '__l%s' % n if newkey in allkeys: n += 1 else: done = True return newkey template_name_re = re.compile('\\A\\s*(\\w[\\w\\d]*)\\s*\\Z') def expand_sub(substr, names): substr = substr.replace('\\>', '@rightarrow@') substr = substr.replace('\\<', '@leftarrow@') lnames = find_repl_patterns(substr) substr = named_re.sub('<\\1>', substr) def listrepl(mobj): thelist = conv(mobj.group(1).replace('\\,', '@comma@')) if template_name_re.match(thelist): return '<%s>' % thelist name = None for key in lnames.keys(): if lnames[key] == thelist: name = key if name is None: name = unique_key(lnames) lnames[name] = thelist return '<%s>' % name substr = list_re.sub(listrepl, substr) numsubs = None base_rule = None rules = {} for r in template_re.findall(substr): if r not in rules: thelist = lnames.get(r, names.get(r, None)) if thelist is None: raise ValueError('No replicates found for <%s>' % r) if r not in names and (not thelist.startswith('_')): names[r] = thelist rule = [i.replace('@comma@', ',') for i in thelist.split(',')] num = len(rule) if numsubs is None: numsubs = num rules[r] = rule base_rule = r elif num == numsubs: rules[r] = rule else: print('Mismatch in number of replacements (base <{}={}>) for <{}={}>. Ignoring.'.format(base_rule, ','.join(rules[base_rule]), r, thelist)) if not rules: return substr def namerepl(mobj): name = mobj.group(1) return rules.get(name, (k + 1) * [name])[k] newstr = '' for k in range(numsubs): newstr += template_re.sub(namerepl, substr) + '\n\n' newstr = newstr.replace('@rightarrow@', '>') newstr = newstr.replace('@leftarrow@', '<') return newstr def process_str(allstr): newstr = allstr writestr = '' struct = parse_structure(newstr) oldend = 0 names = {} names.update(_special_names) for sub in struct: (cleanedstr, defs) = find_and_remove_repl_patterns(newstr[oldend:sub[0]]) writestr += cleanedstr names.update(defs) writestr += expand_sub(newstr[sub[0]:sub[1]], names) oldend = sub[1] writestr += newstr[oldend:] return writestr include_src_re = re.compile('(\\n|\\A)\\s*include\\s*[\'\\"](?P[\\w\\d./\\\\]+\\.src)[\'\\"]', re.I) def resolve_includes(source): d = os.path.dirname(source) with open(source) as fid: lines = [] for line in fid: m = include_src_re.match(line) if m: fn = m.group('name') if not os.path.isabs(fn): fn = os.path.join(d, fn) if os.path.isfile(fn): lines.extend(resolve_includes(fn)) else: lines.append(line) else: lines.append(line) return lines def process_file(source): lines = resolve_includes(source) return process_str(''.join(lines)) _special_names = find_repl_patterns('\n<_c=s,d,c,z>\n<_t=real,double precision,complex,double complex>\n\n\n\n\n\n') # File: numpy-main/numpy/f2py/auxfuncs.py """""" import pprint import sys import re import types from functools import reduce from . import __version__ from . import cfuncs from .cfuncs import errmess __all__ = ['applyrules', 'debugcapi', 'dictappend', 'errmess', 'gentitle', 'getargs2', 'getcallprotoargument', 'getcallstatement', 'getfortranname', 'getpymethoddef', 'getrestdoc', 'getusercode', 'getusercode1', 'getdimension', 'hasbody', 'hascallstatement', 'hascommon', 'hasexternals', 'hasinitvalue', 'hasnote', 'hasresultnote', 'isallocatable', 'isarray', 'isarrayofstrings', 'ischaracter', 'ischaracterarray', 'ischaracter_or_characterarray', 'iscomplex', 'iscomplexarray', 'iscomplexfunction', 'iscomplexfunction_warn', 'isdouble', 'isdummyroutine', 'isexternal', 'isfunction', 'isfunction_wrap', 'isint1', 'isint1array', 'isinteger', 'isintent_aux', 'isintent_c', 'isintent_callback', 'isintent_copy', 'isintent_dict', 'isintent_hide', 'isintent_in', 'isintent_inout', 'isintent_inplace', 'isintent_nothide', 'isintent_out', 'isintent_overwrite', 'islogical', 'islogicalfunction', 'islong_complex', 'islong_double', 'islong_doublefunction', 'islong_long', 'islong_longfunction', 'ismodule', 'ismoduleroutine', 'isoptional', 'isprivate', 'isvariable', 'isrequired', 'isroutine', 'isscalar', 'issigned_long_longarray', 'isstring', 'isstringarray', 'isstring_or_stringarray', 'isstringfunction', 'issubroutine', 'get_f2py_modulename', 'issubroutine_wrap', 'isthreadsafe', 'isunsigned', 'isunsigned_char', 'isunsigned_chararray', 'isunsigned_long_long', 'isunsigned_long_longarray', 'isunsigned_short', 'isunsigned_shortarray', 'l_and', 'l_not', 'l_or', 'outmess', 'replace', 'show', 'stripcomma', 'throw_error', 'isattr_value', 'getuseblocks', 'process_f2cmap_dict'] f2py_version = __version__.version show = pprint.pprint options = {} debugoptions = [] wrapfuncs = 1 def outmess(t): if options.get('verbose', 1): sys.stdout.write(t) def debugcapi(var): return 'capi' in debugoptions def _ischaracter(var): return 'typespec' in var and var['typespec'] == 'character' and (not isexternal(var)) def _isstring(var): return 'typespec' in var and var['typespec'] == 'character' and (not isexternal(var)) def ischaracter_or_characterarray(var): return _ischaracter(var) and 'charselector' not in var def ischaracter(var): return ischaracter_or_characterarray(var) and (not isarray(var)) def ischaracterarray(var): return ischaracter_or_characterarray(var) and isarray(var) def isstring_or_stringarray(var): return _ischaracter(var) and 'charselector' in var def isstring(var): return isstring_or_stringarray(var) and (not isarray(var)) def isstringarray(var): return isstring_or_stringarray(var) and isarray(var) def isarrayofstrings(var): return isstringarray(var) and var['dimension'][-1] == '(*)' def isarray(var): return 'dimension' in var and (not isexternal(var)) def isscalar(var): return not (isarray(var) or isstring(var) or isexternal(var)) def iscomplex(var): return isscalar(var) and var.get('typespec') in ['complex', 'double complex'] def islogical(var): return isscalar(var) and var.get('typespec') == 'logical' def isinteger(var): return isscalar(var) and var.get('typespec') == 'integer' def isreal(var): return isscalar(var) and var.get('typespec') == 'real' def get_kind(var): try: return var['kindselector']['*'] except KeyError: try: return var['kindselector']['kind'] except KeyError: pass def isint1(var): return var.get('typespec') == 'integer' and get_kind(var) == '1' and (not isarray(var)) def islong_long(var): if not isscalar(var): return 0 if var.get('typespec') not in ['integer', 'logical']: return 0 return get_kind(var) == '8' def isunsigned_char(var): if not isscalar(var): return 0 if var.get('typespec') != 'integer': return 0 return get_kind(var) == '-1' def isunsigned_short(var): if not isscalar(var): return 0 if var.get('typespec') != 'integer': return 0 return get_kind(var) == '-2' def isunsigned(var): if not isscalar(var): return 0 if var.get('typespec') != 'integer': return 0 return get_kind(var) == '-4' def isunsigned_long_long(var): if not isscalar(var): return 0 if var.get('typespec') != 'integer': return 0 return get_kind(var) == '-8' def isdouble(var): if not isscalar(var): return 0 if not var.get('typespec') == 'real': return 0 return get_kind(var) == '8' def islong_double(var): if not isscalar(var): return 0 if not var.get('typespec') == 'real': return 0 return get_kind(var) == '16' def islong_complex(var): if not iscomplex(var): return 0 return get_kind(var) == '32' def iscomplexarray(var): return isarray(var) and var.get('typespec') in ['complex', 'double complex'] def isint1array(var): return isarray(var) and var.get('typespec') == 'integer' and (get_kind(var) == '1') def isunsigned_chararray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical'] and (get_kind(var) == '-1') def isunsigned_shortarray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical'] and (get_kind(var) == '-2') def isunsignedarray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical'] and (get_kind(var) == '-4') def isunsigned_long_longarray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical'] and (get_kind(var) == '-8') def issigned_chararray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical'] and (get_kind(var) == '1') def issigned_shortarray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical'] and (get_kind(var) == '2') def issigned_array(var): return isarray(var) and var.get('typespec') in ['integer', 'logical'] and (get_kind(var) == '4') def issigned_long_longarray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical'] and (get_kind(var) == '8') def isallocatable(var): return 'attrspec' in var and 'allocatable' in var['attrspec'] def ismutable(var): return not ('dimension' not in var or isstring(var)) def ismoduleroutine(rout): return 'modulename' in rout def ismodule(rout): return 'block' in rout and 'module' == rout['block'] def isfunction(rout): return 'block' in rout and 'function' == rout['block'] def isfunction_wrap(rout): if isintent_c(rout): return 0 return wrapfuncs and isfunction(rout) and (not isexternal(rout)) def issubroutine(rout): return 'block' in rout and 'subroutine' == rout['block'] def issubroutine_wrap(rout): if isintent_c(rout): return 0 return issubroutine(rout) and hasassumedshape(rout) def isattr_value(var): return 'value' in var.get('attrspec', []) def hasassumedshape(rout): if rout.get('hasassumedshape'): return True for a in rout['args']: for d in rout['vars'].get(a, {}).get('dimension', []): if d == ':': rout['hasassumedshape'] = True return True return False def requiresf90wrapper(rout): return ismoduleroutine(rout) or hasassumedshape(rout) def isroutine(rout): return isfunction(rout) or issubroutine(rout) def islogicalfunction(rout): if not isfunction(rout): return 0 if 'result' in rout: a = rout['result'] else: a = rout['name'] if a in rout['vars']: return islogical(rout['vars'][a]) return 0 def islong_longfunction(rout): if not isfunction(rout): return 0 if 'result' in rout: a = rout['result'] else: a = rout['name'] if a in rout['vars']: return islong_long(rout['vars'][a]) return 0 def islong_doublefunction(rout): if not isfunction(rout): return 0 if 'result' in rout: a = rout['result'] else: a = rout['name'] if a in rout['vars']: return islong_double(rout['vars'][a]) return 0 def iscomplexfunction(rout): if not isfunction(rout): return 0 if 'result' in rout: a = rout['result'] else: a = rout['name'] if a in rout['vars']: return iscomplex(rout['vars'][a]) return 0 def iscomplexfunction_warn(rout): if iscomplexfunction(rout): outmess(' **************************************************************\n Warning: code with a function returning complex value\n may not work correctly with your Fortran compiler.\n When using GNU gcc/g77 compilers, codes should work\n correctly for callbacks with:\n f2py -c -DF2PY_CB_RETURNCOMPLEX\n **************************************************************\n') return 1 return 0 def isstringfunction(rout): if not isfunction(rout): return 0 if 'result' in rout: a = rout['result'] else: a = rout['name'] if a in rout['vars']: return isstring(rout['vars'][a]) return 0 def hasexternals(rout): return 'externals' in rout and rout['externals'] def isthreadsafe(rout): return 'f2pyenhancements' in rout and 'threadsafe' in rout['f2pyenhancements'] def hasvariables(rout): return 'vars' in rout and rout['vars'] def isoptional(var): return ('attrspec' in var and 'optional' in var['attrspec'] and ('required' not in var['attrspec'])) and isintent_nothide(var) def isexternal(var): return 'attrspec' in var and 'external' in var['attrspec'] def getdimension(var): dimpattern = '\\((.*?)\\)' if 'attrspec' in var.keys(): if any(('dimension' in s for s in var['attrspec'])): return [re.findall(dimpattern, v) for v in var['attrspec']][0] def isrequired(var): return not isoptional(var) and isintent_nothide(var) def isintent_in(var): if 'intent' not in var: return 1 if 'hide' in var['intent']: return 0 if 'inplace' in var['intent']: return 0 if 'in' in var['intent']: return 1 if 'out' in var['intent']: return 0 if 'inout' in var['intent']: return 0 if 'outin' in var['intent']: return 0 return 1 def isintent_inout(var): return 'intent' in var and ('inout' in var['intent'] or 'outin' in var['intent']) and ('in' not in var['intent']) and ('hide' not in var['intent']) and ('inplace' not in var['intent']) def isintent_out(var): return 'out' in var.get('intent', []) def isintent_hide(var): return 'intent' in var and ('hide' in var['intent'] or ('out' in var['intent'] and 'in' not in var['intent'] and (not l_or(isintent_inout, isintent_inplace)(var)))) def isintent_nothide(var): return not isintent_hide(var) def isintent_c(var): return 'c' in var.get('intent', []) def isintent_cache(var): return 'cache' in var.get('intent', []) def isintent_copy(var): return 'copy' in var.get('intent', []) def isintent_overwrite(var): return 'overwrite' in var.get('intent', []) def isintent_callback(var): return 'callback' in var.get('intent', []) def isintent_inplace(var): return 'inplace' in var.get('intent', []) def isintent_aux(var): return 'aux' in var.get('intent', []) def isintent_aligned4(var): return 'aligned4' in var.get('intent', []) def isintent_aligned8(var): return 'aligned8' in var.get('intent', []) def isintent_aligned16(var): return 'aligned16' in var.get('intent', []) isintent_dict = {isintent_in: 'INTENT_IN', isintent_inout: 'INTENT_INOUT', isintent_out: 'INTENT_OUT', isintent_hide: 'INTENT_HIDE', isintent_cache: 'INTENT_CACHE', isintent_c: 'INTENT_C', isoptional: 'OPTIONAL', isintent_inplace: 'INTENT_INPLACE', isintent_aligned4: 'INTENT_ALIGNED4', isintent_aligned8: 'INTENT_ALIGNED8', isintent_aligned16: 'INTENT_ALIGNED16'} def isprivate(var): return 'attrspec' in var and 'private' in var['attrspec'] def isvariable(var): if len(var) == 1 and 'attrspec' in var and (var['attrspec'][0] in ('public', 'private')): is_var = False else: is_var = True return is_var def hasinitvalue(var): return '=' in var def hasinitvalueasstring(var): if not hasinitvalue(var): return 0 return var['='][0] in ['"', "'"] def hasnote(var): return 'note' in var def hasresultnote(rout): if not isfunction(rout): return 0 if 'result' in rout: a = rout['result'] else: a = rout['name'] if a in rout['vars']: return hasnote(rout['vars'][a]) return 0 def hascommon(rout): return 'common' in rout def containscommon(rout): if hascommon(rout): return 1 if hasbody(rout): for b in rout['body']: if containscommon(b): return 1 return 0 def containsmodule(block): if ismodule(block): return 1 if not hasbody(block): return 0 for b in block['body']: if containsmodule(b): return 1 return 0 def hasbody(rout): return 'body' in rout def hascallstatement(rout): return getcallstatement(rout) is not None def istrue(var): return 1 def isfalse(var): return 0 class F2PYError(Exception): pass class throw_error: def __init__(self, mess): self.mess = mess def __call__(self, var): mess = '\n\n var = %s\n Message: %s\n' % (var, self.mess) raise F2PYError(mess) def l_and(*f): (l1, l2) = ('lambda v', []) for i in range(len(f)): l1 = '%s,f%d=f[%d]' % (l1, i, i) l2.append('f%d(v)' % i) return eval('%s:%s' % (l1, ' and '.join(l2))) def l_or(*f): (l1, l2) = ('lambda v', []) for i in range(len(f)): l1 = '%s,f%d=f[%d]' % (l1, i, i) l2.append('f%d(v)' % i) return eval('%s:%s' % (l1, ' or '.join(l2))) def l_not(f): return eval('lambda v,f=f:not f(v)') def isdummyroutine(rout): try: return rout['f2pyenhancements']['fortranname'] == '' except KeyError: return 0 def getfortranname(rout): try: name = rout['f2pyenhancements']['fortranname'] if name == '': raise KeyError if not name: errmess('Failed to use fortranname from %s\n' % rout['f2pyenhancements']) raise KeyError except KeyError: name = rout['name'] return name def getmultilineblock(rout, blockname, comment=1, counter=0): try: r = rout['f2pyenhancements'].get(blockname) except KeyError: return if not r: return if counter > 0 and isinstance(r, str): return if isinstance(r, list): if counter >= len(r): return r = r[counter] if r[:3] == "'''": if comment: r = '\t/* start ' + blockname + ' multiline (' + repr(counter) + ') */\n' + r[3:] else: r = r[3:] if r[-3:] == "'''": if comment: r = r[:-3] + '\n\t/* end multiline (' + repr(counter) + ')*/' else: r = r[:-3] else: errmess("%s multiline block should end with `'''`: %s\n" % (blockname, repr(r))) return r def getcallstatement(rout): return getmultilineblock(rout, 'callstatement') def getcallprotoargument(rout, cb_map={}): r = getmultilineblock(rout, 'callprotoargument', comment=0) if r: return r if hascallstatement(rout): outmess('warning: callstatement is defined without callprotoargument\n') return from .capi_maps import getctype (arg_types, arg_types2) = ([], []) if l_and(isstringfunction, l_not(isfunction_wrap))(rout): arg_types.extend(['char*', 'size_t']) for n in rout['args']: var = rout['vars'][n] if isintent_callback(var): continue if n in cb_map: ctype = cb_map[n] + '_typedef' else: ctype = getctype(var) if l_and(isintent_c, l_or(isscalar, iscomplex))(var): pass elif isstring(var): pass elif not isattr_value(var): ctype = ctype + '*' if isstring(var) or isarrayofstrings(var) or isstringarray(var): arg_types2.append('size_t') arg_types.append(ctype) proto_args = ','.join(arg_types + arg_types2) if not proto_args: proto_args = 'void' return proto_args def getusercode(rout): return getmultilineblock(rout, 'usercode') def getusercode1(rout): return getmultilineblock(rout, 'usercode', counter=1) def getpymethoddef(rout): return getmultilineblock(rout, 'pymethoddef') def getargs(rout): (sortargs, args) = ([], []) if 'args' in rout: args = rout['args'] if 'sortvars' in rout: for a in rout['sortvars']: if a in args: sortargs.append(a) for a in args: if a not in sortargs: sortargs.append(a) else: sortargs = rout['args'] return (args, sortargs) def getargs2(rout): (sortargs, args) = ([], rout.get('args', [])) auxvars = [a for a in rout['vars'].keys() if isintent_aux(rout['vars'][a]) and a not in args] args = auxvars + args if 'sortvars' in rout: for a in rout['sortvars']: if a in args: sortargs.append(a) for a in args: if a not in sortargs: sortargs.append(a) else: sortargs = auxvars + rout['args'] return (args, sortargs) def getrestdoc(rout): if 'f2pymultilines' not in rout: return None k = None if rout['block'] == 'python module': k = (rout['block'], rout['name']) return rout['f2pymultilines'].get(k, None) def gentitle(name): ln = (80 - len(name) - 6) // 2 return '/*%s %s %s*/' % (ln * '*', name, ln * '*') def flatlist(lst): if isinstance(lst, list): return reduce(lambda x, y, f=flatlist: x + f(y), lst, []) return [lst] def stripcomma(s): if s and s[-1] == ',': return s[:-1] return s def replace(str, d, defaultsep=''): if isinstance(d, list): return [replace(str, _m, defaultsep) for _m in d] if isinstance(str, list): return [replace(_m, d, defaultsep) for _m in str] for k in 2 * list(d.keys()): if k == 'separatorsfor': continue if 'separatorsfor' in d and k in d['separatorsfor']: sep = d['separatorsfor'][k] else: sep = defaultsep if isinstance(d[k], list): str = str.replace('#%s#' % k, sep.join(flatlist(d[k]))) else: str = str.replace('#%s#' % k, d[k]) return str def dictappend(rd, ar): if isinstance(ar, list): for a in ar: rd = dictappend(rd, a) return rd for k in ar.keys(): if k[0] == '_': continue if k in rd: if isinstance(rd[k], str): rd[k] = [rd[k]] if isinstance(rd[k], list): if isinstance(ar[k], list): rd[k] = rd[k] + ar[k] else: rd[k].append(ar[k]) elif isinstance(rd[k], dict): if isinstance(ar[k], dict): if k == 'separatorsfor': for k1 in ar[k].keys(): if k1 not in rd[k]: rd[k][k1] = ar[k][k1] else: rd[k] = dictappend(rd[k], ar[k]) else: rd[k] = ar[k] return rd def applyrules(rules, d, var={}): ret = {} if isinstance(rules, list): for r in rules: rr = applyrules(r, d, var) ret = dictappend(ret, rr) if '_break' in rr: break return ret if '_check' in rules and (not rules['_check'](var)): return ret if 'need' in rules: res = applyrules({'needs': rules['need']}, d, var) if 'needs' in res: cfuncs.append_needs(res['needs']) for k in rules.keys(): if k == 'separatorsfor': ret[k] = rules[k] continue if isinstance(rules[k], str): ret[k] = replace(rules[k], d) elif isinstance(rules[k], list): ret[k] = [] for i in rules[k]: ar = applyrules({k: i}, d, var) if k in ar: ret[k].append(ar[k]) elif k[0] == '_': continue elif isinstance(rules[k], dict): ret[k] = [] for k1 in rules[k].keys(): if isinstance(k1, types.FunctionType) and k1(var): if isinstance(rules[k][k1], list): for i in rules[k][k1]: if isinstance(i, dict): res = applyrules({'supertext': i}, d, var) if 'supertext' in res: i = res['supertext'] else: i = '' ret[k].append(replace(i, d)) else: i = rules[k][k1] if isinstance(i, dict): res = applyrules({'supertext': i}, d) if 'supertext' in res: i = res['supertext'] else: i = '' ret[k].append(replace(i, d)) else: errmess('applyrules: ignoring rule %s.\n' % repr(rules[k])) if isinstance(ret[k], list): if len(ret[k]) == 1: ret[k] = ret[k][0] if ret[k] == []: del ret[k] return ret _f2py_module_name_match = re.compile('\\s*python\\s*module\\s*(?P[\\w_]+)', re.I).match _f2py_user_module_name_match = re.compile('\\s*python\\s*module\\s*(?P[\\w_]*?__user__[\\w_]*)', re.I).match def get_f2py_modulename(source): name = None with open(source) as f: for line in f: m = _f2py_module_name_match(line) if m: if _f2py_user_module_name_match(line): continue name = m.group('name') break return name def getuseblocks(pymod): all_uses = [] for inner in pymod['body']: for modblock in inner['body']: if modblock.get('use'): all_uses.extend([x for x in modblock.get('use').keys() if '__' not in x]) return all_uses def process_f2cmap_dict(f2cmap_all, new_map, c2py_map, verbose=False): f2cmap_mapped = [] new_map_lower = {} for (k, d1) in new_map.items(): d1_lower = {k1.lower(): v1 for (k1, v1) in d1.items()} new_map_lower[k.lower()] = d1_lower for (k, d1) in new_map_lower.items(): if k not in f2cmap_all: f2cmap_all[k] = {} for (k1, v1) in d1.items(): if v1 in c2py_map: if k1 in f2cmap_all[k]: outmess("\tWarning: redefinition of {'%s':{'%s':'%s'->'%s'}}\n" % (k, k1, f2cmap_all[k][k1], v1)) f2cmap_all[k][k1] = v1 if verbose: outmess('\tMapping "%s(kind=%s)" to "%s"\n' % (k, k1, v1)) f2cmap_mapped.append(v1) elif verbose: errmess("\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n" % (k, k1, v1, v1, list(c2py_map.keys()))) return (f2cmap_all, f2cmap_mapped) # File: numpy-main/numpy/f2py/capi_maps.py """""" from . import __version__ f2py_version = __version__.version import copy import re import os from .crackfortran import markoutercomma from . import cb_rules from ._isocbind import iso_c_binding_map, isoc_c2pycode_map, iso_c2py_map from .auxfuncs import * __all__ = ['getctype', 'getstrlength', 'getarrdims', 'getpydocsign', 'getarrdocsign', 'getinit', 'sign2map', 'routsign2map', 'modsign2map', 'cb_sign2map', 'cb_routsign2map', 'common_sign2map', 'process_f2cmap_dict'] depargs = [] lcb_map = {} lcb2_map = {} c2py_map = {'double': 'float', 'float': 'float', 'long_double': 'float', 'char': 'int', 'signed_char': 'int', 'unsigned_char': 'int', 'short': 'int', 'unsigned_short': 'int', 'int': 'int', 'long': 'int', 'long_long': 'long', 'unsigned': 'int', 'complex_float': 'complex', 'complex_double': 'complex', 'complex_long_double': 'complex', 'string': 'string', 'character': 'bytes'} c2capi_map = {'double': 'NPY_DOUBLE', 'float': 'NPY_FLOAT', 'long_double': 'NPY_LONGDOUBLE', 'char': 'NPY_BYTE', 'unsigned_char': 'NPY_UBYTE', 'signed_char': 'NPY_BYTE', 'short': 'NPY_SHORT', 'unsigned_short': 'NPY_USHORT', 'int': 'NPY_INT', 'unsigned': 'NPY_UINT', 'long': 'NPY_LONG', 'unsigned_long': 'NPY_ULONG', 'long_long': 'NPY_LONGLONG', 'unsigned_long_long': 'NPY_ULONGLONG', 'complex_float': 'NPY_CFLOAT', 'complex_double': 'NPY_CDOUBLE', 'complex_long_double': 'NPY_CDOUBLE', 'string': 'NPY_STRING', 'character': 'NPY_STRING'} c2pycode_map = {'double': 'd', 'float': 'f', 'long_double': 'g', 'char': 'b', 'unsigned_char': 'B', 'signed_char': 'b', 'short': 'h', 'unsigned_short': 'H', 'int': 'i', 'unsigned': 'I', 'long': 'l', 'unsigned_long': 'L', 'long_long': 'q', 'unsigned_long_long': 'Q', 'complex_float': 'F', 'complex_double': 'D', 'complex_long_double': 'G', 'string': 'S', 'character': 'c'} c2buildvalue_map = {'double': 'd', 'float': 'f', 'char': 'b', 'signed_char': 'b', 'short': 'h', 'int': 'i', 'long': 'l', 'long_long': 'L', 'complex_float': 'N', 'complex_double': 'N', 'complex_long_double': 'N', 'string': 'y', 'character': 'c'} f2cmap_all = {'real': {'': 'float', '4': 'float', '8': 'double', '12': 'long_double', '16': 'long_double'}, 'integer': {'': 'int', '1': 'signed_char', '2': 'short', '4': 'int', '8': 'long_long', '-1': 'unsigned_char', '-2': 'unsigned_short', '-4': 'unsigned', '-8': 'unsigned_long_long'}, 'complex': {'': 'complex_float', '8': 'complex_float', '16': 'complex_double', '24': 'complex_long_double', '32': 'complex_long_double'}, 'complexkind': {'': 'complex_float', '4': 'complex_float', '8': 'complex_double', '12': 'complex_long_double', '16': 'complex_long_double'}, 'logical': {'': 'int', '1': 'char', '2': 'short', '4': 'int', '8': 'long_long'}, 'double complex': {'': 'complex_double'}, 'double precision': {'': 'double'}, 'byte': {'': 'char'}} c2pycode_map.update(isoc_c2pycode_map) c2py_map.update(iso_c2py_map) (f2cmap_all, _) = process_f2cmap_dict(f2cmap_all, iso_c_binding_map, c2py_map) f2cmap_default = copy.deepcopy(f2cmap_all) f2cmap_mapped = [] def load_f2cmap_file(f2cmap_file): global f2cmap_all, f2cmap_mapped f2cmap_all = copy.deepcopy(f2cmap_default) if f2cmap_file is None: f2cmap_file = '.f2py_f2cmap' if not os.path.isfile(f2cmap_file): return try: outmess('Reading f2cmap from {!r} ...\n'.format(f2cmap_file)) with open(f2cmap_file) as f: d = eval(f.read().lower(), {}, {}) (f2cmap_all, f2cmap_mapped) = process_f2cmap_dict(f2cmap_all, d, c2py_map, True) outmess('Successfully applied user defined f2cmap changes\n') except Exception as msg: errmess('Failed to apply user defined f2cmap changes: %s. Skipping.\n' % msg) cformat_map = {'double': '%g', 'float': '%g', 'long_double': '%Lg', 'char': '%d', 'signed_char': '%d', 'unsigned_char': '%hhu', 'short': '%hd', 'unsigned_short': '%hu', 'int': '%d', 'unsigned': '%u', 'long': '%ld', 'unsigned_long': '%lu', 'long_long': '%ld', 'complex_float': '(%g,%g)', 'complex_double': '(%g,%g)', 'complex_long_double': '(%Lg,%Lg)', 'string': '\\"%s\\"', 'character': "'%c'"} def getctype(var): ctype = 'void' if isfunction(var): if 'result' in var: a = var['result'] else: a = var['name'] if a in var['vars']: return getctype(var['vars'][a]) else: errmess('getctype: function %s has no return value?!\n' % a) elif issubroutine(var): return ctype elif ischaracter_or_characterarray(var): return 'character' elif isstring_or_stringarray(var): return 'string' elif 'typespec' in var and var['typespec'].lower() in f2cmap_all: typespec = var['typespec'].lower() f2cmap = f2cmap_all[typespec] ctype = f2cmap[''] if 'kindselector' in var: if '*' in var['kindselector']: try: ctype = f2cmap[var['kindselector']['*']] except KeyError: errmess('getctype: "%s %s %s" not supported.\n' % (var['typespec'], '*', var['kindselector']['*'])) elif 'kind' in var['kindselector']: if typespec + 'kind' in f2cmap_all: f2cmap = f2cmap_all[typespec + 'kind'] try: ctype = f2cmap[var['kindselector']['kind']] except KeyError: if typespec in f2cmap_all: f2cmap = f2cmap_all[typespec] try: ctype = f2cmap[str(var['kindselector']['kind'])] except KeyError: errmess('getctype: "%s(kind=%s)" is mapped to C "%s" (to override define dict(%s = dict(%s="")) in %s/.f2py_f2cmap file).\n' % (typespec, var['kindselector']['kind'], ctype, typespec, var['kindselector']['kind'], os.getcwd())) elif not isexternal(var): errmess('getctype: No C-type found in "%s", assuming void.\n' % var) return ctype def f2cexpr(expr): expr = re.sub('\\blen\\b', 'f2py_slen', expr) return expr def getstrlength(var): if isstringfunction(var): if 'result' in var: a = var['result'] else: a = var['name'] if a in var['vars']: return getstrlength(var['vars'][a]) else: errmess('getstrlength: function %s has no return value?!\n' % a) if not isstring(var): errmess('getstrlength: expected a signature of a string but got: %s\n' % repr(var)) len = '1' if 'charselector' in var: a = var['charselector'] if '*' in a: len = a['*'] elif 'len' in a: len = f2cexpr(a['len']) if re.match('\\(\\s*(\\*|:)\\s*\\)', len) or re.match('(\\*|:)', len): if isintent_hide(var): errmess('getstrlength:intent(hide): expected a string with defined length but got: %s\n' % repr(var)) len = '-1' return len def getarrdims(a, var, verbose=0): ret = {} if isstring(var) and (not isarray(var)): ret['size'] = getstrlength(var) ret['rank'] = '0' ret['dims'] = '' elif isscalar(var): ret['size'] = '1' ret['rank'] = '0' ret['dims'] = '' elif isarray(var): dim = copy.copy(var['dimension']) ret['size'] = '*'.join(dim) try: ret['size'] = repr(eval(ret['size'])) except Exception: pass ret['dims'] = ','.join(dim) ret['rank'] = repr(len(dim)) ret['rank*[-1]'] = repr(len(dim) * [-1])[1:-1] for i in range(len(dim)): v = [] if dim[i] in depargs: v = [dim[i]] else: for va in depargs: if re.match('.*?\\b%s\\b.*' % va, dim[i]): v.append(va) for va in v: if depargs.index(va) > depargs.index(a): dim[i] = '*' break (ret['setdims'], i) = ('', -1) for d in dim: i = i + 1 if d not in ['*', ':', '(*)', '(:)']: ret['setdims'] = '%s#varname#_Dims[%d]=%s,' % (ret['setdims'], i, d) if ret['setdims']: ret['setdims'] = ret['setdims'][:-1] (ret['cbsetdims'], i) = ('', -1) for d in var['dimension']: i = i + 1 if d not in ['*', ':', '(*)', '(:)']: ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % (ret['cbsetdims'], i, d) elif isintent_in(var): outmess('getarrdims:warning: assumed shape array, using 0 instead of %r\n' % d) ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % (ret['cbsetdims'], i, 0) elif verbose: errmess('getarrdims: If in call-back function: array argument %s must have bounded dimensions: got %s\n' % (repr(a), repr(d))) if ret['cbsetdims']: ret['cbsetdims'] = ret['cbsetdims'][:-1] return ret def getpydocsign(a, var): global lcb_map if isfunction(var): if 'result' in var: af = var['result'] else: af = var['name'] if af in var['vars']: return getpydocsign(af, var['vars'][af]) else: errmess('getctype: function %s has no return value?!\n' % af) return ('', '') (sig, sigout) = (a, a) opt = '' if isintent_in(var): opt = 'input' elif isintent_inout(var): opt = 'in/output' out_a = a if isintent_out(var): for k in var['intent']: if k[:4] == 'out=': out_a = k[4:] break init = '' ctype = getctype(var) if hasinitvalue(var): (init, showinit) = getinit(a, var) init = ', optional\\n Default: %s' % showinit if isscalar(var): if isintent_inout(var): sig = "%s : %s rank-0 array(%s,'%s')%s" % (a, opt, c2py_map[ctype], c2pycode_map[ctype], init) else: sig = '%s : %s %s%s' % (a, opt, c2py_map[ctype], init) sigout = '%s : %s' % (out_a, c2py_map[ctype]) elif isstring(var): if isintent_inout(var): sig = "%s : %s rank-0 array(string(len=%s),'c')%s" % (a, opt, getstrlength(var), init) else: sig = '%s : %s string(len=%s)%s' % (a, opt, getstrlength(var), init) sigout = '%s : string(len=%s)' % (out_a, getstrlength(var)) elif isarray(var): dim = var['dimension'] rank = repr(len(dim)) sig = "%s : %s rank-%s array('%s') with bounds (%s)%s" % (a, opt, rank, c2pycode_map[ctype], ','.join(dim), init) if a == out_a: sigout = "%s : rank-%s array('%s') with bounds (%s)" % (a, rank, c2pycode_map[ctype], ','.join(dim)) else: sigout = "%s : rank-%s array('%s') with bounds (%s) and %s storage" % (out_a, rank, c2pycode_map[ctype], ','.join(dim), a) elif isexternal(var): ua = '' if a in lcb_map and lcb_map[a] in lcb2_map and ('argname' in lcb2_map[lcb_map[a]]): ua = lcb2_map[lcb_map[a]]['argname'] if not ua == a: ua = ' => %s' % ua else: ua = '' sig = '%s : call-back function%s' % (a, ua) sigout = sig else: errmess('getpydocsign: Could not resolve docsignature for "%s".\n' % a) return (sig, sigout) def getarrdocsign(a, var): ctype = getctype(var) if isstring(var) and (not isarray(var)): sig = "%s : rank-0 array(string(len=%s),'c')" % (a, getstrlength(var)) elif isscalar(var): sig = "%s : rank-0 array(%s,'%s')" % (a, c2py_map[ctype], c2pycode_map[ctype]) elif isarray(var): dim = var['dimension'] rank = repr(len(dim)) sig = "%s : rank-%s array('%s') with bounds (%s)" % (a, rank, c2pycode_map[ctype], ','.join(dim)) return sig def getinit(a, var): if isstring(var): (init, showinit) = ('""', "''") else: (init, showinit) = ('', '') if hasinitvalue(var): init = var['='] showinit = init if iscomplex(var) or iscomplexarray(var): ret = {} try: v = var['='] if ',' in v: (ret['init.r'], ret['init.i']) = markoutercomma(v[1:-1]).split('@,@') else: v = eval(v, {}, {}) (ret['init.r'], ret['init.i']) = (str(v.real), str(v.imag)) except Exception: raise ValueError("getinit: expected complex number `(r,i)' but got `%s' as initial value of %r." % (init, a)) if isarray(var): init = '(capi_c.r=%s,capi_c.i=%s,capi_c)' % (ret['init.r'], ret['init.i']) elif isstring(var): if not init: (init, showinit) = ('""', "''") if init[0] == "'": init = '"%s"' % init[1:-1].replace('"', '\\"') if init[0] == '"': showinit = "'%s'" % init[1:-1] return (init, showinit) def get_elsize(var): if isstring(var) or isstringarray(var): elsize = getstrlength(var) elsize = var['charselector'].get('f2py_len', elsize) return elsize if ischaracter(var) or ischaracterarray(var): return '1' return '1' def sign2map(a, var): out_a = a if isintent_out(var): for k in var['intent']: if k[:4] == 'out=': out_a = k[4:] break ret = {'varname': a, 'outvarname': out_a, 'ctype': getctype(var)} intent_flags = [] for (f, s) in isintent_dict.items(): if f(var): intent_flags.append('F2PY_%s' % s) if intent_flags: ret['intent'] = '|'.join(intent_flags) else: ret['intent'] = 'F2PY_INTENT_IN' if isarray(var): ret['varrformat'] = 'N' elif ret['ctype'] in c2buildvalue_map: ret['varrformat'] = c2buildvalue_map[ret['ctype']] else: ret['varrformat'] = 'O' (ret['init'], ret['showinit']) = getinit(a, var) if hasinitvalue(var) and iscomplex(var) and (not isarray(var)): (ret['init.r'], ret['init.i']) = markoutercomma(ret['init'][1:-1]).split('@,@') if isexternal(var): ret['cbnamekey'] = a if a in lcb_map: ret['cbname'] = lcb_map[a] ret['maxnofargs'] = lcb2_map[lcb_map[a]]['maxnofargs'] ret['nofoptargs'] = lcb2_map[lcb_map[a]]['nofoptargs'] ret['cbdocstr'] = lcb2_map[lcb_map[a]]['docstr'] ret['cblatexdocstr'] = lcb2_map[lcb_map[a]]['latexdocstr'] else: ret['cbname'] = a errmess('sign2map: Confused: external %s is not in lcb_map%s.\n' % (a, list(lcb_map.keys()))) if isstring(var): ret['length'] = getstrlength(var) if isarray(var): ret = dictappend(ret, getarrdims(a, var)) dim = copy.copy(var['dimension']) if ret['ctype'] in c2capi_map: ret['atype'] = c2capi_map[ret['ctype']] ret['elsize'] = get_elsize(var) if debugcapi(var): il = [isintent_in, 'input', isintent_out, 'output', isintent_inout, 'inoutput', isrequired, 'required', isoptional, 'optional', isintent_hide, 'hidden', iscomplex, 'complex scalar', l_and(isscalar, l_not(iscomplex)), 'scalar', isstring, 'string', isarray, 'array', iscomplexarray, 'complex array', isstringarray, 'string array', iscomplexfunction, 'complex function', l_and(isfunction, l_not(iscomplexfunction)), 'function', isexternal, 'callback', isintent_callback, 'callback', isintent_aux, 'auxiliary'] rl = [] for i in range(0, len(il), 2): if il[i](var): rl.append(il[i + 1]) if isstring(var): rl.append('slen(%s)=%s' % (a, ret['length'])) if isarray(var): ddim = ','.join(map(lambda x, y: '%s|%s' % (x, y), var['dimension'], dim)) rl.append('dims(%s)' % ddim) if isexternal(var): ret['vardebuginfo'] = 'debug-capi:%s=>%s:%s' % (a, ret['cbname'], ','.join(rl)) else: ret['vardebuginfo'] = 'debug-capi:%s %s=%s:%s' % (ret['ctype'], a, ret['showinit'], ','.join(rl)) if isscalar(var): if ret['ctype'] in cformat_map: ret['vardebugshowvalue'] = 'debug-capi:%s=%s' % (a, cformat_map[ret['ctype']]) if isstring(var): ret['vardebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (a, a) if isexternal(var): ret['vardebugshowvalue'] = 'debug-capi:%s=%%p' % a if ret['ctype'] in cformat_map: ret['varshowvalue'] = '#name#:%s=%s' % (a, cformat_map[ret['ctype']]) ret['showvalueformat'] = '%s' % cformat_map[ret['ctype']] if isstring(var): ret['varshowvalue'] = '#name#:slen(%s)=%%d %s=\\"%%s\\"' % (a, a) (ret['pydocsign'], ret['pydocsignout']) = getpydocsign(a, var) if hasnote(var): ret['note'] = var['note'] return ret def routsign2map(rout): global lcb_map name = rout['name'] fname = getfortranname(rout) ret = {'name': name, 'texname': name.replace('_', '\\_'), 'name_lower': name.lower(), 'NAME': name.upper(), 'begintitle': gentitle(name), 'endtitle': gentitle('end of %s' % name), 'fortranname': fname, 'FORTRANNAME': fname.upper(), 'callstatement': getcallstatement(rout) or '', 'usercode': getusercode(rout) or '', 'usercode1': getusercode1(rout) or ''} if '_' in fname: ret['F_FUNC'] = 'F_FUNC_US' else: ret['F_FUNC'] = 'F_FUNC' if '_' in name: ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC_US' else: ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC' lcb_map = {} if 'use' in rout: for u in rout['use'].keys(): if u in cb_rules.cb_map: for un in cb_rules.cb_map[u]: ln = un[0] if 'map' in rout['use'][u]: for k in rout['use'][u]['map'].keys(): if rout['use'][u]['map'][k] == un[0]: ln = k break lcb_map[ln] = un[1] elif rout.get('externals'): errmess('routsign2map: Confused: function %s has externals %s but no "use" statement.\n' % (ret['name'], repr(rout['externals']))) ret['callprotoargument'] = getcallprotoargument(rout, lcb_map) or '' if isfunction(rout): if 'result' in rout: a = rout['result'] else: a = rout['name'] ret['rname'] = a (ret['pydocsign'], ret['pydocsignout']) = getpydocsign(a, rout) ret['ctype'] = getctype(rout['vars'][a]) if hasresultnote(rout): ret['resultnote'] = rout['vars'][a]['note'] rout['vars'][a]['note'] = ['See elsewhere.'] if ret['ctype'] in c2buildvalue_map: ret['rformat'] = c2buildvalue_map[ret['ctype']] else: ret['rformat'] = 'O' errmess('routsign2map: no c2buildvalue key for type %s\n' % repr(ret['ctype'])) if debugcapi(rout): if ret['ctype'] in cformat_map: ret['routdebugshowvalue'] = 'debug-capi:%s=%s' % (a, cformat_map[ret['ctype']]) if isstringfunction(rout): ret['routdebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (a, a) if isstringfunction(rout): ret['rlength'] = getstrlength(rout['vars'][a]) if ret['rlength'] == '-1': errmess('routsign2map: expected explicit specification of the length of the string returned by the fortran function %s; taking 10.\n' % repr(rout['name'])) ret['rlength'] = '10' if hasnote(rout): ret['note'] = rout['note'] rout['note'] = ['See elsewhere.'] return ret def modsign2map(m): if ismodule(m): ret = {'f90modulename': m['name'], 'F90MODULENAME': m['name'].upper(), 'texf90modulename': m['name'].replace('_', '\\_')} else: ret = {'modulename': m['name'], 'MODULENAME': m['name'].upper(), 'texmodulename': m['name'].replace('_', '\\_')} ret['restdoc'] = getrestdoc(m) or [] if hasnote(m): ret['note'] = m['note'] ret['usercode'] = getusercode(m) or '' ret['usercode1'] = getusercode1(m) or '' if m['body']: ret['interface_usercode'] = getusercode(m['body'][0]) or '' else: ret['interface_usercode'] = '' ret['pymethoddef'] = getpymethoddef(m) or '' if 'gil_used' in m: ret['gil_used'] = m['gil_used'] if 'coutput' in m: ret['coutput'] = m['coutput'] if 'f2py_wrapper_output' in m: ret['f2py_wrapper_output'] = m['f2py_wrapper_output'] return ret def cb_sign2map(a, var, index=None): ret = {'varname': a} ret['varname_i'] = ret['varname'] ret['ctype'] = getctype(var) if ret['ctype'] in c2capi_map: ret['atype'] = c2capi_map[ret['ctype']] ret['elsize'] = get_elsize(var) if ret['ctype'] in cformat_map: ret['showvalueformat'] = '%s' % cformat_map[ret['ctype']] if isarray(var): ret = dictappend(ret, getarrdims(a, var)) (ret['pydocsign'], ret['pydocsignout']) = getpydocsign(a, var) if hasnote(var): ret['note'] = var['note'] var['note'] = ['See elsewhere.'] return ret def cb_routsign2map(rout, um): ret = {'name': 'cb_%s_in_%s' % (rout['name'], um), 'returncptr': ''} if isintent_callback(rout): if '_' in rout['name']: F_FUNC = 'F_FUNC_US' else: F_FUNC = 'F_FUNC' ret['callbackname'] = '%s(%s,%s)' % (F_FUNC, rout['name'].lower(), rout['name'].upper()) ret['static'] = 'extern' else: ret['callbackname'] = ret['name'] ret['static'] = 'static' ret['argname'] = rout['name'] ret['begintitle'] = gentitle(ret['name']) ret['endtitle'] = gentitle('end of %s' % ret['name']) ret['ctype'] = getctype(rout) ret['rctype'] = 'void' if ret['ctype'] == 'string': ret['rctype'] = 'void' else: ret['rctype'] = ret['ctype'] if ret['rctype'] != 'void': if iscomplexfunction(rout): ret['returncptr'] = '\n#ifdef F2PY_CB_RETURNCOMPLEX\nreturn_value=\n#endif\n' else: ret['returncptr'] = 'return_value=' if ret['ctype'] in cformat_map: ret['showvalueformat'] = '%s' % cformat_map[ret['ctype']] if isstringfunction(rout): ret['strlength'] = getstrlength(rout) if isfunction(rout): if 'result' in rout: a = rout['result'] else: a = rout['name'] if hasnote(rout['vars'][a]): ret['note'] = rout['vars'][a]['note'] rout['vars'][a]['note'] = ['See elsewhere.'] ret['rname'] = a (ret['pydocsign'], ret['pydocsignout']) = getpydocsign(a, rout) if iscomplexfunction(rout): ret['rctype'] = '\n#ifdef F2PY_CB_RETURNCOMPLEX\n#ctype#\n#else\nvoid\n#endif\n' elif hasnote(rout): ret['note'] = rout['note'] rout['note'] = ['See elsewhere.'] nofargs = 0 nofoptargs = 0 if 'args' in rout and 'vars' in rout: for a in rout['args']: var = rout['vars'][a] if l_or(isintent_in, isintent_inout)(var): nofargs = nofargs + 1 if isoptional(var): nofoptargs = nofoptargs + 1 ret['maxnofargs'] = repr(nofargs) ret['nofoptargs'] = repr(nofoptargs) if hasnote(rout) and isfunction(rout) and ('result' in rout): ret['routnote'] = rout['note'] rout['note'] = ['See elsewhere.'] return ret def common_sign2map(a, var): ret = {'varname': a, 'ctype': getctype(var)} if isstringarray(var): ret['ctype'] = 'char' if ret['ctype'] in c2capi_map: ret['atype'] = c2capi_map[ret['ctype']] ret['elsize'] = get_elsize(var) if ret['ctype'] in cformat_map: ret['showvalueformat'] = '%s' % cformat_map[ret['ctype']] if isarray(var): ret = dictappend(ret, getarrdims(a, var)) elif isstring(var): ret['size'] = getstrlength(var) ret['rank'] = '1' (ret['pydocsign'], ret['pydocsignout']) = getpydocsign(a, var) if hasnote(var): ret['note'] = var['note'] var['note'] = ['See elsewhere.'] ret['arrdocstr'] = getarrdocsign(a, var) return ret # File: numpy-main/numpy/f2py/cb_rules.py """""" from . import __version__ from .auxfuncs import applyrules, debugcapi, dictappend, errmess, getargs, hasnote, isarray, iscomplex, iscomplexarray, iscomplexfunction, isfunction, isintent_c, isintent_hide, isintent_in, isintent_inout, isintent_nothide, isintent_out, isoptional, isrequired, isscalar, isstring, isstringfunction, issubroutine, l_and, l_not, l_or, outmess, replace, stripcomma, throw_error from . import cfuncs f2py_version = __version__.version cb_routine_rules = {'cbtypedefs': 'typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);', 'body': '\n#begintitle#\ntypedef struct {\n PyObject *capi;\n PyTupleObject *args_capi;\n int nofargs;\n jmp_buf jmpbuf;\n} #name#_t;\n\n#if defined(F2PY_THREAD_LOCAL_DECL) && !defined(F2PY_USE_PYTHON_TLS)\n\nstatic F2PY_THREAD_LOCAL_DECL #name#_t *_active_#name# = NULL;\n\nstatic #name#_t *swap_active_#name#(#name#_t *ptr) {\n #name#_t *prev = _active_#name#;\n _active_#name# = ptr;\n return prev;\n}\n\nstatic #name#_t *get_active_#name#(void) {\n return _active_#name#;\n}\n\n#else\n\nstatic #name#_t *swap_active_#name#(#name#_t *ptr) {\n char *key = "__f2py_cb_#name#";\n return (#name#_t *)F2PySwapThreadLocalCallbackPtr(key, ptr);\n}\n\nstatic #name#_t *get_active_#name#(void) {\n char *key = "__f2py_cb_#name#";\n return (#name#_t *)F2PyGetThreadLocalCallbackPtr(key);\n}\n\n#endif\n\n/*typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);*/\n#static# #rctype# #callbackname# (#optargs##args##strarglens##noargs#) {\n #name#_t cb_local = { NULL, NULL, 0 };\n #name#_t *cb = NULL;\n PyTupleObject *capi_arglist = NULL;\n PyObject *capi_return = NULL;\n PyObject *capi_tmp = NULL;\n PyObject *capi_arglist_list = NULL;\n int capi_j,capi_i = 0;\n int capi_longjmp_ok = 1;\n#decl#\n#ifdef F2PY_REPORT_ATEXIT\nf2py_cb_start_clock();\n#endif\n cb = get_active_#name#();\n if (cb == NULL) {\n capi_longjmp_ok = 0;\n cb = &cb_local;\n }\n capi_arglist = cb->args_capi;\n CFUNCSMESS("cb:Call-back function #name# (maxnofargs=#maxnofargs#(-#nofoptargs#))\\n");\n CFUNCSMESSPY("cb:#name#_capi=",cb->capi);\n if (cb->capi==NULL) {\n capi_longjmp_ok = 0;\n cb->capi = PyObject_GetAttrString(#modulename#_module,"#argname#");\n CFUNCSMESSPY("cb:#name#_capi=",cb->capi);\n }\n if (cb->capi==NULL) {\n PyErr_SetString(#modulename#_error,"cb: Callback #argname# not defined (as an argument or module #modulename# attribute).\\n");\n goto capi_fail;\n }\n if (F2PyCapsule_Check(cb->capi)) {\n #name#_typedef #name#_cptr;\n #name#_cptr = F2PyCapsule_AsVoidPtr(cb->capi);\n #returncptr#(*#name#_cptr)(#optargs_nm##args_nm##strarglens_nm#);\n #return#\n }\n if (capi_arglist==NULL) {\n capi_longjmp_ok = 0;\n capi_tmp = PyObject_GetAttrString(#modulename#_module,"#argname#_extra_args");\n if (capi_tmp) {\n capi_arglist = (PyTupleObject *)PySequence_Tuple(capi_tmp);\n Py_DECREF(capi_tmp);\n if (capi_arglist==NULL) {\n PyErr_SetString(#modulename#_error,"Failed to convert #modulename#.#argname#_extra_args to tuple.\\n");\n goto capi_fail;\n }\n } else {\n PyErr_Clear();\n capi_arglist = (PyTupleObject *)Py_BuildValue("()");\n }\n }\n if (capi_arglist == NULL) {\n PyErr_SetString(#modulename#_error,"Callback #argname# argument list is not set.\\n");\n goto capi_fail;\n }\n#setdims#\n#ifdef PYPY_VERSION\n#define CAPI_ARGLIST_SETITEM(idx, value) PyList_SetItem((PyObject *)capi_arglist_list, idx, value)\n capi_arglist_list = PySequence_List((PyObject *)capi_arglist);\n if (capi_arglist_list == NULL) goto capi_fail;\n#else\n#define CAPI_ARGLIST_SETITEM(idx, value) PyTuple_SetItem((PyObject *)capi_arglist, idx, value)\n#endif\n#pyobjfrom#\n#undef CAPI_ARGLIST_SETITEM\n#ifdef PYPY_VERSION\n CFUNCSMESSPY("cb:capi_arglist=",capi_arglist_list);\n#else\n CFUNCSMESSPY("cb:capi_arglist=",capi_arglist);\n#endif\n CFUNCSMESS("cb:Call-back calling Python function #argname#.\\n");\n#ifdef F2PY_REPORT_ATEXIT\nf2py_cb_start_call_clock();\n#endif\n#ifdef PYPY_VERSION\n capi_return = PyObject_CallObject(cb->capi,(PyObject *)capi_arglist_list);\n Py_DECREF(capi_arglist_list);\n capi_arglist_list = NULL;\n#else\n capi_return = PyObject_CallObject(cb->capi,(PyObject *)capi_arglist);\n#endif\n#ifdef F2PY_REPORT_ATEXIT\nf2py_cb_stop_call_clock();\n#endif\n CFUNCSMESSPY("cb:capi_return=",capi_return);\n if (capi_return == NULL) {\n fprintf(stderr,"capi_return is NULL\\n");\n goto capi_fail;\n }\n if (capi_return == Py_None) {\n Py_DECREF(capi_return);\n capi_return = Py_BuildValue("()");\n }\n else if (!PyTuple_Check(capi_return)) {\n capi_return = Py_BuildValue("(N)",capi_return);\n }\n capi_j = PyTuple_Size(capi_return);\n capi_i = 0;\n#frompyobj#\n CFUNCSMESS("cb:#name#:successful\\n");\n Py_DECREF(capi_return);\n#ifdef F2PY_REPORT_ATEXIT\nf2py_cb_stop_clock();\n#endif\n goto capi_return_pt;\ncapi_fail:\n fprintf(stderr,"Call-back #name# failed.\\n");\n Py_XDECREF(capi_return);\n Py_XDECREF(capi_arglist_list);\n if (capi_longjmp_ok) {\n longjmp(cb->jmpbuf,-1);\n }\ncapi_return_pt:\n ;\n#return#\n}\n#endtitle#\n', 'need': ['setjmp.h', 'CFUNCSMESS', 'F2PY_THREAD_LOCAL_DECL'], 'maxnofargs': '#maxnofargs#', 'nofoptargs': '#nofoptargs#', 'docstr': ' def #argname#(#docsignature#): return #docreturn#\\n\\\n#docstrsigns#', 'latexdocstr': '\n{{}\\verb@def #argname#(#latexdocsignature#): return #docreturn#@{}}\n#routnote#\n\n#latexdocstrsigns#', 'docstrshort': 'def #argname#(#docsignature#): return #docreturn#'} cb_rout_rules = [{'separatorsfor': {'decl': '\n', 'args': ',', 'optargs': '', 'pyobjfrom': '\n', 'freemem': '\n', 'args_td': ',', 'optargs_td': '', 'args_nm': ',', 'optargs_nm': '', 'frompyobj': '\n', 'setdims': '\n', 'docstrsigns': '\\n"\n"', 'latexdocstrsigns': '\n', 'latexdocstrreq': '\n', 'latexdocstropt': '\n', 'latexdocstrout': '\n', 'latexdocstrcbs': '\n'}, 'decl': '/*decl*/', 'pyobjfrom': '/*pyobjfrom*/', 'frompyobj': '/*frompyobj*/', 'args': [], 'optargs': '', 'return': '', 'strarglens': '', 'freemem': '/*freemem*/', 'args_td': [], 'optargs_td': '', 'strarglens_td': '', 'args_nm': [], 'optargs_nm': '', 'strarglens_nm': '', 'noargs': '', 'setdims': '/*setdims*/', 'docstrsigns': '', 'latexdocstrsigns': '', 'docstrreq': ' Required arguments:', 'docstropt': ' Optional arguments:', 'docstrout': ' Return objects:', 'docstrcbs': ' Call-back functions:', 'docreturn': '', 'docsign': '', 'docsignopt': '', 'latexdocstrreq': '\\noindent Required arguments:', 'latexdocstropt': '\\noindent Optional arguments:', 'latexdocstrout': '\\noindent Return objects:', 'latexdocstrcbs': '\\noindent Call-back functions:', 'routnote': {hasnote: '--- #note#', l_not(hasnote): ''}}, {'decl': ' #ctype# return_value = 0;', 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting return_value->");'}, ' if (capi_j>capi_i) {\n GETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,\n "#ctype#_from_pyobj failed in converting return_value of"\n " call-back function #name# to C #ctype#\\n");\n } else {\n fprintf(stderr,"Warning: call-back function #name# did not provide"\n " return value (index=%d, type=#ctype#)\\n",capi_i);\n }', {debugcapi: ' fprintf(stderr,"#showvalueformat#.\\n",return_value);'}], 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, 'GETSCALARFROMPYTUPLE'], 'return': ' return return_value;', '_check': l_and(isfunction, l_not(isstringfunction), l_not(iscomplexfunction))}, {'pyobjfrom': {debugcapi: ' fprintf(stderr,"debug-capi:cb:#name#:%d:\\n",return_value_len);'}, 'args': '#ctype# return_value,int return_value_len', 'args_nm': 'return_value,&return_value_len', 'args_td': '#ctype# ,int', 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting return_value->\\"");'}, ' if (capi_j>capi_i) {\n GETSTRFROMPYTUPLE(capi_return,capi_i++,return_value,return_value_len);\n } else {\n fprintf(stderr,"Warning: call-back function #name# did not provide"\n " return value (index=%d, type=#ctype#)\\n",capi_i);\n }', {debugcapi: ' fprintf(stderr,"#showvalueformat#\\".\\n",return_value);'}], 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, 'string.h', 'GETSTRFROMPYTUPLE'], 'return': 'return;', '_check': isstringfunction}, {'optargs': '\n#ifndef F2PY_CB_RETURNCOMPLEX\n#ctype# *return_value\n#endif\n', 'optargs_nm': '\n#ifndef F2PY_CB_RETURNCOMPLEX\nreturn_value\n#endif\n', 'optargs_td': '\n#ifndef F2PY_CB_RETURNCOMPLEX\n#ctype# *\n#endif\n', 'decl': '\n#ifdef F2PY_CB_RETURNCOMPLEX\n #ctype# return_value = {0, 0};\n#endif\n', 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting return_value->");'}, ' if (capi_j>capi_i) {\n#ifdef F2PY_CB_RETURNCOMPLEX\n GETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,\n "#ctype#_from_pyobj failed in converting return_value of call-back"\n " function #name# to C #ctype#\\n");\n#else\n GETSCALARFROMPYTUPLE(capi_return,capi_i++,return_value,#ctype#,\n "#ctype#_from_pyobj failed in converting return_value of call-back"\n " function #name# to C #ctype#\\n");\n#endif\n } else {\n fprintf(stderr,\n "Warning: call-back function #name# did not provide"\n " return value (index=%d, type=#ctype#)\\n",capi_i);\n }', {debugcapi: '#ifdef F2PY_CB_RETURNCOMPLEX\n fprintf(stderr,"#showvalueformat#.\\n",(return_value).r,(return_value).i);\n#else\n fprintf(stderr,"#showvalueformat#.\\n",(*return_value).r,(*return_value).i);\n#endif\n'}], 'return': '\n#ifdef F2PY_CB_RETURNCOMPLEX\n return return_value;\n#else\n return;\n#endif\n', 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, 'string.h', 'GETSCALARFROMPYTUPLE', '#ctype#'], '_check': iscomplexfunction}, {'docstrout': ' #pydocsignout#', 'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}', {hasnote: '--- #note#'}], 'docreturn': '#rname#,', '_check': isfunction}, {'_check': issubroutine, 'return': 'return;'}] cb_arg_rules = [{'docstropt': {l_and(isoptional, isintent_nothide): ' #pydocsign#'}, 'docstrreq': {l_and(isrequired, isintent_nothide): ' #pydocsign#'}, 'docstrout': {isintent_out: ' #pydocsignout#'}, 'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote: '--- #note#'}]}, 'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote: '--- #note#'}]}, 'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}', {l_and(hasnote, isintent_hide): '--- #note#', l_and(hasnote, isintent_nothide): '--- See above.'}]}, 'docsign': {l_and(isrequired, isintent_nothide): '#varname#,'}, 'docsignopt': {l_and(isoptional, isintent_nothide): '#varname#,'}, 'depend': ''}, {'args': {l_and(isscalar, isintent_c): '#ctype# #varname_i#', l_and(isscalar, l_not(isintent_c)): '#ctype# *#varname_i#_cb_capi', isarray: '#ctype# *#varname_i#', isstring: '#ctype# #varname_i#'}, 'args_nm': {l_and(isscalar, isintent_c): '#varname_i#', l_and(isscalar, l_not(isintent_c)): '#varname_i#_cb_capi', isarray: '#varname_i#', isstring: '#varname_i#'}, 'args_td': {l_and(isscalar, isintent_c): '#ctype#', l_and(isscalar, l_not(isintent_c)): '#ctype# *', isarray: '#ctype# *', isstring: '#ctype#'}, 'need': {l_or(isscalar, isarray, isstring): '#ctype#'}, 'strarglens': {isstring: ',int #varname_i#_cb_len'}, 'strarglens_td': {isstring: ',int'}, 'strarglens_nm': {isstring: ',#varname_i#_cb_len'}}, {'decl': {l_not(isintent_c): ' #ctype# #varname_i#=(*#varname_i#_cb_capi);'}, 'error': {l_and(isintent_c, isintent_out, throw_error('intent(c,out) is forbidden for callback scalar arguments')): ''}, 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->");'}, {isintent_out: ' if (capi_j>capi_i)\n GETSCALARFROMPYTUPLE(capi_return,capi_i++,#varname_i#_cb_capi,#ctype#,"#ctype#_from_pyobj failed in converting argument #varname# of call-back function #name# to C #ctype#\\n");'}, {l_and(debugcapi, l_and(l_not(iscomplex), isintent_c)): ' fprintf(stderr,"#showvalueformat#.\\n",#varname_i#);'}, {l_and(debugcapi, l_and(l_not(iscomplex), l_not(isintent_c))): ' fprintf(stderr,"#showvalueformat#.\\n",*#varname_i#_cb_capi);'}, {l_and(debugcapi, l_and(iscomplex, isintent_c)): ' fprintf(stderr,"#showvalueformat#.\\n",(#varname_i#).r,(#varname_i#).i);'}, {l_and(debugcapi, l_and(iscomplex, l_not(isintent_c))): ' fprintf(stderr,"#showvalueformat#.\\n",(*#varname_i#_cb_capi).r,(*#varname_i#_cb_capi).i);'}], 'need': [{isintent_out: ['#ctype#_from_pyobj', 'GETSCALARFROMPYTUPLE']}, {debugcapi: 'CFUNCSMESS'}], '_check': isscalar}, {'pyobjfrom': [{isintent_in: ' if (cb->nofargs>capi_i)\n if (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1(#varname_i#)))\n goto capi_fail;'}, {isintent_inout: ' if (cb->nofargs>capi_i)\n if (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#_cb_capi)))\n goto capi_fail;'}], 'need': [{isintent_in: 'pyobj_from_#ctype#1'}, {isintent_inout: 'pyarr_from_p_#ctype#1'}, {iscomplex: '#ctype#'}], '_check': l_and(isscalar, isintent_nothide), '_optional': ''}, {'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->\\"");'}, ' if (capi_j>capi_i)\n GETSTRFROMPYTUPLE(capi_return,capi_i++,#varname_i#,#varname_i#_cb_len);', {debugcapi: ' fprintf(stderr,"#showvalueformat#\\":%d:.\\n",#varname_i#,#varname_i#_cb_len);'}], 'need': ['#ctype#', 'GETSTRFROMPYTUPLE', {debugcapi: 'CFUNCSMESS'}, 'string.h'], '_check': l_and(isstring, isintent_out)}, {'pyobjfrom': [{debugcapi: ' fprintf(stderr,"debug-capi:cb:#varname#=#showvalueformat#:%d:\\n",#varname_i#,#varname_i#_cb_len);'}, {isintent_in: ' if (cb->nofargs>capi_i)\n if (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1size(#varname_i#,#varname_i#_cb_len)))\n goto capi_fail;'}, {isintent_inout: ' if (cb->nofargs>capi_i) {\n int #varname_i#_cb_dims[] = {#varname_i#_cb_len};\n if (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#,#varname_i#_cb_dims)))\n goto capi_fail;\n }'}], 'need': [{isintent_in: 'pyobj_from_#ctype#1size'}, {isintent_inout: 'pyarr_from_p_#ctype#1'}], '_check': l_and(isstring, isintent_nothide), '_optional': ''}, {'decl': ' npy_intp #varname_i#_Dims[#rank#] = {#rank*[-1]#};', 'setdims': ' #cbsetdims#;', '_check': isarray, '_depend': ''}, {'pyobjfrom': [{debugcapi: ' fprintf(stderr,"debug-capi:cb:#varname#\\n");'}, {isintent_c: ' if (cb->nofargs>capi_i) {\n /* tmp_arr will be inserted to capi_arglist_list that will be\n destroyed when leaving callback function wrapper together\n with tmp_arr. */\n PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,\n #rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,#elsize#,\n NPY_ARRAY_CARRAY,NULL);\n', l_not(isintent_c): ' if (cb->nofargs>capi_i) {\n /* tmp_arr will be inserted to capi_arglist_list that will be\n destroyed when leaving callback function wrapper together\n with tmp_arr. */\n PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,\n #rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,#elsize#,\n NPY_ARRAY_FARRAY,NULL);\n'}, '\n if (tmp_arr==NULL)\n goto capi_fail;\n if (CAPI_ARGLIST_SETITEM(capi_i++,(PyObject *)tmp_arr))\n goto capi_fail;\n}'], '_check': l_and(isarray, isintent_nothide, l_or(isintent_in, isintent_inout)), '_optional': ''}, {'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->");'}, ' if (capi_j>capi_i) {\n PyArrayObject *rv_cb_arr = NULL;\n if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail;\n rv_cb_arr = array_from_pyobj(#atype#,#varname_i#_Dims,#rank#,F2PY_INTENT_IN', {isintent_c: '|F2PY_INTENT_C'}, ',capi_tmp);\n if (rv_cb_arr == NULL) {\n fprintf(stderr,"rv_cb_arr is NULL\\n");\n goto capi_fail;\n }\n MEMCOPY(#varname_i#,PyArray_DATA(rv_cb_arr),PyArray_NBYTES(rv_cb_arr));\n if (capi_tmp != (PyObject *)rv_cb_arr) {\n Py_DECREF(rv_cb_arr);\n }\n }', {debugcapi: ' fprintf(stderr,"<-.\\n");'}], 'need': ['MEMCOPY', {iscomplexarray: '#ctype#'}], '_check': l_and(isarray, isintent_out)}, {'docreturn': '#varname#,', '_check': isintent_out}] cb_map = {} def buildcallbacks(m): cb_map[m['name']] = [] for bi in m['body']: if bi['block'] == 'interface': for b in bi['body']: if b: buildcallback(b, m['name']) else: errmess('warning: empty body for %s\n' % m['name']) def buildcallback(rout, um): from . import capi_maps outmess(' Constructing call-back function "cb_%s_in_%s"\n' % (rout['name'], um)) (args, depargs) = getargs(rout) capi_maps.depargs = depargs var = rout['vars'] vrd = capi_maps.cb_routsign2map(rout, um) rd = dictappend({}, vrd) cb_map[um].append([rout['name'], rd['name']]) for r in cb_rout_rules: if '_check' in r and r['_check'](rout) or '_check' not in r: ar = applyrules(r, vrd, rout) rd = dictappend(rd, ar) savevrd = {} for (i, a) in enumerate(args): vrd = capi_maps.cb_sign2map(a, var[a], index=i) savevrd[a] = vrd for r in cb_arg_rules: if '_depend' in r: continue if '_optional' in r and isoptional(var[a]): continue if '_check' in r and r['_check'](var[a]) or '_check' not in r: ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break for a in args: vrd = savevrd[a] for r in cb_arg_rules: if '_depend' in r: continue if '_optional' not in r or ('_optional' in r and isrequired(var[a])): continue if '_check' in r and r['_check'](var[a]) or '_check' not in r: ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break for a in depargs: vrd = savevrd[a] for r in cb_arg_rules: if '_depend' not in r: continue if '_optional' in r: continue if '_check' in r and r['_check'](var[a]) or '_check' not in r: ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break if 'args' in rd and 'optargs' in rd: if isinstance(rd['optargs'], list): rd['optargs'] = rd['optargs'] + ['\n#ifndef F2PY_CB_RETURNCOMPLEX\n,\n#endif\n'] rd['optargs_nm'] = rd['optargs_nm'] + ['\n#ifndef F2PY_CB_RETURNCOMPLEX\n,\n#endif\n'] rd['optargs_td'] = rd['optargs_td'] + ['\n#ifndef F2PY_CB_RETURNCOMPLEX\n,\n#endif\n'] if isinstance(rd['docreturn'], list): rd['docreturn'] = stripcomma(replace('#docreturn#', {'docreturn': rd['docreturn']})) optargs = stripcomma(replace('#docsignopt#', {'docsignopt': rd['docsignopt']})) if optargs == '': rd['docsignature'] = stripcomma(replace('#docsign#', {'docsign': rd['docsign']})) else: rd['docsignature'] = replace('#docsign#[#docsignopt#]', {'docsign': rd['docsign'], 'docsignopt': optargs}) rd['latexdocsignature'] = rd['docsignature'].replace('_', '\\_') rd['latexdocsignature'] = rd['latexdocsignature'].replace(',', ', ') rd['docstrsigns'] = [] rd['latexdocstrsigns'] = [] for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']: if k in rd and isinstance(rd[k], list): rd['docstrsigns'] = rd['docstrsigns'] + rd[k] k = 'latex' + k if k in rd and isinstance(rd[k], list): rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] + ['\\begin{description}'] + rd[k][1:] + ['\\end{description}'] if 'args' not in rd: rd['args'] = '' rd['args_td'] = '' rd['args_nm'] = '' if not (rd.get('args') or rd.get('optargs') or rd.get('strarglens')): rd['noargs'] = 'void' ar = applyrules(cb_routine_rules, rd) cfuncs.callbacks[rd['name']] = ar['body'] if isinstance(ar['need'], str): ar['need'] = [ar['need']] if 'need' in rd: for t in cfuncs.typedefs.keys(): if t in rd['need']: ar['need'].append(t) cfuncs.typedefs_generated[rd['name'] + '_typedef'] = ar['cbtypedefs'] ar['need'].append(rd['name'] + '_typedef') cfuncs.needs[rd['name']] = ar['need'] capi_maps.lcb2_map[rd['name']] = {'maxnofargs': ar['maxnofargs'], 'nofoptargs': ar['nofoptargs'], 'docstr': ar['docstr'], 'latexdocstr': ar['latexdocstr'], 'argname': rd['argname']} outmess(' %s\n' % ar['docstrshort']) return # File: numpy-main/numpy/f2py/cfuncs.py """""" import sys import copy from . import __version__ f2py_version = __version__.version def errmess(s: str) -> None: if sys.stderr is not None: sys.stderr.write(s) outneeds = {'includes0': [], 'includes': [], 'typedefs': [], 'typedefs_generated': [], 'userincludes': [], 'cppmacros': [], 'cfuncs': [], 'callbacks': [], 'f90modhooks': [], 'commonhooks': []} needs = {} includes0 = {'includes0': '/*need_includes0*/'} includes = {'includes': '/*need_includes*/'} userincludes = {'userincludes': '/*need_userincludes*/'} typedefs = {'typedefs': '/*need_typedefs*/'} typedefs_generated = {'typedefs_generated': '/*need_typedefs_generated*/'} cppmacros = {'cppmacros': '/*need_cppmacros*/'} cfuncs = {'cfuncs': '/*need_cfuncs*/'} callbacks = {'callbacks': '/*need_callbacks*/'} f90modhooks = {'f90modhooks': '/*need_f90modhooks*/', 'initf90modhooksstatic': '/*initf90modhooksstatic*/', 'initf90modhooksdynamic': '/*initf90modhooksdynamic*/'} commonhooks = {'commonhooks': '/*need_commonhooks*/', 'initcommonhooks': '/*need_initcommonhooks*/'} includes0['math.h'] = '#include ' includes0['string.h'] = '#include ' includes0['setjmp.h'] = '#include ' includes['arrayobject.h'] = '#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API\n#include "arrayobject.h"' includes['npy_math.h'] = '#include "numpy/npy_math.h"' includes['arrayobject.h'] = '#include "fortranobject.h"' includes['stdarg.h'] = '#include ' typedefs['unsigned_char'] = 'typedef unsigned char unsigned_char;' typedefs['unsigned_short'] = 'typedef unsigned short unsigned_short;' typedefs['unsigned_long'] = 'typedef unsigned long unsigned_long;' typedefs['signed_char'] = 'typedef signed char signed_char;' typedefs['long_long'] = '\n#if defined(NPY_OS_WIN32)\ntypedef __int64 long_long;\n#else\ntypedef long long long_long;\ntypedef unsigned long long unsigned_long_long;\n#endif\n' typedefs['unsigned_long_long'] = '\n#if defined(NPY_OS_WIN32)\ntypedef __uint64 long_long;\n#else\ntypedef unsigned long long unsigned_long_long;\n#endif\n' typedefs['long_double'] = '\n#ifndef _LONG_DOUBLE\ntypedef long double long_double;\n#endif\n' typedefs['complex_long_double'] = 'typedef struct {long double r,i;} complex_long_double;' typedefs['complex_float'] = 'typedef struct {float r,i;} complex_float;' typedefs['complex_double'] = 'typedef struct {double r,i;} complex_double;' typedefs['string'] = 'typedef char * string;' typedefs['character'] = 'typedef char character;' cppmacros['CFUNCSMESS'] = '\n#ifdef DEBUGCFUNCS\n#define CFUNCSMESS(mess) fprintf(stderr,"debug-capi:"mess);\n#define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \\\n PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\\n fprintf(stderr,"\\n");\n#else\n#define CFUNCSMESS(mess)\n#define CFUNCSMESSPY(mess,obj)\n#endif\n' cppmacros['F_FUNC'] = '\n#if defined(PREPEND_FORTRAN)\n#if defined(NO_APPEND_FORTRAN)\n#if defined(UPPERCASE_FORTRAN)\n#define F_FUNC(f,F) _##F\n#else\n#define F_FUNC(f,F) _##f\n#endif\n#else\n#if defined(UPPERCASE_FORTRAN)\n#define F_FUNC(f,F) _##F##_\n#else\n#define F_FUNC(f,F) _##f##_\n#endif\n#endif\n#else\n#if defined(NO_APPEND_FORTRAN)\n#if defined(UPPERCASE_FORTRAN)\n#define F_FUNC(f,F) F\n#else\n#define F_FUNC(f,F) f\n#endif\n#else\n#if defined(UPPERCASE_FORTRAN)\n#define F_FUNC(f,F) F##_\n#else\n#define F_FUNC(f,F) f##_\n#endif\n#endif\n#endif\n#if defined(UNDERSCORE_G77)\n#define F_FUNC_US(f,F) F_FUNC(f##_,F##_)\n#else\n#define F_FUNC_US(f,F) F_FUNC(f,F)\n#endif\n' cppmacros['F_WRAPPEDFUNC'] = '\n#if defined(PREPEND_FORTRAN)\n#if defined(NO_APPEND_FORTRAN)\n#if defined(UPPERCASE_FORTRAN)\n#define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F\n#else\n#define F_WRAPPEDFUNC(f,F) _f2pywrap##f\n#endif\n#else\n#if defined(UPPERCASE_FORTRAN)\n#define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F##_\n#else\n#define F_WRAPPEDFUNC(f,F) _f2pywrap##f##_\n#endif\n#endif\n#else\n#if defined(NO_APPEND_FORTRAN)\n#if defined(UPPERCASE_FORTRAN)\n#define F_WRAPPEDFUNC(f,F) F2PYWRAP##F\n#else\n#define F_WRAPPEDFUNC(f,F) f2pywrap##f\n#endif\n#else\n#if defined(UPPERCASE_FORTRAN)\n#define F_WRAPPEDFUNC(f,F) F2PYWRAP##F##_\n#else\n#define F_WRAPPEDFUNC(f,F) f2pywrap##f##_\n#endif\n#endif\n#endif\n#if defined(UNDERSCORE_G77)\n#define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f##_,F##_)\n#else\n#define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f,F)\n#endif\n' cppmacros['F_MODFUNC'] = '\n#if defined(F90MOD2CCONV1) /*E.g. Compaq Fortran */\n#if defined(NO_APPEND_FORTRAN)\n#define F_MODFUNCNAME(m,f) $ ## m ## $ ## f\n#else\n#define F_MODFUNCNAME(m,f) $ ## m ## $ ## f ## _\n#endif\n#endif\n\n#if defined(F90MOD2CCONV2) /*E.g. IBM XL Fortran, not tested though */\n#if defined(NO_APPEND_FORTRAN)\n#define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f\n#else\n#define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f ## _\n#endif\n#endif\n\n#if defined(F90MOD2CCONV3) /*E.g. MIPSPro Compilers */\n#if defined(NO_APPEND_FORTRAN)\n#define F_MODFUNCNAME(m,f) f ## .in. ## m\n#else\n#define F_MODFUNCNAME(m,f) f ## .in. ## m ## _\n#endif\n#endif\n/*\n#if defined(UPPERCASE_FORTRAN)\n#define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(M,F)\n#else\n#define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(m,f)\n#endif\n*/\n\n#define F_MODFUNC(m,f) (*(f2pymodstruct##m##.##f))\n' cppmacros['SWAPUNSAFE'] = '\n#define SWAP(a,b) (size_t)(a) = ((size_t)(a) ^ (size_t)(b));\\\n (size_t)(b) = ((size_t)(a) ^ (size_t)(b));\\\n (size_t)(a) = ((size_t)(a) ^ (size_t)(b))\n' cppmacros['SWAP'] = '\n#define SWAP(a,b,t) {\\\n t *c;\\\n c = a;\\\n a = b;\\\n b = c;}\n' cppmacros['PRINTPYOBJERR'] = '\n#define PRINTPYOBJERR(obj)\\\n fprintf(stderr,"#modulename#.error is related to ");\\\n PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\\n fprintf(stderr,"\\n");\n' cppmacros['MINMAX'] = '\n#ifndef max\n#define max(a,b) ((a > b) ? (a) : (b))\n#endif\n#ifndef min\n#define min(a,b) ((a < b) ? (a) : (b))\n#endif\n#ifndef MAX\n#define MAX(a,b) ((a > b) ? (a) : (b))\n#endif\n#ifndef MIN\n#define MIN(a,b) ((a < b) ? (a) : (b))\n#endif\n' cppmacros['len..'] = '\n/* See fortranobject.h for definitions. The macros here are provided for BC. */\n#define rank f2py_rank\n#define shape f2py_shape\n#define fshape f2py_shape\n#define len f2py_len\n#define flen f2py_flen\n#define slen f2py_slen\n#define size f2py_size\n' cppmacros['pyobj_from_char1'] = '\n#define pyobj_from_char1(v) (PyLong_FromLong(v))\n' cppmacros['pyobj_from_short1'] = '\n#define pyobj_from_short1(v) (PyLong_FromLong(v))\n' needs['pyobj_from_int1'] = ['signed_char'] cppmacros['pyobj_from_int1'] = '\n#define pyobj_from_int1(v) (PyLong_FromLong(v))\n' cppmacros['pyobj_from_long1'] = '\n#define pyobj_from_long1(v) (PyLong_FromLong(v))\n' needs['pyobj_from_long_long1'] = ['long_long'] cppmacros['pyobj_from_long_long1'] = '\n#ifdef HAVE_LONG_LONG\n#define pyobj_from_long_long1(v) (PyLong_FromLongLong(v))\n#else\n#warning HAVE_LONG_LONG is not available. Redefining pyobj_from_long_long.\n#define pyobj_from_long_long1(v) (PyLong_FromLong(v))\n#endif\n' needs['pyobj_from_long_double1'] = ['long_double'] cppmacros['pyobj_from_long_double1'] = '\n#define pyobj_from_long_double1(v) (PyFloat_FromDouble(v))' cppmacros['pyobj_from_double1'] = '\n#define pyobj_from_double1(v) (PyFloat_FromDouble(v))' cppmacros['pyobj_from_float1'] = '\n#define pyobj_from_float1(v) (PyFloat_FromDouble(v))' needs['pyobj_from_complex_long_double1'] = ['complex_long_double'] cppmacros['pyobj_from_complex_long_double1'] = '\n#define pyobj_from_complex_long_double1(v) (PyComplex_FromDoubles(v.r,v.i))' needs['pyobj_from_complex_double1'] = ['complex_double'] cppmacros['pyobj_from_complex_double1'] = '\n#define pyobj_from_complex_double1(v) (PyComplex_FromDoubles(v.r,v.i))' needs['pyobj_from_complex_float1'] = ['complex_float'] cppmacros['pyobj_from_complex_float1'] = '\n#define pyobj_from_complex_float1(v) (PyComplex_FromDoubles(v.r,v.i))' needs['pyobj_from_string1'] = ['string'] cppmacros['pyobj_from_string1'] = '\n#define pyobj_from_string1(v) (PyUnicode_FromString((char *)v))' needs['pyobj_from_string1size'] = ['string'] cppmacros['pyobj_from_string1size'] = '\n#define pyobj_from_string1size(v,len) (PyUnicode_FromStringAndSize((char *)v, len))' needs['TRYPYARRAYTEMPLATE'] = ['PRINTPYOBJERR'] cppmacros['TRYPYARRAYTEMPLATE'] = '\n/* New SciPy */\n#define TRYPYARRAYTEMPLATECHAR case NPY_STRING: *(char *)(PyArray_DATA(arr))=*v; break;\n#define TRYPYARRAYTEMPLATELONG case NPY_LONG: *(long *)(PyArray_DATA(arr))=*v; break;\n#define TRYPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr,PyArray_DATA(arr),pyobj_from_ ## ctype ## 1(*v)); break;\n\n#define TRYPYARRAYTEMPLATE(ctype,typecode) \\\n PyArrayObject *arr = NULL;\\\n if (!obj) return -2;\\\n if (!PyArray_Check(obj)) return -1;\\\n if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,"TRYPYARRAYTEMPLATE:");PRINTPYOBJERR(obj);return 0;}\\\n if (PyArray_DESCR(arr)->type==typecode) {*(ctype *)(PyArray_DATA(arr))=*v; return 1;}\\\n switch (PyArray_TYPE(arr)) {\\\n case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=(*v!=0); break;\\\n case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\\n case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_ ## ctype ## 1(*v)); break;\\\n default: return -2;\\\n };\\\n return 1\n' needs['TRYCOMPLEXPYARRAYTEMPLATE'] = ['PRINTPYOBJERR'] cppmacros['TRYCOMPLEXPYARRAYTEMPLATE'] = '\n#define TRYCOMPLEXPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;\n#define TRYCOMPLEXPYARRAYTEMPLATE(ctype,typecode)\\\n PyArrayObject *arr = NULL;\\\n if (!obj) return -2;\\\n if (!PyArray_Check(obj)) return -1;\\\n if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,"TRYCOMPLEXPYARRAYTEMPLATE:");PRINTPYOBJERR(obj);return 0;}\\\n if (PyArray_DESCR(arr)->type==typecode) {\\\n *(ctype *)(PyArray_DATA(arr))=(*v).r;\\\n *(ctype *)(PyArray_DATA(arr)+sizeof(ctype))=(*v).i;\\\n return 1;\\\n }\\\n switch (PyArray_TYPE(arr)) {\\\n case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r;\\\n *(npy_double *)(PyArray_DATA(arr)+sizeof(npy_double))=(*v).i;\\\n break;\\\n case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r;\\\n *(npy_float *)(PyArray_DATA(arr)+sizeof(npy_float))=(*v).i;\\\n break;\\\n case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=((*v).r!=0 && (*v).i!=0); break;\\\n case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r; break;\\\n case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r;\\\n *(npy_longdouble *)(PyArray_DATA(arr)+sizeof(npy_longdouble))=(*v).i;\\\n break;\\\n case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;\\\n default: return -2;\\\n };\\\n return -1;\n' needs['GETSTRFROMPYTUPLE'] = ['STRINGCOPYN', 'PRINTPYOBJERR'] cppmacros['GETSTRFROMPYTUPLE'] = '\n#define GETSTRFROMPYTUPLE(tuple,index,str,len) {\\\n PyObject *rv_cb_str = PyTuple_GetItem((tuple),(index));\\\n if (rv_cb_str == NULL)\\\n goto capi_fail;\\\n if (PyBytes_Check(rv_cb_str)) {\\\n str[len-1]=\'\\0\';\\\n STRINGCOPYN((str),PyBytes_AS_STRING((PyBytesObject*)rv_cb_str),(len));\\\n } else {\\\n PRINTPYOBJERR(rv_cb_str);\\\n PyErr_SetString(#modulename#_error,"string object expected");\\\n goto capi_fail;\\\n }\\\n }\n' cppmacros['GETSCALARFROMPYTUPLE'] = '\n#define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\\\n if ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\\\n if (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\\\n goto capi_fail;\\\n }\n' cppmacros['FAILNULL'] = '#define FAILNULL(p) do { \\\n if ((p) == NULL) { \\\n PyErr_SetString(PyExc_MemoryError, "NULL pointer found"); \\\n goto capi_fail; \\\n } \\\n} while (0)\n' needs['MEMCOPY'] = ['string.h', 'FAILNULL'] cppmacros['MEMCOPY'] = '\n#define MEMCOPY(to,from,n)\\\n do { FAILNULL(to); FAILNULL(from); (void)memcpy(to,from,n); } while (0)\n' cppmacros['STRINGMALLOC'] = '\n#define STRINGMALLOC(str,len)\\\n if ((str = (string)malloc(len+1)) == NULL) {\\\n PyErr_SetString(PyExc_MemoryError, "out of memory");\\\n goto capi_fail;\\\n } else {\\\n (str)[len] = \'\\0\';\\\n }\n' cppmacros['STRINGFREE'] = '\n#define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0)\n' needs['STRINGPADN'] = ['string.h'] cppmacros['STRINGPADN'] = '\n/*\nSTRINGPADN replaces null values with padding values from the right.\n\n`to` must have size of at least N bytes.\n\nIf the `to[N-1]` has null value, then replace it and all the\npreceding, nulls with the given padding.\n\nSTRINGPADN(to, N, PADDING, NULLVALUE) is an inverse operation.\n*/\n#define STRINGPADN(to, N, NULLVALUE, PADDING) \\\n do { \\\n int _m = (N); \\\n char *_to = (to); \\\n for (_m -= 1; _m >= 0 && _to[_m] == NULLVALUE; _m--) { \\\n _to[_m] = PADDING; \\\n } \\\n } while (0)\n' needs['STRINGCOPYN'] = ['string.h', 'FAILNULL'] cppmacros['STRINGCOPYN'] = '\n/*\nSTRINGCOPYN copies N bytes.\n\n`to` and `from` buffers must have sizes of at least N bytes.\n*/\n#define STRINGCOPYN(to,from,N) \\\n do { \\\n int _m = (N); \\\n char *_to = (to); \\\n char *_from = (from); \\\n FAILNULL(_to); FAILNULL(_from); \\\n (void)strncpy(_to, _from, _m); \\\n } while (0)\n' needs['STRINGCOPY'] = ['string.h', 'FAILNULL'] cppmacros['STRINGCOPY'] = '\n#define STRINGCOPY(to,from)\\\n do { FAILNULL(to); FAILNULL(from); (void)strcpy(to,from); } while (0)\n' cppmacros['CHECKGENERIC'] = '\n#define CHECKGENERIC(check,tcheck,name) \\\n if (!(check)) {\\\n PyErr_SetString(#modulename#_error,"("tcheck") failed for "name);\\\n /*goto capi_fail;*/\\\n } else ' cppmacros['CHECKARRAY'] = '\n#define CHECKARRAY(check,tcheck,name) \\\n if (!(check)) {\\\n PyErr_SetString(#modulename#_error,"("tcheck") failed for "name);\\\n /*goto capi_fail;*/\\\n } else ' cppmacros['CHECKSTRING'] = '\n#define CHECKSTRING(check,tcheck,name,show,var)\\\n if (!(check)) {\\\n char errstring[256];\\\n sprintf(errstring, "%s: "show, "("tcheck") failed for "name, slen(var), var);\\\n PyErr_SetString(#modulename#_error, errstring);\\\n /*goto capi_fail;*/\\\n } else ' cppmacros['CHECKSCALAR'] = '\n#define CHECKSCALAR(check,tcheck,name,show,var)\\\n if (!(check)) {\\\n char errstring[256];\\\n sprintf(errstring, "%s: "show, "("tcheck") failed for "name, var);\\\n PyErr_SetString(#modulename#_error,errstring);\\\n /*goto capi_fail;*/\\\n } else ' cppmacros['ARRSIZE'] = '#define ARRSIZE(dims,rank) (_PyArray_multiply_list(dims,rank))' cppmacros['OLDPYNUM'] = '\n#ifdef OLDPYNUM\n#error You need to install NumPy version 0.13 or higher. See https://scipy.org/install.html\n#endif\n' cppmacros['F2PY_THREAD_LOCAL_DECL'] = '\n#ifndef F2PY_THREAD_LOCAL_DECL\n#if defined(_MSC_VER)\n#define F2PY_THREAD_LOCAL_DECL __declspec(thread)\n#elif defined(NPY_OS_MINGW)\n#define F2PY_THREAD_LOCAL_DECL __thread\n#elif defined(__STDC_VERSION__) \\\n && (__STDC_VERSION__ >= 201112L) \\\n && !defined(__STDC_NO_THREADS__) \\\n && (!defined(__GLIBC__) || __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 12)) \\\n && !defined(NPY_OS_OPENBSD) && !defined(NPY_OS_HAIKU)\n/* __STDC_NO_THREADS__ was first defined in a maintenance release of glibc 2.12,\n see https://lists.gnu.org/archive/html/commit-hurd/2012-07/msg00180.html,\n so `!defined(__STDC_NO_THREADS__)` may give false positive for the existence\n of `threads.h` when using an older release of glibc 2.12\n See gh-19437 for details on OpenBSD */\n#include \n#define F2PY_THREAD_LOCAL_DECL thread_local\n#elif defined(__GNUC__) \\\n && (__GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 4)))\n#define F2PY_THREAD_LOCAL_DECL __thread\n#endif\n#endif\n' cfuncs['calcarrindex'] = '\nstatic int calcarrindex(int *i,PyArrayObject *arr) {\n int k,ii = i[0];\n for (k=1; k < PyArray_NDIM(arr); k++)\n ii += (ii*(PyArray_DIM(arr,k) - 1)+i[k]); /* assuming contiguous arr */\n return ii;\n}' cfuncs['calcarrindextr'] = '\nstatic int calcarrindextr(int *i,PyArrayObject *arr) {\n int k,ii = i[PyArray_NDIM(arr)-1];\n for (k=1; k < PyArray_NDIM(arr); k++)\n ii += (ii*(PyArray_DIM(arr,PyArray_NDIM(arr)-k-1) - 1)+i[PyArray_NDIM(arr)-k-1]); /* assuming contiguous arr */\n return ii;\n}' cfuncs['forcomb'] = '\nstatic struct { int nd;npy_intp *d;int *i,*i_tr,tr; } forcombcache;\nstatic int initforcomb(npy_intp *dims,int nd,int tr) {\n int k;\n if (dims==NULL) return 0;\n if (nd<0) return 0;\n forcombcache.nd = nd;\n forcombcache.d = dims;\n forcombcache.tr = tr;\n if ((forcombcache.i = (int *)malloc(sizeof(int)*nd))==NULL) return 0;\n if ((forcombcache.i_tr = (int *)malloc(sizeof(int)*nd))==NULL) return 0;\n for (k=1;k PyArray_NBYTES(arr)) {\n n = PyArray_NBYTES(arr);\n }\n STRINGCOPYN(buf, str, n);\n return 1;\n }\ncapi_fail:\n PRINTPYOBJERR(obj);\n PyErr_SetString(#modulename#_error, "try_pyarr_from_string failed");\n return 0;\n}\n' needs['string_from_pyobj'] = ['string', 'STRINGMALLOC', 'STRINGCOPYN'] cfuncs['string_from_pyobj'] = '\n/*\n Create a new string buffer `str` of at most length `len` from a\n Python string-like object `obj`.\n\n The string buffer has given size (len) or the size of inistr when len==-1.\n\n The string buffer is padded with blanks: in Fortran, trailing blanks\n are insignificant contrary to C nulls.\n */\nstatic int\nstring_from_pyobj(string *str, int *len, const string inistr, PyObject *obj,\n const char *errmess)\n{\n PyObject *tmp = NULL;\n string buf = NULL;\n npy_intp n = -1;\n#ifdef DEBUGCFUNCS\nfprintf(stderr,"string_from_pyobj(str=\'%s\',len=%d,inistr=\'%s\',obj=%p)\\n",\n (char*)str, *len, (char *)inistr, obj);\n#endif\n if (obj == Py_None) {\n n = strlen(inistr);\n buf = inistr;\n }\n else if (PyArray_Check(obj)) {\n PyArrayObject *arr = (PyArrayObject *)obj;\n if (!ISCONTIGUOUS(arr)) {\n PyErr_SetString(PyExc_ValueError,\n "array object is non-contiguous.");\n goto capi_fail;\n }\n n = PyArray_NBYTES(arr);\n buf = PyArray_DATA(arr);\n n = strnlen(buf, n);\n }\n else {\n if (PyBytes_Check(obj)) {\n tmp = obj;\n Py_INCREF(tmp);\n }\n else if (PyUnicode_Check(obj)) {\n tmp = PyUnicode_AsASCIIString(obj);\n }\n else {\n PyObject *tmp2;\n tmp2 = PyObject_Str(obj);\n if (tmp2) {\n tmp = PyUnicode_AsASCIIString(tmp2);\n Py_DECREF(tmp2);\n }\n else {\n tmp = NULL;\n }\n }\n if (tmp == NULL) goto capi_fail;\n n = PyBytes_GET_SIZE(tmp);\n buf = PyBytes_AS_STRING(tmp);\n }\n if (*len == -1) {\n /* TODO: change the type of `len` so that we can remove this */\n if (n > NPY_MAX_INT) {\n PyErr_SetString(PyExc_OverflowError,\n "object too large for a 32-bit int");\n goto capi_fail;\n }\n *len = n;\n }\n else if (*len < n) {\n /* discard the last (len-n) bytes of input buf */\n n = *len;\n }\n if (n < 0 || *len < 0 || buf == NULL) {\n goto capi_fail;\n }\n STRINGMALLOC(*str, *len); // *str is allocated with size (*len + 1)\n if (n < *len) {\n /*\n Pad fixed-width string with nulls. The caller will replace\n nulls with blanks when the corresponding argument is not\n intent(c).\n */\n memset(*str + n, \'\\0\', *len - n);\n }\n STRINGCOPYN(*str, buf, n);\n Py_XDECREF(tmp);\n return 1;\ncapi_fail:\n Py_XDECREF(tmp);\n {\n PyObject* err = PyErr_Occurred();\n if (err == NULL) {\n err = #modulename#_error;\n }\n PyErr_SetString(err, errmess);\n }\n return 0;\n}\n' cfuncs['character_from_pyobj'] = '\nstatic int\ncharacter_from_pyobj(character* v, PyObject *obj, const char *errmess) {\n if (PyBytes_Check(obj)) {\n /* empty bytes has trailing null, so dereferencing is always safe */\n *v = PyBytes_AS_STRING(obj)[0];\n return 1;\n } else if (PyUnicode_Check(obj)) {\n PyObject* tmp = PyUnicode_AsASCIIString(obj);\n if (tmp != NULL) {\n *v = PyBytes_AS_STRING(tmp)[0];\n Py_DECREF(tmp);\n return 1;\n }\n } else if (PyArray_Check(obj)) {\n PyArrayObject* arr = (PyArrayObject*)obj;\n if (F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr)) {\n *v = PyArray_BYTES(arr)[0];\n return 1;\n } else if (F2PY_IS_UNICODE_ARRAY(arr)) {\n // TODO: update when numpy will support 1-byte and\n // 2-byte unicode dtypes\n PyObject* tmp = PyUnicode_FromKindAndData(\n PyUnicode_4BYTE_KIND,\n PyArray_BYTES(arr),\n (PyArray_NBYTES(arr)>0?1:0));\n if (tmp != NULL) {\n if (character_from_pyobj(v, tmp, errmess)) {\n Py_DECREF(tmp);\n return 1;\n }\n Py_DECREF(tmp);\n }\n }\n } else if (PySequence_Check(obj)) {\n PyObject* tmp = PySequence_GetItem(obj,0);\n if (tmp != NULL) {\n if (character_from_pyobj(v, tmp, errmess)) {\n Py_DECREF(tmp);\n return 1;\n }\n Py_DECREF(tmp);\n }\n }\n {\n /* TODO: This error (and most other) error handling needs cleaning. */\n char mess[F2PY_MESSAGE_BUFFER_SIZE];\n strcpy(mess, errmess);\n PyObject* err = PyErr_Occurred();\n if (err == NULL) {\n err = PyExc_TypeError;\n Py_INCREF(err);\n }\n else {\n Py_INCREF(err);\n PyErr_Clear();\n }\n sprintf(mess + strlen(mess),\n " -- expected str|bytes|sequence-of-str-or-bytes, got ");\n f2py_describe(obj, mess + strlen(mess));\n PyErr_SetString(err, mess);\n Py_DECREF(err);\n }\n return 0;\n}\n' needs['char_from_pyobj'] = ['int_from_pyobj'] cfuncs['char_from_pyobj'] = '\nstatic int\nchar_from_pyobj(char* v, PyObject *obj, const char *errmess) {\n int i = 0;\n if (int_from_pyobj(&i, obj, errmess)) {\n *v = (char)i;\n return 1;\n }\n return 0;\n}\n' needs['signed_char_from_pyobj'] = ['int_from_pyobj', 'signed_char'] cfuncs['signed_char_from_pyobj'] = '\nstatic int\nsigned_char_from_pyobj(signed_char* v, PyObject *obj, const char *errmess) {\n int i = 0;\n if (int_from_pyobj(&i, obj, errmess)) {\n *v = (signed_char)i;\n return 1;\n }\n return 0;\n}\n' needs['short_from_pyobj'] = ['int_from_pyobj'] cfuncs['short_from_pyobj'] = '\nstatic int\nshort_from_pyobj(short* v, PyObject *obj, const char *errmess) {\n int i = 0;\n if (int_from_pyobj(&i, obj, errmess)) {\n *v = (short)i;\n return 1;\n }\n return 0;\n}\n' cfuncs['int_from_pyobj'] = '\nstatic int\nint_from_pyobj(int* v, PyObject *obj, const char *errmess)\n{\n PyObject* tmp = NULL;\n\n if (PyLong_Check(obj)) {\n *v = Npy__PyLong_AsInt(obj);\n return !(*v == -1 && PyErr_Occurred());\n }\n\n tmp = PyNumber_Long(obj);\n if (tmp) {\n *v = Npy__PyLong_AsInt(tmp);\n Py_DECREF(tmp);\n return !(*v == -1 && PyErr_Occurred());\n }\n\n if (PyComplex_Check(obj)) {\n PyErr_Clear();\n tmp = PyObject_GetAttrString(obj,"real");\n }\n else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {\n /*pass*/;\n }\n else if (PySequence_Check(obj)) {\n PyErr_Clear();\n tmp = PySequence_GetItem(obj, 0);\n }\n\n if (tmp) {\n if (int_from_pyobj(v, tmp, errmess)) {\n Py_DECREF(tmp);\n return 1;\n }\n Py_DECREF(tmp);\n }\n\n {\n PyObject* err = PyErr_Occurred();\n if (err == NULL) {\n err = #modulename#_error;\n }\n PyErr_SetString(err, errmess);\n }\n return 0;\n}\n' cfuncs['long_from_pyobj'] = '\nstatic int\nlong_from_pyobj(long* v, PyObject *obj, const char *errmess) {\n PyObject* tmp = NULL;\n\n if (PyLong_Check(obj)) {\n *v = PyLong_AsLong(obj);\n return !(*v == -1 && PyErr_Occurred());\n }\n\n tmp = PyNumber_Long(obj);\n if (tmp) {\n *v = PyLong_AsLong(tmp);\n Py_DECREF(tmp);\n return !(*v == -1 && PyErr_Occurred());\n }\n\n if (PyComplex_Check(obj)) {\n PyErr_Clear();\n tmp = PyObject_GetAttrString(obj,"real");\n }\n else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {\n /*pass*/;\n }\n else if (PySequence_Check(obj)) {\n PyErr_Clear();\n tmp = PySequence_GetItem(obj, 0);\n }\n\n if (tmp) {\n if (long_from_pyobj(v, tmp, errmess)) {\n Py_DECREF(tmp);\n return 1;\n }\n Py_DECREF(tmp);\n }\n {\n PyObject* err = PyErr_Occurred();\n if (err == NULL) {\n err = #modulename#_error;\n }\n PyErr_SetString(err, errmess);\n }\n return 0;\n}\n' needs['long_long_from_pyobj'] = ['long_long'] cfuncs['long_long_from_pyobj'] = '\nstatic int\nlong_long_from_pyobj(long_long* v, PyObject *obj, const char *errmess)\n{\n PyObject* tmp = NULL;\n\n if (PyLong_Check(obj)) {\n *v = PyLong_AsLongLong(obj);\n return !(*v == -1 && PyErr_Occurred());\n }\n\n tmp = PyNumber_Long(obj);\n if (tmp) {\n *v = PyLong_AsLongLong(tmp);\n Py_DECREF(tmp);\n return !(*v == -1 && PyErr_Occurred());\n }\n\n if (PyComplex_Check(obj)) {\n PyErr_Clear();\n tmp = PyObject_GetAttrString(obj,"real");\n }\n else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {\n /*pass*/;\n }\n else if (PySequence_Check(obj)) {\n PyErr_Clear();\n tmp = PySequence_GetItem(obj, 0);\n }\n\n if (tmp) {\n if (long_long_from_pyobj(v, tmp, errmess)) {\n Py_DECREF(tmp);\n return 1;\n }\n Py_DECREF(tmp);\n }\n {\n PyObject* err = PyErr_Occurred();\n if (err == NULL) {\n err = #modulename#_error;\n }\n PyErr_SetString(err,errmess);\n }\n return 0;\n}\n' needs['long_double_from_pyobj'] = ['double_from_pyobj', 'long_double'] cfuncs['long_double_from_pyobj'] = '\nstatic int\nlong_double_from_pyobj(long_double* v, PyObject *obj, const char *errmess)\n{\n double d=0;\n if (PyArray_CheckScalar(obj)){\n if PyArray_IsScalar(obj, LongDouble) {\n PyArray_ScalarAsCtype(obj, v);\n return 1;\n }\n else if (PyArray_Check(obj) && PyArray_TYPE(obj) == NPY_LONGDOUBLE) {\n (*v) = *((npy_longdouble *)PyArray_DATA(obj));\n return 1;\n }\n }\n if (double_from_pyobj(&d, obj, errmess)) {\n *v = (long_double)d;\n return 1;\n }\n return 0;\n}\n' cfuncs['double_from_pyobj'] = '\nstatic int\ndouble_from_pyobj(double* v, PyObject *obj, const char *errmess)\n{\n PyObject* tmp = NULL;\n if (PyFloat_Check(obj)) {\n *v = PyFloat_AsDouble(obj);\n return !(*v == -1.0 && PyErr_Occurred());\n }\n\n tmp = PyNumber_Float(obj);\n if (tmp) {\n *v = PyFloat_AsDouble(tmp);\n Py_DECREF(tmp);\n return !(*v == -1.0 && PyErr_Occurred());\n }\n\n if (PyComplex_Check(obj)) {\n PyErr_Clear();\n tmp = PyObject_GetAttrString(obj,"real");\n }\n else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {\n /*pass*/;\n }\n else if (PySequence_Check(obj)) {\n PyErr_Clear();\n tmp = PySequence_GetItem(obj, 0);\n }\n\n if (tmp) {\n if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;}\n Py_DECREF(tmp);\n }\n {\n PyObject* err = PyErr_Occurred();\n if (err==NULL) err = #modulename#_error;\n PyErr_SetString(err,errmess);\n }\n return 0;\n}\n' needs['float_from_pyobj'] = ['double_from_pyobj'] cfuncs['float_from_pyobj'] = '\nstatic int\nfloat_from_pyobj(float* v, PyObject *obj, const char *errmess)\n{\n double d=0.0;\n if (double_from_pyobj(&d,obj,errmess)) {\n *v = (float)d;\n return 1;\n }\n return 0;\n}\n' needs['complex_long_double_from_pyobj'] = ['complex_long_double', 'long_double', 'complex_double_from_pyobj', 'npy_math.h'] cfuncs['complex_long_double_from_pyobj'] = '\nstatic int\ncomplex_long_double_from_pyobj(complex_long_double* v, PyObject *obj, const char *errmess)\n{\n complex_double cd = {0.0,0.0};\n if (PyArray_CheckScalar(obj)){\n if PyArray_IsScalar(obj, CLongDouble) {\n PyArray_ScalarAsCtype(obj, v);\n return 1;\n }\n else if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_CLONGDOUBLE) {\n (*v).r = npy_creall(*(((npy_clongdouble *)PyArray_DATA(obj))));\n (*v).i = npy_cimagl(*(((npy_clongdouble *)PyArray_DATA(obj))));\n return 1;\n }\n }\n if (complex_double_from_pyobj(&cd,obj,errmess)) {\n (*v).r = (long_double)cd.r;\n (*v).i = (long_double)cd.i;\n return 1;\n }\n return 0;\n}\n' needs['complex_double_from_pyobj'] = ['complex_double', 'npy_math.h'] cfuncs['complex_double_from_pyobj'] = '\nstatic int\ncomplex_double_from_pyobj(complex_double* v, PyObject *obj, const char *errmess) {\n Py_complex c;\n if (PyComplex_Check(obj)) {\n c = PyComplex_AsCComplex(obj);\n (*v).r = c.real;\n (*v).i = c.imag;\n return 1;\n }\n if (PyArray_IsScalar(obj, ComplexFloating)) {\n if (PyArray_IsScalar(obj, CFloat)) {\n npy_cfloat new;\n PyArray_ScalarAsCtype(obj, &new);\n (*v).r = (double)npy_crealf(new);\n (*v).i = (double)npy_cimagf(new);\n }\n else if (PyArray_IsScalar(obj, CLongDouble)) {\n npy_clongdouble new;\n PyArray_ScalarAsCtype(obj, &new);\n (*v).r = (double)npy_creall(new);\n (*v).i = (double)npy_cimagl(new);\n }\n else { /* if (PyArray_IsScalar(obj, CDouble)) */\n PyArray_ScalarAsCtype(obj, v);\n }\n return 1;\n }\n if (PyArray_CheckScalar(obj)) { /* 0-dim array or still array scalar */\n PyArrayObject *arr;\n if (PyArray_Check(obj)) {\n arr = (PyArrayObject *)PyArray_Cast((PyArrayObject *)obj, NPY_CDOUBLE);\n }\n else {\n arr = (PyArrayObject *)PyArray_FromScalar(obj, PyArray_DescrFromType(NPY_CDOUBLE));\n }\n if (arr == NULL) {\n return 0;\n }\n (*v).r = npy_creal(*(((npy_cdouble *)PyArray_DATA(arr))));\n (*v).i = npy_cimag(*(((npy_cdouble *)PyArray_DATA(arr))));\n Py_DECREF(arr);\n return 1;\n }\n /* Python does not provide PyNumber_Complex function :-( */\n (*v).i = 0.0;\n if (PyFloat_Check(obj)) {\n (*v).r = PyFloat_AsDouble(obj);\n return !((*v).r == -1.0 && PyErr_Occurred());\n }\n if (PyLong_Check(obj)) {\n (*v).r = PyLong_AsDouble(obj);\n return !((*v).r == -1.0 && PyErr_Occurred());\n }\n if (PySequence_Check(obj) && !(PyBytes_Check(obj) || PyUnicode_Check(obj))) {\n PyObject *tmp = PySequence_GetItem(obj,0);\n if (tmp) {\n if (complex_double_from_pyobj(v,tmp,errmess)) {\n Py_DECREF(tmp);\n return 1;\n }\n Py_DECREF(tmp);\n }\n }\n {\n PyObject* err = PyErr_Occurred();\n if (err==NULL)\n err = PyExc_TypeError;\n PyErr_SetString(err,errmess);\n }\n return 0;\n}\n' needs['complex_float_from_pyobj'] = ['complex_float', 'complex_double_from_pyobj'] cfuncs['complex_float_from_pyobj'] = '\nstatic int\ncomplex_float_from_pyobj(complex_float* v,PyObject *obj,const char *errmess)\n{\n complex_double cd={0.0,0.0};\n if (complex_double_from_pyobj(&cd,obj,errmess)) {\n (*v).r = (float)cd.r;\n (*v).i = (float)cd.i;\n return 1;\n }\n return 0;\n}\n' cfuncs['try_pyarr_from_character'] = '\nstatic int try_pyarr_from_character(PyObject* obj, character* v) {\n PyArrayObject *arr = (PyArrayObject*)obj;\n if (!obj) return -2;\n if (PyArray_Check(obj)) {\n if (F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr)) {\n *(character *)(PyArray_DATA(arr)) = *v;\n return 1;\n }\n }\n {\n char mess[F2PY_MESSAGE_BUFFER_SIZE];\n PyObject* err = PyErr_Occurred();\n if (err == NULL) {\n err = PyExc_ValueError;\n strcpy(mess, "try_pyarr_from_character failed"\n " -- expected bytes array-scalar|array, got ");\n f2py_describe(obj, mess + strlen(mess));\n PyErr_SetString(err, mess);\n }\n }\n return 0;\n}\n' needs['try_pyarr_from_char'] = ['pyobj_from_char1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_char'] = "static int try_pyarr_from_char(PyObject* obj,char* v) {\n TRYPYARRAYTEMPLATE(char,'c');\n}\n" needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'unsigned_char'] cfuncs['try_pyarr_from_unsigned_char'] = "static int try_pyarr_from_unsigned_char(PyObject* obj,unsigned_char* v) {\n TRYPYARRAYTEMPLATE(unsigned_char,'b');\n}\n" needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'signed_char'] cfuncs['try_pyarr_from_signed_char'] = "static int try_pyarr_from_signed_char(PyObject* obj,signed_char* v) {\n TRYPYARRAYTEMPLATE(signed_char,'1');\n}\n" needs['try_pyarr_from_short'] = ['pyobj_from_short1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_short'] = "static int try_pyarr_from_short(PyObject* obj,short* v) {\n TRYPYARRAYTEMPLATE(short,'s');\n}\n" needs['try_pyarr_from_int'] = ['pyobj_from_int1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_int'] = "static int try_pyarr_from_int(PyObject* obj,int* v) {\n TRYPYARRAYTEMPLATE(int,'i');\n}\n" needs['try_pyarr_from_long'] = ['pyobj_from_long1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_long'] = "static int try_pyarr_from_long(PyObject* obj,long* v) {\n TRYPYARRAYTEMPLATE(long,'l');\n}\n" needs['try_pyarr_from_long_long'] = ['pyobj_from_long_long1', 'TRYPYARRAYTEMPLATE', 'long_long'] cfuncs['try_pyarr_from_long_long'] = "static int try_pyarr_from_long_long(PyObject* obj,long_long* v) {\n TRYPYARRAYTEMPLATE(long_long,'L');\n}\n" needs['try_pyarr_from_float'] = ['pyobj_from_float1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_float'] = "static int try_pyarr_from_float(PyObject* obj,float* v) {\n TRYPYARRAYTEMPLATE(float,'f');\n}\n" needs['try_pyarr_from_double'] = ['pyobj_from_double1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_double'] = "static int try_pyarr_from_double(PyObject* obj,double* v) {\n TRYPYARRAYTEMPLATE(double,'d');\n}\n" needs['try_pyarr_from_complex_float'] = ['pyobj_from_complex_float1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_float'] cfuncs['try_pyarr_from_complex_float'] = "static int try_pyarr_from_complex_float(PyObject* obj,complex_float* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(float,'F');\n}\n" needs['try_pyarr_from_complex_double'] = ['pyobj_from_complex_double1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_double'] cfuncs['try_pyarr_from_complex_double'] = "static int try_pyarr_from_complex_double(PyObject* obj,complex_double* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(double,'D');\n}\n" needs['create_cb_arglist'] = ['CFUNCSMESS', 'PRINTPYOBJERR', 'MINMAX'] cfuncs['create_cb_arglist'] = '\nstatic int\ncreate_cb_arglist(PyObject* fun, PyTupleObject* xa , const int maxnofargs,\n const int nofoptargs, int *nofargs, PyTupleObject **args,\n const char *errmess)\n{\n PyObject *tmp = NULL;\n PyObject *tmp_fun = NULL;\n Py_ssize_t tot, opt, ext, siz, i, di = 0;\n CFUNCSMESS("create_cb_arglist\\n");\n tot=opt=ext=siz=0;\n /* Get the total number of arguments */\n if (PyFunction_Check(fun)) {\n tmp_fun = fun;\n Py_INCREF(tmp_fun);\n }\n else {\n di = 1;\n if (PyObject_HasAttrString(fun,"im_func")) {\n tmp_fun = PyObject_GetAttrString(fun,"im_func");\n }\n else if (PyObject_HasAttrString(fun,"__call__")) {\n tmp = PyObject_GetAttrString(fun,"__call__");\n if (PyObject_HasAttrString(tmp,"im_func"))\n tmp_fun = PyObject_GetAttrString(tmp,"im_func");\n else {\n tmp_fun = fun; /* built-in function */\n Py_INCREF(tmp_fun);\n tot = maxnofargs;\n if (PyCFunction_Check(fun)) {\n /* In case the function has a co_argcount (like on PyPy) */\n di = 0;\n }\n if (xa != NULL)\n tot += PyTuple_Size((PyObject *)xa);\n }\n Py_XDECREF(tmp);\n }\n else if (PyFortran_Check(fun) || PyFortran_Check1(fun)) {\n tot = maxnofargs;\n if (xa != NULL)\n tot += PyTuple_Size((PyObject *)xa);\n tmp_fun = fun;\n Py_INCREF(tmp_fun);\n }\n else if (F2PyCapsule_Check(fun)) {\n tot = maxnofargs;\n if (xa != NULL)\n ext = PyTuple_Size((PyObject *)xa);\n if(ext>0) {\n fprintf(stderr,"extra arguments tuple cannot be used with PyCapsule call-back\\n");\n goto capi_fail;\n }\n tmp_fun = fun;\n Py_INCREF(tmp_fun);\n }\n }\n\n if (tmp_fun == NULL) {\n fprintf(stderr,\n "Call-back argument must be function|instance|instance.__call__|f2py-function "\n "but got %s.\\n",\n ((fun == NULL) ? "NULL" : Py_TYPE(fun)->tp_name));\n goto capi_fail;\n }\n\n if (PyObject_HasAttrString(tmp_fun,"__code__")) {\n if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,"__code__"),"co_argcount")) {\n PyObject *tmp_argcount = PyObject_GetAttrString(tmp,"co_argcount");\n Py_DECREF(tmp);\n if (tmp_argcount == NULL) {\n goto capi_fail;\n }\n tot = PyLong_AsSsize_t(tmp_argcount) - di;\n Py_DECREF(tmp_argcount);\n }\n }\n /* Get the number of optional arguments */\n if (PyObject_HasAttrString(tmp_fun,"__defaults__")) {\n if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,"__defaults__")))\n opt = PyTuple_Size(tmp);\n Py_XDECREF(tmp);\n }\n /* Get the number of extra arguments */\n if (xa != NULL)\n ext = PyTuple_Size((PyObject *)xa);\n /* Calculate the size of call-backs argument list */\n siz = MIN(maxnofargs+ext,tot);\n *nofargs = MAX(0,siz-ext);\n\n#ifdef DEBUGCFUNCS\n fprintf(stderr,\n "debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),"\n "tot,opt,ext,siz,nofargs = %d(-%d), %zd, %zd, %zd, %zd, %d\\n",\n maxnofargs, nofoptargs, tot, opt, ext, siz, *nofargs);\n#endif\n\n if (siz < tot-opt) {\n fprintf(stderr,\n "create_cb_arglist: Failed to build argument list "\n "(siz) with enough arguments (tot-opt) required by "\n "user-supplied function (siz,tot,opt=%zd, %zd, %zd).\\n",\n siz, tot, opt);\n goto capi_fail;\n }\n\n /* Initialize argument list */\n *args = (PyTupleObject *)PyTuple_New(siz);\n for (i=0;i<*nofargs;i++) {\n Py_INCREF(Py_None);\n PyTuple_SET_ITEM((PyObject *)(*args),i,Py_None);\n }\n if (xa != NULL)\n for (i=(*nofargs);i 0: if outneeds[n][0] not in needs: out.append(outneeds[n][0]) del outneeds[n][0] else: flag = 0 for k in outneeds[n][1:]: if k in needs[outneeds[n][0]]: flag = 1 break if flag: outneeds[n] = outneeds[n][1:] + [outneeds[n][0]] else: out.append(outneeds[n][0]) del outneeds[n][0] if saveout and 0 not in map(lambda x, y: x == y, saveout, outneeds[n]) and (outneeds[n] != []): print(n, saveout) errmess('get_needs: no progress in sorting needs, probably circular dependence, skipping.\n') out = out + saveout break saveout = copy.copy(outneeds[n]) if out == []: out = [n] res[n] = out return res # File: numpy-main/numpy/f2py/common_rules.py """""" from . import __version__ f2py_version = __version__.version from .auxfuncs import hasbody, hascommon, hasnote, isintent_hide, outmess, getuseblocks from . import capi_maps from . import func2subr from .crackfortran import rmbadname def findcommonblocks(block, top=1): ret = [] if hascommon(block): for (key, value) in block['common'].items(): vars_ = {v: block['vars'][v] for v in value} ret.append((key, value, vars_)) elif hasbody(block): for b in block['body']: ret = ret + findcommonblocks(b, 0) if top: tret = [] names = [] for t in ret: if t[0] not in names: names.append(t[0]) tret.append(t) return tret return ret def buildhooks(m): ret = {'commonhooks': [], 'initcommonhooks': [], 'docs': ['"COMMON blocks:\\n"']} fwrap = [''] def fadd(line, s=fwrap): s[0] = '%s\n %s' % (s[0], line) chooks = [''] def cadd(line, s=chooks): s[0] = '%s\n%s' % (s[0], line) ihooks = [''] def iadd(line, s=ihooks): s[0] = '%s\n%s' % (s[0], line) doc = [''] def dadd(line, s=doc): s[0] = '%s\n%s' % (s[0], line) for (name, vnames, vars) in findcommonblocks(m): lower_name = name.lower() (hnames, inames) = ([], []) for n in vnames: if isintent_hide(vars[n]): hnames.append(n) else: inames.append(n) if hnames: outmess('\t\tConstructing COMMON block support for "%s"...\n\t\t %s\n\t\t Hidden: %s\n' % (name, ','.join(inames), ','.join(hnames))) else: outmess('\t\tConstructing COMMON block support for "%s"...\n\t\t %s\n' % (name, ','.join(inames))) fadd('subroutine f2pyinit%s(setupfunc)' % name) for usename in getuseblocks(m): fadd(f'use {usename}') fadd('external setupfunc') for n in vnames: fadd(func2subr.var2fixfortran(vars, n)) if name == '_BLNK_': fadd('common %s' % ','.join(vnames)) else: fadd('common /%s/ %s' % (name, ','.join(vnames))) fadd('call setupfunc(%s)' % ','.join(inames)) fadd('end\n') cadd('static FortranDataDef f2py_%s_def[] = {' % name) idims = [] for n in inames: ct = capi_maps.getctype(vars[n]) elsize = capi_maps.get_elsize(vars[n]) at = capi_maps.c2capi_map[ct] dm = capi_maps.getarrdims(n, vars[n]) if dm['dims']: idims.append('(%s)' % dm['dims']) else: idims.append('') dms = dm['dims'].strip() if not dms: dms = '-1' cadd('\t{"%s",%s,{{%s}},%s, %s},' % (n, dm['rank'], dms, at, elsize)) cadd('\t{NULL}\n};') inames1 = rmbadname(inames) inames1_tps = ','.join(['char *' + s for s in inames1]) cadd('static void f2py_setup_%s(%s) {' % (name, inames1_tps)) cadd('\tint i_f2py=0;') for n in inames1: cadd('\tf2py_%s_def[i_f2py++].data = %s;' % (name, n)) cadd('}') if '_' in lower_name: F_FUNC = 'F_FUNC_US' else: F_FUNC = 'F_FUNC' cadd('extern void %s(f2pyinit%s,F2PYINIT%s)(void(*)(%s));' % (F_FUNC, lower_name, name.upper(), ','.join(['char*'] * len(inames1)))) cadd('static void f2py_init_%s(void) {' % name) cadd('\t%s(f2pyinit%s,F2PYINIT%s)(f2py_setup_%s);' % (F_FUNC, lower_name, name.upper(), name)) cadd('}\n') iadd('\ttmp = PyFortranObject_New(f2py_%s_def,f2py_init_%s);' % (name, name)) iadd('\tif (tmp == NULL) return NULL;') iadd('\tif (F2PyDict_SetItemString(d, "%s", tmp) == -1) return NULL;' % name) iadd('\tPy_DECREF(tmp);') tname = name.replace('_', '\\_') dadd('\\subsection{Common block \\texttt{%s}}\n' % tname) dadd('\\begin{description}') for n in inames: dadd('\\item[]{{}\\verb@%s@{}}' % capi_maps.getarrdocsign(n, vars[n])) if hasnote(vars[n]): note = vars[n]['note'] if isinstance(note, list): note = '\n'.join(note) dadd('--- %s' % note) dadd('\\end{description}') ret['docs'].append('"\t/%s/ %s\\n"' % (name, ','.join(map(lambda v, d: v + d, inames, idims)))) ret['commonhooks'] = chooks ret['initcommonhooks'] = ihooks ret['latexdoc'] = doc[0] if len(ret['docs']) <= 1: ret['docs'] = '' return (ret, fwrap[0]) # File: numpy-main/numpy/f2py/crackfortran.py """""" import sys import string import fileinput import re import os import copy import platform import codecs from pathlib import Path try: import charset_normalizer except ImportError: charset_normalizer = None from . import __version__ from .auxfuncs import * from . import symbolic f2py_version = __version__.version strictf77 = 1 sourcecodeform = 'fix' quiet = 0 verbose = 1 tabchar = 4 * ' ' pyffilename = '' f77modulename = '' skipemptyends = 0 ignorecontains = 1 dolowercase = 1 debug = [] beginpattern = '' currentfilename = '' expectbegin = 1 f90modulevars = {} filepositiontext = '' gotnextfile = 1 groupcache = None groupcounter = 0 grouplist = {groupcounter: []} groupname = '' include_paths = [] neededmodule = -1 onlyfuncs = [] previous_context = None skipblocksuntil = -1 skipfuncs = [] skipfunctions = [] usermodules = [] def reset_global_f2py_vars(): global groupcounter, grouplist, neededmodule, expectbegin global skipblocksuntil, usermodules, f90modulevars, gotnextfile global filepositiontext, currentfilename, skipfunctions, skipfuncs global onlyfuncs, include_paths, previous_context global strictf77, sourcecodeform, quiet, verbose, tabchar, pyffilename global f77modulename, skipemptyends, ignorecontains, dolowercase, debug strictf77 = 1 sourcecodeform = 'fix' quiet = 0 verbose = 1 tabchar = 4 * ' ' pyffilename = '' f77modulename = '' skipemptyends = 0 ignorecontains = 1 dolowercase = 1 debug = [] groupcounter = 0 grouplist = {groupcounter: []} neededmodule = -1 expectbegin = 1 skipblocksuntil = -1 usermodules = [] f90modulevars = {} gotnextfile = 1 filepositiontext = '' currentfilename = '' skipfunctions = [] skipfuncs = [] onlyfuncs = [] include_paths = [] previous_context = None def outmess(line, flag=1): global filepositiontext if not verbose: return if not quiet: if flag: sys.stdout.write(filepositiontext) sys.stdout.write(line) re._MAXCACHE = 50 defaultimplicitrules = {} for c in 'abcdefghopqrstuvwxyz$_': defaultimplicitrules[c] = {'typespec': 'real'} for c in 'ijklmn': defaultimplicitrules[c] = {'typespec': 'integer'} badnames = {} invbadnames = {} for n in ['int', 'double', 'float', 'char', 'short', 'long', 'void', 'case', 'while', 'return', 'signed', 'unsigned', 'if', 'for', 'typedef', 'sizeof', 'union', 'struct', 'static', 'register', 'new', 'break', 'do', 'goto', 'switch', 'continue', 'else', 'inline', 'extern', 'delete', 'const', 'auto', 'len', 'rank', 'shape', 'index', 'slen', 'size', '_i', 'max', 'min', 'flen', 'fshape', 'string', 'complex_double', 'float_double', 'stdin', 'stderr', 'stdout', 'type', 'default']: badnames[n] = n + '_bn' invbadnames[n + '_bn'] = n def rmbadname1(name): if name in badnames: errmess('rmbadname1: Replacing "%s" with "%s".\n' % (name, badnames[name])) return badnames[name] return name def rmbadname(names): return [rmbadname1(_m) for _m in names] def undo_rmbadname1(name): if name in invbadnames: errmess('undo_rmbadname1: Replacing "%s" with "%s".\n' % (name, invbadnames[name])) return invbadnames[name] return name def undo_rmbadname(names): return [undo_rmbadname1(_m) for _m in names] _has_f_header = re.compile('-\\*-\\s*fortran\\s*-\\*-', re.I).search _has_f90_header = re.compile('-\\*-\\s*f90\\s*-\\*-', re.I).search _has_fix_header = re.compile('-\\*-\\s*fix\\s*-\\*-', re.I).search _free_f90_start = re.compile('[^c*]\\s*[^\\s\\d\\t]', re.I).match COMMON_FREE_EXTENSIONS = ['.f90', '.f95', '.f03', '.f08'] COMMON_FIXED_EXTENSIONS = ['.for', '.ftn', '.f77', '.f'] def openhook(filename, mode): if charset_normalizer is not None: encoding = charset_normalizer.from_path(filename).best().encoding else: nbytes = min(32, os.path.getsize(filename)) with open(filename, 'rb') as fhandle: raw = fhandle.read(nbytes) if raw.startswith(codecs.BOM_UTF8): encoding = 'UTF-8-SIG' elif raw.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)): encoding = 'UTF-32' elif raw.startswith((codecs.BOM_LE, codecs.BOM_BE)): encoding = 'UTF-16' else: encoding = 'ascii' return open(filename, mode, encoding=encoding) def is_free_format(fname): result = False if Path(fname).suffix.lower() in COMMON_FREE_EXTENSIONS: result = True with openhook(fname, 'r') as fhandle: line = fhandle.readline() n = 15 if _has_f_header(line): n = 0 elif _has_f90_header(line): n = 0 result = True while n > 0 and line: if line[0] != '!' and line.strip(): n -= 1 if line[0] != '\t' and _free_f90_start(line[:5]) or line[-2:-1] == '&': result = True break line = fhandle.readline() return result def readfortrancode(ffile, dowithline=show, istop=1): global gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77 global beginpattern, quiet, verbose, dolowercase, include_paths if not istop: saveglobals = (gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77, beginpattern, quiet, verbose, dolowercase) if ffile == []: return localdolowercase = dolowercase cont = False finalline = '' ll = '' includeline = re.compile('\\s*include\\s*(\\\'|")(?P[^\\\'"]*)(\\\'|")', re.I) cont1 = re.compile('(?P.*)&\\s*\\Z') cont2 = re.compile('(\\s*&|)(?P.*)') mline_mark = re.compile(".*?'''") if istop: dowithline('', -1) (ll, l1) = ('', '') spacedigits = [' '] + [str(_m) for _m in range(10)] filepositiontext = '' fin = fileinput.FileInput(ffile, openhook=openhook) while True: try: l = fin.readline() except UnicodeDecodeError as msg: raise Exception(f'readfortrancode: reading {fin.filename()}#{fin.lineno()} failed with\n{msg}.\nIt is likely that installing charset_normalizer package will help f2py determine the input file encoding correctly.') if not l: break if fin.isfirstline(): filepositiontext = '' currentfilename = fin.filename() gotnextfile = 1 l1 = l strictf77 = 0 sourcecodeform = 'fix' ext = os.path.splitext(currentfilename)[1] if Path(currentfilename).suffix.lower() in COMMON_FIXED_EXTENSIONS and (not (_has_f90_header(l) or _has_fix_header(l))): strictf77 = 1 elif is_free_format(currentfilename) and (not _has_fix_header(l)): sourcecodeform = 'free' if strictf77: beginpattern = beginpattern77 else: beginpattern = beginpattern90 outmess('\tReading file %s (format:%s%s)\n' % (repr(currentfilename), sourcecodeform, strictf77 and ',strict' or '')) l = l.expandtabs().replace('\xa0', ' ') while not l == '': if l[-1] not in '\n\r\x0c': break l = l[:-1] (l, rl) = split_by_unquoted(l, '!') l += ' ' if rl[:5].lower() == '!f2py': (l, _) = split_by_unquoted(l + 4 * ' ' + rl[5:], '!') if l.strip() == '': if sourcecodeform == 'free': pass else: cont = False continue if sourcecodeform == 'fix': if l[0] in ['*', 'c', '!', 'C', '#']: if l[1:5].lower() == 'f2py': l = ' ' + l[5:] else: cont = False continue elif strictf77: if len(l) > 72: l = l[:72] if l[0] not in spacedigits: raise Exception('readfortrancode: Found non-(space,digit) char in the first column.\n\tAre you sure that this code is in fix form?\n\tline=%s' % repr(l)) if (not cont or strictf77) and (len(l) > 5 and (not l[5] == ' ')): ll = ll + l[6:] finalline = '' origfinalline = '' else: r = cont1.match(l) if r: l = r.group('line') if cont: ll = ll + cont2.match(l).group('line') finalline = '' origfinalline = '' else: l = ' ' + l[5:] if localdolowercase: finalline = ll.lower() else: finalline = ll origfinalline = ll ll = l elif sourcecodeform == 'free': if not cont and ext == '.pyf' and mline_mark.match(l): l = l + '\n' while True: lc = fin.readline() if not lc: errmess('Unexpected end of file when reading multiline\n') break l = l + lc if mline_mark.match(lc): break l = l.rstrip() r = cont1.match(l) if r: l = r.group('line') if cont: ll = ll + cont2.match(l).group('line') finalline = '' origfinalline = '' else: if localdolowercase: finalline = ll.lower() else: finalline = ll origfinalline = ll ll = l cont = r is not None else: raise ValueError("Flag sourcecodeform must be either 'fix' or 'free': %s" % repr(sourcecodeform)) filepositiontext = 'Line #%d in %s:"%s"\n\t' % (fin.filelineno() - 1, currentfilename, l1) m = includeline.match(origfinalline) if m: fn = m.group('name') if os.path.isfile(fn): readfortrancode(fn, dowithline=dowithline, istop=0) else: include_dirs = [os.path.dirname(currentfilename)] + include_paths foundfile = 0 for inc_dir in include_dirs: fn1 = os.path.join(inc_dir, fn) if os.path.isfile(fn1): foundfile = 1 readfortrancode(fn1, dowithline=dowithline, istop=0) break if not foundfile: outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n' % (repr(fn), os.pathsep.join(include_dirs))) else: dowithline(finalline) l1 = ll if localdolowercase: finalline = ll.lower() else: finalline = ll origfinalline = ll filepositiontext = 'Line #%d in %s:"%s"\n\t' % (fin.filelineno() - 1, currentfilename, l1) m = includeline.match(origfinalline) if m: fn = m.group('name') if os.path.isfile(fn): readfortrancode(fn, dowithline=dowithline, istop=0) else: include_dirs = [os.path.dirname(currentfilename)] + include_paths foundfile = 0 for inc_dir in include_dirs: fn1 = os.path.join(inc_dir, fn) if os.path.isfile(fn1): foundfile = 1 readfortrancode(fn1, dowithline=dowithline, istop=0) break if not foundfile: outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n' % (repr(fn), os.pathsep.join(include_dirs))) else: dowithline(finalline) filepositiontext = '' fin.close() if istop: dowithline('', 1) else: (gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77, beginpattern, quiet, verbose, dolowercase) = saveglobals beforethisafter = '\\s*(?P%s(?=\\s*(\\b(%s)\\b)))' + '\\s*(?P(\\b(%s)\\b))' + '\\s*(?P%s)\\s*\\Z' fortrantypes = 'character|logical|integer|real|complex|double\\s*(precision\\s*(complex|)|complex)|type(?=\\s*\\([\\w\\s,=(*)]*\\))|byte' typespattern = (re.compile(beforethisafter % ('', fortrantypes, fortrantypes, '.*'), re.I), 'type') typespattern4implicit = re.compile(beforethisafter % ('', fortrantypes + '|static|automatic|undefined', fortrantypes + '|static|automatic|undefined', '.*'), re.I) functionpattern = (re.compile(beforethisafter % ('([a-z]+[\\w\\s(=*+-/)]*?|)', 'function', 'function', '.*'), re.I), 'begin') subroutinepattern = (re.compile(beforethisafter % ('[a-z\\s]*?', 'subroutine', 'subroutine', '.*'), re.I), 'begin') groupbegins77 = 'program|block\\s*data' beginpattern77 = (re.compile(beforethisafter % ('', groupbegins77, groupbegins77, '.*'), re.I), 'begin') groupbegins90 = groupbegins77 + '|module(?!\\s*procedure)|python\\s*module|(abstract|)\\s*interface|' + 'type(?!\\s*\\()' beginpattern90 = (re.compile(beforethisafter % ('', groupbegins90, groupbegins90, '.*'), re.I), 'begin') groupends = 'end|endprogram|endblockdata|endmodule|endpythonmodule|endinterface|endsubroutine|endfunction' endpattern = (re.compile(beforethisafter % ('', groupends, groupends, '.*'), re.I), 'end') endifs = 'end\\s*(if|do|where|select|while|forall|associate|' + 'critical|enum|team)' endifpattern = (re.compile(beforethisafter % ('[\\w]*?', endifs, endifs, '.*'), re.I), 'endif') moduleprocedures = 'module\\s*procedure' moduleprocedurepattern = (re.compile(beforethisafter % ('', moduleprocedures, moduleprocedures, '.*'), re.I), 'moduleprocedure') implicitpattern = (re.compile(beforethisafter % ('', 'implicit', 'implicit', '.*'), re.I), 'implicit') dimensionpattern = (re.compile(beforethisafter % ('', 'dimension|virtual', 'dimension|virtual', '.*'), re.I), 'dimension') externalpattern = (re.compile(beforethisafter % ('', 'external', 'external', '.*'), re.I), 'external') optionalpattern = (re.compile(beforethisafter % ('', 'optional', 'optional', '.*'), re.I), 'optional') requiredpattern = (re.compile(beforethisafter % ('', 'required', 'required', '.*'), re.I), 'required') publicpattern = (re.compile(beforethisafter % ('', 'public', 'public', '.*'), re.I), 'public') privatepattern = (re.compile(beforethisafter % ('', 'private', 'private', '.*'), re.I), 'private') intrinsicpattern = (re.compile(beforethisafter % ('', 'intrinsic', 'intrinsic', '.*'), re.I), 'intrinsic') intentpattern = (re.compile(beforethisafter % ('', 'intent|depend|note|check', 'intent|depend|note|check', '\\s*\\(.*?\\).*'), re.I), 'intent') parameterpattern = (re.compile(beforethisafter % ('', 'parameter', 'parameter', '\\s*\\(.*'), re.I), 'parameter') datapattern = (re.compile(beforethisafter % ('', 'data', 'data', '.*'), re.I), 'data') callpattern = (re.compile(beforethisafter % ('', 'call', 'call', '.*'), re.I), 'call') entrypattern = (re.compile(beforethisafter % ('', 'entry', 'entry', '.*'), re.I), 'entry') callfunpattern = (re.compile(beforethisafter % ('', 'callfun', 'callfun', '.*'), re.I), 'callfun') commonpattern = (re.compile(beforethisafter % ('', 'common', 'common', '.*'), re.I), 'common') usepattern = (re.compile(beforethisafter % ('', 'use', 'use', '.*'), re.I), 'use') containspattern = (re.compile(beforethisafter % ('', 'contains', 'contains', ''), re.I), 'contains') formatpattern = (re.compile(beforethisafter % ('', 'format', 'format', '.*'), re.I), 'format') f2pyenhancementspattern = (re.compile(beforethisafter % ('', 'threadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddef', 'threadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddef', '.*'), re.I | re.S), 'f2pyenhancements') multilinepattern = (re.compile("\\s*(?P''')(?P.*?)(?P''')\\s*\\Z", re.S), 'multiline') def split_by_unquoted(line, characters): assert not set('"\'') & set(characters), 'cannot split by unquoted quotes' r = re.compile('\\A(?P({single_quoted}|{double_quoted}|{not_quoted})*)(?P{char}.*)\\Z'.format(not_quoted='[^"\'{}]'.format(re.escape(characters)), char='[{}]'.format(re.escape(characters)), single_quoted="('([^'\\\\]|(\\\\.))*')", double_quoted='("([^"\\\\]|(\\\\.))*")')) m = r.match(line) if m: d = m.groupdict() return (d['before'], d['after']) return (line, '') def _simplifyargs(argsline): a = [] for n in markoutercomma(argsline).split('@,@'): for r in '(),': n = n.replace(r, '_') a.append(n) return ','.join(a) crackline_re_1 = re.compile('\\s*(?P\\b[a-z]+\\w*\\b)\\s*=.*', re.I) crackline_bind_1 = re.compile('\\s*(?P\\b[a-z]+\\w*\\b)\\s*=.*', re.I) crackline_bindlang = re.compile('\\s*bind\\(\\s*(?P[^,]+)\\s*,\\s*name\\s*=\\s*"(?P[^"]+)"\\s*\\)', re.I) def crackline(line, reset=0): global beginpattern, groupcounter, groupname, groupcache, grouplist global filepositiontext, currentfilename, neededmodule, expectbegin global skipblocksuntil, skipemptyends, previous_context, gotnextfile (_, has_semicolon) = split_by_unquoted(line, ';') if has_semicolon and (not (f2pyenhancementspattern[0].match(line) or multilinepattern[0].match(line))): assert reset == 0, repr(reset) (line, semicolon_line) = split_by_unquoted(line, ';') while semicolon_line: crackline(line, reset) (line, semicolon_line) = split_by_unquoted(semicolon_line[1:], ';') crackline(line, reset) return if reset < 0: groupcounter = 0 groupname = {groupcounter: ''} groupcache = {groupcounter: {}} grouplist = {groupcounter: []} groupcache[groupcounter]['body'] = [] groupcache[groupcounter]['vars'] = {} groupcache[groupcounter]['block'] = '' groupcache[groupcounter]['name'] = '' neededmodule = -1 skipblocksuntil = -1 return if reset > 0: fl = 0 if f77modulename and neededmodule == groupcounter: fl = 2 while groupcounter > fl: outmess('crackline: groupcounter=%s groupname=%s\n' % (repr(groupcounter), repr(groupname))) outmess('crackline: Mismatch of blocks encountered. Trying to fix it by assuming "end" statement.\n') grouplist[groupcounter - 1].append(groupcache[groupcounter]) grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] del grouplist[groupcounter] groupcounter = groupcounter - 1 if f77modulename and neededmodule == groupcounter: grouplist[groupcounter - 1].append(groupcache[groupcounter]) grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] del grouplist[groupcounter] groupcounter = groupcounter - 1 grouplist[groupcounter - 1].append(groupcache[groupcounter]) grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] del grouplist[groupcounter] groupcounter = groupcounter - 1 neededmodule = -1 return if line == '': return flag = 0 for pat in [dimensionpattern, externalpattern, intentpattern, optionalpattern, requiredpattern, parameterpattern, datapattern, publicpattern, privatepattern, intrinsicpattern, endifpattern, endpattern, formatpattern, beginpattern, functionpattern, subroutinepattern, implicitpattern, typespattern, commonpattern, callpattern, usepattern, containspattern, entrypattern, f2pyenhancementspattern, multilinepattern, moduleprocedurepattern]: m = pat[0].match(line) if m: break flag = flag + 1 if not m: re_1 = crackline_re_1 if 0 <= skipblocksuntil <= groupcounter: return if 'externals' in groupcache[groupcounter]: for name in groupcache[groupcounter]['externals']: if name in invbadnames: name = invbadnames[name] if 'interfaced' in groupcache[groupcounter] and name in groupcache[groupcounter]['interfaced']: continue m1 = re.match('(?P[^"]*)\\b%s\\b\\s*@\\(@(?P[^@]*)@\\)@.*\\Z' % name, markouterparen(line), re.I) if m1: m2 = re_1.match(m1.group('before')) a = _simplifyargs(m1.group('args')) if m2: line = 'callfun %s(%s) result (%s)' % (name, a, m2.group('result')) else: line = 'callfun %s(%s)' % (name, a) m = callfunpattern[0].match(line) if not m: outmess('crackline: could not resolve function call for line=%s.\n' % repr(line)) return analyzeline(m, 'callfun', line) return if verbose > 1 or (verbose == 1 and currentfilename.lower().endswith('.pyf')): previous_context = None outmess('crackline:%d: No pattern for line\n' % groupcounter) return elif pat[1] == 'end': if 0 <= skipblocksuntil < groupcounter: groupcounter = groupcounter - 1 if skipblocksuntil <= groupcounter: return if groupcounter <= 0: raise Exception('crackline: groupcounter(=%s) is nonpositive. Check the blocks.' % groupcounter) m1 = beginpattern[0].match(line) if m1 and (not m1.group('this') == groupname[groupcounter]): raise Exception('crackline: End group %s does not match with previous Begin group %s\n\t%s' % (repr(m1.group('this')), repr(groupname[groupcounter]), filepositiontext)) if skipblocksuntil == groupcounter: skipblocksuntil = -1 grouplist[groupcounter - 1].append(groupcache[groupcounter]) grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] del grouplist[groupcounter] groupcounter = groupcounter - 1 if not skipemptyends: expectbegin = 1 elif pat[1] == 'begin': if 0 <= skipblocksuntil <= groupcounter: groupcounter = groupcounter + 1 return gotnextfile = 0 analyzeline(m, pat[1], line) expectbegin = 0 elif pat[1] == 'endif': pass elif pat[1] == 'moduleprocedure': analyzeline(m, pat[1], line) elif pat[1] == 'contains': if ignorecontains: return if 0 <= skipblocksuntil <= groupcounter: return skipblocksuntil = groupcounter else: if 0 <= skipblocksuntil <= groupcounter: return analyzeline(m, pat[1], line) def markouterparen(line): l = '' f = 0 for c in line: if c == '(': f = f + 1 if f == 1: l = l + '@(@' continue elif c == ')': f = f - 1 if f == 0: l = l + '@)@' continue l = l + c return l def markoutercomma(line, comma=','): l = '' f = 0 (before, after) = split_by_unquoted(line, comma + '()') l += before while after: if after[0] == comma and f == 0: l += '@' + comma + '@' else: l += after[0] if after[0] == '(': f += 1 elif after[0] == ')': f -= 1 (before, after) = split_by_unquoted(after[1:], comma + '()') l += before assert not f, repr((f, line, l)) return l def unmarkouterparen(line): r = line.replace('@(@', '(').replace('@)@', ')') return r def appenddecl(decl, decl2, force=1): if not decl: decl = {} if not decl2: return decl if decl is decl2: return decl for k in list(decl2.keys()): if k == 'typespec': if force or k not in decl: decl[k] = decl2[k] elif k == 'attrspec': for l in decl2[k]: decl = setattrspec(decl, l, force) elif k == 'kindselector': decl = setkindselector(decl, decl2[k], force) elif k == 'charselector': decl = setcharselector(decl, decl2[k], force) elif k in ['=', 'typename']: if force or k not in decl: decl[k] = decl2[k] elif k == 'note': pass elif k in ['intent', 'check', 'dimension', 'optional', 'required', 'depend']: errmess('appenddecl: "%s" not implemented.\n' % k) else: raise Exception('appenddecl: Unknown variable definition key: ' + str(k)) return decl selectpattern = re.compile('\\s*(?P(@\\(@.*?@\\)@|\\*[\\d*]+|\\*\\s*@\\(@.*?@\\)@|))(?P.*)\\Z', re.I) typedefpattern = re.compile('(?:,(?P[\\w(),]+))?(::)?(?P\\b[a-z$_][\\w$]*\\b)(?:\\((?P[\\w,]*)\\))?\\Z', re.I) nameargspattern = re.compile('\\s*(?P\\b[\\w$]+\\b)\\s*(@\\(@\\s*(?P[\\w\\s,]*)\\s*@\\)@|)\\s*((result(\\s*@\\(@\\s*(?P\\b[\\w$]+\\b)\\s*@\\)@|))|(bind\\s*@\\(@\\s*(?P(?:(?!@\\)@).)*)\\s*@\\)@))*\\s*\\Z', re.I) operatorpattern = re.compile('\\s*(?P(operator|assignment))@\\(@\\s*(?P[^)]+)\\s*@\\)@\\s*\\Z', re.I) callnameargspattern = re.compile('\\s*(?P\\b[\\w$]+\\b)\\s*@\\(@\\s*(?P.*)\\s*@\\)@\\s*\\Z', re.I) real16pattern = re.compile('([-+]?(?:\\d+(?:\\.\\d*)?|\\d*\\.\\d+))[dD]((?:[-+]?\\d+)?)') real8pattern = re.compile('([-+]?((?:\\d+(?:\\.\\d*)?|\\d*\\.\\d+))[eE]((?:[-+]?\\d+)?)|(\\d+\\.\\d*))') _intentcallbackpattern = re.compile('intent\\s*\\(.*?\\bcallback\\b', re.I) def _is_intent_callback(vdecl): for a in vdecl.get('attrspec', []): if _intentcallbackpattern.match(a): return 1 return 0 def _resolvetypedefpattern(line): line = ''.join(line.split()) m1 = typedefpattern.match(line) print(line, m1) if m1: attrs = m1.group('attributes') attrs = [a.lower() for a in attrs.split(',')] if attrs else [] return (m1.group('name'), attrs, m1.group('params')) return (None, [], None) def parse_name_for_bind(line): pattern = re.compile('bind\\(\\s*(?P[^,]+)(?:\\s*,\\s*name\\s*=\\s*["\\\'](?P[^"\\\']+)["\\\']\\s*)?\\)', re.I) match = pattern.search(line) bind_statement = None if match: bind_statement = match.group(0) line = line[:match.start()] + line[match.end():] return (line, bind_statement) def _resolvenameargspattern(line): (line, bind_cname) = parse_name_for_bind(line) line = markouterparen(line) m1 = nameargspattern.match(line) if m1: return (m1.group('name'), m1.group('args'), m1.group('result'), bind_cname) m1 = operatorpattern.match(line) if m1: name = m1.group('scheme') + '(' + m1.group('name') + ')' return (name, [], None, None) m1 = callnameargspattern.match(line) if m1: return (m1.group('name'), m1.group('args'), None, None) return (None, [], None, None) def analyzeline(m, case, line): global groupcounter, groupname, groupcache, grouplist, filepositiontext global currentfilename, f77modulename, neededinterface, neededmodule global expectbegin, gotnextfile, previous_context block = m.group('this') if case != 'multiline': previous_context = None if expectbegin and case not in ['begin', 'call', 'callfun', 'type'] and (not skipemptyends) and (groupcounter < 1): newname = os.path.basename(currentfilename).split('.')[0] outmess('analyzeline: no group yet. Creating program group with name "%s".\n' % newname) gotnextfile = 0 groupcounter = groupcounter + 1 groupname[groupcounter] = 'program' groupcache[groupcounter] = {} grouplist[groupcounter] = [] groupcache[groupcounter]['body'] = [] groupcache[groupcounter]['vars'] = {} groupcache[groupcounter]['block'] = 'program' groupcache[groupcounter]['name'] = newname groupcache[groupcounter]['from'] = 'fromsky' expectbegin = 0 if case in ['begin', 'call', 'callfun']: block = block.lower() if re.match('block\\s*data', block, re.I): block = 'block data' elif re.match('python\\s*module', block, re.I): block = 'python module' elif re.match('abstract\\s*interface', block, re.I): block = 'abstract interface' if block == 'type': (name, attrs, _) = _resolvetypedefpattern(m.group('after')) groupcache[groupcounter]['vars'][name] = dict(attrspec=attrs) args = [] result = None else: (name, args, result, bindcline) = _resolvenameargspattern(m.group('after')) if name is None: if block == 'block data': name = '_BLOCK_DATA_' else: name = '' if block not in ['interface', 'block data', 'abstract interface']: outmess('analyzeline: No name/args pattern found for line.\n') previous_context = (block, name, groupcounter) if args: args = rmbadname([x.strip() for x in markoutercomma(args).split('@,@')]) else: args = [] if '' in args: while '' in args: args.remove('') outmess('analyzeline: argument list is malformed (missing argument).\n') needmodule = 0 needinterface = 0 if case in ['call', 'callfun']: needinterface = 1 if 'args' not in groupcache[groupcounter]: return if name not in groupcache[groupcounter]['args']: return for it in grouplist[groupcounter]: if it['name'] == name: return if name in groupcache[groupcounter]['interfaced']: return block = {'call': 'subroutine', 'callfun': 'function'}[case] if f77modulename and neededmodule == -1 and (groupcounter <= 1): neededmodule = groupcounter + 2 needmodule = 1 if block not in ['interface', 'abstract interface']: needinterface = 1 groupcounter = groupcounter + 1 groupcache[groupcounter] = {} grouplist[groupcounter] = [] if needmodule: if verbose > 1: outmess('analyzeline: Creating module block %s\n' % repr(f77modulename), 0) groupname[groupcounter] = 'module' groupcache[groupcounter]['block'] = 'python module' groupcache[groupcounter]['name'] = f77modulename groupcache[groupcounter]['from'] = '' groupcache[groupcounter]['body'] = [] groupcache[groupcounter]['externals'] = [] groupcache[groupcounter]['interfaced'] = [] groupcache[groupcounter]['vars'] = {} groupcounter = groupcounter + 1 groupcache[groupcounter] = {} grouplist[groupcounter] = [] if needinterface: if verbose > 1: outmess('analyzeline: Creating additional interface block (groupcounter=%s).\n' % groupcounter, 0) groupname[groupcounter] = 'interface' groupcache[groupcounter]['block'] = 'interface' groupcache[groupcounter]['name'] = 'unknown_interface' groupcache[groupcounter]['from'] = '%s:%s' % (groupcache[groupcounter - 1]['from'], groupcache[groupcounter - 1]['name']) groupcache[groupcounter]['body'] = [] groupcache[groupcounter]['externals'] = [] groupcache[groupcounter]['interfaced'] = [] groupcache[groupcounter]['vars'] = {} groupcounter = groupcounter + 1 groupcache[groupcounter] = {} grouplist[groupcounter] = [] groupname[groupcounter] = block groupcache[groupcounter]['block'] = block if not name: name = 'unknown_' + block.replace(' ', '_') groupcache[groupcounter]['prefix'] = m.group('before') groupcache[groupcounter]['name'] = rmbadname1(name) groupcache[groupcounter]['result'] = result if groupcounter == 1: groupcache[groupcounter]['from'] = currentfilename elif f77modulename and groupcounter == 3: groupcache[groupcounter]['from'] = '%s:%s' % (groupcache[groupcounter - 1]['from'], currentfilename) else: groupcache[groupcounter]['from'] = '%s:%s' % (groupcache[groupcounter - 1]['from'], groupcache[groupcounter - 1]['name']) for k in list(groupcache[groupcounter].keys()): if not groupcache[groupcounter][k]: del groupcache[groupcounter][k] groupcache[groupcounter]['args'] = args groupcache[groupcounter]['body'] = [] groupcache[groupcounter]['externals'] = [] groupcache[groupcounter]['interfaced'] = [] groupcache[groupcounter]['vars'] = {} groupcache[groupcounter]['entry'] = {} if block == 'type': groupcache[groupcounter]['varnames'] = [] if case in ['call', 'callfun']: if name not in groupcache[groupcounter - 2]['externals']: groupcache[groupcounter - 2]['externals'].append(name) groupcache[groupcounter]['vars'] = copy.deepcopy(groupcache[groupcounter - 2]['vars']) try: del groupcache[groupcounter]['vars'][name][groupcache[groupcounter]['vars'][name]['attrspec'].index('external')] except Exception: pass if block in ['function', 'subroutine']: if bindcline: bindcdat = re.search(crackline_bindlang, bindcline) if bindcdat: groupcache[groupcounter]['bindlang'] = {name: {}} groupcache[groupcounter]['bindlang'][name]['lang'] = bindcdat.group('lang') if bindcdat.group('lang_name'): groupcache[groupcounter]['bindlang'][name]['name'] = bindcdat.group('lang_name') try: groupcache[groupcounter]['vars'][name] = appenddecl(groupcache[groupcounter]['vars'][name], groupcache[groupcounter - 2]['vars']['']) except Exception: pass if case == 'callfun': if result and result in groupcache[groupcounter]['vars']: if not name == result: groupcache[groupcounter]['vars'][name] = appenddecl(groupcache[groupcounter]['vars'][name], groupcache[groupcounter]['vars'][result]) try: groupcache[groupcounter - 2]['interfaced'].append(name) except Exception: pass if block == 'function': t = typespattern[0].match(m.group('before') + ' ' + name) if t: (typespec, selector, attr, edecl) = cracktypespec0(t.group('this'), t.group('after')) updatevars(typespec, selector, attr, edecl) if case in ['call', 'callfun']: grouplist[groupcounter - 1].append(groupcache[groupcounter]) grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] del grouplist[groupcounter] groupcounter = groupcounter - 1 grouplist[groupcounter - 1].append(groupcache[groupcounter]) grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter] del grouplist[groupcounter] groupcounter = groupcounter - 1 elif case == 'entry': (name, args, result, _) = _resolvenameargspattern(m.group('after')) if name is not None: if args: args = rmbadname([x.strip() for x in markoutercomma(args).split('@,@')]) else: args = [] assert result is None, repr(result) groupcache[groupcounter]['entry'][name] = args previous_context = ('entry', name, groupcounter) elif case == 'type': (typespec, selector, attr, edecl) = cracktypespec0(block, m.group('after')) last_name = updatevars(typespec, selector, attr, edecl) if last_name is not None: previous_context = ('variable', last_name, groupcounter) elif case in ['dimension', 'intent', 'optional', 'required', 'external', 'public', 'private', 'intrinsic']: edecl = groupcache[groupcounter]['vars'] ll = m.group('after').strip() i = ll.find('::') if i < 0 and case == 'intent': i = markouterparen(ll).find('@)@') - 2 ll = ll[:i + 1] + '::' + ll[i + 1:] i = ll.find('::') if ll[i:] == '::' and 'args' in groupcache[groupcounter]: outmess('All arguments will have attribute %s%s\n' % (m.group('this'), ll[:i])) ll = ll + ','.join(groupcache[groupcounter]['args']) if i < 0: i = 0 pl = '' else: pl = ll[:i].strip() ll = ll[i + 2:] ch = markoutercomma(pl).split('@,@') if len(ch) > 1: pl = ch[0] outmess('analyzeline: cannot handle multiple attributes without type specification. Ignoring %r.\n' % ','.join(ch[1:])) last_name = None for e in [x.strip() for x in markoutercomma(ll).split('@,@')]: m1 = namepattern.match(e) if not m1: if case in ['public', 'private']: k = '' else: print(m.groupdict()) outmess('analyzeline: no name pattern found in %s statement for %s. Skipping.\n' % (case, repr(e))) continue else: k = rmbadname1(m1.group('name')) if case in ['public', 'private'] and (k == 'operator' or k == 'assignment'): k += m1.group('after') if k not in edecl: edecl[k] = {} if case == 'dimension': ap = case + m1.group('after') if case == 'intent': ap = m.group('this') + pl if _intentcallbackpattern.match(ap): if k not in groupcache[groupcounter]['args']: if groupcounter > 1: if '__user__' not in groupcache[groupcounter - 2]['name']: outmess('analyzeline: missing __user__ module (could be nothing)\n') if k != groupcache[groupcounter]['name']: outmess('analyzeline: appending intent(callback) %s to %s arguments\n' % (k, groupcache[groupcounter]['name'])) groupcache[groupcounter]['args'].append(k) else: errmess('analyzeline: intent(callback) %s is ignored\n' % k) else: errmess('analyzeline: intent(callback) %s is already in argument list\n' % k) if case in ['optional', 'required', 'public', 'external', 'private', 'intrinsic']: ap = case if 'attrspec' in edecl[k]: edecl[k]['attrspec'].append(ap) else: edecl[k]['attrspec'] = [ap] if case == 'external': if groupcache[groupcounter]['block'] == 'program': outmess('analyzeline: ignoring program arguments\n') continue if k not in groupcache[groupcounter]['args']: continue if 'externals' not in groupcache[groupcounter]: groupcache[groupcounter]['externals'] = [] groupcache[groupcounter]['externals'].append(k) last_name = k groupcache[groupcounter]['vars'] = edecl if last_name is not None: previous_context = ('variable', last_name, groupcounter) elif case == 'moduleprocedure': groupcache[groupcounter]['implementedby'] = [x.strip() for x in m.group('after').split(',')] elif case == 'parameter': edecl = groupcache[groupcounter]['vars'] ll = m.group('after').strip()[1:-1] last_name = None for e in markoutercomma(ll).split('@,@'): try: (k, initexpr) = [x.strip() for x in e.split('=')] except Exception: outmess('analyzeline: could not extract name,expr in parameter statement "%s" of "%s"\n' % (e, ll)) continue params = get_parameters(edecl) k = rmbadname1(k) if k not in edecl: edecl[k] = {} if '=' in edecl[k] and (not edecl[k]['='] == initexpr): outmess('analyzeline: Overwriting the value of parameter "%s" ("%s") with "%s".\n' % (k, edecl[k]['='], initexpr)) t = determineexprtype(initexpr, params) if t: if t.get('typespec') == 'real': tt = list(initexpr) for m in real16pattern.finditer(initexpr): tt[m.start():m.end()] = list(initexpr[m.start():m.end()].lower().replace('d', 'e')) initexpr = ''.join(tt) elif t.get('typespec') == 'complex': initexpr = initexpr[1:].lower().replace('d', 'e').replace(',', '+1j*(') try: v = eval(initexpr, {}, params) except (SyntaxError, NameError, TypeError) as msg: errmess('analyzeline: Failed to evaluate %r. Ignoring: %s\n' % (initexpr, msg)) continue edecl[k]['='] = repr(v) if 'attrspec' in edecl[k]: edecl[k]['attrspec'].append('parameter') else: edecl[k]['attrspec'] = ['parameter'] last_name = k groupcache[groupcounter]['vars'] = edecl if last_name is not None: previous_context = ('variable', last_name, groupcounter) elif case == 'implicit': if m.group('after').strip().lower() == 'none': groupcache[groupcounter]['implicit'] = None elif m.group('after'): if 'implicit' in groupcache[groupcounter]: impl = groupcache[groupcounter]['implicit'] else: impl = {} if impl is None: outmess('analyzeline: Overwriting earlier "implicit none" statement.\n') impl = {} for e in markoutercomma(m.group('after')).split('@,@'): decl = {} m1 = re.match('\\s*(?P.*?)\\s*(\\(\\s*(?P[a-z-, ]+)\\s*\\)\\s*|)\\Z', e, re.I) if not m1: outmess('analyzeline: could not extract info of implicit statement part "%s"\n' % e) continue m2 = typespattern4implicit.match(m1.group('this')) if not m2: outmess('analyzeline: could not extract types pattern of implicit statement part "%s"\n' % e) continue (typespec, selector, attr, edecl) = cracktypespec0(m2.group('this'), m2.group('after')) (kindselect, charselect, typename) = cracktypespec(typespec, selector) decl['typespec'] = typespec decl['kindselector'] = kindselect decl['charselector'] = charselect decl['typename'] = typename for k in list(decl.keys()): if not decl[k]: del decl[k] for r in markoutercomma(m1.group('after')).split('@,@'): if '-' in r: try: (begc, endc) = [x.strip() for x in r.split('-')] except Exception: outmess('analyzeline: expected "-" instead of "%s" in range list of implicit statement\n' % r) continue else: begc = endc = r.strip() if not len(begc) == len(endc) == 1: outmess('analyzeline: expected "-" instead of "%s" in range list of implicit statement (2)\n' % r) continue for o in range(ord(begc), ord(endc) + 1): impl[chr(o)] = decl groupcache[groupcounter]['implicit'] = impl elif case == 'data': ll = [] dl = '' il = '' f = 0 fc = 1 inp = 0 for c in m.group('after'): if not inp: if c == "'": fc = not fc if c == '/' and fc: f = f + 1 continue if c == '(': inp = inp + 1 elif c == ')': inp = inp - 1 if f == 0: dl = dl + c elif f == 1: il = il + c elif f == 2: dl = dl.strip() if dl.startswith(','): dl = dl[1:].strip() ll.append([dl, il]) dl = c il = '' f = 0 if f == 2: dl = dl.strip() if dl.startswith(','): dl = dl[1:].strip() ll.append([dl, il]) vars = groupcache[groupcounter].get('vars', {}) last_name = None for l in ll: (l[0], l[1]) = (l[0].strip(), l[1].strip()) if l[0].startswith(','): l[0] = l[0][1:] if l[0].startswith('('): outmess('analyzeline: implied-DO list "%s" is not supported. Skipping.\n' % l[0]) continue for (idx, v) in enumerate(rmbadname([x.strip() for x in markoutercomma(l[0]).split('@,@')])): if v.startswith('('): outmess('analyzeline: implied-DO list "%s" is not supported. Skipping.\n' % v) continue if '!' in l[1]: outmess('Comment line in declaration "%s" is not supported. Skipping.\n' % l[1]) continue vars.setdefault(v, {}) vtype = vars[v].get('typespec') vdim = getdimension(vars[v]) matches = re.findall('\\(.*?\\)', l[1]) if vtype == 'complex' else l[1].split(',') try: new_val = '(/{}/)'.format(', '.join(matches)) if vdim else matches[idx] except IndexError: if any(('*' in m for m in matches)): expanded_list = [] for match in matches: if '*' in match: try: (multiplier, value) = match.split('*') expanded_list.extend([value.strip()] * int(multiplier)) except ValueError: expanded_list.append(match.strip()) else: expanded_list.append(match.strip()) matches = expanded_list new_val = '(/{}/)'.format(', '.join(matches)) if vdim else matches[idx] current_val = vars[v].get('=') if current_val and current_val != new_val: outmess('analyzeline: changing init expression of "%s" ("%s") to "%s"\n' % (v, current_val, new_val)) vars[v]['='] = new_val last_name = v groupcache[groupcounter]['vars'] = vars if last_name: previous_context = ('variable', last_name, groupcounter) elif case == 'common': line = m.group('after').strip() if not line[0] == '/': line = '//' + line cl = [] f = 0 bn = '' ol = '' for c in line: if c == '/': f = f + 1 continue if f >= 3: bn = bn.strip() if not bn: bn = '_BLNK_' cl.append([bn, ol]) f = f - 2 bn = '' ol = '' if f % 2: bn = bn + c else: ol = ol + c bn = bn.strip() if not bn: bn = '_BLNK_' cl.append([bn, ol]) commonkey = {} if 'common' in groupcache[groupcounter]: commonkey = groupcache[groupcounter]['common'] for c in cl: if c[0] not in commonkey: commonkey[c[0]] = [] for i in [x.strip() for x in markoutercomma(c[1]).split('@,@')]: if i: commonkey[c[0]].append(i) groupcache[groupcounter]['common'] = commonkey previous_context = ('common', bn, groupcounter) elif case == 'use': m1 = re.match('\\A\\s*(?P\\b\\w+\\b)\\s*((,(\\s*\\bonly\\b\\s*:|(?P))\\s*(?P.*))|)\\s*\\Z', m.group('after'), re.I) if m1: mm = m1.groupdict() if 'use' not in groupcache[groupcounter]: groupcache[groupcounter]['use'] = {} name = m1.group('name') groupcache[groupcounter]['use'][name] = {} isonly = 0 if 'list' in mm and mm['list'] is not None: if 'notonly' in mm and mm['notonly'] is None: isonly = 1 groupcache[groupcounter]['use'][name]['only'] = isonly ll = [x.strip() for x in mm['list'].split(',')] rl = {} for l in ll: if '=' in l: m2 = re.match('\\A\\s*(?P\\b\\w+\\b)\\s*=\\s*>\\s*(?P\\b\\w+\\b)\\s*\\Z', l, re.I) if m2: rl[m2.group('local').strip()] = m2.group('use').strip() else: outmess('analyzeline: Not local=>use pattern found in %s\n' % repr(l)) else: rl[l] = l groupcache[groupcounter]['use'][name]['map'] = rl else: pass else: print(m.groupdict()) outmess('analyzeline: Could not crack the use statement.\n') elif case in ['f2pyenhancements']: if 'f2pyenhancements' not in groupcache[groupcounter]: groupcache[groupcounter]['f2pyenhancements'] = {} d = groupcache[groupcounter]['f2pyenhancements'] if m.group('this') == 'usercode' and 'usercode' in d: if isinstance(d['usercode'], str): d['usercode'] = [d['usercode']] d['usercode'].append(m.group('after')) else: d[m.group('this')] = m.group('after') elif case == 'multiline': if previous_context is None: if verbose: outmess('analyzeline: No context for multiline block.\n') return gc = groupcounter appendmultiline(groupcache[gc], previous_context[:2], m.group('this')) elif verbose > 1: print(m.groupdict()) outmess('analyzeline: No code implemented for line.\n') def appendmultiline(group, context_name, ml): if 'f2pymultilines' not in group: group['f2pymultilines'] = {} d = group['f2pymultilines'] if context_name not in d: d[context_name] = [] d[context_name].append(ml) return def cracktypespec0(typespec, ll): selector = None attr = None if re.match('double\\s*complex', typespec, re.I): typespec = 'double complex' elif re.match('double\\s*precision', typespec, re.I): typespec = 'double precision' else: typespec = typespec.strip().lower() m1 = selectpattern.match(markouterparen(ll)) if not m1: outmess('cracktypespec0: no kind/char_selector pattern found for line.\n') return d = m1.groupdict() for k in list(d.keys()): d[k] = unmarkouterparen(d[k]) if typespec in ['complex', 'integer', 'logical', 'real', 'character', 'type']: selector = d['this'] ll = d['after'] i = ll.find('::') if i >= 0: attr = ll[:i].strip() ll = ll[i + 2:] return (typespec, selector, attr, ll) namepattern = re.compile('\\s*(?P\\b\\w+\\b)\\s*(?P.*)\\s*\\Z', re.I) kindselector = re.compile('\\s*(\\(\\s*(kind\\s*=)?\\s*(?P.*)\\s*\\)|\\*\\s*(?P.*?))\\s*\\Z', re.I) charselector = re.compile('\\s*(\\((?P.*)\\)|\\*\\s*(?P.*))\\s*\\Z', re.I) lenkindpattern = re.compile('\\s*(kind\\s*=\\s*(?P.*?)\\s*(@,@\\s*len\\s*=\\s*(?P.*)|)|(len\\s*=\\s*|)(?P.*?)\\s*(@,@\\s*(kind\\s*=\\s*|)(?P.*)|(f2py_len\\s*=\\s*(?P.*))|))\\s*\\Z', re.I) lenarraypattern = re.compile('\\s*(@\\(@\\s*(?!/)\\s*(?P.*?)\\s*@\\)@\\s*\\*\\s*(?P.*?)|(\\*\\s*(?P.*?)|)\\s*(@\\(@\\s*(?!/)\\s*(?P.*?)\\s*@\\)@|))\\s*(=\\s*(?P.*?)|(@\\(@|)/\\s*(?P.*?)\\s*/(@\\)@|)|)\\s*\\Z', re.I) def removespaces(expr): expr = expr.strip() if len(expr) <= 1: return expr expr2 = expr[0] for i in range(1, len(expr) - 1): if expr[i] == ' ' and (expr[i + 1] in '()[]{}=+-/* ' or expr[i - 1] in '()[]{}=+-/* '): continue expr2 = expr2 + expr[i] expr2 = expr2 + expr[-1] return expr2 def markinnerspaces(line): fragment = '' inside = False current_quote = None escaped = '' for c in line: if escaped == '\\' and c in ['\\', "'", '"']: fragment += c escaped = c continue if not inside and c in ["'", '"']: current_quote = c if c == current_quote: inside = not inside elif c == ' ' and inside: fragment += '@_@' continue fragment += c escaped = c return fragment def updatevars(typespec, selector, attrspec, entitydecl): global groupcache, groupcounter last_name = None (kindselect, charselect, typename) = cracktypespec(typespec, selector) if attrspec: attrspec = [x.strip() for x in markoutercomma(attrspec).split('@,@')] l = [] c = re.compile('(?P[a-zA-Z]+)') for a in attrspec: if not a: continue m = c.match(a) if m: s = m.group('start').lower() a = s + a[len(s):] l.append(a) attrspec = l el = [x.strip() for x in markoutercomma(entitydecl).split('@,@')] el1 = [] for e in el: for e1 in [x.strip() for x in markoutercomma(removespaces(markinnerspaces(e)), comma=' ').split('@ @')]: if e1: el1.append(e1.replace('@_@', ' ')) for e in el1: m = namepattern.match(e) if not m: outmess('updatevars: no name pattern found for entity=%s. Skipping.\n' % repr(e)) continue ename = rmbadname1(m.group('name')) edecl = {} if ename in groupcache[groupcounter]['vars']: edecl = groupcache[groupcounter]['vars'][ename].copy() not_has_typespec = 'typespec' not in edecl if not_has_typespec: edecl['typespec'] = typespec elif typespec and (not typespec == edecl['typespec']): outmess('updatevars: attempt to change the type of "%s" ("%s") to "%s". Ignoring.\n' % (ename, edecl['typespec'], typespec)) if 'kindselector' not in edecl: edecl['kindselector'] = copy.copy(kindselect) elif kindselect: for k in list(kindselect.keys()): if k in edecl['kindselector'] and (not kindselect[k] == edecl['kindselector'][k]): outmess('updatevars: attempt to change the kindselector "%s" of "%s" ("%s") to "%s". Ignoring.\n' % (k, ename, edecl['kindselector'][k], kindselect[k])) else: edecl['kindselector'][k] = copy.copy(kindselect[k]) if 'charselector' not in edecl and charselect: if not_has_typespec: edecl['charselector'] = charselect else: errmess('updatevars:%s: attempt to change empty charselector to %r. Ignoring.\n' % (ename, charselect)) elif charselect: for k in list(charselect.keys()): if k in edecl['charselector'] and (not charselect[k] == edecl['charselector'][k]): outmess('updatevars: attempt to change the charselector "%s" of "%s" ("%s") to "%s". Ignoring.\n' % (k, ename, edecl['charselector'][k], charselect[k])) else: edecl['charselector'][k] = copy.copy(charselect[k]) if 'typename' not in edecl: edecl['typename'] = typename elif typename and (not edecl['typename'] == typename): outmess('updatevars: attempt to change the typename of "%s" ("%s") to "%s". Ignoring.\n' % (ename, edecl['typename'], typename)) if 'attrspec' not in edecl: edecl['attrspec'] = copy.copy(attrspec) elif attrspec: for a in attrspec: if a not in edecl['attrspec']: edecl['attrspec'].append(a) else: edecl['typespec'] = copy.copy(typespec) edecl['kindselector'] = copy.copy(kindselect) edecl['charselector'] = copy.copy(charselect) edecl['typename'] = typename edecl['attrspec'] = copy.copy(attrspec) if 'external' in (edecl.get('attrspec') or []) and e in groupcache[groupcounter]['args']: if 'externals' not in groupcache[groupcounter]: groupcache[groupcounter]['externals'] = [] groupcache[groupcounter]['externals'].append(e) if m.group('after'): m1 = lenarraypattern.match(markouterparen(m.group('after'))) if m1: d1 = m1.groupdict() for lk in ['len', 'array', 'init']: if d1[lk + '2'] is not None: d1[lk] = d1[lk + '2'] del d1[lk + '2'] for k in list(d1.keys()): if d1[k] is not None: d1[k] = unmarkouterparen(d1[k]) else: del d1[k] if 'len' in d1 and 'array' in d1: if d1['len'] == '': d1['len'] = d1['array'] del d1['array'] elif typespec == 'character': if 'charselector' not in edecl or not edecl['charselector']: edecl['charselector'] = {} if 'len' in edecl['charselector']: del edecl['charselector']['len'] edecl['charselector']['*'] = d1['len'] del d1['len'] else: d1['array'] = d1['array'] + ',' + d1['len'] del d1['len'] errmess('updatevars: "%s %s" is mapped to "%s %s(%s)"\n' % (typespec, e, typespec, ename, d1['array'])) if 'len' in d1: if typespec in ['complex', 'integer', 'logical', 'real']: if 'kindselector' not in edecl or not edecl['kindselector']: edecl['kindselector'] = {} edecl['kindselector']['*'] = d1['len'] del d1['len'] elif typespec == 'character': if 'charselector' not in edecl or not edecl['charselector']: edecl['charselector'] = {} if 'len' in edecl['charselector']: del edecl['charselector']['len'] edecl['charselector']['*'] = d1['len'] del d1['len'] if 'init' in d1: if '=' in edecl and (not edecl['='] == d1['init']): outmess('updatevars: attempt to change the init expression of "%s" ("%s") to "%s". Ignoring.\n' % (ename, edecl['='], d1['init'])) else: edecl['='] = d1['init'] if 'array' in d1: dm = 'dimension(%s)' % d1['array'] if 'attrspec' not in edecl or not edecl['attrspec']: edecl['attrspec'] = [dm] else: edecl['attrspec'].append(dm) for dm1 in edecl['attrspec']: if dm1[:9] == 'dimension' and dm1 != dm: del edecl['attrspec'][-1] errmess('updatevars:%s: attempt to change %r to %r. Ignoring.\n' % (ename, dm1, dm)) break else: outmess('updatevars: could not crack entity declaration "%s". Ignoring.\n' % (ename + m.group('after'))) for k in list(edecl.keys()): if not edecl[k]: del edecl[k] groupcache[groupcounter]['vars'][ename] = edecl if 'varnames' in groupcache[groupcounter]: groupcache[groupcounter]['varnames'].append(ename) last_name = ename return last_name def cracktypespec(typespec, selector): kindselect = None charselect = None typename = None if selector: if typespec in ['complex', 'integer', 'logical', 'real']: kindselect = kindselector.match(selector) if not kindselect: outmess('cracktypespec: no kindselector pattern found for %s\n' % repr(selector)) return kindselect = kindselect.groupdict() kindselect['*'] = kindselect['kind2'] del kindselect['kind2'] for k in list(kindselect.keys()): if not kindselect[k]: del kindselect[k] for (k, i) in list(kindselect.items()): kindselect[k] = rmbadname1(i) elif typespec == 'character': charselect = charselector.match(selector) if not charselect: outmess('cracktypespec: no charselector pattern found for %s\n' % repr(selector)) return charselect = charselect.groupdict() charselect['*'] = charselect['charlen'] del charselect['charlen'] if charselect['lenkind']: lenkind = lenkindpattern.match(markoutercomma(charselect['lenkind'])) lenkind = lenkind.groupdict() for lk in ['len', 'kind']: if lenkind[lk + '2']: lenkind[lk] = lenkind[lk + '2'] charselect[lk] = lenkind[lk] del lenkind[lk + '2'] if lenkind['f2py_len'] is not None: charselect['f2py_len'] = lenkind['f2py_len'] del charselect['lenkind'] for k in list(charselect.keys()): if not charselect[k]: del charselect[k] for (k, i) in list(charselect.items()): charselect[k] = rmbadname1(i) elif typespec == 'type': typename = re.match('\\s*\\(\\s*(?P\\w+)\\s*\\)', selector, re.I) if typename: typename = typename.group('name') else: outmess('cracktypespec: no typename found in %s\n' % repr(typespec + selector)) else: outmess('cracktypespec: no selector used for %s\n' % repr(selector)) return (kindselect, charselect, typename) def setattrspec(decl, attr, force=0): if not decl: decl = {} if not attr: return decl if 'attrspec' not in decl: decl['attrspec'] = [attr] return decl if force: decl['attrspec'].append(attr) if attr in decl['attrspec']: return decl if attr == 'static' and 'automatic' not in decl['attrspec']: decl['attrspec'].append(attr) elif attr == 'automatic' and 'static' not in decl['attrspec']: decl['attrspec'].append(attr) elif attr == 'public': if 'private' not in decl['attrspec']: decl['attrspec'].append(attr) elif attr == 'private': if 'public' not in decl['attrspec']: decl['attrspec'].append(attr) else: decl['attrspec'].append(attr) return decl def setkindselector(decl, sel, force=0): if not decl: decl = {} if not sel: return decl if 'kindselector' not in decl: decl['kindselector'] = sel return decl for k in list(sel.keys()): if force or k not in decl['kindselector']: decl['kindselector'][k] = sel[k] return decl def setcharselector(decl, sel, force=0): if not decl: decl = {} if not sel: return decl if 'charselector' not in decl: decl['charselector'] = sel return decl for k in list(sel.keys()): if force or k not in decl['charselector']: decl['charselector'][k] = sel[k] return decl def getblockname(block, unknown='unknown'): if 'name' in block: return block['name'] return unknown def setmesstext(block): global filepositiontext try: filepositiontext = 'In: %s:%s\n' % (block['from'], block['name']) except Exception: pass def get_usedict(block): usedict = {} if 'parent_block' in block: usedict = get_usedict(block['parent_block']) if 'use' in block: usedict.update(block['use']) return usedict def get_useparameters(block, param_map=None): global f90modulevars if param_map is None: param_map = {} usedict = get_usedict(block) if not usedict: return param_map for (usename, mapping) in list(usedict.items()): usename = usename.lower() if usename not in f90modulevars: outmess('get_useparameters: no module %s info used by %s\n' % (usename, block.get('name'))) continue mvars = f90modulevars[usename] params = get_parameters(mvars) if not params: continue if mapping: errmess('get_useparameters: mapping for %s not impl.\n' % mapping) for (k, v) in list(params.items()): if k in param_map: outmess('get_useparameters: overriding parameter %s with value from module %s\n' % (repr(k), repr(usename))) param_map[k] = v return param_map def postcrack2(block, tab='', param_map=None): global f90modulevars if not f90modulevars: return block if isinstance(block, list): ret = [postcrack2(g, tab=tab + '\t', param_map=param_map) for g in block] return ret setmesstext(block) outmess('%sBlock: %s\n' % (tab, block['name']), 0) if param_map is None: param_map = get_useparameters(block) if param_map is not None and 'vars' in block: vars = block['vars'] for n in list(vars.keys()): var = vars[n] if 'kindselector' in var: kind = var['kindselector'] if 'kind' in kind: val = kind['kind'] if val in param_map: kind['kind'] = param_map[val] new_body = [postcrack2(b, tab=tab + '\t', param_map=param_map) for b in block['body']] block['body'] = new_body return block def postcrack(block, args=None, tab=''): global usermodules, onlyfunctions if isinstance(block, list): gret = [] uret = [] for g in block: setmesstext(g) g = postcrack(g, tab=tab + '\t') if 'name' in g and '__user__' in g['name']: uret.append(g) else: gret.append(g) return uret + gret setmesstext(block) if not isinstance(block, dict) and 'block' not in block: raise Exception('postcrack: Expected block dictionary instead of ' + str(block)) if 'name' in block and (not block['name'] == 'unknown_interface'): outmess('%sBlock: %s\n' % (tab, block['name']), 0) block = analyzeargs(block) block = analyzecommon(block) block['vars'] = analyzevars(block) block['sortvars'] = sortvarnames(block['vars']) if block.get('args'): args = block['args'] block['body'] = analyzebody(block, args, tab=tab) userisdefined = [] if 'use' in block: useblock = block['use'] for k in list(useblock.keys()): if '__user__' in k: userisdefined.append(k) else: useblock = {} name = '' if 'name' in block: name = block['name'] if block.get('externals'): interfaced = [] if 'interfaced' in block: interfaced = block['interfaced'] mvars = copy.copy(block['vars']) if name: mname = name + '__user__routines' else: mname = 'unknown__user__routines' if mname in userisdefined: i = 1 while '%s_%i' % (mname, i) in userisdefined: i = i + 1 mname = '%s_%i' % (mname, i) interface = {'block': 'interface', 'body': [], 'vars': {}, 'name': name + '_user_interface'} for e in block['externals']: if e in interfaced: edef = [] j = -1 for b in block['body']: j = j + 1 if b['block'] == 'interface': i = -1 for bb in b['body']: i = i + 1 if 'name' in bb and bb['name'] == e: edef = copy.copy(bb) del b['body'][i] break if edef: if not b['body']: del block['body'][j] del interfaced[interfaced.index(e)] break interface['body'].append(edef) elif e in mvars and (not isexternal(mvars[e])): interface['vars'][e] = mvars[e] if interface['vars'] or interface['body']: block['interfaced'] = interfaced mblock = {'block': 'python module', 'body': [interface], 'vars': {}, 'name': mname, 'interfaced': block['externals']} useblock[mname] = {} usermodules.append(mblock) if useblock: block['use'] = useblock return block def sortvarnames(vars): indep = [] dep = [] for v in list(vars.keys()): if 'depend' in vars[v] and vars[v]['depend']: dep.append(v) else: indep.append(v) n = len(dep) i = 0 while dep: v = dep[0] fl = 0 for w in dep[1:]: if w in vars[v]['depend']: fl = 1 break if fl: dep = dep[1:] + [v] i = i + 1 if i > n: errmess('sortvarnames: failed to compute dependencies because of cyclic dependencies between ' + ', '.join(dep) + '\n') indep = indep + dep break else: indep.append(v) dep = dep[1:] n = len(dep) i = 0 return indep def analyzecommon(block): if not hascommon(block): return block commonvars = [] for k in list(block['common'].keys()): comvars = [] for e in block['common'][k]: m = re.match('\\A\\s*\\b(?P.*?)\\b\\s*(\\((?P.*?)\\)|)\\s*\\Z', e, re.I) if m: dims = [] if m.group('dims'): dims = [x.strip() for x in markoutercomma(m.group('dims')).split('@,@')] n = rmbadname1(m.group('name').strip()) if n in block['vars']: if 'attrspec' in block['vars'][n]: block['vars'][n]['attrspec'].append('dimension(%s)' % ','.join(dims)) else: block['vars'][n]['attrspec'] = ['dimension(%s)' % ','.join(dims)] elif dims: block['vars'][n] = {'attrspec': ['dimension(%s)' % ','.join(dims)]} else: block['vars'][n] = {} if n not in commonvars: commonvars.append(n) else: n = e errmess('analyzecommon: failed to extract "[()]" from "%s" in common /%s/.\n' % (e, k)) comvars.append(n) block['common'][k] = comvars if 'commonvars' not in block: block['commonvars'] = commonvars else: block['commonvars'] = block['commonvars'] + commonvars return block def analyzebody(block, args, tab=''): global usermodules, skipfuncs, onlyfuncs, f90modulevars setmesstext(block) maybe_private = {key: value for (key, value) in block['vars'].items() if 'attrspec' not in value or 'public' not in value['attrspec']} body = [] for b in block['body']: b['parent_block'] = block if b['block'] in ['function', 'subroutine']: if args is not None and b['name'] not in args: continue else: as_ = b['args'] if b['name'] in maybe_private.keys(): skipfuncs.append(b['name']) if b['name'] in skipfuncs: continue if onlyfuncs and b['name'] not in onlyfuncs: continue b['saved_interface'] = crack2fortrangen(b, '\n' + ' ' * 6, as_interface=True) else: as_ = args b = postcrack(b, as_, tab=tab + '\t') if b['block'] in ['interface', 'abstract interface'] and (not b['body']) and (not b.get('implementedby')): if 'f2pyenhancements' not in b: continue if b['block'].replace(' ', '') == 'pythonmodule': usermodules.append(b) else: if b['block'] == 'module': f90modulevars[b['name']] = b['vars'] body.append(b) return body def buildimplicitrules(block): setmesstext(block) implicitrules = defaultimplicitrules attrrules = {} if 'implicit' in block: if block['implicit'] is None: implicitrules = None if verbose > 1: outmess('buildimplicitrules: no implicit rules for routine %s.\n' % repr(block['name'])) else: for k in list(block['implicit'].keys()): if block['implicit'][k].get('typespec') not in ['static', 'automatic']: implicitrules[k] = block['implicit'][k] else: attrrules[k] = block['implicit'][k]['typespec'] return (implicitrules, attrrules) def myeval(e, g=None, l=None): r = eval(e, g, l) if type(r) in [int, float]: return r raise ValueError('r=%r' % r) getlincoef_re_1 = re.compile('\\A\\b\\w+\\b\\Z', re.I) def getlincoef(e, xset): try: c = int(myeval(e, {}, {})) return (0, c, None) except Exception: pass if getlincoef_re_1.match(e): return (1, 0, e) len_e = len(e) for x in xset: if len(x) > len_e: continue if re.search('\\w\\s*\\([^)]*\\b' + x + '\\b', e): continue re_1 = re.compile('(?P.*?)\\b' + x + '\\b(?P.*)', re.I) m = re_1.match(e) if m: try: m1 = re_1.match(e) while m1: ee = '%s(%s)%s' % (m1.group('before'), 0, m1.group('after')) m1 = re_1.match(ee) b = myeval(ee, {}, {}) m1 = re_1.match(e) while m1: ee = '%s(%s)%s' % (m1.group('before'), 1, m1.group('after')) m1 = re_1.match(ee) a = myeval(ee, {}, {}) - b m1 = re_1.match(e) while m1: ee = '%s(%s)%s' % (m1.group('before'), 0.5, m1.group('after')) m1 = re_1.match(ee) c = myeval(ee, {}, {}) m1 = re_1.match(e) while m1: ee = '%s(%s)%s' % (m1.group('before'), 1.5, m1.group('after')) m1 = re_1.match(ee) c2 = myeval(ee, {}, {}) if a * 0.5 + b == c and a * 1.5 + b == c2: return (a, b, x) except Exception: pass break return (None, None, None) word_pattern = re.compile('\\b[a-z][\\w$]*\\b', re.I) def _get_depend_dict(name, vars, deps): if name in vars: words = vars[name].get('depend', []) if '=' in vars[name] and (not isstring(vars[name])): for word in word_pattern.findall(vars[name]['=']): if word not in words and word in vars and (word != name): words.append(word) for word in words[:]: for w in deps.get(word, []) or _get_depend_dict(word, vars, deps): if w not in words: words.append(w) else: outmess('_get_depend_dict: no dependence info for %s\n' % repr(name)) words = [] deps[name] = words return words def _calc_depend_dict(vars): names = list(vars.keys()) depend_dict = {} for n in names: _get_depend_dict(n, vars, depend_dict) return depend_dict def get_sorted_names(vars): depend_dict = _calc_depend_dict(vars) names = [] for name in list(depend_dict.keys()): if not depend_dict[name]: names.append(name) del depend_dict[name] while depend_dict: for (name, lst) in list(depend_dict.items()): new_lst = [n for n in lst if n in depend_dict] if not new_lst: names.append(name) del depend_dict[name] else: depend_dict[name] = new_lst return [name for name in names if name in vars] def _kind_func(string): if string[0] in '\'"': string = string[1:-1] if real16pattern.match(string): return 8 elif real8pattern.match(string): return 4 return 'kind(' + string + ')' def _selected_int_kind_func(r): m = 10 ** r if m <= 2 ** 8: return 1 if m <= 2 ** 16: return 2 if m <= 2 ** 32: return 4 if m <= 2 ** 63: return 8 if m <= 2 ** 128: return 16 return -1 def _selected_real_kind_func(p, r=0, radix=0): if p < 7: return 4 if p < 16: return 8 machine = platform.machine().lower() if machine.startswith(('aarch64', 'alpha', 'arm64', 'loongarch', 'mips', 'power', 'ppc', 'riscv', 's390x', 'sparc')): if p <= 33: return 16 elif p < 19: return 10 elif p <= 33: return 16 return -1 def get_parameters(vars, global_params={}): params = copy.copy(global_params) g_params = copy.copy(global_params) for (name, func) in [('kind', _kind_func), ('selected_int_kind', _selected_int_kind_func), ('selected_real_kind', _selected_real_kind_func)]: if name not in g_params: g_params[name] = func param_names = [] for n in get_sorted_names(vars): if 'attrspec' in vars[n] and 'parameter' in vars[n]['attrspec']: param_names.append(n) kind_re = re.compile('\\bkind\\s*\\(\\s*(?P.*)\\s*\\)', re.I) selected_int_kind_re = re.compile('\\bselected_int_kind\\s*\\(\\s*(?P.*)\\s*\\)', re.I) selected_kind_re = re.compile('\\bselected_(int|real)_kind\\s*\\(\\s*(?P.*)\\s*\\)', re.I) for n in param_names: if '=' in vars[n]: v = vars[n]['='] if islogical(vars[n]): v = v.lower() for repl in [('.false.', 'False'), ('.true.', 'True')]: v = v.replace(*repl) v = kind_re.sub('kind("\\1")', v) v = selected_int_kind_re.sub('selected_int_kind(\\1)', v) is_replaced = False if 'kindselector' in vars[n]: if 'kind' in vars[n]['kindselector']: orig_v_len = len(v) v = v.replace('_' + vars[n]['kindselector']['kind'], '') is_replaced = len(v) < orig_v_len if not is_replaced: if not selected_kind_re.match(v): v_ = v.split('_') if len(v_) > 1: v = ''.join(v_[:-1]).lower().replace(v_[-1].lower(), '') if isdouble(vars[n]): tt = list(v) for m in real16pattern.finditer(v): tt[m.start():m.end()] = list(v[m.start():m.end()].lower().replace('d', 'e')) v = ''.join(tt) elif iscomplex(vars[n]): outmess(f'get_parameters[TODO]: implement evaluation of complex expression {v}\n') dimspec = ([s.removeprefix('dimension').strip() for s in vars[n]['attrspec'] if s.startswith('dimension')] or [None])[0] if real16pattern.search(v): v = 8 elif real8pattern.search(v): v = 4 try: params[n] = param_eval(v, g_params, params, dimspec=dimspec) except Exception as msg: params[n] = v outmess(f'get_parameters: got "{msg}" on {n!r}\n') if isstring(vars[n]) and isinstance(params[n], int): params[n] = chr(params[n]) nl = n.lower() if nl != n: params[nl] = params[n] else: print(vars[n]) outmess(f'get_parameters:parameter {n!r} does not have value?!\n') return params def _eval_length(length, params): if length in ['(:)', '(*)', '*']: return '(*)' return _eval_scalar(length, params) _is_kind_number = re.compile('\\d+_').match def _eval_scalar(value, params): if _is_kind_number(value): value = value.split('_')[0] try: value = eval(value, {}, params) value = (repr if isinstance(value, str) else str)(value) except (NameError, SyntaxError, TypeError): return value except Exception as msg: errmess('"%s" in evaluating %r (available names: %s)\n' % (msg, value, list(params.keys()))) return value def analyzevars(block): global f90modulevars setmesstext(block) (implicitrules, attrrules) = buildimplicitrules(block) vars = copy.copy(block['vars']) if block['block'] == 'function' and block['name'] not in vars: vars[block['name']] = {} if '' in block['vars']: del vars[''] if 'attrspec' in block['vars']['']: gen = block['vars']['']['attrspec'] for n in set(vars) | set((b['name'] for b in block['body'])): for k in ['public', 'private']: if k in gen: vars[n] = setattrspec(vars.get(n, {}), k) svars = [] args = block['args'] for a in args: try: vars[a] svars.append(a) except KeyError: pass for n in list(vars.keys()): if n not in args: svars.append(n) params = get_parameters(vars, get_useparameters(block)) dep_matches = {} name_match = re.compile('[A-Za-z][\\w$]*').match for v in list(vars.keys()): m = name_match(v) if m: n = v[m.start():m.end()] try: dep_matches[n] except KeyError: dep_matches[n] = re.compile('.*\\b%s\\b' % v, re.I).match for n in svars: if n[0] in list(attrrules.keys()): vars[n] = setattrspec(vars[n], attrrules[n[0]]) if 'typespec' not in vars[n]: if not ('attrspec' in vars[n] and 'external' in vars[n]['attrspec']): if implicitrules: ln0 = n[0].lower() for k in list(implicitrules[ln0].keys()): if k == 'typespec' and implicitrules[ln0][k] == 'undefined': continue if k not in vars[n]: vars[n][k] = implicitrules[ln0][k] elif k == 'attrspec': for l in implicitrules[ln0][k]: vars[n] = setattrspec(vars[n], l) elif n in block['args']: outmess('analyzevars: typespec of variable %s is not defined in routine %s.\n' % (repr(n), block['name'])) if 'charselector' in vars[n]: if 'len' in vars[n]['charselector']: l = vars[n]['charselector']['len'] try: l = str(eval(l, {}, params)) except Exception: pass vars[n]['charselector']['len'] = l if 'kindselector' in vars[n]: if 'kind' in vars[n]['kindselector']: l = vars[n]['kindselector']['kind'] try: l = str(eval(l, {}, params)) except Exception: pass vars[n]['kindselector']['kind'] = l dimension_exprs = {} if 'attrspec' in vars[n]: attr = vars[n]['attrspec'] attr.reverse() vars[n]['attrspec'] = [] (dim, intent, depend, check, note) = (None, None, None, None, None) for a in attr: if a[:9] == 'dimension': dim = a[9:].strip()[1:-1] elif a[:6] == 'intent': intent = a[6:].strip()[1:-1] elif a[:6] == 'depend': depend = a[6:].strip()[1:-1] elif a[:5] == 'check': check = a[5:].strip()[1:-1] elif a[:4] == 'note': note = a[4:].strip()[1:-1] else: vars[n] = setattrspec(vars[n], a) if intent: if 'intent' not in vars[n]: vars[n]['intent'] = [] for c in [x.strip() for x in markoutercomma(intent).split('@,@')]: tmp = c.replace(' ', '') if tmp not in vars[n]['intent']: vars[n]['intent'].append(tmp) intent = None if note: note = note.replace('\\n\\n', '\n\n') note = note.replace('\\n ', '\n') if 'note' not in vars[n]: vars[n]['note'] = [note] else: vars[n]['note'].append(note) note = None if depend is not None: if 'depend' not in vars[n]: vars[n]['depend'] = [] for c in rmbadname([x.strip() for x in markoutercomma(depend).split('@,@')]): if c not in vars[n]['depend']: vars[n]['depend'].append(c) depend = None if check is not None: if 'check' not in vars[n]: vars[n]['check'] = [] for c in [x.strip() for x in markoutercomma(check).split('@,@')]: if c not in vars[n]['check']: vars[n]['check'].append(c) check = None if dim and 'dimension' not in vars[n]: vars[n]['dimension'] = [] for d in rmbadname([x.strip() for x in markoutercomma(dim).split('@,@')]): try: d = param_parse(d, params) except (ValueError, IndexError, KeyError): outmess(f'analyzevars: could not parse dimension for variable {d!r}\n') dim_char = ':' if d == ':' else '*' if d == dim_char: dl = [dim_char] else: dl = markoutercomma(d, ':').split('@:@') if len(dl) == 2 and '*' in dl: dl = ['*'] d = '*' if len(dl) == 1 and dl[0] != dim_char: dl = ['1', dl[0]] if len(dl) == 2: (d1, d2) = map(symbolic.Expr.parse, dl) dsize = d2 - d1 + 1 d = dsize.tostring(language=symbolic.Language.C) solver_and_deps = {} for v in block['vars']: s = symbolic.as_symbol(v) if dsize.contains(s): try: (a, b) = dsize.linear_solve(s) def solve_v(s, a=a, b=b): return (s - b) / a all_symbols = set(a.symbols()) all_symbols.update(b.symbols()) except RuntimeError as msg: solve_v = None all_symbols = set(dsize.symbols()) v_deps = set((s.data for s in all_symbols if s.data in vars)) solver_and_deps[v] = (solve_v, list(v_deps)) dimension_exprs[d] = solver_and_deps vars[n]['dimension'].append(d) if 'check' not in vars[n] and 'args' in block and (n in block['args']): n_deps = vars[n].get('depend', []) n_checks = [] n_is_input = l_or(isintent_in, isintent_inout, isintent_inplace)(vars[n]) if isarray(vars[n]): for (i, d) in enumerate(vars[n]['dimension']): coeffs_and_deps = dimension_exprs.get(d) if coeffs_and_deps is None: pass elif n_is_input: for (v, (solver, deps)) in coeffs_and_deps.items(): def compute_deps(v, deps): for v1 in coeffs_and_deps.get(v, [None, []])[1]: if v1 not in deps: deps.add(v1) compute_deps(v1, deps) all_deps = set() compute_deps(v, all_deps) if v in n_deps or '=' in vars[v] or 'depend' in vars[v]: continue if solver is not None and v not in all_deps: is_required = False init = solver(symbolic.as_symbol(f'shape({n}, {i})')) init = init.tostring(language=symbolic.Language.C) vars[v]['='] = init vars[v]['depend'] = [n] + deps if 'check' not in vars[v]: vars[v]['check'] = [f'shape({n}, {i}) == {d}'] else: is_required = True if 'intent' not in vars[v]: vars[v]['intent'] = [] if 'in' not in vars[v]['intent']: vars[v]['intent'].append('in') n_deps.append(v) n_checks.append(f'shape({n}, {i}) == {d}') v_attr = vars[v].get('attrspec', []) if not ('optional' in v_attr or 'required' in v_attr): v_attr.append('required' if is_required else 'optional') if v_attr: vars[v]['attrspec'] = v_attr if coeffs_and_deps is not None: for (v, (solver, deps)) in coeffs_and_deps.items(): v_deps = vars[v].get('depend', []) for aa in vars[v].get('attrspec', []): if aa.startswith('depend'): aa = ''.join(aa.split()) v_deps.extend(aa[7:-1].split(',')) if v_deps: vars[v]['depend'] = list(set(v_deps)) if n not in v_deps: n_deps.append(v) elif isstring(vars[n]): if 'charselector' in vars[n]: if '*' in vars[n]['charselector']: length = _eval_length(vars[n]['charselector']['*'], params) vars[n]['charselector']['*'] = length elif 'len' in vars[n]['charselector']: length = _eval_length(vars[n]['charselector']['len'], params) del vars[n]['charselector']['len'] vars[n]['charselector']['*'] = length if n_checks: vars[n]['check'] = n_checks if n_deps: vars[n]['depend'] = list(set(n_deps)) if '=' in vars[n]: if 'attrspec' not in vars[n]: vars[n]['attrspec'] = [] if 'optional' not in vars[n]['attrspec'] and 'required' not in vars[n]['attrspec']: vars[n]['attrspec'].append('optional') if 'depend' not in vars[n]: vars[n]['depend'] = [] for (v, m) in list(dep_matches.items()): if m(vars[n]['=']): vars[n]['depend'].append(v) if not vars[n]['depend']: del vars[n]['depend'] if isscalar(vars[n]): vars[n]['='] = _eval_scalar(vars[n]['='], params) for n in list(vars.keys()): if n == block['name']: if 'note' in vars[n]: block['note'] = vars[n]['note'] if block['block'] == 'function': if 'result' in block and block['result'] in vars: vars[n] = appenddecl(vars[n], vars[block['result']]) if 'prefix' in block: pr = block['prefix'] pr1 = pr.replace('pure', '') ispure = not pr == pr1 pr = pr1.replace('recursive', '') isrec = not pr == pr1 m = typespattern[0].match(pr) if m: (typespec, selector, attr, edecl) = cracktypespec0(m.group('this'), m.group('after')) (kindselect, charselect, typename) = cracktypespec(typespec, selector) vars[n]['typespec'] = typespec try: if block['result']: vars[block['result']]['typespec'] = typespec except Exception: pass if kindselect: if 'kind' in kindselect: try: kindselect['kind'] = eval(kindselect['kind'], {}, params) except Exception: pass vars[n]['kindselector'] = kindselect if charselect: vars[n]['charselector'] = charselect if typename: vars[n]['typename'] = typename if ispure: vars[n] = setattrspec(vars[n], 'pure') if isrec: vars[n] = setattrspec(vars[n], 'recursive') else: outmess('analyzevars: prefix (%s) were not used\n' % repr(block['prefix'])) if block['block'] not in ['module', 'pythonmodule', 'python module', 'block data']: if 'commonvars' in block: neededvars = copy.copy(block['args'] + block['commonvars']) else: neededvars = copy.copy(block['args']) for n in list(vars.keys()): if l_or(isintent_callback, isintent_aux)(vars[n]): neededvars.append(n) if 'entry' in block: neededvars.extend(list(block['entry'].keys())) for k in list(block['entry'].keys()): for n in block['entry'][k]: if n not in neededvars: neededvars.append(n) if block['block'] == 'function': if 'result' in block: neededvars.append(block['result']) else: neededvars.append(block['name']) if block['block'] in ['subroutine', 'function']: name = block['name'] if name in vars and 'intent' in vars[name]: block['intent'] = vars[name]['intent'] if block['block'] == 'type': neededvars.extend(list(vars.keys())) for n in list(vars.keys()): if n not in neededvars: del vars[n] return vars analyzeargs_re_1 = re.compile('\\A[a-z]+[\\w$]*\\Z', re.I) def param_eval(v, g_params, params, dimspec=None): if dimspec is None: try: p = eval(v, g_params, params) except Exception as msg: p = v outmess(f'param_eval: got "{msg}" on {v!r}\n') return p if len(dimspec) < 2 or dimspec[::len(dimspec) - 1] != '()': raise ValueError(f"param_eval: dimension {dimspec} can't be parsed") dimrange = dimspec[1:-1].split(',') if len(dimrange) == 1: dimrange = dimrange[0].split(':') if len(dimrange) == 1: bound = param_parse(dimrange[0], params) dimrange = range(1, int(bound) + 1) else: lbound = param_parse(dimrange[0], params) ubound = param_parse(dimrange[1], params) dimrange = range(int(lbound), int(ubound) + 1) else: raise ValueError(f'param_eval: multidimensional array parameters {dimspec} not supported') v = (v[2:-2] if v.startswith('(/') else v).split(',') v_eval = [] for item in v: try: item = eval(item, g_params, params) except Exception as msg: outmess(f'param_eval: got "{msg}" on {item!r}\n') v_eval.append(item) p = dict(zip(dimrange, v_eval)) return p def param_parse(d, params): if '(' in d: dname = d[:d.find('(')] ddims = d[d.find('(') + 1:d.rfind(')')] index = int(param_parse(ddims, params)) return str(params[dname][index]) elif d in params: return str(params[d]) else: for p in params: re_1 = re.compile('(?P.*?)\\b' + p + '\\b(?P.*)', re.I) m = re_1.match(d) while m: d = m.group('before') + str(params[p]) + m.group('after') m = re_1.match(d) return d def expr2name(a, block, args=[]): orig_a = a a_is_expr = not analyzeargs_re_1.match(a) if a_is_expr: (implicitrules, attrrules) = buildimplicitrules(block) at = determineexprtype(a, block['vars'], implicitrules) na = 'e_' for c in a: c = c.lower() if c not in string.ascii_lowercase + string.digits: c = '_' na = na + c if na[-1] == '_': na = na + 'e' else: na = na + '_e' a = na while a in block['vars'] or a in block['args']: a = a + 'r' if a in args: k = 1 while a + str(k) in args: k = k + 1 a = a + str(k) if a_is_expr: block['vars'][a] = at else: if a not in block['vars']: if orig_a in block['vars']: block['vars'][a] = block['vars'][orig_a] else: block['vars'][a] = {} if 'externals' in block and orig_a in block['externals'] + block['interfaced']: block['vars'][a] = setattrspec(block['vars'][a], 'external') return a def analyzeargs(block): setmesstext(block) (implicitrules, _) = buildimplicitrules(block) if 'args' not in block: block['args'] = [] args = [] for a in block['args']: a = expr2name(a, block, args) args.append(a) block['args'] = args if 'entry' in block: for (k, args1) in list(block['entry'].items()): for a in args1: if a not in block['vars']: block['vars'][a] = {} for b in block['body']: if b['name'] in args: if 'externals' not in block: block['externals'] = [] if b['name'] not in block['externals']: block['externals'].append(b['name']) if 'result' in block and block['result'] not in block['vars']: block['vars'][block['result']] = {} return block determineexprtype_re_1 = re.compile('\\A\\(.+?,.+?\\)\\Z', re.I) determineexprtype_re_2 = re.compile('\\A[+-]?\\d+(_(?P\\w+)|)\\Z', re.I) determineexprtype_re_3 = re.compile('\\A[+-]?[\\d.]+[-\\d+de.]*(_(?P\\w+)|)\\Z', re.I) determineexprtype_re_4 = re.compile('\\A\\(.*\\)\\Z', re.I) determineexprtype_re_5 = re.compile('\\A(?P\\w+)\\s*\\(.*?\\)\\s*\\Z', re.I) def _ensure_exprdict(r): if isinstance(r, int): return {'typespec': 'integer'} if isinstance(r, float): return {'typespec': 'real'} if isinstance(r, complex): return {'typespec': 'complex'} if isinstance(r, dict): return r raise AssertionError(repr(r)) def determineexprtype(expr, vars, rules={}): if expr in vars: return _ensure_exprdict(vars[expr]) expr = expr.strip() if determineexprtype_re_1.match(expr): return {'typespec': 'complex'} m = determineexprtype_re_2.match(expr) if m: if 'name' in m.groupdict() and m.group('name'): outmess('determineexprtype: selected kind types not supported (%s)\n' % repr(expr)) return {'typespec': 'integer'} m = determineexprtype_re_3.match(expr) if m: if 'name' in m.groupdict() and m.group('name'): outmess('determineexprtype: selected kind types not supported (%s)\n' % repr(expr)) return {'typespec': 'real'} for op in ['+', '-', '*', '/']: for e in [x.strip() for x in markoutercomma(expr, comma=op).split('@' + op + '@')]: if e in vars: return _ensure_exprdict(vars[e]) t = {} if determineexprtype_re_4.match(expr): t = determineexprtype(expr[1:-1], vars, rules) else: m = determineexprtype_re_5.match(expr) if m: rn = m.group('name') t = determineexprtype(m.group('name'), vars, rules) if t and 'attrspec' in t: del t['attrspec'] if not t: if rn[0] in rules: return _ensure_exprdict(rules[rn[0]]) if expr[0] in '\'"': return {'typespec': 'character', 'charselector': {'*': '*'}} if not t: outmess('determineexprtype: could not determine expressions (%s) type.\n' % repr(expr)) return t def crack2fortrangen(block, tab='\n', as_interface=False): global skipfuncs, onlyfuncs setmesstext(block) ret = '' if isinstance(block, list): for g in block: if g and g['block'] in ['function', 'subroutine']: if g['name'] in skipfuncs: continue if onlyfuncs and g['name'] not in onlyfuncs: continue ret = ret + crack2fortrangen(g, tab, as_interface=as_interface) return ret prefix = '' name = '' args = '' blocktype = block['block'] if blocktype == 'program': return '' argsl = [] if 'name' in block: name = block['name'] if 'args' in block: vars = block['vars'] for a in block['args']: a = expr2name(a, block, argsl) if not isintent_callback(vars[a]): argsl.append(a) if block['block'] == 'function' or argsl: args = '(%s)' % ','.join(argsl) f2pyenhancements = '' if 'f2pyenhancements' in block: for k in list(block['f2pyenhancements'].keys()): f2pyenhancements = '%s%s%s %s' % (f2pyenhancements, tab + tabchar, k, block['f2pyenhancements'][k]) intent_lst = block.get('intent', [])[:] if blocktype == 'function' and 'callback' in intent_lst: intent_lst.remove('callback') if intent_lst: f2pyenhancements = '%s%sintent(%s) %s' % (f2pyenhancements, tab + tabchar, ','.join(intent_lst), name) use = '' if 'use' in block: use = use2fortran(block['use'], tab + tabchar) common = '' if 'common' in block: common = common2fortran(block['common'], tab + tabchar) if name == 'unknown_interface': name = '' result = '' if 'result' in block: result = ' result (%s)' % block['result'] if block['result'] not in argsl: argsl.append(block['result']) body = crack2fortrangen(block['body'], tab + tabchar, as_interface=as_interface) vars = vars2fortran(block, block['vars'], argsl, tab + tabchar, as_interface=as_interface) mess = '' if 'from' in block and (not as_interface): mess = '! in %s' % block['from'] if 'entry' in block: entry_stmts = '' for (k, i) in list(block['entry'].items()): entry_stmts = '%s%sentry %s(%s)' % (entry_stmts, tab + tabchar, k, ','.join(i)) body = body + entry_stmts if blocktype == 'block data' and name == '_BLOCK_DATA_': name = '' ret = '%s%s%s %s%s%s %s%s%s%s%s%s%send %s %s' % (tab, prefix, blocktype, name, args, result, mess, f2pyenhancements, use, vars, common, body, tab, blocktype, name) return ret def common2fortran(common, tab=''): ret = '' for k in list(common.keys()): if k == '_BLNK_': ret = '%s%scommon %s' % (ret, tab, ','.join(common[k])) else: ret = '%s%scommon /%s/ %s' % (ret, tab, k, ','.join(common[k])) return ret def use2fortran(use, tab=''): ret = '' for m in list(use.keys()): ret = '%s%suse %s,' % (ret, tab, m) if use[m] == {}: if ret and ret[-1] == ',': ret = ret[:-1] continue if 'only' in use[m] and use[m]['only']: ret = '%s only:' % ret if 'map' in use[m] and use[m]['map']: c = ' ' for k in list(use[m]['map'].keys()): if k == use[m]['map'][k]: ret = '%s%s%s' % (ret, c, k) c = ',' else: ret = '%s%s%s=>%s' % (ret, c, k, use[m]['map'][k]) c = ',' if ret and ret[-1] == ',': ret = ret[:-1] return ret def true_intent_list(var): lst = var['intent'] ret = [] for intent in lst: try: f = globals()['isintent_%s' % intent] except KeyError: pass else: if f(var): ret.append(intent) return ret def vars2fortran(block, vars, args, tab='', as_interface=False): setmesstext(block) ret = '' nout = [] for a in args: if a in block['vars']: nout.append(a) if 'commonvars' in block: for a in block['commonvars']: if a in vars: if a not in nout: nout.append(a) else: errmess('vars2fortran: Confused?!: "%s" is not defined in vars.\n' % a) if 'varnames' in block: nout.extend(block['varnames']) if not as_interface: for a in list(vars.keys()): if a not in nout: nout.append(a) for a in nout: if 'depend' in vars[a]: for d in vars[a]['depend']: if d in vars and 'depend' in vars[d] and (a in vars[d]['depend']): errmess('vars2fortran: Warning: cross-dependence between variables "%s" and "%s"\n' % (a, d)) if 'externals' in block and a in block['externals']: if isintent_callback(vars[a]): ret = '%s%sintent(callback) %s' % (ret, tab, a) ret = '%s%sexternal %s' % (ret, tab, a) if isoptional(vars[a]): ret = '%s%soptional %s' % (ret, tab, a) if a in vars and 'typespec' not in vars[a]: continue cont = 1 for b in block['body']: if a == b['name'] and b['block'] == 'function': cont = 0 break if cont: continue if a not in vars: show(vars) outmess('vars2fortran: No definition for argument "%s".\n' % a) continue if a == block['name']: if block['block'] != 'function' or block.get('result'): continue if 'typespec' not in vars[a]: if 'attrspec' in vars[a] and 'external' in vars[a]['attrspec']: if a in args: ret = '%s%sexternal %s' % (ret, tab, a) continue show(vars[a]) outmess('vars2fortran: No typespec for argument "%s".\n' % a) continue vardef = vars[a]['typespec'] if vardef == 'type' and 'typename' in vars[a]: vardef = '%s(%s)' % (vardef, vars[a]['typename']) selector = {} if 'kindselector' in vars[a]: selector = vars[a]['kindselector'] elif 'charselector' in vars[a]: selector = vars[a]['charselector'] if '*' in selector: if selector['*'] in ['*', ':']: vardef = '%s*(%s)' % (vardef, selector['*']) else: vardef = '%s*%s' % (vardef, selector['*']) elif 'len' in selector: vardef = '%s(len=%s' % (vardef, selector['len']) if 'kind' in selector: vardef = '%s,kind=%s)' % (vardef, selector['kind']) else: vardef = '%s)' % vardef elif 'kind' in selector: vardef = '%s(kind=%s)' % (vardef, selector['kind']) c = ' ' if 'attrspec' in vars[a]: attr = [l for l in vars[a]['attrspec'] if l not in ['external']] if as_interface and 'intent(in)' in attr and ('intent(out)' in attr): attr.remove('intent(out)') if attr: vardef = '%s, %s' % (vardef, ','.join(attr)) c = ',' if 'dimension' in vars[a]: vardef = '%s%sdimension(%s)' % (vardef, c, ','.join(vars[a]['dimension'])) c = ',' if 'intent' in vars[a]: lst = true_intent_list(vars[a]) if lst: vardef = '%s%sintent(%s)' % (vardef, c, ','.join(lst)) c = ',' if 'check' in vars[a]: vardef = '%s%scheck(%s)' % (vardef, c, ','.join(vars[a]['check'])) c = ',' if 'depend' in vars[a]: vardef = '%s%sdepend(%s)' % (vardef, c, ','.join(vars[a]['depend'])) c = ',' if '=' in vars[a]: v = vars[a]['='] if vars[a]['typespec'] in ['complex', 'double complex']: try: v = eval(v) v = '(%s,%s)' % (v.real, v.imag) except Exception: pass vardef = '%s :: %s=%s' % (vardef, a, v) else: vardef = '%s :: %s' % (vardef, a) ret = '%s%s%s' % (ret, tab, vardef) return ret post_processing_hooks = [] def crackfortran(files): global usermodules, post_processing_hooks outmess('Reading fortran codes...\n', 0) readfortrancode(files, crackline) outmess('Post-processing...\n', 0) usermodules = [] postlist = postcrack(grouplist[0]) outmess('Applying post-processing hooks...\n', 0) for hook in post_processing_hooks: outmess(f' {hook.__name__}\n', 0) postlist = traverse(postlist, hook) outmess('Post-processing (stage 2)...\n', 0) postlist = postcrack2(postlist) return usermodules + postlist def crack2fortran(block): global f2py_version pyf = crack2fortrangen(block) + '\n' header = '! -*- f90 -*-\n! Note: the context of this file is case sensitive.\n' footer = '\n! This file was auto-generated with f2py (version:%s).\n! See:\n! https://web.archive.org/web/20140822061353/http://cens.ioc.ee/projects/f2py2e\n' % f2py_version return header + pyf + footer def _is_visit_pair(obj): return isinstance(obj, tuple) and len(obj) == 2 and isinstance(obj[0], (int, str)) def traverse(obj, visit, parents=[], result=None, *args, **kwargs): if _is_visit_pair(obj): if obj[0] == 'parent_block': return obj new_result = visit(obj, parents, result, *args, **kwargs) if new_result is not None: assert _is_visit_pair(new_result) return new_result parent = obj (result_key, obj) = obj else: parent = (None, obj) result_key = None if isinstance(obj, list): new_result = [] for (index, value) in enumerate(obj): (new_index, new_item) = traverse((index, value), visit, *args, parents=parents + [parent], result=result, **kwargs) if new_index is not None: new_result.append(new_item) elif isinstance(obj, dict): new_result = dict() for (key, value) in obj.items(): (new_key, new_value) = traverse((key, value), visit, *args, parents=parents + [parent], result=result, **kwargs) if new_key is not None: new_result[new_key] = new_value else: new_result = obj if result_key is None: return new_result return (result_key, new_result) def character_backward_compatibility_hook(item, parents, result, *args, **kwargs): (parent_key, parent_value) = parents[-1] (key, value) = item def fix_usage(varname, value): value = re.sub('[*]\\s*\\b' + varname + '\\b', varname, value) value = re.sub('\\b' + varname + '\\b\\s*[\\[]\\s*0\\s*[\\]]', varname, value) return value if parent_key in ['dimension', 'check']: assert parents[-3][0] == 'vars' vars_dict = parents[-3][1] elif key == '=': assert parents[-2][0] == 'vars' vars_dict = parents[-2][1] else: vars_dict = None new_value = None if vars_dict is not None: new_value = value for (varname, vd) in vars_dict.items(): if ischaracter(vd): new_value = fix_usage(varname, new_value) elif key == 'callstatement': vars_dict = parents[-2][1]['vars'] new_value = value for (varname, vd) in vars_dict.items(): if ischaracter(vd): new_value = re.sub('(? `{new_value}`\n', 1) return (key, new_value) post_processing_hooks.append(character_backward_compatibility_hook) if __name__ == '__main__': files = [] funcs = [] f = 1 f2 = 0 f3 = 0 showblocklist = 0 for l in sys.argv[1:]: if l == '': pass elif l[0] == ':': f = 0 elif l == '-quiet': quiet = 1 verbose = 0 elif l == '-verbose': verbose = 2 quiet = 0 elif l == '-fix': if strictf77: outmess('Use option -f90 before -fix if Fortran 90 code is in fix form.\n', 0) skipemptyends = 1 sourcecodeform = 'fix' elif l == '-skipemptyends': skipemptyends = 1 elif l == '--ignore-contains': ignorecontains = 1 elif l == '-f77': strictf77 = 1 sourcecodeform = 'fix' elif l == '-f90': strictf77 = 0 sourcecodeform = 'free' skipemptyends = 1 elif l == '-h': f2 = 1 elif l == '-show': showblocklist = 1 elif l == '-m': f3 = 1 elif l[0] == '-': errmess('Unknown option %s\n' % repr(l)) elif f2: f2 = 0 pyffilename = l elif f3: f3 = 0 f77modulename = l elif f: try: open(l).close() files.append(l) except OSError as detail: errmess(f'OSError: {detail!s}\n') else: funcs.append(l) if not strictf77 and f77modulename and (not skipemptyends): outmess(' Warning: You have specified module name for non Fortran 77 code that\n should not need one (expect if you are scanning F90 code for non\n module blocks but then you should use flag -skipemptyends and also\n be sure that the files do not contain programs without program\n statement).\n', 0) postlist = crackfortran(files) if pyffilename: outmess('Writing fortran code to file %s\n' % repr(pyffilename), 0) pyf = crack2fortran(postlist) with open(pyffilename, 'w') as f: f.write(pyf) if showblocklist: show(postlist) # File: numpy-main/numpy/f2py/diagnose.py import os import sys import tempfile def run_command(cmd): print('Running %r:' % cmd) os.system(cmd) print('------') def run(): _path = os.getcwd() os.chdir(tempfile.gettempdir()) print('------') print('os.name=%r' % os.name) print('------') print('sys.platform=%r' % sys.platform) print('------') print('sys.version:') print(sys.version) print('------') print('sys.prefix:') print(sys.prefix) print('------') print('sys.path=%r' % ':'.join(sys.path)) print('------') try: import numpy has_newnumpy = 1 except ImportError as e: print('Failed to import new numpy:', e) has_newnumpy = 0 try: from numpy.f2py import f2py2e has_f2py2e = 1 except ImportError as e: print('Failed to import f2py2e:', e) has_f2py2e = 0 try: import numpy.distutils has_numpy_distutils = 2 except ImportError: try: import numpy_distutils has_numpy_distutils = 1 except ImportError as e: print('Failed to import numpy_distutils:', e) has_numpy_distutils = 0 if has_newnumpy: try: print('Found new numpy version %r in %s' % (numpy.__version__, numpy.__file__)) except Exception as msg: print('error:', msg) print('------') if has_f2py2e: try: print('Found f2py2e version %r in %s' % (f2py2e.__version__.version, f2py2e.__file__)) except Exception as msg: print('error:', msg) print('------') if has_numpy_distutils: try: if has_numpy_distutils == 2: print('Found numpy.distutils version %r in %r' % (numpy.distutils.__version__, numpy.distutils.__file__)) else: print('Found numpy_distutils version %r in %r' % (numpy_distutils.numpy_distutils_version.numpy_distutils_version, numpy_distutils.__file__)) print('------') except Exception as msg: print('error:', msg) print('------') try: if has_numpy_distutils == 1: print('Importing numpy_distutils.command.build_flib ...', end=' ') import numpy_distutils.command.build_flib as build_flib print('ok') print('------') try: print('Checking availability of supported Fortran compilers:') for compiler_class in build_flib.all_compilers: compiler_class(verbose=1).is_available() print('------') except Exception as msg: print('error:', msg) print('------') except Exception as msg: print('error:', msg, '(ignore it, build_flib is obsolete for numpy.distutils 0.2.2 and up)') print('------') try: if has_numpy_distutils == 2: print('Importing numpy.distutils.fcompiler ...', end=' ') import numpy.distutils.fcompiler as fcompiler else: print('Importing numpy_distutils.fcompiler ...', end=' ') import numpy_distutils.fcompiler as fcompiler print('ok') print('------') try: print('Checking availability of supported Fortran compilers:') fcompiler.show_fcompilers() print('------') except Exception as msg: print('error:', msg) print('------') except Exception as msg: print('error:', msg) print('------') try: if has_numpy_distutils == 2: print('Importing numpy.distutils.cpuinfo ...', end=' ') from numpy.distutils.cpuinfo import cpuinfo print('ok') print('------') else: try: print('Importing numpy_distutils.command.cpuinfo ...', end=' ') from numpy_distutils.command.cpuinfo import cpuinfo print('ok') print('------') except Exception as msg: print('error:', msg, '(ignore it)') print('Importing numpy_distutils.cpuinfo ...', end=' ') from numpy_distutils.cpuinfo import cpuinfo print('ok') print('------') cpu = cpuinfo() print('CPU information:', end=' ') for name in dir(cpuinfo): if name[0] == '_' and name[1] != '_' and getattr(cpu, name[1:])(): print(name[1:], end=' ') print('------') except Exception as msg: print('error:', msg) print('------') os.chdir(_path) if __name__ == '__main__': run() # File: numpy-main/numpy/f2py/f2py2e.py """""" import sys import os import pprint import re import argparse from . import crackfortran from . import rules from . import cb_rules from . import auxfuncs from . import cfuncs from . import f90mod_rules from . import __version__ from . import capi_maps from .cfuncs import errmess from numpy.f2py._backends import f2py_build_generator f2py_version = __version__.version numpy_version = __version__.version show = pprint.pprint outmess = auxfuncs.outmess MESON_ONLY_VER = sys.version_info >= (3, 12) __usage__ = f"""Usage:\n\n1) To construct extension module sources:\n\n f2py [] [[[only:]||[skip:]] \\\n ] \\\n [: ...]\n\n2) To compile fortran files and build extension modules:\n\n f2py -c [, , ] \n\n3) To generate signature files:\n\n f2py -h ...< same options as in (1) >\n\nDescription: This program generates a Python C/API file (module.c)\n that contains wrappers for given fortran functions so that they\n can be called from Python. With the -c option the corresponding\n extension modules are built.\n\nOptions:\n\n -h Write signatures of the fortran routines to file \n and exit. You can then edit and use it instead\n of . If ==stdout then the\n signatures are printed to stdout.\n Names of fortran routines for which Python C/API\n functions will be generated. Default is all that are found\n in .\n Paths to fortran/signature files that will be scanned for\n in order to determine their signatures.\n skip: Ignore fortran functions that follow until `:'.\n only: Use only fortran functions that follow until `:'.\n : Get back to mode.\n\n -m Name of the module; f2py generates a Python/C API\n file module.c or extension module .\n Default is 'untitled'.\n\n '-include

' Writes additional headers in the C wrapper, can be passed\n multiple times, generates #include
each time.\n\n --[no-]lower Do [not] lower the cases in . By default,\n --lower is assumed with -h key, and --no-lower without -h key.\n\n --build-dir All f2py generated files are created in .\n Default is tempfile.mkdtemp().\n\n --overwrite-signature Overwrite existing signature file.\n\n --[no-]latex-doc Create (or not) module.tex.\n Default is --no-latex-doc.\n --short-latex Create 'incomplete' LaTeX document (without commands\n \\documentclass, \\tableofcontents, and \\begin{{document}},\n \\end{{document}}).\n\n --[no-]rest-doc Create (or not) module.rst.\n Default is --no-rest-doc.\n\n --debug-capi Create C/API code that reports the state of the wrappers\n during runtime. Useful for debugging.\n\n --[no-]wrap-functions Create Fortran subroutine wrappers to Fortran 77\n functions. --wrap-functions is default because it ensures\n maximum portability/compiler independence.\n\n --[no-]freethreading-compatible Create a module that declares it does or\n doesn't require the GIL. The default is\n --freethreading-compatible for backward\n compatibility. Inspect the Fortran code you are wrapping for\n thread safety issues before passing\n --no-freethreading-compatible, as f2py does not analyze\n fortran code for thread safety issues.\n\n --include-paths ::... Search include files from the given\n directories.\n\n --help-link [..] List system resources found by system_info.py. See also\n --link- switch below. [..] is optional list\n of resources names. E.g. try 'f2py --help-link lapack_opt'.\n\n --f2cmap Load Fortran-to-Python KIND specification from the given\n file. Default: .f2py_f2cmap in current directory.\n\n --quiet Run quietly.\n --verbose Run with extra verbosity.\n --skip-empty-wrappers Only generate wrapper files when needed.\n -v Print f2py version ID and exit.\n\n\nbuild backend options (only effective with -c)\n[NO_MESON] is used to indicate an option not meant to be used\nwith the meson backend or above Python 3.12:\n\n --fcompiler= Specify Fortran compiler type by vendor [NO_MESON]\n --compiler= Specify distutils C compiler type [NO_MESON]\n\n --help-fcompiler List available Fortran compilers and exit [NO_MESON]\n --f77exec= Specify the path to F77 compiler [NO_MESON]\n --f90exec= Specify the path to F90 compiler [NO_MESON]\n --f77flags= Specify F77 compiler flags\n --f90flags= Specify F90 compiler flags\n --opt= Specify optimization flags [NO_MESON]\n --arch= Specify architecture specific optimization flags [NO_MESON]\n --noopt Compile without optimization [NO_MESON]\n --noarch Compile without arch-dependent optimization [NO_MESON]\n --debug Compile with debugging information\n\n --dep \n Specify a meson dependency for the module. This may\n be passed multiple times for multiple dependencies.\n Dependencies are stored in a list for further processing.\n\n Example: --dep lapack --dep scalapack\n This will identify "lapack" and "scalapack" as dependencies\n and remove them from argv, leaving a dependencies list\n containing ["lapack", "scalapack"].\n\n --backend \n Specify the build backend for the compilation process.\n The supported backends are 'meson' and 'distutils'.\n If not specified, defaults to 'distutils'. On\n Python 3.12 or higher, the default is 'meson'.\n\nExtra options (only effective with -c):\n\n --link- Link extension module with as defined\n by numpy.distutils/system_info.py. E.g. to link\n with optimized LAPACK libraries (vecLib on MacOSX,\n ATLAS elsewhere), use --link-lapack_opt.\n See also --help-link switch. [NO_MESON]\n\n -L/path/to/lib/ -l\n -D -U\n -I/path/to/include/\n .o .so .a\n\n Using the following macros may be required with non-gcc Fortran\n compilers:\n -DPREPEND_FORTRAN -DNO_APPEND_FORTRAN -DUPPERCASE_FORTRAN\n\n When using -DF2PY_REPORT_ATEXIT, a performance report of F2PY\n interface is printed out at exit (platforms: Linux).\n\n When using -DF2PY_REPORT_ON_ARRAY_COPY=, a message is\n sent to stderr whenever F2PY interface makes a copy of an\n array. Integer sets the threshold for array sizes when\n a message should be shown.\n\nVersion: {f2py_version}\nnumpy Version: {numpy_version}\nLicense: NumPy license (see LICENSE.txt in the NumPy source code)\nCopyright 1999 -- 2011 Pearu Peterson all rights reserved.\nCopyright 2011 -- present NumPy Developers.\nhttps://numpy.org/doc/stable/f2py/index.html\n""" def scaninputline(inputline): (files, skipfuncs, onlyfuncs, debug) = ([], [], [], []) (f, f2, f3, f5, f6, f8, f9, f10) = (1, 0, 0, 0, 0, 0, 0, 0) verbose = 1 emptygen = True dolc = -1 dolatexdoc = 0 dorestdoc = 0 wrapfuncs = 1 buildpath = '.' (include_paths, freethreading_compatible, inputline) = get_newer_options(inputline) (signsfile, modulename) = (None, None) options = {'buildpath': buildpath, 'coutput': None, 'f2py_wrapper_output': None} for l in inputline: if l == '': pass elif l == 'only:': f = 0 elif l == 'skip:': f = -1 elif l == ':': f = 1 elif l[:8] == '--debug-': debug.append(l[8:]) elif l == '--lower': dolc = 1 elif l == '--build-dir': f6 = 1 elif l == '--no-lower': dolc = 0 elif l == '--quiet': verbose = 0 elif l == '--verbose': verbose += 1 elif l == '--latex-doc': dolatexdoc = 1 elif l == '--no-latex-doc': dolatexdoc = 0 elif l == '--rest-doc': dorestdoc = 1 elif l == '--no-rest-doc': dorestdoc = 0 elif l == '--wrap-functions': wrapfuncs = 1 elif l == '--no-wrap-functions': wrapfuncs = 0 elif l == '--short-latex': options['shortlatex'] = 1 elif l == '--coutput': f8 = 1 elif l == '--f2py-wrapper-output': f9 = 1 elif l == '--f2cmap': f10 = 1 elif l == '--overwrite-signature': options['h-overwrite'] = 1 elif l == '-h': f2 = 1 elif l == '-m': f3 = 1 elif l[:2] == '-v': print(f2py_version) sys.exit() elif l == '--show-compilers': f5 = 1 elif l[:8] == '-include': cfuncs.outneeds['userincludes'].append(l[9:-1]) cfuncs.userincludes[l[9:-1]] = '#include ' + l[8:] elif l == '--skip-empty-wrappers': emptygen = False elif l[0] == '-': errmess('Unknown option %s\n' % repr(l)) sys.exit() elif f2: f2 = 0 signsfile = l elif f3: f3 = 0 modulename = l elif f6: f6 = 0 buildpath = l elif f8: f8 = 0 options['coutput'] = l elif f9: f9 = 0 options['f2py_wrapper_output'] = l elif f10: f10 = 0 options['f2cmap_file'] = l elif f == 1: try: with open(l): pass files.append(l) except OSError as detail: errmess(f'OSError: {detail!s}. Skipping file "{l!s}".\n') elif f == -1: skipfuncs.append(l) elif f == 0: onlyfuncs.append(l) if not f5 and (not files) and (not modulename): print(__usage__) sys.exit() if not os.path.isdir(buildpath): if not verbose: outmess('Creating build directory %s\n' % buildpath) os.mkdir(buildpath) if signsfile: signsfile = os.path.join(buildpath, signsfile) if signsfile and os.path.isfile(signsfile) and ('h-overwrite' not in options): errmess('Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n' % signsfile) sys.exit() options['emptygen'] = emptygen options['debug'] = debug options['verbose'] = verbose if dolc == -1 and (not signsfile): options['do-lower'] = 0 else: options['do-lower'] = dolc if modulename: options['module'] = modulename if signsfile: options['signsfile'] = signsfile if onlyfuncs: options['onlyfuncs'] = onlyfuncs if skipfuncs: options['skipfuncs'] = skipfuncs options['dolatexdoc'] = dolatexdoc options['dorestdoc'] = dorestdoc options['wrapfuncs'] = wrapfuncs options['buildpath'] = buildpath options['include_paths'] = include_paths options['requires_gil'] = not freethreading_compatible options.setdefault('f2cmap_file', None) return (files, options) def callcrackfortran(files, options): rules.options = options crackfortran.debug = options['debug'] crackfortran.verbose = options['verbose'] if 'module' in options: crackfortran.f77modulename = options['module'] if 'skipfuncs' in options: crackfortran.skipfuncs = options['skipfuncs'] if 'onlyfuncs' in options: crackfortran.onlyfuncs = options['onlyfuncs'] crackfortran.include_paths[:] = options['include_paths'] crackfortran.dolowercase = options['do-lower'] postlist = crackfortran.crackfortran(files) if 'signsfile' in options: outmess('Saving signatures to file "%s"\n' % options['signsfile']) pyf = crackfortran.crack2fortran(postlist) if options['signsfile'][-6:] == 'stdout': sys.stdout.write(pyf) else: with open(options['signsfile'], 'w') as f: f.write(pyf) if options['coutput'] is None: for mod in postlist: mod['coutput'] = '%smodule.c' % mod['name'] else: for mod in postlist: mod['coutput'] = options['coutput'] if options['f2py_wrapper_output'] is None: for mod in postlist: mod['f2py_wrapper_output'] = '%s-f2pywrappers.f' % mod['name'] else: for mod in postlist: mod['f2py_wrapper_output'] = options['f2py_wrapper_output'] for mod in postlist: if options['requires_gil']: mod['gil_used'] = 'Py_MOD_GIL_USED' else: mod['gil_used'] = 'Py_MOD_GIL_NOT_USED' return postlist def buildmodules(lst): cfuncs.buildcfuncs() outmess('Building modules...\n') (modules, mnames, isusedby) = ([], [], {}) for item in lst: if '__user__' in item['name']: cb_rules.buildcallbacks(item) else: if 'use' in item: for u in item['use'].keys(): if u not in isusedby: isusedby[u] = [] isusedby[u].append(item['name']) modules.append(item) mnames.append(item['name']) ret = {} for (module, name) in zip(modules, mnames): if name in isusedby: outmess('\tSkipping module "%s" which is used by %s.\n' % (name, ','.join(('"%s"' % s for s in isusedby[name])))) else: um = [] if 'use' in module: for u in module['use'].keys(): if u in isusedby and u in mnames: um.append(modules[mnames.index(u)]) else: outmess(f'\tModule "{name}" uses nonexisting "{u}" which will be ignored.\n') ret[name] = {} dict_append(ret[name], rules.buildmodule(module, um)) return ret def dict_append(d_out, d_in): for (k, v) in d_in.items(): if k not in d_out: d_out[k] = [] if isinstance(v, list): d_out[k] = d_out[k] + v else: d_out[k].append(v) def run_main(comline_list): crackfortran.reset_global_f2py_vars() f2pydir = os.path.dirname(os.path.abspath(cfuncs.__file__)) fobjhsrc = os.path.join(f2pydir, 'src', 'fortranobject.h') fobjcsrc = os.path.join(f2pydir, 'src', 'fortranobject.c') parser = make_f2py_compile_parser() (args, comline_list) = parser.parse_known_args(comline_list) (pyf_files, _) = filter_files('', '[.]pyf([.]src|)', comline_list) if args.module_name: if '-h' in comline_list: modname = args.module_name else: modname = validate_modulename(pyf_files, args.module_name) comline_list += ['-m', modname] (files, options) = scaninputline(comline_list) auxfuncs.options = options capi_maps.load_f2cmap_file(options['f2cmap_file']) postlist = callcrackfortran(files, options) isusedby = {} for plist in postlist: if 'use' in plist: for u in plist['use'].keys(): if u not in isusedby: isusedby[u] = [] isusedby[u].append(plist['name']) for plist in postlist: if plist['block'] == 'python module' and '__user__' in plist['name']: if plist['name'] in isusedby: outmess(f'''Skipping Makefile build for module "{plist['name']}" which is used by {{}}\n'''.format(','.join((f'"{s}"' for s in isusedby[plist['name']])))) if 'signsfile' in options: if options['verbose'] > 1: outmess('Stopping. Edit the signature file and then run f2py on the signature file: ') outmess('%s %s\n' % (os.path.basename(sys.argv[0]), options['signsfile'])) return for plist in postlist: if plist['block'] != 'python module': if 'python module' not in options: errmess('Tip: If your original code is Fortran source then you must use -m option.\n') raise TypeError('All blocks must be python module blocks but got %s' % repr(plist['block'])) auxfuncs.debugoptions = options['debug'] f90mod_rules.options = options auxfuncs.wrapfuncs = options['wrapfuncs'] ret = buildmodules(postlist) for mn in ret.keys(): dict_append(ret[mn], {'csrc': fobjcsrc, 'h': fobjhsrc}) return ret def filter_files(prefix, suffix, files, remove_prefix=None): (filtered, rest) = ([], []) match = re.compile(prefix + '.*' + suffix + '\\Z').match if remove_prefix: ind = len(prefix) else: ind = 0 for file in [x.strip() for x in files]: if match(file): filtered.append(file[ind:]) else: rest.append(file) return (filtered, rest) def get_prefix(module): p = os.path.dirname(os.path.dirname(module.__file__)) return p class CombineIncludePaths(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): include_paths_set = set(getattr(namespace, 'include_paths', []) or []) if option_string == '--include_paths': outmess('Use --include-paths or -I instead of --include_paths which will be removed') if option_string == '--include-paths' or option_string == '--include_paths': include_paths_set.update(values.split(':')) else: include_paths_set.add(values) namespace.include_paths = list(include_paths_set) def f2py_parser(): parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-I', dest='include_paths', action=CombineIncludePaths) parser.add_argument('--include-paths', dest='include_paths', action=CombineIncludePaths) parser.add_argument('--include_paths', dest='include_paths', action=CombineIncludePaths) parser.add_argument('--freethreading-compatible', dest='ftcompat', action=argparse.BooleanOptionalAction) return parser def get_newer_options(iline): iline = ' '.join(iline).split() parser = f2py_parser() (args, remain) = parser.parse_known_args(iline) ipaths = args.include_paths if args.include_paths is None: ipaths = [] return (ipaths, args.ftcompat, remain) def make_f2py_compile_parser(): parser = argparse.ArgumentParser(add_help=False) parser.add_argument('--dep', action='append', dest='dependencies') parser.add_argument('--backend', choices=['meson', 'distutils'], default='distutils') parser.add_argument('-m', dest='module_name') return parser def preparse_sysargv(): parser = make_f2py_compile_parser() (args, remaining_argv) = parser.parse_known_args() sys.argv = [sys.argv[0]] + remaining_argv backend_key = args.backend if MESON_ONLY_VER and backend_key == 'distutils': outmess('Cannot use distutils backend with Python>=3.12, using meson backend instead.\n') backend_key = 'meson' return {'dependencies': args.dependencies or [], 'backend': backend_key, 'modulename': args.module_name} def run_compile(): import tempfile argy = preparse_sysargv() modulename = argy['modulename'] if modulename is None: modulename = 'untitled' dependencies = argy['dependencies'] backend_key = argy['backend'] build_backend = f2py_build_generator(backend_key) i = sys.argv.index('-c') del sys.argv[i] remove_build_dir = 0 try: i = sys.argv.index('--build-dir') except ValueError: i = None if i is not None: build_dir = sys.argv[i + 1] del sys.argv[i + 1] del sys.argv[i] else: remove_build_dir = 1 build_dir = tempfile.mkdtemp() _reg1 = re.compile('--link-') sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags] if sysinfo_flags: sysinfo_flags = [f[7:] for f in sysinfo_flags] _reg2 = re.compile('--((no-|)(wrap-functions|lower|freethreading-compatible)|debug-capi|quiet|skip-empty-wrappers)|-include') f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in f2py_flags] f2py_flags2 = [] fl = 0 for a in sys.argv[1:]: if a in ['only:', 'skip:']: fl = 1 elif a == ':': fl = 0 if fl or a == ':': f2py_flags2.append(a) if f2py_flags2 and f2py_flags2[-1] != ':': f2py_flags2.append(':') f2py_flags.extend(f2py_flags2) sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2] _reg3 = re.compile('--((f(90)?compiler(-exec|)|compiler)=|help-compiler)') flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in flib_flags] reg_f77_f90_flags = re.compile('--f(77|90)flags=') reg_distutils_flags = re.compile('--((f(77|90)exec|opt|arch)=|(debug|noopt|noarch|help-fcompiler))') fc_flags = [_m for _m in sys.argv[1:] if reg_f77_f90_flags.match(_m)] distutils_flags = [_m for _m in sys.argv[1:] if reg_distutils_flags.match(_m)] if not (MESON_ONLY_VER or backend_key == 'meson'): fc_flags.extend(distutils_flags) sys.argv = [_m for _m in sys.argv if _m not in fc_flags + distutils_flags] del_list = [] for s in flib_flags: v = '--fcompiler=' if s[:len(v)] == v: if MESON_ONLY_VER or backend_key == 'meson': outmess('--fcompiler cannot be used with meson,set compiler with the FC environment variable\n') else: from numpy.distutils import fcompiler fcompiler.load_all_fcompiler_classes() allowed_keys = list(fcompiler.fcompiler_class.keys()) nv = ov = s[len(v):].lower() if ov not in allowed_keys: vmap = {} try: nv = vmap[ov] except KeyError: if ov not in vmap.values(): print('Unknown vendor: "%s"' % s[len(v):]) nv = ov i = flib_flags.index(s) flib_flags[i] = '--fcompiler=' + nv continue for s in del_list: i = flib_flags.index(s) del flib_flags[i] assert len(flib_flags) <= 2, repr(flib_flags) _reg5 = re.compile('--(verbose)') setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in setup_flags] if '--quiet' in f2py_flags: setup_flags.append('--quiet') sources = sys.argv[1:] f2cmapopt = '--f2cmap' if f2cmapopt in sys.argv: i = sys.argv.index(f2cmapopt) f2py_flags.extend(sys.argv[i:i + 2]) del sys.argv[i + 1], sys.argv[i] sources = sys.argv[1:] (pyf_files, _sources) = filter_files('', '[.]pyf([.]src|)', sources) sources = pyf_files + _sources modulename = validate_modulename(pyf_files, modulename) (extra_objects, sources) = filter_files('', '[.](o|a|so|dylib)', sources) (library_dirs, sources) = filter_files('-L', '', sources, remove_prefix=1) (libraries, sources) = filter_files('-l', '', sources, remove_prefix=1) (undef_macros, sources) = filter_files('-U', '', sources, remove_prefix=1) (define_macros, sources) = filter_files('-D', '', sources, remove_prefix=1) for i in range(len(define_macros)): name_value = define_macros[i].split('=', 1) if len(name_value) == 1: name_value.append(None) if len(name_value) == 2: define_macros[i] = tuple(name_value) else: print('Invalid use of -D:', name_value) if backend_key == 'meson': if not pyf_files: outmess('Using meson backend\nWill pass --lower to f2py\nSee https://numpy.org/doc/stable/f2py/buildtools/meson.html\n') f2py_flags.append('--lower') run_main(f" {' '.join(f2py_flags)} -m {modulename} {' '.join(sources)}".split()) else: run_main(f" {' '.join(f2py_flags)} {' '.join(pyf_files)}".split()) (include_dirs, _, sources) = get_newer_options(sources) builder = build_backend(modulename, sources, extra_objects, build_dir, include_dirs, library_dirs, libraries, define_macros, undef_macros, f2py_flags, sysinfo_flags, fc_flags, flib_flags, setup_flags, remove_build_dir, {'dependencies': dependencies}) builder.compile() def validate_modulename(pyf_files, modulename='untitled'): if len(pyf_files) > 1: raise ValueError('Only one .pyf file per call') if pyf_files: pyff = pyf_files[0] pyf_modname = auxfuncs.get_f2py_modulename(pyff) if modulename != pyf_modname: outmess(f'Ignoring -m {modulename}.\n{pyff} defines {pyf_modname} to be the modulename.\n') modulename = pyf_modname return modulename def main(): if '--help-link' in sys.argv[1:]: sys.argv.remove('--help-link') if MESON_ONLY_VER: outmess('Use --dep for meson builds\n') else: from numpy.distutils.system_info import show_all show_all() return if '-c' in sys.argv[1:]: run_compile() else: run_main(sys.argv[1:]) # File: numpy-main/numpy/f2py/f90mod_rules.py """""" __version__ = '$Revision: 1.27 $'[10:-1] f2py_version = 'See `f2py -v`' import numpy as np from . import capi_maps from . import func2subr from .crackfortran import undo_rmbadname, undo_rmbadname1 from .auxfuncs import * options = {} def findf90modules(m): if ismodule(m): return [m] if not hasbody(m): return [] ret = [] for b in m['body']: if ismodule(b): ret.append(b) else: ret = ret + findf90modules(b) return ret fgetdims1 = ' external f2pysetdata\n logical ns\n integer r,i\n integer(%d) s(*)\n ns = .FALSE.\n if (allocated(d)) then\n do i=1,r\n if ((size(d,i).ne.s(i)).and.(s(i).ge.0)) then\n ns = .TRUE.\n end if\n end do\n if (ns) then\n deallocate(d)\n end if\n end if\n if ((.not.allocated(d)).and.(s(1).ge.1)) then' % np.intp().itemsize fgetdims2 = ' end if\n if (allocated(d)) then\n do i=1,r\n s(i) = size(d,i)\n end do\n end if\n flag = 1\n call f2pysetdata(d,allocated(d))' fgetdims2_sa = ' end if\n if (allocated(d)) then\n do i=1,r\n s(i) = size(d,i)\n end do\n !s(r) must be equal to len(d(1))\n end if\n flag = 2\n call f2pysetdata(d,allocated(d))' def buildhooks(pymod): from . import rules ret = {'f90modhooks': [], 'initf90modhooks': [], 'body': [], 'need': ['F_FUNC', 'arrayobject.h'], 'separatorsfor': {'includes0': '\n', 'includes': '\n'}, 'docs': ['"Fortran 90/95 modules:\\n"'], 'latexdoc': []} fhooks = [''] def fadd(line, s=fhooks): s[0] = '%s\n %s' % (s[0], line) doc = [''] def dadd(line, s=doc): s[0] = '%s\n%s' % (s[0], line) usenames = getuseblocks(pymod) for m in findf90modules(pymod): contains_functions_or_subroutines = any((item for item in m['body'] if item['block'] in ['function', 'subroutine'])) (sargs, fargs, efargs, modobjs, notvars, onlyvars) = ([], [], [], [], [m['name']], []) sargsp = [] ifargs = [] mfargs = [] if hasbody(m): for b in m['body']: notvars.append(b['name']) for n in m['vars'].keys(): var = m['vars'][n] if (n not in notvars and isvariable(var)) and (not l_or(isintent_hide, isprivate)(var)): onlyvars.append(n) mfargs.append(n) outmess('\t\tConstructing F90 module support for "%s"...\n' % m['name']) if len(onlyvars) == 0 and len(notvars) == 1 and (m['name'] in notvars): outmess(f"\t\t\tSkipping {m['name']} since there are no public vars/func in this module...\n") continue if m['name'] in usenames and (not contains_functions_or_subroutines): outmess(f"\t\t\tSkipping {m['name']} since it is in 'use'...\n") continue if onlyvars: outmess('\t\t Variables: %s\n' % ' '.join(onlyvars)) chooks = [''] def cadd(line, s=chooks): s[0] = '%s\n%s' % (s[0], line) ihooks = [''] def iadd(line, s=ihooks): s[0] = '%s\n%s' % (s[0], line) vrd = capi_maps.modsign2map(m) cadd('static FortranDataDef f2py_%s_def[] = {' % m['name']) dadd('\\subsection{Fortran 90/95 module \\texttt{%s}}\n' % m['name']) if hasnote(m): note = m['note'] if isinstance(note, list): note = '\n'.join(note) dadd(note) if onlyvars: dadd('\\begin{description}') for n in onlyvars: var = m['vars'][n] modobjs.append(n) ct = capi_maps.getctype(var) at = capi_maps.c2capi_map[ct] dm = capi_maps.getarrdims(n, var) dms = dm['dims'].replace('*', '-1').strip() dms = dms.replace(':', '-1').strip() if not dms: dms = '-1' use_fgetdims2 = fgetdims2 cadd('\t{"%s",%s,{{%s}},%s, %s},' % (undo_rmbadname1(n), dm['rank'], dms, at, capi_maps.get_elsize(var))) dadd('\\item[]{{}\\verb@%s@{}}' % capi_maps.getarrdocsign(n, var)) if hasnote(var): note = var['note'] if isinstance(note, list): note = '\n'.join(note) dadd('--- %s' % note) if isallocatable(var): fargs.append('f2py_%s_getdims_%s' % (m['name'], n)) efargs.append(fargs[-1]) sargs.append('void (*%s)(int*,npy_intp*,void(*)(char*,npy_intp*),int*)' % n) sargsp.append('void (*)(int*,npy_intp*,void(*)(char*,npy_intp*),int*)') iadd('\tf2py_%s_def[i_f2py++].func = %s;' % (m['name'], n)) fadd('subroutine %s(r,s,f2pysetdata,flag)' % fargs[-1]) fadd('use %s, only: d => %s\n' % (m['name'], undo_rmbadname1(n))) fadd('integer flag\n') fhooks[0] = fhooks[0] + fgetdims1 dms = range(1, int(dm['rank']) + 1) fadd(' allocate(d(%s))\n' % ','.join(['s(%s)' % i for i in dms])) fhooks[0] = fhooks[0] + use_fgetdims2 fadd('end subroutine %s' % fargs[-1]) else: fargs.append(n) sargs.append('char *%s' % n) sargsp.append('char*') iadd('\tf2py_%s_def[i_f2py++].data = %s;' % (m['name'], n)) if onlyvars: dadd('\\end{description}') if hasbody(m): for b in m['body']: if not isroutine(b): outmess(f"f90mod_rules.buildhooks: skipping {b['block']} {b['name']}\n") continue modobjs.append('%s()' % b['name']) b['modulename'] = m['name'] (api, wrap) = rules.buildapi(b) if isfunction(b): fhooks[0] = fhooks[0] + wrap fargs.append('f2pywrap_%s_%s' % (m['name'], b['name'])) ifargs.append(func2subr.createfuncwrapper(b, signature=1)) elif wrap: fhooks[0] = fhooks[0] + wrap fargs.append('f2pywrap_%s_%s' % (m['name'], b['name'])) ifargs.append(func2subr.createsubrwrapper(b, signature=1)) else: fargs.append(b['name']) mfargs.append(fargs[-1]) api['externroutines'] = [] ar = applyrules(api, vrd) ar['docs'] = [] ar['docshort'] = [] ret = dictappend(ret, ar) cadd('\t{"%s",-1,{{-1}},0,0,NULL,(void *)f2py_rout_#modulename#_%s_%s,doc_f2py_rout_#modulename#_%s_%s},' % (b['name'], m['name'], b['name'], m['name'], b['name'])) sargs.append('char *%s' % b['name']) sargsp.append('char *') iadd('\tf2py_%s_def[i_f2py++].data = %s;' % (m['name'], b['name'])) cadd('\t{NULL}\n};\n') iadd('}') ihooks[0] = 'static void f2py_setup_%s(%s) {\n\tint i_f2py=0;%s' % (m['name'], ','.join(sargs), ihooks[0]) if '_' in m['name']: F_FUNC = 'F_FUNC_US' else: F_FUNC = 'F_FUNC' iadd('extern void %s(f2pyinit%s,F2PYINIT%s)(void (*)(%s));' % (F_FUNC, m['name'], m['name'].upper(), ','.join(sargsp))) iadd('static void f2py_init_%s(void) {' % m['name']) iadd('\t%s(f2pyinit%s,F2PYINIT%s)(f2py_setup_%s);' % (F_FUNC, m['name'], m['name'].upper(), m['name'])) iadd('}\n') ret['f90modhooks'] = ret['f90modhooks'] + chooks + ihooks ret['initf90modhooks'] = ['\tPyDict_SetItemString(d, "%s", PyFortranObject_New(f2py_%s_def,f2py_init_%s));' % (m['name'], m['name'], m['name'])] + ret['initf90modhooks'] fadd('') fadd('subroutine f2pyinit%s(f2pysetupfunc)' % m['name']) if mfargs: for a in undo_rmbadname(mfargs): fadd('use %s, only : %s' % (m['name'], a)) if ifargs: fadd(' '.join(['interface'] + ifargs)) fadd('end interface') fadd('external f2pysetupfunc') if efargs: for a in undo_rmbadname(efargs): fadd('external %s' % a) fadd('call f2pysetupfunc(%s)' % ','.join(undo_rmbadname(fargs))) fadd('end subroutine f2pyinit%s\n' % m['name']) dadd('\n'.join(ret['latexdoc']).replace('\\subsection{', '\\subsubsection{')) ret['latexdoc'] = [] ret['docs'].append('"\t%s --- %s"' % (m['name'], ','.join(undo_rmbadname(modobjs)))) ret['routine_defs'] = '' ret['doc'] = [] ret['docshort'] = [] ret['latexdoc'] = doc[0] if len(ret['docs']) <= 1: ret['docs'] = '' return (ret, fhooks[0]) # File: numpy-main/numpy/f2py/func2subr.py """""" import copy from .auxfuncs import getfortranname, isexternal, isfunction, isfunction_wrap, isintent_in, isintent_out, islogicalfunction, ismoduleroutine, isscalar, issubroutine, issubroutine_wrap, outmess, show from ._isocbind import isoc_kindmap def var2fixfortran(vars, a, fa=None, f90mode=None): if fa is None: fa = a if a not in vars: show(vars) outmess('var2fixfortran: No definition for argument "%s".\n' % a) return '' if 'typespec' not in vars[a]: show(vars[a]) outmess('var2fixfortran: No typespec for argument "%s".\n' % a) return '' vardef = vars[a]['typespec'] if vardef == 'type' and 'typename' in vars[a]: vardef = '%s(%s)' % (vardef, vars[a]['typename']) selector = {} lk = '' if 'kindselector' in vars[a]: selector = vars[a]['kindselector'] lk = 'kind' elif 'charselector' in vars[a]: selector = vars[a]['charselector'] lk = 'len' if '*' in selector: if f90mode: if selector['*'] in ['*', ':', '(*)']: vardef = '%s(len=*)' % vardef else: vardef = '%s(%s=%s)' % (vardef, lk, selector['*']) elif selector['*'] in ['*', ':']: vardef = '%s*(%s)' % (vardef, selector['*']) else: vardef = '%s*%s' % (vardef, selector['*']) elif 'len' in selector: vardef = '%s(len=%s' % (vardef, selector['len']) if 'kind' in selector: vardef = '%s,kind=%s)' % (vardef, selector['kind']) else: vardef = '%s)' % vardef elif 'kind' in selector: vardef = '%s(kind=%s)' % (vardef, selector['kind']) vardef = '%s %s' % (vardef, fa) if 'dimension' in vars[a]: vardef = '%s(%s)' % (vardef, ','.join(vars[a]['dimension'])) return vardef def useiso_c_binding(rout): useisoc = False for (key, value) in rout['vars'].items(): kind_value = value.get('kindselector', {}).get('kind') if kind_value in isoc_kindmap: return True return useisoc def createfuncwrapper(rout, signature=0): assert isfunction(rout) extra_args = [] vars = rout['vars'] for a in rout['args']: v = rout['vars'][a] for (i, d) in enumerate(v.get('dimension', [])): if d == ':': dn = 'f2py_%s_d%s' % (a, i) dv = dict(typespec='integer', intent=['hide']) dv['='] = 'shape(%s, %s)' % (a, i) extra_args.append(dn) vars[dn] = dv v['dimension'][i] = dn rout['args'].extend(extra_args) need_interface = bool(extra_args) ret = [''] def add(line, ret=ret): ret[0] = '%s\n %s' % (ret[0], line) name = rout['name'] fortranname = getfortranname(rout) f90mode = ismoduleroutine(rout) newname = '%sf2pywrap' % name if newname not in vars: vars[newname] = vars[name] args = [newname] + rout['args'][1:] else: args = [newname] + rout['args'] l_tmpl = var2fixfortran(vars, name, '@@@NAME@@@', f90mode) if l_tmpl[:13] == 'character*(*)': if f90mode: l_tmpl = 'character(len=10)' + l_tmpl[13:] else: l_tmpl = 'character*10' + l_tmpl[13:] charselect = vars[name]['charselector'] if charselect.get('*', '') == '(*)': charselect['*'] = '10' l1 = l_tmpl.replace('@@@NAME@@@', newname) rl = None useisoc = useiso_c_binding(rout) sargs = ', '.join(args) if f90mode: sargs = sargs.replace(f'{name}, ', '') args = [arg for arg in args if arg != name] rout['args'] = args add('subroutine f2pywrap_%s_%s (%s)' % (rout['modulename'], name, sargs)) if not signature: add('use %s, only : %s' % (rout['modulename'], fortranname)) if useisoc: add('use iso_c_binding') else: add('subroutine f2pywrap%s (%s)' % (name, sargs)) if useisoc: add('use iso_c_binding') if not need_interface: add('external %s' % fortranname) rl = l_tmpl.replace('@@@NAME@@@', '') + ' ' + fortranname if need_interface: for line in rout['saved_interface'].split('\n'): if line.lstrip().startswith('use ') and '__user__' not in line: add(line) args = args[1:] dumped_args = [] for a in args: if isexternal(vars[a]): add('external %s' % a) dumped_args.append(a) for a in args: if a in dumped_args: continue if isscalar(vars[a]): add(var2fixfortran(vars, a, f90mode=f90mode)) dumped_args.append(a) for a in args: if a in dumped_args: continue if isintent_in(vars[a]): add(var2fixfortran(vars, a, f90mode=f90mode)) dumped_args.append(a) for a in args: if a in dumped_args: continue add(var2fixfortran(vars, a, f90mode=f90mode)) add(l1) if rl is not None: add(rl) if need_interface: if f90mode: pass else: add('interface') add(rout['saved_interface'].lstrip()) add('end interface') sargs = ', '.join([a for a in args if a not in extra_args]) if not signature: if islogicalfunction(rout): add('%s = .not.(.not.%s(%s))' % (newname, fortranname, sargs)) else: add('%s = %s(%s)' % (newname, fortranname, sargs)) if f90mode: add('end subroutine f2pywrap_%s_%s' % (rout['modulename'], name)) else: add('end') return ret[0] def createsubrwrapper(rout, signature=0): assert issubroutine(rout) extra_args = [] vars = rout['vars'] for a in rout['args']: v = rout['vars'][a] for (i, d) in enumerate(v.get('dimension', [])): if d == ':': dn = 'f2py_%s_d%s' % (a, i) dv = dict(typespec='integer', intent=['hide']) dv['='] = 'shape(%s, %s)' % (a, i) extra_args.append(dn) vars[dn] = dv v['dimension'][i] = dn rout['args'].extend(extra_args) need_interface = bool(extra_args) ret = [''] def add(line, ret=ret): ret[0] = '%s\n %s' % (ret[0], line) name = rout['name'] fortranname = getfortranname(rout) f90mode = ismoduleroutine(rout) args = rout['args'] useisoc = useiso_c_binding(rout) sargs = ', '.join(args) if f90mode: add('subroutine f2pywrap_%s_%s (%s)' % (rout['modulename'], name, sargs)) if useisoc: add('use iso_c_binding') if not signature: add('use %s, only : %s' % (rout['modulename'], fortranname)) else: add('subroutine f2pywrap%s (%s)' % (name, sargs)) if useisoc: add('use iso_c_binding') if not need_interface: add('external %s' % fortranname) if need_interface: for line in rout['saved_interface'].split('\n'): if line.lstrip().startswith('use ') and '__user__' not in line: add(line) dumped_args = [] for a in args: if isexternal(vars[a]): add('external %s' % a) dumped_args.append(a) for a in args: if a in dumped_args: continue if isscalar(vars[a]): add(var2fixfortran(vars, a, f90mode=f90mode)) dumped_args.append(a) for a in args: if a in dumped_args: continue add(var2fixfortran(vars, a, f90mode=f90mode)) if need_interface: if f90mode: pass else: add('interface') for line in rout['saved_interface'].split('\n'): if line.lstrip().startswith('use ') and '__user__' in line: continue add(line) add('end interface') sargs = ', '.join([a for a in args if a not in extra_args]) if not signature: add('call %s(%s)' % (fortranname, sargs)) if f90mode: add('end subroutine f2pywrap_%s_%s' % (rout['modulename'], name)) else: add('end') return ret[0] def assubr(rout): if isfunction_wrap(rout): fortranname = getfortranname(rout) name = rout['name'] outmess('\t\tCreating wrapper for Fortran function "%s"("%s")...\n' % (name, fortranname)) rout = copy.copy(rout) fname = name rname = fname if 'result' in rout: rname = rout['result'] rout['vars'][fname] = rout['vars'][rname] fvar = rout['vars'][fname] if not isintent_out(fvar): if 'intent' not in fvar: fvar['intent'] = [] fvar['intent'].append('out') flag = 1 for i in fvar['intent']: if i.startswith('out='): flag = 0 break if flag: fvar['intent'].append('out=%s' % rname) rout['args'][:] = [fname] + rout['args'] return (rout, createfuncwrapper(rout)) if issubroutine_wrap(rout): fortranname = getfortranname(rout) name = rout['name'] outmess('\t\tCreating wrapper for Fortran subroutine "%s"("%s")...\n' % (name, fortranname)) rout = copy.copy(rout) return (rout, createsubrwrapper(rout)) return (rout, '') # File: numpy-main/numpy/f2py/rules.py """""" import os import sys import time import copy from pathlib import Path from . import __version__ from .auxfuncs import applyrules, debugcapi, dictappend, errmess, gentitle, getargs2, hascallstatement, hasexternals, hasinitvalue, hasnote, hasresultnote, isarray, isarrayofstrings, ischaracter, ischaracterarray, ischaracter_or_characterarray, iscomplex, iscomplexarray, iscomplexfunction, iscomplexfunction_warn, isdummyroutine, isexternal, isfunction, isfunction_wrap, isint1, isint1array, isintent_aux, isintent_c, isintent_callback, isintent_copy, isintent_hide, isintent_inout, isintent_nothide, isintent_out, isintent_overwrite, islogical, islong_complex, islong_double, islong_doublefunction, islong_long, islong_longfunction, ismoduleroutine, isoptional, isrequired, isscalar, issigned_long_longarray, isstring, isstringarray, isstringfunction, issubroutine, isattr_value, issubroutine_wrap, isthreadsafe, isunsigned, isunsigned_char, isunsigned_chararray, isunsigned_long_long, isunsigned_long_longarray, isunsigned_short, isunsigned_shortarray, l_and, l_not, l_or, outmess, replace, stripcomma, requiresf90wrapper from . import capi_maps from . import cfuncs from . import common_rules from . import use_rules from . import f90mod_rules from . import func2subr f2py_version = __version__.version numpy_version = __version__.version options = {} sepdict = {} for k in ['decl', 'frompyobj', 'cleanupfrompyobj', 'topyarr', 'method', 'pyobjfrom', 'closepyobjfrom', 'freemem', 'userincludes', 'includes0', 'includes', 'typedefs', 'typedefs_generated', 'cppmacros', 'cfuncs', 'callbacks', 'latexdoc', 'restdoc', 'routine_defs', 'externroutines', 'initf2pywraphooks', 'commonhooks', 'initcommonhooks', 'f90modhooks', 'initf90modhooks']: sepdict[k] = '\n' generationtime = int(os.environ.get('SOURCE_DATE_EPOCH', time.time())) module_rules = {'modulebody': '/* File: #modulename#module.c\n * This file is auto-generated with f2py (version:#f2py_version#).\n * f2py is a Fortran to Python Interface Generator (FPIG), Second Edition,\n * written by Pearu Peterson .\n * Generation date: ' + time.asctime(time.gmtime(generationtime)) + '\n * Do not edit this file directly unless you know what you are doing!!!\n */\n\n#ifdef __cplusplus\nextern "C" {\n#endif\n\n#ifndef PY_SSIZE_T_CLEAN\n#define PY_SSIZE_T_CLEAN\n#endif /* PY_SSIZE_T_CLEAN */\n\n/* Unconditionally included */\n#include \n#include \n\n' + gentitle('See f2py2e/cfuncs.py: includes') + '\n#includes#\n#includes0#\n\n' + gentitle("See f2py2e/rules.py: mod_rules['modulebody']") + '\nstatic PyObject *#modulename#_error;\nstatic PyObject *#modulename#_module;\n\n' + gentitle('See f2py2e/cfuncs.py: typedefs') + '\n#typedefs#\n\n' + gentitle('See f2py2e/cfuncs.py: typedefs_generated') + '\n#typedefs_generated#\n\n' + gentitle('See f2py2e/cfuncs.py: cppmacros') + '\n#cppmacros#\n\n' + gentitle('See f2py2e/cfuncs.py: cfuncs') + '\n#cfuncs#\n\n' + gentitle('See f2py2e/cfuncs.py: userincludes') + '\n#userincludes#\n\n' + gentitle('See f2py2e/capi_rules.py: usercode') + '\n#usercode#\n\n/* See f2py2e/rules.py */\n#externroutines#\n\n' + gentitle('See f2py2e/capi_rules.py: usercode1') + '\n#usercode1#\n\n' + gentitle('See f2py2e/cb_rules.py: buildcallback') + '\n#callbacks#\n\n' + gentitle('See f2py2e/rules.py: buildapi') + '\n#body#\n\n' + gentitle('See f2py2e/f90mod_rules.py: buildhooks') + '\n#f90modhooks#\n\n' + gentitle("See f2py2e/rules.py: module_rules['modulebody']") + '\n\n' + gentitle('See f2py2e/common_rules.py: buildhooks') + '\n#commonhooks#\n\n' + gentitle('See f2py2e/rules.py') + '\n\nstatic FortranDataDef f2py_routine_defs[] = {\n#routine_defs#\n {NULL}\n};\n\nstatic PyMethodDef f2py_module_methods[] = {\n#pymethoddef#\n {NULL,NULL}\n};\n\nstatic struct PyModuleDef moduledef = {\n PyModuleDef_HEAD_INIT,\n "#modulename#",\n NULL,\n -1,\n f2py_module_methods,\n NULL,\n NULL,\n NULL,\n NULL\n};\n\nPyMODINIT_FUNC PyInit_#modulename#(void) {\n int i;\n PyObject *m,*d, *s, *tmp;\n m = #modulename#_module = PyModule_Create(&moduledef);\n Py_SET_TYPE(&PyFortran_Type, &PyType_Type);\n import_array();\n if (PyErr_Occurred())\n {PyErr_SetString(PyExc_ImportError, "can\'t initialize module #modulename# (failed to import numpy)"); return m;}\n d = PyModule_GetDict(m);\n s = PyUnicode_FromString("#f2py_version#");\n PyDict_SetItemString(d, "__version__", s);\n Py_DECREF(s);\n s = PyUnicode_FromString(\n "This module \'#modulename#\' is auto-generated with f2py (version:#f2py_version#).\\nFunctions:\\n"\n#docs#".");\n PyDict_SetItemString(d, "__doc__", s);\n Py_DECREF(s);\n s = PyUnicode_FromString("' + numpy_version + '");\n PyDict_SetItemString(d, "__f2py_numpy_version__", s);\n Py_DECREF(s);\n #modulename#_error = PyErr_NewException ("#modulename#.error", NULL, NULL);\n /*\n * Store the error object inside the dict, so that it could get deallocated.\n * (in practice, this is a module, so it likely will not and cannot.)\n */\n PyDict_SetItemString(d, "_#modulename#_error", #modulename#_error);\n Py_DECREF(#modulename#_error);\n for(i=0;f2py_routine_defs[i].name!=NULL;i++) {\n tmp = PyFortranObject_NewAsAttr(&f2py_routine_defs[i]);\n PyDict_SetItemString(d, f2py_routine_defs[i].name, tmp);\n Py_DECREF(tmp);\n }\n#initf2pywraphooks#\n#initf90modhooks#\n#initcommonhooks#\n#interface_usercode#\n\n#if Py_GIL_DISABLED\n // signal whether this module supports running with the GIL disabled\n PyUnstable_Module_SetGIL(m , #gil_used#);\n#endif\n\n#ifdef F2PY_REPORT_ATEXIT\n if (! PyErr_Occurred())\n on_exit(f2py_report_on_exit,(void*)"#modulename#");\n#endif\n return m;\n}\n#ifdef __cplusplus\n}\n#endif\n', 'separatorsfor': {'latexdoc': '\n\n', 'restdoc': '\n\n'}, 'latexdoc': ['\\section{Module \\texttt{#texmodulename#}}\n', '#modnote#\n', '#latexdoc#'], 'restdoc': ['Module #modulename#\n' + '=' * 80, '\n#restdoc#']} defmod_rules = [{'body': '/*eof body*/', 'method': '/*eof method*/', 'externroutines': '/*eof externroutines*/', 'routine_defs': '/*eof routine_defs*/', 'initf90modhooks': '/*eof initf90modhooks*/', 'initf2pywraphooks': '/*eof initf2pywraphooks*/', 'initcommonhooks': '/*eof initcommonhooks*/', 'latexdoc': '', 'restdoc': '', 'modnote': {hasnote: '#note#', l_not(hasnote): ''}}] routine_rules = {'separatorsfor': sepdict, 'body': '\n#begintitle#\nstatic char doc_#apiname#[] = "\\\n#docreturn##name#(#docsignatureshort#)\\n\\nWrapper for ``#name#``.\\\n\\n#docstrsigns#";\n/* #declfortranroutine# */\nstatic PyObject *#apiname#(const PyObject *capi_self,\n PyObject *capi_args,\n PyObject *capi_keywds,\n #functype# (*f2py_func)(#callprotoargument#)) {\n PyObject * volatile capi_buildvalue = NULL;\n volatile int f2py_success = 1;\n#decl#\n static char *capi_kwlist[] = {#kwlist##kwlistopt##kwlistxa#NULL};\n#usercode#\n#routdebugenter#\n#ifdef F2PY_REPORT_ATEXIT\nf2py_start_clock();\n#endif\n if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\\\n "#argformat#|#keyformat##xaformat#:#pyname#",\\\n capi_kwlist#args_capi##keys_capi##keys_xa#))\n return NULL;\n#frompyobj#\n/*end of frompyobj*/\n#ifdef F2PY_REPORT_ATEXIT\nf2py_start_call_clock();\n#endif\n#callfortranroutine#\nif (PyErr_Occurred())\n f2py_success = 0;\n#ifdef F2PY_REPORT_ATEXIT\nf2py_stop_call_clock();\n#endif\n/*end of callfortranroutine*/\n if (f2py_success) {\n#pyobjfrom#\n/*end of pyobjfrom*/\n CFUNCSMESS("Building return value.\\n");\n capi_buildvalue = Py_BuildValue("#returnformat#"#return#);\n/*closepyobjfrom*/\n#closepyobjfrom#\n } /*if (f2py_success) after callfortranroutine*/\n/*cleanupfrompyobj*/\n#cleanupfrompyobj#\n if (capi_buildvalue == NULL) {\n#routdebugfailure#\n } else {\n#routdebugleave#\n }\n CFUNCSMESS("Freeing memory.\\n");\n#freemem#\n#ifdef F2PY_REPORT_ATEXIT\nf2py_stop_clock();\n#endif\n return capi_buildvalue;\n}\n#endtitle#\n', 'routine_defs': '#routine_def#', 'initf2pywraphooks': '#initf2pywraphook#', 'externroutines': '#declfortranroutine#', 'doc': '#docreturn##name#(#docsignature#)', 'docshort': '#docreturn##name#(#docsignatureshort#)', 'docs': '" #docreturn##name#(#docsignature#)\\n"\n', 'need': ['arrayobject.h', 'CFUNCSMESS', 'MINMAX'], 'cppmacros': {debugcapi: '#define DEBUGCFUNCS'}, 'latexdoc': ['\\subsection{Wrapper function \\texttt{#texname#}}\n', '\n\\noindent{{}\\verb@#docreturn##name#@{}}\\texttt{(#latexdocsignatureshort#)}\n#routnote#\n\n#latexdocstrsigns#\n'], 'restdoc': ['Wrapped function ``#name#``\n' + '-' * 80]} rout_rules = [{'separatorsfor': {'callfortranroutine': '\n', 'routdebugenter': '\n', 'decl': '\n', 'routdebugleave': '\n', 'routdebugfailure': '\n', 'setjmpbuf': ' || ', 'docstrreq': '\n', 'docstropt': '\n', 'docstrout': '\n', 'docstrcbs': '\n', 'docstrsigns': '\\n"\n"', 'latexdocstrsigns': '\n', 'latexdocstrreq': '\n', 'latexdocstropt': '\n', 'latexdocstrout': '\n', 'latexdocstrcbs': '\n'}, 'kwlist': '', 'kwlistopt': '', 'callfortran': '', 'callfortranappend': '', 'docsign': '', 'docsignopt': '', 'decl': '/*decl*/', 'freemem': '/*freemem*/', 'docsignshort': '', 'docsignoptshort': '', 'docstrsigns': '', 'latexdocstrsigns': '', 'docstrreq': '\\nParameters\\n----------', 'docstropt': '\\nOther Parameters\\n----------------', 'docstrout': '\\nReturns\\n-------', 'docstrcbs': '\\nNotes\\n-----\\nCall-back functions::\\n', 'latexdocstrreq': '\\noindent Required arguments:', 'latexdocstropt': '\\noindent Optional arguments:', 'latexdocstrout': '\\noindent Return objects:', 'latexdocstrcbs': '\\noindent Call-back functions:', 'args_capi': '', 'keys_capi': '', 'functype': '', 'frompyobj': '/*frompyobj*/', 'cleanupfrompyobj': ['/*end of cleanupfrompyobj*/'], 'pyobjfrom': '/*pyobjfrom*/', 'closepyobjfrom': ['/*end of closepyobjfrom*/'], 'topyarr': '/*topyarr*/', 'routdebugleave': '/*routdebugleave*/', 'routdebugenter': '/*routdebugenter*/', 'routdebugfailure': '/*routdebugfailure*/', 'callfortranroutine': '/*callfortranroutine*/', 'argformat': '', 'keyformat': '', 'need_cfuncs': '', 'docreturn': '', 'return': '', 'returnformat': '', 'rformat': '', 'kwlistxa': '', 'keys_xa': '', 'xaformat': '', 'docsignxa': '', 'docsignxashort': '', 'initf2pywraphook': '', 'routnote': {hasnote: '--- #note#', l_not(hasnote): ''}}, {'apiname': 'f2py_rout_#modulename#_#name#', 'pyname': '#modulename#.#name#', 'decl': '', '_check': l_not(ismoduleroutine)}, {'apiname': 'f2py_rout_#modulename#_#f90modulename#_#name#', 'pyname': '#modulename#.#f90modulename#.#name#', 'decl': '', '_check': ismoduleroutine}, {'functype': 'void', 'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern void #fortranname#(#callprotoargument#);', ismoduleroutine: '', isdummyroutine: ''}, 'routine_def': {l_not(l_or(ismoduleroutine, isintent_c, isdummyroutine)): ' {"#name#",-1,{{-1}},0,0,(char *) #F_FUNC#(#fortranname#,#FORTRANNAME#), (f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): ' {"#name#",-1,{{-1}},0,0,(char *)#fortranname#, (f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isdummyroutine): ' {"#name#",-1,{{-1}},0,0,NULL, (f2py_init_func)#apiname#,doc_#apiname#},'}, 'need': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'F_FUNC'}, 'callfortranroutine': [{debugcapi: [' fprintf(stderr,"debug-capi:Fortran subroutine `#fortranname#(#callfortran#)\'\\n");']}, {hasexternals: ' if (#setjmpbuf#) {\n f2py_success = 0;\n } else {'}, {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'}, {hascallstatement: ' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'}, {l_not(l_or(hascallstatement, isdummyroutine)): ' (*f2py_func)(#callfortran#);'}, {isthreadsafe: ' Py_END_ALLOW_THREADS'}, {hasexternals: ' }'}], '_check': l_and(issubroutine, l_not(issubroutine_wrap))}, {'functype': 'void', 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);', isdummyroutine: ''}, 'routine_def': {l_not(l_or(ismoduleroutine, isdummyroutine)): ' {"#name#",-1,{{-1}},0,0,(char *) #F_WRAPPEDFUNC#(#name_lower#,#NAME#), (f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: ' {"#name#",-1,{{-1}},0,0,NULL, (f2py_init_func)#apiname#,doc_#apiname#},'}, 'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): '\n {\n extern #ctype# #F_FUNC#(#name_lower#,#NAME#)(void);\n PyObject* o = PyDict_GetItemString(d,"#name#");\n tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL);\n PyObject_SetAttrString(o,"_cpointer", tmp);\n Py_DECREF(tmp);\n s = PyUnicode_FromString("#name#");\n PyObject_SetAttrString(o,"__name__", s);\n Py_DECREF(s);\n }\n '}, 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']}, 'callfortranroutine': [{debugcapi: [' fprintf(stderr,"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n");']}, {hasexternals: ' if (#setjmpbuf#) {\n f2py_success = 0;\n } else {'}, {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'}, {l_not(l_or(hascallstatement, isdummyroutine)): ' (*f2py_func)(#callfortran#);'}, {hascallstatement: ' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'}, {isthreadsafe: ' Py_END_ALLOW_THREADS'}, {hasexternals: ' }'}], '_check': isfunction_wrap}, {'functype': 'void', 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);', isdummyroutine: ''}, 'routine_def': {l_not(l_or(ismoduleroutine, isdummyroutine)): ' {"#name#",-1,{{-1}},0,0,(char *) #F_WRAPPEDFUNC#(#name_lower#,#NAME#), (f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: ' {"#name#",-1,{{-1}},0,0,NULL, (f2py_init_func)#apiname#,doc_#apiname#},'}, 'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): '\n {\n extern void #F_FUNC#(#name_lower#,#NAME#)(void);\n PyObject* o = PyDict_GetItemString(d,"#name#");\n tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL);\n PyObject_SetAttrString(o,"_cpointer", tmp);\n Py_DECREF(tmp);\n s = PyUnicode_FromString("#name#");\n PyObject_SetAttrString(o,"__name__", s);\n Py_DECREF(s);\n }\n '}, 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']}, 'callfortranroutine': [{debugcapi: [' fprintf(stderr,"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n");']}, {hasexternals: ' if (#setjmpbuf#) {\n f2py_success = 0;\n } else {'}, {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'}, {l_not(l_or(hascallstatement, isdummyroutine)): ' (*f2py_func)(#callfortran#);'}, {hascallstatement: ' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'}, {isthreadsafe: ' Py_END_ALLOW_THREADS'}, {hasexternals: ' }'}], '_check': issubroutine_wrap}, {'functype': '#ctype#', 'docreturn': {l_not(isintent_hide): '#rname#,'}, 'docstrout': '#pydocsignout#', 'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}', {hasresultnote: '--- #resultnote#'}], 'callfortranroutine': [{l_and(debugcapi, isstringfunction): '#ifdef USESCOMPAQFORTRAN\n fprintf(stderr,"debug-capi:Fortran function #ctype# #fortranname#(#callcompaqfortran#)\\n");\n#else\n fprintf(stderr,"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n");\n#endif\n'}, {l_and(debugcapi, l_not(isstringfunction)): ' fprintf(stderr,"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n");\n'}], '_check': l_and(isfunction, l_not(isfunction_wrap))}, {'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern #ctype# #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern #ctype# #fortranname#(#callprotoargument#);', isdummyroutine: ''}, 'routine_def': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): ' {"#name#",-1,{{-1}},0,0,(char *) #F_FUNC#(#fortranname#,#FORTRANNAME#), (f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): ' {"#name#",-1,{{-1}},0,0,(char *)#fortranname#, (f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: ' {"#name#",-1,{{-1}},0,0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},'}, 'decl': [{iscomplexfunction_warn: ' #ctype# #name#_return_value={0,0};', l_not(iscomplexfunction): ' #ctype# #name#_return_value=0;'}, {iscomplexfunction: ' PyObject *#name#_return_value_capi = Py_None;'}], 'callfortranroutine': [{hasexternals: ' if (#setjmpbuf#) {\n f2py_success = 0;\n } else {'}, {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'}, {hascallstatement: ' #callstatement#;\n/* #name#_return_value = (*f2py_func)(#callfortran#);*/\n'}, {l_not(l_or(hascallstatement, isdummyroutine)): ' #name#_return_value = (*f2py_func)(#callfortran#);'}, {isthreadsafe: ' Py_END_ALLOW_THREADS'}, {hasexternals: ' }'}, {l_and(debugcapi, iscomplexfunction): ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value.r,#name#_return_value.i);'}, {l_and(debugcapi, l_not(iscomplexfunction)): ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value);'}], 'pyobjfrom': {iscomplexfunction: ' #name#_return_value_capi = pyobj_from_#ctype#1(#name#_return_value);'}, 'need': [{l_not(isdummyroutine): 'F_FUNC'}, {iscomplexfunction: 'pyobj_from_#ctype#1'}, {islong_longfunction: 'long_long'}, {islong_doublefunction: 'long_double'}], 'returnformat': {l_not(isintent_hide): '#rformat#'}, 'return': {iscomplexfunction: ',#name#_return_value_capi', l_not(l_or(iscomplexfunction, isintent_hide)): ',#name#_return_value'}, '_check': l_and(isfunction, l_not(isstringfunction), l_not(isfunction_wrap))}, {'declfortranroutine': 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', 'routine_def': {l_not(l_or(ismoduleroutine, isintent_c)): ' {"#name#",-1,{{-1}},0,0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c): ' {"#name#",-1,{{-1}},0,0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},'}, 'decl': [' #ctype# #name#_return_value = NULL;', ' int #name#_return_value_len = 0;'], 'callfortran': '#name#_return_value,#name#_return_value_len,', 'callfortranroutine': [' #name#_return_value_len = #rlength#;', ' if ((#name#_return_value = (string)malloc(' + '#name#_return_value_len+1) == NULL) {', ' PyErr_SetString(PyExc_MemoryError, "out of memory");', ' f2py_success = 0;', ' } else {', " (#name#_return_value)[#name#_return_value_len] = '\\0';", ' }', ' if (f2py_success) {', {hasexternals: ' if (#setjmpbuf#) {\n f2py_success = 0;\n } else {'}, {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'}, '#ifdef USESCOMPAQFORTRAN\n (*f2py_func)(#callcompaqfortran#);\n#else\n (*f2py_func)(#callfortran#);\n#endif\n', {isthreadsafe: ' Py_END_ALLOW_THREADS'}, {hasexternals: ' }'}, {debugcapi: ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value_len,#name#_return_value);'}, ' } /* if (f2py_success) after (string)malloc */'], 'returnformat': '#rformat#', 'return': ',#name#_return_value', 'freemem': ' STRINGFREE(#name#_return_value);', 'need': ['F_FUNC', '#ctype#', 'STRINGFREE'], '_check': l_and(isstringfunction, l_not(isfunction_wrap))}, {'routdebugenter': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#(#docsignature#)\\n");', 'routdebugleave': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: successful.\\n");', 'routdebugfailure': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: failure.\\n");', '_check': debugcapi}] typedef_need_dict = {islong_long: 'long_long', islong_double: 'long_double', islong_complex: 'complex_long_double', isunsigned_char: 'unsigned_char', isunsigned_short: 'unsigned_short', isunsigned: 'unsigned', isunsigned_long_long: 'unsigned_long_long', isunsigned_chararray: 'unsigned_char', isunsigned_shortarray: 'unsigned_short', isunsigned_long_longarray: 'unsigned_long_long', issigned_long_longarray: 'long_long', isint1: 'signed_char', ischaracter_or_characterarray: 'character'} aux_rules = [{'separatorsfor': sepdict}, {'frompyobj': [' /* Processing auxiliary variable #varname# */', {debugcapi: ' fprintf(stderr,"#vardebuginfo#\\n");'}], 'cleanupfrompyobj': ' /* End of cleaning variable #varname# */', 'need': typedef_need_dict}, {'decl': ' #ctype# #varname# = 0;', 'need': {hasinitvalue: 'math.h'}, 'frompyobj': {hasinitvalue: ' #varname# = #init#;'}, '_check': l_and(isscalar, l_not(iscomplex))}, {'return': ',#varname#', 'docstrout': '#pydocsignout#', 'docreturn': '#outvarname#,', 'returnformat': '#varrformat#', '_check': l_and(isscalar, l_not(iscomplex), isintent_out)}, {'decl': ' #ctype# #varname#;', 'frompyobj': {hasinitvalue: ' #varname#.r = #init.r#, #varname#.i = #init.i#;'}, '_check': iscomplex}, {'decl': [' #ctype# #varname# = NULL;', ' int slen(#varname#);'], 'need': ['len..'], '_check': isstring}, {'decl': [' #ctype# *#varname# = NULL;', ' npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};', ' const int #varname#_Rank = #rank#;'], 'need': ['len..', {hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}], '_check': isarray}, {'_check': l_and(isarray, l_not(iscomplexarray))}, {'_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide)}, {'need': '#ctype#', '_check': isint1array, '_depend': ''}, {'need': '#ctype#', '_check': l_or(isunsigned_chararray, isunsigned_char), '_depend': ''}, {'need': '#ctype#', '_check': isunsigned_shortarray, '_depend': ''}, {'need': '#ctype#', '_check': isunsigned_long_longarray, '_depend': ''}, {'need': '#ctype#', '_check': iscomplexarray, '_depend': ''}, {'callfortranappend': {isarrayofstrings: 'flen(#varname#),'}, 'need': 'string', '_check': isstringarray}] arg_rules = [{'separatorsfor': sepdict}, {'frompyobj': [' /* Processing variable #varname# */', {debugcapi: ' fprintf(stderr,"#vardebuginfo#\\n");'}], 'cleanupfrompyobj': ' /* End of cleaning variable #varname# */', '_depend': '', 'need': typedef_need_dict}, {'docstropt': {l_and(isoptional, isintent_nothide): '#pydocsign#'}, 'docstrreq': {l_and(isrequired, isintent_nothide): '#pydocsign#'}, 'docstrout': {isintent_out: '#pydocsignout#'}, 'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote: '--- #note#'}]}, 'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote: '--- #note#'}]}, 'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}', {l_and(hasnote, isintent_hide): '--- #note#', l_and(hasnote, isintent_nothide): '--- See above.'}]}, 'depend': ''}, {'kwlist': '"#varname#",', 'docsign': '#varname#,', '_check': l_and(isintent_nothide, l_not(isoptional))}, {'kwlistopt': '"#varname#",', 'docsignopt': '#varname#=#showinit#,', 'docsignoptshort': '#varname#,', '_check': l_and(isintent_nothide, isoptional)}, {'docreturn': '#outvarname#,', 'returnformat': '#varrformat#', '_check': isintent_out}, {'docsignxa': {isintent_nothide: '#varname#_extra_args=(),'}, 'docsignxashort': {isintent_nothide: '#varname#_extra_args,'}, 'docstropt': {isintent_nothide: '#varname#_extra_args : input tuple, optional\\n Default: ()'}, 'docstrcbs': '#cbdocstr#', 'latexdocstrcbs': '\\item[] #cblatexdocstr#', 'latexdocstropt': {isintent_nothide: '\\item[]{{}\\verb@#varname#_extra_args := () input tuple@{}} --- Extra arguments for call-back function {{}\\verb@#varname#@{}}.'}, 'decl': [' #cbname#_t #varname#_cb = { Py_None, NULL, 0 };', ' #cbname#_t *#varname#_cb_ptr = &#varname#_cb;', ' PyTupleObject *#varname#_xa_capi = NULL;', {l_not(isintent_callback): ' #cbname#_typedef #varname#_cptr;'}], 'kwlistxa': {isintent_nothide: '"#varname#_extra_args",'}, 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'xaformat': {isintent_nothide: 'O!'}, 'args_capi': {isrequired: ',&#varname#_cb.capi'}, 'keys_capi': {isoptional: ',&#varname#_cb.capi'}, 'keys_xa': ',&PyTuple_Type,&#varname#_xa_capi', 'setjmpbuf': '(setjmp(#varname#_cb.jmpbuf))', 'callfortran': {l_not(isintent_callback): '#varname#_cptr,'}, 'need': ['#cbname#', 'setjmp.h'], '_check': isexternal}, {'frompyobj': [{l_not(isintent_callback): 'if(F2PyCapsule_Check(#varname#_cb.capi)) {\n #varname#_cptr = F2PyCapsule_AsVoidPtr(#varname#_cb.capi);\n} else {\n #varname#_cptr = #cbname#;\n}\n'}, {isintent_callback: 'if (#varname#_cb.capi==Py_None) {\n #varname#_cb.capi = PyObject_GetAttrString(#modulename#_module,"#varname#");\n if (#varname#_cb.capi) {\n if (#varname#_xa_capi==NULL) {\n if (PyObject_HasAttrString(#modulename#_module,"#varname#_extra_args")) {\n PyObject* capi_tmp = PyObject_GetAttrString(#modulename#_module,"#varname#_extra_args");\n if (capi_tmp) {\n #varname#_xa_capi = (PyTupleObject *)PySequence_Tuple(capi_tmp);\n Py_DECREF(capi_tmp);\n }\n else {\n #varname#_xa_capi = (PyTupleObject *)Py_BuildValue("()");\n }\n if (#varname#_xa_capi==NULL) {\n PyErr_SetString(#modulename#_error,"Failed to convert #modulename#.#varname#_extra_args to tuple.\\n");\n return NULL;\n }\n }\n }\n }\n if (#varname#_cb.capi==NULL) {\n PyErr_SetString(#modulename#_error,"Callback #varname# not defined (as an argument or module #modulename# attribute).\\n");\n return NULL;\n }\n}\n'}, ' if (create_cb_arglist(#varname#_cb.capi,#varname#_xa_capi,#maxnofargs#,#nofoptargs#,&#varname#_cb.nofargs,&#varname#_cb.args_capi,"failed in processing argument list for call-back #varname#.")) {\n', {debugcapi: [' fprintf(stderr,"debug-capi:Assuming %d arguments; at most #maxnofargs#(-#nofoptargs#) is expected.\\n",#varname#_cb.nofargs);\n CFUNCSMESSPY("for #varname#=",#varname#_cb.capi);', {l_not(isintent_callback): ' fprintf(stderr,"#vardebugshowvalue# (call-back in C).\\n",#cbname#);'}]}, ' CFUNCSMESS("Saving callback variables for `#varname#`.\\n");\n #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);'], 'cleanupfrompyobj': ' CFUNCSMESS("Restoring callback variables for `#varname#`.\\n");\n #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);\n Py_DECREF(#varname#_cb.args_capi);\n }', 'need': ['SWAP', 'create_cb_arglist'], '_check': isexternal, '_depend': ''}, {'decl': ' #ctype# #varname# = 0;', 'pyobjfrom': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'}, 'callfortran': {l_or(isintent_c, isattr_value): '#varname#,', l_not(l_or(isintent_c, isattr_value)): '&#varname#,'}, 'return': {isintent_out: ',#varname#'}, '_check': l_and(isscalar, l_not(iscomplex))}, {'need': {hasinitvalue: 'math.h'}, '_check': l_and(isscalar, l_not(iscomplex))}, {'decl': ' PyObject *#varname#_capi = Py_None;', 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, 'pyobjfrom': {isintent_inout: ' f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#);\n if (f2py_success) {'}, 'closepyobjfrom': {isintent_inout: ' } /*if (f2py_success) of #varname# pyobjfrom*/'}, 'need': {isintent_inout: 'try_pyarr_from_#ctype#'}, '_check': l_and(isscalar, l_not(iscomplex), l_not(isstring), isintent_nothide)}, {'frompyobj': [{hasinitvalue: ' if (#varname#_capi == Py_None) #varname# = #init#; else', '_depend': ''}, {l_and(isoptional, l_not(hasinitvalue)): ' if (#varname#_capi != Py_None)', '_depend': ''}, {l_not(islogical): ' f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");\n if (f2py_success) {'}, {islogical: ' #varname# = (#ctype#)PyObject_IsTrue(#varname#_capi);\n f2py_success = 1;\n if (f2py_success) {'}], 'cleanupfrompyobj': ' } /*if (f2py_success) of #varname#*/', 'need': {l_not(islogical): '#ctype#_from_pyobj'}, '_check': l_and(isscalar, l_not(iscomplex), isintent_nothide), '_depend': ''}, {'frompyobj': {hasinitvalue: ' #varname# = #init#;'}, 'need': typedef_need_dict, '_check': l_and(isscalar, l_not(iscomplex), isintent_hide), '_depend': ''}, {'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'}, '_check': l_and(isscalar, l_not(iscomplex)), '_depend': ''}, {'decl': ' #ctype# #varname#;', 'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'}, 'pyobjfrom': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'}, 'return': {isintent_out: ',#varname#_capi'}, '_check': iscomplex}, {'decl': ' PyObject *#varname#_capi = Py_None;', 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, 'need': {isintent_inout: 'try_pyarr_from_#ctype#'}, 'pyobjfrom': {isintent_inout: ' f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#);\n if (f2py_success) {'}, 'closepyobjfrom': {isintent_inout: ' } /*if (f2py_success) of #varname# pyobjfrom*/'}, '_check': l_and(iscomplex, isintent_nothide)}, {'frompyobj': [{hasinitvalue: ' if (#varname#_capi==Py_None) {#varname#.r = #init.r#, #varname#.i = #init.i#;} else'}, {l_and(isoptional, l_not(hasinitvalue)): ' if (#varname#_capi != Py_None)'}, ' f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");\n if (f2py_success) {'], 'cleanupfrompyobj': ' } /*if (f2py_success) of #varname# frompyobj*/', 'need': ['#ctype#_from_pyobj'], '_check': l_and(iscomplex, isintent_nothide), '_depend': ''}, {'decl': {isintent_out: ' PyObject *#varname#_capi = Py_None;'}, '_check': l_and(iscomplex, isintent_hide)}, {'frompyobj': {hasinitvalue: ' #varname#.r = #init.r#, #varname#.i = #init.i#;'}, '_check': l_and(iscomplex, isintent_hide), '_depend': ''}, {'pyobjfrom': {isintent_out: ' #varname#_capi = pyobj_from_#ctype#1(#varname#);'}, 'need': ['pyobj_from_#ctype#1'], '_check': iscomplex}, {'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'}, '_check': iscomplex, '_depend': ''}, {'decl': [' #ctype# #varname# = NULL;', ' int slen(#varname#);', ' PyObject *#varname#_capi = Py_None;'], 'callfortran': '#varname#,', 'callfortranappend': 'slen(#varname#),', 'pyobjfrom': [{debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'}, {l_and(isintent_out, l_not(isintent_c)): " STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"}], 'return': {isintent_out: ',#varname#'}, 'need': ['len..', {l_and(isintent_out, l_not(isintent_c)): 'STRINGPADN'}], '_check': isstring}, {'frompyobj': [' slen(#varname#) = #elsize#;\n f2py_success = #ctype#_from_pyobj(&#varname#,&slen(#varname#),#init#,#varname#_capi,"#ctype#_from_pyobj failed in converting #nth#`#varname#\' of #pyname# to C #ctype#");\n if (f2py_success) {', {l_not(isintent_c): " STRINGPADN(#varname#, slen(#varname#), '\\0', ' ');"}], 'cleanupfrompyobj': ' STRINGFREE(#varname#);\n } /*if (f2py_success) of #varname#*/', 'need': ['#ctype#_from_pyobj', 'len..', 'STRINGFREE', {l_not(isintent_c): 'STRINGPADN'}], '_check': isstring, '_depend': ''}, {'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, 'pyobjfrom': [{l_and(isintent_inout, l_not(isintent_c)): " STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"}, {isintent_inout: ' f2py_success = try_pyarr_from_#ctype#(#varname#_capi, #varname#,\n slen(#varname#));\n if (f2py_success) {'}], 'closepyobjfrom': {isintent_inout: ' } /*if (f2py_success) of #varname# pyobjfrom*/'}, 'need': {isintent_inout: 'try_pyarr_from_#ctype#', l_and(isintent_inout, l_not(isintent_c)): 'STRINGPADN'}, '_check': l_and(isstring, isintent_nothide)}, {'_check': l_and(isstring, isintent_hide)}, {'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'}, '_check': isstring, '_depend': ''}, {'decl': [' #ctype# *#varname# = NULL;', ' npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};', ' const int #varname#_Rank = #rank#;', ' PyArrayObject *capi_#varname#_as_array = NULL;', ' int capi_#varname#_intent = 0;', {isstringarray: ' int slen(#varname#) = 0;'}], 'callfortran': '#varname#,', 'callfortranappend': {isstringarray: 'slen(#varname#),'}, 'return': {isintent_out: ',capi_#varname#_as_array'}, 'need': 'len..', '_check': isarray}, {'decl': ' int capi_overwrite_#varname# = 1;', 'kwlistxa': '"overwrite_#varname#",', 'xaformat': 'i', 'keys_xa': ',&capi_overwrite_#varname#', 'docsignxa': 'overwrite_#varname#=1,', 'docsignxashort': 'overwrite_#varname#,', 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 1', '_check': l_and(isarray, isintent_overwrite)}, {'frompyobj': ' capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);', '_check': l_and(isarray, isintent_overwrite), '_depend': ''}, {'decl': ' int capi_overwrite_#varname# = 0;', 'kwlistxa': '"overwrite_#varname#",', 'xaformat': 'i', 'keys_xa': ',&capi_overwrite_#varname#', 'docsignxa': 'overwrite_#varname#=0,', 'docsignxashort': 'overwrite_#varname#,', 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 0', '_check': l_and(isarray, isintent_copy)}, {'frompyobj': ' capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);', '_check': l_and(isarray, isintent_copy), '_depend': ''}, {'need': [{hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}], '_check': isarray, '_depend': ''}, {'decl': ' PyObject *#varname#_capi = Py_None;', 'argformat': {isrequired: 'O'}, 'keyformat': {isoptional: 'O'}, 'args_capi': {isrequired: ',&#varname#_capi'}, 'keys_capi': {isoptional: ',&#varname#_capi'}, '_check': l_and(isarray, isintent_nothide)}, {'frompyobj': [' #setdims#;', ' capi_#varname#_intent |= #intent#;', ' const char * capi_errmess = "#modulename#.#pyname#: failed to create array from the #nth# `#varname#`";', {isintent_hide: ' capi_#varname#_as_array = ndarray_from_pyobj( #atype#,#elsize#,#varname#_Dims,#varname#_Rank, capi_#varname#_intent,Py_None,capi_errmess);'}, {isintent_nothide: ' capi_#varname#_as_array = ndarray_from_pyobj( #atype#,#elsize#,#varname#_Dims,#varname#_Rank, capi_#varname#_intent,#varname#_capi,capi_errmess);'}, ' if (capi_#varname#_as_array == NULL) {\n PyObject* capi_err = PyErr_Occurred();\n if (capi_err == NULL) {\n capi_err = #modulename#_error;\n PyErr_SetString(capi_err, capi_errmess);\n }\n } else {\n #varname# = (#ctype# *)(PyArray_DATA(capi_#varname#_as_array));\n', {isstringarray: ' slen(#varname#) = f2py_itemsize(#varname#);'}, {hasinitvalue: [{isintent_nothide: ' if (#varname#_capi == Py_None) {'}, {isintent_hide: ' {'}, {iscomplexarray: ' #ctype# capi_c;'}, ' int *_i,capi_i=0;\n CFUNCSMESS("#name#: Initializing #varname#=#init#\\n");\n if (initforcomb(PyArray_DIMS(capi_#varname#_as_array),\n PyArray_NDIM(capi_#varname#_as_array),1)) {\n while ((_i = nextforcomb()))\n #varname#[capi_i++] = #init#; /* fortran way */\n } else {\n PyObject *exc, *val, *tb;\n PyErr_Fetch(&exc, &val, &tb);\n PyErr_SetString(exc ? exc : #modulename#_error,\n "Initialization of #nth# #varname# failed (initforcomb).");\n npy_PyErr_ChainExceptionsCause(exc, val, tb);\n f2py_success = 0;\n }\n }\n if (f2py_success) {']}], 'cleanupfrompyobj': [' } /* if (capi_#varname#_as_array == NULL) ... else of #varname# */', {l_not(l_or(isintent_out, isintent_hide)): ' if((PyObject *)capi_#varname#_as_array!=#varname#_capi) {\n Py_XDECREF(capi_#varname#_as_array); }'}, {l_and(isintent_hide, l_not(isintent_out)): ' Py_XDECREF(capi_#varname#_as_array);'}, {hasinitvalue: ' } /*if (f2py_success) of #varname# init*/'}], '_check': isarray, '_depend': ''}, {'_check': l_and(isarray, l_not(iscomplexarray))}, {'_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide)}, {'need': '#ctype#', '_check': isint1array, '_depend': ''}, {'need': '#ctype#', '_check': isunsigned_chararray, '_depend': ''}, {'need': '#ctype#', '_check': isunsigned_shortarray, '_depend': ''}, {'need': '#ctype#', '_check': isunsigned_long_longarray, '_depend': ''}, {'need': '#ctype#', '_check': iscomplexarray, '_depend': ''}, {'need': 'string', '_check': ischaracter}, {'need': 'string', '_check': ischaracterarray}, {'callfortranappend': {isarrayofstrings: 'flen(#varname#),'}, 'need': 'string', '_check': isstringarray}] check_rules = [{'frompyobj': {debugcapi: ' fprintf(stderr,"debug-capi:Checking `#check#\'\\n");'}, 'need': 'len..'}, {'frompyobj': ' CHECKSCALAR(#check#,"#check#","#nth# #varname#","#varshowvalue#",#varname#) {', 'cleanupfrompyobj': ' } /*CHECKSCALAR(#check#)*/', 'need': 'CHECKSCALAR', '_check': l_and(isscalar, l_not(iscomplex)), '_break': ''}, {'frompyobj': ' CHECKSTRING(#check#,"#check#","#nth# #varname#","#varshowvalue#",#varname#) {', 'cleanupfrompyobj': ' } /*CHECKSTRING(#check#)*/', 'need': 'CHECKSTRING', '_check': isstring, '_break': ''}, {'need': 'CHECKARRAY', 'frompyobj': ' CHECKARRAY(#check#,"#check#","#nth# #varname#") {', 'cleanupfrompyobj': ' } /*CHECKARRAY(#check#)*/', '_check': isarray, '_break': ''}, {'need': 'CHECKGENERIC', 'frompyobj': ' CHECKGENERIC(#check#,"#check#","#nth# #varname#") {', 'cleanupfrompyobj': ' } /*CHECKGENERIC(#check#)*/'}] def buildmodule(m, um): outmess(' Building module "%s"...\n' % m['name']) ret = {} mod_rules = defmod_rules[:] vrd = capi_maps.modsign2map(m) rd = dictappend({'f2py_version': f2py_version}, vrd) funcwrappers = [] funcwrappers2 = [] for n in m['interfaced']: nb = None for bi in m['body']: if bi['block'] not in ['interface', 'abstract interface']: errmess('buildmodule: Expected interface block. Skipping.\n') continue for b in bi['body']: if b['name'] == n: nb = b break if not nb: print('buildmodule: Could not find the body of interfaced routine "%s". Skipping.\n' % n, file=sys.stderr) continue nb_list = [nb] if 'entry' in nb: for (k, a) in nb['entry'].items(): nb1 = copy.deepcopy(nb) del nb1['entry'] nb1['name'] = k nb1['args'] = a nb_list.append(nb1) for nb in nb_list: isf90 = requiresf90wrapper(nb) if options['emptygen']: b_path = options['buildpath'] m_name = vrd['modulename'] outmess(' Generating possibly empty wrappers"\n') Path(f"{b_path}/{vrd['coutput']}").touch() if isf90: outmess(f' Maybe empty "{m_name}-f2pywrappers2.f90"\n') Path(f'{b_path}/{m_name}-f2pywrappers2.f90').touch() outmess(f' Maybe empty "{m_name}-f2pywrappers.f"\n') Path(f'{b_path}/{m_name}-f2pywrappers.f').touch() else: outmess(f' Maybe empty "{m_name}-f2pywrappers.f"\n') Path(f'{b_path}/{m_name}-f2pywrappers.f').touch() (api, wrap) = buildapi(nb) if wrap: if isf90: funcwrappers2.append(wrap) else: funcwrappers.append(wrap) ar = applyrules(api, vrd) rd = dictappend(rd, ar) (cr, wrap) = common_rules.buildhooks(m) if wrap: funcwrappers.append(wrap) ar = applyrules(cr, vrd) rd = dictappend(rd, ar) (mr, wrap) = f90mod_rules.buildhooks(m) if wrap: funcwrappers2.append(wrap) ar = applyrules(mr, vrd) rd = dictappend(rd, ar) for u in um: ar = use_rules.buildusevars(u, m['use'][u['name']]) rd = dictappend(rd, ar) needs = cfuncs.get_needs() needs['typedefs'] += [cvar for cvar in capi_maps.f2cmap_mapped if cvar in typedef_need_dict.values()] code = {} for n in needs.keys(): code[n] = [] for k in needs[n]: c = '' if k in cfuncs.includes0: c = cfuncs.includes0[k] elif k in cfuncs.includes: c = cfuncs.includes[k] elif k in cfuncs.userincludes: c = cfuncs.userincludes[k] elif k in cfuncs.typedefs: c = cfuncs.typedefs[k] elif k in cfuncs.typedefs_generated: c = cfuncs.typedefs_generated[k] elif k in cfuncs.cppmacros: c = cfuncs.cppmacros[k] elif k in cfuncs.cfuncs: c = cfuncs.cfuncs[k] elif k in cfuncs.callbacks: c = cfuncs.callbacks[k] elif k in cfuncs.f90modhooks: c = cfuncs.f90modhooks[k] elif k in cfuncs.commonhooks: c = cfuncs.commonhooks[k] else: errmess('buildmodule: unknown need %s.\n' % repr(k)) continue code[n].append(c) mod_rules.append(code) for r in mod_rules: if '_check' in r and r['_check'](m) or '_check' not in r: ar = applyrules(r, vrd, m) rd = dictappend(rd, ar) ar = applyrules(module_rules, rd) fn = os.path.join(options['buildpath'], vrd['coutput']) ret['csrc'] = fn with open(fn, 'w') as f: f.write(ar['modulebody'].replace('\t', 2 * ' ')) outmess(' Wrote C/API module "%s" to file "%s"\n' % (m['name'], fn)) if options['dorestdoc']: fn = os.path.join(options['buildpath'], vrd['modulename'] + 'module.rest') with open(fn, 'w') as f: f.write('.. -*- rest -*-\n') f.write('\n'.join(ar['restdoc'])) outmess(' ReST Documentation is saved to file "%s/%smodule.rest"\n' % (options['buildpath'], vrd['modulename'])) if options['dolatexdoc']: fn = os.path.join(options['buildpath'], vrd['modulename'] + 'module.tex') ret['ltx'] = fn with open(fn, 'w') as f: f.write('%% This file is auto-generated with f2py (version:%s)\n' % f2py_version) if 'shortlatex' not in options: f.write('\\documentclass{article}\n\\usepackage{a4wide}\n\\begin{document}\n\\tableofcontents\n\n') f.write('\n'.join(ar['latexdoc'])) if 'shortlatex' not in options: f.write('\\end{document}') outmess(' Documentation is saved to file "%s/%smodule.tex"\n' % (options['buildpath'], vrd['modulename'])) if funcwrappers: wn = os.path.join(options['buildpath'], vrd['f2py_wrapper_output']) ret['fsrc'] = wn with open(wn, 'w') as f: f.write('C -*- fortran -*-\n') f.write('C This file is autogenerated with f2py (version:%s)\n' % f2py_version) f.write('C It contains Fortran 77 wrappers to fortran functions.\n') lines = [] for l in ('\n\n'.join(funcwrappers) + '\n').split('\n'): if 0 <= l.find('!') < 66: lines.append(l + '\n') elif l and l[0] == ' ': while len(l) >= 66: lines.append(l[:66] + '\n &') l = l[66:] lines.append(l + '\n') else: lines.append(l + '\n') lines = ''.join(lines).replace('\n &\n', '\n') f.write(lines) outmess(' Fortran 77 wrappers are saved to "%s"\n' % wn) if funcwrappers2: wn = os.path.join(options['buildpath'], '%s-f2pywrappers2.f90' % vrd['modulename']) ret['fsrc'] = wn with open(wn, 'w') as f: f.write('! -*- f90 -*-\n') f.write('! This file is autogenerated with f2py (version:%s)\n' % f2py_version) f.write('! It contains Fortran 90 wrappers to fortran functions.\n') lines = [] for l in ('\n\n'.join(funcwrappers2) + '\n').split('\n'): if 0 <= l.find('!') < 72: lines.append(l + '\n') elif len(l) > 72 and l[0] == ' ': lines.append(l[:72] + '&\n &') l = l[72:] while len(l) > 66: lines.append(l[:66] + '&\n &') l = l[66:] lines.append(l + '\n') else: lines.append(l + '\n') lines = ''.join(lines).replace('\n &\n', '\n') f.write(lines) outmess(' Fortran 90 wrappers are saved to "%s"\n' % wn) return ret stnd = {1: 'st', 2: 'nd', 3: 'rd', 4: 'th', 5: 'th', 6: 'th', 7: 'th', 8: 'th', 9: 'th', 0: 'th'} def buildapi(rout): (rout, wrap) = func2subr.assubr(rout) (args, depargs) = getargs2(rout) capi_maps.depargs = depargs var = rout['vars'] if ismoduleroutine(rout): outmess(' Constructing wrapper function "%s.%s"...\n' % (rout['modulename'], rout['name'])) else: outmess(' Constructing wrapper function "%s"...\n' % rout['name']) vrd = capi_maps.routsign2map(rout) rd = dictappend({}, vrd) for r in rout_rules: if '_check' in r and r['_check'](rout) or '_check' not in r: ar = applyrules(r, vrd, rout) rd = dictappend(rd, ar) (nth, nthk) = (0, 0) savevrd = {} for a in args: vrd = capi_maps.sign2map(a, var[a]) if isintent_aux(var[a]): _rules = aux_rules else: _rules = arg_rules if not isintent_hide(var[a]): if not isoptional(var[a]): nth = nth + 1 vrd['nth'] = repr(nth) + stnd[nth % 10] + ' argument' else: nthk = nthk + 1 vrd['nth'] = repr(nthk) + stnd[nthk % 10] + ' keyword' else: vrd['nth'] = 'hidden' savevrd[a] = vrd for r in _rules: if '_depend' in r: continue if '_check' in r and r['_check'](var[a]) or '_check' not in r: ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break for a in depargs: if isintent_aux(var[a]): _rules = aux_rules else: _rules = arg_rules vrd = savevrd[a] for r in _rules: if '_depend' not in r: continue if '_check' in r and r['_check'](var[a]) or '_check' not in r: ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break if 'check' in var[a]: for c in var[a]['check']: vrd['check'] = c ar = applyrules(check_rules, vrd, var[a]) rd = dictappend(rd, ar) if isinstance(rd['cleanupfrompyobj'], list): rd['cleanupfrompyobj'].reverse() if isinstance(rd['closepyobjfrom'], list): rd['closepyobjfrom'].reverse() rd['docsignature'] = stripcomma(replace('#docsign##docsignopt##docsignxa#', {'docsign': rd['docsign'], 'docsignopt': rd['docsignopt'], 'docsignxa': rd['docsignxa']})) optargs = stripcomma(replace('#docsignopt##docsignxa#', {'docsignxa': rd['docsignxashort'], 'docsignopt': rd['docsignoptshort']})) if optargs == '': rd['docsignatureshort'] = stripcomma(replace('#docsign#', {'docsign': rd['docsign']})) else: rd['docsignatureshort'] = replace('#docsign#[#docsignopt#]', {'docsign': rd['docsign'], 'docsignopt': optargs}) rd['latexdocsignatureshort'] = rd['docsignatureshort'].replace('_', '\\_') rd['latexdocsignatureshort'] = rd['latexdocsignatureshort'].replace(',', ', ') cfs = stripcomma(replace('#callfortran##callfortranappend#', {'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']})) if len(rd['callfortranappend']) > 1: rd['callcompaqfortran'] = stripcomma(replace('#callfortran# 0,#callfortranappend#', {'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']})) else: rd['callcompaqfortran'] = cfs rd['callfortran'] = cfs if isinstance(rd['docreturn'], list): rd['docreturn'] = stripcomma(replace('#docreturn#', {'docreturn': rd['docreturn']})) + ' = ' rd['docstrsigns'] = [] rd['latexdocstrsigns'] = [] for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']: if k in rd and isinstance(rd[k], list): rd['docstrsigns'] = rd['docstrsigns'] + rd[k] k = 'latex' + k if k in rd and isinstance(rd[k], list): rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] + ['\\begin{description}'] + rd[k][1:] + ['\\end{description}'] ar = applyrules(routine_rules, rd) if ismoduleroutine(rout): outmess(' %s\n' % ar['docshort']) else: outmess(' %s\n' % ar['docshort']) return (ar, wrap) # File: numpy-main/numpy/f2py/symbolic.py """""" __all__ = ['Expr'] import re import warnings from enum import Enum from math import gcd class Language(Enum): Python = 0 Fortran = 1 C = 2 class Op(Enum): INTEGER = 10 REAL = 12 COMPLEX = 15 STRING = 20 ARRAY = 30 SYMBOL = 40 TERNARY = 100 APPLY = 200 INDEXING = 210 CONCAT = 220 RELATIONAL = 300 TERMS = 1000 FACTORS = 2000 REF = 3000 DEREF = 3001 class RelOp(Enum): EQ = 1 NE = 2 LT = 3 LE = 4 GT = 5 GE = 6 @classmethod def fromstring(cls, s, language=Language.C): if language is Language.Fortran: return {'.eq.': RelOp.EQ, '.ne.': RelOp.NE, '.lt.': RelOp.LT, '.le.': RelOp.LE, '.gt.': RelOp.GT, '.ge.': RelOp.GE}[s.lower()] return {'==': RelOp.EQ, '!=': RelOp.NE, '<': RelOp.LT, '<=': RelOp.LE, '>': RelOp.GT, '>=': RelOp.GE}[s] def tostring(self, language=Language.C): if language is Language.Fortran: return {RelOp.EQ: '.eq.', RelOp.NE: '.ne.', RelOp.LT: '.lt.', RelOp.LE: '.le.', RelOp.GT: '.gt.', RelOp.GE: '.ge.'}[self] return {RelOp.EQ: '==', RelOp.NE: '!=', RelOp.LT: '<', RelOp.LE: '<=', RelOp.GT: '>', RelOp.GE: '>='}[self] class ArithOp(Enum): POS = 1 NEG = 2 ADD = 3 SUB = 4 MUL = 5 DIV = 6 POW = 7 class OpError(Exception): pass class Precedence(Enum): ATOM = 0 POWER = 1 UNARY = 2 PRODUCT = 3 SUM = 4 LT = 6 EQ = 7 LAND = 11 LOR = 12 TERNARY = 13 ASSIGN = 14 TUPLE = 15 NONE = 100 integer_types = (int,) number_types = (int, float) def _pairs_add(d, k, v): c = d.get(k) if c is None: d[k] = v else: c = c + v if c: d[k] = c else: del d[k] class ExprWarning(UserWarning): pass def ewarn(message): warnings.warn(message, ExprWarning, stacklevel=2) class Expr: @staticmethod def parse(s, language=Language.C): return fromstring(s, language=language) def __init__(self, op, data): assert isinstance(op, Op) if op is Op.INTEGER: assert isinstance(data, tuple) and len(data) == 2 assert isinstance(data[0], int) assert isinstance(data[1], (int, str)), data elif op is Op.REAL: assert isinstance(data, tuple) and len(data) == 2 assert isinstance(data[0], float) assert isinstance(data[1], (int, str)), data elif op is Op.COMPLEX: assert isinstance(data, tuple) and len(data) == 2 elif op is Op.STRING: assert isinstance(data, tuple) and len(data) == 2 assert isinstance(data[0], str) and data[0][::len(data[0]) - 1] in ('""', "''", '@@') assert isinstance(data[1], (int, str)), data elif op is Op.SYMBOL: assert hash(data) is not None elif op in (Op.ARRAY, Op.CONCAT): assert isinstance(data, tuple) assert all((isinstance(item, Expr) for item in data)), data elif op in (Op.TERMS, Op.FACTORS): assert isinstance(data, dict) elif op is Op.APPLY: assert isinstance(data, tuple) and len(data) == 3 assert hash(data[0]) is not None assert isinstance(data[1], tuple) assert isinstance(data[2], dict) elif op is Op.INDEXING: assert isinstance(data, tuple) and len(data) == 2 assert hash(data[0]) is not None elif op is Op.TERNARY: assert isinstance(data, tuple) and len(data) == 3 elif op in (Op.REF, Op.DEREF): assert isinstance(data, Expr) elif op is Op.RELATIONAL: assert isinstance(data, tuple) and len(data) == 3 else: raise NotImplementedError(f'unknown op or missing sanity check: {op}') self.op = op self.data = data def __eq__(self, other): return isinstance(other, Expr) and self.op is other.op and (self.data == other.data) def __hash__(self): if self.op in (Op.TERMS, Op.FACTORS): data = tuple(sorted(self.data.items())) elif self.op is Op.APPLY: data = self.data[:2] + tuple(sorted(self.data[2].items())) else: data = self.data return hash((self.op, data)) def __lt__(self, other): if isinstance(other, Expr): if self.op is not other.op: return self.op.value < other.op.value if self.op in (Op.TERMS, Op.FACTORS): return tuple(sorted(self.data.items())) < tuple(sorted(other.data.items())) if self.op is Op.APPLY: if self.data[:2] != other.data[:2]: return self.data[:2] < other.data[:2] return tuple(sorted(self.data[2].items())) < tuple(sorted(other.data[2].items())) return self.data < other.data return NotImplemented def __le__(self, other): return self == other or self < other def __gt__(self, other): return not self <= other def __ge__(self, other): return not self < other def __repr__(self): return f'{type(self).__name__}({self.op}, {self.data!r})' def __str__(self): return self.tostring() def tostring(self, parent_precedence=Precedence.NONE, language=Language.Fortran): if self.op in (Op.INTEGER, Op.REAL): precedence = Precedence.SUM if self.data[0] < 0 else Precedence.ATOM r = str(self.data[0]) + (f'_{self.data[1]}' if self.data[1] != 4 else '') elif self.op is Op.COMPLEX: r = ', '.join((item.tostring(Precedence.TUPLE, language=language) for item in self.data)) r = '(' + r + ')' precedence = Precedence.ATOM elif self.op is Op.SYMBOL: precedence = Precedence.ATOM r = str(self.data) elif self.op is Op.STRING: r = self.data[0] if self.data[1] != 1: r = self.data[1] + '_' + r precedence = Precedence.ATOM elif self.op is Op.ARRAY: r = ', '.join((item.tostring(Precedence.TUPLE, language=language) for item in self.data)) r = '[' + r + ']' precedence = Precedence.ATOM elif self.op is Op.TERMS: terms = [] for (term, coeff) in sorted(self.data.items()): if coeff < 0: op = ' - ' coeff = -coeff else: op = ' + ' if coeff == 1: term = term.tostring(Precedence.SUM, language=language) elif term == as_number(1): term = str(coeff) else: term = f'{coeff} * ' + term.tostring(Precedence.PRODUCT, language=language) if terms: terms.append(op) elif op == ' - ': terms.append('-') terms.append(term) r = ''.join(terms) or '0' precedence = Precedence.SUM if terms else Precedence.ATOM elif self.op is Op.FACTORS: factors = [] tail = [] for (base, exp) in sorted(self.data.items()): op = ' * ' if exp == 1: factor = base.tostring(Precedence.PRODUCT, language=language) elif language is Language.C: if exp in range(2, 10): factor = base.tostring(Precedence.PRODUCT, language=language) factor = ' * '.join([factor] * exp) elif exp in range(-10, 0): factor = base.tostring(Precedence.PRODUCT, language=language) tail += [factor] * -exp continue else: factor = base.tostring(Precedence.TUPLE, language=language) factor = f'pow({factor}, {exp})' else: factor = base.tostring(Precedence.POWER, language=language) + f' ** {exp}' if factors: factors.append(op) factors.append(factor) if tail: if not factors: factors += ['1'] factors += ['/', '(', ' * '.join(tail), ')'] r = ''.join(factors) or '1' precedence = Precedence.PRODUCT if factors else Precedence.ATOM elif self.op is Op.APPLY: (name, args, kwargs) = self.data if name is ArithOp.DIV and language is Language.C: (numer, denom) = [arg.tostring(Precedence.PRODUCT, language=language) for arg in args] r = f'{numer} / {denom}' precedence = Precedence.PRODUCT else: args = [arg.tostring(Precedence.TUPLE, language=language) for arg in args] args += [k + '=' + v.tostring(Precedence.NONE) for (k, v) in kwargs.items()] r = f"{name}({', '.join(args)})" precedence = Precedence.ATOM elif self.op is Op.INDEXING: name = self.data[0] args = [arg.tostring(Precedence.TUPLE, language=language) for arg in self.data[1:]] r = f"{name}[{', '.join(args)}]" precedence = Precedence.ATOM elif self.op is Op.CONCAT: args = [arg.tostring(Precedence.PRODUCT, language=language) for arg in self.data] r = ' // '.join(args) precedence = Precedence.PRODUCT elif self.op is Op.TERNARY: (cond, expr1, expr2) = [a.tostring(Precedence.TUPLE, language=language) for a in self.data] if language is Language.C: r = f'({cond}?{expr1}:{expr2})' elif language is Language.Python: r = f'({expr1} if {cond} else {expr2})' elif language is Language.Fortran: r = f'merge({expr1}, {expr2}, {cond})' else: raise NotImplementedError(f'tostring for {self.op} and {language}') precedence = Precedence.ATOM elif self.op is Op.REF: r = '&' + self.data.tostring(Precedence.UNARY, language=language) precedence = Precedence.UNARY elif self.op is Op.DEREF: r = '*' + self.data.tostring(Precedence.UNARY, language=language) precedence = Precedence.UNARY elif self.op is Op.RELATIONAL: (rop, left, right) = self.data precedence = Precedence.EQ if rop in (RelOp.EQ, RelOp.NE) else Precedence.LT left = left.tostring(precedence, language=language) right = right.tostring(precedence, language=language) rop = rop.tostring(language=language) r = f'{left} {rop} {right}' else: raise NotImplementedError(f'tostring for op {self.op}') if parent_precedence.value < precedence.value: return '(' + r + ')' return r def __pos__(self): return self def __neg__(self): return self * -1 def __add__(self, other): other = as_expr(other) if isinstance(other, Expr): if self.op is other.op: if self.op in (Op.INTEGER, Op.REAL): return as_number(self.data[0] + other.data[0], max(self.data[1], other.data[1])) if self.op is Op.COMPLEX: (r1, i1) = self.data (r2, i2) = other.data return as_complex(r1 + r2, i1 + i2) if self.op is Op.TERMS: r = Expr(self.op, dict(self.data)) for (k, v) in other.data.items(): _pairs_add(r.data, k, v) return normalize(r) if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL): return self + as_complex(other) elif self.op in (Op.INTEGER, Op.REAL) and other.op is Op.COMPLEX: return as_complex(self) + other elif self.op is Op.REAL and other.op is Op.INTEGER: return self + as_real(other, kind=self.data[1]) elif self.op is Op.INTEGER and other.op is Op.REAL: return as_real(self, kind=other.data[1]) + other return as_terms(self) + as_terms(other) return NotImplemented def __radd__(self, other): if isinstance(other, number_types): return as_number(other) + self return NotImplemented def __sub__(self, other): return self + -other def __rsub__(self, other): if isinstance(other, number_types): return as_number(other) - self return NotImplemented def __mul__(self, other): other = as_expr(other) if isinstance(other, Expr): if self.op is other.op: if self.op in (Op.INTEGER, Op.REAL): return as_number(self.data[0] * other.data[0], max(self.data[1], other.data[1])) elif self.op is Op.COMPLEX: (r1, i1) = self.data (r2, i2) = other.data return as_complex(r1 * r2 - i1 * i2, r1 * i2 + r2 * i1) if self.op is Op.FACTORS: r = Expr(self.op, dict(self.data)) for (k, v) in other.data.items(): _pairs_add(r.data, k, v) return normalize(r) elif self.op is Op.TERMS: r = Expr(self.op, {}) for (t1, c1) in self.data.items(): for (t2, c2) in other.data.items(): _pairs_add(r.data, t1 * t2, c1 * c2) return normalize(r) if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL): return self * as_complex(other) elif other.op is Op.COMPLEX and self.op in (Op.INTEGER, Op.REAL): return as_complex(self) * other elif self.op is Op.REAL and other.op is Op.INTEGER: return self * as_real(other, kind=self.data[1]) elif self.op is Op.INTEGER and other.op is Op.REAL: return as_real(self, kind=other.data[1]) * other if self.op is Op.TERMS: return self * as_terms(other) elif other.op is Op.TERMS: return as_terms(self) * other return as_factors(self) * as_factors(other) return NotImplemented def __rmul__(self, other): if isinstance(other, number_types): return as_number(other) * self return NotImplemented def __pow__(self, other): other = as_expr(other) if isinstance(other, Expr): if other.op is Op.INTEGER: exponent = other.data[0] if exponent == 0: return as_number(1) if exponent == 1: return self if exponent > 0: if self.op is Op.FACTORS: r = Expr(self.op, {}) for (k, v) in self.data.items(): r.data[k] = v * exponent return normalize(r) return self * self ** (exponent - 1) elif exponent != -1: return (self ** (-exponent)) ** (-1) return Expr(Op.FACTORS, {self: exponent}) return as_apply(ArithOp.POW, self, other) return NotImplemented def __truediv__(self, other): other = as_expr(other) if isinstance(other, Expr): return normalize(as_apply(ArithOp.DIV, self, other)) return NotImplemented def __rtruediv__(self, other): other = as_expr(other) if isinstance(other, Expr): return other / self return NotImplemented def __floordiv__(self, other): other = as_expr(other) if isinstance(other, Expr): return normalize(Expr(Op.CONCAT, (self, other))) return NotImplemented def __rfloordiv__(self, other): other = as_expr(other) if isinstance(other, Expr): return other // self return NotImplemented def __call__(self, *args, **kwargs): return as_apply(self, *map(as_expr, args), **dict(((k, as_expr(v)) for (k, v) in kwargs.items()))) def __getitem__(self, index): index = as_expr(index) if not isinstance(index, tuple): index = (index,) if len(index) > 1: ewarn(f'C-index should be a single expression but got `{index}`') return Expr(Op.INDEXING, (self,) + index) def substitute(self, symbols_map): if self.op is Op.SYMBOL: value = symbols_map.get(self) if value is None: return self m = re.match('\\A(@__f2py_PARENTHESIS_(\\w+)_\\d+@)\\Z', self.data) if m: (items, paren) = m.groups() if paren in ['ROUNDDIV', 'SQUARE']: return as_array(value) assert paren == 'ROUND', (paren, value) return value if self.op in (Op.INTEGER, Op.REAL, Op.STRING): return self if self.op in (Op.ARRAY, Op.COMPLEX): return Expr(self.op, tuple((item.substitute(symbols_map) for item in self.data))) if self.op is Op.CONCAT: return normalize(Expr(self.op, tuple((item.substitute(symbols_map) for item in self.data)))) if self.op is Op.TERMS: r = None for (term, coeff) in self.data.items(): if r is None: r = term.substitute(symbols_map) * coeff else: r += term.substitute(symbols_map) * coeff if r is None: ewarn('substitute: empty TERMS expression interpreted as int-literal 0') return as_number(0) return r if self.op is Op.FACTORS: r = None for (base, exponent) in self.data.items(): if r is None: r = base.substitute(symbols_map) ** exponent else: r *= base.substitute(symbols_map) ** exponent if r is None: ewarn('substitute: empty FACTORS expression interpreted as int-literal 1') return as_number(1) return r if self.op is Op.APPLY: (target, args, kwargs) = self.data if isinstance(target, Expr): target = target.substitute(symbols_map) args = tuple((a.substitute(symbols_map) for a in args)) kwargs = dict(((k, v.substitute(symbols_map)) for (k, v) in kwargs.items())) return normalize(Expr(self.op, (target, args, kwargs))) if self.op is Op.INDEXING: func = self.data[0] if isinstance(func, Expr): func = func.substitute(symbols_map) args = tuple((a.substitute(symbols_map) for a in self.data[1:])) return normalize(Expr(self.op, (func,) + args)) if self.op is Op.TERNARY: operands = tuple((a.substitute(symbols_map) for a in self.data)) return normalize(Expr(self.op, operands)) if self.op in (Op.REF, Op.DEREF): return normalize(Expr(self.op, self.data.substitute(symbols_map))) if self.op is Op.RELATIONAL: (rop, left, right) = self.data left = left.substitute(symbols_map) right = right.substitute(symbols_map) return normalize(Expr(self.op, (rop, left, right))) raise NotImplementedError(f'substitute method for {self.op}: {self!r}') def traverse(self, visit, *args, **kwargs): result = visit(self, *args, **kwargs) if result is not None: return result if self.op in (Op.INTEGER, Op.REAL, Op.STRING, Op.SYMBOL): return self elif self.op in (Op.COMPLEX, Op.ARRAY, Op.CONCAT, Op.TERNARY): return normalize(Expr(self.op, tuple((item.traverse(visit, *args, **kwargs) for item in self.data)))) elif self.op in (Op.TERMS, Op.FACTORS): data = {} for (k, v) in self.data.items(): k = k.traverse(visit, *args, **kwargs) v = v.traverse(visit, *args, **kwargs) if isinstance(v, Expr) else v if k in data: v = data[k] + v data[k] = v return normalize(Expr(self.op, data)) elif self.op is Op.APPLY: obj = self.data[0] func = obj.traverse(visit, *args, **kwargs) if isinstance(obj, Expr) else obj operands = tuple((operand.traverse(visit, *args, **kwargs) for operand in self.data[1])) kwoperands = dict(((k, v.traverse(visit, *args, **kwargs)) for (k, v) in self.data[2].items())) return normalize(Expr(self.op, (func, operands, kwoperands))) elif self.op is Op.INDEXING: obj = self.data[0] obj = obj.traverse(visit, *args, **kwargs) if isinstance(obj, Expr) else obj indices = tuple((index.traverse(visit, *args, **kwargs) for index in self.data[1:])) return normalize(Expr(self.op, (obj,) + indices)) elif self.op in (Op.REF, Op.DEREF): return normalize(Expr(self.op, self.data.traverse(visit, *args, **kwargs))) elif self.op is Op.RELATIONAL: (rop, left, right) = self.data left = left.traverse(visit, *args, **kwargs) right = right.traverse(visit, *args, **kwargs) return normalize(Expr(self.op, (rop, left, right))) raise NotImplementedError(f'traverse method for {self.op}') def contains(self, other): found = [] def visit(expr, found=found): if found: return expr elif expr == other: found.append(1) return expr self.traverse(visit) return len(found) != 0 def symbols(self): found = set() def visit(expr, found=found): if expr.op is Op.SYMBOL: found.add(expr) self.traverse(visit) return found def polynomial_atoms(self): found = set() def visit(expr, found=found): if expr.op is Op.FACTORS: for b in expr.data: b.traverse(visit) return expr if expr.op in (Op.TERMS, Op.COMPLEX): return if expr.op is Op.APPLY and isinstance(expr.data[0], ArithOp): if expr.data[0] is ArithOp.POW: expr.data[1][0].traverse(visit) return expr return if expr.op in (Op.INTEGER, Op.REAL): return expr found.add(expr) if expr.op in (Op.INDEXING, Op.APPLY): return expr self.traverse(visit) return found def linear_solve(self, symbol): b = self.substitute({symbol: as_number(0)}) ax = self - b a = ax.substitute({symbol: as_number(1)}) (zero, _) = as_numer_denom(a * symbol - ax) if zero != as_number(0): raise RuntimeError(f'not a {symbol}-linear equation: {a} * {symbol} + {b} == {self}') return (a, b) def normalize(obj): if not isinstance(obj, Expr): return obj if obj.op is Op.TERMS: d = {} for (t, c) in obj.data.items(): if c == 0: continue if t.op is Op.COMPLEX and c != 1: t = t * c c = 1 if t.op is Op.TERMS: for (t1, c1) in t.data.items(): _pairs_add(d, t1, c1 * c) else: _pairs_add(d, t, c) if len(d) == 0: return as_number(0) elif len(d) == 1: ((t, c),) = d.items() if c == 1: return t return Expr(Op.TERMS, d) if obj.op is Op.FACTORS: coeff = 1 d = {} for (b, e) in obj.data.items(): if e == 0: continue if b.op is Op.TERMS and isinstance(e, integer_types) and (e > 1): b = b * b ** (e - 1) e = 1 if b.op in (Op.INTEGER, Op.REAL): if e == 1: coeff *= b.data[0] elif e > 0: coeff *= b.data[0] ** e else: _pairs_add(d, b, e) elif b.op is Op.FACTORS: if e > 0 and isinstance(e, integer_types): for (b1, e1) in b.data.items(): _pairs_add(d, b1, e1 * e) else: _pairs_add(d, b, e) else: _pairs_add(d, b, e) if len(d) == 0 or coeff == 0: assert isinstance(coeff, number_types) return as_number(coeff) elif len(d) == 1: ((b, e),) = d.items() if e == 1: t = b else: t = Expr(Op.FACTORS, d) if coeff == 1: return t return Expr(Op.TERMS, {t: coeff}) elif coeff == 1: return Expr(Op.FACTORS, d) else: return Expr(Op.TERMS, {Expr(Op.FACTORS, d): coeff}) if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV: (dividend, divisor) = obj.data[1] (t1, c1) = as_term_coeff(dividend) (t2, c2) = as_term_coeff(divisor) if isinstance(c1, integer_types) and isinstance(c2, integer_types): g = gcd(c1, c2) (c1, c2) = (c1 // g, c2 // g) else: (c1, c2) = (c1 / c2, 1) if t1.op is Op.APPLY and t1.data[0] is ArithOp.DIV: numer = t1.data[1][0] * c1 denom = t1.data[1][1] * t2 * c2 return as_apply(ArithOp.DIV, numer, denom) if t2.op is Op.APPLY and t2.data[0] is ArithOp.DIV: numer = t2.data[1][1] * t1 * c1 denom = t2.data[1][0] * c2 return as_apply(ArithOp.DIV, numer, denom) d = dict(as_factors(t1).data) for (b, e) in as_factors(t2).data.items(): _pairs_add(d, b, -e) (numer, denom) = ({}, {}) for (b, e) in d.items(): if e > 0: numer[b] = e else: denom[b] = -e numer = normalize(Expr(Op.FACTORS, numer)) * c1 denom = normalize(Expr(Op.FACTORS, denom)) * c2 if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] == 1: return numer return as_apply(ArithOp.DIV, numer, denom) if obj.op is Op.CONCAT: lst = [obj.data[0]] for s in obj.data[1:]: last = lst[-1] if last.op is Op.STRING and s.op is Op.STRING and (last.data[0][0] in '"\'') and (s.data[0][0] == last.data[0][-1]): new_last = as_string(last.data[0][:-1] + s.data[0][1:], max(last.data[1], s.data[1])) lst[-1] = new_last else: lst.append(s) if len(lst) == 1: return lst[0] return Expr(Op.CONCAT, tuple(lst)) if obj.op is Op.TERNARY: (cond, expr1, expr2) = map(normalize, obj.data) if cond.op is Op.INTEGER: return expr1 if cond.data[0] else expr2 return Expr(Op.TERNARY, (cond, expr1, expr2)) return obj def as_expr(obj): if isinstance(obj, complex): return as_complex(obj.real, obj.imag) if isinstance(obj, number_types): return as_number(obj) if isinstance(obj, str): return as_string(repr(obj)) if isinstance(obj, tuple): return tuple(map(as_expr, obj)) return obj def as_symbol(obj): return Expr(Op.SYMBOL, obj) def as_number(obj, kind=4): if isinstance(obj, int): return Expr(Op.INTEGER, (obj, kind)) if isinstance(obj, float): return Expr(Op.REAL, (obj, kind)) if isinstance(obj, Expr): if obj.op in (Op.INTEGER, Op.REAL): return obj raise OpError(f'cannot convert {obj} to INTEGER or REAL constant') def as_integer(obj, kind=4): if isinstance(obj, int): return Expr(Op.INTEGER, (obj, kind)) if isinstance(obj, Expr): if obj.op is Op.INTEGER: return obj raise OpError(f'cannot convert {obj} to INTEGER constant') def as_real(obj, kind=4): if isinstance(obj, int): return Expr(Op.REAL, (float(obj), kind)) if isinstance(obj, float): return Expr(Op.REAL, (obj, kind)) if isinstance(obj, Expr): if obj.op is Op.REAL: return obj elif obj.op is Op.INTEGER: return Expr(Op.REAL, (float(obj.data[0]), kind)) raise OpError(f'cannot convert {obj} to REAL constant') def as_string(obj, kind=1): return Expr(Op.STRING, (obj, kind)) def as_array(obj): if isinstance(obj, Expr): obj = (obj,) return Expr(Op.ARRAY, obj) def as_complex(real, imag=0): return Expr(Op.COMPLEX, (as_expr(real), as_expr(imag))) def as_apply(func, *args, **kwargs): return Expr(Op.APPLY, (func, tuple(map(as_expr, args)), dict(((k, as_expr(v)) for (k, v) in kwargs.items())))) def as_ternary(cond, expr1, expr2): return Expr(Op.TERNARY, (cond, expr1, expr2)) def as_ref(expr): return Expr(Op.REF, expr) def as_deref(expr): return Expr(Op.DEREF, expr) def as_eq(left, right): return Expr(Op.RELATIONAL, (RelOp.EQ, left, right)) def as_ne(left, right): return Expr(Op.RELATIONAL, (RelOp.NE, left, right)) def as_lt(left, right): return Expr(Op.RELATIONAL, (RelOp.LT, left, right)) def as_le(left, right): return Expr(Op.RELATIONAL, (RelOp.LE, left, right)) def as_gt(left, right): return Expr(Op.RELATIONAL, (RelOp.GT, left, right)) def as_ge(left, right): return Expr(Op.RELATIONAL, (RelOp.GE, left, right)) def as_terms(obj): if isinstance(obj, Expr): obj = normalize(obj) if obj.op is Op.TERMS: return obj if obj.op is Op.INTEGER: return Expr(Op.TERMS, {as_integer(1, obj.data[1]): obj.data[0]}) if obj.op is Op.REAL: return Expr(Op.TERMS, {as_real(1, obj.data[1]): obj.data[0]}) return Expr(Op.TERMS, {obj: 1}) raise OpError(f'cannot convert {type(obj)} to terms Expr') def as_factors(obj): if isinstance(obj, Expr): obj = normalize(obj) if obj.op is Op.FACTORS: return obj if obj.op is Op.TERMS: if len(obj.data) == 1: ((term, coeff),) = obj.data.items() if coeff == 1: return Expr(Op.FACTORS, {term: 1}) return Expr(Op.FACTORS, {term: 1, Expr.number(coeff): 1}) if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV and (not obj.data[2]): return Expr(Op.FACTORS, {obj.data[1][0]: 1, obj.data[1][1]: -1}) return Expr(Op.FACTORS, {obj: 1}) raise OpError(f'cannot convert {type(obj)} to terms Expr') def as_term_coeff(obj): if isinstance(obj, Expr): obj = normalize(obj) if obj.op is Op.INTEGER: return (as_integer(1, obj.data[1]), obj.data[0]) if obj.op is Op.REAL: return (as_real(1, obj.data[1]), obj.data[0]) if obj.op is Op.TERMS: if len(obj.data) == 1: ((term, coeff),) = obj.data.items() return (term, coeff) if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV: (t, c) = as_term_coeff(obj.data[1][0]) return (as_apply(ArithOp.DIV, t, obj.data[1][1]), c) return (obj, 1) raise OpError(f'cannot convert {type(obj)} to term and coeff') def as_numer_denom(obj): if isinstance(obj, Expr): obj = normalize(obj) if obj.op in (Op.INTEGER, Op.REAL, Op.COMPLEX, Op.SYMBOL, Op.INDEXING, Op.TERNARY): return (obj, as_number(1)) elif obj.op is Op.APPLY: if obj.data[0] is ArithOp.DIV and (not obj.data[2]): (numers, denoms) = map(as_numer_denom, obj.data[1]) return (numers[0] * denoms[1], numers[1] * denoms[0]) return (obj, as_number(1)) elif obj.op is Op.TERMS: (numers, denoms) = ([], []) for (term, coeff) in obj.data.items(): (n, d) = as_numer_denom(term) n = n * coeff numers.append(n) denoms.append(d) (numer, denom) = (as_number(0), as_number(1)) for i in range(len(numers)): n = numers[i] for j in range(len(numers)): if i != j: n *= denoms[j] numer += n denom *= denoms[i] if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] < 0: (numer, denom) = (-numer, -denom) return (numer, denom) elif obj.op is Op.FACTORS: (numer, denom) = (as_number(1), as_number(1)) for (b, e) in obj.data.items(): (bnumer, bdenom) = as_numer_denom(b) if e > 0: numer *= bnumer ** e denom *= bdenom ** e elif e < 0: numer *= bdenom ** (-e) denom *= bnumer ** (-e) return (numer, denom) raise OpError(f'cannot convert {type(obj)} to numer and denom') def _counter(): counter = 0 while True: counter += 1 yield counter COUNTER = _counter() def eliminate_quotes(s): d = {} def repl(m): (kind, value) = m.groups()[:2] if kind: kind = kind[:-1] p = {"'": 'SINGLE', '"': 'DOUBLE'}[value[0]] k = f'{kind}@__f2py_QUOTES_{p}_{COUNTER.__next__()}@' d[k] = value return k new_s = re.sub('({kind}_|)({single_quoted}|{double_quoted})'.format(kind='\\w[\\w\\d_]*', single_quoted="('([^'\\\\]|(\\\\.))*')", double_quoted='("([^"\\\\]|(\\\\.))*")'), repl, s) assert '"' not in new_s assert "'" not in new_s return (new_s, d) def insert_quotes(s, d): for (k, v) in d.items(): kind = k[:k.find('@')] if kind: kind += '_' s = s.replace(k, kind + v) return s def replace_parenthesis(s): (left, right) = (None, None) mn_i = len(s) for (left_, right_) in (('(/', '/)'), '()', '{}', '[]'): i = s.find(left_) if i == -1: continue if i < mn_i: mn_i = i (left, right) = (left_, right_) if left is None: return (s, {}) i = mn_i j = s.find(right, i) while s.count(left, i + 1, j) != s.count(right, i + 1, j): j = s.find(right, j + 1) if j == -1: raise ValueError(f'Mismatch of {left + right} parenthesis in {s!r}') p = {'(': 'ROUND', '[': 'SQUARE', '{': 'CURLY', '(/': 'ROUNDDIV'}[left] k = f'@__f2py_PARENTHESIS_{p}_{COUNTER.__next__()}@' v = s[i + len(left):j] (r, d) = replace_parenthesis(s[j + len(right):]) d[k] = v return (s[:i] + k + r, d) def _get_parenthesis_kind(s): assert s.startswith('@__f2py_PARENTHESIS_'), s return s.split('_')[4] def unreplace_parenthesis(s, d): for (k, v) in d.items(): p = _get_parenthesis_kind(k) left = dict(ROUND='(', SQUARE='[', CURLY='{', ROUNDDIV='(/')[p] right = dict(ROUND=')', SQUARE=']', CURLY='}', ROUNDDIV='/)')[p] s = s.replace(k, left + v + right) return s def fromstring(s, language=Language.C): r = _FromStringWorker(language=language).parse(s) if isinstance(r, Expr): return r raise ValueError(f'failed to parse `{s}` to Expr instance: got `{r}`') class _Pair: def __init__(self, left, right): self.left = left self.right = right def substitute(self, symbols_map): (left, right) = (self.left, self.right) if isinstance(left, Expr): left = left.substitute(symbols_map) if isinstance(right, Expr): right = right.substitute(symbols_map) return _Pair(left, right) def __repr__(self): return f'{type(self).__name__}({self.left}, {self.right})' class _FromStringWorker: def __init__(self, language=Language.C): self.original = None self.quotes_map = None self.language = language def finalize_string(self, s): return insert_quotes(s, self.quotes_map) def parse(self, inp): self.original = inp (unquoted, self.quotes_map) = eliminate_quotes(inp) return self.process(unquoted) def process(self, s, context='expr'): if isinstance(s, (list, tuple)): return type(s)((self.process(s_, context) for s_ in s)) assert isinstance(s, str), (type(s), s) (r, raw_symbols_map) = replace_parenthesis(s) r = r.strip() def restore(r): if isinstance(r, (list, tuple)): return type(r)(map(restore, r)) return unreplace_parenthesis(r, raw_symbols_map) if ',' in r: operands = restore(r.split(',')) if context == 'args': return tuple(self.process(operands)) if context == 'expr': if len(operands) == 2: return as_complex(*self.process(operands)) raise NotImplementedError(f'parsing comma-separated list (context={context}): {r}') m = re.match('\\A([^?]+)[?]([^:]+)[:](.+)\\Z', r) if m: assert context == 'expr', context (oper, expr1, expr2) = restore(m.groups()) oper = self.process(oper) expr1 = self.process(expr1) expr2 = self.process(expr2) return as_ternary(oper, expr1, expr2) if self.language is Language.Fortran: m = re.match('\\A(.+)\\s*[.](eq|ne|lt|le|gt|ge)[.]\\s*(.+)\\Z', r, re.I) else: m = re.match('\\A(.+)\\s*([=][=]|[!][=]|[<][=]|[<]|[>][=]|[>])\\s*(.+)\\Z', r) if m: (left, rop, right) = m.groups() if self.language is Language.Fortran: rop = '.' + rop + '.' (left, right) = self.process(restore((left, right))) rop = RelOp.fromstring(rop, language=self.language) return Expr(Op.RELATIONAL, (rop, left, right)) m = re.match('\\A(\\w[\\w\\d_]*)\\s*[=](.*)\\Z', r) if m: (keyname, value) = m.groups() value = restore(value) return _Pair(keyname, self.process(value)) operands = re.split('((? 1: result = self.process(restore(operands[0] or '0')) for (op, operand) in zip(operands[1::2], operands[2::2]): operand = self.process(restore(operand)) op = op.strip() if op == '+': result += operand else: assert op == '-' result -= operand return result if self.language is Language.Fortran and '//' in r: operands = restore(r.split('//')) return Expr(Op.CONCAT, tuple(self.process(operands))) operands = re.split('(?<=[@\\w\\d_])\\s*([*]|/)', r if self.language is Language.C else r.replace('**', '@__f2py_DOUBLE_STAR@')) if len(operands) > 1: operands = restore(operands) if self.language is not Language.C: operands = [operand.replace('@__f2py_DOUBLE_STAR@', '**') for operand in operands] result = self.process(operands[0]) for (op, operand) in zip(operands[1::2], operands[2::2]): operand = self.process(operand) op = op.strip() if op == '*': result *= operand else: assert op == '/' result /= operand return result if r.startswith(('*', '&')): op = {'*': Op.DEREF, '&': Op.REF}[r[0]] operand = self.process(restore(r[1:])) return Expr(op, operand) if self.language is not Language.C and '**' in r: operands = list(reversed(restore(r.split('**')))) result = self.process(operands[0]) for operand in operands[1:]: operand = self.process(operand) result = operand ** result return result m = re.match('\\A({digit_string})({kind}|)\\Z'.format(digit_string='\\d+', kind='_(\\d+|\\w[\\w\\d_]*)'), r) if m: (value, _, kind) = m.groups() if kind and kind.isdigit(): kind = int(kind) return as_integer(int(value), kind or 4) m = re.match('\\A({significant}({exponent}|)|\\d+{exponent})({kind}|)\\Z'.format(significant='[.]\\d+|\\d+[.]\\d*', exponent='[edED][+-]?\\d+', kind='_(\\d+|\\w[\\w\\d_]*)'), r) if m: (value, _, _, kind) = m.groups() if kind and kind.isdigit(): kind = int(kind) value = value.lower() if 'd' in value: return as_real(float(value.replace('d', 'e')), kind or 8) return as_real(float(value), kind or 4) if r in self.quotes_map: kind = r[:r.find('@')] return as_string(self.quotes_map[r], kind or 1) if r in raw_symbols_map: paren = _get_parenthesis_kind(r) items = self.process(restore(raw_symbols_map[r]), 'expr' if paren == 'ROUND' else 'args') if paren == 'ROUND': if isinstance(items, Expr): return items if paren in ['ROUNDDIV', 'SQUARE']: if isinstance(items, Expr): items = (items,) return as_array(items) m = re.match('\\A(.+)\\s*(@__f2py_PARENTHESIS_(ROUND|SQUARE)_\\d+@)\\Z', r) if m: (target, args, paren) = m.groups() target = self.process(restore(target)) args = self.process(restore(args)[1:-1], 'args') if not isinstance(args, tuple): args = (args,) if paren == 'ROUND': kwargs = dict(((a.left, a.right) for a in args if isinstance(a, _Pair))) args = tuple((a for a in args if not isinstance(a, _Pair))) return as_apply(target, *args, **kwargs) else: assert paren == 'SQUARE' return target[args] m = re.match('\\A\\w[\\w\\d_]*\\Z', r) if m: return as_symbol(r) r = self.finalize_string(restore(r)) ewarn(f'fromstring: treating {r!r} as symbol (original={self.original})') return as_symbol(r) # File: numpy-main/numpy/f2py/use_rules.py """""" __version__ = '$Revision: 1.3 $'[10:-1] f2py_version = 'See `f2py -v`' from .auxfuncs import applyrules, dictappend, gentitle, hasnote, outmess usemodule_rules = {'body': '\n#begintitle#\nstatic char doc_#apiname#[] = "\\\nVariable wrapper signature:\\n\\\n\t #name# = get_#name#()\\n\\\nArguments:\\n\\\n#docstr#";\nextern F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#);\nstatic PyObject *#apiname#(PyObject *capi_self, PyObject *capi_args) {\n/*#decl#*/\n\tif (!PyArg_ParseTuple(capi_args, "")) goto capi_fail;\nprintf("c: %d\\n",F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#));\n\treturn Py_BuildValue("");\ncapi_fail:\n\treturn NULL;\n}\n', 'method': '\t{"get_#name#",#apiname#,METH_VARARGS|METH_KEYWORDS,doc_#apiname#},', 'need': ['F_MODFUNC']} def buildusevars(m, r): ret = {} outmess('\t\tBuilding use variable hooks for module "%s" (feature only for F90/F95)...\n' % m['name']) varsmap = {} revmap = {} if 'map' in r: for k in r['map'].keys(): if r['map'][k] in revmap: outmess('\t\t\tVariable "%s<=%s" is already mapped by "%s". Skipping.\n' % (r['map'][k], k, revmap[r['map'][k]])) else: revmap[r['map'][k]] = k if r.get('only'): for v in r['map'].keys(): if r['map'][v] in m['vars']: if revmap[r['map'][v]] == v: varsmap[v] = r['map'][v] else: outmess('\t\t\tIgnoring map "%s=>%s". See above.\n' % (v, r['map'][v])) else: outmess('\t\t\tNo definition for variable "%s=>%s". Skipping.\n' % (v, r['map'][v])) else: for v in m['vars'].keys(): if v in revmap: varsmap[v] = revmap[v] else: varsmap[v] = v for v in varsmap.keys(): ret = dictappend(ret, buildusevar(v, varsmap[v], m['vars'], m['name'])) return ret def buildusevar(name, realname, vars, usemodulename): outmess('\t\t\tConstructing wrapper function for variable "%s=>%s"...\n' % (name, realname)) ret = {} vrd = {'name': name, 'realname': realname, 'REALNAME': realname.upper(), 'usemodulename': usemodulename, 'USEMODULENAME': usemodulename.upper(), 'texname': name.replace('_', '\\_'), 'begintitle': gentitle('%s=>%s' % (name, realname)), 'endtitle': gentitle('end of %s=>%s' % (name, realname)), 'apiname': '#modulename#_use_%s_from_%s' % (realname, usemodulename)} nummap = {0: 'Ro', 1: 'Ri', 2: 'Rii', 3: 'Riii', 4: 'Riv', 5: 'Rv', 6: 'Rvi', 7: 'Rvii', 8: 'Rviii', 9: 'Rix'} vrd['texnamename'] = name for i in nummap.keys(): vrd['texnamename'] = vrd['texnamename'].replace(repr(i), nummap[i]) if hasnote(vars[realname]): vrd['note'] = vars[realname]['note'] rd = dictappend({}, vrd) print(name, realname, vars[realname]) ret = applyrules(usemodule_rules, rd) return ret # File: numpy-main/numpy/fft/__init__.py """""" from . import _pocketfft, _helper from . import helper from ._pocketfft import * from ._helper import * __all__ = _pocketfft.__all__.copy() __all__ += _helper.__all__ from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester # File: numpy-main/numpy/fft/_helper.py """""" from numpy._core import integer, empty, arange, asarray, roll from numpy._core.overrides import array_function_dispatch, set_module __all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq'] integer_types = (int, integer) def _fftshift_dispatcher(x, axes=None): return (x,) @array_function_dispatch(_fftshift_dispatcher, module='numpy.fft') def fftshift(x, axes=None): x = asarray(x) if axes is None: axes = tuple(range(x.ndim)) shift = [dim // 2 for dim in x.shape] elif isinstance(axes, integer_types): shift = x.shape[axes] // 2 else: shift = [x.shape[ax] // 2 for ax in axes] return roll(x, shift, axes) @array_function_dispatch(_fftshift_dispatcher, module='numpy.fft') def ifftshift(x, axes=None): x = asarray(x) if axes is None: axes = tuple(range(x.ndim)) shift = [-(dim // 2) for dim in x.shape] elif isinstance(axes, integer_types): shift = -(x.shape[axes] // 2) else: shift = [-(x.shape[ax] // 2) for ax in axes] return roll(x, shift, axes) @set_module('numpy.fft') def fftfreq(n, d=1.0, device=None): if not isinstance(n, integer_types): raise ValueError('n should be an integer') val = 1.0 / (n * d) results = empty(n, int, device=device) N = (n - 1) // 2 + 1 p1 = arange(0, N, dtype=int, device=device) results[:N] = p1 p2 = arange(-(n // 2), 0, dtype=int, device=device) results[N:] = p2 return results * val @set_module('numpy.fft') def rfftfreq(n, d=1.0, device=None): if not isinstance(n, integer_types): raise ValueError('n should be an integer') val = 1.0 / (n * d) N = n // 2 + 1 results = arange(0, N, dtype=int, device=device) return results * val # File: numpy-main/numpy/fft/_pocketfft.py """""" __all__ = ['fft', 'ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn', 'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn'] import functools import warnings from numpy.lib.array_utils import normalize_axis_index from numpy._core import asarray, empty_like, result_type, conjugate, take, sqrt, reciprocal from . import _pocketfft_umath as pfu from numpy._core import overrides array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy.fft') def _raw_fft(a, n, axis, is_real, is_forward, norm, out=None): if n < 1: raise ValueError(f'Invalid number of FFT data points ({n}) specified.') if not is_forward: norm = _swap_direction(norm) real_dtype = result_type(a.real.dtype, 1.0) if norm is None or norm == 'backward': fct = 1 elif norm == 'ortho': fct = reciprocal(sqrt(n, dtype=real_dtype)) elif norm == 'forward': fct = reciprocal(n, dtype=real_dtype) else: raise ValueError(f'Invalid norm value {norm}; should be "backward","ortho" or "forward".') n_out = n if is_real: if is_forward: ufunc = pfu.rfft_n_even if n % 2 == 0 else pfu.rfft_n_odd n_out = n // 2 + 1 else: ufunc = pfu.irfft else: ufunc = pfu.fft if is_forward else pfu.ifft axis = normalize_axis_index(axis, a.ndim) if out is None: if is_real and (not is_forward): out_dtype = real_dtype else: out_dtype = result_type(a.dtype, 1j) out = empty_like(a, shape=a.shape[:axis] + (n_out,) + a.shape[axis + 1:], dtype=out_dtype) elif (shape := getattr(out, 'shape', None)) is not None and (len(shape) != a.ndim or shape[axis] != n_out): raise ValueError('output array has wrong shape.') return ufunc(a, fct, axes=[(axis,), (), (axis,)], out=out) _SWAP_DIRECTION_MAP = {'backward': 'forward', None: 'forward', 'ortho': 'ortho', 'forward': 'backward'} def _swap_direction(norm): try: return _SWAP_DIRECTION_MAP[norm] except KeyError: raise ValueError(f'Invalid norm value {norm}; should be "backward", "ortho" or "forward".') from None def _fft_dispatcher(a, n=None, axis=None, norm=None, out=None): return (a, out) @array_function_dispatch(_fft_dispatcher) def fft(a, n=None, axis=-1, norm=None, out=None): a = asarray(a) if n is None: n = a.shape[axis] output = _raw_fft(a, n, axis, False, True, norm, out) return output @array_function_dispatch(_fft_dispatcher) def ifft(a, n=None, axis=-1, norm=None, out=None): a = asarray(a) if n is None: n = a.shape[axis] output = _raw_fft(a, n, axis, False, False, norm, out=out) return output @array_function_dispatch(_fft_dispatcher) def rfft(a, n=None, axis=-1, norm=None, out=None): a = asarray(a) if n is None: n = a.shape[axis] output = _raw_fft(a, n, axis, True, True, norm, out=out) return output @array_function_dispatch(_fft_dispatcher) def irfft(a, n=None, axis=-1, norm=None, out=None): a = asarray(a) if n is None: n = (a.shape[axis] - 1) * 2 output = _raw_fft(a, n, axis, True, False, norm, out=out) return output @array_function_dispatch(_fft_dispatcher) def hfft(a, n=None, axis=-1, norm=None, out=None): a = asarray(a) if n is None: n = (a.shape[axis] - 1) * 2 new_norm = _swap_direction(norm) output = irfft(conjugate(a), n, axis, norm=new_norm, out=None) return output @array_function_dispatch(_fft_dispatcher) def ihfft(a, n=None, axis=-1, norm=None, out=None): a = asarray(a) if n is None: n = a.shape[axis] new_norm = _swap_direction(norm) out = rfft(a, n, axis, norm=new_norm, out=out) return conjugate(out, out=out) def _cook_nd_args(a, s=None, axes=None, invreal=0): if s is None: shapeless = True if axes is None: s = list(a.shape) else: s = take(a.shape, axes) else: shapeless = False s = list(s) if axes is None: if not shapeless: msg = '`axes` should not be `None` if `s` is not `None` (Deprecated in NumPy 2.0). In a future version of NumPy, this will raise an error and `s[i]` will correspond to the size along the transformed axis specified by `axes[i]`. To retain current behaviour, pass a sequence [0, ..., k-1] to `axes` for an array of dimension k.' warnings.warn(msg, DeprecationWarning, stacklevel=3) axes = list(range(-len(s), 0)) if len(s) != len(axes): raise ValueError('Shape and axes have different lengths.') if invreal and shapeless: s[-1] = (a.shape[axes[-1]] - 1) * 2 if None in s: msg = 'Passing an array containing `None` values to `s` is deprecated in NumPy 2.0 and will raise an error in a future version of NumPy. To use the default behaviour of the corresponding 1-D transform, pass the value matching the default for its `n` parameter. To use the default behaviour for every axis, the `s` argument can be omitted.' warnings.warn(msg, DeprecationWarning, stacklevel=3) s = [a.shape[_a] if _s == -1 else _s for (_s, _a) in zip(s, axes)] return (s, axes) def _raw_fftnd(a, s=None, axes=None, function=fft, norm=None, out=None): a = asarray(a) (s, axes) = _cook_nd_args(a, s, axes) itl = list(range(len(axes))) itl.reverse() for ii in itl: a = function(a, n=s[ii], axis=axes[ii], norm=norm, out=out) return a def _fftn_dispatcher(a, s=None, axes=None, norm=None, out=None): return (a, out) @array_function_dispatch(_fftn_dispatcher) def fftn(a, s=None, axes=None, norm=None, out=None): return _raw_fftnd(a, s, axes, fft, norm, out=out) @array_function_dispatch(_fftn_dispatcher) def ifftn(a, s=None, axes=None, norm=None, out=None): return _raw_fftnd(a, s, axes, ifft, norm, out=out) @array_function_dispatch(_fftn_dispatcher) def fft2(a, s=None, axes=(-2, -1), norm=None, out=None): return _raw_fftnd(a, s, axes, fft, norm, out=out) @array_function_dispatch(_fftn_dispatcher) def ifft2(a, s=None, axes=(-2, -1), norm=None, out=None): return _raw_fftnd(a, s, axes, ifft, norm, out=None) @array_function_dispatch(_fftn_dispatcher) def rfftn(a, s=None, axes=None, norm=None, out=None): a = asarray(a) (s, axes) = _cook_nd_args(a, s, axes) a = rfft(a, s[-1], axes[-1], norm, out=out) for ii in range(len(axes) - 1): a = fft(a, s[ii], axes[ii], norm, out=out) return a @array_function_dispatch(_fftn_dispatcher) def rfft2(a, s=None, axes=(-2, -1), norm=None, out=None): return rfftn(a, s, axes, norm, out=out) @array_function_dispatch(_fftn_dispatcher) def irfftn(a, s=None, axes=None, norm=None, out=None): a = asarray(a) (s, axes) = _cook_nd_args(a, s, axes, invreal=1) for ii in range(len(axes) - 1): a = ifft(a, s[ii], axes[ii], norm) a = irfft(a, s[-1], axes[-1], norm, out=out) return a @array_function_dispatch(_fftn_dispatcher) def irfft2(a, s=None, axes=(-2, -1), norm=None, out=None): return irfftn(a, s, axes, norm, out=None) # File: numpy-main/numpy/fft/helper.py def __getattr__(attr_name): import warnings from numpy.fft import _helper ret = getattr(_helper, attr_name, None) if ret is None: raise AttributeError(f"module 'numpy.fft.helper' has no attribute {attr_name}") warnings.warn(f'The numpy.fft.helper has been made private and renamed to numpy.fft._helper. All four functions exported by it (i.e. fftshift, ifftshift, fftfreq, rfftfreq) are available from numpy.fft. Please use numpy.fft.{attr_name} instead.', DeprecationWarning, stacklevel=3) return ret # File: numpy-main/numpy/lib/__init__.py """""" from . import array_utils from . import introspect from . import mixins from . import npyio from . import scimath from . import stride_tricks from . import _type_check_impl from . import _index_tricks_impl from . import _nanfunctions_impl from . import _function_base_impl from . import _stride_tricks_impl from . import _shape_base_impl from . import _twodim_base_impl from . import _ufunclike_impl from . import _histograms_impl from . import _utils_impl from . import _arraysetops_impl from . import _polynomial_impl from . import _npyio_impl from . import _arrayterator_impl from . import _arraypad_impl from . import _version from ._arrayterator_impl import Arrayterator from ._version import NumpyVersion from numpy._core._multiarray_umath import add_docstring, tracemalloc_domain from numpy._core.function_base import add_newdoc __all__ = ['Arrayterator', 'add_docstring', 'add_newdoc', 'array_utils', 'introspect', 'mixins', 'NumpyVersion', 'npyio', 'scimath', 'stride_tricks', 'tracemalloc_domain'] from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester def __getattr__(attr): import math import warnings if attr == 'math': warnings.warn('`np.lib.math` is a deprecated alias for the standard library `math` module (Deprecated Numpy 1.25). Replace usages of `numpy.lib.math` with `math`', DeprecationWarning, stacklevel=2) return math elif attr == 'emath': raise AttributeError('numpy.lib.emath was an alias for emath module that was removed in NumPy 2.0. Replace usages of numpy.lib.emath with numpy.emath.', name=None) elif attr in ('histograms', 'type_check', 'nanfunctions', 'function_base', 'arraypad', 'arraysetops', 'ufunclike', 'utils', 'twodim_base', 'shape_base', 'polynomial', 'index_tricks'): raise AttributeError(f'numpy.lib.{attr} is now private. If you are using a public function, it should be available in the main numpy namespace, otherwise check the NumPy 2.0 migration guide.', name=None) elif attr == 'arrayterator': raise AttributeError('numpy.lib.arrayterator submodule is now private. To access Arrayterator class use numpy.lib.Arrayterator.', name=None) else: raise AttributeError('module {!r} has no attribute {!r}'.format(__name__, attr)) # File: numpy-main/numpy/lib/_array_utils_impl.py """""" from numpy._core import asarray from numpy._core.numeric import normalize_axis_tuple, normalize_axis_index from numpy._utils import set_module __all__ = ['byte_bounds', 'normalize_axis_tuple', 'normalize_axis_index'] @set_module('numpy.lib.array_utils') def byte_bounds(a): ai = a.__array_interface__ a_data = ai['data'][0] astrides = ai['strides'] ashape = ai['shape'] bytes_a = asarray(a).dtype.itemsize a_low = a_high = a_data if astrides is None: a_high += a.size * bytes_a else: for (shape, stride) in zip(ashape, astrides): if stride < 0: a_low += (shape - 1) * stride else: a_high += (shape - 1) * stride a_high += bytes_a return (a_low, a_high) # File: numpy-main/numpy/lib/_arraypad_impl.py """""" import numpy as np from numpy._core.overrides import array_function_dispatch from numpy.lib._index_tricks_impl import ndindex __all__ = ['pad'] def _round_if_needed(arr, dtype): if np.issubdtype(dtype, np.integer): arr.round(out=arr) def _slice_at_axis(sl, axis): return (slice(None),) * axis + (sl,) + (...,) def _view_roi(array, original_area_slice, axis): axis += 1 sl = (slice(None),) * axis + original_area_slice[axis:] return array[sl] def _pad_simple(array, pad_width, fill_value=None): new_shape = tuple((left + size + right for (size, (left, right)) in zip(array.shape, pad_width))) order = 'F' if array.flags.fnc else 'C' padded = np.empty(new_shape, dtype=array.dtype, order=order) if fill_value is not None: padded.fill(fill_value) original_area_slice = tuple((slice(left, left + size) for (size, (left, right)) in zip(array.shape, pad_width))) padded[original_area_slice] = array return (padded, original_area_slice) def _set_pad_area(padded, axis, width_pair, value_pair): left_slice = _slice_at_axis(slice(None, width_pair[0]), axis) padded[left_slice] = value_pair[0] right_slice = _slice_at_axis(slice(padded.shape[axis] - width_pair[1], None), axis) padded[right_slice] = value_pair[1] def _get_edges(padded, axis, width_pair): left_index = width_pair[0] left_slice = _slice_at_axis(slice(left_index, left_index + 1), axis) left_edge = padded[left_slice] right_index = padded.shape[axis] - width_pair[1] right_slice = _slice_at_axis(slice(right_index - 1, right_index), axis) right_edge = padded[right_slice] return (left_edge, right_edge) def _get_linear_ramps(padded, axis, width_pair, end_value_pair): edge_pair = _get_edges(padded, axis, width_pair) (left_ramp, right_ramp) = (np.linspace(start=end_value, stop=edge.squeeze(axis), num=width, endpoint=False, dtype=padded.dtype, axis=axis) for (end_value, edge, width) in zip(end_value_pair, edge_pair, width_pair)) right_ramp = right_ramp[_slice_at_axis(slice(None, None, -1), axis)] return (left_ramp, right_ramp) def _get_stats(padded, axis, width_pair, length_pair, stat_func): left_index = width_pair[0] right_index = padded.shape[axis] - width_pair[1] max_length = right_index - left_index (left_length, right_length) = length_pair if left_length is None or max_length < left_length: left_length = max_length if right_length is None or max_length < right_length: right_length = max_length if (left_length == 0 or right_length == 0) and stat_func in {np.amax, np.amin}: raise ValueError('stat_length of 0 yields no value for padding') left_slice = _slice_at_axis(slice(left_index, left_index + left_length), axis) left_chunk = padded[left_slice] left_stat = stat_func(left_chunk, axis=axis, keepdims=True) _round_if_needed(left_stat, padded.dtype) if left_length == right_length == max_length: return (left_stat, left_stat) right_slice = _slice_at_axis(slice(right_index - right_length, right_index), axis) right_chunk = padded[right_slice] right_stat = stat_func(right_chunk, axis=axis, keepdims=True) _round_if_needed(right_stat, padded.dtype) return (left_stat, right_stat) def _set_reflect_both(padded, axis, width_pair, method, original_period, include_edge=False): (left_pad, right_pad) = width_pair old_length = padded.shape[axis] - right_pad - left_pad if include_edge: old_length = old_length // original_period * original_period edge_offset = 1 else: old_length = (old_length - 1) // (original_period - 1) * (original_period - 1) + 1 edge_offset = 0 old_length -= 1 if left_pad > 0: chunk_length = min(old_length, left_pad) stop = left_pad - edge_offset start = stop + chunk_length left_slice = _slice_at_axis(slice(start, stop, -1), axis) left_chunk = padded[left_slice] if method == 'odd': edge_slice = _slice_at_axis(slice(left_pad, left_pad + 1), axis) left_chunk = 2 * padded[edge_slice] - left_chunk start = left_pad - chunk_length stop = left_pad pad_area = _slice_at_axis(slice(start, stop), axis) padded[pad_area] = left_chunk left_pad -= chunk_length if right_pad > 0: chunk_length = min(old_length, right_pad) start = -right_pad + edge_offset - 2 stop = start - chunk_length right_slice = _slice_at_axis(slice(start, stop, -1), axis) right_chunk = padded[right_slice] if method == 'odd': edge_slice = _slice_at_axis(slice(-right_pad - 1, -right_pad), axis) right_chunk = 2 * padded[edge_slice] - right_chunk start = padded.shape[axis] - right_pad stop = start + chunk_length pad_area = _slice_at_axis(slice(start, stop), axis) padded[pad_area] = right_chunk right_pad -= chunk_length return (left_pad, right_pad) def _set_wrap_both(padded, axis, width_pair, original_period): (left_pad, right_pad) = width_pair period = padded.shape[axis] - right_pad - left_pad period = period // original_period * original_period new_left_pad = 0 new_right_pad = 0 if left_pad > 0: slice_end = left_pad + period slice_start = slice_end - min(period, left_pad) right_slice = _slice_at_axis(slice(slice_start, slice_end), axis) right_chunk = padded[right_slice] if left_pad > period: pad_area = _slice_at_axis(slice(left_pad - period, left_pad), axis) new_left_pad = left_pad - period else: pad_area = _slice_at_axis(slice(None, left_pad), axis) padded[pad_area] = right_chunk if right_pad > 0: slice_start = -right_pad - period slice_end = slice_start + min(period, right_pad) left_slice = _slice_at_axis(slice(slice_start, slice_end), axis) left_chunk = padded[left_slice] if right_pad > period: pad_area = _slice_at_axis(slice(-right_pad, -right_pad + period), axis) new_right_pad = right_pad - period else: pad_area = _slice_at_axis(slice(-right_pad, None), axis) padded[pad_area] = left_chunk return (new_left_pad, new_right_pad) def _as_pairs(x, ndim, as_index=False): if x is None: return ((None, None),) * ndim x = np.array(x) if as_index: x = np.round(x).astype(np.intp, copy=False) if x.ndim < 3: if x.size == 1: x = x.ravel() if as_index and x < 0: raise ValueError("index can't contain negative values") return ((x[0], x[0]),) * ndim if x.size == 2 and x.shape != (2, 1): x = x.ravel() if as_index and (x[0] < 0 or x[1] < 0): raise ValueError("index can't contain negative values") return ((x[0], x[1]),) * ndim if as_index and x.min() < 0: raise ValueError("index can't contain negative values") return np.broadcast_to(x, (ndim, 2)).tolist() def _pad_dispatcher(array, pad_width, mode=None, **kwargs): return (array,) @array_function_dispatch(_pad_dispatcher, module='numpy') def pad(array, pad_width, mode='constant', **kwargs): array = np.asarray(array) pad_width = np.asarray(pad_width) if not pad_width.dtype.kind == 'i': raise TypeError('`pad_width` must be of integral type.') pad_width = _as_pairs(pad_width, array.ndim, as_index=True) if callable(mode): function = mode (padded, _) = _pad_simple(array, pad_width, fill_value=0) for axis in range(padded.ndim): view = np.moveaxis(padded, axis, -1) inds = ndindex(view.shape[:-1]) inds = (ind + (Ellipsis,) for ind in inds) for ind in inds: function(view[ind], pad_width[axis], axis, kwargs) return padded allowed_kwargs = {'empty': [], 'edge': [], 'wrap': [], 'constant': ['constant_values'], 'linear_ramp': ['end_values'], 'maximum': ['stat_length'], 'mean': ['stat_length'], 'median': ['stat_length'], 'minimum': ['stat_length'], 'reflect': ['reflect_type'], 'symmetric': ['reflect_type']} try: unsupported_kwargs = set(kwargs) - set(allowed_kwargs[mode]) except KeyError: raise ValueError("mode '{}' is not supported".format(mode)) from None if unsupported_kwargs: raise ValueError("unsupported keyword arguments for mode '{}': {}".format(mode, unsupported_kwargs)) stat_functions = {'maximum': np.amax, 'minimum': np.amin, 'mean': np.mean, 'median': np.median} (padded, original_area_slice) = _pad_simple(array, pad_width) axes = range(padded.ndim) if mode == 'constant': values = kwargs.get('constant_values', 0) values = _as_pairs(values, padded.ndim) for (axis, width_pair, value_pair) in zip(axes, pad_width, values): roi = _view_roi(padded, original_area_slice, axis) _set_pad_area(roi, axis, width_pair, value_pair) elif mode == 'empty': pass elif array.size == 0: for (axis, width_pair) in zip(axes, pad_width): if array.shape[axis] == 0 and any(width_pair): raise ValueError("can't extend empty axis {} using modes other than 'constant' or 'empty'".format(axis)) elif mode == 'edge': for (axis, width_pair) in zip(axes, pad_width): roi = _view_roi(padded, original_area_slice, axis) edge_pair = _get_edges(roi, axis, width_pair) _set_pad_area(roi, axis, width_pair, edge_pair) elif mode == 'linear_ramp': end_values = kwargs.get('end_values', 0) end_values = _as_pairs(end_values, padded.ndim) for (axis, width_pair, value_pair) in zip(axes, pad_width, end_values): roi = _view_roi(padded, original_area_slice, axis) ramp_pair = _get_linear_ramps(roi, axis, width_pair, value_pair) _set_pad_area(roi, axis, width_pair, ramp_pair) elif mode in stat_functions: func = stat_functions[mode] length = kwargs.get('stat_length', None) length = _as_pairs(length, padded.ndim, as_index=True) for (axis, width_pair, length_pair) in zip(axes, pad_width, length): roi = _view_roi(padded, original_area_slice, axis) stat_pair = _get_stats(roi, axis, width_pair, length_pair, func) _set_pad_area(roi, axis, width_pair, stat_pair) elif mode in {'reflect', 'symmetric'}: method = kwargs.get('reflect_type', 'even') include_edge = mode == 'symmetric' for (axis, (left_index, right_index)) in zip(axes, pad_width): if array.shape[axis] == 1 and (left_index > 0 or right_index > 0): edge_pair = _get_edges(padded, axis, (left_index, right_index)) _set_pad_area(padded, axis, (left_index, right_index), edge_pair) continue roi = _view_roi(padded, original_area_slice, axis) while left_index > 0 or right_index > 0: (left_index, right_index) = _set_reflect_both(roi, axis, (left_index, right_index), method, array.shape[axis], include_edge) elif mode == 'wrap': for (axis, (left_index, right_index)) in zip(axes, pad_width): roi = _view_roi(padded, original_area_slice, axis) original_period = padded.shape[axis] - right_index - left_index while left_index > 0 or right_index > 0: (left_index, right_index) = _set_wrap_both(roi, axis, (left_index, right_index), original_period) return padded # File: numpy-main/numpy/lib/_arraysetops_impl.py """""" import functools import warnings from typing import NamedTuple import numpy as np from numpy._core import overrides from numpy._core._multiarray_umath import _array_converter array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') __all__ = ['ediff1d', 'in1d', 'intersect1d', 'isin', 'setdiff1d', 'setxor1d', 'union1d', 'unique', 'unique_all', 'unique_counts', 'unique_inverse', 'unique_values'] def _ediff1d_dispatcher(ary, to_end=None, to_begin=None): return (ary, to_end, to_begin) @array_function_dispatch(_ediff1d_dispatcher) def ediff1d(ary, to_end=None, to_begin=None): conv = _array_converter(ary) ary = conv[0].ravel() dtype_req = ary.dtype if to_begin is None and to_end is None: return ary[1:] - ary[:-1] if to_begin is None: l_begin = 0 else: to_begin = np.asanyarray(to_begin) if not np.can_cast(to_begin, dtype_req, casting='same_kind'): raise TypeError('dtype of `to_begin` must be compatible with input `ary` under the `same_kind` rule.') to_begin = to_begin.ravel() l_begin = len(to_begin) if to_end is None: l_end = 0 else: to_end = np.asanyarray(to_end) if not np.can_cast(to_end, dtype_req, casting='same_kind'): raise TypeError('dtype of `to_end` must be compatible with input `ary` under the `same_kind` rule.') to_end = to_end.ravel() l_end = len(to_end) l_diff = max(len(ary) - 1, 0) result = np.empty_like(ary, shape=l_diff + l_begin + l_end) if l_begin > 0: result[:l_begin] = to_begin if l_end > 0: result[l_begin + l_diff:] = to_end np.subtract(ary[1:], ary[:-1], result[l_begin:l_begin + l_diff]) return conv.wrap(result) def _unpack_tuple(x): if len(x) == 1: return x[0] else: return x def _unique_dispatcher(ar, return_index=None, return_inverse=None, return_counts=None, axis=None, *, equal_nan=None): return (ar,) @array_function_dispatch(_unique_dispatcher) def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, *, equal_nan=True): ar = np.asanyarray(ar) if axis is None: ret = _unique1d(ar, return_index, return_inverse, return_counts, equal_nan=equal_nan, inverse_shape=ar.shape, axis=None) return _unpack_tuple(ret) try: ar = np.moveaxis(ar, axis, 0) except np.exceptions.AxisError: raise np.exceptions.AxisError(axis, ar.ndim) from None inverse_shape = [1] * ar.ndim inverse_shape[axis] = ar.shape[0] (orig_shape, orig_dtype) = (ar.shape, ar.dtype) ar = ar.reshape(orig_shape[0], np.prod(orig_shape[1:], dtype=np.intp)) ar = np.ascontiguousarray(ar) dtype = [('f{i}'.format(i=i), ar.dtype) for i in range(ar.shape[1])] try: if ar.shape[1] > 0: consolidated = ar.view(dtype) else: consolidated = np.empty(len(ar), dtype=dtype) except TypeError as e: msg = 'The axis argument to unique is not supported for dtype {dt}' raise TypeError(msg.format(dt=ar.dtype)) from e def reshape_uniq(uniq): n = len(uniq) uniq = uniq.view(orig_dtype) uniq = uniq.reshape(n, *orig_shape[1:]) uniq = np.moveaxis(uniq, 0, axis) return uniq output = _unique1d(consolidated, return_index, return_inverse, return_counts, equal_nan=equal_nan, inverse_shape=inverse_shape, axis=axis) output = (reshape_uniq(output[0]),) + output[1:] return _unpack_tuple(output) def _unique1d(ar, return_index=False, return_inverse=False, return_counts=False, *, equal_nan=True, inverse_shape=None, axis=None): ar = np.asanyarray(ar).flatten() optional_indices = return_index or return_inverse if optional_indices: perm = ar.argsort(kind='mergesort' if return_index else 'quicksort') aux = ar[perm] else: ar.sort() aux = ar mask = np.empty(aux.shape, dtype=np.bool) mask[:1] = True if equal_nan and aux.shape[0] > 0 and (aux.dtype.kind in 'cfmM') and np.isnan(aux[-1]): if aux.dtype.kind == 'c': aux_firstnan = np.searchsorted(np.isnan(aux), True, side='left') else: aux_firstnan = np.searchsorted(aux, aux[-1], side='left') if aux_firstnan > 0: mask[1:aux_firstnan] = aux[1:aux_firstnan] != aux[:aux_firstnan - 1] mask[aux_firstnan] = True mask[aux_firstnan + 1:] = False else: mask[1:] = aux[1:] != aux[:-1] ret = (aux[mask],) if return_index: ret += (perm[mask],) if return_inverse: imask = np.cumsum(mask) - 1 inv_idx = np.empty(mask.shape, dtype=np.intp) inv_idx[perm] = imask ret += (inv_idx.reshape(inverse_shape) if axis is None else inv_idx,) if return_counts: idx = np.concatenate(np.nonzero(mask) + ([mask.size],)) ret += (np.diff(idx),) return ret class UniqueAllResult(NamedTuple): values: np.ndarray indices: np.ndarray inverse_indices: np.ndarray counts: np.ndarray class UniqueCountsResult(NamedTuple): values: np.ndarray counts: np.ndarray class UniqueInverseResult(NamedTuple): values: np.ndarray inverse_indices: np.ndarray def _unique_all_dispatcher(x, /): return (x,) @array_function_dispatch(_unique_all_dispatcher) def unique_all(x): result = unique(x, return_index=True, return_inverse=True, return_counts=True, equal_nan=False) return UniqueAllResult(*result) def _unique_counts_dispatcher(x, /): return (x,) @array_function_dispatch(_unique_counts_dispatcher) def unique_counts(x): result = unique(x, return_index=False, return_inverse=False, return_counts=True, equal_nan=False) return UniqueCountsResult(*result) def _unique_inverse_dispatcher(x, /): return (x,) @array_function_dispatch(_unique_inverse_dispatcher) def unique_inverse(x): result = unique(x, return_index=False, return_inverse=True, return_counts=False, equal_nan=False) return UniqueInverseResult(*result) def _unique_values_dispatcher(x, /): return (x,) @array_function_dispatch(_unique_values_dispatcher) def unique_values(x): return unique(x, return_index=False, return_inverse=False, return_counts=False, equal_nan=False) def _intersect1d_dispatcher(ar1, ar2, assume_unique=None, return_indices=None): return (ar1, ar2) @array_function_dispatch(_intersect1d_dispatcher) def intersect1d(ar1, ar2, assume_unique=False, return_indices=False): ar1 = np.asanyarray(ar1) ar2 = np.asanyarray(ar2) if not assume_unique: if return_indices: (ar1, ind1) = unique(ar1, return_index=True) (ar2, ind2) = unique(ar2, return_index=True) else: ar1 = unique(ar1) ar2 = unique(ar2) else: ar1 = ar1.ravel() ar2 = ar2.ravel() aux = np.concatenate((ar1, ar2)) if return_indices: aux_sort_indices = np.argsort(aux, kind='mergesort') aux = aux[aux_sort_indices] else: aux.sort() mask = aux[1:] == aux[:-1] int1d = aux[:-1][mask] if return_indices: ar1_indices = aux_sort_indices[:-1][mask] ar2_indices = aux_sort_indices[1:][mask] - ar1.size if not assume_unique: ar1_indices = ind1[ar1_indices] ar2_indices = ind2[ar2_indices] return (int1d, ar1_indices, ar2_indices) else: return int1d def _setxor1d_dispatcher(ar1, ar2, assume_unique=None): return (ar1, ar2) @array_function_dispatch(_setxor1d_dispatcher) def setxor1d(ar1, ar2, assume_unique=False): if not assume_unique: ar1 = unique(ar1) ar2 = unique(ar2) aux = np.concatenate((ar1, ar2), axis=None) if aux.size == 0: return aux aux.sort() flag = np.concatenate(([True], aux[1:] != aux[:-1], [True])) return aux[flag[1:] & flag[:-1]] def _in1d_dispatcher(ar1, ar2, assume_unique=None, invert=None, *, kind=None): return (ar1, ar2) @array_function_dispatch(_in1d_dispatcher) def in1d(ar1, ar2, assume_unique=False, invert=False, *, kind=None): warnings.warn('`in1d` is deprecated. Use `np.isin` instead.', DeprecationWarning, stacklevel=2) return _in1d(ar1, ar2, assume_unique, invert, kind=kind) def _in1d(ar1, ar2, assume_unique=False, invert=False, *, kind=None): ar1 = np.asarray(ar1).ravel() ar2 = np.asarray(ar2).ravel() if ar2.dtype == object: ar2 = ar2.reshape(-1, 1) if kind not in {None, 'sort', 'table'}: raise ValueError(f"Invalid kind: '{kind}'. Please use None, 'sort' or 'table'.") is_int_arrays = all((ar.dtype.kind in ('u', 'i', 'b') for ar in (ar1, ar2))) use_table_method = is_int_arrays and kind in {None, 'table'} if use_table_method: if ar2.size == 0: if invert: return np.ones_like(ar1, dtype=bool) else: return np.zeros_like(ar1, dtype=bool) if ar1.dtype == bool: ar1 = ar1.astype(np.uint8) if ar2.dtype == bool: ar2 = ar2.astype(np.uint8) ar2_min = int(np.min(ar2)) ar2_max = int(np.max(ar2)) ar2_range = ar2_max - ar2_min below_memory_constraint = ar2_range <= 6 * (ar1.size + ar2.size) range_safe_from_overflow = ar2_range <= np.iinfo(ar2.dtype).max if range_safe_from_overflow and (below_memory_constraint or kind == 'table'): if invert: outgoing_array = np.ones_like(ar1, dtype=bool) else: outgoing_array = np.zeros_like(ar1, dtype=bool) if invert: isin_helper_ar = np.ones(ar2_range + 1, dtype=bool) isin_helper_ar[ar2 - ar2_min] = 0 else: isin_helper_ar = np.zeros(ar2_range + 1, dtype=bool) isin_helper_ar[ar2 - ar2_min] = 1 basic_mask = (ar1 <= ar2_max) & (ar1 >= ar2_min) in_range_ar1 = ar1[basic_mask] if in_range_ar1.size == 0: return outgoing_array try: ar2_min = np.array(ar2_min, dtype=np.intp) dtype = np.intp except OverflowError: dtype = ar2.dtype out = np.empty_like(in_range_ar1, dtype=np.intp) outgoing_array[basic_mask] = isin_helper_ar[np.subtract(in_range_ar1, ar2_min, dtype=dtype, out=out, casting='unsafe')] return outgoing_array elif kind == 'table': raise RuntimeError("You have specified kind='table', but the range of values in `ar2` or `ar1` exceed the maximum integer of the datatype. Please set `kind` to None or 'sort'.") elif kind == 'table': raise ValueError("The 'table' method is only supported for boolean or integer arrays. Please select 'sort' or None for kind.") contains_object = ar1.dtype.hasobject or ar2.dtype.hasobject if len(ar2) < 10 * len(ar1) ** 0.145 or contains_object: if invert: mask = np.ones(len(ar1), dtype=bool) for a in ar2: mask &= ar1 != a else: mask = np.zeros(len(ar1), dtype=bool) for a in ar2: mask |= ar1 == a return mask if not assume_unique: (ar1, rev_idx) = np.unique(ar1, return_inverse=True) ar2 = np.unique(ar2) ar = np.concatenate((ar1, ar2)) order = ar.argsort(kind='mergesort') sar = ar[order] if invert: bool_ar = sar[1:] != sar[:-1] else: bool_ar = sar[1:] == sar[:-1] flag = np.concatenate((bool_ar, [invert])) ret = np.empty(ar.shape, dtype=bool) ret[order] = flag if assume_unique: return ret[:len(ar1)] else: return ret[rev_idx] def _isin_dispatcher(element, test_elements, assume_unique=None, invert=None, *, kind=None): return (element, test_elements) @array_function_dispatch(_isin_dispatcher) def isin(element, test_elements, assume_unique=False, invert=False, *, kind=None): element = np.asarray(element) return _in1d(element, test_elements, assume_unique=assume_unique, invert=invert, kind=kind).reshape(element.shape) def _union1d_dispatcher(ar1, ar2): return (ar1, ar2) @array_function_dispatch(_union1d_dispatcher) def union1d(ar1, ar2): return unique(np.concatenate((ar1, ar2), axis=None)) def _setdiff1d_dispatcher(ar1, ar2, assume_unique=None): return (ar1, ar2) @array_function_dispatch(_setdiff1d_dispatcher) def setdiff1d(ar1, ar2, assume_unique=False): if assume_unique: ar1 = np.asarray(ar1).ravel() else: ar1 = unique(ar1) ar2 = unique(ar2) return ar1[_in1d(ar1, ar2, assume_unique=True, invert=True)] # File: numpy-main/numpy/lib/_arrayterator_impl.py """""" from operator import mul from functools import reduce __all__ = ['Arrayterator'] class Arrayterator: def __init__(self, var, buf_size=None): self.var = var self.buf_size = buf_size self.start = [0 for dim in var.shape] self.stop = list(var.shape) self.step = [1 for dim in var.shape] def __getattr__(self, attr): return getattr(self.var, attr) def __getitem__(self, index): if not isinstance(index, tuple): index = (index,) fixed = [] (length, dims) = (len(index), self.ndim) for slice_ in index: if slice_ is Ellipsis: fixed.extend([slice(None)] * (dims - length + 1)) length = len(fixed) elif isinstance(slice_, int): fixed.append(slice(slice_, slice_ + 1, 1)) else: fixed.append(slice_) index = tuple(fixed) if len(index) < dims: index += (slice(None),) * (dims - len(index)) out = self.__class__(self.var, self.buf_size) for (i, (start, stop, step, slice_)) in enumerate(zip(self.start, self.stop, self.step, index)): out.start[i] = start + (slice_.start or 0) out.step[i] = step * (slice_.step or 1) out.stop[i] = start + (slice_.stop or stop - start) out.stop[i] = min(stop, out.stop[i]) return out def __array__(self, dtype=None, copy=None): slice_ = tuple((slice(*t) for t in zip(self.start, self.stop, self.step))) return self.var[slice_] @property def flat(self): for block in self: yield from block.flat @property def shape(self): return tuple(((stop - start - 1) // step + 1 for (start, stop, step) in zip(self.start, self.stop, self.step))) def __iter__(self): if [dim for dim in self.shape if dim <= 0]: return start = self.start[:] stop = self.stop[:] step = self.step[:] ndims = self.var.ndim while True: count = self.buf_size or reduce(mul, self.shape) rundim = 0 for i in range(ndims - 1, -1, -1): if count == 0: stop[i] = start[i] + 1 elif count <= self.shape[i]: stop[i] = start[i] + count * step[i] rundim = i else: stop[i] = self.stop[i] stop[i] = min(self.stop[i], stop[i]) count = count // self.shape[i] slice_ = tuple((slice(*t) for t in zip(start, stop, step))) yield self.var[slice_] start[rundim] = stop[rundim] for i in range(ndims - 1, 0, -1): if start[i] >= self.stop[i]: start[i] = self.start[i] start[i - 1] += self.step[i - 1] if start[0] >= self.stop[0]: return # File: numpy-main/numpy/lib/_datasource.py """""" import os from .._utils import set_module _open = open def _check_mode(mode, encoding, newline): if 't' in mode: if 'b' in mode: raise ValueError('Invalid mode: %r' % (mode,)) else: if encoding is not None: raise ValueError("Argument 'encoding' not supported in binary mode") if newline is not None: raise ValueError("Argument 'newline' not supported in binary mode") class _FileOpeners: def __init__(self): self._loaded = False self._file_openers = {None: open} def _load(self): if self._loaded: return try: import bz2 self._file_openers['.bz2'] = bz2.open except ImportError: pass try: import gzip self._file_openers['.gz'] = gzip.open except ImportError: pass try: import lzma self._file_openers['.xz'] = lzma.open self._file_openers['.lzma'] = lzma.open except (ImportError, AttributeError): pass self._loaded = True def keys(self): self._load() return list(self._file_openers.keys()) def __getitem__(self, key): self._load() return self._file_openers[key] _file_openers = _FileOpeners() def open(path, mode='r', destpath=os.curdir, encoding=None, newline=None): ds = DataSource(destpath) return ds.open(path, mode, encoding=encoding, newline=newline) @set_module('numpy.lib.npyio') class DataSource: def __init__(self, destpath=os.curdir): if destpath: self._destpath = os.path.abspath(destpath) self._istmpdest = False else: import tempfile self._destpath = tempfile.mkdtemp() self._istmpdest = True def __del__(self): if hasattr(self, '_istmpdest') and self._istmpdest: import shutil shutil.rmtree(self._destpath) def _iszip(self, filename): (fname, ext) = os.path.splitext(filename) return ext in _file_openers.keys() def _iswritemode(self, mode): _writemodes = ('w', '+') return any((c in _writemodes for c in mode)) def _splitzipext(self, filename): if self._iszip(filename): return os.path.splitext(filename) else: return (filename, None) def _possible_names(self, filename): names = [filename] if not self._iszip(filename): for zipext in _file_openers.keys(): if zipext: names.append(filename + zipext) return names def _isurl(self, path): from urllib.parse import urlparse (scheme, netloc, upath, uparams, uquery, ufrag) = urlparse(path) return bool(scheme and netloc) def _cache(self, path): import shutil from urllib.request import urlopen upath = self.abspath(path) if not os.path.exists(os.path.dirname(upath)): os.makedirs(os.path.dirname(upath)) if self._isurl(path): with urlopen(path) as openedurl: with _open(upath, 'wb') as f: shutil.copyfileobj(openedurl, f) else: shutil.copyfile(path, upath) return upath def _findfile(self, path): if not self._isurl(path): filelist = self._possible_names(path) filelist += self._possible_names(self.abspath(path)) else: filelist = self._possible_names(self.abspath(path)) filelist = filelist + self._possible_names(path) for name in filelist: if self.exists(name): if self._isurl(name): name = self._cache(name) return name return None def abspath(self, path): from urllib.parse import urlparse splitpath = path.split(self._destpath, 2) if len(splitpath) > 1: path = splitpath[1] (scheme, netloc, upath, uparams, uquery, ufrag) = urlparse(path) netloc = self._sanitize_relative_path(netloc) upath = self._sanitize_relative_path(upath) return os.path.join(self._destpath, netloc, upath) def _sanitize_relative_path(self, path): last = None path = os.path.normpath(path) while path != last: last = path path = path.lstrip(os.sep).lstrip('/') path = path.lstrip(os.pardir).removeprefix('..') (drive, path) = os.path.splitdrive(path) return path def exists(self, path): if os.path.exists(path): return True from urllib.request import urlopen from urllib.error import URLError upath = self.abspath(path) if os.path.exists(upath): return True if self._isurl(path): try: netfile = urlopen(path) netfile.close() del netfile return True except URLError: return False return False def open(self, path, mode='r', encoding=None, newline=None): if self._isurl(path) and self._iswritemode(mode): raise ValueError('URLs are not writeable') found = self._findfile(path) if found: (_fname, ext) = self._splitzipext(found) if ext == 'bz2': mode.replace('+', '') return _file_openers[ext](found, mode=mode, encoding=encoding, newline=newline) else: raise FileNotFoundError(f'{path} not found.') class Repository(DataSource): def __init__(self, baseurl, destpath=os.curdir): DataSource.__init__(self, destpath=destpath) self._baseurl = baseurl def __del__(self): DataSource.__del__(self) def _fullpath(self, path): splitpath = path.split(self._baseurl, 2) if len(splitpath) == 1: result = os.path.join(self._baseurl, path) else: result = path return result def _findfile(self, path): return DataSource._findfile(self, self._fullpath(path)) def abspath(self, path): return DataSource.abspath(self, self._fullpath(path)) def exists(self, path): return DataSource.exists(self, self._fullpath(path)) def open(self, path, mode='r', encoding=None, newline=None): return DataSource.open(self, self._fullpath(path), mode, encoding=encoding, newline=newline) def listdir(self): if self._isurl(self._baseurl): raise NotImplementedError('Directory listing of URLs, not supported yet.') else: return os.listdir(self._baseurl) # File: numpy-main/numpy/lib/_function_base_impl.py import builtins import collections.abc import functools import re import sys import warnings import numpy as np import numpy._core.numeric as _nx from numpy._core import transpose, overrides from numpy._core.numeric import ones, zeros_like, arange, concatenate, array, asarray, asanyarray, empty, ndarray, take, dot, where, intp, integer, isscalar, absolute from numpy._core.umath import pi, add, arctan2, frompyfunc, cos, less_equal, sqrt, sin, mod, exp, not_equal, subtract, minimum from numpy._core.fromnumeric import ravel, nonzero, partition, mean, any, sum from numpy._core.numerictypes import typecodes from numpy.lib._twodim_base_impl import diag from numpy._core.multiarray import _place, bincount, normalize_axis_index, _monotonicity, interp as compiled_interp, interp_complex as compiled_interp_complex from numpy._core._multiarray_umath import _array_converter from numpy._utils import set_module from numpy.lib._histograms_impl import histogram, histogramdd array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') __all__ = ['select', 'piecewise', 'trim_zeros', 'copy', 'iterable', 'percentile', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'flip', 'rot90', 'extract', 'place', 'vectorize', 'asarray_chkfinite', 'average', 'bincount', 'digitize', 'cov', 'corrcoef', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapezoid', 'trapz', 'i0', 'meshgrid', 'delete', 'insert', 'append', 'interp', 'quantile'] _QuantileMethods = dict(inverted_cdf=dict(get_virtual_index=lambda n, quantiles: _inverted_cdf(n, quantiles), fix_gamma=None), averaged_inverted_cdf=dict(get_virtual_index=lambda n, quantiles: n * quantiles - 1, fix_gamma=lambda gamma, _: _get_gamma_mask(shape=gamma.shape, default_value=1.0, conditioned_value=0.5, where=gamma == 0)), closest_observation=dict(get_virtual_index=lambda n, quantiles: _closest_observation(n, quantiles), fix_gamma=None), interpolated_inverted_cdf=dict(get_virtual_index=lambda n, quantiles: _compute_virtual_index(n, quantiles, 0, 1), fix_gamma=lambda gamma, _: gamma), hazen=dict(get_virtual_index=lambda n, quantiles: _compute_virtual_index(n, quantiles, 0.5, 0.5), fix_gamma=lambda gamma, _: gamma), weibull=dict(get_virtual_index=lambda n, quantiles: _compute_virtual_index(n, quantiles, 0, 0), fix_gamma=lambda gamma, _: gamma), linear=dict(get_virtual_index=lambda n, quantiles: (n - 1) * quantiles, fix_gamma=lambda gamma, _: gamma), median_unbiased=dict(get_virtual_index=lambda n, quantiles: _compute_virtual_index(n, quantiles, 1 / 3.0, 1 / 3.0), fix_gamma=lambda gamma, _: gamma), normal_unbiased=dict(get_virtual_index=lambda n, quantiles: _compute_virtual_index(n, quantiles, 3 / 8.0, 3 / 8.0), fix_gamma=lambda gamma, _: gamma), lower=dict(get_virtual_index=lambda n, quantiles: np.floor((n - 1) * quantiles).astype(np.intp), fix_gamma=None), higher=dict(get_virtual_index=lambda n, quantiles: np.ceil((n - 1) * quantiles).astype(np.intp), fix_gamma=None), midpoint=dict(get_virtual_index=lambda n, quantiles: 0.5 * (np.floor((n - 1) * quantiles) + np.ceil((n - 1) * quantiles)), fix_gamma=lambda gamma, index: _get_gamma_mask(shape=gamma.shape, default_value=0.5, conditioned_value=0.0, where=index % 1 == 0)), nearest=dict(get_virtual_index=lambda n, quantiles: np.around((n - 1) * quantiles).astype(np.intp), fix_gamma=None)) def _rot90_dispatcher(m, k=None, axes=None): return (m,) @array_function_dispatch(_rot90_dispatcher) def rot90(m, k=1, axes=(0, 1)): axes = tuple(axes) if len(axes) != 2: raise ValueError('len(axes) must be 2.') m = asanyarray(m) if axes[0] == axes[1] or absolute(axes[0] - axes[1]) == m.ndim: raise ValueError('Axes must be different.') if axes[0] >= m.ndim or axes[0] < -m.ndim or axes[1] >= m.ndim or (axes[1] < -m.ndim): raise ValueError('Axes={} out of range for array of ndim={}.'.format(axes, m.ndim)) k %= 4 if k == 0: return m[:] if k == 2: return flip(flip(m, axes[0]), axes[1]) axes_list = arange(0, m.ndim) (axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]], axes_list[axes[0]]) if k == 1: return transpose(flip(m, axes[1]), axes_list) else: return flip(transpose(m, axes_list), axes[1]) def _flip_dispatcher(m, axis=None): return (m,) @array_function_dispatch(_flip_dispatcher) def flip(m, axis=None): if not hasattr(m, 'ndim'): m = asarray(m) if axis is None: indexer = (np.s_[::-1],) * m.ndim else: axis = _nx.normalize_axis_tuple(axis, m.ndim) indexer = [np.s_[:]] * m.ndim for ax in axis: indexer[ax] = np.s_[::-1] indexer = tuple(indexer) return m[indexer] @set_module('numpy') def iterable(y): try: iter(y) except TypeError: return False return True def _weights_are_valid(weights, a, axis): wgt = np.asanyarray(weights) if a.shape != wgt.shape: if axis is None: raise TypeError('Axis must be specified when shapes of a and weights differ.') if wgt.shape != tuple((a.shape[ax] for ax in axis)): raise ValueError('Shape of weights must be consistent with shape of a along specified axis.') wgt = wgt.transpose(np.argsort(axis)) wgt = wgt.reshape(tuple((s if ax in axis else 1 for (ax, s) in enumerate(a.shape)))) return wgt def _average_dispatcher(a, axis=None, weights=None, returned=None, *, keepdims=None): return (a, weights) @array_function_dispatch(_average_dispatcher) def average(a, axis=None, weights=None, returned=False, *, keepdims=np._NoValue): a = np.asanyarray(a) if axis is not None: axis = _nx.normalize_axis_tuple(axis, a.ndim, argname='axis') if keepdims is np._NoValue: keepdims_kw = {} else: keepdims_kw = {'keepdims': keepdims} if weights is None: avg = a.mean(axis, **keepdims_kw) avg_as_array = np.asanyarray(avg) scl = avg_as_array.dtype.type(a.size / avg_as_array.size) else: wgt = _weights_are_valid(weights=weights, a=a, axis=axis) if issubclass(a.dtype.type, (np.integer, np.bool)): result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8') else: result_dtype = np.result_type(a.dtype, wgt.dtype) scl = wgt.sum(axis=axis, dtype=result_dtype, **keepdims_kw) if np.any(scl == 0.0): raise ZeroDivisionError("Weights sum to zero, can't be normalized") avg = avg_as_array = np.multiply(a, wgt, dtype=result_dtype).sum(axis, **keepdims_kw) / scl if returned: if scl.shape != avg_as_array.shape: scl = np.broadcast_to(scl, avg_as_array.shape).copy() return (avg, scl) else: return avg @set_module('numpy') def asarray_chkfinite(a, dtype=None, order=None): a = asarray(a, dtype=dtype, order=order) if a.dtype.char in typecodes['AllFloat'] and (not np.isfinite(a).all()): raise ValueError('array must not contain infs or NaNs') return a def _piecewise_dispatcher(x, condlist, funclist, *args, **kw): yield x if np.iterable(condlist): yield from condlist @array_function_dispatch(_piecewise_dispatcher) def piecewise(x, condlist, funclist, *args, **kw): x = asanyarray(x) n2 = len(funclist) if isscalar(condlist) or (not isinstance(condlist[0], (list, ndarray)) and x.ndim != 0): condlist = [condlist] condlist = asarray(condlist, dtype=bool) n = len(condlist) if n == n2 - 1: condelse = ~np.any(condlist, axis=0, keepdims=True) condlist = np.concatenate([condlist, condelse], axis=0) n += 1 elif n != n2: raise ValueError('with {} condition(s), either {} or {} functions are expected'.format(n, n, n + 1)) y = zeros_like(x) for (cond, func) in zip(condlist, funclist): if not isinstance(func, collections.abc.Callable): y[cond] = func else: vals = x[cond] if vals.size > 0: y[cond] = func(vals, *args, **kw) return y def _select_dispatcher(condlist, choicelist, default=None): yield from condlist yield from choicelist @array_function_dispatch(_select_dispatcher) def select(condlist, choicelist, default=0): if len(condlist) != len(choicelist): raise ValueError('list of cases must be same length as list of conditions') if len(condlist) == 0: raise ValueError('select with an empty condition list is not possible') choicelist = [choice if type(choice) in (int, float, complex) else np.asarray(choice) for choice in choicelist] choicelist.append(default if type(default) in (int, float, complex) else np.asarray(default)) try: dtype = np.result_type(*choicelist) except TypeError as e: msg = f'Choicelist and default value do not have a common dtype: {e}' raise TypeError(msg) from None condlist = np.broadcast_arrays(*condlist) choicelist = np.broadcast_arrays(*choicelist) for (i, cond) in enumerate(condlist): if cond.dtype.type is not np.bool: raise TypeError('invalid entry {} in condlist: should be boolean ndarray'.format(i)) if choicelist[0].ndim == 0: result_shape = condlist[0].shape else: result_shape = np.broadcast_arrays(condlist[0], choicelist[0])[0].shape result = np.full(result_shape, choicelist[-1], dtype) choicelist = choicelist[-2::-1] condlist = condlist[::-1] for (choice, cond) in zip(choicelist, condlist): np.copyto(result, choice, where=cond) return result def _copy_dispatcher(a, order=None, subok=None): return (a,) @array_function_dispatch(_copy_dispatcher) def copy(a, order='K', subok=False): return array(a, order=order, subok=subok, copy=True) def _gradient_dispatcher(f, *varargs, axis=None, edge_order=None): yield f yield from varargs @array_function_dispatch(_gradient_dispatcher) def gradient(f, *varargs, axis=None, edge_order=1): f = np.asanyarray(f) N = f.ndim if axis is None: axes = tuple(range(N)) else: axes = _nx.normalize_axis_tuple(axis, N) len_axes = len(axes) n = len(varargs) if n == 0: dx = [1.0] * len_axes elif n == 1 and np.ndim(varargs[0]) == 0: dx = varargs * len_axes elif n == len_axes: dx = list(varargs) for (i, distances) in enumerate(dx): distances = np.asanyarray(distances) if distances.ndim == 0: continue elif distances.ndim != 1: raise ValueError('distances must be either scalars or 1d') if len(distances) != f.shape[axes[i]]: raise ValueError('when 1d, distances must match the length of the corresponding dimension') if np.issubdtype(distances.dtype, np.integer): distances = distances.astype(np.float64) diffx = np.diff(distances) if (diffx == diffx[0]).all(): diffx = diffx[0] dx[i] = diffx else: raise TypeError('invalid number of arguments') if edge_order > 2: raise ValueError("'edge_order' greater than 2 not supported") outvals = [] slice1 = [slice(None)] * N slice2 = [slice(None)] * N slice3 = [slice(None)] * N slice4 = [slice(None)] * N otype = f.dtype if otype.type is np.datetime64: otype = np.dtype(otype.name.replace('datetime', 'timedelta')) f = f.view(otype) elif otype.type is np.timedelta64: pass elif np.issubdtype(otype, np.inexact): pass else: if np.issubdtype(otype, np.integer): f = f.astype(np.float64) otype = np.float64 for (axis, ax_dx) in zip(axes, dx): if f.shape[axis] < edge_order + 1: raise ValueError('Shape of array too small to calculate a numerical gradient, at least (edge_order + 1) elements are required.') out = np.empty_like(f, dtype=otype) uniform_spacing = np.ndim(ax_dx) == 0 slice1[axis] = slice(1, -1) slice2[axis] = slice(None, -2) slice3[axis] = slice(1, -1) slice4[axis] = slice(2, None) if uniform_spacing: out[tuple(slice1)] = (f[tuple(slice4)] - f[tuple(slice2)]) / (2.0 * ax_dx) else: dx1 = ax_dx[0:-1] dx2 = ax_dx[1:] a = -dx2 / (dx1 * (dx1 + dx2)) b = (dx2 - dx1) / (dx1 * dx2) c = dx1 / (dx2 * (dx1 + dx2)) shape = np.ones(N, dtype=int) shape[axis] = -1 a.shape = b.shape = c.shape = shape out[tuple(slice1)] = a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)] if edge_order == 1: slice1[axis] = 0 slice2[axis] = 1 slice3[axis] = 0 dx_0 = ax_dx if uniform_spacing else ax_dx[0] out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_0 slice1[axis] = -1 slice2[axis] = -1 slice3[axis] = -2 dx_n = ax_dx if uniform_spacing else ax_dx[-1] out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_n else: slice1[axis] = 0 slice2[axis] = 0 slice3[axis] = 1 slice4[axis] = 2 if uniform_spacing: a = -1.5 / ax_dx b = 2.0 / ax_dx c = -0.5 / ax_dx else: dx1 = ax_dx[0] dx2 = ax_dx[1] a = -(2.0 * dx1 + dx2) / (dx1 * (dx1 + dx2)) b = (dx1 + dx2) / (dx1 * dx2) c = -dx1 / (dx2 * (dx1 + dx2)) out[tuple(slice1)] = a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)] slice1[axis] = -1 slice2[axis] = -3 slice3[axis] = -2 slice4[axis] = -1 if uniform_spacing: a = 0.5 / ax_dx b = -2.0 / ax_dx c = 1.5 / ax_dx else: dx1 = ax_dx[-2] dx2 = ax_dx[-1] a = dx2 / (dx1 * (dx1 + dx2)) b = -(dx2 + dx1) / (dx1 * dx2) c = (2.0 * dx2 + dx1) / (dx2 * (dx1 + dx2)) out[tuple(slice1)] = a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)] outvals.append(out) slice1[axis] = slice(None) slice2[axis] = slice(None) slice3[axis] = slice(None) slice4[axis] = slice(None) if len_axes == 1: return outvals[0] return tuple(outvals) def _diff_dispatcher(a, n=None, axis=None, prepend=None, append=None): return (a, prepend, append) @array_function_dispatch(_diff_dispatcher) def diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): if n == 0: return a if n < 0: raise ValueError('order must be non-negative but got ' + repr(n)) a = asanyarray(a) nd = a.ndim if nd == 0: raise ValueError('diff requires input that is at least one dimensional') axis = normalize_axis_index(axis, nd) combined = [] if prepend is not np._NoValue: prepend = np.asanyarray(prepend) if prepend.ndim == 0: shape = list(a.shape) shape[axis] = 1 prepend = np.broadcast_to(prepend, tuple(shape)) combined.append(prepend) combined.append(a) if append is not np._NoValue: append = np.asanyarray(append) if append.ndim == 0: shape = list(a.shape) shape[axis] = 1 append = np.broadcast_to(append, tuple(shape)) combined.append(append) if len(combined) > 1: a = np.concatenate(combined, axis) slice1 = [slice(None)] * nd slice2 = [slice(None)] * nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) slice1 = tuple(slice1) slice2 = tuple(slice2) op = not_equal if a.dtype == np.bool else subtract for _ in range(n): a = op(a[slice1], a[slice2]) return a def _interp_dispatcher(x, xp, fp, left=None, right=None, period=None): return (x, xp, fp) @array_function_dispatch(_interp_dispatcher) def interp(x, xp, fp, left=None, right=None, period=None): fp = np.asarray(fp) if np.iscomplexobj(fp): interp_func = compiled_interp_complex input_dtype = np.complex128 else: interp_func = compiled_interp input_dtype = np.float64 if period is not None: if period == 0: raise ValueError('period must be a non-zero value') period = abs(period) left = None right = None x = np.asarray(x, dtype=np.float64) xp = np.asarray(xp, dtype=np.float64) fp = np.asarray(fp, dtype=input_dtype) if xp.ndim != 1 or fp.ndim != 1: raise ValueError('Data points must be 1-D sequences') if xp.shape[0] != fp.shape[0]: raise ValueError('fp and xp are not of the same length') x = x % period xp = xp % period asort_xp = np.argsort(xp) xp = xp[asort_xp] fp = fp[asort_xp] xp = np.concatenate((xp[-1:] - period, xp, xp[0:1] + period)) fp = np.concatenate((fp[-1:], fp, fp[0:1])) return interp_func(x, xp, fp, left, right) def _angle_dispatcher(z, deg=None): return (z,) @array_function_dispatch(_angle_dispatcher) def angle(z, deg=False): z = asanyarray(z) if issubclass(z.dtype.type, _nx.complexfloating): zimag = z.imag zreal = z.real else: zimag = 0 zreal = z a = arctan2(zimag, zreal) if deg: a *= 180 / pi return a def _unwrap_dispatcher(p, discont=None, axis=None, *, period=None): return (p,) @array_function_dispatch(_unwrap_dispatcher) def unwrap(p, discont=None, axis=-1, *, period=2 * pi): p = asarray(p) nd = p.ndim dd = diff(p, axis=axis) if discont is None: discont = period / 2 slice1 = [slice(None, None)] * nd slice1[axis] = slice(1, None) slice1 = tuple(slice1) dtype = np.result_type(dd, period) if _nx.issubdtype(dtype, _nx.integer): (interval_high, rem) = divmod(period, 2) boundary_ambiguous = rem == 0 else: interval_high = period / 2 boundary_ambiguous = True interval_low = -interval_high ddmod = mod(dd - interval_low, period) + interval_low if boundary_ambiguous: _nx.copyto(ddmod, interval_high, where=(ddmod == interval_low) & (dd > 0)) ph_correct = ddmod - dd _nx.copyto(ph_correct, 0, where=abs(dd) < discont) up = array(p, copy=True, dtype=dtype) up[slice1] = p[slice1] + ph_correct.cumsum(axis) return up def _sort_complex(a): return (a,) @array_function_dispatch(_sort_complex) def sort_complex(a): b = array(a, copy=True) b.sort() if not issubclass(b.dtype.type, _nx.complexfloating): if b.dtype.char in 'bhBH': return b.astype('F') elif b.dtype.char == 'g': return b.astype('G') else: return b.astype('D') else: return b def _trim_zeros(filt, trim=None): return (filt,) @array_function_dispatch(_trim_zeros) def trim_zeros(filt, trim='fb'): first = 0 trim = trim.upper() if 'F' in trim: for i in filt: if i != 0.0: break else: first = first + 1 last = len(filt) if 'B' in trim: for i in filt[::-1]: if i != 0.0: break else: last = last - 1 return filt[first:last] def _extract_dispatcher(condition, arr): return (condition, arr) @array_function_dispatch(_extract_dispatcher) def extract(condition, arr): return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) def _place_dispatcher(arr, mask, vals): return (arr, mask, vals) @array_function_dispatch(_place_dispatcher) def place(arr, mask, vals): return _place(arr, mask, vals) def disp(mesg, device=None, linefeed=True): warnings.warn('`disp` is deprecated, use your own printing function instead. (deprecated in NumPy 2.0)', DeprecationWarning, stacklevel=2) if device is None: device = sys.stdout if linefeed: device.write('%s\n' % mesg) else: device.write('%s' % mesg) device.flush() return _DIMENSION_NAME = '\\w+' _CORE_DIMENSION_LIST = '(?:{0:}(?:,{0:})*)?'.format(_DIMENSION_NAME) _ARGUMENT = '\\({}\\)'.format(_CORE_DIMENSION_LIST) _ARGUMENT_LIST = '{0:}(?:,{0:})*'.format(_ARGUMENT) _SIGNATURE = '^{0:}->{0:}$'.format(_ARGUMENT_LIST) def _parse_gufunc_signature(signature): signature = re.sub('\\s+', '', signature) if not re.match(_SIGNATURE, signature): raise ValueError('not a valid gufunc signature: {}'.format(signature)) return tuple(([tuple(re.findall(_DIMENSION_NAME, arg)) for arg in re.findall(_ARGUMENT, arg_list)] for arg_list in signature.split('->'))) def _update_dim_sizes(dim_sizes, arg, core_dims): if not core_dims: return num_core_dims = len(core_dims) if arg.ndim < num_core_dims: raise ValueError('%d-dimensional argument does not have enough dimensions for all core dimensions %r' % (arg.ndim, core_dims)) core_shape = arg.shape[-num_core_dims:] for (dim, size) in zip(core_dims, core_shape): if dim in dim_sizes: if size != dim_sizes[dim]: raise ValueError('inconsistent size for core dimension %r: %r vs %r' % (dim, size, dim_sizes[dim])) else: dim_sizes[dim] = size def _parse_input_dimensions(args, input_core_dims): broadcast_args = [] dim_sizes = {} for (arg, core_dims) in zip(args, input_core_dims): _update_dim_sizes(dim_sizes, arg, core_dims) ndim = arg.ndim - len(core_dims) dummy_array = np.lib.stride_tricks.as_strided(0, arg.shape[:ndim]) broadcast_args.append(dummy_array) broadcast_shape = np.lib._stride_tricks_impl._broadcast_shape(*broadcast_args) return (broadcast_shape, dim_sizes) def _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims): return [broadcast_shape + tuple((dim_sizes[dim] for dim in core_dims)) for core_dims in list_of_core_dims] def _create_arrays(broadcast_shape, dim_sizes, list_of_core_dims, dtypes, results=None): shapes = _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims) if dtypes is None: dtypes = [None] * len(shapes) if results is None: arrays = tuple((np.empty(shape=shape, dtype=dtype) for (shape, dtype) in zip(shapes, dtypes))) else: arrays = tuple((np.empty_like(result, shape=shape, dtype=dtype) for (result, shape, dtype) in zip(results, shapes, dtypes))) return arrays def _get_vectorize_dtype(dtype): if dtype.char in 'SU': return dtype.char return dtype @set_module('numpy') class vectorize: def __init__(self, pyfunc=np._NoValue, otypes=None, doc=None, excluded=None, cache=False, signature=None): if pyfunc != np._NoValue and (not callable(pyfunc)): part1 = 'When used as a decorator, ' part2 = 'only accepts keyword arguments.' raise TypeError(part1 + part2) self.pyfunc = pyfunc self.cache = cache self.signature = signature if pyfunc != np._NoValue and hasattr(pyfunc, '__name__'): self.__name__ = pyfunc.__name__ self._ufunc = {} self._doc = None self.__doc__ = doc if doc is None and hasattr(pyfunc, '__doc__'): self.__doc__ = pyfunc.__doc__ else: self._doc = doc if isinstance(otypes, str): for char in otypes: if char not in typecodes['All']: raise ValueError('Invalid otype specified: %s' % (char,)) elif iterable(otypes): otypes = [_get_vectorize_dtype(_nx.dtype(x)) for x in otypes] elif otypes is not None: raise ValueError('Invalid otype specification') self.otypes = otypes if excluded is None: excluded = set() self.excluded = set(excluded) if signature is not None: self._in_and_out_core_dims = _parse_gufunc_signature(signature) else: self._in_and_out_core_dims = None def _init_stage_2(self, pyfunc, *args, **kwargs): self.__name__ = pyfunc.__name__ self.pyfunc = pyfunc if self._doc is None: self.__doc__ = pyfunc.__doc__ else: self.__doc__ = self._doc def _call_as_normal(self, *args, **kwargs): excluded = self.excluded if not kwargs and (not excluded): func = self.pyfunc vargs = args else: nargs = len(args) names = [_n for _n in kwargs if _n not in excluded] inds = [_i for _i in range(nargs) if _i not in excluded] the_args = list(args) def func(*vargs): for (_n, _i) in enumerate(inds): the_args[_i] = vargs[_n] kwargs.update(zip(names, vargs[len(inds):])) return self.pyfunc(*the_args, **kwargs) vargs = [args[_i] for _i in inds] vargs.extend([kwargs[_n] for _n in names]) return self._vectorize_call(func=func, args=vargs) def __call__(self, *args, **kwargs): if self.pyfunc is np._NoValue: self._init_stage_2(*args, **kwargs) return self return self._call_as_normal(*args, **kwargs) def _get_ufunc_and_otypes(self, func, args): if not args: raise ValueError('args can not be empty') if self.otypes is not None: otypes = self.otypes nin = len(args) nout = len(self.otypes) if func is not self.pyfunc or nin not in self._ufunc: ufunc = frompyfunc(func, nin, nout) else: ufunc = None if func is self.pyfunc: ufunc = self._ufunc.setdefault(nin, ufunc) else: args = [asarray(arg) for arg in args] if builtins.any((arg.size == 0 for arg in args)): raise ValueError('cannot call `vectorize` on size 0 inputs unless `otypes` is set') inputs = [arg.flat[0] for arg in args] outputs = func(*inputs) if self.cache: _cache = [outputs] def _func(*vargs): if _cache: return _cache.pop() else: return func(*vargs) else: _func = func if isinstance(outputs, tuple): nout = len(outputs) else: nout = 1 outputs = (outputs,) otypes = ''.join([asarray(outputs[_k]).dtype.char for _k in range(nout)]) ufunc = frompyfunc(_func, len(args), nout) return (ufunc, otypes) def _vectorize_call(self, func, args): if self.signature is not None: res = self._vectorize_call_with_signature(func, args) elif not args: res = func() else: (ufunc, otypes) = self._get_ufunc_and_otypes(func=func, args=args) inputs = [asanyarray(a, dtype=object) for a in args] outputs = ufunc(*inputs) if ufunc.nout == 1: res = asanyarray(outputs, dtype=otypes[0]) else: res = tuple([asanyarray(x, dtype=t) for (x, t) in zip(outputs, otypes)]) return res def _vectorize_call_with_signature(self, func, args): (input_core_dims, output_core_dims) = self._in_and_out_core_dims if len(args) != len(input_core_dims): raise TypeError('wrong number of positional arguments: expected %r, got %r' % (len(input_core_dims), len(args))) args = tuple((asanyarray(arg) for arg in args)) (broadcast_shape, dim_sizes) = _parse_input_dimensions(args, input_core_dims) input_shapes = _calculate_shapes(broadcast_shape, dim_sizes, input_core_dims) args = [np.broadcast_to(arg, shape, subok=True) for (arg, shape) in zip(args, input_shapes)] outputs = None otypes = self.otypes nout = len(output_core_dims) for index in np.ndindex(*broadcast_shape): results = func(*(arg[index] for arg in args)) n_results = len(results) if isinstance(results, tuple) else 1 if nout != n_results: raise ValueError('wrong number of outputs from pyfunc: expected %r, got %r' % (nout, n_results)) if nout == 1: results = (results,) if outputs is None: for (result, core_dims) in zip(results, output_core_dims): _update_dim_sizes(dim_sizes, result, core_dims) outputs = _create_arrays(broadcast_shape, dim_sizes, output_core_dims, otypes, results) for (output, result) in zip(outputs, results): output[index] = result if outputs is None: if otypes is None: raise ValueError('cannot call `vectorize` on size 0 inputs unless `otypes` is set') if builtins.any((dim not in dim_sizes for dims in output_core_dims for dim in dims)): raise ValueError('cannot call `vectorize` with a signature including new output dimensions on size 0 inputs') outputs = _create_arrays(broadcast_shape, dim_sizes, output_core_dims, otypes) return outputs[0] if nout == 1 else outputs def _cov_dispatcher(m, y=None, rowvar=None, bias=None, ddof=None, fweights=None, aweights=None, *, dtype=None): return (m, y, fweights, aweights) @array_function_dispatch(_cov_dispatcher) def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, *, dtype=None): if ddof is not None and ddof != int(ddof): raise ValueError('ddof must be integer') m = np.asarray(m) if m.ndim > 2: raise ValueError('m has more than 2 dimensions') if y is not None: y = np.asarray(y) if y.ndim > 2: raise ValueError('y has more than 2 dimensions') if dtype is None: if y is None: dtype = np.result_type(m, np.float64) else: dtype = np.result_type(m, y, np.float64) X = array(m, ndmin=2, dtype=dtype) if not rowvar and X.shape[0] != 1: X = X.T if X.shape[0] == 0: return np.array([]).reshape(0, 0) if y is not None: y = array(y, copy=None, ndmin=2, dtype=dtype) if not rowvar and y.shape[0] != 1: y = y.T X = np.concatenate((X, y), axis=0) if ddof is None: if bias == 0: ddof = 1 else: ddof = 0 w = None if fweights is not None: fweights = np.asarray(fweights, dtype=float) if not np.all(fweights == np.around(fweights)): raise TypeError('fweights must be integer') if fweights.ndim > 1: raise RuntimeError('cannot handle multidimensional fweights') if fweights.shape[0] != X.shape[1]: raise RuntimeError('incompatible numbers of samples and fweights') if any(fweights < 0): raise ValueError('fweights cannot be negative') w = fweights if aweights is not None: aweights = np.asarray(aweights, dtype=float) if aweights.ndim > 1: raise RuntimeError('cannot handle multidimensional aweights') if aweights.shape[0] != X.shape[1]: raise RuntimeError('incompatible numbers of samples and aweights') if any(aweights < 0): raise ValueError('aweights cannot be negative') if w is None: w = aweights else: w *= aweights (avg, w_sum) = average(X, axis=1, weights=w, returned=True) w_sum = w_sum[0] if w is None: fact = X.shape[1] - ddof elif ddof == 0: fact = w_sum elif aweights is None: fact = w_sum - ddof else: fact = w_sum - ddof * sum(w * aweights) / w_sum if fact <= 0: warnings.warn('Degrees of freedom <= 0 for slice', RuntimeWarning, stacklevel=2) fact = 0.0 X -= avg[:, None] if w is None: X_T = X.T else: X_T = (X * w).T c = dot(X, X_T.conj()) c *= np.true_divide(1, fact) return c.squeeze() def _corrcoef_dispatcher(x, y=None, rowvar=None, bias=None, ddof=None, *, dtype=None): return (x, y) @array_function_dispatch(_corrcoef_dispatcher) def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue, *, dtype=None): if bias is not np._NoValue or ddof is not np._NoValue: warnings.warn('bias and ddof have no effect and are deprecated', DeprecationWarning, stacklevel=2) c = cov(x, y, rowvar, dtype=dtype) try: d = diag(c) except ValueError: return c / c stddev = sqrt(d.real) c /= stddev[:, None] c /= stddev[None, :] np.clip(c.real, -1, 1, out=c.real) if np.iscomplexobj(c): np.clip(c.imag, -1, 1, out=c.imag) return c @set_module('numpy') def blackman(M): values = np.array([0.0, M]) M = values[1] if M < 1: return array([], dtype=values.dtype) if M == 1: return ones(1, dtype=values.dtype) n = arange(1 - M, M, 2) return 0.42 + 0.5 * cos(pi * n / (M - 1)) + 0.08 * cos(2.0 * pi * n / (M - 1)) @set_module('numpy') def bartlett(M): values = np.array([0.0, M]) M = values[1] if M < 1: return array([], dtype=values.dtype) if M == 1: return ones(1, dtype=values.dtype) n = arange(1 - M, M, 2) return where(less_equal(n, 0), 1 + n / (M - 1), 1 - n / (M - 1)) @set_module('numpy') def hanning(M): values = np.array([0.0, M]) M = values[1] if M < 1: return array([], dtype=values.dtype) if M == 1: return ones(1, dtype=values.dtype) n = arange(1 - M, M, 2) return 0.5 + 0.5 * cos(pi * n / (M - 1)) @set_module('numpy') def hamming(M): values = np.array([0.0, M]) M = values[1] if M < 1: return array([], dtype=values.dtype) if M == 1: return ones(1, dtype=values.dtype) n = arange(1 - M, M, 2) return 0.54 + 0.46 * cos(pi * n / (M - 1)) _i0A = [-4.4153416464793395e-18, 3.3307945188222384e-17, -2.431279846547955e-16, 1.715391285555133e-15, -1.1685332877993451e-14, 7.676185498604936e-14, -4.856446783111929e-13, 2.95505266312964e-12, -1.726826291441556e-11, 9.675809035373237e-11, -5.189795601635263e-10, 2.6598237246823866e-09, -1.300025009986248e-08, 6.046995022541919e-08, -2.670793853940612e-07, 1.1173875391201037e-06, -4.4167383584587505e-06, 1.6448448070728896e-05, -5.754195010082104e-05, 0.00018850288509584165, -0.0005763755745385824, 0.0016394756169413357, -0.004324309995050576, 0.010546460394594998, -0.02373741480589947, 0.04930528423967071, -0.09490109704804764, 0.17162090152220877, -0.3046826723431984, 0.6767952744094761] _i0B = [-7.233180487874754e-18, -4.830504485944182e-18, 4.46562142029676e-17, 3.461222867697461e-17, -2.8276239805165836e-16, -3.425485619677219e-16, 1.7725601330565263e-15, 3.8116806693526224e-15, -9.554846698828307e-15, -4.150569347287222e-14, 1.54008621752141e-14, 3.8527783827421426e-13, 7.180124451383666e-13, -1.7941785315068062e-12, -1.3215811840447713e-11, -3.1499165279632416e-11, 1.1889147107846439e-11, 4.94060238822497e-10, 3.3962320257083865e-09, 2.266668990498178e-08, 2.0489185894690638e-07, 2.8913705208347567e-06, 6.889758346916825e-05, 0.0033691164782556943, 0.8044904110141088] def _chbevl(x, vals): b0 = vals[0] b1 = 0.0 for i in range(1, len(vals)): b2 = b1 b1 = b0 b0 = x * b1 - b2 + vals[i] return 0.5 * (b0 - b2) def _i0_1(x): return exp(x) * _chbevl(x / 2.0 - 2, _i0A) def _i0_2(x): return exp(x) * _chbevl(32.0 / x - 2.0, _i0B) / sqrt(x) def _i0_dispatcher(x): return (x,) @array_function_dispatch(_i0_dispatcher) def i0(x): x = np.asanyarray(x) if x.dtype.kind == 'c': raise TypeError('i0 not supported for complex values') if x.dtype.kind != 'f': x = x.astype(float) x = np.abs(x) return piecewise(x, [x <= 8.0], [_i0_1, _i0_2]) @set_module('numpy') def kaiser(M, beta): values = np.array([0.0, M, beta]) M = values[1] beta = values[2] if M == 1: return np.ones(1, dtype=values.dtype) n = arange(0, M) alpha = (M - 1) / 2.0 return i0(beta * sqrt(1 - ((n - alpha) / alpha) ** 2.0)) / i0(beta) def _sinc_dispatcher(x): return (x,) @array_function_dispatch(_sinc_dispatcher) def sinc(x): x = np.asanyarray(x) y = pi * where(x == 0, 1e-20, x) return sin(y) / y def _ureduce(a, func, keepdims=False, **kwargs): a = np.asanyarray(a) axis = kwargs.get('axis', None) out = kwargs.get('out', None) if keepdims is np._NoValue: keepdims = False nd = a.ndim if axis is not None: axis = _nx.normalize_axis_tuple(axis, nd) if keepdims: if out is not None: index_out = tuple((0 if i in axis else slice(None) for i in range(nd))) kwargs['out'] = out[(Ellipsis,) + index_out] if len(axis) == 1: kwargs['axis'] = axis[0] else: keep = set(range(nd)) - set(axis) nkeep = len(keep) for (i, s) in enumerate(sorted(keep)): a = a.swapaxes(i, s) a = a.reshape(a.shape[:nkeep] + (-1,)) kwargs['axis'] = -1 elif keepdims: if out is not None: index_out = (0,) * nd kwargs['out'] = out[(Ellipsis,) + index_out] r = func(a, **kwargs) if out is not None: return out if keepdims: if axis is None: index_r = (np.newaxis,) * nd else: index_r = tuple((np.newaxis if i in axis else slice(None) for i in range(nd))) r = r[(Ellipsis,) + index_r] return r def _median_dispatcher(a, axis=None, out=None, overwrite_input=None, keepdims=None): return (a, out) @array_function_dispatch(_median_dispatcher) def median(a, axis=None, out=None, overwrite_input=False, keepdims=False): return _ureduce(a, func=_median, keepdims=keepdims, axis=axis, out=out, overwrite_input=overwrite_input) def _median(a, axis=None, out=None, overwrite_input=False): a = np.asanyarray(a) if axis is None: sz = a.size else: sz = a.shape[axis] if sz % 2 == 0: szh = sz // 2 kth = [szh - 1, szh] else: kth = [(sz - 1) // 2] supports_nans = np.issubdtype(a.dtype, np.inexact) or a.dtype.kind in 'Mm' if supports_nans: kth.append(-1) if overwrite_input: if axis is None: part = a.ravel() part.partition(kth) else: a.partition(kth, axis=axis) part = a else: part = partition(a, kth, axis=axis) if part.shape == (): return part.item() if axis is None: axis = 0 indexer = [slice(None)] * part.ndim index = part.shape[axis] // 2 if part.shape[axis] % 2 == 1: indexer[axis] = slice(index, index + 1) else: indexer[axis] = slice(index - 1, index + 1) indexer = tuple(indexer) rout = mean(part[indexer], axis=axis, out=out) if supports_nans and sz > 0: rout = np.lib._utils_impl._median_nancheck(part, rout, axis) return rout def _percentile_dispatcher(a, q, axis=None, out=None, overwrite_input=None, method=None, keepdims=None, *, weights=None, interpolation=None): return (a, q, out, weights) @array_function_dispatch(_percentile_dispatcher) def percentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, weights=None, interpolation=None): if interpolation is not None: method = _check_interpolation_as_method(method, interpolation, 'percentile') a = np.asanyarray(a) if a.dtype.kind == 'c': raise TypeError('a must be an array of real numbers') q = np.true_divide(q, a.dtype.type(100) if a.dtype.kind == 'f' else 100) q = asanyarray(q) if not _quantile_is_valid(q): raise ValueError('Percentiles must be in the range [0, 100]') if weights is not None: if method != 'inverted_cdf': msg = f"Only method 'inverted_cdf' supports weights. Got: {method}." raise ValueError(msg) if axis is not None: axis = _nx.normalize_axis_tuple(axis, a.ndim, argname='axis') weights = _weights_are_valid(weights=weights, a=a, axis=axis) if np.any(weights < 0): raise ValueError('Weights must be non-negative.') return _quantile_unchecked(a, q, axis, out, overwrite_input, method, keepdims, weights) def _quantile_dispatcher(a, q, axis=None, out=None, overwrite_input=None, method=None, keepdims=None, *, weights=None, interpolation=None): return (a, q, out, weights) @array_function_dispatch(_quantile_dispatcher) def quantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, weights=None, interpolation=None): if interpolation is not None: method = _check_interpolation_as_method(method, interpolation, 'quantile') a = np.asanyarray(a) if a.dtype.kind == 'c': raise TypeError('a must be an array of real numbers') if isinstance(q, (int, float)) and a.dtype.kind == 'f': q = np.asanyarray(q, dtype=a.dtype) else: q = np.asanyarray(q) if not _quantile_is_valid(q): raise ValueError('Quantiles must be in the range [0, 1]') if weights is not None: if method != 'inverted_cdf': msg = f"Only method 'inverted_cdf' supports weights. Got: {method}." raise ValueError(msg) if axis is not None: axis = _nx.normalize_axis_tuple(axis, a.ndim, argname='axis') weights = _weights_are_valid(weights=weights, a=a, axis=axis) if np.any(weights < 0): raise ValueError('Weights must be non-negative.') return _quantile_unchecked(a, q, axis, out, overwrite_input, method, keepdims, weights) def _quantile_unchecked(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, weights=None): return _ureduce(a, func=_quantile_ureduce_func, q=q, weights=weights, keepdims=keepdims, axis=axis, out=out, overwrite_input=overwrite_input, method=method) def _quantile_is_valid(q): if q.ndim == 1 and q.size < 10: for i in range(q.size): if not 0.0 <= q[i] <= 1.0: return False elif not (q.min() >= 0 and q.max() <= 1): return False return True def _check_interpolation_as_method(method, interpolation, fname): warnings.warn(f"the `interpolation=` argument to {fname} was renamed to `method=`, which has additional options.\nUsers of the modes 'nearest', 'lower', 'higher', or 'midpoint' are encouraged to review the method they used. (Deprecated NumPy 1.22)", DeprecationWarning, stacklevel=4) if method != 'linear': raise TypeError('You shall not pass both `method` and `interpolation`!\n(`interpolation` is Deprecated in favor of `method`)') return interpolation def _compute_virtual_index(n, quantiles, alpha: float, beta: float): return n * quantiles + (alpha + quantiles * (1 - alpha - beta)) - 1 def _get_gamma(virtual_indexes, previous_indexes, method): gamma = np.asanyarray(virtual_indexes - previous_indexes) gamma = method['fix_gamma'](gamma, virtual_indexes) return np.asanyarray(gamma, dtype=virtual_indexes.dtype) def _lerp(a, b, t, out=None): diff_b_a = subtract(b, a) lerp_interpolation = asanyarray(add(a, diff_b_a * t, out=out)) subtract(b, diff_b_a * (1 - t), out=lerp_interpolation, where=t >= 0.5, casting='unsafe', dtype=type(lerp_interpolation.dtype)) if lerp_interpolation.ndim == 0 and out is None: lerp_interpolation = lerp_interpolation[()] return lerp_interpolation def _get_gamma_mask(shape, default_value, conditioned_value, where): out = np.full(shape, default_value) np.copyto(out, conditioned_value, where=where, casting='unsafe') return out def _discrete_interpolation_to_boundaries(index, gamma_condition_fun): previous = np.floor(index) next = previous + 1 gamma = index - previous res = _get_gamma_mask(shape=index.shape, default_value=next, conditioned_value=previous, where=gamma_condition_fun(gamma, index)).astype(np.intp) res[res < 0] = 0 return res def _closest_observation(n, quantiles): gamma_fun = lambda gamma, index: (gamma == 0) & (np.floor(index) % 2 == 1) return _discrete_interpolation_to_boundaries(n * quantiles - 1 - 0.5, gamma_fun) def _inverted_cdf(n, quantiles): gamma_fun = lambda gamma, _: gamma == 0 return _discrete_interpolation_to_boundaries(n * quantiles - 1, gamma_fun) def _quantile_ureduce_func(a: np.array, q: np.array, weights: np.array, axis: int | None=None, out=None, overwrite_input: bool=False, method='linear') -> np.array: if q.ndim > 2: raise ValueError('q must be a scalar or 1d') if overwrite_input: if axis is None: axis = 0 arr = a.ravel() wgt = None if weights is None else weights.ravel() else: arr = a wgt = weights elif axis is None: axis = 0 arr = a.flatten() wgt = None if weights is None else weights.flatten() else: arr = a.copy() wgt = weights result = _quantile(arr, quantiles=q, axis=axis, method=method, out=out, weights=wgt) return result def _get_indexes(arr, virtual_indexes, valid_values_count): previous_indexes = np.asanyarray(np.floor(virtual_indexes)) next_indexes = np.asanyarray(previous_indexes + 1) indexes_above_bounds = virtual_indexes >= valid_values_count - 1 if indexes_above_bounds.any(): previous_indexes[indexes_above_bounds] = -1 next_indexes[indexes_above_bounds] = -1 indexes_below_bounds = virtual_indexes < 0 if indexes_below_bounds.any(): previous_indexes[indexes_below_bounds] = 0 next_indexes[indexes_below_bounds] = 0 if np.issubdtype(arr.dtype, np.inexact): virtual_indexes_nans = np.isnan(virtual_indexes) if virtual_indexes_nans.any(): previous_indexes[virtual_indexes_nans] = -1 next_indexes[virtual_indexes_nans] = -1 previous_indexes = previous_indexes.astype(np.intp) next_indexes = next_indexes.astype(np.intp) return (previous_indexes, next_indexes) def _quantile(arr: np.array, quantiles: np.array, axis: int=-1, method='linear', out=None, weights=None): arr = np.asanyarray(arr) values_count = arr.shape[axis] if axis != 0: arr = np.moveaxis(arr, axis, destination=0) supports_nans = np.issubdtype(arr.dtype, np.inexact) or arr.dtype.kind in 'Mm' if weights is None: try: method_props = _QuantileMethods[method] except KeyError: raise ValueError(f'{method!r} is not a valid method. Use one of: {_QuantileMethods.keys()}') from None virtual_indexes = method_props['get_virtual_index'](values_count, quantiles) virtual_indexes = np.asanyarray(virtual_indexes) if method_props['fix_gamma'] is None: supports_integers = True else: int_virtual_indices = np.issubdtype(virtual_indexes.dtype, np.integer) supports_integers = method == 'linear' and int_virtual_indices if supports_integers: if supports_nans: arr.partition(concatenate((virtual_indexes.ravel(), [-1])), axis=0) slices_having_nans = np.isnan(arr[-1, ...]) else: arr.partition(virtual_indexes.ravel(), axis=0) slices_having_nans = np.array(False, dtype=bool) result = take(arr, virtual_indexes, axis=0, out=out) else: (previous_indexes, next_indexes) = _get_indexes(arr, virtual_indexes, values_count) arr.partition(np.unique(np.concatenate(([0, -1], previous_indexes.ravel(), next_indexes.ravel()))), axis=0) if supports_nans: slices_having_nans = np.isnan(arr[-1, ...]) else: slices_having_nans = None previous = arr[previous_indexes] next = arr[next_indexes] gamma = _get_gamma(virtual_indexes, previous_indexes, method_props) result_shape = virtual_indexes.shape + (1,) * (arr.ndim - 1) gamma = gamma.reshape(result_shape) result = _lerp(previous, next, gamma, out=out) else: weights = np.asanyarray(weights) if axis != 0: weights = np.moveaxis(weights, axis, destination=0) index_array = np.argsort(arr, axis=0, kind='stable') arr = np.take_along_axis(arr, index_array, axis=0) if weights.shape == arr.shape: weights = np.take_along_axis(weights, index_array, axis=0) else: weights = weights.reshape(-1)[index_array, ...] if supports_nans: slices_having_nans = np.isnan(arr[-1, ...]) else: slices_having_nans = np.array(False, dtype=bool) cdf = weights.cumsum(axis=0, dtype=np.float64) cdf /= cdf[-1, ...] if quantiles.dtype.kind == 'f': cdf = cdf.astype(quantiles.dtype) def find_cdf_1d(arr, cdf): indices = np.searchsorted(cdf, quantiles, side='left') indices = minimum(indices, values_count - 1) result = take(arr, indices, axis=0) return result r_shape = arr.shape[1:] if quantiles.ndim > 0: r_shape = quantiles.shape + r_shape if out is None: result = np.empty_like(arr, shape=r_shape) else: if out.shape != r_shape: msg = f"Wrong shape of argument 'out', shape={r_shape} is required; got shape={out.shape}." raise ValueError(msg) result = out Nk = arr.shape[1:] for kk in np.ndindex(Nk): result[(...,) + kk] = find_cdf_1d(arr[np.s_[:,] + kk], cdf[np.s_[:,] + kk]) if result.shape == () and result.dtype == np.dtype('O'): result = result.item() if np.any(slices_having_nans): if result.ndim == 0 and out is None: result = arr[-1] else: np.copyto(result, arr[-1, ...], where=slices_having_nans) return result def _trapezoid_dispatcher(y, x=None, dx=None, axis=None): return (y, x) @array_function_dispatch(_trapezoid_dispatcher) def trapezoid(y, x=None, dx=1.0, axis=-1): y = asanyarray(y) if x is None: d = dx else: x = asanyarray(x) if x.ndim == 1: d = diff(x) shape = [1] * y.ndim shape[axis] = d.shape[0] d = d.reshape(shape) else: d = diff(x, axis=axis) nd = y.ndim slice1 = [slice(None)] * nd slice2 = [slice(None)] * nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) try: ret = (d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0).sum(axis) except ValueError: d = np.asarray(d) y = np.asarray(y) ret = add.reduce(d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0, axis) return ret @set_module('numpy') def trapz(y, x=None, dx=1.0, axis=-1): warnings.warn('`trapz` is deprecated. Use `trapezoid` instead, or one of the numerical integration functions in `scipy.integrate`.', DeprecationWarning, stacklevel=2) return trapezoid(y, x=x, dx=dx, axis=axis) def _meshgrid_dispatcher(*xi, copy=None, sparse=None, indexing=None): return xi @array_function_dispatch(_meshgrid_dispatcher) def meshgrid(*xi, copy=True, sparse=False, indexing='xy'): ndim = len(xi) if indexing not in ['xy', 'ij']: raise ValueError("Valid values for `indexing` are 'xy' and 'ij'.") s0 = (1,) * ndim output = [np.asanyarray(x).reshape(s0[:i] + (-1,) + s0[i + 1:]) for (i, x) in enumerate(xi)] if indexing == 'xy' and ndim > 1: output[0].shape = (1, -1) + s0[2:] output[1].shape = (-1, 1) + s0[2:] if not sparse: output = np.broadcast_arrays(*output, subok=True) if copy: output = tuple((x.copy() for x in output)) return output def _delete_dispatcher(arr, obj, axis=None): return (arr, obj) @array_function_dispatch(_delete_dispatcher) def delete(arr, obj, axis=None): conv = _array_converter(arr) (arr,) = conv.as_arrays(subok=False) ndim = arr.ndim arrorder = 'F' if arr.flags.fnc else 'C' if axis is None: if ndim != 1: arr = arr.ravel() ndim = arr.ndim axis = ndim - 1 else: axis = normalize_axis_index(axis, ndim) slobj = [slice(None)] * ndim N = arr.shape[axis] newshape = list(arr.shape) if isinstance(obj, slice): (start, stop, step) = obj.indices(N) xr = range(start, stop, step) numtodel = len(xr) if numtodel <= 0: return conv.wrap(arr.copy(order=arrorder), to_scalar=False) if step < 0: step = -step start = xr[-1] stop = xr[0] + 1 newshape[axis] -= numtodel new = empty(newshape, arr.dtype, arrorder) if start == 0: pass else: slobj[axis] = slice(None, start) new[tuple(slobj)] = arr[tuple(slobj)] if stop == N: pass else: slobj[axis] = slice(stop - numtodel, None) slobj2 = [slice(None)] * ndim slobj2[axis] = slice(stop, None) new[tuple(slobj)] = arr[tuple(slobj2)] if step == 1: pass else: keep = ones(stop - start, dtype=bool) keep[:stop - start:step] = False slobj[axis] = slice(start, stop - numtodel) slobj2 = [slice(None)] * ndim slobj2[axis] = slice(start, stop) arr = arr[tuple(slobj2)] slobj2[axis] = keep new[tuple(slobj)] = arr[tuple(slobj2)] return conv.wrap(new, to_scalar=False) if isinstance(obj, (int, integer)) and (not isinstance(obj, bool)): single_value = True else: single_value = False _obj = obj obj = np.asarray(obj) if obj.size == 0 and (not isinstance(_obj, np.ndarray)): obj = obj.astype(intp) elif obj.size == 1 and obj.dtype.kind in 'ui': obj = obj.item() single_value = True if single_value: if obj < -N or obj >= N: raise IndexError('index %i is out of bounds for axis %i with size %i' % (obj, axis, N)) if obj < 0: obj += N newshape[axis] -= 1 new = empty(newshape, arr.dtype, arrorder) slobj[axis] = slice(None, obj) new[tuple(slobj)] = arr[tuple(slobj)] slobj[axis] = slice(obj, None) slobj2 = [slice(None)] * ndim slobj2[axis] = slice(obj + 1, None) new[tuple(slobj)] = arr[tuple(slobj2)] else: if obj.dtype == bool: if obj.shape != (N,): raise ValueError('boolean array argument obj to delete must be one dimensional and match the axis length of {}'.format(N)) keep = ~obj else: keep = ones(N, dtype=bool) keep[obj,] = False slobj[axis] = keep new = arr[tuple(slobj)] return conv.wrap(new, to_scalar=False) def _insert_dispatcher(arr, obj, values, axis=None): return (arr, obj, values) @array_function_dispatch(_insert_dispatcher) def insert(arr, obj, values, axis=None): conv = _array_converter(arr) (arr,) = conv.as_arrays(subok=False) ndim = arr.ndim arrorder = 'F' if arr.flags.fnc else 'C' if axis is None: if ndim != 1: arr = arr.ravel() ndim = arr.ndim axis = ndim - 1 else: axis = normalize_axis_index(axis, ndim) slobj = [slice(None)] * ndim N = arr.shape[axis] newshape = list(arr.shape) if isinstance(obj, slice): indices = arange(*obj.indices(N), dtype=intp) else: indices = np.array(obj) if indices.dtype == bool: warnings.warn('in the future insert will treat boolean arrays and array-likes as a boolean index instead of casting it to integer', FutureWarning, stacklevel=2) indices = indices.astype(intp) elif indices.ndim > 1: raise ValueError('index array argument obj to insert must be one dimensional or scalar') if indices.size == 1: index = indices.item() if index < -N or index > N: raise IndexError(f'index {obj} is out of bounds for axis {axis} with size {N}') if index < 0: index += N values = array(values, copy=None, ndmin=arr.ndim, dtype=arr.dtype) if indices.ndim == 0: values = np.moveaxis(values, 0, axis) numnew = values.shape[axis] newshape[axis] += numnew new = empty(newshape, arr.dtype, arrorder) slobj[axis] = slice(None, index) new[tuple(slobj)] = arr[tuple(slobj)] slobj[axis] = slice(index, index + numnew) new[tuple(slobj)] = values slobj[axis] = slice(index + numnew, None) slobj2 = [slice(None)] * ndim slobj2[axis] = slice(index, None) new[tuple(slobj)] = arr[tuple(slobj2)] return conv.wrap(new, to_scalar=False) elif indices.size == 0 and (not isinstance(obj, np.ndarray)): indices = indices.astype(intp) indices[indices < 0] += N numnew = len(indices) order = indices.argsort(kind='mergesort') indices[order] += np.arange(numnew) newshape[axis] += numnew old_mask = ones(newshape[axis], dtype=bool) old_mask[indices] = False new = empty(newshape, arr.dtype, arrorder) slobj2 = [slice(None)] * ndim slobj[axis] = indices slobj2[axis] = old_mask new[tuple(slobj)] = values new[tuple(slobj2)] = arr return conv.wrap(new, to_scalar=False) def _append_dispatcher(arr, values, axis=None): return (arr, values) @array_function_dispatch(_append_dispatcher) def append(arr, values, axis=None): arr = asanyarray(arr) if axis is None: if arr.ndim != 1: arr = arr.ravel() values = ravel(values) axis = arr.ndim - 1 return concatenate((arr, values), axis=axis) def _digitize_dispatcher(x, bins, right=None): return (x, bins) @array_function_dispatch(_digitize_dispatcher) def digitize(x, bins, right=False): x = _nx.asarray(x) bins = _nx.asarray(bins) if np.issubdtype(x.dtype, _nx.complexfloating): raise TypeError('x may not be complex') mono = _monotonicity(bins) if mono == 0: raise ValueError('bins must be monotonically increasing or decreasing') side = 'left' if right else 'right' if mono == -1: return len(bins) - _nx.searchsorted(bins[::-1], x, side=side) else: return _nx.searchsorted(bins, x, side=side) # File: numpy-main/numpy/lib/_histograms_impl.py """""" import contextlib import functools import operator import warnings import numpy as np from numpy._core import overrides __all__ = ['histogram', 'histogramdd', 'histogram_bin_edges'] array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') _range = range def _ptp(x): return _unsigned_subtract(x.max(), x.min()) def _hist_bin_sqrt(x, range): del range return _ptp(x) / np.sqrt(x.size) def _hist_bin_sturges(x, range): del range return _ptp(x) / (np.log2(x.size) + 1.0) def _hist_bin_rice(x, range): del range return _ptp(x) / (2.0 * x.size ** (1.0 / 3)) def _hist_bin_scott(x, range): del range return (24.0 * np.pi ** 0.5 / x.size) ** (1.0 / 3.0) * np.std(x) def _hist_bin_stone(x, range): n = x.size ptp_x = _ptp(x) if n <= 1 or ptp_x == 0: return 0 def jhat(nbins): hh = ptp_x / nbins p_k = np.histogram(x, bins=nbins, range=range)[0] / n return (2 - (n + 1) * p_k.dot(p_k)) / hh nbins_upper_bound = max(100, int(np.sqrt(n))) nbins = min(_range(1, nbins_upper_bound + 1), key=jhat) if nbins == nbins_upper_bound: warnings.warn('The number of bins estimated may be suboptimal.', RuntimeWarning, stacklevel=3) return ptp_x / nbins def _hist_bin_doane(x, range): del range if x.size > 2: sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3))) sigma = np.std(x) if sigma > 0.0: temp = x - np.mean(x) np.true_divide(temp, sigma, temp) np.power(temp, 3, temp) g1 = np.mean(temp) return _ptp(x) / (1.0 + np.log2(x.size) + np.log2(1.0 + np.absolute(g1) / sg1)) return 0.0 def _hist_bin_fd(x, range): del range iqr = np.subtract(*np.percentile(x, [75, 25])) return 2.0 * iqr * x.size ** (-1.0 / 3.0) def _hist_bin_auto(x, range): fd_bw = _hist_bin_fd(x, range) sturges_bw = _hist_bin_sturges(x, range) del range if fd_bw: return min(fd_bw, sturges_bw) else: return sturges_bw _hist_bin_selectors = {'stone': _hist_bin_stone, 'auto': _hist_bin_auto, 'doane': _hist_bin_doane, 'fd': _hist_bin_fd, 'rice': _hist_bin_rice, 'scott': _hist_bin_scott, 'sqrt': _hist_bin_sqrt, 'sturges': _hist_bin_sturges} def _ravel_and_check_weights(a, weights): a = np.asarray(a) if a.dtype == np.bool: warnings.warn('Converting input from {} to {} for compatibility.'.format(a.dtype, np.uint8), RuntimeWarning, stacklevel=3) a = a.astype(np.uint8) if weights is not None: weights = np.asarray(weights) if weights.shape != a.shape: raise ValueError('weights should have the same shape as a.') weights = weights.ravel() a = a.ravel() return (a, weights) def _get_outer_edges(a, range): if range is not None: (first_edge, last_edge) = range if first_edge > last_edge: raise ValueError('max must be larger than min in range parameter.') if not (np.isfinite(first_edge) and np.isfinite(last_edge)): raise ValueError('supplied range of [{}, {}] is not finite'.format(first_edge, last_edge)) elif a.size == 0: (first_edge, last_edge) = (0, 1) else: (first_edge, last_edge) = (a.min(), a.max()) if not (np.isfinite(first_edge) and np.isfinite(last_edge)): raise ValueError('autodetected range of [{}, {}] is not finite'.format(first_edge, last_edge)) if first_edge == last_edge: first_edge = first_edge - 0.5 last_edge = last_edge + 0.5 return (first_edge, last_edge) def _unsigned_subtract(a, b): signed_to_unsigned = {np.byte: np.ubyte, np.short: np.ushort, np.intc: np.uintc, np.int_: np.uint, np.longlong: np.ulonglong} dt = np.result_type(a, b) try: unsigned_dt = signed_to_unsigned[dt.type] except KeyError: return np.subtract(a, b, dtype=dt) else: return np.subtract(np.asarray(a, dtype=dt), np.asarray(b, dtype=dt), casting='unsafe', dtype=unsigned_dt) def _get_bin_edges(a, bins, range, weights): n_equal_bins = None bin_edges = None if isinstance(bins, str): bin_name = bins if bin_name not in _hist_bin_selectors: raise ValueError('{!r} is not a valid estimator for `bins`'.format(bin_name)) if weights is not None: raise TypeError('Automated estimation of the number of bins is not supported for weighted data') (first_edge, last_edge) = _get_outer_edges(a, range) if range is not None: keep = a >= first_edge keep &= a <= last_edge if not np.logical_and.reduce(keep): a = a[keep] if a.size == 0: n_equal_bins = 1 else: width = _hist_bin_selectors[bin_name](a, (first_edge, last_edge)) if width: if np.issubdtype(a.dtype, np.integer) and width < 1: width = 1 n_equal_bins = int(np.ceil(_unsigned_subtract(last_edge, first_edge) / width)) else: n_equal_bins = 1 elif np.ndim(bins) == 0: try: n_equal_bins = operator.index(bins) except TypeError as e: raise TypeError('`bins` must be an integer, a string, or an array') from e if n_equal_bins < 1: raise ValueError('`bins` must be positive, when an integer') (first_edge, last_edge) = _get_outer_edges(a, range) elif np.ndim(bins) == 1: bin_edges = np.asarray(bins) if np.any(bin_edges[:-1] > bin_edges[1:]): raise ValueError('`bins` must increase monotonically, when an array') else: raise ValueError('`bins` must be 1d, when an array') if n_equal_bins is not None: bin_type = np.result_type(first_edge, last_edge, a) if np.issubdtype(bin_type, np.integer): bin_type = np.result_type(bin_type, float) bin_edges = np.linspace(first_edge, last_edge, n_equal_bins + 1, endpoint=True, dtype=bin_type) if np.any(bin_edges[:-1] >= bin_edges[1:]): raise ValueError(f'Too many bins for data range. Cannot create {n_equal_bins} finite-sized bins.') return (bin_edges, (first_edge, last_edge, n_equal_bins)) else: return (bin_edges, None) def _search_sorted_inclusive(a, v): return np.concatenate((a.searchsorted(v[:-1], 'left'), a.searchsorted(v[-1:], 'right'))) def _histogram_bin_edges_dispatcher(a, bins=None, range=None, weights=None): return (a, bins, weights) @array_function_dispatch(_histogram_bin_edges_dispatcher) def histogram_bin_edges(a, bins=10, range=None, weights=None): (a, weights) = _ravel_and_check_weights(a, weights) (bin_edges, _) = _get_bin_edges(a, bins, range, weights) return bin_edges def _histogram_dispatcher(a, bins=None, range=None, density=None, weights=None): return (a, bins, weights) @array_function_dispatch(_histogram_dispatcher) def histogram(a, bins=10, range=None, density=None, weights=None): (a, weights) = _ravel_and_check_weights(a, weights) (bin_edges, uniform_bins) = _get_bin_edges(a, bins, range, weights) if weights is None: ntype = np.dtype(np.intp) else: ntype = weights.dtype BLOCK = 65536 simple_weights = weights is None or np.can_cast(weights.dtype, np.double) or np.can_cast(weights.dtype, complex) if uniform_bins is not None and simple_weights: (first_edge, last_edge, n_equal_bins) = uniform_bins n = np.zeros(n_equal_bins, ntype) norm_numerator = n_equal_bins norm_denom = _unsigned_subtract(last_edge, first_edge) for i in _range(0, len(a), BLOCK): tmp_a = a[i:i + BLOCK] if weights is None: tmp_w = None else: tmp_w = weights[i:i + BLOCK] keep = tmp_a >= first_edge keep &= tmp_a <= last_edge if not np.logical_and.reduce(keep): tmp_a = tmp_a[keep] if tmp_w is not None: tmp_w = tmp_w[keep] tmp_a = tmp_a.astype(bin_edges.dtype, copy=False) f_indices = _unsigned_subtract(tmp_a, first_edge) / norm_denom * norm_numerator indices = f_indices.astype(np.intp) indices[indices == n_equal_bins] -= 1 decrement = tmp_a < bin_edges[indices] indices[decrement] -= 1 increment = (tmp_a >= bin_edges[indices + 1]) & (indices != n_equal_bins - 1) indices[increment] += 1 if ntype.kind == 'c': n.real += np.bincount(indices, weights=tmp_w.real, minlength=n_equal_bins) n.imag += np.bincount(indices, weights=tmp_w.imag, minlength=n_equal_bins) else: n += np.bincount(indices, weights=tmp_w, minlength=n_equal_bins).astype(ntype) else: cum_n = np.zeros(bin_edges.shape, ntype) if weights is None: for i in _range(0, len(a), BLOCK): sa = np.sort(a[i:i + BLOCK]) cum_n += _search_sorted_inclusive(sa, bin_edges) else: zero = np.zeros(1, dtype=ntype) for i in _range(0, len(a), BLOCK): tmp_a = a[i:i + BLOCK] tmp_w = weights[i:i + BLOCK] sorting_index = np.argsort(tmp_a) sa = tmp_a[sorting_index] sw = tmp_w[sorting_index] cw = np.concatenate((zero, sw.cumsum())) bin_index = _search_sorted_inclusive(sa, bin_edges) cum_n += cw[bin_index] n = np.diff(cum_n) if density: db = np.array(np.diff(bin_edges), float) return (n / db / n.sum(), bin_edges) return (n, bin_edges) def _histogramdd_dispatcher(sample, bins=None, range=None, density=None, weights=None): if hasattr(sample, 'shape'): yield sample else: yield from sample with contextlib.suppress(TypeError): yield from bins yield weights @array_function_dispatch(_histogramdd_dispatcher) def histogramdd(sample, bins=10, range=None, density=None, weights=None): try: (N, D) = sample.shape except (AttributeError, ValueError): sample = np.atleast_2d(sample).T (N, D) = sample.shape nbin = np.empty(D, np.intp) edges = D * [None] dedges = D * [None] if weights is not None: weights = np.asarray(weights) try: M = len(bins) if M != D: raise ValueError('The dimension of bins must be equal to the dimension of the sample x.') except TypeError: bins = D * [bins] if range is None: range = (None,) * D elif len(range) != D: raise ValueError('range argument must have one entry per dimension') for i in _range(D): if np.ndim(bins[i]) == 0: if bins[i] < 1: raise ValueError('`bins[{}]` must be positive, when an integer'.format(i)) (smin, smax) = _get_outer_edges(sample[:, i], range[i]) try: n = operator.index(bins[i]) except TypeError as e: raise TypeError('`bins[{}]` must be an integer, when a scalar'.format(i)) from e edges[i] = np.linspace(smin, smax, n + 1) elif np.ndim(bins[i]) == 1: edges[i] = np.asarray(bins[i]) if np.any(edges[i][:-1] > edges[i][1:]): raise ValueError('`bins[{}]` must be monotonically increasing, when an array'.format(i)) else: raise ValueError('`bins[{}]` must be a scalar or 1d array'.format(i)) nbin[i] = len(edges[i]) + 1 dedges[i] = np.diff(edges[i]) Ncount = tuple((np.searchsorted(edges[i], sample[:, i], side='right') for i in _range(D))) for i in _range(D): on_edge = sample[:, i] == edges[i][-1] Ncount[i][on_edge] -= 1 xy = np.ravel_multi_index(Ncount, nbin) hist = np.bincount(xy, weights, minlength=nbin.prod()) hist = hist.reshape(nbin) hist = hist.astype(float, casting='safe') core = D * (slice(1, -1),) hist = hist[core] if density: s = hist.sum() for i in _range(D): shape = np.ones(D, int) shape[i] = nbin[i] - 2 hist = hist / dedges[i].reshape(shape) hist /= s if (hist.shape != nbin - 2).any(): raise RuntimeError('Internal Shape Error') return (hist, edges) # File: numpy-main/numpy/lib/_index_tricks_impl.py import functools import sys import math import warnings import numpy as np from .._utils import set_module import numpy._core.numeric as _nx from numpy._core.numeric import ScalarType, array from numpy._core.numerictypes import issubdtype import numpy.matrixlib as matrixlib from numpy._core.multiarray import ravel_multi_index, unravel_index from numpy._core import overrides, linspace from numpy.lib.stride_tricks import as_strided from numpy.lib._function_base_impl import diff array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') __all__ = ['ravel_multi_index', 'unravel_index', 'mgrid', 'ogrid', 'r_', 'c_', 's_', 'index_exp', 'ix_', 'ndenumerate', 'ndindex', 'fill_diagonal', 'diag_indices', 'diag_indices_from'] def _ix__dispatcher(*args): return args @array_function_dispatch(_ix__dispatcher) def ix_(*args): out = [] nd = len(args) for (k, new) in enumerate(args): if not isinstance(new, _nx.ndarray): new = np.asarray(new) if new.size == 0: new = new.astype(_nx.intp) if new.ndim != 1: raise ValueError('Cross index must be 1 dimensional') if issubdtype(new.dtype, _nx.bool): (new,) = new.nonzero() new = new.reshape((1,) * k + (new.size,) + (1,) * (nd - k - 1)) out.append(new) return tuple(out) class nd_grid: __slots__ = ('sparse',) def __init__(self, sparse=False): self.sparse = sparse def __getitem__(self, key): try: size = [] num_list = [0] for k in range(len(key)): step = key[k].step start = key[k].start stop = key[k].stop if start is None: start = 0 if step is None: step = 1 if isinstance(step, (_nx.complexfloating, complex)): step = abs(step) size.append(int(step)) else: size.append(int(math.ceil((stop - start) / (step * 1.0)))) num_list += [start, stop, step] typ = _nx.result_type(*num_list) if self.sparse: nn = [_nx.arange(_x, dtype=_t) for (_x, _t) in zip(size, (typ,) * len(size))] else: nn = _nx.indices(size, typ) for (k, kk) in enumerate(key): step = kk.step start = kk.start if start is None: start = 0 if step is None: step = 1 if isinstance(step, (_nx.complexfloating, complex)): step = int(abs(step)) if step != 1: step = (kk.stop - start) / float(step - 1) nn[k] = nn[k] * step + start if self.sparse: slobj = [_nx.newaxis] * len(size) for k in range(len(size)): slobj[k] = slice(None, None) nn[k] = nn[k][tuple(slobj)] slobj[k] = _nx.newaxis return tuple(nn) return nn except (IndexError, TypeError): step = key.step stop = key.stop start = key.start if start is None: start = 0 if isinstance(step, (_nx.complexfloating, complex)): step_float = abs(step) step = length = int(step_float) if step != 1: step = (key.stop - start) / float(step - 1) typ = _nx.result_type(start, stop, step_float) return _nx.arange(0, length, 1, dtype=typ) * step + start else: return _nx.arange(start, stop, step) class MGridClass(nd_grid): __slots__ = () def __init__(self): super().__init__(sparse=False) mgrid = MGridClass() class OGridClass(nd_grid): __slots__ = () def __init__(self): super().__init__(sparse=True) ogrid = OGridClass() class AxisConcatenator: __slots__ = ('axis', 'matrix', 'trans1d', 'ndmin') concatenate = staticmethod(_nx.concatenate) makemat = staticmethod(matrixlib.matrix) def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1): self.axis = axis self.matrix = matrix self.trans1d = trans1d self.ndmin = ndmin def __getitem__(self, key): if isinstance(key, str): frame = sys._getframe().f_back mymat = matrixlib.bmat(key, frame.f_globals, frame.f_locals) return mymat if not isinstance(key, tuple): key = (key,) trans1d = self.trans1d ndmin = self.ndmin matrix = self.matrix axis = self.axis objs = [] result_type_objs = [] for (k, item) in enumerate(key): scalar = False if isinstance(item, slice): step = item.step start = item.start stop = item.stop if start is None: start = 0 if step is None: step = 1 if isinstance(step, (_nx.complexfloating, complex)): size = int(abs(step)) newobj = linspace(start, stop, num=size) else: newobj = _nx.arange(start, stop, step) if ndmin > 1: newobj = array(newobj, copy=None, ndmin=ndmin) if trans1d != -1: newobj = newobj.swapaxes(-1, trans1d) elif isinstance(item, str): if k != 0: raise ValueError('special directives must be the first entry.') if item in ('r', 'c'): matrix = True col = item == 'c' continue if ',' in item: vec = item.split(',') try: (axis, ndmin) = [int(x) for x in vec[:2]] if len(vec) == 3: trans1d = int(vec[2]) continue except Exception as e: raise ValueError('unknown special directive {!r}'.format(item)) from e try: axis = int(item) continue except (ValueError, TypeError) as e: raise ValueError('unknown special directive') from e elif type(item) in ScalarType: scalar = True newobj = item else: item_ndim = np.ndim(item) newobj = array(item, copy=None, subok=True, ndmin=ndmin) if trans1d != -1 and item_ndim < ndmin: k2 = ndmin - item_ndim k1 = trans1d if k1 < 0: k1 += k2 + 1 defaxes = list(range(ndmin)) axes = defaxes[:k1] + defaxes[k2:] + defaxes[k1:k2] newobj = newobj.transpose(axes) objs.append(newobj) if scalar: result_type_objs.append(item) else: result_type_objs.append(newobj.dtype) if len(result_type_objs) != 0: final_dtype = _nx.result_type(*result_type_objs) objs = [array(obj, copy=None, subok=True, ndmin=ndmin, dtype=final_dtype) for obj in objs] res = self.concatenate(tuple(objs), axis=axis) if matrix: oldndim = res.ndim res = self.makemat(res) if oldndim == 1 and col: res = res.T return res def __len__(self): return 0 class RClass(AxisConcatenator): __slots__ = () def __init__(self): AxisConcatenator.__init__(self, 0) r_ = RClass() class CClass(AxisConcatenator): __slots__ = () def __init__(self): AxisConcatenator.__init__(self, -1, ndmin=2, trans1d=0) c_ = CClass() @set_module('numpy') class ndenumerate: def __init__(self, arr): self.iter = np.asarray(arr).flat def __next__(self): return (self.iter.coords, next(self.iter)) def __iter__(self): return self @set_module('numpy') class ndindex: def __init__(self, *shape): if len(shape) == 1 and isinstance(shape[0], tuple): shape = shape[0] x = as_strided(_nx.zeros(1), shape=shape, strides=_nx.zeros_like(shape)) self._it = _nx.nditer(x, flags=['multi_index', 'zerosize_ok'], order='C') def __iter__(self): return self def ndincr(self): warnings.warn('`ndindex.ndincr()` is deprecated, use `next(ndindex)` instead', DeprecationWarning, stacklevel=2) next(self) def __next__(self): next(self._it) return self._it.multi_index class IndexExpression: __slots__ = ('maketuple',) def __init__(self, maketuple): self.maketuple = maketuple def __getitem__(self, item): if self.maketuple and (not isinstance(item, tuple)): return (item,) else: return item index_exp = IndexExpression(maketuple=True) s_ = IndexExpression(maketuple=False) def _fill_diagonal_dispatcher(a, val, wrap=None): return (a,) @array_function_dispatch(_fill_diagonal_dispatcher) def fill_diagonal(a, val, wrap=False): if a.ndim < 2: raise ValueError('array must be at least 2-d') end = None if a.ndim == 2: step = a.shape[1] + 1 if not wrap: end = a.shape[1] * a.shape[1] else: if not np.all(diff(a.shape) == 0): raise ValueError('All dimensions of input must be of equal length') step = 1 + np.cumprod(a.shape[:-1]).sum() a.flat[:end:step] = val @set_module('numpy') def diag_indices(n, ndim=2): idx = np.arange(n) return (idx,) * ndim def _diag_indices_from(arr): return (arr,) @array_function_dispatch(_diag_indices_from) def diag_indices_from(arr): if not arr.ndim >= 2: raise ValueError('input array must be at least 2-d') if not np.all(diff(arr.shape) == 0): raise ValueError('All dimensions of input must be of equal length') return diag_indices(arr.shape[0], arr.ndim) # File: numpy-main/numpy/lib/_iotools.py """""" __docformat__ = 'restructuredtext en' import numpy as np import numpy._core.numeric as nx from numpy._utils import asbytes, asunicode def _decode_line(line, encoding=None): if type(line) is bytes: if encoding is None: encoding = 'latin1' line = line.decode(encoding) return line def _is_string_like(obj): try: obj + '' except (TypeError, ValueError): return False return True def _is_bytes_like(obj): try: obj + b'' except (TypeError, ValueError): return False return True def has_nested_fields(ndtype): return any((ndtype[name].names is not None for name in ndtype.names or ())) def flatten_dtype(ndtype, flatten_base=False): names = ndtype.names if names is None: if flatten_base: return [ndtype.base] * int(np.prod(ndtype.shape)) return [ndtype.base] else: types = [] for field in names: info = ndtype.fields[field] flat_dt = flatten_dtype(info[0], flatten_base) types.extend(flat_dt) return types class LineSplitter: def autostrip(self, method): return lambda input: [_.strip() for _ in method(input)] def __init__(self, delimiter=None, comments='#', autostrip=True, encoding=None): delimiter = _decode_line(delimiter) comments = _decode_line(comments) self.comments = comments if delimiter is None or isinstance(delimiter, str): delimiter = delimiter or None _handyman = self._delimited_splitter elif hasattr(delimiter, '__iter__'): _handyman = self._variablewidth_splitter idx = np.cumsum([0] + list(delimiter)) delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])] elif int(delimiter): (_handyman, delimiter) = (self._fixedwidth_splitter, int(delimiter)) else: (_handyman, delimiter) = (self._delimited_splitter, None) self.delimiter = delimiter if autostrip: self._handyman = self.autostrip(_handyman) else: self._handyman = _handyman self.encoding = encoding def _delimited_splitter(self, line): if self.comments is not None: line = line.split(self.comments)[0] line = line.strip(' \r\n') if not line: return [] return line.split(self.delimiter) def _fixedwidth_splitter(self, line): if self.comments is not None: line = line.split(self.comments)[0] line = line.strip('\r\n') if not line: return [] fixed = self.delimiter slices = [slice(i, i + fixed) for i in range(0, len(line), fixed)] return [line[s] for s in slices] def _variablewidth_splitter(self, line): if self.comments is not None: line = line.split(self.comments)[0] if not line: return [] slices = self.delimiter return [line[s] for s in slices] def __call__(self, line): return self._handyman(_decode_line(line, self.encoding)) class NameValidator: defaultexcludelist = ['return', 'file', 'print'] defaultdeletechars = set("~!@#$%^&*()-=+~\\|]}[{';: /?.>,<") def __init__(self, excludelist=None, deletechars=None, case_sensitive=None, replace_space='_'): if excludelist is None: excludelist = [] excludelist.extend(self.defaultexcludelist) self.excludelist = excludelist if deletechars is None: delete = self.defaultdeletechars else: delete = set(deletechars) delete.add('"') self.deletechars = delete if case_sensitive is None or case_sensitive is True: self.case_converter = lambda x: x elif case_sensitive is False or case_sensitive.startswith('u'): self.case_converter = lambda x: x.upper() elif case_sensitive.startswith('l'): self.case_converter = lambda x: x.lower() else: msg = 'unrecognized case_sensitive value %s.' % case_sensitive raise ValueError(msg) self.replace_space = replace_space def validate(self, names, defaultfmt='f%i', nbfields=None): if names is None: if nbfields is None: return None names = [] if isinstance(names, str): names = [names] if nbfields is not None: nbnames = len(names) if nbnames < nbfields: names = list(names) + [''] * (nbfields - nbnames) elif nbnames > nbfields: names = names[:nbfields] deletechars = self.deletechars excludelist = self.excludelist case_converter = self.case_converter replace_space = self.replace_space validatednames = [] seen = dict() nbempty = 0 for item in names: item = case_converter(item).strip() if replace_space: item = item.replace(' ', replace_space) item = ''.join([c for c in item if c not in deletechars]) if item == '': item = defaultfmt % nbempty while item in names: nbempty += 1 item = defaultfmt % nbempty nbempty += 1 elif item in excludelist: item += '_' cnt = seen.get(item, 0) if cnt > 0: validatednames.append(item + '_%d' % cnt) else: validatednames.append(item) seen[item] = cnt + 1 return tuple(validatednames) def __call__(self, names, defaultfmt='f%i', nbfields=None): return self.validate(names, defaultfmt=defaultfmt, nbfields=nbfields) def str2bool(value): value = value.upper() if value == 'TRUE': return True elif value == 'FALSE': return False else: raise ValueError('Invalid boolean') class ConverterError(Exception): pass class ConverterLockError(ConverterError): pass class ConversionWarning(UserWarning): pass class StringConverter: _mapper = [(nx.bool, str2bool, False), (nx.int_, int, -1)] if nx.dtype(nx.int_).itemsize < nx.dtype(nx.int64).itemsize: _mapper.append((nx.int64, int, -1)) _mapper.extend([(nx.float64, float, nx.nan), (nx.complex128, complex, nx.nan + 0j), (nx.longdouble, nx.longdouble, nx.nan), (nx.integer, int, -1), (nx.floating, float, nx.nan), (nx.complexfloating, complex, nx.nan + 0j), (nx.str_, asunicode, '???'), (nx.bytes_, asbytes, '???')]) @classmethod def _getdtype(cls, val): return np.array(val).dtype @classmethod def _getsubdtype(cls, val): return np.array(val).dtype.type @classmethod def _dtypeortype(cls, dtype): if dtype.type == np.datetime64: return dtype return dtype.type @classmethod def upgrade_mapper(cls, func, default=None): if callable(func): cls._mapper.insert(-1, (cls._getsubdtype(default), func, default)) return elif hasattr(func, '__iter__'): if isinstance(func[0], (tuple, list)): for _ in func: cls._mapper.insert(-1, _) return if default is None: default = [None] * len(func) else: default = list(default) default.append([None] * (len(func) - len(default))) for (fct, dft) in zip(func, default): cls._mapper.insert(-1, (cls._getsubdtype(dft), fct, dft)) @classmethod def _find_map_entry(cls, dtype): for (i, (deftype, func, default_def)) in enumerate(cls._mapper): if dtype.type == deftype: return (i, (deftype, func, default_def)) for (i, (deftype, func, default_def)) in enumerate(cls._mapper): if np.issubdtype(dtype.type, deftype): return (i, (deftype, func, default_def)) raise LookupError def __init__(self, dtype_or_func=None, default=None, missing_values=None, locked=False): self._locked = bool(locked) if dtype_or_func is None: self.func = str2bool self._status = 0 self.default = default or False dtype = np.dtype('bool') else: try: self.func = None dtype = np.dtype(dtype_or_func) except TypeError: if not callable(dtype_or_func): errmsg = "The input argument `dtype` is neither a function nor a dtype (got '%s' instead)" raise TypeError(errmsg % type(dtype_or_func)) self.func = dtype_or_func if default is None: try: default = self.func('0') except ValueError: default = None dtype = self._getdtype(default) try: (self._status, (_, func, default_def)) = self._find_map_entry(dtype) except LookupError: self.default = default (_, func, _) = self._mapper[-1] self._status = 0 else: if default is None: self.default = default_def else: self.default = default if self.func is None: self.func = func if self.func == self._mapper[1][1]: if issubclass(dtype.type, np.uint64): self.func = np.uint64 elif issubclass(dtype.type, np.int64): self.func = np.int64 else: self.func = lambda x: int(float(x)) if missing_values is None: self.missing_values = {''} else: if isinstance(missing_values, str): missing_values = missing_values.split(',') self.missing_values = set(list(missing_values) + ['']) self._callingfunction = self._strict_call self.type = self._dtypeortype(dtype) self._checked = False self._initial_default = default def _loose_call(self, value): try: return self.func(value) except ValueError: return self.default def _strict_call(self, value): try: new_value = self.func(value) if self.func is int: try: np.array(value, dtype=self.type) except OverflowError: raise ValueError return new_value except ValueError: if value.strip() in self.missing_values: if not self._status: self._checked = False return self.default raise ValueError("Cannot convert string '%s'" % value) def __call__(self, value): return self._callingfunction(value) def _do_upgrade(self): if self._locked: errmsg = 'Converter is locked and cannot be upgraded' raise ConverterLockError(errmsg) _statusmax = len(self._mapper) _status = self._status if _status == _statusmax: errmsg = 'Could not find a valid conversion function' raise ConverterError(errmsg) elif _status < _statusmax - 1: _status += 1 (self.type, self.func, default) = self._mapper[_status] self._status = _status if self._initial_default is not None: self.default = self._initial_default else: self.default = default def upgrade(self, value): self._checked = True try: return self._strict_call(value) except ValueError: self._do_upgrade() return self.upgrade(value) def iterupgrade(self, value): self._checked = True if not hasattr(value, '__iter__'): value = (value,) _strict_call = self._strict_call try: for _m in value: _strict_call(_m) except ValueError: self._do_upgrade() self.iterupgrade(value) def update(self, func, default=None, testing_value=None, missing_values='', locked=False): self.func = func self._locked = locked if default is not None: self.default = default self.type = self._dtypeortype(self._getdtype(default)) else: try: tester = func(testing_value or '1') except (TypeError, ValueError): tester = None self.type = self._dtypeortype(self._getdtype(tester)) if missing_values is None: self.missing_values = set() else: if not np.iterable(missing_values): missing_values = [missing_values] if not all((isinstance(v, str) for v in missing_values)): raise TypeError('missing_values must be strings or unicode') self.missing_values.update(missing_values) def easy_dtype(ndtype, names=None, defaultfmt='f%i', **validationargs): try: ndtype = np.dtype(ndtype) except TypeError: validate = NameValidator(**validationargs) nbfields = len(ndtype) if names is None: names = [''] * len(ndtype) elif isinstance(names, str): names = names.split(',') names = validate(names, nbfields=nbfields, defaultfmt=defaultfmt) ndtype = np.dtype(dict(formats=ndtype, names=names)) else: if names is not None: validate = NameValidator(**validationargs) if isinstance(names, str): names = names.split(',') if ndtype.names is None: formats = tuple([ndtype.type] * len(names)) names = validate(names, defaultfmt=defaultfmt) ndtype = np.dtype(list(zip(names, formats))) else: ndtype.names = validate(names, nbfields=len(ndtype.names), defaultfmt=defaultfmt) elif ndtype.names is not None: validate = NameValidator(**validationargs) numbered_names = tuple(('f%i' % i for i in range(len(ndtype.names)))) if ndtype.names == numbered_names and defaultfmt != 'f%i': ndtype.names = validate([''] * len(ndtype.names), defaultfmt=defaultfmt) else: ndtype.names = validate(ndtype.names, defaultfmt=defaultfmt) return ndtype # File: numpy-main/numpy/lib/_nanfunctions_impl.py """""" import functools import warnings import numpy as np import numpy._core.numeric as _nx from numpy.lib import _function_base_impl as fnb from numpy.lib._function_base_impl import _weights_are_valid from numpy._core import overrides array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') __all__ = ['nansum', 'nanmax', 'nanmin', 'nanargmax', 'nanargmin', 'nanmean', 'nanmedian', 'nanpercentile', 'nanvar', 'nanstd', 'nanprod', 'nancumsum', 'nancumprod', 'nanquantile'] def _nan_mask(a, out=None): if a.dtype.kind not in 'fc': return True y = np.isnan(a, out=out) y = np.invert(y, out=y) return y def _replace_nan(a, val): a = np.asanyarray(a) if a.dtype == np.object_: mask = np.not_equal(a, a, dtype=bool) elif issubclass(a.dtype.type, np.inexact): mask = np.isnan(a) else: mask = None if mask is not None: a = np.array(a, subok=True, copy=True) np.copyto(a, val, where=mask) return (a, mask) def _copyto(a, val, mask): if isinstance(a, np.ndarray): np.copyto(a, val, where=mask, casting='unsafe') else: a = a.dtype.type(val) return a def _remove_nan_1d(arr1d, second_arr1d=None, overwrite_input=False): if arr1d.dtype == object: c = np.not_equal(arr1d, arr1d, dtype=bool) else: c = np.isnan(arr1d) s = np.nonzero(c)[0] if s.size == arr1d.size: warnings.warn('All-NaN slice encountered', RuntimeWarning, stacklevel=6) if second_arr1d is None: return (arr1d[:0], None, True) else: return (arr1d[:0], second_arr1d[:0], True) elif s.size == 0: return (arr1d, second_arr1d, overwrite_input) else: if not overwrite_input: arr1d = arr1d.copy() enonan = arr1d[-s.size:][~c[-s.size:]] arr1d[s[:enonan.size]] = enonan if second_arr1d is None: return (arr1d[:-s.size], None, True) else: if not overwrite_input: second_arr1d = second_arr1d.copy() enonan = second_arr1d[-s.size:][~c[-s.size:]] second_arr1d[s[:enonan.size]] = enonan return (arr1d[:-s.size], second_arr1d[:-s.size], True) def _divide_by_count(a, b, out=None): with np.errstate(invalid='ignore', divide='ignore'): if isinstance(a, np.ndarray): if out is None: return np.divide(a, b, out=a, casting='unsafe') else: return np.divide(a, b, out=out, casting='unsafe') elif out is None: try: return a.dtype.type(a / b) except AttributeError: return a / b else: return np.divide(a, b, out=out, casting='unsafe') def _nanmin_dispatcher(a, axis=None, out=None, keepdims=None, initial=None, where=None): return (a, out) @array_function_dispatch(_nanmin_dispatcher) def nanmin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue): kwargs = {} if keepdims is not np._NoValue: kwargs['keepdims'] = keepdims if initial is not np._NoValue: kwargs['initial'] = initial if where is not np._NoValue: kwargs['where'] = where if type(a) is np.ndarray and a.dtype != np.object_: res = np.fmin.reduce(a, axis=axis, out=out, **kwargs) if np.isnan(res).any(): warnings.warn('All-NaN slice encountered', RuntimeWarning, stacklevel=2) else: (a, mask) = _replace_nan(a, +np.inf) res = np.amin(a, axis=axis, out=out, **kwargs) if mask is None: return res kwargs.pop('initial', None) mask = np.all(mask, axis=axis, **kwargs) if np.any(mask): res = _copyto(res, np.nan, mask) warnings.warn('All-NaN axis encountered', RuntimeWarning, stacklevel=2) return res def _nanmax_dispatcher(a, axis=None, out=None, keepdims=None, initial=None, where=None): return (a, out) @array_function_dispatch(_nanmax_dispatcher) def nanmax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue): kwargs = {} if keepdims is not np._NoValue: kwargs['keepdims'] = keepdims if initial is not np._NoValue: kwargs['initial'] = initial if where is not np._NoValue: kwargs['where'] = where if type(a) is np.ndarray and a.dtype != np.object_: res = np.fmax.reduce(a, axis=axis, out=out, **kwargs) if np.isnan(res).any(): warnings.warn('All-NaN slice encountered', RuntimeWarning, stacklevel=2) else: (a, mask) = _replace_nan(a, -np.inf) res = np.amax(a, axis=axis, out=out, **kwargs) if mask is None: return res kwargs.pop('initial', None) mask = np.all(mask, axis=axis, **kwargs) if np.any(mask): res = _copyto(res, np.nan, mask) warnings.warn('All-NaN axis encountered', RuntimeWarning, stacklevel=2) return res def _nanargmin_dispatcher(a, axis=None, out=None, *, keepdims=None): return (a,) @array_function_dispatch(_nanargmin_dispatcher) def nanargmin(a, axis=None, out=None, *, keepdims=np._NoValue): (a, mask) = _replace_nan(a, np.inf) if mask is not None and mask.size: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError('All-NaN slice encountered') res = np.argmin(a, axis=axis, out=out, keepdims=keepdims) return res def _nanargmax_dispatcher(a, axis=None, out=None, *, keepdims=None): return (a,) @array_function_dispatch(_nanargmax_dispatcher) def nanargmax(a, axis=None, out=None, *, keepdims=np._NoValue): (a, mask) = _replace_nan(a, -np.inf) if mask is not None and mask.size: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError('All-NaN slice encountered') res = np.argmax(a, axis=axis, out=out, keepdims=keepdims) return res def _nansum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, initial=None, where=None): return (a, out) @array_function_dispatch(_nansum_dispatcher) def nansum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue): (a, mask) = _replace_nan(a, 0) return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims, initial=initial, where=where) def _nanprod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, initial=None, where=None): return (a, out) @array_function_dispatch(_nanprod_dispatcher) def nanprod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue): (a, mask) = _replace_nan(a, 1) return np.prod(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims, initial=initial, where=where) def _nancumsum_dispatcher(a, axis=None, dtype=None, out=None): return (a, out) @array_function_dispatch(_nancumsum_dispatcher) def nancumsum(a, axis=None, dtype=None, out=None): (a, mask) = _replace_nan(a, 0) return np.cumsum(a, axis=axis, dtype=dtype, out=out) def _nancumprod_dispatcher(a, axis=None, dtype=None, out=None): return (a, out) @array_function_dispatch(_nancumprod_dispatcher) def nancumprod(a, axis=None, dtype=None, out=None): (a, mask) = _replace_nan(a, 1) return np.cumprod(a, axis=axis, dtype=dtype, out=out) def _nanmean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, *, where=None): return (a, out) @array_function_dispatch(_nanmean_dispatcher) def nanmean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, *, where=np._NoValue): (arr, mask) = _replace_nan(a, 0) if mask is None: return np.mean(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims, where=where) if dtype is not None: dtype = np.dtype(dtype) if dtype is not None and (not issubclass(dtype.type, np.inexact)): raise TypeError('If a is inexact, then dtype must be inexact') if out is not None and (not issubclass(out.dtype.type, np.inexact)): raise TypeError('If a is inexact, then out must be inexact') cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims, where=where) tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims, where=where) avg = _divide_by_count(tot, cnt, out=out) isbad = cnt == 0 if isbad.any(): warnings.warn('Mean of empty slice', RuntimeWarning, stacklevel=2) return avg def _nanmedian1d(arr1d, overwrite_input=False): (arr1d_parsed, _, overwrite_input) = _remove_nan_1d(arr1d, overwrite_input=overwrite_input) if arr1d_parsed.size == 0: return arr1d[-1] return np.median(arr1d_parsed, overwrite_input=overwrite_input) def _nanmedian(a, axis=None, out=None, overwrite_input=False): if axis is None or a.ndim == 1: part = a.ravel() if out is None: return _nanmedian1d(part, overwrite_input) else: out[...] = _nanmedian1d(part, overwrite_input) return out else: if a.shape[axis] < 600: return _nanmedian_small(a, axis, out, overwrite_input) result = np.apply_along_axis(_nanmedian1d, axis, a, overwrite_input) if out is not None: out[...] = result return result def _nanmedian_small(a, axis=None, out=None, overwrite_input=False): a = np.ma.masked_array(a, np.isnan(a)) m = np.ma.median(a, axis=axis, overwrite_input=overwrite_input) for i in range(np.count_nonzero(m.mask.ravel())): warnings.warn('All-NaN slice encountered', RuntimeWarning, stacklevel=5) fill_value = np.timedelta64('NaT') if m.dtype.kind == 'm' else np.nan if out is not None: out[...] = m.filled(fill_value) return out return m.filled(fill_value) def _nanmedian_dispatcher(a, axis=None, out=None, overwrite_input=None, keepdims=None): return (a, out) @array_function_dispatch(_nanmedian_dispatcher) def nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=np._NoValue): a = np.asanyarray(a) if a.size == 0: return np.nanmean(a, axis, out=out, keepdims=keepdims) return fnb._ureduce(a, func=_nanmedian, keepdims=keepdims, axis=axis, out=out, overwrite_input=overwrite_input) def _nanpercentile_dispatcher(a, q, axis=None, out=None, overwrite_input=None, method=None, keepdims=None, *, weights=None, interpolation=None): return (a, q, out, weights) @array_function_dispatch(_nanpercentile_dispatcher) def nanpercentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=np._NoValue, *, weights=None, interpolation=None): if interpolation is not None: method = fnb._check_interpolation_as_method(method, interpolation, 'nanpercentile') a = np.asanyarray(a) if a.dtype.kind == 'c': raise TypeError('a must be an array of real numbers') q = np.true_divide(q, a.dtype.type(100) if a.dtype.kind == 'f' else 100) q = np.asanyarray(q) if not fnb._quantile_is_valid(q): raise ValueError('Percentiles must be in the range [0, 100]') if weights is not None: if method != 'inverted_cdf': msg = f"Only method 'inverted_cdf' supports weights. Got: {method}." raise ValueError(msg) if axis is not None: axis = _nx.normalize_axis_tuple(axis, a.ndim, argname='axis') weights = _weights_are_valid(weights=weights, a=a, axis=axis) if np.any(weights < 0): raise ValueError('Weights must be non-negative.') return _nanquantile_unchecked(a, q, axis, out, overwrite_input, method, keepdims, weights) def _nanquantile_dispatcher(a, q, axis=None, out=None, overwrite_input=None, method=None, keepdims=None, *, weights=None, interpolation=None): return (a, q, out, weights) @array_function_dispatch(_nanquantile_dispatcher) def nanquantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=np._NoValue, *, weights=None, interpolation=None): if interpolation is not None: method = fnb._check_interpolation_as_method(method, interpolation, 'nanquantile') a = np.asanyarray(a) if a.dtype.kind == 'c': raise TypeError('a must be an array of real numbers') if isinstance(q, (int, float)) and a.dtype.kind == 'f': q = np.asanyarray(q, dtype=a.dtype) else: q = np.asanyarray(q) if not fnb._quantile_is_valid(q): raise ValueError('Quantiles must be in the range [0, 1]') if weights is not None: if method != 'inverted_cdf': msg = f"Only method 'inverted_cdf' supports weights. Got: {method}." raise ValueError(msg) if axis is not None: axis = _nx.normalize_axis_tuple(axis, a.ndim, argname='axis') weights = _weights_are_valid(weights=weights, a=a, axis=axis) if np.any(weights < 0): raise ValueError('Weights must be non-negative.') return _nanquantile_unchecked(a, q, axis, out, overwrite_input, method, keepdims, weights) def _nanquantile_unchecked(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=np._NoValue, weights=None): if a.size == 0: return np.nanmean(a, axis, out=out, keepdims=keepdims) return fnb._ureduce(a, func=_nanquantile_ureduce_func, q=q, weights=weights, keepdims=keepdims, axis=axis, out=out, overwrite_input=overwrite_input, method=method) def _nanquantile_ureduce_func(a: np.array, q: np.array, weights: np.array, axis: int | None=None, out=None, overwrite_input: bool=False, method='linear'): if axis is None or a.ndim == 1: part = a.ravel() wgt = None if weights is None else weights.ravel() result = _nanquantile_1d(part, q, overwrite_input, method, weights=wgt) elif weights is None: result = np.apply_along_axis(_nanquantile_1d, axis, a, q, overwrite_input, method, weights) if q.ndim != 0: from_ax = [axis + i for i in range(q.ndim)] result = np.moveaxis(result, from_ax, list(range(q.ndim))) else: a = np.moveaxis(a, axis, -1) if weights is not None: weights = np.moveaxis(weights, axis, -1) if out is not None: result = out else: result = np.empty_like(a, shape=q.shape + a.shape[:-1]) for ii in np.ndindex(a.shape[:-1]): result[(...,) + ii] = _nanquantile_1d(a[ii], q, weights=weights[ii], overwrite_input=overwrite_input, method=method) return result if out is not None: out[...] = result return result def _nanquantile_1d(arr1d, q, overwrite_input=False, method='linear', weights=None): (arr1d, weights, overwrite_input) = _remove_nan_1d(arr1d, second_arr1d=weights, overwrite_input=overwrite_input) if arr1d.size == 0: return np.full(q.shape, np.nan, dtype=arr1d.dtype)[()] return fnb._quantile_unchecked(arr1d, q, overwrite_input=overwrite_input, method=method, weights=weights) def _nanvar_dispatcher(a, axis=None, dtype=None, out=None, ddof=None, keepdims=None, *, where=None, mean=None, correction=None): return (a, out) @array_function_dispatch(_nanvar_dispatcher) def nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *, where=np._NoValue, mean=np._NoValue, correction=np._NoValue): (arr, mask) = _replace_nan(a, 0) if mask is None: return np.var(arr, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, where=where, mean=mean, correction=correction) if dtype is not None: dtype = np.dtype(dtype) if dtype is not None and (not issubclass(dtype.type, np.inexact)): raise TypeError('If a is inexact, then dtype must be inexact') if out is not None and (not issubclass(out.dtype.type, np.inexact)): raise TypeError('If a is inexact, then out must be inexact') if correction != np._NoValue: if ddof != 0: raise ValueError("ddof and correction can't be provided simultaneously.") else: ddof = correction if type(arr) is np.matrix: _keepdims = np._NoValue else: _keepdims = True cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=_keepdims, where=where) if mean is not np._NoValue: avg = mean else: avg = np.sum(arr, axis=axis, dtype=dtype, keepdims=_keepdims, where=where) avg = _divide_by_count(avg, cnt) np.subtract(arr, avg, out=arr, casting='unsafe', where=where) arr = _copyto(arr, 0, mask) if issubclass(arr.dtype.type, np.complexfloating): sqr = np.multiply(arr, arr.conj(), out=arr, where=where).real else: sqr = np.multiply(arr, arr, out=arr, where=where) var = np.sum(sqr, axis=axis, dtype=dtype, out=out, keepdims=keepdims, where=where) try: var_ndim = var.ndim except AttributeError: var_ndim = np.ndim(var) if var_ndim < cnt.ndim: cnt = cnt.squeeze(axis) dof = cnt - ddof var = _divide_by_count(var, dof) isbad = dof <= 0 if np.any(isbad): warnings.warn('Degrees of freedom <= 0 for slice.', RuntimeWarning, stacklevel=2) var = _copyto(var, np.nan, isbad) return var def _nanstd_dispatcher(a, axis=None, dtype=None, out=None, ddof=None, keepdims=None, *, where=None, mean=None, correction=None): return (a, out) @array_function_dispatch(_nanstd_dispatcher) def nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *, where=np._NoValue, mean=np._NoValue, correction=np._NoValue): var = nanvar(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, where=where, mean=mean, correction=correction) if isinstance(var, np.ndarray): std = np.sqrt(var, out=var) elif hasattr(var, 'dtype'): std = var.dtype.type(np.sqrt(var)) else: std = np.sqrt(var) return std # File: numpy-main/numpy/lib/_npyio_impl.py """""" import os import re import functools import itertools import warnings import weakref import contextlib import operator from operator import itemgetter from collections.abc import Mapping import pickle import numpy as np from . import format from ._datasource import DataSource from numpy._core import overrides from numpy._core.multiarray import packbits, unpackbits from numpy._core._multiarray_umath import _load_from_filelike from numpy._core.overrides import set_array_function_like_doc, set_module from ._iotools import LineSplitter, NameValidator, StringConverter, ConverterError, ConverterLockError, ConversionWarning, _is_string_like, has_nested_fields, flatten_dtype, easy_dtype, _decode_line from numpy._utils import asunicode, asbytes __all__ = ['savetxt', 'loadtxt', 'genfromtxt', 'load', 'save', 'savez', 'savez_compressed', 'packbits', 'unpackbits', 'fromregex'] array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') class BagObj: def __init__(self, obj): self._obj = weakref.proxy(obj) def __getattribute__(self, key): try: return object.__getattribute__(self, '_obj')[key] except KeyError: raise AttributeError(key) from None def __dir__(self): return list(object.__getattribute__(self, '_obj').keys()) def zipfile_factory(file, *args, **kwargs): if not hasattr(file, 'read'): file = os.fspath(file) import zipfile kwargs['allowZip64'] = True return zipfile.ZipFile(file, *args, **kwargs) @set_module('numpy.lib.npyio') class NpzFile(Mapping): zip = None fid = None _MAX_REPR_ARRAY_COUNT = 5 def __init__(self, fid, own_fid=False, allow_pickle=False, pickle_kwargs=None, *, max_header_size=format._MAX_HEADER_SIZE): _zip = zipfile_factory(fid) self._files = _zip.namelist() self.files = [] self.allow_pickle = allow_pickle self.max_header_size = max_header_size self.pickle_kwargs = pickle_kwargs for x in self._files: if x.endswith('.npy'): self.files.append(x[:-4]) else: self.files.append(x) self.zip = _zip self.f = BagObj(self) if own_fid: self.fid = fid def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def close(self): if self.zip is not None: self.zip.close() self.zip = None if self.fid is not None: self.fid.close() self.fid = None self.f = None def __del__(self): self.close() def __iter__(self): return iter(self.files) def __len__(self): return len(self.files) def __getitem__(self, key): member = False if key in self._files: member = True elif key in self.files: member = True key += '.npy' if member: bytes = self.zip.open(key) magic = bytes.read(len(format.MAGIC_PREFIX)) bytes.close() if magic == format.MAGIC_PREFIX: bytes = self.zip.open(key) return format.read_array(bytes, allow_pickle=self.allow_pickle, pickle_kwargs=self.pickle_kwargs, max_header_size=self.max_header_size) else: return self.zip.read(key) else: raise KeyError(f'{key} is not a file in the archive') def __contains__(self, key): return key in self._files or key in self.files def __repr__(self): if isinstance(self.fid, str): filename = self.fid else: filename = getattr(self.fid, 'name', 'object') array_names = ', '.join(self.files[:self._MAX_REPR_ARRAY_COUNT]) if len(self.files) > self._MAX_REPR_ARRAY_COUNT: array_names += '...' return f'NpzFile {filename!r} with keys: {array_names}' def get(self, key, default=None, /): return Mapping.get(self, key, default) def items(self): return Mapping.items(self) def keys(self): return Mapping.keys(self) def values(self): return Mapping.values(self) @set_module('numpy') def load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII', *, max_header_size=format._MAX_HEADER_SIZE): if encoding not in ('ASCII', 'latin1', 'bytes'): raise ValueError("encoding must be 'ASCII', 'latin1', or 'bytes'") pickle_kwargs = dict(encoding=encoding, fix_imports=fix_imports) with contextlib.ExitStack() as stack: if hasattr(file, 'read'): fid = file own_fid = False else: fid = stack.enter_context(open(os.fspath(file), 'rb')) own_fid = True _ZIP_PREFIX = b'PK\x03\x04' _ZIP_SUFFIX = b'PK\x05\x06' N = len(format.MAGIC_PREFIX) magic = fid.read(N) if not magic: raise EOFError('No data left in file') fid.seek(-min(N, len(magic)), 1) if magic.startswith((_ZIP_PREFIX, _ZIP_SUFFIX)): stack.pop_all() ret = NpzFile(fid, own_fid=own_fid, allow_pickle=allow_pickle, pickle_kwargs=pickle_kwargs, max_header_size=max_header_size) return ret elif magic == format.MAGIC_PREFIX: if mmap_mode: if allow_pickle: max_header_size = 2 ** 64 return format.open_memmap(file, mode=mmap_mode, max_header_size=max_header_size) else: return format.read_array(fid, allow_pickle=allow_pickle, pickle_kwargs=pickle_kwargs, max_header_size=max_header_size) else: if not allow_pickle: raise ValueError('Cannot load file containing pickled data when allow_pickle=False') try: return pickle.load(fid, **pickle_kwargs) except Exception as e: raise pickle.UnpicklingError(f'Failed to interpret file {file!r} as a pickle') from e def _save_dispatcher(file, arr, allow_pickle=None, fix_imports=None): return (arr,) @array_function_dispatch(_save_dispatcher) def save(file, arr, allow_pickle=True, fix_imports=np._NoValue): if fix_imports is not np._NoValue: warnings.warn("The 'fix_imports' flag is deprecated and has no effect. (Deprecated in NumPy 2.1)", DeprecationWarning, stacklevel=2) if hasattr(file, 'write'): file_ctx = contextlib.nullcontext(file) else: file = os.fspath(file) if not file.endswith('.npy'): file = file + '.npy' file_ctx = open(file, 'wb') with file_ctx as fid: arr = np.asanyarray(arr) format.write_array(fid, arr, allow_pickle=allow_pickle, pickle_kwargs=dict(fix_imports=fix_imports)) def _savez_dispatcher(file, *args, **kwds): yield from args yield from kwds.values() @array_function_dispatch(_savez_dispatcher) def savez(file, *args, **kwds): _savez(file, args, kwds, False) def _savez_compressed_dispatcher(file, *args, **kwds): yield from args yield from kwds.values() @array_function_dispatch(_savez_compressed_dispatcher) def savez_compressed(file, *args, **kwds): _savez(file, args, kwds, True) def _savez(file, args, kwds, compress, allow_pickle=True, pickle_kwargs=None): import zipfile if not hasattr(file, 'write'): file = os.fspath(file) if not file.endswith('.npz'): file = file + '.npz' namedict = kwds for (i, val) in enumerate(args): key = 'arr_%d' % i if key in namedict.keys(): raise ValueError('Cannot use un-named variables and keyword %s' % key) namedict[key] = val if compress: compression = zipfile.ZIP_DEFLATED else: compression = zipfile.ZIP_STORED zipf = zipfile_factory(file, mode='w', compression=compression) for (key, val) in namedict.items(): fname = key + '.npy' val = np.asanyarray(val) with zipf.open(fname, 'w', force_zip64=True) as fid: format.write_array(fid, val, allow_pickle=allow_pickle, pickle_kwargs=pickle_kwargs) zipf.close() def _ensure_ndmin_ndarray_check_param(ndmin): if ndmin not in [0, 1, 2]: raise ValueError(f'Illegal value of ndmin keyword: {ndmin}') def _ensure_ndmin_ndarray(a, *, ndmin: int): if a.ndim > ndmin: a = np.squeeze(a) if a.ndim < ndmin: if ndmin == 1: a = np.atleast_1d(a) elif ndmin == 2: a = np.atleast_2d(a).T return a _loadtxt_chunksize = 50000 def _check_nonneg_int(value, name='argument'): try: operator.index(value) except TypeError: raise TypeError(f'{name} must be an integer') from None if value < 0: raise ValueError(f'{name} must be nonnegative') def _preprocess_comments(iterable, comments, encoding): for line in iterable: if isinstance(line, bytes): line = line.decode(encoding) for c in comments: line = line.split(c, 1)[0] yield line _loadtxt_chunksize = 50000 def _read(fname, *, delimiter=',', comment='#', quote='"', imaginary_unit='j', usecols=None, skiplines=0, max_rows=None, converters=None, ndmin=None, unpack=False, dtype=np.float64, encoding=None): byte_converters = False if encoding == 'bytes': encoding = None byte_converters = True if dtype is None: raise TypeError('a dtype must be provided.') dtype = np.dtype(dtype) read_dtype_via_object_chunks = None if dtype.kind in 'SUM' and (dtype == 'S0' or dtype == 'U0' or dtype == 'M8' or (dtype == 'm8')): read_dtype_via_object_chunks = dtype dtype = np.dtype(object) if usecols is not None: try: usecols = list(usecols) except TypeError: usecols = [usecols] _ensure_ndmin_ndarray_check_param(ndmin) if comment is None: comments = None else: if '' in comment: raise ValueError('comments cannot be an empty string. Use comments=None to disable comments.') comments = tuple(comment) comment = None if len(comments) == 0: comments = None elif len(comments) == 1: if isinstance(comments[0], str) and len(comments[0]) == 1: comment = comments[0] comments = None elif delimiter in comments: raise TypeError(f"Comment characters '{comments}' cannot include the delimiter '{delimiter}'") if comments is not None: if quote is not None: raise ValueError('when multiple comments or a multi-character comment is given, quotes are not supported. In this case quotechar must be set to None.') if len(imaginary_unit) != 1: raise ValueError('len(imaginary_unit) must be 1.') _check_nonneg_int(skiplines) if max_rows is not None: _check_nonneg_int(max_rows) else: max_rows = -1 fh_closing_ctx = contextlib.nullcontext() filelike = False try: if isinstance(fname, os.PathLike): fname = os.fspath(fname) if isinstance(fname, str): fh = np.lib._datasource.open(fname, 'rt', encoding=encoding) if encoding is None: encoding = getattr(fh, 'encoding', 'latin1') fh_closing_ctx = contextlib.closing(fh) data = fh filelike = True else: if encoding is None: encoding = getattr(fname, 'encoding', 'latin1') data = iter(fname) except TypeError as e: raise ValueError(f'fname must be a string, filehandle, list of strings,\nor generator. Got {type(fname)} instead.') from e with fh_closing_ctx: if comments is not None: if filelike: data = iter(data) filelike = False data = _preprocess_comments(data, comments, encoding) if read_dtype_via_object_chunks is None: arr = _load_from_filelike(data, delimiter=delimiter, comment=comment, quote=quote, imaginary_unit=imaginary_unit, usecols=usecols, skiplines=skiplines, max_rows=max_rows, converters=converters, dtype=dtype, encoding=encoding, filelike=filelike, byte_converters=byte_converters) else: if filelike: data = iter(data) filelike = False c_byte_converters = False if read_dtype_via_object_chunks == 'S': c_byte_converters = True chunks = [] while max_rows != 0: if max_rows < 0: chunk_size = _loadtxt_chunksize else: chunk_size = min(_loadtxt_chunksize, max_rows) next_arr = _load_from_filelike(data, delimiter=delimiter, comment=comment, quote=quote, imaginary_unit=imaginary_unit, usecols=usecols, skiplines=skiplines, max_rows=chunk_size, converters=converters, dtype=dtype, encoding=encoding, filelike=filelike, byte_converters=byte_converters, c_byte_converters=c_byte_converters) chunks.append(next_arr.astype(read_dtype_via_object_chunks)) skiprows = 0 if max_rows >= 0: max_rows -= chunk_size if len(next_arr) < chunk_size: break if len(chunks) > 1 and len(chunks[-1]) == 0: del chunks[-1] if len(chunks) == 1: arr = chunks[0] else: arr = np.concatenate(chunks, axis=0) arr = _ensure_ndmin_ndarray(arr, ndmin=ndmin) if arr.shape: if arr.shape[0] == 0: warnings.warn(f'loadtxt: input contained no data: "{fname}"', category=UserWarning, stacklevel=3) if unpack: dt = arr.dtype if dt.names is not None: return [arr[field] for field in dt.names] else: return arr.T else: return arr @set_array_function_like_doc @set_module('numpy') def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding=None, max_rows=None, *, quotechar=None, like=None): if like is not None: return _loadtxt_with_like(like, fname, dtype=dtype, comments=comments, delimiter=delimiter, converters=converters, skiprows=skiprows, usecols=usecols, unpack=unpack, ndmin=ndmin, encoding=encoding, max_rows=max_rows) if isinstance(delimiter, bytes): delimiter.decode('latin1') if dtype is None: dtype = np.float64 comment = comments if comment is not None: if isinstance(comment, (str, bytes)): comment = [comment] comment = [x.decode('latin1') if isinstance(x, bytes) else x for x in comment] if isinstance(delimiter, bytes): delimiter = delimiter.decode('latin1') arr = _read(fname, dtype=dtype, comment=comment, delimiter=delimiter, converters=converters, skiplines=skiprows, usecols=usecols, unpack=unpack, ndmin=ndmin, encoding=encoding, max_rows=max_rows, quote=quotechar) return arr _loadtxt_with_like = array_function_dispatch()(loadtxt) def _savetxt_dispatcher(fname, X, fmt=None, delimiter=None, newline=None, header=None, footer=None, comments=None, encoding=None): return (X,) @array_function_dispatch(_savetxt_dispatcher) def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None): class WriteWrap: def __init__(self, fh, encoding): self.fh = fh self.encoding = encoding self.do_write = self.first_write def close(self): self.fh.close() def write(self, v): self.do_write(v) def write_bytes(self, v): if isinstance(v, bytes): self.fh.write(v) else: self.fh.write(v.encode(self.encoding)) def write_normal(self, v): self.fh.write(asunicode(v)) def first_write(self, v): try: self.write_normal(v) self.write = self.write_normal except TypeError: self.write_bytes(v) self.write = self.write_bytes own_fh = False if isinstance(fname, os.PathLike): fname = os.fspath(fname) if _is_string_like(fname): open(fname, 'wt').close() fh = np.lib._datasource.open(fname, 'wt', encoding=encoding) own_fh = True elif hasattr(fname, 'write'): fh = WriteWrap(fname, encoding or 'latin1') else: raise ValueError('fname must be a string or file handle') try: X = np.asarray(X) if X.ndim == 0 or X.ndim > 2: raise ValueError('Expected 1D or 2D array, got %dD array instead' % X.ndim) elif X.ndim == 1: if X.dtype.names is None: X = np.atleast_2d(X).T ncol = 1 else: ncol = len(X.dtype.names) else: ncol = X.shape[1] iscomplex_X = np.iscomplexobj(X) if type(fmt) in (list, tuple): if len(fmt) != ncol: raise AttributeError('fmt has wrong shape. %s' % str(fmt)) format = delimiter.join(fmt) elif isinstance(fmt, str): n_fmt_chars = fmt.count('%') error = ValueError('fmt has wrong number of %% formats: %s' % fmt) if n_fmt_chars == 1: if iscomplex_X: fmt = [' (%s+%sj)' % (fmt, fmt)] * ncol else: fmt = [fmt] * ncol format = delimiter.join(fmt) elif iscomplex_X and n_fmt_chars != 2 * ncol: raise error elif not iscomplex_X and n_fmt_chars != ncol: raise error else: format = fmt else: raise ValueError('invalid fmt: %r' % (fmt,)) if len(header) > 0: header = header.replace('\n', '\n' + comments) fh.write(comments + header + newline) if iscomplex_X: for row in X: row2 = [] for number in row: row2.append(number.real) row2.append(number.imag) s = format % tuple(row2) + newline fh.write(s.replace('+-', '-')) else: for row in X: try: v = format % tuple(row) + newline except TypeError as e: raise TypeError("Mismatch between array dtype ('%s') and format specifier ('%s')" % (str(X.dtype), format)) from e fh.write(v) if len(footer) > 0: footer = footer.replace('\n', '\n' + comments) fh.write(comments + footer + newline) finally: if own_fh: fh.close() @set_module('numpy') def fromregex(file, regexp, dtype, encoding=None): own_fh = False if not hasattr(file, 'read'): file = os.fspath(file) file = np.lib._datasource.open(file, 'rt', encoding=encoding) own_fh = True try: if not isinstance(dtype, np.dtype): dtype = np.dtype(dtype) if dtype.names is None: raise TypeError('dtype must be a structured datatype.') content = file.read() if isinstance(content, bytes) and isinstance(regexp, str): regexp = asbytes(regexp) if not hasattr(regexp, 'match'): regexp = re.compile(regexp) seq = regexp.findall(content) if seq and (not isinstance(seq[0], tuple)): newdtype = np.dtype(dtype[dtype.names[0]]) output = np.array(seq, dtype=newdtype) output.dtype = dtype else: output = np.array(seq, dtype=dtype) return output finally: if own_fh: file.close() @set_array_function_like_doc @set_module('numpy') def genfromtxt(fname, dtype=float, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=''.join(sorted(NameValidator.defaultdeletechars)), replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding=None, *, ndmin=0, like=None): if like is not None: return _genfromtxt_with_like(like, fname, dtype=dtype, comments=comments, delimiter=delimiter, skip_header=skip_header, skip_footer=skip_footer, converters=converters, missing_values=missing_values, filling_values=filling_values, usecols=usecols, names=names, excludelist=excludelist, deletechars=deletechars, replace_space=replace_space, autostrip=autostrip, case_sensitive=case_sensitive, defaultfmt=defaultfmt, unpack=unpack, usemask=usemask, loose=loose, invalid_raise=invalid_raise, max_rows=max_rows, encoding=encoding, ndmin=ndmin) _ensure_ndmin_ndarray_check_param(ndmin) if max_rows is not None: if skip_footer: raise ValueError("The keywords 'skip_footer' and 'max_rows' can not be specified at the same time.") if max_rows < 1: raise ValueError("'max_rows' must be at least 1.") if usemask: from numpy.ma import MaskedArray, make_mask_descr user_converters = converters or {} if not isinstance(user_converters, dict): raise TypeError("The input argument 'converter' should be a valid dictionary (got '%s' instead)" % type(user_converters)) if encoding == 'bytes': encoding = None byte_converters = True else: byte_converters = False if isinstance(fname, os.PathLike): fname = os.fspath(fname) if isinstance(fname, str): fid = np.lib._datasource.open(fname, 'rt', encoding=encoding) fid_ctx = contextlib.closing(fid) else: fid = fname fid_ctx = contextlib.nullcontext(fid) try: fhd = iter(fid) except TypeError as e: raise TypeError(f'fname must be a string, a filehandle, a sequence of strings,\nor an iterator of strings. Got {type(fname)} instead.') from e with fid_ctx: split_line = LineSplitter(delimiter=delimiter, comments=comments, autostrip=autostrip, encoding=encoding) validate_names = NameValidator(excludelist=excludelist, deletechars=deletechars, case_sensitive=case_sensitive, replace_space=replace_space) try: for i in range(skip_header): next(fhd) first_values = None while not first_values: first_line = _decode_line(next(fhd), encoding) if names is True and comments is not None: if comments in first_line: first_line = ''.join(first_line.split(comments)[1:]) first_values = split_line(first_line) except StopIteration: first_line = '' first_values = [] warnings.warn('genfromtxt: Empty input file: "%s"' % fname, stacklevel=2) if names is True: fval = first_values[0].strip() if comments is not None: if fval in comments: del first_values[0] if usecols is not None: try: usecols = [_.strip() for _ in usecols.split(',')] except AttributeError: try: usecols = list(usecols) except TypeError: usecols = [usecols] nbcols = len(usecols or first_values) if names is True: names = validate_names([str(_.strip()) for _ in first_values]) first_line = '' elif _is_string_like(names): names = validate_names([_.strip() for _ in names.split(',')]) elif names: names = validate_names(names) if dtype is not None: dtype = easy_dtype(dtype, defaultfmt=defaultfmt, names=names, excludelist=excludelist, deletechars=deletechars, case_sensitive=case_sensitive, replace_space=replace_space) if names is not None: names = list(names) if usecols: for (i, current) in enumerate(usecols): if _is_string_like(current): usecols[i] = names.index(current) elif current < 0: usecols[i] = current + len(first_values) if dtype is not None and len(dtype) > nbcols: descr = dtype.descr dtype = np.dtype([descr[_] for _ in usecols]) names = list(dtype.names) elif names is not None and len(names) > nbcols: names = [names[_] for _ in usecols] elif names is not None and dtype is not None: names = list(dtype.names) user_missing_values = missing_values or () if isinstance(user_missing_values, bytes): user_missing_values = user_missing_values.decode('latin1') missing_values = [[''] for _ in range(nbcols)] if isinstance(user_missing_values, dict): for (key, val) in user_missing_values.items(): if _is_string_like(key): try: key = names.index(key) except ValueError: continue if usecols: try: key = usecols.index(key) except ValueError: pass if isinstance(val, (list, tuple)): val = [str(_) for _ in val] else: val = [str(val)] if key is None: for miss in missing_values: miss.extend(val) else: missing_values[key].extend(val) elif isinstance(user_missing_values, (list, tuple)): for (value, entry) in zip(user_missing_values, missing_values): value = str(value) if value not in entry: entry.append(value) elif isinstance(user_missing_values, str): user_value = user_missing_values.split(',') for entry in missing_values: entry.extend(user_value) else: for entry in missing_values: entry.extend([str(user_missing_values)]) user_filling_values = filling_values if user_filling_values is None: user_filling_values = [] filling_values = [None] * nbcols if isinstance(user_filling_values, dict): for (key, val) in user_filling_values.items(): if _is_string_like(key): try: key = names.index(key) except ValueError: continue if usecols: try: key = usecols.index(key) except ValueError: pass filling_values[key] = val elif isinstance(user_filling_values, (list, tuple)): n = len(user_filling_values) if n <= nbcols: filling_values[:n] = user_filling_values else: filling_values = user_filling_values[:nbcols] else: filling_values = [user_filling_values] * nbcols if dtype is None: converters = [StringConverter(None, missing_values=miss, default=fill) for (miss, fill) in zip(missing_values, filling_values)] else: dtype_flat = flatten_dtype(dtype, flatten_base=True) if len(dtype_flat) > 1: zipit = zip(dtype_flat, missing_values, filling_values) converters = [StringConverter(dt, locked=True, missing_values=miss, default=fill) for (dt, miss, fill) in zipit] else: zipit = zip(missing_values, filling_values) converters = [StringConverter(dtype, locked=True, missing_values=miss, default=fill) for (miss, fill) in zipit] uc_update = [] for (j, conv) in user_converters.items(): if _is_string_like(j): try: j = names.index(j) i = j except ValueError: continue elif usecols: try: i = usecols.index(j) except ValueError: continue else: i = j if len(first_line): testing_value = first_values[j] else: testing_value = None if conv is bytes: user_conv = asbytes elif byte_converters: def tobytes_first(x, conv): if type(x) is bytes: return conv(x) return conv(x.encode('latin1')) user_conv = functools.partial(tobytes_first, conv=conv) else: user_conv = conv converters[i].update(user_conv, locked=True, testing_value=testing_value, default=filling_values[i], missing_values=missing_values[i]) uc_update.append((i, user_conv)) user_converters.update(uc_update) rows = [] append_to_rows = rows.append if usemask: masks = [] append_to_masks = masks.append invalid = [] append_to_invalid = invalid.append for (i, line) in enumerate(itertools.chain([first_line], fhd)): values = split_line(line) nbvalues = len(values) if nbvalues == 0: continue if usecols: try: values = [values[_] for _ in usecols] except IndexError: append_to_invalid((i + skip_header + 1, nbvalues)) continue elif nbvalues != nbcols: append_to_invalid((i + skip_header + 1, nbvalues)) continue append_to_rows(tuple(values)) if usemask: append_to_masks(tuple([v.strip() in m for (v, m) in zip(values, missing_values)])) if len(rows) == max_rows: break if dtype is None: for (i, converter) in enumerate(converters): current_column = [itemgetter(i)(_m) for _m in rows] try: converter.iterupgrade(current_column) except ConverterLockError: errmsg = 'Converter #%i is locked and cannot be upgraded: ' % i current_column = map(itemgetter(i), rows) for (j, value) in enumerate(current_column): try: converter.upgrade(value) except (ConverterError, ValueError): errmsg += "(occurred line #%i for value '%s')" errmsg %= (j + 1 + skip_header, value) raise ConverterError(errmsg) nbinvalid = len(invalid) if nbinvalid > 0: nbrows = len(rows) + nbinvalid - skip_footer template = ' Line #%%i (got %%i columns instead of %i)' % nbcols if skip_footer > 0: nbinvalid_skipped = len([_ for _ in invalid if _[0] > nbrows + skip_header]) invalid = invalid[:nbinvalid - nbinvalid_skipped] skip_footer -= nbinvalid_skipped errmsg = [template % (i, nb) for (i, nb) in invalid] if len(errmsg): errmsg.insert(0, 'Some errors were detected !') errmsg = '\n'.join(errmsg) if invalid_raise: raise ValueError(errmsg) else: warnings.warn(errmsg, ConversionWarning, stacklevel=2) if skip_footer > 0: rows = rows[:-skip_footer] if usemask: masks = masks[:-skip_footer] if loose: rows = list(zip(*[[conv._loose_call(_r) for _r in map(itemgetter(i), rows)] for (i, conv) in enumerate(converters)])) else: rows = list(zip(*[[conv._strict_call(_r) for _r in map(itemgetter(i), rows)] for (i, conv) in enumerate(converters)])) data = rows if dtype is None: column_types = [conv.type for conv in converters] strcolidx = [i for (i, v) in enumerate(column_types) if v == np.str_] if byte_converters and strcolidx: warnings.warn('Reading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default.', np.exceptions.VisibleDeprecationWarning, stacklevel=2) def encode_unicode_cols(row_tup): row = list(row_tup) for i in strcolidx: row[i] = row[i].encode('latin1') return tuple(row) try: data = [encode_unicode_cols(r) for r in data] except UnicodeEncodeError: pass else: for i in strcolidx: column_types[i] = np.bytes_ sized_column_types = column_types[:] for (i, col_type) in enumerate(column_types): if np.issubdtype(col_type, np.character): n_chars = max((len(row[i]) for row in data)) sized_column_types[i] = (col_type, n_chars) if names is None: base = {c_type for (c, c_type) in zip(converters, column_types) if c._checked} if len(base) == 1: (uniform_type,) = base (ddtype, mdtype) = (uniform_type, bool) else: ddtype = [(defaultfmt % i, dt) for (i, dt) in enumerate(sized_column_types)] if usemask: mdtype = [(defaultfmt % i, bool) for (i, dt) in enumerate(sized_column_types)] else: ddtype = list(zip(names, sized_column_types)) mdtype = list(zip(names, [bool] * len(sized_column_types))) output = np.array(data, dtype=ddtype) if usemask: outputmask = np.array(masks, dtype=mdtype) else: if names and dtype.names is not None: dtype.names = names if len(dtype_flat) > 1: if 'O' in (_.char for _ in dtype_flat): if has_nested_fields(dtype): raise NotImplementedError('Nested fields involving objects are not supported...') else: output = np.array(data, dtype=dtype) else: rows = np.array(data, dtype=[('', _) for _ in dtype_flat]) output = rows.view(dtype) if usemask: rowmasks = np.array(masks, dtype=np.dtype([('', bool) for t in dtype_flat])) mdtype = make_mask_descr(dtype) outputmask = rowmasks.view(mdtype) else: if user_converters: ishomogeneous = True descr = [] for (i, ttype) in enumerate([conv.type for conv in converters]): if i in user_converters: ishomogeneous &= ttype == dtype.type if np.issubdtype(ttype, np.character): ttype = (ttype, max((len(row[i]) for row in data))) descr.append(('', ttype)) else: descr.append(('', dtype)) if not ishomogeneous: if len(descr) > 1: dtype = np.dtype(descr) else: dtype = np.dtype(ttype) output = np.array(data, dtype) if usemask: if dtype.names is not None: mdtype = [(_, bool) for _ in dtype.names] else: mdtype = bool outputmask = np.array(masks, dtype=mdtype) names = output.dtype.names if usemask and names: for (name, conv) in zip(names, converters): missing_values = [conv(_) for _ in conv.missing_values if _ != ''] for mval in missing_values: outputmask[name] |= output[name] == mval if usemask: output = output.view(MaskedArray) output._mask = outputmask output = _ensure_ndmin_ndarray(output, ndmin=ndmin) if unpack: if names is None: return output.T elif len(names) == 1: return output[names[0]] else: return [output[field] for field in names] return output _genfromtxt_with_like = array_function_dispatch()(genfromtxt) def recfromtxt(fname, **kwargs): warnings.warn('`recfromtxt` is deprecated, use `numpy.genfromtxt` instead.(deprecated in NumPy 2.0)', DeprecationWarning, stacklevel=2) kwargs.setdefault('dtype', None) usemask = kwargs.get('usemask', False) output = genfromtxt(fname, **kwargs) if usemask: from numpy.ma.mrecords import MaskedRecords output = output.view(MaskedRecords) else: output = output.view(np.recarray) return output def recfromcsv(fname, **kwargs): warnings.warn('`recfromcsv` is deprecated, use `numpy.genfromtxt` with comma as `delimiter` instead. (deprecated in NumPy 2.0)', DeprecationWarning, stacklevel=2) kwargs.setdefault('case_sensitive', 'lower') kwargs.setdefault('names', True) kwargs.setdefault('delimiter', ',') kwargs.setdefault('dtype', None) output = genfromtxt(fname, **kwargs) usemask = kwargs.get('usemask', False) if usemask: from numpy.ma.mrecords import MaskedRecords output = output.view(MaskedRecords) else: output = output.view(np.recarray) return output # File: numpy-main/numpy/lib/_polynomial_impl.py """""" __all__ = ['poly', 'roots', 'polyint', 'polyder', 'polyadd', 'polysub', 'polymul', 'polydiv', 'polyval', 'poly1d', 'polyfit'] import functools import re import warnings from .._utils import set_module import numpy._core.numeric as NX from numpy._core import isscalar, abs, finfo, atleast_1d, hstack, dot, array, ones from numpy._core import overrides from numpy.exceptions import RankWarning from numpy.lib._twodim_base_impl import diag, vander from numpy.lib._function_base_impl import trim_zeros from numpy.lib._type_check_impl import iscomplex, real, imag, mintypecode from numpy.linalg import eigvals, lstsq, inv array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') def _poly_dispatcher(seq_of_zeros): return seq_of_zeros @array_function_dispatch(_poly_dispatcher) def poly(seq_of_zeros): seq_of_zeros = atleast_1d(seq_of_zeros) sh = seq_of_zeros.shape if len(sh) == 2 and sh[0] == sh[1] and (sh[0] != 0): seq_of_zeros = eigvals(seq_of_zeros) elif len(sh) == 1: dt = seq_of_zeros.dtype if dt != object: seq_of_zeros = seq_of_zeros.astype(mintypecode(dt.char)) else: raise ValueError('input must be 1d or non-empty square 2d array.') if len(seq_of_zeros) == 0: return 1.0 dt = seq_of_zeros.dtype a = ones((1,), dtype=dt) for zero in seq_of_zeros: a = NX.convolve(a, array([1, -zero], dtype=dt), mode='full') if issubclass(a.dtype.type, NX.complexfloating): roots = NX.asarray(seq_of_zeros, complex) if NX.all(NX.sort(roots) == NX.sort(roots.conjugate())): a = a.real.copy() return a def _roots_dispatcher(p): return p @array_function_dispatch(_roots_dispatcher) def roots(p): p = atleast_1d(p) if p.ndim != 1: raise ValueError('Input must be a rank-1 array.') non_zero = NX.nonzero(NX.ravel(p))[0] if len(non_zero) == 0: return NX.array([]) trailing_zeros = len(p) - non_zero[-1] - 1 p = p[int(non_zero[0]):int(non_zero[-1]) + 1] if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)): p = p.astype(float) N = len(p) if N > 1: A = diag(NX.ones((N - 2,), p.dtype), -1) A[0, :] = -p[1:] / p[0] roots = eigvals(A) else: roots = NX.array([]) roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype))) return roots def _polyint_dispatcher(p, m=None, k=None): return (p,) @array_function_dispatch(_polyint_dispatcher) def polyint(p, m=1, k=None): m = int(m) if m < 0: raise ValueError('Order of integral must be positive (see polyder)') if k is None: k = NX.zeros(m, float) k = atleast_1d(k) if len(k) == 1 and m > 1: k = k[0] * NX.ones(m, float) if len(k) < m: raise ValueError('k must be a scalar or a rank-1 array of length 1 or >m.') truepoly = isinstance(p, poly1d) p = NX.asarray(p) if m == 0: if truepoly: return poly1d(p) return p else: y = NX.concatenate((p.__truediv__(NX.arange(len(p), 0, -1)), [k[0]])) val = polyint(y, m - 1, k=k[1:]) if truepoly: return poly1d(val) return val def _polyder_dispatcher(p, m=None): return (p,) @array_function_dispatch(_polyder_dispatcher) def polyder(p, m=1): m = int(m) if m < 0: raise ValueError('Order of derivative must be positive (see polyint)') truepoly = isinstance(p, poly1d) p = NX.asarray(p) n = len(p) - 1 y = p[:-1] * NX.arange(n, 0, -1) if m == 0: val = p else: val = polyder(y, m - 1) if truepoly: val = poly1d(val) return val def _polyfit_dispatcher(x, y, deg, rcond=None, full=None, w=None, cov=None): return (x, y, w) @array_function_dispatch(_polyfit_dispatcher) def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): order = int(deg) + 1 x = NX.asarray(x) + 0.0 y = NX.asarray(y) + 0.0 if deg < 0: raise ValueError('expected deg >= 0') if x.ndim != 1: raise TypeError('expected 1D vector for x') if x.size == 0: raise TypeError('expected non-empty vector for x') if y.ndim < 1 or y.ndim > 2: raise TypeError('expected 1D or 2D array for y') if x.shape[0] != y.shape[0]: raise TypeError('expected x and y to have same length') if rcond is None: rcond = len(x) * finfo(x.dtype).eps lhs = vander(x, order) rhs = y if w is not None: w = NX.asarray(w) + 0.0 if w.ndim != 1: raise TypeError('expected a 1-d array for weights') if w.shape[0] != y.shape[0]: raise TypeError('expected w and y to have the same length') lhs *= w[:, NX.newaxis] if rhs.ndim == 2: rhs *= w[:, NX.newaxis] else: rhs *= w scale = NX.sqrt((lhs * lhs).sum(axis=0)) lhs /= scale (c, resids, rank, s) = lstsq(lhs, rhs, rcond) c = (c.T / scale).T if rank != order and (not full): msg = 'Polyfit may be poorly conditioned' warnings.warn(msg, RankWarning, stacklevel=2) if full: return (c, resids, rank, s, rcond) elif cov: Vbase = inv(dot(lhs.T, lhs)) Vbase /= NX.outer(scale, scale) if cov == 'unscaled': fac = 1 else: if len(x) <= order: raise ValueError('the number of data points must exceed order to scale the covariance matrix') fac = resids / (len(x) - order) if y.ndim == 1: return (c, Vbase * fac) else: return (c, Vbase[:, :, NX.newaxis] * fac) else: return c def _polyval_dispatcher(p, x): return (p, x) @array_function_dispatch(_polyval_dispatcher) def polyval(p, x): p = NX.asarray(p) if isinstance(x, poly1d): y = 0 else: x = NX.asanyarray(x) y = NX.zeros_like(x) for pv in p: y = y * x + pv return y def _binary_op_dispatcher(a1, a2): return (a1, a2) @array_function_dispatch(_binary_op_dispatcher) def polyadd(a1, a2): truepoly = isinstance(a1, poly1d) or isinstance(a2, poly1d) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: val = a1 + a2 elif diff > 0: zr = NX.zeros(diff, a1.dtype) val = NX.concatenate((zr, a1)) + a2 else: zr = NX.zeros(abs(diff), a2.dtype) val = a1 + NX.concatenate((zr, a2)) if truepoly: val = poly1d(val) return val @array_function_dispatch(_binary_op_dispatcher) def polysub(a1, a2): truepoly = isinstance(a1, poly1d) or isinstance(a2, poly1d) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: val = a1 - a2 elif diff > 0: zr = NX.zeros(diff, a1.dtype) val = NX.concatenate((zr, a1)) - a2 else: zr = NX.zeros(abs(diff), a2.dtype) val = a1 - NX.concatenate((zr, a2)) if truepoly: val = poly1d(val) return val @array_function_dispatch(_binary_op_dispatcher) def polymul(a1, a2): truepoly = isinstance(a1, poly1d) or isinstance(a2, poly1d) (a1, a2) = (poly1d(a1), poly1d(a2)) val = NX.convolve(a1, a2) if truepoly: val = poly1d(val) return val def _polydiv_dispatcher(u, v): return (u, v) @array_function_dispatch(_polydiv_dispatcher) def polydiv(u, v): truepoly = isinstance(u, poly1d) or isinstance(v, poly1d) u = atleast_1d(u) + 0.0 v = atleast_1d(v) + 0.0 w = u[0] + v[0] m = len(u) - 1 n = len(v) - 1 scale = 1.0 / v[0] q = NX.zeros((max(m - n + 1, 1),), w.dtype) r = u.astype(w.dtype) for k in range(0, m - n + 1): d = scale * r[k] q[k] = d r[k:k + n + 1] -= d * v while NX.allclose(r[0], 0, rtol=1e-14) and r.shape[-1] > 1: r = r[1:] if truepoly: return (poly1d(q), poly1d(r)) return (q, r) _poly_mat = re.compile('\\*\\*([0-9]*)') def _raise_power(astr, wrap=70): n = 0 line1 = '' line2 = '' output = ' ' while True: mat = _poly_mat.search(astr, n) if mat is None: break span = mat.span() power = mat.groups()[0] partstr = astr[n:span[0]] n = span[1] toadd2 = partstr + ' ' * (len(power) - 1) toadd1 = ' ' * (len(partstr) - 1) + power if len(line2) + len(toadd2) > wrap or len(line1) + len(toadd1) > wrap: output += line1 + '\n' + line2 + '\n ' line1 = toadd1 line2 = toadd2 else: line2 += partstr + ' ' * (len(power) - 1) line1 += ' ' * (len(partstr) - 1) + power output += line1 + '\n' + line2 return output + astr[n:] @set_module('numpy') class poly1d: __hash__ = None @property def coeffs(self): return self._coeffs @coeffs.setter def coeffs(self, value): if value is not self._coeffs: raise AttributeError('Cannot set attribute') @property def variable(self): return self._variable @property def order(self): return len(self._coeffs) - 1 @property def roots(self): return roots(self._coeffs) @property def _coeffs(self): return self.__dict__['coeffs'] @_coeffs.setter def _coeffs(self, coeffs): self.__dict__['coeffs'] = coeffs r = roots c = coef = coefficients = coeffs o = order def __init__(self, c_or_r, r=False, variable=None): if isinstance(c_or_r, poly1d): self._variable = c_or_r._variable self._coeffs = c_or_r._coeffs if set(c_or_r.__dict__) - set(self.__dict__): msg = 'In the future extra properties will not be copied across when constructing one poly1d from another' warnings.warn(msg, FutureWarning, stacklevel=2) self.__dict__.update(c_or_r.__dict__) if variable is not None: self._variable = variable return if r: c_or_r = poly(c_or_r) c_or_r = atleast_1d(c_or_r) if c_or_r.ndim > 1: raise ValueError('Polynomial must be 1d only.') c_or_r = trim_zeros(c_or_r, trim='f') if len(c_or_r) == 0: c_or_r = NX.array([0], dtype=c_or_r.dtype) self._coeffs = c_or_r if variable is None: variable = 'x' self._variable = variable def __array__(self, t=None, copy=None): if t: return NX.asarray(self.coeffs, t, copy=copy) else: return NX.asarray(self.coeffs, copy=copy) def __repr__(self): vals = repr(self.coeffs) vals = vals[6:-1] return 'poly1d(%s)' % vals def __len__(self): return self.order def __str__(self): thestr = '0' var = self.variable coeffs = self.coeffs[NX.logical_or.accumulate(self.coeffs != 0)] N = len(coeffs) - 1 def fmt_float(q): s = '%.4g' % q if s.endswith('.0000'): s = s[:-5] return s for (k, coeff) in enumerate(coeffs): if not iscomplex(coeff): coefstr = fmt_float(real(coeff)) elif real(coeff) == 0: coefstr = '%sj' % fmt_float(imag(coeff)) else: coefstr = '(%s + %sj)' % (fmt_float(real(coeff)), fmt_float(imag(coeff))) power = N - k if power == 0: if coefstr != '0': newstr = '%s' % (coefstr,) elif k == 0: newstr = '0' else: newstr = '' elif power == 1: if coefstr == '0': newstr = '' elif coefstr == 'b': newstr = var else: newstr = '%s %s' % (coefstr, var) elif coefstr == '0': newstr = '' elif coefstr == 'b': newstr = '%s**%d' % (var, power) else: newstr = '%s %s**%d' % (coefstr, var, power) if k > 0: if newstr != '': if newstr.startswith('-'): thestr = '%s - %s' % (thestr, newstr[1:]) else: thestr = '%s + %s' % (thestr, newstr) else: thestr = newstr return _raise_power(thestr) def __call__(self, val): return polyval(self.coeffs, val) def __neg__(self): return poly1d(-self.coeffs) def __pos__(self): return self def __mul__(self, other): if isscalar(other): return poly1d(self.coeffs * other) else: other = poly1d(other) return poly1d(polymul(self.coeffs, other.coeffs)) def __rmul__(self, other): if isscalar(other): return poly1d(other * self.coeffs) else: other = poly1d(other) return poly1d(polymul(self.coeffs, other.coeffs)) def __add__(self, other): other = poly1d(other) return poly1d(polyadd(self.coeffs, other.coeffs)) def __radd__(self, other): other = poly1d(other) return poly1d(polyadd(self.coeffs, other.coeffs)) def __pow__(self, val): if not isscalar(val) or int(val) != val or val < 0: raise ValueError('Power to non-negative integers only.') res = [1] for _ in range(val): res = polymul(self.coeffs, res) return poly1d(res) def __sub__(self, other): other = poly1d(other) return poly1d(polysub(self.coeffs, other.coeffs)) def __rsub__(self, other): other = poly1d(other) return poly1d(polysub(other.coeffs, self.coeffs)) def __div__(self, other): if isscalar(other): return poly1d(self.coeffs / other) else: other = poly1d(other) return polydiv(self, other) __truediv__ = __div__ def __rdiv__(self, other): if isscalar(other): return poly1d(other / self.coeffs) else: other = poly1d(other) return polydiv(other, self) __rtruediv__ = __rdiv__ def __eq__(self, other): if not isinstance(other, poly1d): return NotImplemented if self.coeffs.shape != other.coeffs.shape: return False return (self.coeffs == other.coeffs).all() def __ne__(self, other): if not isinstance(other, poly1d): return NotImplemented return not self.__eq__(other) def __getitem__(self, val): ind = self.order - val if val > self.order: return self.coeffs.dtype.type(0) if val < 0: return self.coeffs.dtype.type(0) return self.coeffs[ind] def __setitem__(self, key, val): ind = self.order - key if key < 0: raise ValueError('Does not support negative powers.') if key > self.order: zr = NX.zeros(key - self.order, self.coeffs.dtype) self._coeffs = NX.concatenate((zr, self.coeffs)) ind = 0 self._coeffs[ind] = val return def __iter__(self): return iter(self.coeffs) def integ(self, m=1, k=0): return poly1d(polyint(self.coeffs, m=m, k=k)) def deriv(self, m=1): return poly1d(polyder(self.coeffs, m=m)) warnings.simplefilter('always', RankWarning) # File: numpy-main/numpy/lib/_scimath_impl.py """""" import numpy._core.numeric as nx import numpy._core.numerictypes as nt from numpy._core.numeric import asarray, any from numpy._core.overrides import array_function_dispatch from numpy.lib._type_check_impl import isreal __all__ = ['sqrt', 'log', 'log2', 'logn', 'log10', 'power', 'arccos', 'arcsin', 'arctanh'] _ln2 = nx.log(2.0) def _tocomplex(arr): if issubclass(arr.dtype.type, (nt.single, nt.byte, nt.short, nt.ubyte, nt.ushort, nt.csingle)): return arr.astype(nt.csingle) else: return arr.astype(nt.cdouble) def _fix_real_lt_zero(x): x = asarray(x) if any(isreal(x) & (x < 0)): x = _tocomplex(x) return x def _fix_int_lt_zero(x): x = asarray(x) if any(isreal(x) & (x < 0)): x = x * 1.0 return x def _fix_real_abs_gt_1(x): x = asarray(x) if any(isreal(x) & (abs(x) > 1)): x = _tocomplex(x) return x def _unary_dispatcher(x): return (x,) @array_function_dispatch(_unary_dispatcher) def sqrt(x): x = _fix_real_lt_zero(x) return nx.sqrt(x) @array_function_dispatch(_unary_dispatcher) def log(x): x = _fix_real_lt_zero(x) return nx.log(x) @array_function_dispatch(_unary_dispatcher) def log10(x): x = _fix_real_lt_zero(x) return nx.log10(x) def _logn_dispatcher(n, x): return (n, x) @array_function_dispatch(_logn_dispatcher) def logn(n, x): x = _fix_real_lt_zero(x) n = _fix_real_lt_zero(n) return nx.log(x) / nx.log(n) @array_function_dispatch(_unary_dispatcher) def log2(x): x = _fix_real_lt_zero(x) return nx.log2(x) def _power_dispatcher(x, p): return (x, p) @array_function_dispatch(_power_dispatcher) def power(x, p): x = _fix_real_lt_zero(x) p = _fix_int_lt_zero(p) return nx.power(x, p) @array_function_dispatch(_unary_dispatcher) def arccos(x): x = _fix_real_abs_gt_1(x) return nx.arccos(x) @array_function_dispatch(_unary_dispatcher) def arcsin(x): x = _fix_real_abs_gt_1(x) return nx.arcsin(x) @array_function_dispatch(_unary_dispatcher) def arctanh(x): x = _fix_real_abs_gt_1(x) return nx.arctanh(x) # File: numpy-main/numpy/lib/_shape_base_impl.py import functools import warnings import numpy._core.numeric as _nx from numpy._core.numeric import asarray, zeros, zeros_like, array, asanyarray from numpy._core.fromnumeric import reshape, transpose from numpy._core.multiarray import normalize_axis_index from numpy._core._multiarray_umath import _array_converter from numpy._core import overrides from numpy._core import vstack, atleast_3d from numpy._core.numeric import normalize_axis_tuple from numpy._core.overrides import set_module from numpy._core.shape_base import _arrays_for_stack_dispatcher from numpy.lib._index_tricks_impl import ndindex from numpy.matrixlib.defmatrix import matrix __all__ = ['column_stack', 'row_stack', 'dstack', 'array_split', 'split', 'hsplit', 'vsplit', 'dsplit', 'apply_over_axes', 'expand_dims', 'apply_along_axis', 'kron', 'tile', 'take_along_axis', 'put_along_axis'] array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') def _make_along_axis_idx(arr_shape, indices, axis): if not _nx.issubdtype(indices.dtype, _nx.integer): raise IndexError('`indices` must be an integer array') if len(arr_shape) != indices.ndim: raise ValueError('`indices` and `arr` must have the same number of dimensions') shape_ones = (1,) * indices.ndim dest_dims = list(range(axis)) + [None] + list(range(axis + 1, indices.ndim)) fancy_index = [] for (dim, n) in zip(dest_dims, arr_shape): if dim is None: fancy_index.append(indices) else: ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim + 1:] fancy_index.append(_nx.arange(n).reshape(ind_shape)) return tuple(fancy_index) def _take_along_axis_dispatcher(arr, indices, axis): return (arr, indices) @array_function_dispatch(_take_along_axis_dispatcher) def take_along_axis(arr, indices, axis): if axis is None: if indices.ndim != 1: raise ValueError('when axis=None, `indices` must have a single dimension.') arr = arr.flat arr_shape = (len(arr),) axis = 0 else: axis = normalize_axis_index(axis, arr.ndim) arr_shape = arr.shape return arr[_make_along_axis_idx(arr_shape, indices, axis)] def _put_along_axis_dispatcher(arr, indices, values, axis): return (arr, indices, values) @array_function_dispatch(_put_along_axis_dispatcher) def put_along_axis(arr, indices, values, axis): if axis is None: if indices.ndim != 1: raise ValueError('when axis=None, `indices` must have a single dimension.') arr = arr.flat axis = 0 arr_shape = (len(arr),) else: axis = normalize_axis_index(axis, arr.ndim) arr_shape = arr.shape arr[_make_along_axis_idx(arr_shape, indices, axis)] = values def _apply_along_axis_dispatcher(func1d, axis, arr, *args, **kwargs): return (arr,) @array_function_dispatch(_apply_along_axis_dispatcher) def apply_along_axis(func1d, axis, arr, *args, **kwargs): conv = _array_converter(arr) arr = conv[0] nd = arr.ndim axis = normalize_axis_index(axis, nd) in_dims = list(range(nd)) inarr_view = transpose(arr, in_dims[:axis] + in_dims[axis + 1:] + [axis]) inds = ndindex(inarr_view.shape[:-1]) inds = (ind + (Ellipsis,) for ind in inds) try: ind0 = next(inds) except StopIteration: raise ValueError('Cannot apply_along_axis when any iteration dimensions are 0') from None res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs)) if not isinstance(res, matrix): buff = zeros_like(res, shape=inarr_view.shape[:-1] + res.shape) else: buff = zeros(inarr_view.shape[:-1] + res.shape, dtype=res.dtype) buff_dims = list(range(buff.ndim)) buff_permute = buff_dims[0:axis] + buff_dims[buff.ndim - res.ndim:buff.ndim] + buff_dims[axis:buff.ndim - res.ndim] buff[ind0] = res for ind in inds: buff[ind] = asanyarray(func1d(inarr_view[ind], *args, **kwargs)) res = transpose(buff, buff_permute) return conv.wrap(res) def _apply_over_axes_dispatcher(func, a, axes): return (a,) @array_function_dispatch(_apply_over_axes_dispatcher) def apply_over_axes(func, a, axes): val = asarray(a) N = a.ndim if array(axes).ndim == 0: axes = (axes,) for axis in axes: if axis < 0: axis = N + axis args = (val, axis) res = func(*args) if res.ndim == val.ndim: val = res else: res = expand_dims(res, axis) if res.ndim == val.ndim: val = res else: raise ValueError('function is not returning an array of the correct shape') return val def _expand_dims_dispatcher(a, axis): return (a,) @array_function_dispatch(_expand_dims_dispatcher) def expand_dims(a, axis): if isinstance(a, matrix): a = asarray(a) else: a = asanyarray(a) if type(axis) not in (tuple, list): axis = (axis,) out_ndim = len(axis) + a.ndim axis = normalize_axis_tuple(axis, out_ndim) shape_it = iter(a.shape) shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)] return a.reshape(shape) @set_module('numpy') def row_stack(tup, *, dtype=None, casting='same_kind'): warnings.warn('`row_stack` alias is deprecated. Use `np.vstack` directly.', DeprecationWarning, stacklevel=2) return vstack(tup, dtype=dtype, casting=casting) row_stack.__doc__ = vstack.__doc__ def _column_stack_dispatcher(tup): return _arrays_for_stack_dispatcher(tup) @array_function_dispatch(_column_stack_dispatcher) def column_stack(tup): arrays = [] for v in tup: arr = asanyarray(v) if arr.ndim < 2: arr = array(arr, copy=None, subok=True, ndmin=2).T arrays.append(arr) return _nx.concatenate(arrays, 1) def _dstack_dispatcher(tup): return _arrays_for_stack_dispatcher(tup) @array_function_dispatch(_dstack_dispatcher) def dstack(tup): arrs = atleast_3d(*tup) if not isinstance(arrs, tuple): arrs = (arrs,) return _nx.concatenate(arrs, 2) def _replace_zero_by_x_arrays(sub_arys): for i in range(len(sub_arys)): if _nx.ndim(sub_arys[i]) == 0: sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype) elif _nx.sometrue(_nx.equal(_nx.shape(sub_arys[i]), 0)): sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype) return sub_arys def _array_split_dispatcher(ary, indices_or_sections, axis=None): return (ary, indices_or_sections) @array_function_dispatch(_array_split_dispatcher) def array_split(ary, indices_or_sections, axis=0): try: Ntotal = ary.shape[axis] except AttributeError: Ntotal = len(ary) try: Nsections = len(indices_or_sections) + 1 div_points = [0] + list(indices_or_sections) + [Ntotal] except TypeError: Nsections = int(indices_or_sections) if Nsections <= 0: raise ValueError('number sections must be larger than 0.') from None (Neach_section, extras) = divmod(Ntotal, Nsections) section_sizes = [0] + extras * [Neach_section + 1] + (Nsections - extras) * [Neach_section] div_points = _nx.array(section_sizes, dtype=_nx.intp).cumsum() sub_arys = [] sary = _nx.swapaxes(ary, axis, 0) for i in range(Nsections): st = div_points[i] end = div_points[i + 1] sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0)) return sub_arys def _split_dispatcher(ary, indices_or_sections, axis=None): return (ary, indices_or_sections) @array_function_dispatch(_split_dispatcher) def split(ary, indices_or_sections, axis=0): try: len(indices_or_sections) except TypeError: sections = indices_or_sections N = ary.shape[axis] if N % sections: raise ValueError('array split does not result in an equal division') from None return array_split(ary, indices_or_sections, axis) def _hvdsplit_dispatcher(ary, indices_or_sections): return (ary, indices_or_sections) @array_function_dispatch(_hvdsplit_dispatcher) def hsplit(ary, indices_or_sections): if _nx.ndim(ary) == 0: raise ValueError('hsplit only works on arrays of 1 or more dimensions') if ary.ndim > 1: return split(ary, indices_or_sections, 1) else: return split(ary, indices_or_sections, 0) @array_function_dispatch(_hvdsplit_dispatcher) def vsplit(ary, indices_or_sections): if _nx.ndim(ary) < 2: raise ValueError('vsplit only works on arrays of 2 or more dimensions') return split(ary, indices_or_sections, 0) @array_function_dispatch(_hvdsplit_dispatcher) def dsplit(ary, indices_or_sections): if _nx.ndim(ary) < 3: raise ValueError('dsplit only works on arrays of 3 or more dimensions') return split(ary, indices_or_sections, 2) def get_array_wrap(*args): warnings.warn('`get_array_wrap` is deprecated. (deprecated in NumPy 2.0)', DeprecationWarning, stacklevel=2) wrappers = sorted(((getattr(x, '__array_priority__', 0), -i, x.__array_wrap__) for (i, x) in enumerate(args) if hasattr(x, '__array_wrap__'))) if wrappers: return wrappers[-1][-1] return None def _kron_dispatcher(a, b): return (a, b) @array_function_dispatch(_kron_dispatcher) def kron(a, b): b = asanyarray(b) a = array(a, copy=None, subok=True, ndmin=b.ndim) is_any_mat = isinstance(a, matrix) or isinstance(b, matrix) (ndb, nda) = (b.ndim, a.ndim) nd = max(ndb, nda) if nda == 0 or ndb == 0: return _nx.multiply(a, b) as_ = a.shape bs = b.shape if not a.flags.contiguous: a = reshape(a, as_) if not b.flags.contiguous: b = reshape(b, bs) as_ = (1,) * max(0, ndb - nda) + as_ bs = (1,) * max(0, nda - ndb) + bs a_arr = expand_dims(a, axis=tuple(range(ndb - nda))) b_arr = expand_dims(b, axis=tuple(range(nda - ndb))) a_arr = expand_dims(a_arr, axis=tuple(range(1, nd * 2, 2))) b_arr = expand_dims(b_arr, axis=tuple(range(0, nd * 2, 2))) result = _nx.multiply(a_arr, b_arr, subok=not is_any_mat) result = result.reshape(_nx.multiply(as_, bs)) return result if not is_any_mat else matrix(result, copy=False) def _tile_dispatcher(A, reps): return (A, reps) @array_function_dispatch(_tile_dispatcher) def tile(A, reps): try: tup = tuple(reps) except TypeError: tup = (reps,) d = len(tup) if all((x == 1 for x in tup)) and isinstance(A, _nx.ndarray): return _nx.array(A, copy=True, subok=True, ndmin=d) else: c = _nx.array(A, copy=None, subok=True, ndmin=d) if d < c.ndim: tup = (1,) * (c.ndim - d) + tup shape_out = tuple((s * t for (s, t) in zip(c.shape, tup))) n = c.size if n > 0: for (dim_in, nrep) in zip(c.shape, tup): if nrep != 1: c = c.reshape(-1, n).repeat(nrep, 0) n //= dim_in return c.reshape(shape_out) # File: numpy-main/numpy/lib/_stride_tricks_impl.py """""" import numpy as np from numpy._core.numeric import normalize_axis_tuple from numpy._core.overrides import array_function_dispatch, set_module __all__ = ['broadcast_to', 'broadcast_arrays', 'broadcast_shapes'] class DummyArray: def __init__(self, interface, base=None): self.__array_interface__ = interface self.base = base def _maybe_view_as_subclass(original_array, new_array): if type(original_array) is not type(new_array): new_array = new_array.view(type=type(original_array)) if new_array.__array_finalize__: new_array.__array_finalize__(original_array) return new_array @set_module('numpy.lib.stride_tricks') def as_strided(x, shape=None, strides=None, subok=False, writeable=True): x = np.array(x, copy=None, subok=subok) interface = dict(x.__array_interface__) if shape is not None: interface['shape'] = tuple(shape) if strides is not None: interface['strides'] = tuple(strides) array = np.asarray(DummyArray(interface, base=x)) array.dtype = x.dtype view = _maybe_view_as_subclass(x, array) if view.flags.writeable and (not writeable): view.flags.writeable = False return view def _sliding_window_view_dispatcher(x, window_shape, axis=None, *, subok=None, writeable=None): return (x,) @array_function_dispatch(_sliding_window_view_dispatcher, module='numpy.lib.stride_tricks') def sliding_window_view(x, window_shape, axis=None, *, subok=False, writeable=False): window_shape = tuple(window_shape) if np.iterable(window_shape) else (window_shape,) x = np.array(x, copy=None, subok=subok) window_shape_array = np.array(window_shape) if np.any(window_shape_array < 0): raise ValueError('`window_shape` cannot contain negative values') if axis is None: axis = tuple(range(x.ndim)) if len(window_shape) != len(axis): raise ValueError(f'Since axis is `None`, must provide window_shape for all dimensions of `x`; got {len(window_shape)} window_shape elements and `x.ndim` is {x.ndim}.') else: axis = normalize_axis_tuple(axis, x.ndim, allow_duplicate=True) if len(window_shape) != len(axis): raise ValueError(f'Must provide matching length window_shape and axis; got {len(window_shape)} window_shape elements and {len(axis)} axes elements.') out_strides = x.strides + tuple((x.strides[ax] for ax in axis)) x_shape_trimmed = list(x.shape) for (ax, dim) in zip(axis, window_shape): if x_shape_trimmed[ax] < dim: raise ValueError('window shape cannot be larger than input array shape') x_shape_trimmed[ax] -= dim - 1 out_shape = tuple(x_shape_trimmed) + window_shape return as_strided(x, strides=out_strides, shape=out_shape, subok=subok, writeable=writeable) def _broadcast_to(array, shape, subok, readonly): shape = tuple(shape) if np.iterable(shape) else (shape,) array = np.array(array, copy=None, subok=subok) if not shape and array.shape: raise ValueError('cannot broadcast a non-scalar to a scalar array') if any((size < 0 for size in shape)): raise ValueError('all elements of broadcast shape must be non-negative') extras = [] it = np.nditer((array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras, op_flags=['readonly'], itershape=shape, order='C') with it: broadcast = it.itviews[0] result = _maybe_view_as_subclass(array, broadcast) if not readonly and array.flags._writeable_no_warn: result.flags.writeable = True result.flags._warn_on_write = True return result def _broadcast_to_dispatcher(array, shape, subok=None): return (array,) @array_function_dispatch(_broadcast_to_dispatcher, module='numpy') def broadcast_to(array, shape, subok=False): return _broadcast_to(array, shape, subok=subok, readonly=True) def _broadcast_shape(*args): b = np.broadcast(*args[:32]) for pos in range(32, len(args), 31): b = broadcast_to(0, b.shape) b = np.broadcast(b, *args[pos:pos + 31]) return b.shape _size0_dtype = np.dtype([]) @set_module('numpy') def broadcast_shapes(*args): arrays = [np.empty(x, dtype=_size0_dtype) for x in args] return _broadcast_shape(*arrays) def _broadcast_arrays_dispatcher(*args, subok=None): return args @array_function_dispatch(_broadcast_arrays_dispatcher, module='numpy') def broadcast_arrays(*args, subok=False): args = [np.array(_m, copy=None, subok=subok) for _m in args] shape = _broadcast_shape(*args) result = [array if array.shape == shape else _broadcast_to(array, shape, subok=subok, readonly=False) for array in args] return tuple(result) # File: numpy-main/numpy/lib/_twodim_base_impl.py """""" import functools import operator from numpy._core._multiarray_umath import _array_converter from numpy._core.numeric import asanyarray, arange, zeros, greater_equal, multiply, ones, asarray, where, int8, int16, int32, int64, intp, empty, promote_types, diagonal, nonzero, indices from numpy._core.overrides import set_array_function_like_doc, set_module from numpy._core import overrides from numpy._core import iinfo from numpy.lib._stride_tricks_impl import broadcast_to __all__ = ['diag', 'diagflat', 'eye', 'fliplr', 'flipud', 'tri', 'triu', 'tril', 'vander', 'histogram2d', 'mask_indices', 'tril_indices', 'tril_indices_from', 'triu_indices', 'triu_indices_from'] array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') i1 = iinfo(int8) i2 = iinfo(int16) i4 = iinfo(int32) def _min_int(low, high): if high <= i1.max and low >= i1.min: return int8 if high <= i2.max and low >= i2.min: return int16 if high <= i4.max and low >= i4.min: return int32 return int64 def _flip_dispatcher(m): return (m,) @array_function_dispatch(_flip_dispatcher) def fliplr(m): m = asanyarray(m) if m.ndim < 2: raise ValueError('Input must be >= 2-d.') return m[:, ::-1] @array_function_dispatch(_flip_dispatcher) def flipud(m): m = asanyarray(m) if m.ndim < 1: raise ValueError('Input must be >= 1-d.') return m[::-1, ...] @set_array_function_like_doc @set_module('numpy') def eye(N, M=None, k=0, dtype=float, order='C', *, device=None, like=None): if like is not None: return _eye_with_like(like, N, M=M, k=k, dtype=dtype, order=order, device=device) if M is None: M = N m = zeros((N, M), dtype=dtype, order=order, device=device) if k >= M: return m M = operator.index(M) k = operator.index(k) if k >= 0: i = k else: i = -k * M m[:M - k].flat[i::M + 1] = 1 return m _eye_with_like = array_function_dispatch()(eye) def _diag_dispatcher(v, k=None): return (v,) @array_function_dispatch(_diag_dispatcher) def diag(v, k=0): v = asanyarray(v) s = v.shape if len(s) == 1: n = s[0] + abs(k) res = zeros((n, n), v.dtype) if k >= 0: i = k else: i = -k * n res[:n - k].flat[i::n + 1] = v return res elif len(s) == 2: return diagonal(v, k) else: raise ValueError('Input must be 1- or 2-d.') @array_function_dispatch(_diag_dispatcher) def diagflat(v, k=0): conv = _array_converter(v) (v,) = conv.as_arrays(subok=False) v = v.ravel() s = len(v) n = s + abs(k) res = zeros((n, n), v.dtype) if k >= 0: i = arange(0, n - k, dtype=intp) fi = i + k + i * n else: i = arange(0, n + k, dtype=intp) fi = i + (i - k) * n res.flat[fi] = v return conv.wrap(res) @set_array_function_like_doc @set_module('numpy') def tri(N, M=None, k=0, dtype=float, *, like=None): if like is not None: return _tri_with_like(like, N, M=M, k=k, dtype=dtype) if M is None: M = N m = greater_equal.outer(arange(N, dtype=_min_int(0, N)), arange(-k, M - k, dtype=_min_int(-k, M - k))) m = m.astype(dtype, copy=False) return m _tri_with_like = array_function_dispatch()(tri) def _trilu_dispatcher(m, k=None): return (m,) @array_function_dispatch(_trilu_dispatcher) def tril(m, k=0): m = asanyarray(m) mask = tri(*m.shape[-2:], k=k, dtype=bool) return where(mask, m, zeros(1, m.dtype)) @array_function_dispatch(_trilu_dispatcher) def triu(m, k=0): m = asanyarray(m) mask = tri(*m.shape[-2:], k=k - 1, dtype=bool) return where(mask, zeros(1, m.dtype), m) def _vander_dispatcher(x, N=None, increasing=None): return (x,) @array_function_dispatch(_vander_dispatcher) def vander(x, N=None, increasing=False): x = asarray(x) if x.ndim != 1: raise ValueError('x must be a one-dimensional array or sequence.') if N is None: N = len(x) v = empty((len(x), N), dtype=promote_types(x.dtype, int)) tmp = v[:, ::-1] if not increasing else v if N > 0: tmp[:, 0] = 1 if N > 1: tmp[:, 1:] = x[:, None] multiply.accumulate(tmp[:, 1:], out=tmp[:, 1:], axis=1) return v def _histogram2d_dispatcher(x, y, bins=None, range=None, density=None, weights=None): yield x yield y try: N = len(bins) except TypeError: N = 1 if N == 2: yield from bins else: yield bins yield weights @array_function_dispatch(_histogram2d_dispatcher) def histogram2d(x, y, bins=10, range=None, density=None, weights=None): from numpy import histogramdd if len(x) != len(y): raise ValueError('x and y must have the same length.') try: N = len(bins) except TypeError: N = 1 if N != 1 and N != 2: xedges = yedges = asarray(bins) bins = [xedges, yedges] (hist, edges) = histogramdd([x, y], bins, range, density, weights) return (hist, edges[0], edges[1]) @set_module('numpy') def mask_indices(n, mask_func, k=0): m = ones((n, n), int) a = mask_func(m, k) return nonzero(a != 0) @set_module('numpy') def tril_indices(n, k=0, m=None): tri_ = tri(n, m, k=k, dtype=bool) return tuple((broadcast_to(inds, tri_.shape)[tri_] for inds in indices(tri_.shape, sparse=True))) def _trilu_indices_form_dispatcher(arr, k=None): return (arr,) @array_function_dispatch(_trilu_indices_form_dispatcher) def tril_indices_from(arr, k=0): if arr.ndim != 2: raise ValueError('input array must be 2-d') return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1]) @set_module('numpy') def triu_indices(n, k=0, m=None): tri_ = ~tri(n, m, k=k - 1, dtype=bool) return tuple((broadcast_to(inds, tri_.shape)[tri_] for inds in indices(tri_.shape, sparse=True))) @array_function_dispatch(_trilu_indices_form_dispatcher) def triu_indices_from(arr, k=0): if arr.ndim != 2: raise ValueError('input array must be 2-d') return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1]) # File: numpy-main/numpy/lib/_type_check_impl.py """""" import functools __all__ = ['iscomplexobj', 'isrealobj', 'imag', 'iscomplex', 'isreal', 'nan_to_num', 'real', 'real_if_close', 'typename', 'mintypecode', 'common_type'] from .._utils import set_module import numpy._core.numeric as _nx from numpy._core.numeric import asarray, asanyarray, isnan, zeros from numpy._core import overrides, getlimits from ._ufunclike_impl import isneginf, isposinf array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy') _typecodes_by_elsize = 'GDFgdfQqLlIiHhBb?' @set_module('numpy') def mintypecode(typechars, typeset='GDFgdf', default='d'): typecodes = (isinstance(t, str) and t or asarray(t).dtype.char for t in typechars) intersection = set((t for t in typecodes if t in typeset)) if not intersection: return default if 'F' in intersection and 'd' in intersection: return 'D' return min(intersection, key=_typecodes_by_elsize.index) def _real_dispatcher(val): return (val,) @array_function_dispatch(_real_dispatcher) def real(val): try: return val.real except AttributeError: return asanyarray(val).real def _imag_dispatcher(val): return (val,) @array_function_dispatch(_imag_dispatcher) def imag(val): try: return val.imag except AttributeError: return asanyarray(val).imag def _is_type_dispatcher(x): return (x,) @array_function_dispatch(_is_type_dispatcher) def iscomplex(x): ax = asanyarray(x) if issubclass(ax.dtype.type, _nx.complexfloating): return ax.imag != 0 res = zeros(ax.shape, bool) return res[()] @array_function_dispatch(_is_type_dispatcher) def isreal(x): return imag(x) == 0 @array_function_dispatch(_is_type_dispatcher) def iscomplexobj(x): try: dtype = x.dtype type_ = dtype.type except AttributeError: type_ = asarray(x).dtype.type return issubclass(type_, _nx.complexfloating) @array_function_dispatch(_is_type_dispatcher) def isrealobj(x): return not iscomplexobj(x) def _getmaxmin(t): from numpy._core import getlimits f = getlimits.finfo(t) return (f.max, f.min) def _nan_to_num_dispatcher(x, copy=None, nan=None, posinf=None, neginf=None): return (x,) @array_function_dispatch(_nan_to_num_dispatcher) def nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None): x = _nx.array(x, subok=True, copy=copy) xtype = x.dtype.type isscalar = x.ndim == 0 if not issubclass(xtype, _nx.inexact): return x[()] if isscalar else x iscomplex = issubclass(xtype, _nx.complexfloating) dest = (x.real, x.imag) if iscomplex else (x,) (maxf, minf) = _getmaxmin(x.real.dtype) if posinf is not None: maxf = posinf if neginf is not None: minf = neginf for d in dest: idx_nan = isnan(d) idx_posinf = isposinf(d) idx_neginf = isneginf(d) _nx.copyto(d, nan, where=idx_nan) _nx.copyto(d, maxf, where=idx_posinf) _nx.copyto(d, minf, where=idx_neginf) return x[()] if isscalar else x def _real_if_close_dispatcher(a, tol=None): return (a,) @array_function_dispatch(_real_if_close_dispatcher) def real_if_close(a, tol=100): a = asanyarray(a) type_ = a.dtype.type if not issubclass(type_, _nx.complexfloating): return a if tol > 1: f = getlimits.finfo(type_) tol = f.eps * tol if _nx.all(_nx.absolute(a.imag) < tol): a = a.real return a _namefromtype = {'S1': 'character', '?': 'bool', 'b': 'signed char', 'B': 'unsigned char', 'h': 'short', 'H': 'unsigned short', 'i': 'integer', 'I': 'unsigned integer', 'l': 'long integer', 'L': 'unsigned long integer', 'q': 'long long integer', 'Q': 'unsigned long long integer', 'f': 'single precision', 'd': 'double precision', 'g': 'long precision', 'F': 'complex single precision', 'D': 'complex double precision', 'G': 'complex long double precision', 'S': 'string', 'U': 'unicode', 'V': 'void', 'O': 'object'} @set_module('numpy') def typename(char): return _namefromtype[char] array_type = [[_nx.float16, _nx.float32, _nx.float64, _nx.longdouble], [None, _nx.complex64, _nx.complex128, _nx.clongdouble]] array_precision = {_nx.float16: 0, _nx.float32: 1, _nx.float64: 2, _nx.longdouble: 3, _nx.complex64: 1, _nx.complex128: 2, _nx.clongdouble: 3} def _common_type_dispatcher(*arrays): return arrays @array_function_dispatch(_common_type_dispatcher) def common_type(*arrays): is_complex = False precision = 0 for a in arrays: t = a.dtype.type if iscomplexobj(a): is_complex = True if issubclass(t, _nx.integer): p = 2 else: p = array_precision.get(t) if p is None: raise TypeError("can't get common type for non-numeric array") precision = max(precision, p) if is_complex: return array_type[1][precision] else: return array_type[0][precision] # File: numpy-main/numpy/lib/_ufunclike_impl.py """""" __all__ = ['fix', 'isneginf', 'isposinf'] import numpy._core.numeric as nx from numpy._core.overrides import array_function_dispatch def _dispatcher(x, out=None): return (x, out) @array_function_dispatch(_dispatcher, verify=False, module='numpy') def fix(x, out=None): res = nx.asanyarray(nx.ceil(x, out=out)) res = nx.floor(x, out=res, where=nx.greater_equal(x, 0)) if out is None and type(res) is nx.ndarray: res = res[()] return res @array_function_dispatch(_dispatcher, verify=False, module='numpy') def isposinf(x, out=None): is_inf = nx.isinf(x) try: signbit = ~nx.signbit(x) except TypeError as e: dtype = nx.asanyarray(x).dtype raise TypeError(f'This operation is not supported for {dtype} values because it would be ambiguous.') from e else: return nx.logical_and(is_inf, signbit, out) @array_function_dispatch(_dispatcher, verify=False, module='numpy') def isneginf(x, out=None): is_inf = nx.isinf(x) try: signbit = nx.signbit(x) except TypeError as e: dtype = nx.asanyarray(x).dtype raise TypeError(f'This operation is not supported for {dtype} values because it would be ambiguous.') from e else: return nx.logical_and(is_inf, signbit, out) # File: numpy-main/numpy/lib/_user_array_impl.py """""" from numpy._core import array, asarray, absolute, add, subtract, multiply, divide, remainder, power, left_shift, right_shift, bitwise_and, bitwise_or, bitwise_xor, invert, less, less_equal, not_equal, equal, greater, greater_equal, shape, reshape, arange, sin, sqrt, transpose class container: def __init__(self, data, dtype=None, copy=True): self.array = array(data, dtype, copy=copy) def __repr__(self): if self.ndim > 0: return self.__class__.__name__ + repr(self.array)[len('array'):] else: return self.__class__.__name__ + '(' + repr(self.array) + ')' def __array__(self, t=None): if t: return self.array.astype(t) return self.array def __len__(self): return len(self.array) def __getitem__(self, index): return self._rc(self.array[index]) def __setitem__(self, index, value): self.array[index] = asarray(value, self.dtype) def __abs__(self): return self._rc(absolute(self.array)) def __neg__(self): return self._rc(-self.array) def __add__(self, other): return self._rc(self.array + asarray(other)) __radd__ = __add__ def __iadd__(self, other): add(self.array, other, self.array) return self def __sub__(self, other): return self._rc(self.array - asarray(other)) def __rsub__(self, other): return self._rc(asarray(other) - self.array) def __isub__(self, other): subtract(self.array, other, self.array) return self def __mul__(self, other): return self._rc(multiply(self.array, asarray(other))) __rmul__ = __mul__ def __imul__(self, other): multiply(self.array, other, self.array) return self def __div__(self, other): return self._rc(divide(self.array, asarray(other))) def __rdiv__(self, other): return self._rc(divide(asarray(other), self.array)) def __idiv__(self, other): divide(self.array, other, self.array) return self def __mod__(self, other): return self._rc(remainder(self.array, other)) def __rmod__(self, other): return self._rc(remainder(other, self.array)) def __imod__(self, other): remainder(self.array, other, self.array) return self def __divmod__(self, other): return (self._rc(divide(self.array, other)), self._rc(remainder(self.array, other))) def __rdivmod__(self, other): return (self._rc(divide(other, self.array)), self._rc(remainder(other, self.array))) def __pow__(self, other): return self._rc(power(self.array, asarray(other))) def __rpow__(self, other): return self._rc(power(asarray(other), self.array)) def __ipow__(self, other): power(self.array, other, self.array) return self def __lshift__(self, other): return self._rc(left_shift(self.array, other)) def __rshift__(self, other): return self._rc(right_shift(self.array, other)) def __rlshift__(self, other): return self._rc(left_shift(other, self.array)) def __rrshift__(self, other): return self._rc(right_shift(other, self.array)) def __ilshift__(self, other): left_shift(self.array, other, self.array) return self def __irshift__(self, other): right_shift(self.array, other, self.array) return self def __and__(self, other): return self._rc(bitwise_and(self.array, other)) def __rand__(self, other): return self._rc(bitwise_and(other, self.array)) def __iand__(self, other): bitwise_and(self.array, other, self.array) return self def __xor__(self, other): return self._rc(bitwise_xor(self.array, other)) def __rxor__(self, other): return self._rc(bitwise_xor(other, self.array)) def __ixor__(self, other): bitwise_xor(self.array, other, self.array) return self def __or__(self, other): return self._rc(bitwise_or(self.array, other)) def __ror__(self, other): return self._rc(bitwise_or(other, self.array)) def __ior__(self, other): bitwise_or(self.array, other, self.array) return self def __pos__(self): return self._rc(self.array) def __invert__(self): return self._rc(invert(self.array)) def _scalarfunc(self, func): if self.ndim == 0: return func(self[0]) else: raise TypeError('only rank-0 arrays can be converted to Python scalars.') def __complex__(self): return self._scalarfunc(complex) def __float__(self): return self._scalarfunc(float) def __int__(self): return self._scalarfunc(int) def __hex__(self): return self._scalarfunc(hex) def __oct__(self): return self._scalarfunc(oct) def __lt__(self, other): return self._rc(less(self.array, other)) def __le__(self, other): return self._rc(less_equal(self.array, other)) def __eq__(self, other): return self._rc(equal(self.array, other)) def __ne__(self, other): return self._rc(not_equal(self.array, other)) def __gt__(self, other): return self._rc(greater(self.array, other)) def __ge__(self, other): return self._rc(greater_equal(self.array, other)) def copy(self): """""" return self._rc(self.array.copy()) def tostring(self): """""" return self.array.tostring() def tobytes(self): """""" return self.array.tobytes() def byteswap(self): """""" return self._rc(self.array.byteswap()) def astype(self, typecode): """""" return self._rc(self.array.astype(typecode)) def _rc(self, a): if len(shape(a)) == 0: return a else: return self.__class__(a) def __array_wrap__(self, *args): return self.__class__(args[0]) def __setattr__(self, attr, value): if attr == 'array': object.__setattr__(self, attr, value) return try: self.array.__setattr__(attr, value) except AttributeError: object.__setattr__(self, attr, value) def __getattr__(self, attr): if attr == 'array': return object.__getattribute__(self, attr) return self.array.__getattribute__(attr) if __name__ == '__main__': temp = reshape(arange(10000), (100, 100)) ua = container(temp) print(dir(ua)) print(shape(ua), ua.shape) ua_small = ua[:3, :5] print(ua_small) ua_small[0, 0] = 10 print(ua_small[0, 0], ua[0, 0]) print(sin(ua_small) / 3.0 * 6.0 + sqrt(ua_small ** 2)) print(less(ua_small, 103), type(less(ua_small, 103))) print(type(ua_small * reshape(arange(15), shape(ua_small)))) print(reshape(ua_small, (5, 3))) print(transpose(ua_small)) # File: numpy-main/numpy/lib/_utils_impl.py import os import sys import textwrap import types import warnings import functools import platform from numpy._core import ndarray from numpy._utils import set_module import numpy as np __all__ = ['get_include', 'info', 'show_runtime'] @set_module('numpy') def show_runtime(): from numpy._core._multiarray_umath import __cpu_features__, __cpu_baseline__, __cpu_dispatch__ from pprint import pprint config_found = [{'numpy_version': np.__version__, 'python': sys.version, 'uname': platform.uname()}] (features_found, features_not_found) = ([], []) for feature in __cpu_dispatch__: if __cpu_features__[feature]: features_found.append(feature) else: features_not_found.append(feature) config_found.append({'simd_extensions': {'baseline': __cpu_baseline__, 'found': features_found, 'not_found': features_not_found}}) try: from threadpoolctl import threadpool_info config_found.extend(threadpool_info()) except ImportError: print('WARNING: `threadpoolctl` not found in system! Install it by `pip install threadpoolctl`. Once installed, try `np.show_runtime` again for more detailed build information') pprint(config_found) @set_module('numpy') def get_include(): import numpy if numpy.show_config is None: d = os.path.join(os.path.dirname(numpy.__file__), '_core', 'include') else: import numpy._core as _core d = os.path.join(os.path.dirname(_core.__file__), 'include') return d class _Deprecate: def __init__(self, old_name=None, new_name=None, message=None): self.old_name = old_name self.new_name = new_name self.message = message def __call__(self, func, *args, **kwargs): old_name = self.old_name new_name = self.new_name message = self.message if old_name is None: old_name = func.__name__ if new_name is None: depdoc = '`%s` is deprecated!' % old_name else: depdoc = '`%s` is deprecated, use `%s` instead!' % (old_name, new_name) if message is not None: depdoc += '\n' + message @functools.wraps(func) def newfunc(*args, **kwds): warnings.warn(depdoc, DeprecationWarning, stacklevel=2) return func(*args, **kwds) newfunc.__name__ = old_name doc = func.__doc__ if doc is None: doc = depdoc else: lines = doc.expandtabs().split('\n') indent = _get_indent(lines[1:]) if lines[0].lstrip(): doc = indent * ' ' + doc else: skip = len(lines[0]) + 1 for line in lines[1:]: if len(line) > indent: break skip += len(line) + 1 doc = doc[skip:] depdoc = textwrap.indent(depdoc, ' ' * indent) doc = f'{depdoc}\n\n{doc}' newfunc.__doc__ = doc return newfunc def _get_indent(lines): indent = sys.maxsize for line in lines: content = len(line.lstrip()) if content: indent = min(indent, len(line) - content) if indent == sys.maxsize: indent = 0 return indent def deprecate(*args, **kwargs): warnings.warn('`deprecate` is deprecated, use `warn` with `DeprecationWarning` instead. (deprecated in NumPy 2.0)', DeprecationWarning, stacklevel=2) if args: fn = args[0] args = args[1:] return _Deprecate(*args, **kwargs)(fn) else: return _Deprecate(*args, **kwargs) def deprecate_with_doc(msg): warnings.warn('`deprecate` is deprecated, use `warn` with `DeprecationWarning` instead. (deprecated in NumPy 2.0)', DeprecationWarning, stacklevel=2) return _Deprecate(message=msg) def _split_line(name, arguments, width): firstwidth = len(name) k = firstwidth newstr = name sepstr = ', ' arglist = arguments.split(sepstr) for argument in arglist: if k == firstwidth: addstr = '' else: addstr = sepstr k = k + len(argument) + len(addstr) if k > width: k = firstwidth + 1 + len(argument) newstr = newstr + ',\n' + ' ' * (firstwidth + 2) + argument else: newstr = newstr + addstr + argument return newstr _namedict = None _dictlist = None def _makenamedict(module='numpy'): module = __import__(module, globals(), locals(), []) thedict = {module.__name__: module.__dict__} dictlist = [module.__name__] totraverse = [module.__dict__] while True: if len(totraverse) == 0: break thisdict = totraverse.pop(0) for x in thisdict.keys(): if isinstance(thisdict[x], types.ModuleType): modname = thisdict[x].__name__ if modname not in dictlist: moddict = thisdict[x].__dict__ dictlist.append(modname) totraverse.append(moddict) thedict[modname] = moddict return (thedict, dictlist) def _info(obj, output=None): extra = '' tic = '' bp = lambda x: x cls = getattr(obj, '__class__', type(obj)) nm = getattr(cls, '__name__', cls) strides = obj.strides endian = obj.dtype.byteorder if output is None: output = sys.stdout print('class: ', nm, file=output) print('shape: ', obj.shape, file=output) print('strides: ', strides, file=output) print('itemsize: ', obj.itemsize, file=output) print('aligned: ', bp(obj.flags.aligned), file=output) print('contiguous: ', bp(obj.flags.contiguous), file=output) print('fortran: ', obj.flags.fortran, file=output) print('data pointer: %s%s' % (hex(obj.ctypes._as_parameter_.value), extra), file=output) print('byteorder: ', end=' ', file=output) if endian in ['|', '=']: print('%s%s%s' % (tic, sys.byteorder, tic), file=output) byteswap = False elif endian == '>': print('%sbig%s' % (tic, tic), file=output) byteswap = sys.byteorder != 'big' else: print('%slittle%s' % (tic, tic), file=output) byteswap = sys.byteorder != 'little' print('byteswap: ', bp(byteswap), file=output) print('type: %s' % obj.dtype, file=output) @set_module('numpy') def info(object=None, maxwidth=76, output=None, toplevel='numpy'): global _namedict, _dictlist import pydoc import inspect if hasattr(object, '_ppimport_importer') or hasattr(object, '_ppimport_module'): object = object._ppimport_module elif hasattr(object, '_ppimport_attr'): object = object._ppimport_attr if output is None: output = sys.stdout if object is None: info(info) elif isinstance(object, ndarray): _info(object, output=output) elif isinstance(object, str): if _namedict is None: (_namedict, _dictlist) = _makenamedict(toplevel) numfound = 0 objlist = [] for namestr in _dictlist: try: obj = _namedict[namestr][object] if id(obj) in objlist: print('\n *** Repeat reference found in %s *** ' % namestr, file=output) else: objlist.append(id(obj)) print(' *** Found in %s ***' % namestr, file=output) info(obj) print('-' * maxwidth, file=output) numfound += 1 except KeyError: pass if numfound == 0: print('Help for %s not found.' % object, file=output) else: print('\n *** Total of %d references found. ***' % numfound, file=output) elif inspect.isfunction(object) or inspect.ismethod(object): name = object.__name__ try: arguments = str(inspect.signature(object)) except Exception: arguments = '()' if len(name + arguments) > maxwidth: argstr = _split_line(name, arguments, maxwidth) else: argstr = name + arguments print(' ' + argstr + '\n', file=output) print(inspect.getdoc(object), file=output) elif inspect.isclass(object): name = object.__name__ try: arguments = str(inspect.signature(object)) except Exception: arguments = '()' if len(name + arguments) > maxwidth: argstr = _split_line(name, arguments, maxwidth) else: argstr = name + arguments print(' ' + argstr + '\n', file=output) doc1 = inspect.getdoc(object) if doc1 is None: if hasattr(object, '__init__'): print(inspect.getdoc(object.__init__), file=output) else: print(inspect.getdoc(object), file=output) methods = pydoc.allmethods(object) public_methods = [meth for meth in methods if meth[0] != '_'] if public_methods: print('\n\nMethods:\n', file=output) for meth in public_methods: thisobj = getattr(object, meth, None) if thisobj is not None: (methstr, other) = pydoc.splitdoc(inspect.getdoc(thisobj) or 'None') print(' %s -- %s' % (meth, methstr), file=output) elif hasattr(object, '__doc__'): print(inspect.getdoc(object), file=output) def safe_eval(source): warnings.warn('`safe_eval` is deprecated. Use `ast.literal_eval` instead. Be aware of security implications, such as memory exhaustion based attacks (deprecated in NumPy 2.0)', DeprecationWarning, stacklevel=2) import ast return ast.literal_eval(source) def _median_nancheck(data, result, axis): if data.size == 0: return result potential_nans = data.take(-1, axis=axis) n = np.isnan(potential_nans) if np.ma.isMaskedArray(n): n = n.filled(False) if not n.any(): return result if isinstance(result, np.generic): return potential_nans np.copyto(result, potential_nans, where=n) return result def _opt_info(): from numpy._core._multiarray_umath import __cpu_features__, __cpu_baseline__, __cpu_dispatch__ if len(__cpu_baseline__) == 0 and len(__cpu_dispatch__) == 0: return '' enabled_features = ' '.join(__cpu_baseline__) for feature in __cpu_dispatch__: if __cpu_features__[feature]: enabled_features += f' {feature}*' else: enabled_features += f' {feature}?' return enabled_features def drop_metadata(dtype, /): if dtype.fields is not None: found_metadata = dtype.metadata is not None names = [] formats = [] offsets = [] titles = [] for (name, field) in dtype.fields.items(): field_dt = drop_metadata(field[0]) if field_dt is not field[0]: found_metadata = True names.append(name) formats.append(field_dt) offsets.append(field[1]) titles.append(None if len(field) < 3 else field[2]) if not found_metadata: return dtype structure = dict(names=names, formats=formats, offsets=offsets, titles=titles, itemsize=dtype.itemsize) return np.dtype(structure, align=dtype.isalignedstruct) elif dtype.subdtype is not None: (subdtype, shape) = dtype.subdtype new_subdtype = drop_metadata(subdtype) if dtype.metadata is None and new_subdtype is subdtype: return dtype return np.dtype((new_subdtype, shape)) else: if dtype.metadata is None: return dtype return np.dtype(dtype.str) # File: numpy-main/numpy/lib/_version.py """""" import re __all__ = ['NumpyVersion'] class NumpyVersion: def __init__(self, vstring): self.vstring = vstring ver_main = re.match('\\d+\\.\\d+\\.\\d+', vstring) if not ver_main: raise ValueError('Not a valid numpy version string') self.version = ver_main.group() (self.major, self.minor, self.bugfix) = [int(x) for x in self.version.split('.')] if len(vstring) == ver_main.end(): self.pre_release = 'final' else: alpha = re.match('a\\d', vstring[ver_main.end():]) beta = re.match('b\\d', vstring[ver_main.end():]) rc = re.match('rc\\d', vstring[ver_main.end():]) pre_rel = [m for m in [alpha, beta, rc] if m is not None] if pre_rel: self.pre_release = pre_rel[0].group() else: self.pre_release = '' self.is_devversion = bool(re.search('.dev', vstring)) def _compare_version(self, other): if self.major == other.major: if self.minor == other.minor: if self.bugfix == other.bugfix: vercmp = 0 elif self.bugfix > other.bugfix: vercmp = 1 else: vercmp = -1 elif self.minor > other.minor: vercmp = 1 else: vercmp = -1 elif self.major > other.major: vercmp = 1 else: vercmp = -1 return vercmp def _compare_pre_release(self, other): if self.pre_release == other.pre_release: vercmp = 0 elif self.pre_release == 'final': vercmp = 1 elif other.pre_release == 'final': vercmp = -1 elif self.pre_release > other.pre_release: vercmp = 1 else: vercmp = -1 return vercmp def _compare(self, other): if not isinstance(other, (str, NumpyVersion)): raise ValueError('Invalid object to compare with NumpyVersion.') if isinstance(other, str): other = NumpyVersion(other) vercmp = self._compare_version(other) if vercmp == 0: vercmp = self._compare_pre_release(other) if vercmp == 0: if self.is_devversion is other.is_devversion: vercmp = 0 elif self.is_devversion: vercmp = -1 else: vercmp = 1 return vercmp def __lt__(self, other): return self._compare(other) < 0 def __le__(self, other): return self._compare(other) <= 0 def __eq__(self, other): return self._compare(other) == 0 def __ne__(self, other): return self._compare(other) != 0 def __gt__(self, other): return self._compare(other) > 0 def __ge__(self, other): return self._compare(other) >= 0 def __repr__(self): return 'NumpyVersion(%s)' % self.vstring # File: numpy-main/numpy/lib/format.py """""" import io import os import pickle import warnings import numpy from numpy.lib._utils_impl import drop_metadata __all__ = [] EXPECTED_KEYS = {'descr', 'fortran_order', 'shape'} MAGIC_PREFIX = b'\x93NUMPY' MAGIC_LEN = len(MAGIC_PREFIX) + 2 ARRAY_ALIGN = 64 BUFFER_SIZE = 2 ** 18 GROWTH_AXIS_MAX_DIGITS = 21 _header_size_info = {(1, 0): (' 255: raise ValueError('major version must be 0 <= major < 256') if minor < 0 or minor > 255: raise ValueError('minor version must be 0 <= minor < 256') return MAGIC_PREFIX + bytes([major, minor]) def read_magic(fp): magic_str = _read_bytes(fp, MAGIC_LEN, 'magic string') if magic_str[:-2] != MAGIC_PREFIX: msg = 'the magic string is not correct; expected %r, got %r' raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) (major, minor) = magic_str[-2:] return (major, minor) def dtype_to_descr(dtype): new_dtype = drop_metadata(dtype) if new_dtype is not dtype: warnings.warn('metadata on a dtype is not saved to an npy/npz. Use another format (such as pickle) to store it.', UserWarning, stacklevel=2) dtype = new_dtype if dtype.names is not None: return dtype.descr elif not type(dtype)._legacy: warnings.warn('Custom dtypes are saved as python objects using the pickle protocol. Loading this file requires allow_pickle=True to be set.', UserWarning, stacklevel=2) return '|O' else: return dtype.str def descr_to_dtype(descr): if isinstance(descr, str): return numpy.dtype(descr) elif isinstance(descr, tuple): dt = descr_to_dtype(descr[0]) return numpy.dtype((dt, descr[1])) titles = [] names = [] formats = [] offsets = [] offset = 0 for field in descr: if len(field) == 2: (name, descr_str) = field dt = descr_to_dtype(descr_str) else: (name, descr_str, shape) = field dt = numpy.dtype((descr_to_dtype(descr_str), shape)) is_pad = name == '' and dt.type is numpy.void and (dt.names is None) if not is_pad: (title, name) = name if isinstance(name, tuple) else (None, name) titles.append(title) names.append(name) formats.append(dt) offsets.append(offset) offset += dt.itemsize return numpy.dtype({'names': names, 'formats': formats, 'titles': titles, 'offsets': offsets, 'itemsize': offset}) def header_data_from_array_1_0(array): d = {'shape': array.shape} if array.flags.c_contiguous: d['fortran_order'] = False elif array.flags.f_contiguous: d['fortran_order'] = True else: d['fortran_order'] = False d['descr'] = dtype_to_descr(array.dtype) return d def _wrap_header(header, version): import struct assert version is not None (fmt, encoding) = _header_size_info[version] header = header.encode(encoding) hlen = len(header) + 1 padlen = ARRAY_ALIGN - (MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN try: header_prefix = magic(*version) + struct.pack(fmt, hlen + padlen) except struct.error: msg = 'Header length {} too big for version={}'.format(hlen, version) raise ValueError(msg) from None return header_prefix + header + b' ' * padlen + b'\n' def _wrap_header_guess_version(header): try: return _wrap_header(header, (1, 0)) except ValueError: pass try: ret = _wrap_header(header, (2, 0)) except UnicodeEncodeError: pass else: warnings.warn('Stored array in format 2.0. It can only beread by NumPy >= 1.9', UserWarning, stacklevel=2) return ret header = _wrap_header(header, (3, 0)) warnings.warn('Stored array in format 3.0. It can only be read by NumPy >= 1.17', UserWarning, stacklevel=2) return header def _write_array_header(fp, d, version=None): header = ['{'] for (key, value) in sorted(d.items()): header.append("'%s': %s, " % (key, repr(value))) header.append('}') header = ''.join(header) shape = d['shape'] header += ' ' * (GROWTH_AXIS_MAX_DIGITS - len(repr(shape[-1 if d['fortran_order'] else 0])) if len(shape) > 0 else 0) if version is None: header = _wrap_header_guess_version(header) else: header = _wrap_header(header, version) fp.write(header) def write_array_header_1_0(fp, d): _write_array_header(fp, d, (1, 0)) def write_array_header_2_0(fp, d): _write_array_header(fp, d, (2, 0)) def read_array_header_1_0(fp, max_header_size=_MAX_HEADER_SIZE): return _read_array_header(fp, version=(1, 0), max_header_size=max_header_size) def read_array_header_2_0(fp, max_header_size=_MAX_HEADER_SIZE): return _read_array_header(fp, version=(2, 0), max_header_size=max_header_size) def _filter_header(s): import tokenize from io import StringIO tokens = [] last_token_was_number = False for token in tokenize.generate_tokens(StringIO(s).readline): token_type = token[0] token_string = token[1] if last_token_was_number and token_type == tokenize.NAME and (token_string == 'L'): continue else: tokens.append(token) last_token_was_number = token_type == tokenize.NUMBER return tokenize.untokenize(tokens) def _read_array_header(fp, version, max_header_size=_MAX_HEADER_SIZE): import ast import struct hinfo = _header_size_info.get(version) if hinfo is None: raise ValueError('Invalid version {!r}'.format(version)) (hlength_type, encoding) = hinfo hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), 'array header length') header_length = struct.unpack(hlength_type, hlength_str)[0] header = _read_bytes(fp, header_length, 'array header') header = header.decode(encoding) if len(header) > max_header_size: raise ValueError(f'Header info length ({len(header)}) is large and may not be safe to load securely.\nTo allow loading, adjust `max_header_size` or fully trust the `.npy` file using `allow_pickle=True`.\nFor safety against large resource use or crashes, sandboxing may be necessary.') try: d = ast.literal_eval(header) except SyntaxError as e: if version <= (2, 0): header = _filter_header(header) try: d = ast.literal_eval(header) except SyntaxError as e2: msg = 'Cannot parse header: {!r}' raise ValueError(msg.format(header)) from e2 else: warnings.warn('Reading `.npy` or `.npz` file required additional header parsing as it was created on Python 2. Save the file again to speed up loading and avoid this warning.', UserWarning, stacklevel=4) else: msg = 'Cannot parse header: {!r}' raise ValueError(msg.format(header)) from e if not isinstance(d, dict): msg = 'Header is not a dictionary: {!r}' raise ValueError(msg.format(d)) if EXPECTED_KEYS != d.keys(): keys = sorted(d.keys()) msg = 'Header does not contain the correct keys: {!r}' raise ValueError(msg.format(keys)) if not isinstance(d['shape'], tuple) or not all((isinstance(x, int) for x in d['shape'])): msg = 'shape is not valid: {!r}' raise ValueError(msg.format(d['shape'])) if not isinstance(d['fortran_order'], bool): msg = 'fortran_order is not a valid bool: {!r}' raise ValueError(msg.format(d['fortran_order'])) try: dtype = descr_to_dtype(d['descr']) except TypeError as e: msg = 'descr is not a valid dtype descriptor: {!r}' raise ValueError(msg.format(d['descr'])) from e return (d['shape'], d['fortran_order'], dtype) def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None): _check_version(version) _write_array_header(fp, header_data_from_array_1_0(array), version) if array.itemsize == 0: buffersize = 0 else: buffersize = max(16 * 1024 ** 2 // array.itemsize, 1) dtype_class = type(array.dtype) if array.dtype.hasobject or not dtype_class._legacy: if not allow_pickle: if array.dtype.hasobject: raise ValueError('Object arrays cannot be saved when allow_pickle=False') if not dtype_class._legacy: raise ValueError('User-defined dtypes cannot be saved when allow_pickle=False') if pickle_kwargs is None: pickle_kwargs = {} pickle.dump(array, fp, protocol=4, **pickle_kwargs) elif array.flags.f_contiguous and (not array.flags.c_contiguous): if isfileobj(fp): array.T.tofile(fp) else: for chunk in numpy.nditer(array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='F'): fp.write(chunk.tobytes('C')) elif isfileobj(fp): array.tofile(fp) else: for chunk in numpy.nditer(array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='C'): fp.write(chunk.tobytes('C')) def read_array(fp, allow_pickle=False, pickle_kwargs=None, *, max_header_size=_MAX_HEADER_SIZE): if allow_pickle: max_header_size = 2 ** 64 version = read_magic(fp) _check_version(version) (shape, fortran_order, dtype) = _read_array_header(fp, version, max_header_size=max_header_size) if len(shape) == 0: count = 1 else: count = numpy.multiply.reduce(shape, dtype=numpy.int64) if dtype.hasobject: if not allow_pickle: raise ValueError('Object arrays cannot be loaded when allow_pickle=False') if pickle_kwargs is None: pickle_kwargs = {} try: array = pickle.load(fp, **pickle_kwargs) except UnicodeError as err: raise UnicodeError('Unpickling a python object failed: %r\nYou may need to pass the encoding= option to numpy.load' % (err,)) from err else: if isfileobj(fp): array = numpy.fromfile(fp, dtype=dtype, count=count) else: array = numpy.ndarray(count, dtype=dtype) if dtype.itemsize > 0: max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) for i in range(0, count, max_read_count): read_count = min(max_read_count, count - i) read_size = int(read_count * dtype.itemsize) data = _read_bytes(fp, read_size, 'array data') array[i:i + read_count] = numpy.frombuffer(data, dtype=dtype, count=read_count) if fortran_order: array.shape = shape[::-1] array = array.transpose() else: array.shape = shape return array def open_memmap(filename, mode='r+', dtype=None, shape=None, fortran_order=False, version=None, *, max_header_size=_MAX_HEADER_SIZE): if isfileobj(filename): raise ValueError('Filename must be a string or a path-like object. Memmap cannot use existing file handles.') if 'w' in mode: _check_version(version) dtype = numpy.dtype(dtype) if dtype.hasobject: msg = "Array can't be memory-mapped: Python objects in dtype." raise ValueError(msg) d = dict(descr=dtype_to_descr(dtype), fortran_order=fortran_order, shape=shape) with open(os.fspath(filename), mode + 'b') as fp: _write_array_header(fp, d, version) offset = fp.tell() else: with open(os.fspath(filename), 'rb') as fp: version = read_magic(fp) _check_version(version) (shape, fortran_order, dtype) = _read_array_header(fp, version, max_header_size=max_header_size) if dtype.hasobject: msg = "Array can't be memory-mapped: Python objects in dtype." raise ValueError(msg) offset = fp.tell() if fortran_order: order = 'F' else: order = 'C' if mode == 'w+': mode = 'r+' marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order, mode=mode, offset=offset) return marray def _read_bytes(fp, size, error_template='ran out of data'): data = bytes() while True: try: r = fp.read(size - len(data)) data += r if len(r) == 0 or len(data) == size: break except BlockingIOError: pass if len(data) != size: msg = 'EOF: reading %s, expected %d bytes got %d' raise ValueError(msg % (error_template, size, len(data))) else: return data def isfileobj(f): if not isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter)): return False try: f.fileno() return True except OSError: return False # File: numpy-main/numpy/lib/introspect.py """""" import re __all__ = ['opt_func_info'] def opt_func_info(func_name=None, signature=None): from numpy._core._multiarray_umath import __cpu_targets_info__ as targets, dtype if func_name is not None: func_pattern = re.compile(func_name) matching_funcs = {k: v for (k, v) in targets.items() if func_pattern.search(k)} else: matching_funcs = targets if signature is not None: sig_pattern = re.compile(signature) matching_sigs = {} for (k, v) in matching_funcs.items(): matching_chars = {} for (chars, targets) in v.items(): if any((sig_pattern.search(c) or sig_pattern.search(dtype(c).name) for c in chars)): matching_chars[chars] = targets if matching_chars: matching_sigs[k] = matching_chars else: matching_sigs = matching_funcs return matching_sigs # File: numpy-main/numpy/lib/mixins.py """""" from numpy._core import umath as um __all__ = ['NDArrayOperatorsMixin'] def _disables_array_ufunc(obj): try: return obj.__array_ufunc__ is None except AttributeError: return False def _binary_method(ufunc, name): def func(self, other): if _disables_array_ufunc(other): return NotImplemented return ufunc(self, other) func.__name__ = '__{}__'.format(name) return func def _reflected_binary_method(ufunc, name): def func(self, other): if _disables_array_ufunc(other): return NotImplemented return ufunc(other, self) func.__name__ = '__r{}__'.format(name) return func def _inplace_binary_method(ufunc, name): def func(self, other): return ufunc(self, other, out=(self,)) func.__name__ = '__i{}__'.format(name) return func def _numeric_methods(ufunc, name): return (_binary_method(ufunc, name), _reflected_binary_method(ufunc, name), _inplace_binary_method(ufunc, name)) def _unary_method(ufunc, name): def func(self): return ufunc(self) func.__name__ = '__{}__'.format(name) return func class NDArrayOperatorsMixin: __slots__ = () __lt__ = _binary_method(um.less, 'lt') __le__ = _binary_method(um.less_equal, 'le') __eq__ = _binary_method(um.equal, 'eq') __ne__ = _binary_method(um.not_equal, 'ne') __gt__ = _binary_method(um.greater, 'gt') __ge__ = _binary_method(um.greater_equal, 'ge') (__add__, __radd__, __iadd__) = _numeric_methods(um.add, 'add') (__sub__, __rsub__, __isub__) = _numeric_methods(um.subtract, 'sub') (__mul__, __rmul__, __imul__) = _numeric_methods(um.multiply, 'mul') (__matmul__, __rmatmul__, __imatmul__) = _numeric_methods(um.matmul, 'matmul') (__truediv__, __rtruediv__, __itruediv__) = _numeric_methods(um.true_divide, 'truediv') (__floordiv__, __rfloordiv__, __ifloordiv__) = _numeric_methods(um.floor_divide, 'floordiv') (__mod__, __rmod__, __imod__) = _numeric_methods(um.remainder, 'mod') __divmod__ = _binary_method(um.divmod, 'divmod') __rdivmod__ = _reflected_binary_method(um.divmod, 'divmod') (__pow__, __rpow__, __ipow__) = _numeric_methods(um.power, 'pow') (__lshift__, __rlshift__, __ilshift__) = _numeric_methods(um.left_shift, 'lshift') (__rshift__, __rrshift__, __irshift__) = _numeric_methods(um.right_shift, 'rshift') (__and__, __rand__, __iand__) = _numeric_methods(um.bitwise_and, 'and') (__xor__, __rxor__, __ixor__) = _numeric_methods(um.bitwise_xor, 'xor') (__or__, __ror__, __ior__) = _numeric_methods(um.bitwise_or, 'or') __neg__ = _unary_method(um.negative, 'neg') __pos__ = _unary_method(um.positive, 'pos') __abs__ = _unary_method(um.absolute, 'abs') __invert__ = _unary_method(um.invert, 'invert') # File: numpy-main/numpy/lib/recfunctions.py """""" import itertools import numpy as np import numpy.ma as ma from numpy import ndarray from numpy.ma import MaskedArray from numpy.ma.mrecords import MaskedRecords from numpy._core.overrides import array_function_dispatch from numpy._core.records import recarray from numpy.lib._iotools import _is_string_like _check_fill_value = np.ma.core._check_fill_value __all__ = ['append_fields', 'apply_along_fields', 'assign_fields_by_name', 'drop_fields', 'find_duplicates', 'flatten_descr', 'get_fieldstructure', 'get_names', 'get_names_flat', 'join_by', 'merge_arrays', 'rec_append_fields', 'rec_drop_fields', 'rec_join', 'recursive_fill_fields', 'rename_fields', 'repack_fields', 'require_fields', 'stack_arrays', 'structured_to_unstructured', 'unstructured_to_structured'] def _recursive_fill_fields_dispatcher(input, output): return (input, output) @array_function_dispatch(_recursive_fill_fields_dispatcher) def recursive_fill_fields(input, output): newdtype = output.dtype for field in newdtype.names: try: current = input[field] except ValueError: continue if current.dtype.names is not None: recursive_fill_fields(current, output[field]) else: output[field][:len(current)] = current return output def _get_fieldspec(dtype): if dtype.names is None: return [('', dtype)] else: fields = ((name, dtype.fields[name]) for name in dtype.names) return [(name if len(f) == 2 else (f[2], name), f[0]) for (name, f) in fields] def get_names(adtype): listnames = [] names = adtype.names for name in names: current = adtype[name] if current.names is not None: listnames.append((name, tuple(get_names(current)))) else: listnames.append(name) return tuple(listnames) def get_names_flat(adtype): listnames = [] names = adtype.names for name in names: listnames.append(name) current = adtype[name] if current.names is not None: listnames.extend(get_names_flat(current)) return tuple(listnames) def flatten_descr(ndtype): names = ndtype.names if names is None: return (('', ndtype),) else: descr = [] for field in names: (typ, _) = ndtype.fields[field] if typ.names is not None: descr.extend(flatten_descr(typ)) else: descr.append((field, typ)) return tuple(descr) def _zip_dtype(seqarrays, flatten=False): newdtype = [] if flatten: for a in seqarrays: newdtype.extend(flatten_descr(a.dtype)) else: for a in seqarrays: current = a.dtype if current.names is not None and len(current.names) == 1: newdtype.extend(_get_fieldspec(current)) else: newdtype.append(('', current)) return np.dtype(newdtype) def _zip_descr(seqarrays, flatten=False): return _zip_dtype(seqarrays, flatten=flatten).descr def get_fieldstructure(adtype, lastname=None, parents=None): if parents is None: parents = {} names = adtype.names for name in names: current = adtype[name] if current.names is not None: if lastname: parents[name] = [lastname] else: parents[name] = [] parents.update(get_fieldstructure(current, name, parents)) else: lastparent = list(parents.get(lastname, []) or []) if lastparent: lastparent.append(lastname) elif lastname: lastparent = [lastname] parents[name] = lastparent or [] return parents def _izip_fields_flat(iterable): for element in iterable: if isinstance(element, np.void): yield from _izip_fields_flat(tuple(element)) else: yield element def _izip_fields(iterable): for element in iterable: if hasattr(element, '__iter__') and (not isinstance(element, str)): yield from _izip_fields(element) elif isinstance(element, np.void) and len(tuple(element)) == 1: yield from _izip_fields(element) else: yield element def _izip_records(seqarrays, fill_value=None, flatten=True): if flatten: zipfunc = _izip_fields_flat else: zipfunc = _izip_fields for tup in itertools.zip_longest(*seqarrays, fillvalue=fill_value): yield tuple(zipfunc(tup)) def _fix_output(output, usemask=True, asrecarray=False): if not isinstance(output, MaskedArray): usemask = False if usemask: if asrecarray: output = output.view(MaskedRecords) else: output = ma.filled(output) if asrecarray: output = output.view(recarray) return output def _fix_defaults(output, defaults=None): names = output.dtype.names (data, mask, fill_value) = (output.data, output.mask, output.fill_value) for (k, v) in (defaults or {}).items(): if k in names: fill_value[k] = v data[k][mask[k]] = v return output def _merge_arrays_dispatcher(seqarrays, fill_value=None, flatten=None, usemask=None, asrecarray=None): return seqarrays @array_function_dispatch(_merge_arrays_dispatcher) def merge_arrays(seqarrays, fill_value=-1, flatten=False, usemask=False, asrecarray=False): if len(seqarrays) == 1: seqarrays = np.asanyarray(seqarrays[0]) if isinstance(seqarrays, (ndarray, np.void)): seqdtype = seqarrays.dtype if seqdtype.names is None: seqdtype = np.dtype([('', seqdtype)]) if not flatten or _zip_dtype((seqarrays,), flatten=True) == seqdtype: seqarrays = seqarrays.ravel() if usemask: if asrecarray: seqtype = MaskedRecords else: seqtype = MaskedArray elif asrecarray: seqtype = recarray else: seqtype = ndarray return seqarrays.view(dtype=seqdtype, type=seqtype) else: seqarrays = (seqarrays,) else: seqarrays = [np.asanyarray(_m) for _m in seqarrays] sizes = tuple((a.size for a in seqarrays)) maxlength = max(sizes) newdtype = _zip_dtype(seqarrays, flatten=flatten) seqdata = [] seqmask = [] if usemask: for (a, n) in zip(seqarrays, sizes): nbmissing = maxlength - n data = a.ravel().__array__() mask = ma.getmaskarray(a).ravel() if nbmissing: fval = _check_fill_value(fill_value, a.dtype) if isinstance(fval, (ndarray, np.void)): if len(fval.dtype) == 1: fval = fval.item()[0] fmsk = True else: fval = np.array(fval, dtype=a.dtype, ndmin=1) fmsk = np.ones((1,), dtype=mask.dtype) else: fval = None fmsk = True seqdata.append(itertools.chain(data, [fval] * nbmissing)) seqmask.append(itertools.chain(mask, [fmsk] * nbmissing)) data = tuple(_izip_records(seqdata, flatten=flatten)) output = ma.array(np.fromiter(data, dtype=newdtype, count=maxlength), mask=list(_izip_records(seqmask, flatten=flatten))) if asrecarray: output = output.view(MaskedRecords) else: for (a, n) in zip(seqarrays, sizes): nbmissing = maxlength - n data = a.ravel().__array__() if nbmissing: fval = _check_fill_value(fill_value, a.dtype) if isinstance(fval, (ndarray, np.void)): if len(fval.dtype) == 1: fval = fval.item()[0] else: fval = np.array(fval, dtype=a.dtype, ndmin=1) else: fval = None seqdata.append(itertools.chain(data, [fval] * nbmissing)) output = np.fromiter(tuple(_izip_records(seqdata, flatten=flatten)), dtype=newdtype, count=maxlength) if asrecarray: output = output.view(recarray) return output def _drop_fields_dispatcher(base, drop_names, usemask=None, asrecarray=None): return (base,) @array_function_dispatch(_drop_fields_dispatcher) def drop_fields(base, drop_names, usemask=True, asrecarray=False): if _is_string_like(drop_names): drop_names = [drop_names] else: drop_names = set(drop_names) def _drop_descr(ndtype, drop_names): names = ndtype.names newdtype = [] for name in names: current = ndtype[name] if name in drop_names: continue if current.names is not None: descr = _drop_descr(current, drop_names) if descr: newdtype.append((name, descr)) else: newdtype.append((name, current)) return newdtype newdtype = _drop_descr(base.dtype, drop_names) output = np.empty(base.shape, dtype=newdtype) output = recursive_fill_fields(base, output) return _fix_output(output, usemask=usemask, asrecarray=asrecarray) def _keep_fields(base, keep_names, usemask=True, asrecarray=False): newdtype = [(n, base.dtype[n]) for n in keep_names] output = np.empty(base.shape, dtype=newdtype) output = recursive_fill_fields(base, output) return _fix_output(output, usemask=usemask, asrecarray=asrecarray) def _rec_drop_fields_dispatcher(base, drop_names): return (base,) @array_function_dispatch(_rec_drop_fields_dispatcher) def rec_drop_fields(base, drop_names): return drop_fields(base, drop_names, usemask=False, asrecarray=True) def _rename_fields_dispatcher(base, namemapper): return (base,) @array_function_dispatch(_rename_fields_dispatcher) def rename_fields(base, namemapper): def _recursive_rename_fields(ndtype, namemapper): newdtype = [] for name in ndtype.names: newname = namemapper.get(name, name) current = ndtype[name] if current.names is not None: newdtype.append((newname, _recursive_rename_fields(current, namemapper))) else: newdtype.append((newname, current)) return newdtype newdtype = _recursive_rename_fields(base.dtype, namemapper) return base.view(newdtype) def _append_fields_dispatcher(base, names, data, dtypes=None, fill_value=None, usemask=None, asrecarray=None): yield base yield from data @array_function_dispatch(_append_fields_dispatcher) def append_fields(base, names, data, dtypes=None, fill_value=-1, usemask=True, asrecarray=False): if isinstance(names, (tuple, list)): if len(names) != len(data): msg = 'The number of arrays does not match the number of names' raise ValueError(msg) elif isinstance(names, str): names = [names] data = [data] if dtypes is None: data = [np.array(a, copy=None, subok=True) for a in data] data = [a.view([(name, a.dtype)]) for (name, a) in zip(names, data)] else: if not isinstance(dtypes, (tuple, list)): dtypes = [dtypes] if len(data) != len(dtypes): if len(dtypes) == 1: dtypes = dtypes * len(data) else: msg = 'The dtypes argument must be None, a dtype, or a list.' raise ValueError(msg) data = [np.array(a, copy=None, subok=True, dtype=d).view([(n, d)]) for (a, n, d) in zip(data, names, dtypes)] base = merge_arrays(base, usemask=usemask, fill_value=fill_value) if len(data) > 1: data = merge_arrays(data, flatten=True, usemask=usemask, fill_value=fill_value) else: data = data.pop() output = ma.masked_all(max(len(base), len(data)), dtype=_get_fieldspec(base.dtype) + _get_fieldspec(data.dtype)) output = recursive_fill_fields(base, output) output = recursive_fill_fields(data, output) return _fix_output(output, usemask=usemask, asrecarray=asrecarray) def _rec_append_fields_dispatcher(base, names, data, dtypes=None): yield base yield from data @array_function_dispatch(_rec_append_fields_dispatcher) def rec_append_fields(base, names, data, dtypes=None): return append_fields(base, names, data=data, dtypes=dtypes, asrecarray=True, usemask=False) def _repack_fields_dispatcher(a, align=None, recurse=None): return (a,) @array_function_dispatch(_repack_fields_dispatcher) def repack_fields(a, align=False, recurse=False): if not isinstance(a, np.dtype): dt = repack_fields(a.dtype, align=align, recurse=recurse) return a.astype(dt, copy=False) if a.names is None: return a fieldinfo = [] for name in a.names: tup = a.fields[name] if recurse: fmt = repack_fields(tup[0], align=align, recurse=True) else: fmt = tup[0] if len(tup) == 3: name = (tup[2], name) fieldinfo.append((name, fmt)) dt = np.dtype(fieldinfo, align=align) return np.dtype((a.type, dt)) def _get_fields_and_offsets(dt, offset=0): def count_elem(dt): count = 1 while dt.shape != (): for size in dt.shape: count *= size dt = dt.base return (dt, count) fields = [] for name in dt.names: field = dt.fields[name] (f_dt, f_offset) = (field[0], field[1]) (f_dt, n) = count_elem(f_dt) if f_dt.names is None: fields.append((np.dtype((f_dt, (n,))), n, f_offset + offset)) else: subfields = _get_fields_and_offsets(f_dt, f_offset + offset) size = f_dt.itemsize for i in range(n): if i == 0: fields.extend(subfields) else: fields.extend([(d, c, o + i * size) for (d, c, o) in subfields]) return fields def _common_stride(offsets, counts, itemsize): if len(offsets) <= 1: return itemsize negative = offsets[1] < offsets[0] if negative: it = zip(reversed(offsets), reversed(counts)) else: it = zip(offsets, counts) prev_offset = None stride = None for (offset, count) in it: if count != 1: if negative: return None if stride is None: stride = itemsize if stride != itemsize: return None end_offset = offset + (count - 1) * itemsize else: end_offset = offset if prev_offset is not None: new_stride = offset - prev_offset if stride is None: stride = new_stride if stride != new_stride: return None prev_offset = end_offset if negative: return -stride return stride def _structured_to_unstructured_dispatcher(arr, dtype=None, copy=None, casting=None): return (arr,) @array_function_dispatch(_structured_to_unstructured_dispatcher) def structured_to_unstructured(arr, dtype=None, copy=False, casting='unsafe'): if arr.dtype.names is None: raise ValueError('arr must be a structured array') fields = _get_fields_and_offsets(arr.dtype) n_fields = len(fields) if n_fields == 0 and dtype is None: raise ValueError('arr has no fields. Unable to guess dtype') elif n_fields == 0: raise NotImplementedError('arr with no fields is not supported') (dts, counts, offsets) = zip(*fields) names = ['f{}'.format(n) for n in range(n_fields)] if dtype is None: out_dtype = np.result_type(*[dt.base for dt in dts]) else: out_dtype = np.dtype(dtype) flattened_fields = np.dtype({'names': names, 'formats': dts, 'offsets': offsets, 'itemsize': arr.dtype.itemsize}) arr = arr.view(flattened_fields) can_view = type(arr) in (np.ndarray, np.recarray, np.memmap) if not copy and can_view and all((dt.base == out_dtype for dt in dts)): common_stride = _common_stride(offsets, counts, out_dtype.itemsize) if common_stride is not None: wrap = arr.__array_wrap__ new_shape = arr.shape + (sum(counts), out_dtype.itemsize) new_strides = arr.strides + (abs(common_stride), 1) arr = arr[..., np.newaxis].view(np.uint8) arr = arr[..., min(offsets):] arr = np.lib.stride_tricks.as_strided(arr, new_shape, new_strides, subok=True) arr = arr.view(out_dtype)[..., 0] if common_stride < 0: arr = arr[..., ::-1] if type(arr) is not type(wrap.__self__): arr = wrap(arr) return arr packed_fields = np.dtype({'names': names, 'formats': [(out_dtype, dt.shape) for dt in dts]}) arr = arr.astype(packed_fields, copy=copy, casting=casting) return arr.view((out_dtype, (sum(counts),))) def _unstructured_to_structured_dispatcher(arr, dtype=None, names=None, align=None, copy=None, casting=None): return (arr,) @array_function_dispatch(_unstructured_to_structured_dispatcher) def unstructured_to_structured(arr, dtype=None, names=None, align=False, copy=False, casting='unsafe'): if arr.shape == (): raise ValueError('arr must have at least one dimension') n_elem = arr.shape[-1] if n_elem == 0: raise NotImplementedError('last axis with size 0 is not supported') if dtype is None: if names is None: names = ['f{}'.format(n) for n in range(n_elem)] out_dtype = np.dtype([(n, arr.dtype) for n in names], align=align) fields = _get_fields_and_offsets(out_dtype) (dts, counts, offsets) = zip(*fields) else: if names is not None: raise ValueError("don't supply both dtype and names") dtype = np.dtype(dtype) fields = _get_fields_and_offsets(dtype) if len(fields) == 0: (dts, counts, offsets) = ([], [], []) else: (dts, counts, offsets) = zip(*fields) if n_elem != sum(counts): raise ValueError('The length of the last dimension of arr must be equal to the number of fields in dtype') out_dtype = dtype if align and (not out_dtype.isalignedstruct): raise ValueError('align was True but dtype is not aligned') names = ['f{}'.format(n) for n in range(len(fields))] packed_fields = np.dtype({'names': names, 'formats': [(arr.dtype, dt.shape) for dt in dts]}) arr = np.ascontiguousarray(arr).view(packed_fields) flattened_fields = np.dtype({'names': names, 'formats': dts, 'offsets': offsets, 'itemsize': out_dtype.itemsize}) arr = arr.astype(flattened_fields, copy=copy, casting=casting) return arr.view(out_dtype)[..., 0] def _apply_along_fields_dispatcher(func, arr): return (arr,) @array_function_dispatch(_apply_along_fields_dispatcher) def apply_along_fields(func, arr): if arr.dtype.names is None: raise ValueError('arr must be a structured array') uarr = structured_to_unstructured(arr) return func(uarr, axis=-1) def _assign_fields_by_name_dispatcher(dst, src, zero_unassigned=None): return (dst, src) @array_function_dispatch(_assign_fields_by_name_dispatcher) def assign_fields_by_name(dst, src, zero_unassigned=True): if dst.dtype.names is None: dst[...] = src return for name in dst.dtype.names: if name not in src.dtype.names: if zero_unassigned: dst[name] = 0 else: assign_fields_by_name(dst[name], src[name], zero_unassigned) def _require_fields_dispatcher(array, required_dtype): return (array,) @array_function_dispatch(_require_fields_dispatcher) def require_fields(array, required_dtype): out = np.empty(array.shape, dtype=required_dtype) assign_fields_by_name(out, array) return out def _stack_arrays_dispatcher(arrays, defaults=None, usemask=None, asrecarray=None, autoconvert=None): return arrays @array_function_dispatch(_stack_arrays_dispatcher) def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False, autoconvert=False): if isinstance(arrays, ndarray): return arrays elif len(arrays) == 1: return arrays[0] seqarrays = [np.asanyarray(a).ravel() for a in arrays] nrecords = [len(a) for a in seqarrays] ndtype = [a.dtype for a in seqarrays] fldnames = [d.names for d in ndtype] dtype_l = ndtype[0] newdescr = _get_fieldspec(dtype_l) names = [n for (n, d) in newdescr] for dtype_n in ndtype[1:]: for (fname, fdtype) in _get_fieldspec(dtype_n): if fname not in names: newdescr.append((fname, fdtype)) names.append(fname) else: nameidx = names.index(fname) (_, cdtype) = newdescr[nameidx] if autoconvert: newdescr[nameidx] = (fname, max(fdtype, cdtype)) elif fdtype != cdtype: raise TypeError("Incompatible type '%s' <> '%s'" % (cdtype, fdtype)) if len(newdescr) == 1: output = ma.concatenate(seqarrays) else: output = ma.masked_all((np.sum(nrecords),), newdescr) offset = np.cumsum(np.r_[0, nrecords]) seen = [] for (a, n, i, j) in zip(seqarrays, fldnames, offset[:-1], offset[1:]): names = a.dtype.names if names is None: output['f%i' % len(seen)][i:j] = a else: for name in n: output[name][i:j] = a[name] if name not in seen: seen.append(name) return _fix_output(_fix_defaults(output, defaults), usemask=usemask, asrecarray=asrecarray) def _find_duplicates_dispatcher(a, key=None, ignoremask=None, return_index=None): return (a,) @array_function_dispatch(_find_duplicates_dispatcher) def find_duplicates(a, key=None, ignoremask=True, return_index=False): a = np.asanyarray(a).ravel() fields = get_fieldstructure(a.dtype) base = a if key: for f in fields[key]: base = base[f] base = base[key] sortidx = base.argsort() sortedbase = base[sortidx] sorteddata = sortedbase.filled() flag = sorteddata[:-1] == sorteddata[1:] if ignoremask: sortedmask = sortedbase.recordmask flag[sortedmask[1:]] = False flag = np.concatenate(([False], flag)) flag[:-1] = flag[:-1] + flag[1:] duplicates = a[sortidx][flag] if return_index: return (duplicates, sortidx[flag]) else: return duplicates def _join_by_dispatcher(key, r1, r2, jointype=None, r1postfix=None, r2postfix=None, defaults=None, usemask=None, asrecarray=None): return (r1, r2) @array_function_dispatch(_join_by_dispatcher) def join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None, usemask=True, asrecarray=False): if jointype not in ('inner', 'outer', 'leftouter'): raise ValueError("The 'jointype' argument should be in 'inner', 'outer' or 'leftouter' (got '%s' instead)" % jointype) if isinstance(key, str): key = (key,) if len(set(key)) != len(key): dup = next((x for (n, x) in enumerate(key) if x in key[n + 1:])) raise ValueError('duplicate join key %r' % dup) for name in key: if name not in r1.dtype.names: raise ValueError('r1 does not have key field %r' % name) if name not in r2.dtype.names: raise ValueError('r2 does not have key field %r' % name) r1 = r1.ravel() r2 = r2.ravel() nb1 = len(r1) (r1names, r2names) = (r1.dtype.names, r2.dtype.names) collisions = (set(r1names) & set(r2names)) - set(key) if collisions and (not (r1postfix or r2postfix)): msg = 'r1 and r2 contain common names, r1postfix and r2postfix ' msg += "can't both be empty" raise ValueError(msg) key1 = [n for n in r1names if n in key] r1k = _keep_fields(r1, key1) r2k = _keep_fields(r2, key1) aux = ma.concatenate((r1k, r2k)) idx_sort = aux.argsort(order=key) aux = aux[idx_sort] flag_in = ma.concatenate(([False], aux[1:] == aux[:-1])) flag_in[:-1] = flag_in[1:] + flag_in[:-1] idx_in = idx_sort[flag_in] idx_1 = idx_in[idx_in < nb1] idx_2 = idx_in[idx_in >= nb1] - nb1 (r1cmn, r2cmn) = (len(idx_1), len(idx_2)) if jointype == 'inner': (r1spc, r2spc) = (0, 0) elif jointype == 'outer': idx_out = idx_sort[~flag_in] idx_1 = np.concatenate((idx_1, idx_out[idx_out < nb1])) idx_2 = np.concatenate((idx_2, idx_out[idx_out >= nb1] - nb1)) (r1spc, r2spc) = (len(idx_1) - r1cmn, len(idx_2) - r2cmn) elif jointype == 'leftouter': idx_out = idx_sort[~flag_in] idx_1 = np.concatenate((idx_1, idx_out[idx_out < nb1])) (r1spc, r2spc) = (len(idx_1) - r1cmn, 0) (s1, s2) = (r1[idx_1], r2[idx_2]) ndtype = _get_fieldspec(r1k.dtype) for (fname, fdtype) in _get_fieldspec(r1.dtype): if fname not in key: ndtype.append((fname, fdtype)) for (fname, fdtype) in _get_fieldspec(r2.dtype): names = list((name for (name, dtype) in ndtype)) try: nameidx = names.index(fname) except ValueError: ndtype.append((fname, fdtype)) else: (_, cdtype) = ndtype[nameidx] if fname in key: ndtype[nameidx] = (fname, max(fdtype, cdtype)) else: ndtype[nameidx:nameidx + 1] = [(fname + r1postfix, cdtype), (fname + r2postfix, fdtype)] ndtype = np.dtype(ndtype) cmn = max(r1cmn, r2cmn) output = ma.masked_all((cmn + r1spc + r2spc,), dtype=ndtype) names = output.dtype.names for f in r1names: selected = s1[f] if f not in names or (f in r2names and (not r2postfix) and (f not in key)): f += r1postfix current = output[f] current[:r1cmn] = selected[:r1cmn] if jointype in ('outer', 'leftouter'): current[cmn:cmn + r1spc] = selected[r1cmn:] for f in r2names: selected = s2[f] if f not in names or (f in r1names and (not r1postfix) and (f not in key)): f += r2postfix current = output[f] current[:r2cmn] = selected[:r2cmn] if jointype == 'outer' and r2spc: current[-r2spc:] = selected[r2cmn:] output.sort(order=key) kwargs = dict(usemask=usemask, asrecarray=asrecarray) return _fix_output(_fix_defaults(output, defaults), **kwargs) def _rec_join_dispatcher(key, r1, r2, jointype=None, r1postfix=None, r2postfix=None, defaults=None): return (r1, r2) @array_function_dispatch(_rec_join_dispatcher) def rec_join(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None): kwargs = dict(jointype=jointype, r1postfix=r1postfix, r2postfix=r2postfix, defaults=defaults, usemask=False, asrecarray=True) return join_by(key, r1, r2, **kwargs) # File: numpy-main/numpy/linalg/__init__.py """""" from . import linalg from . import _linalg from ._linalg import * __all__ = _linalg.__all__.copy() from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester # File: numpy-main/numpy/linalg/_linalg.py """""" __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv', 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det', 'svd', 'svdvals', 'eig', 'eigh', 'lstsq', 'norm', 'qr', 'cond', 'matrix_rank', 'LinAlgError', 'multi_dot', 'trace', 'diagonal', 'cross', 'outer', 'tensordot', 'matmul', 'matrix_transpose', 'matrix_norm', 'vector_norm', 'vecdot'] import functools import operator import warnings from typing import NamedTuple, Any from numpy._utils import set_module from numpy._core import array, asarray, zeros, empty, empty_like, intc, single, double, csingle, cdouble, inexact, complexfloating, newaxis, all, inf, dot, add, multiply, sqrt, sum, isfinite, finfo, errstate, moveaxis, amin, amax, prod, abs, atleast_2d, intp, asanyarray, object_, swapaxes, divide, count_nonzero, isnan, sign, argsort, sort, reciprocal, overrides, diagonal as _core_diagonal, trace as _core_trace, cross as _core_cross, outer as _core_outer, tensordot as _core_tensordot, matmul as _core_matmul, matrix_transpose as _core_matrix_transpose, transpose as _core_transpose, vecdot as _core_vecdot from numpy._globals import _NoValue from numpy.lib._twodim_base_impl import triu, eye from numpy.lib.array_utils import normalize_axis_index, normalize_axis_tuple from numpy.linalg import _umath_linalg from numpy._typing import NDArray class EigResult(NamedTuple): eigenvalues: NDArray[Any] eigenvectors: NDArray[Any] class EighResult(NamedTuple): eigenvalues: NDArray[Any] eigenvectors: NDArray[Any] class QRResult(NamedTuple): Q: NDArray[Any] R: NDArray[Any] class SlogdetResult(NamedTuple): sign: NDArray[Any] logabsdet: NDArray[Any] class SVDResult(NamedTuple): U: NDArray[Any] S: NDArray[Any] Vh: NDArray[Any] array_function_dispatch = functools.partial(overrides.array_function_dispatch, module='numpy.linalg') fortran_int = intc @set_module('numpy.linalg') class LinAlgError(ValueError): def _raise_linalgerror_singular(err, flag): raise LinAlgError('Singular matrix') def _raise_linalgerror_nonposdef(err, flag): raise LinAlgError('Matrix is not positive definite') def _raise_linalgerror_eigenvalues_nonconvergence(err, flag): raise LinAlgError('Eigenvalues did not converge') def _raise_linalgerror_svd_nonconvergence(err, flag): raise LinAlgError('SVD did not converge') def _raise_linalgerror_lstsq(err, flag): raise LinAlgError('SVD did not converge in Linear Least Squares') def _raise_linalgerror_qr(err, flag): raise LinAlgError('Incorrect argument found while performing QR factorization') def _makearray(a): new = asarray(a) wrap = getattr(a, '__array_wrap__', new.__array_wrap__) return (new, wrap) def isComplexType(t): return issubclass(t, complexfloating) _real_types_map = {single: single, double: double, csingle: single, cdouble: double} _complex_types_map = {single: csingle, double: cdouble, csingle: csingle, cdouble: cdouble} def _realType(t, default=double): return _real_types_map.get(t, default) def _complexType(t, default=cdouble): return _complex_types_map.get(t, default) def _commonType(*arrays): result_type = single is_complex = False for a in arrays: type_ = a.dtype.type if issubclass(type_, inexact): if isComplexType(type_): is_complex = True rt = _realType(type_, default=None) if rt is double: result_type = double elif rt is None: raise TypeError('array type %s is unsupported in linalg' % (a.dtype.name,)) else: result_type = double if is_complex: result_type = _complex_types_map[result_type] return (cdouble, result_type) else: return (double, result_type) def _to_native_byte_order(*arrays): ret = [] for arr in arrays: if arr.dtype.byteorder not in ('=', '|'): ret.append(asarray(arr, dtype=arr.dtype.newbyteorder('='))) else: ret.append(arr) if len(ret) == 1: return ret[0] else: return ret def _assert_2d(*arrays): for a in arrays: if a.ndim != 2: raise LinAlgError('%d-dimensional array given. Array must be two-dimensional' % a.ndim) def _assert_stacked_2d(*arrays): for a in arrays: if a.ndim < 2: raise LinAlgError('%d-dimensional array given. Array must be at least two-dimensional' % a.ndim) def _assert_stacked_square(*arrays): for a in arrays: (m, n) = a.shape[-2:] if m != n: raise LinAlgError('Last 2 dimensions of the array must be square') def _assert_finite(*arrays): for a in arrays: if not isfinite(a).all(): raise LinAlgError('Array must not contain infs or NaNs') def _is_empty_2d(arr): return arr.size == 0 and prod(arr.shape[-2:]) == 0 def transpose(a): return swapaxes(a, -1, -2) def _tensorsolve_dispatcher(a, b, axes=None): return (a, b) @array_function_dispatch(_tensorsolve_dispatcher) def tensorsolve(a, b, axes=None): (a, wrap) = _makearray(a) b = asarray(b) an = a.ndim if axes is not None: allaxes = list(range(0, an)) for k in axes: allaxes.remove(k) allaxes.insert(an, k) a = a.transpose(allaxes) oldshape = a.shape[-(an - b.ndim):] prod = 1 for k in oldshape: prod *= k if a.size != prod ** 2: raise LinAlgError('Input arrays must satisfy the requirement prod(a.shape[b.ndim:]) == prod(a.shape[:b.ndim])') a = a.reshape(prod, prod) b = b.ravel() res = wrap(solve(a, b)) res.shape = oldshape return res def _solve_dispatcher(a, b): return (a, b) @array_function_dispatch(_solve_dispatcher) def solve(a, b): (a, _) = _makearray(a) _assert_stacked_2d(a) _assert_stacked_square(a) (b, wrap) = _makearray(b) (t, result_t) = _commonType(a, b) if b.ndim == 1: gufunc = _umath_linalg.solve1 else: gufunc = _umath_linalg.solve signature = 'DD->D' if isComplexType(t) else 'dd->d' with errstate(call=_raise_linalgerror_singular, invalid='call', over='ignore', divide='ignore', under='ignore'): r = gufunc(a, b, signature=signature) return wrap(r.astype(result_t, copy=False)) def _tensorinv_dispatcher(a, ind=None): return (a,) @array_function_dispatch(_tensorinv_dispatcher) def tensorinv(a, ind=2): a = asarray(a) oldshape = a.shape prod = 1 if ind > 0: invshape = oldshape[ind:] + oldshape[:ind] for k in oldshape[ind:]: prod *= k else: raise ValueError('Invalid ind argument.') a = a.reshape(prod, -1) ia = inv(a) return ia.reshape(*invshape) def _unary_dispatcher(a): return (a,) @array_function_dispatch(_unary_dispatcher) def inv(a): (a, wrap) = _makearray(a) _assert_stacked_2d(a) _assert_stacked_square(a) (t, result_t) = _commonType(a) signature = 'D->D' if isComplexType(t) else 'd->d' with errstate(call=_raise_linalgerror_singular, invalid='call', over='ignore', divide='ignore', under='ignore'): ainv = _umath_linalg.inv(a, signature=signature) return wrap(ainv.astype(result_t, copy=False)) def _matrix_power_dispatcher(a, n): return (a,) @array_function_dispatch(_matrix_power_dispatcher) def matrix_power(a, n): a = asanyarray(a) _assert_stacked_2d(a) _assert_stacked_square(a) try: n = operator.index(n) except TypeError as e: raise TypeError('exponent must be an integer') from e if a.dtype != object: fmatmul = matmul elif a.ndim == 2: fmatmul = dot else: raise NotImplementedError('matrix_power not supported for stacks of object arrays') if n == 0: a = empty_like(a) a[...] = eye(a.shape[-2], dtype=a.dtype) return a elif n < 0: a = inv(a) n = abs(n) if n == 1: return a elif n == 2: return fmatmul(a, a) elif n == 3: return fmatmul(fmatmul(a, a), a) z = result = None while n > 0: z = a if z is None else fmatmul(z, z) (n, bit) = divmod(n, 2) if bit: result = z if result is None else fmatmul(result, z) return result def _cholesky_dispatcher(a, /, *, upper=None): return (a,) @array_function_dispatch(_cholesky_dispatcher) def cholesky(a, /, *, upper=False): gufunc = _umath_linalg.cholesky_up if upper else _umath_linalg.cholesky_lo (a, wrap) = _makearray(a) _assert_stacked_2d(a) _assert_stacked_square(a) (t, result_t) = _commonType(a) signature = 'D->D' if isComplexType(t) else 'd->d' with errstate(call=_raise_linalgerror_nonposdef, invalid='call', over='ignore', divide='ignore', under='ignore'): r = gufunc(a, signature=signature) return wrap(r.astype(result_t, copy=False)) def _outer_dispatcher(x1, x2): return (x1, x2) @array_function_dispatch(_outer_dispatcher) def outer(x1, x2, /): x1 = asanyarray(x1) x2 = asanyarray(x2) if x1.ndim != 1 or x2.ndim != 1: raise ValueError(f'Input arrays must be one-dimensional, but they are x1.ndim={x1.ndim!r} and x2.ndim={x2.ndim!r}.') return _core_outer(x1, x2, out=None) def _qr_dispatcher(a, mode=None): return (a,) @array_function_dispatch(_qr_dispatcher) def qr(a, mode='reduced'): if mode not in ('reduced', 'complete', 'r', 'raw'): if mode in ('f', 'full'): msg = "The 'full' option is deprecated in favor of 'reduced'.\nFor backward compatibility let mode default." warnings.warn(msg, DeprecationWarning, stacklevel=2) mode = 'reduced' elif mode in ('e', 'economic'): msg = "The 'economic' option is deprecated." warnings.warn(msg, DeprecationWarning, stacklevel=2) mode = 'economic' else: raise ValueError(f"Unrecognized mode '{mode}'") (a, wrap) = _makearray(a) _assert_stacked_2d(a) (m, n) = a.shape[-2:] (t, result_t) = _commonType(a) a = a.astype(t, copy=True) a = _to_native_byte_order(a) mn = min(m, n) signature = 'D->D' if isComplexType(t) else 'd->d' with errstate(call=_raise_linalgerror_qr, invalid='call', over='ignore', divide='ignore', under='ignore'): tau = _umath_linalg.qr_r_raw(a, signature=signature) if mode == 'r': r = triu(a[..., :mn, :]) r = r.astype(result_t, copy=False) return wrap(r) if mode == 'raw': q = transpose(a) q = q.astype(result_t, copy=False) tau = tau.astype(result_t, copy=False) return (wrap(q), tau) if mode == 'economic': a = a.astype(result_t, copy=False) return wrap(a) if mode == 'complete' and m > n: mc = m gufunc = _umath_linalg.qr_complete else: mc = mn gufunc = _umath_linalg.qr_reduced signature = 'DD->D' if isComplexType(t) else 'dd->d' with errstate(call=_raise_linalgerror_qr, invalid='call', over='ignore', divide='ignore', under='ignore'): q = gufunc(a, tau, signature=signature) r = triu(a[..., :mc, :]) q = q.astype(result_t, copy=False) r = r.astype(result_t, copy=False) return QRResult(wrap(q), wrap(r)) @array_function_dispatch(_unary_dispatcher) def eigvals(a): (a, wrap) = _makearray(a) _assert_stacked_2d(a) _assert_stacked_square(a) _assert_finite(a) (t, result_t) = _commonType(a) signature = 'D->D' if isComplexType(t) else 'd->D' with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence, invalid='call', over='ignore', divide='ignore', under='ignore'): w = _umath_linalg.eigvals(a, signature=signature) if not isComplexType(t): if all(w.imag == 0): w = w.real result_t = _realType(result_t) else: result_t = _complexType(result_t) return w.astype(result_t, copy=False) def _eigvalsh_dispatcher(a, UPLO=None): return (a,) @array_function_dispatch(_eigvalsh_dispatcher) def eigvalsh(a, UPLO='L'): UPLO = UPLO.upper() if UPLO not in ('L', 'U'): raise ValueError("UPLO argument must be 'L' or 'U'") if UPLO == 'L': gufunc = _umath_linalg.eigvalsh_lo else: gufunc = _umath_linalg.eigvalsh_up (a, wrap) = _makearray(a) _assert_stacked_2d(a) _assert_stacked_square(a) (t, result_t) = _commonType(a) signature = 'D->d' if isComplexType(t) else 'd->d' with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence, invalid='call', over='ignore', divide='ignore', under='ignore'): w = gufunc(a, signature=signature) return w.astype(_realType(result_t), copy=False) def _convertarray(a): (t, result_t) = _commonType(a) a = a.astype(t).T.copy() return (a, t, result_t) @array_function_dispatch(_unary_dispatcher) def eig(a): (a, wrap) = _makearray(a) _assert_stacked_2d(a) _assert_stacked_square(a) _assert_finite(a) (t, result_t) = _commonType(a) signature = 'D->DD' if isComplexType(t) else 'd->DD' with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence, invalid='call', over='ignore', divide='ignore', under='ignore'): (w, vt) = _umath_linalg.eig(a, signature=signature) if not isComplexType(t) and all(w.imag == 0.0): w = w.real vt = vt.real result_t = _realType(result_t) else: result_t = _complexType(result_t) vt = vt.astype(result_t, copy=False) return EigResult(w.astype(result_t, copy=False), wrap(vt)) @array_function_dispatch(_eigvalsh_dispatcher) def eigh(a, UPLO='L'): UPLO = UPLO.upper() if UPLO not in ('L', 'U'): raise ValueError("UPLO argument must be 'L' or 'U'") (a, wrap) = _makearray(a) _assert_stacked_2d(a) _assert_stacked_square(a) (t, result_t) = _commonType(a) if UPLO == 'L': gufunc = _umath_linalg.eigh_lo else: gufunc = _umath_linalg.eigh_up signature = 'D->dD' if isComplexType(t) else 'd->dd' with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence, invalid='call', over='ignore', divide='ignore', under='ignore'): (w, vt) = gufunc(a, signature=signature) w = w.astype(_realType(result_t), copy=False) vt = vt.astype(result_t, copy=False) return EighResult(w, wrap(vt)) def _svd_dispatcher(a, full_matrices=None, compute_uv=None, hermitian=None): return (a,) @array_function_dispatch(_svd_dispatcher) def svd(a, full_matrices=True, compute_uv=True, hermitian=False): import numpy as _nx (a, wrap) = _makearray(a) if hermitian: if compute_uv: (s, u) = eigh(a) sgn = sign(s) s = abs(s) sidx = argsort(s)[..., ::-1] sgn = _nx.take_along_axis(sgn, sidx, axis=-1) s = _nx.take_along_axis(s, sidx, axis=-1) u = _nx.take_along_axis(u, sidx[..., None, :], axis=-1) vt = transpose(u * sgn[..., None, :]).conjugate() return SVDResult(wrap(u), s, wrap(vt)) else: s = eigvalsh(a) s = abs(s) return sort(s)[..., ::-1] _assert_stacked_2d(a) (t, result_t) = _commonType(a) (m, n) = a.shape[-2:] if compute_uv: if full_matrices: gufunc = _umath_linalg.svd_f else: gufunc = _umath_linalg.svd_s signature = 'D->DdD' if isComplexType(t) else 'd->ddd' with errstate(call=_raise_linalgerror_svd_nonconvergence, invalid='call', over='ignore', divide='ignore', under='ignore'): (u, s, vh) = gufunc(a, signature=signature) u = u.astype(result_t, copy=False) s = s.astype(_realType(result_t), copy=False) vh = vh.astype(result_t, copy=False) return SVDResult(wrap(u), s, wrap(vh)) else: signature = 'D->d' if isComplexType(t) else 'd->d' with errstate(call=_raise_linalgerror_svd_nonconvergence, invalid='call', over='ignore', divide='ignore', under='ignore'): s = _umath_linalg.svd(a, signature=signature) s = s.astype(_realType(result_t), copy=False) return s def _svdvals_dispatcher(x): return (x,) @array_function_dispatch(_svdvals_dispatcher) def svdvals(x, /): return svd(x, compute_uv=False, hermitian=False) def _cond_dispatcher(x, p=None): return (x,) @array_function_dispatch(_cond_dispatcher) def cond(x, p=None): x = asarray(x) if _is_empty_2d(x): raise LinAlgError('cond is not defined on empty arrays') if p is None or p == 2 or p == -2: s = svd(x, compute_uv=False) with errstate(all='ignore'): if p == -2: r = s[..., -1] / s[..., 0] else: r = s[..., 0] / s[..., -1] else: _assert_stacked_2d(x) _assert_stacked_square(x) (t, result_t) = _commonType(x) signature = 'D->D' if isComplexType(t) else 'd->d' with errstate(all='ignore'): invx = _umath_linalg.inv(x, signature=signature) r = norm(x, p, axis=(-2, -1)) * norm(invx, p, axis=(-2, -1)) r = r.astype(result_t, copy=False) r = asarray(r) nan_mask = isnan(r) if nan_mask.any(): nan_mask &= ~isnan(x).any(axis=(-2, -1)) if r.ndim > 0: r[nan_mask] = inf elif nan_mask: r[()] = inf if r.ndim == 0: r = r[()] return r def _matrix_rank_dispatcher(A, tol=None, hermitian=None, *, rtol=None): return (A,) @array_function_dispatch(_matrix_rank_dispatcher) def matrix_rank(A, tol=None, hermitian=False, *, rtol=None): if rtol is not None and tol is not None: raise ValueError("`tol` and `rtol` can't be both set.") A = asarray(A) if A.ndim < 2: return int(not all(A == 0)) S = svd(A, compute_uv=False, hermitian=hermitian) if tol is None: if rtol is None: rtol = max(A.shape[-2:]) * finfo(S.dtype).eps else: rtol = asarray(rtol)[..., newaxis] tol = S.max(axis=-1, keepdims=True) * rtol else: tol = asarray(tol)[..., newaxis] return count_nonzero(S > tol, axis=-1) def _pinv_dispatcher(a, rcond=None, hermitian=None, *, rtol=None): return (a,) @array_function_dispatch(_pinv_dispatcher) def pinv(a, rcond=None, hermitian=False, *, rtol=_NoValue): (a, wrap) = _makearray(a) if rcond is None: if rtol is _NoValue: rcond = 1e-15 elif rtol is None: rcond = max(a.shape[-2:]) * finfo(a.dtype).eps else: rcond = rtol elif rtol is not _NoValue: raise ValueError("`rtol` and `rcond` can't be both set.") else: pass rcond = asarray(rcond) if _is_empty_2d(a): (m, n) = a.shape[-2:] res = empty(a.shape[:-2] + (n, m), dtype=a.dtype) return wrap(res) a = a.conjugate() (u, s, vt) = svd(a, full_matrices=False, hermitian=hermitian) cutoff = rcond[..., newaxis] * amax(s, axis=-1, keepdims=True) large = s > cutoff s = divide(1, s, where=large, out=s) s[~large] = 0 res = matmul(transpose(vt), multiply(s[..., newaxis], transpose(u))) return wrap(res) @array_function_dispatch(_unary_dispatcher) def slogdet(a): a = asarray(a) _assert_stacked_2d(a) _assert_stacked_square(a) (t, result_t) = _commonType(a) real_t = _realType(result_t) signature = 'D->Dd' if isComplexType(t) else 'd->dd' (sign, logdet) = _umath_linalg.slogdet(a, signature=signature) sign = sign.astype(result_t, copy=False) logdet = logdet.astype(real_t, copy=False) return SlogdetResult(sign, logdet) @array_function_dispatch(_unary_dispatcher) def det(a): a = asarray(a) _assert_stacked_2d(a) _assert_stacked_square(a) (t, result_t) = _commonType(a) signature = 'D->D' if isComplexType(t) else 'd->d' r = _umath_linalg.det(a, signature=signature) r = r.astype(result_t, copy=False) return r def _lstsq_dispatcher(a, b, rcond=None): return (a, b) @array_function_dispatch(_lstsq_dispatcher) def lstsq(a, b, rcond=None): (a, _) = _makearray(a) (b, wrap) = _makearray(b) is_1d = b.ndim == 1 if is_1d: b = b[:, newaxis] _assert_2d(a, b) (m, n) = a.shape[-2:] (m2, n_rhs) = b.shape[-2:] if m != m2: raise LinAlgError('Incompatible dimensions') (t, result_t) = _commonType(a, b) result_real_t = _realType(result_t) if rcond is None: rcond = finfo(t).eps * max(n, m) signature = 'DDd->Ddid' if isComplexType(t) else 'ddd->ddid' if n_rhs == 0: b = zeros(b.shape[:-2] + (m, n_rhs + 1), dtype=b.dtype) with errstate(call=_raise_linalgerror_lstsq, invalid='call', over='ignore', divide='ignore', under='ignore'): (x, resids, rank, s) = _umath_linalg.lstsq(a, b, rcond, signature=signature) if m == 0: x[...] = 0 if n_rhs == 0: x = x[..., :n_rhs] resids = resids[..., :n_rhs] if is_1d: x = x.squeeze(axis=-1) if rank != n or m <= n: resids = array([], result_real_t) s = s.astype(result_real_t, copy=False) resids = resids.astype(result_real_t, copy=False) x = x.astype(result_t, copy=True) return (wrap(x), wrap(resids), rank, s) def _multi_svd_norm(x, row_axis, col_axis, op): y = moveaxis(x, (row_axis, col_axis), (-2, -1)) result = op(svd(y, compute_uv=False), axis=-1) return result def _norm_dispatcher(x, ord=None, axis=None, keepdims=None): return (x,) @array_function_dispatch(_norm_dispatcher) def norm(x, ord=None, axis=None, keepdims=False): x = asarray(x) if not issubclass(x.dtype.type, (inexact, object_)): x = x.astype(float) if axis is None: ndim = x.ndim if ord is None or (ord in ('f', 'fro') and ndim == 2) or (ord == 2 and ndim == 1): x = x.ravel(order='K') if isComplexType(x.dtype.type): x_real = x.real x_imag = x.imag sqnorm = x_real.dot(x_real) + x_imag.dot(x_imag) else: sqnorm = x.dot(x) ret = sqrt(sqnorm) if keepdims: ret = ret.reshape(ndim * [1]) return ret nd = x.ndim if axis is None: axis = tuple(range(nd)) elif not isinstance(axis, tuple): try: axis = int(axis) except Exception as e: raise TypeError("'axis' must be None, an integer or a tuple of integers") from e axis = (axis,) if len(axis) == 1: if ord == inf: return abs(x).max(axis=axis, keepdims=keepdims) elif ord == -inf: return abs(x).min(axis=axis, keepdims=keepdims) elif ord == 0: return (x != 0).astype(x.real.dtype).sum(axis=axis, keepdims=keepdims) elif ord == 1: return add.reduce(abs(x), axis=axis, keepdims=keepdims) elif ord is None or ord == 2: s = (x.conj() * x).real return sqrt(add.reduce(s, axis=axis, keepdims=keepdims)) elif isinstance(ord, str): raise ValueError(f"Invalid norm order '{ord}' for vectors") else: absx = abs(x) absx **= ord ret = add.reduce(absx, axis=axis, keepdims=keepdims) ret **= reciprocal(ord, dtype=ret.dtype) return ret elif len(axis) == 2: (row_axis, col_axis) = axis row_axis = normalize_axis_index(row_axis, nd) col_axis = normalize_axis_index(col_axis, nd) if row_axis == col_axis: raise ValueError('Duplicate axes given.') if ord == 2: ret = _multi_svd_norm(x, row_axis, col_axis, amax) elif ord == -2: ret = _multi_svd_norm(x, row_axis, col_axis, amin) elif ord == 1: if col_axis > row_axis: col_axis -= 1 ret = add.reduce(abs(x), axis=row_axis).max(axis=col_axis) elif ord == inf: if row_axis > col_axis: row_axis -= 1 ret = add.reduce(abs(x), axis=col_axis).max(axis=row_axis) elif ord == -1: if col_axis > row_axis: col_axis -= 1 ret = add.reduce(abs(x), axis=row_axis).min(axis=col_axis) elif ord == -inf: if row_axis > col_axis: row_axis -= 1 ret = add.reduce(abs(x), axis=col_axis).min(axis=row_axis) elif ord in [None, 'fro', 'f']: ret = sqrt(add.reduce((x.conj() * x).real, axis=axis)) elif ord == 'nuc': ret = _multi_svd_norm(x, row_axis, col_axis, sum) else: raise ValueError('Invalid norm order for matrices.') if keepdims: ret_shape = list(x.shape) ret_shape[axis[0]] = 1 ret_shape[axis[1]] = 1 ret = ret.reshape(ret_shape) return ret else: raise ValueError('Improper number of dimensions to norm.') def _multidot_dispatcher(arrays, *, out=None): yield from arrays yield out @array_function_dispatch(_multidot_dispatcher) def multi_dot(arrays, *, out=None): n = len(arrays) if n < 2: raise ValueError('Expecting at least two arrays.') elif n == 2: return dot(arrays[0], arrays[1], out=out) arrays = [asanyarray(a) for a in arrays] (ndim_first, ndim_last) = (arrays[0].ndim, arrays[-1].ndim) if arrays[0].ndim == 1: arrays[0] = atleast_2d(arrays[0]) if arrays[-1].ndim == 1: arrays[-1] = atleast_2d(arrays[-1]).T _assert_2d(*arrays) if n == 3: result = _multi_dot_three(arrays[0], arrays[1], arrays[2], out=out) else: order = _multi_dot_matrix_chain_order(arrays) result = _multi_dot(arrays, order, 0, n - 1, out=out) if ndim_first == 1 and ndim_last == 1: return result[0, 0] elif ndim_first == 1 or ndim_last == 1: return result.ravel() else: return result def _multi_dot_three(A, B, C, out=None): (a0, a1b0) = A.shape (b1c0, c1) = C.shape cost1 = a0 * b1c0 * (a1b0 + c1) cost2 = a1b0 * c1 * (a0 + b1c0) if cost1 < cost2: return dot(dot(A, B), C, out=out) else: return dot(A, dot(B, C), out=out) def _multi_dot_matrix_chain_order(arrays, return_costs=False): n = len(arrays) p = [a.shape[0] for a in arrays] + [arrays[-1].shape[1]] m = zeros((n, n), dtype=double) s = empty((n, n), dtype=intp) for l in range(1, n): for i in range(n - l): j = i + l m[i, j] = inf for k in range(i, j): q = m[i, k] + m[k + 1, j] + p[i] * p[k + 1] * p[j + 1] if q < m[i, j]: m[i, j] = q s[i, j] = k return (s, m) if return_costs else s def _multi_dot(arrays, order, i, j, out=None): if i == j: assert out is None return arrays[i] else: return dot(_multi_dot(arrays, order, i, order[i, j]), _multi_dot(arrays, order, order[i, j] + 1, j), out=out) def _diagonal_dispatcher(x, /, *, offset=None): return (x,) @array_function_dispatch(_diagonal_dispatcher) def diagonal(x, /, *, offset=0): return _core_diagonal(x, offset, axis1=-2, axis2=-1) def _trace_dispatcher(x, /, *, offset=None, dtype=None): return (x,) @array_function_dispatch(_trace_dispatcher) def trace(x, /, *, offset=0, dtype=None): return _core_trace(x, offset, axis1=-2, axis2=-1, dtype=dtype) def _cross_dispatcher(x1, x2, /, *, axis=None): return (x1, x2) @array_function_dispatch(_cross_dispatcher) def cross(x1, x2, /, *, axis=-1): x1 = asanyarray(x1) x2 = asanyarray(x2) if x1.shape[axis] != 3 or x2.shape[axis] != 3: raise ValueError(f'Both input arrays must be (arrays of) 3-dimensional vectors, but they are {x1.shape[axis]} and {x2.shape[axis]} dimensional instead.') return _core_cross(x1, x2, axis=axis) def _matmul_dispatcher(x1, x2, /): return (x1, x2) @array_function_dispatch(_matmul_dispatcher) def matmul(x1, x2, /): return _core_matmul(x1, x2) def _tensordot_dispatcher(x1, x2, /, *, axes=None): return (x1, x2) @array_function_dispatch(_tensordot_dispatcher) def tensordot(x1, x2, /, *, axes=2): return _core_tensordot(x1, x2, axes=axes) tensordot.__doc__ = _core_tensordot.__doc__ def _matrix_transpose_dispatcher(x): return (x,) @array_function_dispatch(_matrix_transpose_dispatcher) def matrix_transpose(x, /): return _core_matrix_transpose(x) matrix_transpose.__doc__ = _core_matrix_transpose.__doc__ def _matrix_norm_dispatcher(x, /, *, keepdims=None, ord=None): return (x,) @array_function_dispatch(_matrix_norm_dispatcher) def matrix_norm(x, /, *, keepdims=False, ord='fro'): x = asanyarray(x) return norm(x, axis=(-2, -1), keepdims=keepdims, ord=ord) def _vector_norm_dispatcher(x, /, *, axis=None, keepdims=None, ord=None): return (x,) @array_function_dispatch(_vector_norm_dispatcher) def vector_norm(x, /, *, axis=None, keepdims=False, ord=2): x = asanyarray(x) shape = list(x.shape) if axis is None: x = x.ravel() _axis = 0 elif isinstance(axis, tuple): normalized_axis = normalize_axis_tuple(axis, x.ndim) rest = tuple((i for i in range(x.ndim) if i not in normalized_axis)) newshape = axis + rest x = _core_transpose(x, newshape).reshape((prod([x.shape[i] for i in axis], dtype=int), *[x.shape[i] for i in rest])) _axis = 0 else: _axis = axis res = norm(x, axis=_axis, ord=ord) if keepdims: _axis = normalize_axis_tuple(range(len(shape)) if axis is None else axis, len(shape)) for i in _axis: shape[i] = 1 res = res.reshape(tuple(shape)) return res def _vecdot_dispatcher(x1, x2, /, *, axis=None): return (x1, x2) @array_function_dispatch(_vecdot_dispatcher) def vecdot(x1, x2, /, *, axis=-1): return _core_vecdot(x1, x2, axis=axis) # File: numpy-main/numpy/linalg/lapack_lite/clapack_scrub.py import os import re import sys from plex import Scanner, Str, Lexicon, Opt, Bol, State, AnyChar, TEXT, IGNORE from plex.traditional import re as Re try: from io import BytesIO as UStringIO except ImportError: from io import StringIO as UStringIO class MyScanner(Scanner): def __init__(self, info, name=''): Scanner.__init__(self, self.lexicon, info, name) def begin(self, state_name): Scanner.begin(self, state_name) def sep_seq(sequence, sep): pat = Str(sequence[0]) for s in sequence[1:]: pat += sep + Str(s) return pat def runScanner(data, scanner_class, lexicon=None): info = UStringIO(data) outfo = UStringIO() if lexicon is not None: scanner = scanner_class(lexicon, info) else: scanner = scanner_class(info) while True: (value, text) = scanner.read() if value is None: break elif value is IGNORE: pass else: outfo.write(value) return (outfo.getvalue(), scanner) class LenSubsScanner(MyScanner): def __init__(self, info, name=''): MyScanner.__init__(self, info, name) self.paren_count = 0 def beginArgs(self, text): if self.paren_count == 0: self.begin('args') self.paren_count += 1 return text def endArgs(self, text): self.paren_count -= 1 if self.paren_count == 0: self.begin('') return text digits = Re('[0-9]+') iofun = Re('\\([^;]*;') decl = Re('\\([^)]*\\)[,;' + '\n]') any = Re('[.]*') S = Re('[ \t\n]*') cS = Str(',') + S len_ = Re('[a-z][a-z0-9]*_len') iofunctions = Str('s_cat', 's_copy', 's_stop', 's_cmp', 'i_len', 'do_fio', 'do_lio') + iofun keep_ftnlen = (Str('ilaenv_') | Str('iparmq_') | Str('s_rnge')) + Str('(') lexicon = Lexicon([(iofunctions, TEXT), (keep_ftnlen, beginArgs), State('args', [(Str(')'), endArgs), (Str('('), beginArgs), (AnyChar, TEXT)]), (cS + Re('[1-9][0-9]*L'), IGNORE), (cS + Str('ftnlen') + Opt(S + len_), IGNORE), (cS + sep_seq(['(', 'ftnlen', ')'], S) + S + digits, IGNORE), (Bol + Str('ftnlen ') + len_ + Str(';\n'), IGNORE), (cS + len_, TEXT), (AnyChar, TEXT)]) def scrubFtnlen(source): return runScanner(source, LenSubsScanner)[0] def cleanSource(source): source = re.sub('[\\t ]+\\n', '\n', source) source = re.sub('(?m)^[\\t ]*/\\* *\\.\\. .*?\\n', '', source) source = re.sub('\\n\\n\\n\\n+', '\\n\\n\\n', source) return source class LineQueue: def __init__(self): object.__init__(self) self._queue = [] def add(self, line): self._queue.append(line) def clear(self): self._queue = [] def flushTo(self, other_queue): for line in self._queue: other_queue.add(line) self.clear() def getValue(self): q = LineQueue() self.flushTo(q) s = ''.join(q._queue) self.clear() return s class CommentQueue(LineQueue): def __init__(self): LineQueue.__init__(self) def add(self, line): if line.strip() == '': LineQueue.add(self, '\n') else: line = ' ' + line[2:-3].rstrip() + '\n' LineQueue.add(self, line) def flushTo(self, other_queue): if len(self._queue) == 0: pass elif len(self._queue) == 1: other_queue.add('/*' + self._queue[0][2:].rstrip() + ' */\n') else: other_queue.add('/*\n') LineQueue.flushTo(self, other_queue) other_queue.add('*/\n') self.clear() def cleanComments(source): lines = LineQueue() comments = CommentQueue() def isCommentLine(line): return line.startswith('/*') and line.endswith('*/\n') blanks = LineQueue() def isBlank(line): return line.strip() == '' def SourceLines(line): if isCommentLine(line): comments.add(line) return HaveCommentLines else: lines.add(line) return SourceLines def HaveCommentLines(line): if isBlank(line): blanks.add('\n') return HaveBlankLines elif isCommentLine(line): comments.add(line) return HaveCommentLines else: comments.flushTo(lines) lines.add(line) return SourceLines def HaveBlankLines(line): if isBlank(line): blanks.add('\n') return HaveBlankLines elif isCommentLine(line): blanks.flushTo(comments) comments.add(line) return HaveCommentLines else: comments.flushTo(lines) blanks.flushTo(lines) lines.add(line) return SourceLines state = SourceLines for line in UStringIO(source): state = state(line) comments.flushTo(lines) return lines.getValue() def removeHeader(source): lines = LineQueue() def LookingForHeader(line): m = re.match('/\\*[^\\n]*-- translated', line) if m: return InHeader else: lines.add(line) return LookingForHeader def InHeader(line): if line.startswith('*/'): return OutOfHeader else: return InHeader def OutOfHeader(line): if line.startswith('#include "f2c.h"'): pass else: lines.add(line) return OutOfHeader state = LookingForHeader for line in UStringIO(source): state = state(line) return lines.getValue() def removeSubroutinePrototypes(source): return source def removeBuiltinFunctions(source): lines = LineQueue() def LookingForBuiltinFunctions(line): if line.strip() == '/* Builtin functions */': return InBuiltInFunctions else: lines.add(line) return LookingForBuiltinFunctions def InBuiltInFunctions(line): if line.strip() == '': return LookingForBuiltinFunctions else: return InBuiltInFunctions state = LookingForBuiltinFunctions for line in UStringIO(source): state = state(line) return lines.getValue() def replaceDlamch(source): def repl(m): s = m.group(1) return dict(E='EPSILON', P='PRECISION', S='SAFEMINIMUM', B='BASE')[s[0]] source = re.sub('dlamch_\\("(.*?)"\\)', repl, source) source = re.sub('^\\s+extern.*? dlamch_.*?;$(?m)', '', source) return source def scrubSource(source, nsteps=None, verbose=False): steps = [('scrubbing ftnlen', scrubFtnlen), ('remove header', removeHeader), ('clean source', cleanSource), ('clean comments', cleanComments), ('replace dlamch_() calls', replaceDlamch), ('remove prototypes', removeSubroutinePrototypes), ('remove builtin function prototypes', removeBuiltinFunctions)] if nsteps is not None: steps = steps[:nsteps] for (msg, step) in steps: if verbose: print(msg) source = step(source) return source if __name__ == '__main__': filename = sys.argv[1] outfilename = os.path.join(sys.argv[2], os.path.basename(filename)) with open(filename) as fo: source = fo.read() if len(sys.argv) > 3: nsteps = int(sys.argv[3]) else: nsteps = None source = scrubSource(source, nsteps, verbose=True) with open(outfilename, 'w') as writefo: writefo.write(source) # File: numpy-main/numpy/linalg/lapack_lite/fortran.py import re import itertools def isBlank(line): return not line def isLabel(line): return line[0].isdigit() def isComment(line): return line[0] != ' ' def isContinuation(line): return line[5] != ' ' (COMMENT, STATEMENT, CONTINUATION) = (0, 1, 2) def lineType(line): if isBlank(line): return COMMENT elif isLabel(line): return STATEMENT elif isComment(line): return COMMENT elif isContinuation(line): return CONTINUATION else: return STATEMENT class LineIterator: def __init__(self, iterable): object.__init__(self) self.iterable = iter(iterable) self.lineno = 0 def __iter__(self): return self def __next__(self): self.lineno += 1 line = next(self.iterable) line = line.rstrip() return line next = __next__ class PushbackIterator: def __init__(self, iterable): object.__init__(self) self.iterable = iter(iterable) self.buffer = [] def __iter__(self): return self def __next__(self): if self.buffer: return self.buffer.pop() else: return next(self.iterable) def pushback(self, item): self.buffer.append(item) next = __next__ def fortranSourceLines(fo): numberingiter = LineIterator(fo) with_extra = itertools.chain(numberingiter, ['']) pushbackiter = PushbackIterator(with_extra) for line in pushbackiter: t = lineType(line) if t == COMMENT: continue elif t == STATEMENT: lines = [line] for next_line in pushbackiter: t = lineType(next_line) if t == CONTINUATION: lines.append(next_line[6:]) else: pushbackiter.pushback(next_line) break yield (numberingiter.lineno, ''.join(lines)) else: raise ValueError('jammed: continuation line not expected: %s:%d' % (fo.name, numberingiter.lineno)) def getDependencies(filename): external_pat = re.compile('^\\s*EXTERNAL\\s', re.I) routines = [] with open(filename) as fo: for (lineno, line) in fortranSourceLines(fo): m = external_pat.match(line) if m: names = line[m.end():].strip().split(',') names = [n.strip().lower() for n in names] names = [n for n in names if n] routines.extend(names) return routines # File: numpy-main/numpy/linalg/lapack_lite/make_lite.py """""" import sys import os import re import subprocess import shutil import fortran import clapack_scrub try: from distutils.spawn import find_executable as which except ImportError: from shutil import which F2C_ARGS = ['-A', '-Nx800'] HEADER_BLURB = '/*\n * NOTE: This is generated code. Look in numpy/linalg/lapack_lite for\n * information on remaking this file.\n */\n' HEADER = HEADER_BLURB + '#include "f2c.h"\n\n#ifdef HAVE_CONFIG\n#include "config.h"\n#else\nextern doublereal dlamch_(char *);\n#define EPSILON dlamch_("Epsilon")\n#define SAFEMINIMUM dlamch_("Safe minimum")\n#define PRECISION dlamch_("Precision")\n#define BASE dlamch_("Base")\n#endif\n\nextern doublereal dlapy2_(doublereal *x, doublereal *y);\n\n/*\nf2c knows the exact rules for precedence, and so omits parentheses where not\nstrictly necessary. Since this is generated code, we don\'t really care if\nit\'s readable, and we know what is written is correct. So don\'t warn about\nthem.\n*/\n#if defined(__GNUC__)\n#pragma GCC diagnostic ignored "-Wparentheses"\n#endif\n' class FortranRoutine: type = 'generic' def __init__(self, name=None, filename=None): self.filename = filename if name is None: (root, ext) = os.path.splitext(filename) name = root self.name = name self._dependencies = None def dependencies(self): if self._dependencies is None: deps = fortran.getDependencies(self.filename) self._dependencies = [d.lower() for d in deps] return self._dependencies def __repr__(self): return 'FortranRoutine({!r}, filename={!r})'.format(self.name, self.filename) class UnknownFortranRoutine(FortranRoutine): type = 'unknown' def __init__(self, name): FortranRoutine.__init__(self, name=name, filename='') def dependencies(self): return [] class FortranLibrary: def __init__(self, src_dirs): self._src_dirs = src_dirs self.names_to_routines = {} def _findRoutine(self, rname): rname = rname.lower() for s in self._src_dirs: ffilename = os.path.join(s, rname + '.f') if os.path.exists(ffilename): return self._newFortranRoutine(rname, ffilename) return UnknownFortranRoutine(rname) def _newFortranRoutine(self, rname, filename): return FortranRoutine(rname, filename) def addIgnorableRoutine(self, rname): rname = rname.lower() routine = UnknownFortranRoutine(rname) self.names_to_routines[rname] = routine def addRoutine(self, rname): self.getRoutine(rname) def getRoutine(self, rname): unique = [] rname = rname.lower() routine = self.names_to_routines.get(rname, unique) if routine is unique: routine = self._findRoutine(rname) self.names_to_routines[rname] = routine return routine def allRoutineNames(self): return list(self.names_to_routines.keys()) def allRoutines(self): return list(self.names_to_routines.values()) def resolveAllDependencies(self): done_this = set() last_todo = set() while True: todo = set(self.allRoutineNames()) - done_this if todo == last_todo: break for rn in todo: r = self.getRoutine(rn) deps = r.dependencies() for d in deps: self.addRoutine(d) done_this.add(rn) last_todo = todo return todo class LapackLibrary(FortranLibrary): def _newFortranRoutine(self, rname, filename): routine = FortranLibrary._newFortranRoutine(self, rname, filename) if 'blas' in filename.lower(): routine.type = 'blas' elif 'install' in filename.lower(): routine.type = 'config' elif rname.startswith('z'): routine.type = 'z_lapack' elif rname.startswith('c'): routine.type = 'c_lapack' elif rname.startswith('s'): routine.type = 's_lapack' elif rname.startswith('d'): routine.type = 'd_lapack' else: routine.type = 'lapack' return routine def allRoutinesByType(self, typename): routines = sorted(((r.name, r) for r in self.allRoutines() if r.type == typename)) return [a[1] for a in routines] def printRoutineNames(desc, routines): print(desc) for r in routines: print('\t%s' % r.name) def getLapackRoutines(wrapped_routines, ignores, lapack_dir): blas_src_dir = os.path.join(lapack_dir, 'BLAS', 'SRC') if not os.path.exists(blas_src_dir): blas_src_dir = os.path.join(lapack_dir, 'blas', 'src') lapack_src_dir = os.path.join(lapack_dir, 'SRC') if not os.path.exists(lapack_src_dir): lapack_src_dir = os.path.join(lapack_dir, 'src') install_src_dir = os.path.join(lapack_dir, 'INSTALL') if not os.path.exists(install_src_dir): install_src_dir = os.path.join(lapack_dir, 'install') library = LapackLibrary([install_src_dir, blas_src_dir, lapack_src_dir]) for r in ignores: library.addIgnorableRoutine(r) for w in wrapped_routines: library.addRoutine(w) library.resolveAllDependencies() return library def getWrappedRoutineNames(wrapped_routines_file): routines = [] ignores = [] with open(wrapped_routines_file) as fo: for line in fo: line = line.strip() if not line or line.startswith('#'): continue if line.startswith('IGNORE:'): line = line[7:].strip() ig = line.split() ignores.extend(ig) else: routines.append(line) return (routines, ignores) types = {'blas', 'lapack', 'd_lapack', 's_lapack', 'z_lapack', 'c_lapack', 'config'} def dumpRoutineNames(library, output_dir): for typename in {'unknown'} | types: routines = library.allRoutinesByType(typename) filename = os.path.join(output_dir, typename + '_routines.lst') with open(filename, 'w') as fo: for r in routines: deps = r.dependencies() fo.write('%s: %s\n' % (r.name, ' '.join(deps))) def concatenateRoutines(routines, output_file): with open(output_file, 'w') as output_fo: for r in routines: with open(r.filename) as fo: source = fo.read() output_fo.write(source) class F2CError(Exception): pass def runF2C(fortran_filename, output_dir): fortran_filename = fortran_filename.replace('\\', '/') try: subprocess.check_call(['f2c'] + F2C_ARGS + ['-d', output_dir, fortran_filename]) except subprocess.CalledProcessError: raise F2CError def scrubF2CSource(c_file): with open(c_file) as fo: source = fo.read() source = clapack_scrub.scrubSource(source, verbose=True) with open(c_file, 'w') as fo: fo.write(HEADER) fo.write(source) def ensure_executable(name): try: which(name) except Exception: raise SystemExit(name + ' not found') def create_name_header(output_dir): routine_re = re.compile('^ (subroutine|.* function)\\s+(\\w+)\\(.*$', re.I) extern_re = re.compile('^extern [a-z]+ ([a-z0-9_]+)\\(.*$') symbols = set(['xerbla']) for fn in os.listdir(output_dir): fn = os.path.join(output_dir, fn) if not fn.endswith('.f'): continue with open(fn) as f: for line in f: m = routine_re.match(line) if m: symbols.add(m.group(2).lower()) f2c_symbols = set() with open('f2c.h') as f: for line in f: m = extern_re.match(line) if m: f2c_symbols.add(m.group(1)) with open(os.path.join(output_dir, 'lapack_lite_names.h'), 'w') as f: f.write(HEADER_BLURB) f.write("/*\n * This file renames all BLAS/LAPACK and f2c symbols to avoid\n * dynamic symbol name conflicts, in cases where e.g.\n * integer sizes do not match with 'standard' ABI.\n */\n") for name in sorted(symbols): f.write('#define %s_ BLAS_FUNC(%s)\n' % (name, name)) f.write('\n/* Symbols exported by f2c.c */\n') for name in sorted(f2c_symbols): f.write('#define %s numpy_lapack_lite_%s\n' % (name, name)) def main(): if len(sys.argv) != 3: print(__doc__) return ensure_executable('f2c') ensure_executable('patch') wrapped_routines_file = sys.argv[1] lapack_src_dir = sys.argv[2] output_dir = os.path.join(os.path.dirname(__file__), 'build') shutil.rmtree(output_dir, ignore_errors=True) os.makedirs(output_dir) (wrapped_routines, ignores) = getWrappedRoutineNames(wrapped_routines_file) library = getLapackRoutines(wrapped_routines, ignores, lapack_src_dir) dumpRoutineNames(library, output_dir) for typename in types: fortran_file = os.path.join(output_dir, 'f2c_%s.f' % typename) c_file = fortran_file[:-2] + '.c' print('creating %s ...' % c_file) routines = library.allRoutinesByType(typename) concatenateRoutines(routines, fortran_file) patch_file = os.path.basename(fortran_file) + '.patch' if os.path.exists(patch_file): subprocess.check_call(['patch', '-u', fortran_file, patch_file]) print('Patched {}'.format(fortran_file)) try: runF2C(fortran_file, output_dir) except F2CError: print('f2c failed on %s' % fortran_file) break scrubF2CSource(c_file) c_patch_file = os.path.basename(c_file) + '.patch' if os.path.exists(c_patch_file): subprocess.check_call(['patch', '-u', c_file, c_patch_file]) print() create_name_header(output_dir) for fname in os.listdir(output_dir): if fname.endswith('.c') or fname == 'lapack_lite_names.h': print('Copying ' + fname) shutil.copy(os.path.join(output_dir, fname), os.path.abspath(os.path.dirname(__file__))) if __name__ == '__main__': main() # File: numpy-main/numpy/linalg/linalg.py def __getattr__(attr_name): import warnings from numpy.linalg import _linalg ret = getattr(_linalg, attr_name, None) if ret is None: raise AttributeError(f"module 'numpy.linalg.linalg' has no attribute {attr_name}") warnings.warn(f'The numpy.linalg.linalg has been made private and renamed to numpy.linalg._linalg. All public functions exported by it are available from numpy.linalg. Please use numpy.linalg.{attr_name} instead.', DeprecationWarning, stacklevel=3) return ret # File: numpy-main/numpy/ma/__init__.py """""" from . import core from .core import * from . import extras from .extras import * __all__ = ['core', 'extras'] __all__ += core.__all__ __all__ += extras.__all__ from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester # File: numpy-main/numpy/ma/core.py """""" import builtins import inspect import operator import warnings import textwrap import re from functools import reduce from typing import Dict import numpy as np import numpy._core.umath as umath import numpy._core.numerictypes as ntypes from numpy._core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue, angle from numpy import array as narray, expand_dims, iinfo, finfo from numpy._core.numeric import normalize_axis_tuple from numpy._utils._inspect import getargspec, formatargspec from numpy._utils import set_module __all__ = ['MAError', 'MaskError', 'MaskType', 'MaskedArray', 'abs', 'absolute', 'add', 'all', 'allclose', 'allequal', 'alltrue', 'amax', 'amin', 'angle', 'anom', 'anomalies', 'any', 'append', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argsort', 'around', 'array', 'asanyarray', 'asarray', 'bitwise_and', 'bitwise_or', 'bitwise_xor', 'bool_', 'ceil', 'choose', 'clip', 'common_fill_value', 'compress', 'compressed', 'concatenate', 'conjugate', 'convolve', 'copy', 'correlate', 'cos', 'cosh', 'count', 'cumprod', 'cumsum', 'default_fill_value', 'diag', 'diagonal', 'diff', 'divide', 'empty', 'empty_like', 'equal', 'exp', 'expand_dims', 'fabs', 'filled', 'fix_invalid', 'flatten_mask', 'flatten_structured_array', 'floor', 'floor_divide', 'fmod', 'frombuffer', 'fromflex', 'fromfunction', 'getdata', 'getmask', 'getmaskarray', 'greater', 'greater_equal', 'harden_mask', 'hypot', 'identity', 'ids', 'indices', 'inner', 'innerproduct', 'isMA', 'isMaskedArray', 'is_mask', 'is_masked', 'isarray', 'left_shift', 'less', 'less_equal', 'log', 'log10', 'log2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'make_mask', 'make_mask_descr', 'make_mask_none', 'mask_or', 'masked', 'masked_array', 'masked_equal', 'masked_greater', 'masked_greater_equal', 'masked_inside', 'masked_invalid', 'masked_less', 'masked_less_equal', 'masked_not_equal', 'masked_object', 'masked_outside', 'masked_print_option', 'masked_singleton', 'masked_values', 'masked_where', 'max', 'maximum', 'maximum_fill_value', 'mean', 'min', 'minimum', 'minimum_fill_value', 'mod', 'multiply', 'mvoid', 'ndim', 'negative', 'nomask', 'nonzero', 'not_equal', 'ones', 'ones_like', 'outer', 'outerproduct', 'power', 'prod', 'product', 'ptp', 'put', 'putmask', 'ravel', 'remainder', 'repeat', 'reshape', 'resize', 'right_shift', 'round', 'round_', 'set_fill_value', 'shape', 'sin', 'sinh', 'size', 'soften_mask', 'sometrue', 'sort', 'sqrt', 'squeeze', 'std', 'subtract', 'sum', 'swapaxes', 'take', 'tan', 'tanh', 'trace', 'transpose', 'true_divide', 'var', 'where', 'zeros', 'zeros_like'] MaskType = np.bool nomask = MaskType(0) class MaskedArrayFutureWarning(FutureWarning): pass def _deprecate_argsort_axis(arr): if arr.ndim <= 1: return -1 else: warnings.warn('In the future the default for argsort will be axis=-1, not the current None, to match its documentation and np.argsort. Explicitly pass -1 or None to silence this warning.', MaskedArrayFutureWarning, stacklevel=3) return None def doc_note(initialdoc, note): if initialdoc is None: return if note is None: return initialdoc notesplit = re.split('\\n\\s*?Notes\\n\\s*?-----', inspect.cleandoc(initialdoc)) notedoc = '\n\nNotes\n-----\n%s\n' % inspect.cleandoc(note) return ''.join(notesplit[:1] + [notedoc] + notesplit[1:]) def get_object_signature(obj): try: sig = formatargspec(*getargspec(obj)) except TypeError: sig = '' return sig class MAError(Exception): pass class MaskError(MAError): pass default_filler = {'b': True, 'c': 1e+20 + 0j, 'f': 1e+20, 'i': 999999, 'O': '?', 'S': b'N/A', 'u': 999999, 'V': b'???', 'U': 'N/A'} for v in ['Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns', 'ps', 'fs', 'as']: default_filler['M8[' + v + ']'] = np.datetime64('NaT', v) default_filler['m8[' + v + ']'] = np.timedelta64('NaT', v) float_types_list = [np.half, np.single, np.double, np.longdouble, np.csingle, np.cdouble, np.clongdouble] _minvals: Dict[type, int] = {} _maxvals: Dict[type, int] = {} for sctype in ntypes.sctypeDict.values(): scalar_dtype = np.dtype(sctype) if scalar_dtype.kind in 'Mm': info = np.iinfo(np.int64) (min_val, max_val) = (info.min, info.max) elif np.issubdtype(scalar_dtype, np.integer): info = np.iinfo(sctype) (min_val, max_val) = (info.min, info.max) elif np.issubdtype(scalar_dtype, np.floating): info = np.finfo(sctype) (min_val, max_val) = (info.min, info.max) elif scalar_dtype.kind == 'b': (min_val, max_val) = (0, 1) else: (min_val, max_val) = (None, None) _minvals[sctype] = min_val _maxvals[sctype] = max_val max_filler = _minvals max_filler.update([(k, -np.inf) for k in float_types_list[:4]]) max_filler.update([(k, complex(-np.inf, -np.inf)) for k in float_types_list[-3:]]) min_filler = _maxvals min_filler.update([(k, +np.inf) for k in float_types_list[:4]]) min_filler.update([(k, complex(+np.inf, +np.inf)) for k in float_types_list[-3:]]) del float_types_list def _recursive_fill_value(dtype, f): if dtype.names is not None: vals = tuple((np.array(_recursive_fill_value(dtype[name], f)) for name in dtype.names)) return np.array(vals, dtype=dtype)[()] elif dtype.subdtype: (subtype, shape) = dtype.subdtype subval = _recursive_fill_value(subtype, f) return np.full(shape, subval) else: return f(dtype) def _get_dtype_of(obj): if isinstance(obj, np.dtype): return obj elif hasattr(obj, 'dtype'): return obj.dtype else: return np.asanyarray(obj).dtype def default_fill_value(obj): def _scalar_fill_value(dtype): if dtype.kind in 'Mm': return default_filler.get(dtype.str[1:], '?') else: return default_filler.get(dtype.kind, '?') dtype = _get_dtype_of(obj) return _recursive_fill_value(dtype, _scalar_fill_value) def _extremum_fill_value(obj, extremum, extremum_name): def _scalar_fill_value(dtype): try: return extremum[dtype.type] except KeyError as e: raise TypeError(f'Unsuitable type {dtype} for calculating {extremum_name}.') from None dtype = _get_dtype_of(obj) return _recursive_fill_value(dtype, _scalar_fill_value) def minimum_fill_value(obj): return _extremum_fill_value(obj, min_filler, 'minimum') def maximum_fill_value(obj): return _extremum_fill_value(obj, max_filler, 'maximum') def _recursive_set_fill_value(fillvalue, dt): fillvalue = np.resize(fillvalue, len(dt.names)) output_value = [] for (fval, name) in zip(fillvalue, dt.names): cdtype = dt[name] if cdtype.subdtype: cdtype = cdtype.subdtype[0] if cdtype.names is not None: output_value.append(tuple(_recursive_set_fill_value(fval, cdtype))) else: output_value.append(np.array(fval, dtype=cdtype).item()) return tuple(output_value) def _check_fill_value(fill_value, ndtype): ndtype = np.dtype(ndtype) if fill_value is None: fill_value = default_fill_value(ndtype) elif ndtype.names is not None: if isinstance(fill_value, (ndarray, np.void)): try: fill_value = np.asarray(fill_value, dtype=ndtype) except ValueError as e: err_msg = 'Unable to transform %s to dtype %s' raise ValueError(err_msg % (fill_value, ndtype)) from e else: fill_value = np.asarray(fill_value, dtype=object) fill_value = np.array(_recursive_set_fill_value(fill_value, ndtype), dtype=ndtype) elif isinstance(fill_value, str) and ndtype.char not in 'OSVU': err_msg = 'Cannot set fill value of string with array of dtype %s' raise TypeError(err_msg % ndtype) else: try: fill_value = np.asarray(fill_value, dtype=ndtype) except (OverflowError, ValueError) as e: err_msg = 'Cannot convert fill_value %s to dtype %s' raise TypeError(err_msg % (fill_value, ndtype)) from e return np.array(fill_value) def set_fill_value(a, fill_value): if isinstance(a, MaskedArray): a.set_fill_value(fill_value) return def get_fill_value(a): if isinstance(a, MaskedArray): result = a.fill_value else: result = default_fill_value(a) return result def common_fill_value(a, b): t1 = get_fill_value(a) t2 = get_fill_value(b) if t1 == t2: return t1 return None def filled(a, fill_value=None): if hasattr(a, 'filled'): return a.filled(fill_value) elif isinstance(a, ndarray): return a elif isinstance(a, dict): return np.array(a, 'O') else: return np.array(a) def get_masked_subclass(*arrays): if len(arrays) == 1: arr = arrays[0] if isinstance(arr, MaskedArray): rcls = type(arr) else: rcls = MaskedArray else: arrcls = [type(a) for a in arrays] rcls = arrcls[0] if not issubclass(rcls, MaskedArray): rcls = MaskedArray for cls in arrcls[1:]: if issubclass(cls, rcls): rcls = cls if rcls.__name__ == 'MaskedConstant': return MaskedArray return rcls def getdata(a, subok=True): try: data = a._data except AttributeError: data = np.array(a, copy=None, subok=subok) if not subok: return data.view(ndarray) return data get_data = getdata def fix_invalid(a, mask=nomask, copy=True, fill_value=None): a = masked_array(a, copy=copy, mask=mask, subok=True) invalid = np.logical_not(np.isfinite(a._data)) if not invalid.any(): return a a._mask |= invalid if fill_value is None: fill_value = a.fill_value a._data[invalid] = fill_value return a def is_string_or_list_of_strings(val): return isinstance(val, str) or (isinstance(val, list) and val and builtins.all((isinstance(s, str) for s in val))) ufunc_domain = {} ufunc_fills = {} class _DomainCheckInterval: def __init__(self, a, b): if a > b: (a, b) = (b, a) self.a = a self.b = b def __call__(self, x): with np.errstate(invalid='ignore'): return umath.logical_or(umath.greater(x, self.b), umath.less(x, self.a)) class _DomainTan: def __init__(self, eps): self.eps = eps def __call__(self, x): with np.errstate(invalid='ignore'): return umath.less(umath.absolute(umath.cos(x)), self.eps) class _DomainSafeDivide: def __init__(self, tolerance=None): self.tolerance = tolerance def __call__(self, a, b): if self.tolerance is None: self.tolerance = np.finfo(float).tiny (a, b) = (np.asarray(a), np.asarray(b)) with np.errstate(all='ignore'): return umath.absolute(a) * self.tolerance >= umath.absolute(b) class _DomainGreater: def __init__(self, critical_value): self.critical_value = critical_value def __call__(self, x): with np.errstate(invalid='ignore'): return umath.less_equal(x, self.critical_value) class _DomainGreaterEqual: def __init__(self, critical_value): self.critical_value = critical_value def __call__(self, x): with np.errstate(invalid='ignore'): return umath.less(x, self.critical_value) class _MaskedUFunc: def __init__(self, ufunc): self.f = ufunc self.__doc__ = ufunc.__doc__ self.__name__ = ufunc.__name__ def __str__(self): return f'Masked version of {self.f}' class _MaskedUnaryOperation(_MaskedUFunc): def __init__(self, mufunc, fill=0, domain=None): super().__init__(mufunc) self.fill = fill self.domain = domain ufunc_domain[mufunc] = domain ufunc_fills[mufunc] = fill def __call__(self, a, *args, **kwargs): d = getdata(a) if self.domain is not None: with np.errstate(divide='ignore', invalid='ignore'): result = self.f(d, *args, **kwargs) m = ~umath.isfinite(result) m |= self.domain(d) m |= getmask(a) else: with np.errstate(divide='ignore', invalid='ignore'): result = self.f(d, *args, **kwargs) m = getmask(a) if not result.ndim: if m: return masked return result if m is not nomask: try: np.copyto(result, d, where=m) except TypeError: pass masked_result = result.view(get_masked_subclass(a)) masked_result._mask = m masked_result._update_from(a) return masked_result class _MaskedBinaryOperation(_MaskedUFunc): def __init__(self, mbfunc, fillx=0, filly=0): super().__init__(mbfunc) self.fillx = fillx self.filly = filly ufunc_domain[mbfunc] = None ufunc_fills[mbfunc] = (fillx, filly) def __call__(self, a, b, *args, **kwargs): (da, db) = (getdata(a), getdata(b)) with np.errstate(): np.seterr(divide='ignore', invalid='ignore') result = self.f(da, db, *args, **kwargs) (ma, mb) = (getmask(a), getmask(b)) if ma is nomask: if mb is nomask: m = nomask else: m = umath.logical_or(getmaskarray(a), mb) elif mb is nomask: m = umath.logical_or(ma, getmaskarray(b)) else: m = umath.logical_or(ma, mb) if not result.ndim: if m: return masked return result if m is not nomask and m.any(): try: np.copyto(result, da, casting='unsafe', where=m) except Exception: pass masked_result = result.view(get_masked_subclass(a, b)) masked_result._mask = m if isinstance(a, MaskedArray): masked_result._update_from(a) elif isinstance(b, MaskedArray): masked_result._update_from(b) return masked_result def reduce(self, target, axis=0, dtype=None): tclass = get_masked_subclass(target) m = getmask(target) t = filled(target, self.filly) if t.shape == (): t = t.reshape(1) if m is not nomask: m = make_mask(m, copy=True) m.shape = (1,) if m is nomask: tr = self.f.reduce(t, axis) mr = nomask else: tr = self.f.reduce(t, axis, dtype=dtype) mr = umath.logical_and.reduce(m, axis) if not tr.shape: if mr: return masked else: return tr masked_tr = tr.view(tclass) masked_tr._mask = mr return masked_tr def outer(self, a, b): (da, db) = (getdata(a), getdata(b)) d = self.f.outer(da, db) ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: m = nomask else: ma = getmaskarray(a) mb = getmaskarray(b) m = umath.logical_or.outer(ma, mb) if not m.ndim and m: return masked if m is not nomask: np.copyto(d, da, where=m) if not d.shape: return d masked_d = d.view(get_masked_subclass(a, b)) masked_d._mask = m return masked_d def accumulate(self, target, axis=0): tclass = get_masked_subclass(target) t = filled(target, self.filly) result = self.f.accumulate(t, axis) masked_result = result.view(tclass) return masked_result class _DomainedBinaryOperation(_MaskedUFunc): def __init__(self, dbfunc, domain, fillx=0, filly=0): super().__init__(dbfunc) self.domain = domain self.fillx = fillx self.filly = filly ufunc_domain[dbfunc] = domain ufunc_fills[dbfunc] = (fillx, filly) def __call__(self, a, b, *args, **kwargs): (da, db) = (getdata(a), getdata(b)) with np.errstate(divide='ignore', invalid='ignore'): result = self.f(da, db, *args, **kwargs) m = ~umath.isfinite(result) m |= getmask(a) m |= getmask(b) domain = ufunc_domain.get(self.f, None) if domain is not None: m |= domain(da, db) if not m.ndim: if m: return masked else: return result try: np.copyto(result, 0, casting='unsafe', where=m) masked_da = umath.multiply(m, da) if np.can_cast(masked_da.dtype, result.dtype, casting='safe'): result += masked_da except Exception: pass masked_result = result.view(get_masked_subclass(a, b)) masked_result._mask = m if isinstance(a, MaskedArray): masked_result._update_from(a) elif isinstance(b, MaskedArray): masked_result._update_from(b) return masked_result exp = _MaskedUnaryOperation(umath.exp) conjugate = _MaskedUnaryOperation(umath.conjugate) sin = _MaskedUnaryOperation(umath.sin) cos = _MaskedUnaryOperation(umath.cos) arctan = _MaskedUnaryOperation(umath.arctan) arcsinh = _MaskedUnaryOperation(umath.arcsinh) sinh = _MaskedUnaryOperation(umath.sinh) cosh = _MaskedUnaryOperation(umath.cosh) tanh = _MaskedUnaryOperation(umath.tanh) abs = absolute = _MaskedUnaryOperation(umath.absolute) angle = _MaskedUnaryOperation(angle) fabs = _MaskedUnaryOperation(umath.fabs) negative = _MaskedUnaryOperation(umath.negative) floor = _MaskedUnaryOperation(umath.floor) ceil = _MaskedUnaryOperation(umath.ceil) around = _MaskedUnaryOperation(np.around) logical_not = _MaskedUnaryOperation(umath.logical_not) sqrt = _MaskedUnaryOperation(umath.sqrt, 0.0, _DomainGreaterEqual(0.0)) log = _MaskedUnaryOperation(umath.log, 1.0, _DomainGreater(0.0)) log2 = _MaskedUnaryOperation(umath.log2, 1.0, _DomainGreater(0.0)) log10 = _MaskedUnaryOperation(umath.log10, 1.0, _DomainGreater(0.0)) tan = _MaskedUnaryOperation(umath.tan, 0.0, _DomainTan(1e-35)) arcsin = _MaskedUnaryOperation(umath.arcsin, 0.0, _DomainCheckInterval(-1.0, 1.0)) arccos = _MaskedUnaryOperation(umath.arccos, 0.0, _DomainCheckInterval(-1.0, 1.0)) arccosh = _MaskedUnaryOperation(umath.arccosh, 1.0, _DomainGreaterEqual(1.0)) arctanh = _MaskedUnaryOperation(umath.arctanh, 0.0, _DomainCheckInterval(-1.0 + 1e-15, 1.0 - 1e-15)) add = _MaskedBinaryOperation(umath.add) subtract = _MaskedBinaryOperation(umath.subtract) multiply = _MaskedBinaryOperation(umath.multiply, 1, 1) arctan2 = _MaskedBinaryOperation(umath.arctan2, 0.0, 1.0) equal = _MaskedBinaryOperation(umath.equal) equal.reduce = None not_equal = _MaskedBinaryOperation(umath.not_equal) not_equal.reduce = None less_equal = _MaskedBinaryOperation(umath.less_equal) less_equal.reduce = None greater_equal = _MaskedBinaryOperation(umath.greater_equal) greater_equal.reduce = None less = _MaskedBinaryOperation(umath.less) less.reduce = None greater = _MaskedBinaryOperation(umath.greater) greater.reduce = None logical_and = _MaskedBinaryOperation(umath.logical_and) alltrue = _MaskedBinaryOperation(umath.logical_and, 1, 1).reduce logical_or = _MaskedBinaryOperation(umath.logical_or) sometrue = logical_or.reduce logical_xor = _MaskedBinaryOperation(umath.logical_xor) bitwise_and = _MaskedBinaryOperation(umath.bitwise_and) bitwise_or = _MaskedBinaryOperation(umath.bitwise_or) bitwise_xor = _MaskedBinaryOperation(umath.bitwise_xor) hypot = _MaskedBinaryOperation(umath.hypot) divide = _DomainedBinaryOperation(umath.divide, _DomainSafeDivide(), 0, 1) true_divide = _DomainedBinaryOperation(umath.true_divide, _DomainSafeDivide(), 0, 1) floor_divide = _DomainedBinaryOperation(umath.floor_divide, _DomainSafeDivide(), 0, 1) remainder = _DomainedBinaryOperation(umath.remainder, _DomainSafeDivide(), 0, 1) fmod = _DomainedBinaryOperation(umath.fmod, _DomainSafeDivide(), 0, 1) mod = _DomainedBinaryOperation(umath.mod, _DomainSafeDivide(), 0, 1) def _replace_dtype_fields_recursive(dtype, primitive_dtype): _recurse = _replace_dtype_fields_recursive if dtype.names is not None: descr = [] for name in dtype.names: field = dtype.fields[name] if len(field) == 3: name = (field[-1], name) descr.append((name, _recurse(field[0], primitive_dtype))) new_dtype = np.dtype(descr) elif dtype.subdtype: descr = list(dtype.subdtype) descr[0] = _recurse(dtype.subdtype[0], primitive_dtype) new_dtype = np.dtype(tuple(descr)) else: new_dtype = primitive_dtype if new_dtype == dtype: new_dtype = dtype return new_dtype def _replace_dtype_fields(dtype, primitive_dtype): dtype = np.dtype(dtype) primitive_dtype = np.dtype(primitive_dtype) return _replace_dtype_fields_recursive(dtype, primitive_dtype) def make_mask_descr(ndtype): return _replace_dtype_fields(ndtype, MaskType) def getmask(a): return getattr(a, '_mask', nomask) get_mask = getmask def getmaskarray(arr): mask = getmask(arr) if mask is nomask: mask = make_mask_none(np.shape(arr), getattr(arr, 'dtype', None)) return mask def is_mask(m): try: return m.dtype.type is MaskType except AttributeError: return False def _shrink_mask(m): if m.dtype.names is None and (not m.any()): return nomask else: return m def make_mask(m, copy=False, shrink=True, dtype=MaskType): if m is nomask: return nomask dtype = make_mask_descr(dtype) if isinstance(m, ndarray) and m.dtype.fields and (dtype == np.bool): return np.ones(m.shape, dtype=dtype) copy = None if not copy else True result = np.array(filled(m, True), copy=copy, dtype=dtype, subok=True) if shrink: result = _shrink_mask(result) return result def make_mask_none(newshape, dtype=None): if dtype is None: result = np.zeros(newshape, dtype=MaskType) else: result = np.zeros(newshape, dtype=make_mask_descr(dtype)) return result def _recursive_mask_or(m1, m2, newmask): names = m1.dtype.names for name in names: current1 = m1[name] if current1.dtype.names is not None: _recursive_mask_or(current1, m2[name], newmask[name]) else: umath.logical_or(current1, m2[name], newmask[name]) def mask_or(m1, m2, copy=False, shrink=True): if m1 is nomask or m1 is False: dtype = getattr(m2, 'dtype', MaskType) return make_mask(m2, copy=copy, shrink=shrink, dtype=dtype) if m2 is nomask or m2 is False: dtype = getattr(m1, 'dtype', MaskType) return make_mask(m1, copy=copy, shrink=shrink, dtype=dtype) if m1 is m2 and is_mask(m1): return _shrink_mask(m1) if shrink else m1 (dtype1, dtype2) = (getattr(m1, 'dtype', None), getattr(m2, 'dtype', None)) if dtype1 != dtype2: raise ValueError("Incompatible dtypes '%s'<>'%s'" % (dtype1, dtype2)) if dtype1.names is not None: newmask = np.empty(np.broadcast(m1, m2).shape, dtype1) _recursive_mask_or(m1, m2, newmask) return newmask return make_mask(umath.logical_or(m1, m2), copy=copy, shrink=shrink) def flatten_mask(mask): def _flatmask(mask): mnames = mask.dtype.names if mnames is not None: return [flatten_mask(mask[name]) for name in mnames] else: return mask def _flatsequence(sequence): try: for element in sequence: if hasattr(element, '__iter__'): yield from _flatsequence(element) else: yield element except TypeError: yield sequence mask = np.asarray(mask) flattened = _flatsequence(_flatmask(mask)) return np.array(list(flattened), dtype=bool) def _check_mask_axis(mask, axis, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} if mask is not nomask: return mask.all(axis=axis, **kwargs) return nomask def masked_where(condition, a, copy=True): cond = make_mask(condition, shrink=False) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError('Inconsistent shape between the condition and the input (got %s and %s)' % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) result.mask = _shrink_mask(cond) if not copy and hasattr(a, '_mask') and (getmask(a) is nomask): a._mask = result._mask.view() return result def masked_greater(x, value, copy=True): return masked_where(greater(x, value), x, copy=copy) def masked_greater_equal(x, value, copy=True): return masked_where(greater_equal(x, value), x, copy=copy) def masked_less(x, value, copy=True): return masked_where(less(x, value), x, copy=copy) def masked_less_equal(x, value, copy=True): return masked_where(less_equal(x, value), x, copy=copy) def masked_not_equal(x, value, copy=True): return masked_where(not_equal(x, value), x, copy=copy) def masked_equal(x, value, copy=True): output = masked_where(equal(x, value), x, copy=copy) output.fill_value = value return output def masked_inside(x, v1, v2, copy=True): if v2 < v1: (v1, v2) = (v2, v1) xf = filled(x) condition = (xf >= v1) & (xf <= v2) return masked_where(condition, x, copy=copy) def masked_outside(x, v1, v2, copy=True): if v2 < v1: (v1, v2) = (v2, v1) xf = filled(x) condition = (xf < v1) | (xf > v2) return masked_where(condition, x, copy=copy) def masked_object(x, value, copy=True, shrink=True): if isMaskedArray(x): condition = umath.equal(x._data, value) mask = x._mask else: condition = umath.equal(np.asarray(x), value) mask = nomask mask = mask_or(mask, make_mask(condition, shrink=shrink)) return masked_array(x, mask=mask, copy=copy, fill_value=value) def masked_values(x, value, rtol=1e-05, atol=1e-08, copy=True, shrink=True): xnew = filled(x, value) if np.issubdtype(xnew.dtype, np.floating): mask = np.isclose(xnew, value, atol=atol, rtol=rtol) else: mask = umath.equal(xnew, value) ret = masked_array(xnew, mask=mask, copy=copy, fill_value=value) if shrink: ret.shrink_mask() return ret def masked_invalid(a, copy=True): a = np.array(a, copy=None, subok=True) res = masked_where(~np.isfinite(a), a, copy=copy) if res._mask is nomask: res._mask = make_mask_none(res.shape, res.dtype) return res class _MaskedPrintOption: def __init__(self, display): self._display = display self._enabled = True def display(self): return self._display def set_display(self, s): self._display = s def enabled(self): return self._enabled def enable(self, shrink=1): self._enabled = shrink def __str__(self): return str(self._display) __repr__ = __str__ masked_print_option = _MaskedPrintOption('--') def _recursive_printoption(result, mask, printopt): names = result.dtype.names if names is not None: for name in names: curdata = result[name] curmask = mask[name] _recursive_printoption(curdata, curmask, printopt) else: np.copyto(result, printopt, where=mask) return _legacy_print_templates = dict(long_std=textwrap.dedent(' masked_%(name)s(data =\n %(data)s,\n %(nlen)s mask =\n %(mask)s,\n %(nlen)s fill_value = %(fill)s)\n '), long_flx=textwrap.dedent(' masked_%(name)s(data =\n %(data)s,\n %(nlen)s mask =\n %(mask)s,\n %(nlen)s fill_value = %(fill)s,\n %(nlen)s dtype = %(dtype)s)\n '), short_std=textwrap.dedent(' masked_%(name)s(data = %(data)s,\n %(nlen)s mask = %(mask)s,\n %(nlen)s fill_value = %(fill)s)\n '), short_flx=textwrap.dedent(' masked_%(name)s(data = %(data)s,\n %(nlen)s mask = %(mask)s,\n %(nlen)s fill_value = %(fill)s,\n %(nlen)s dtype = %(dtype)s)\n ')) def _recursive_filled(a, mask, fill_value): names = a.dtype.names for name in names: current = a[name] if current.dtype.names is not None: _recursive_filled(current, mask[name], fill_value[name]) else: np.copyto(current, fill_value[name], where=mask[name]) def flatten_structured_array(a): def flatten_sequence(iterable): for elm in iter(iterable): if hasattr(elm, '__iter__'): yield from flatten_sequence(elm) else: yield elm a = np.asanyarray(a) inishape = a.shape a = a.ravel() if isinstance(a, MaskedArray): out = np.array([tuple(flatten_sequence(d.item())) for d in a._data]) out = out.view(MaskedArray) out._mask = np.array([tuple(flatten_sequence(d.item())) for d in getmaskarray(a)]) else: out = np.array([tuple(flatten_sequence(d.item())) for d in a]) if len(inishape) > 1: newshape = list(out.shape) newshape[0] = inishape out.shape = tuple(flatten_sequence(newshape)) return out def _arraymethod(funcname, onmask=True): def wrapped_method(self, *args, **params): result = getattr(self._data, funcname)(*args, **params) result = result.view(type(self)) result._update_from(self) mask = self._mask if not onmask: result.__setmask__(mask) elif mask is not nomask: result._mask = getattr(mask, funcname)(*args, **params) return result methdoc = getattr(ndarray, funcname, None) or getattr(np, funcname, None) if methdoc is not None: wrapped_method.__doc__ = methdoc.__doc__ wrapped_method.__name__ = funcname return wrapped_method class MaskedIterator: def __init__(self, ma): self.ma = ma self.dataiter = ma._data.flat if ma._mask is nomask: self.maskiter = None else: self.maskiter = ma._mask.flat def __iter__(self): return self def __getitem__(self, indx): result = self.dataiter.__getitem__(indx).view(type(self.ma)) if self.maskiter is not None: _mask = self.maskiter.__getitem__(indx) if isinstance(_mask, ndarray): _mask.shape = result.shape result._mask = _mask elif isinstance(_mask, np.void): return mvoid(result, mask=_mask, hardmask=self.ma._hardmask) elif _mask: return masked return result def __setitem__(self, index, value): self.dataiter[index] = getdata(value) if self.maskiter is not None: self.maskiter[index] = getmaskarray(value) def __next__(self): d = next(self.dataiter) if self.maskiter is not None: m = next(self.maskiter) if isinstance(m, np.void): return mvoid(d, mask=m, hardmask=self.ma._hardmask) elif m: return masked return d @set_module('numpy.ma') class MaskedArray(ndarray): __array_priority__ = 15 _defaultmask = nomask _defaulthardmask = False _baseclass = ndarray _print_width = 100 _print_width_1d = 1500 def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None): copy = None if not copy else True _data = np.array(data, dtype=dtype, copy=copy, order=order, subok=True, ndmin=ndmin) _baseclass = getattr(data, '_baseclass', type(_data)) if isinstance(data, MaskedArray) and data.shape != _data.shape: copy = True if isinstance(data, cls) and subok and (not isinstance(data, MaskedConstant)): _data = ndarray.view(_data, type(data)) else: _data = ndarray.view(_data, cls) if hasattr(data, '_mask') and (not isinstance(data, ndarray)): _data._mask = data._mask mdtype = make_mask_descr(_data.dtype) if mask is nomask: if not keep_mask: if shrink: _data._mask = nomask else: _data._mask = np.zeros(_data.shape, dtype=mdtype) elif isinstance(data, (tuple, list)): try: mask = np.array([getmaskarray(np.asanyarray(m, dtype=_data.dtype)) for m in data], dtype=mdtype) except (ValueError, TypeError): mask = nomask if mdtype == MaskType and mask.any(): _data._mask = mask _data._sharedmask = False else: _data._sharedmask = not copy if copy: _data._mask = _data._mask.copy() if getmask(data) is not nomask: if data._mask.shape != data.shape: data._mask.shape = data.shape else: if mask is None: mask = False if mask is True and mdtype == MaskType: mask = np.ones(_data.shape, dtype=mdtype) elif mask is False and mdtype == MaskType: mask = np.zeros(_data.shape, dtype=mdtype) else: try: mask = np.array(mask, copy=copy, dtype=mdtype) except TypeError: mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) if mask.shape != _data.shape: (nd, nm) = (_data.size, mask.size) if nm == 1: mask = np.resize(mask, _data.shape) elif nm == nd: mask = np.reshape(mask, _data.shape) else: msg = 'Mask and data not compatible: data size is %i, ' + 'mask size is %i.' raise MaskError(msg % (nd, nm)) copy = True if _data._mask is nomask: _data._mask = mask _data._sharedmask = not copy elif not keep_mask: _data._mask = mask _data._sharedmask = not copy else: if _data.dtype.names is not None: def _recursive_or(a, b): for name in a.dtype.names: (af, bf) = (a[name], b[name]) if af.dtype.names is not None: _recursive_or(af, bf) else: af |= bf _recursive_or(_data._mask, mask) else: _data._mask = np.logical_or(mask, _data._mask) _data._sharedmask = False if fill_value is None: fill_value = getattr(data, '_fill_value', None) if fill_value is not None: _data._fill_value = _check_fill_value(fill_value, _data.dtype) if hard_mask is None: _data._hardmask = getattr(data, '_hardmask', False) else: _data._hardmask = hard_mask _data._baseclass = _baseclass return _data def _update_from(self, obj): if isinstance(obj, ndarray): _baseclass = type(obj) else: _baseclass = ndarray _optinfo = {} _optinfo.update(getattr(obj, '_optinfo', {})) _optinfo.update(getattr(obj, '_basedict', {})) if not isinstance(obj, MaskedArray): _optinfo.update(getattr(obj, '__dict__', {})) _dict = dict(_fill_value=getattr(obj, '_fill_value', None), _hardmask=getattr(obj, '_hardmask', False), _sharedmask=getattr(obj, '_sharedmask', False), _isfield=getattr(obj, '_isfield', False), _baseclass=getattr(obj, '_baseclass', _baseclass), _optinfo=_optinfo, _basedict=_optinfo) self.__dict__.update(_dict) self.__dict__.update(_optinfo) return def __array_finalize__(self, obj): self._update_from(obj) if isinstance(obj, ndarray): if obj.dtype.names is not None: _mask = getmaskarray(obj) else: _mask = getmask(obj) if _mask is not nomask and obj.__array_interface__['data'][0] != self.__array_interface__['data'][0]: if self.dtype == obj.dtype: _mask_dtype = _mask.dtype else: _mask_dtype = make_mask_descr(self.dtype) if self.flags.c_contiguous: order = 'C' elif self.flags.f_contiguous: order = 'F' else: order = 'K' _mask = _mask.astype(_mask_dtype, order) else: _mask = _mask.view() else: _mask = nomask self._mask = _mask if self._mask is not nomask: try: self._mask.shape = self.shape except ValueError: self._mask = nomask except (TypeError, AttributeError): pass if self._fill_value is not None: self._fill_value = _check_fill_value(self._fill_value, self.dtype) elif self.dtype.names is not None: self._fill_value = _check_fill_value(None, self.dtype) def __array_wrap__(self, obj, context=None, return_scalar=False): if obj is self: result = obj else: result = obj.view(type(self)) result._update_from(self) if context is not None: result._mask = result._mask.copy() (func, args, out_i) = context input_args = args[:func.nin] m = reduce(mask_or, [getmaskarray(arg) for arg in input_args]) domain = ufunc_domain.get(func) if domain is not None: with np.errstate(divide='ignore', invalid='ignore'): d = filled(domain(*input_args), True) if d.any(): try: fill_value = ufunc_fills[func][-1] except TypeError: fill_value = ufunc_fills[func] except KeyError: fill_value = self.fill_value np.copyto(result, fill_value, where=d) if m is nomask: m = d else: m = m | d if result is not self and result.shape == () and m: return masked else: result._mask = m result._sharedmask = False return result def view(self, dtype=None, type=None, fill_value=None): if dtype is None: if type is None: output = ndarray.view(self) else: output = ndarray.view(self, type) elif type is None: try: if issubclass(dtype, ndarray): output = ndarray.view(self, dtype) dtype = None else: output = ndarray.view(self, dtype) except TypeError: output = ndarray.view(self, dtype) else: output = ndarray.view(self, dtype, type) if getmask(output) is not nomask: output._mask = output._mask.view() if getattr(output, '_fill_value', None) is not None: if fill_value is None: if dtype is None: pass else: output._fill_value = None else: output.fill_value = fill_value return output def __getitem__(self, indx): dout = self.data[indx] _mask = self._mask def _is_scalar(m): return not isinstance(m, np.ndarray) def _scalar_heuristic(arr, elem): if not isinstance(elem, np.ndarray): return True elif arr.dtype.type is np.object_: if arr.dtype is not elem.dtype: return True elif type(arr).__getitem__ == ndarray.__getitem__: return False return None if _mask is not nomask: mout = _mask[indx] scalar_expected = _is_scalar(mout) else: mout = nomask scalar_expected = _scalar_heuristic(self.data, dout) if scalar_expected is None: scalar_expected = _is_scalar(getmaskarray(self)[indx]) if scalar_expected: if isinstance(dout, np.void): return mvoid(dout, mask=mout, hardmask=self._hardmask) elif self.dtype.type is np.object_ and isinstance(dout, np.ndarray) and (dout is not masked): if mout: return MaskedArray(dout, mask=True) else: return dout elif mout: return masked else: return dout else: dout = dout.view(type(self)) dout._update_from(self) if is_string_or_list_of_strings(indx): if self._fill_value is not None: dout._fill_value = self._fill_value[indx] if not isinstance(dout._fill_value, np.ndarray): raise RuntimeError('Internal NumPy error.') if dout._fill_value.ndim > 0: if not (dout._fill_value == dout._fill_value.flat[0]).all(): warnings.warn(f'Upon accessing multidimensional field {indx!s}, need to keep dimensionality of fill_value at 0. Discarding heterogeneous fill_value and setting all to {dout._fill_value[0]!s}.', stacklevel=2) dout._fill_value = dout._fill_value.flat[0:1].squeeze(axis=0) dout._isfield = True if mout is not nomask: dout._mask = reshape(mout, dout.shape) dout._sharedmask = True return dout @np.errstate(over='ignore', invalid='ignore') def __setitem__(self, indx, value): if self is masked: raise MaskError('Cannot alter the masked element.') _data = self._data _mask = self._mask if isinstance(indx, str): _data[indx] = value if _mask is nomask: self._mask = _mask = make_mask_none(self.shape, self.dtype) _mask[indx] = getmask(value) return _dtype = _data.dtype if value is masked: if _mask is nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) if _dtype.names is not None: _mask[indx] = tuple([True] * len(_dtype.names)) else: _mask[indx] = True return dval = getattr(value, '_data', value) mval = getmask(value) if _dtype.names is not None and mval is nomask: mval = tuple([False] * len(_dtype.names)) if _mask is nomask: _data[indx] = dval if mval is not nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) _mask[indx] = mval elif not self._hardmask: if isinstance(indx, masked_array) and (not isinstance(value, masked_array)): _data[indx.data] = dval else: _data[indx] = dval _mask[indx] = mval elif hasattr(indx, 'dtype') and indx.dtype == MaskType: indx = indx * umath.logical_not(_mask) _data[indx] = dval else: if _dtype.names is not None: err_msg = "Flexible 'hard' masks are not yet supported." raise NotImplementedError(err_msg) mindx = mask_or(_mask[indx], mval, copy=True) dindx = self._data[indx] if dindx.size > 1: np.copyto(dindx, dval, where=~mindx) elif mindx is nomask: dindx = dval _data[indx] = dindx _mask[indx] = mindx return @property def dtype(self): return super().dtype @dtype.setter def dtype(self, dtype): super(MaskedArray, type(self)).dtype.__set__(self, dtype) if self._mask is not nomask: self._mask = self._mask.view(make_mask_descr(dtype), ndarray) try: self._mask.shape = self.shape except (AttributeError, TypeError): pass @property def shape(self): return super().shape @shape.setter def shape(self, shape): super(MaskedArray, type(self)).shape.__set__(self, shape) if getmask(self) is not nomask: self._mask.shape = self.shape def __setmask__(self, mask, copy=False): idtype = self.dtype current_mask = self._mask if mask is masked: mask = True if current_mask is nomask: if mask is nomask: return current_mask = self._mask = make_mask_none(self.shape, idtype) if idtype.names is None: if self._hardmask: current_mask |= mask elif isinstance(mask, (int, float, np.bool, np.number)): current_mask[...] = mask else: current_mask.flat = mask else: mdtype = current_mask.dtype mask = np.asarray(mask) if not mask.ndim: if mask.dtype.kind == 'b': mask = np.array(tuple([mask.item()] * len(mdtype)), dtype=mdtype) else: mask = mask.astype(mdtype) else: try: copy = None if not copy else True mask = np.array(mask, copy=copy, dtype=mdtype) except TypeError: mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) if self._hardmask: for n in idtype.names: current_mask[n] |= mask[n] elif isinstance(mask, (int, float, np.bool, np.number)): current_mask[...] = mask else: current_mask.flat = mask if current_mask.shape: current_mask.shape = self.shape return _set_mask = __setmask__ @property def mask(self): return self._mask.view() @mask.setter def mask(self, value): self.__setmask__(value) @property def recordmask(self): _mask = self._mask.view(ndarray) if _mask.dtype.names is None: return _mask return np.all(flatten_structured_array(_mask), axis=-1) @recordmask.setter def recordmask(self, mask): raise NotImplementedError('Coming soon: setting the mask per records!') def harden_mask(self): self._hardmask = True return self def soften_mask(self): self._hardmask = False return self @property def hardmask(self): return self._hardmask def unshare_mask(self): if self._sharedmask: self._mask = self._mask.copy() self._sharedmask = False return self @property def sharedmask(self): return self._sharedmask def shrink_mask(self): self._mask = _shrink_mask(self._mask) return self @property def baseclass(self): return self._baseclass def _get_data(self): return ndarray.view(self, self._baseclass) _data = property(fget=_get_data) data = property(fget=_get_data) @property def flat(self): return MaskedIterator(self) @flat.setter def flat(self, value): y = self.ravel() y[:] = value @property def fill_value(self): if self._fill_value is None: self._fill_value = _check_fill_value(None, self.dtype) if isinstance(self._fill_value, ndarray): return self._fill_value[()] return self._fill_value @fill_value.setter def fill_value(self, value=None): target = _check_fill_value(value, self.dtype) if not target.ndim == 0: warnings.warn('Non-scalar arrays for the fill value are deprecated. Use arrays with scalar values instead. The filled function still supports any array as `fill_value`.', DeprecationWarning, stacklevel=2) _fill_value = self._fill_value if _fill_value is None: self._fill_value = target else: _fill_value[()] = target get_fill_value = fill_value.fget set_fill_value = fill_value.fset def filled(self, fill_value=None): m = self._mask if m is nomask: return self._data if fill_value is None: fill_value = self.fill_value else: fill_value = _check_fill_value(fill_value, self.dtype) if self is masked_singleton: return np.asanyarray(fill_value) if m.dtype.names is not None: result = self._data.copy('K') _recursive_filled(result, self._mask, fill_value) elif not m.any(): return self._data else: result = self._data.copy('K') try: np.copyto(result, fill_value, where=m) except (TypeError, AttributeError): fill_value = narray(fill_value, dtype=object) d = result.astype(object) result = np.choose(m, (d, fill_value)) except IndexError: if self._data.shape: raise elif m: result = np.array(fill_value, dtype=self.dtype) else: result = self._data return result def compressed(self): data = ndarray.ravel(self._data) if self._mask is not nomask: data = data.compress(np.logical_not(ndarray.ravel(self._mask))) return data def compress(self, condition, axis=None, out=None): (_data, _mask) = (self._data, self._mask) condition = np.asarray(condition) _new = _data.compress(condition, axis=axis, out=out).view(type(self)) _new._update_from(self) if _mask is not nomask: _new._mask = _mask.compress(condition, axis=axis) return _new def _insert_masked_print(self): if masked_print_option.enabled(): mask = self._mask if mask is nomask: res = self._data else: data = self._data print_width = self._print_width if self.ndim > 1 else self._print_width_1d for axis in range(self.ndim): if data.shape[axis] > print_width: ind = print_width // 2 arr = np.split(data, (ind, -ind), axis=axis) data = np.concatenate((arr[0], arr[2]), axis=axis) arr = np.split(mask, (ind, -ind), axis=axis) mask = np.concatenate((arr[0], arr[2]), axis=axis) rdtype = _replace_dtype_fields(self.dtype, 'O') res = data.astype(rdtype) _recursive_printoption(res, mask, masked_print_option) else: res = self.filled(self.fill_value) return res def __str__(self): return str(self._insert_masked_print()) def __repr__(self): if self._baseclass is np.ndarray: name = 'array' else: name = self._baseclass.__name__ if np._core.arrayprint._get_legacy_print_mode() <= 113: is_long = self.ndim > 1 parameters = dict(name=name, nlen=' ' * len(name), data=str(self), mask=str(self._mask), fill=str(self.fill_value), dtype=str(self.dtype)) is_structured = bool(self.dtype.names) key = '{}_{}'.format('long' if is_long else 'short', 'flx' if is_structured else 'std') return _legacy_print_templates[key] % parameters prefix = f'masked_{name}(' dtype_needed = not np._core.arrayprint.dtype_is_implied(self.dtype) or np.all(self.mask) or self.size == 0 keys = ['data', 'mask', 'fill_value'] if dtype_needed: keys.append('dtype') is_one_row = builtins.all((dim == 1 for dim in self.shape[:-1])) min_indent = 2 if is_one_row: indents = {} indents[keys[0]] = prefix for k in keys[1:]: n = builtins.max(min_indent, len(prefix + keys[0]) - len(k)) indents[k] = ' ' * n prefix = '' else: indents = {k: ' ' * min_indent for k in keys} prefix = prefix + '\n' reprs = {} reprs['data'] = np.array2string(self._insert_masked_print(), separator=', ', prefix=indents['data'] + 'data=', suffix=',') reprs['mask'] = np.array2string(self._mask, separator=', ', prefix=indents['mask'] + 'mask=', suffix=',') if self._fill_value is None: self.fill_value if self._fill_value.dtype.kind in ('S', 'U') and self.dtype.kind == self._fill_value.dtype.kind: fill_repr = repr(self.fill_value.item()) elif self._fill_value.dtype == self.dtype and (not self.dtype == object): fill_repr = str(self.fill_value) else: fill_repr = repr(self.fill_value) reprs['fill_value'] = fill_repr if dtype_needed: reprs['dtype'] = np._core.arrayprint.dtype_short_repr(self.dtype) result = ',\n'.join(('{}{}={}'.format(indents[k], k, reprs[k]) for k in keys)) return prefix + result + ')' def _delegate_binop(self, other): if isinstance(other, type(self)): return False array_ufunc = getattr(other, '__array_ufunc__', False) if array_ufunc is False: other_priority = getattr(other, '__array_priority__', -1000000) return self.__array_priority__ < other_priority else: return array_ufunc is None def _comparison(self, other, compare): omask = getmask(other) smask = self.mask mask = mask_or(smask, omask, copy=True) odata = getdata(other) if mask.dtype.names is not None: if compare not in (operator.eq, operator.ne): return NotImplemented broadcast_shape = np.broadcast(self, odata).shape sbroadcast = np.broadcast_to(self, broadcast_shape, subok=True) sbroadcast._mask = mask sdata = sbroadcast.filled(odata) mask = mask == np.ones((), mask.dtype) if omask is np.False_: omask = np.zeros((), smask.dtype) else: sdata = self.data check = compare(sdata, odata) if isinstance(check, (np.bool, bool)): return masked if mask else check if mask is not nomask: if compare in (operator.eq, operator.ne): check = np.where(mask, compare(smask, omask), check) if mask.shape != check.shape: mask = np.broadcast_to(mask, check.shape).copy() check = check.view(type(self)) check._update_from(self) check._mask = mask if check._fill_value is not None: try: fill = _check_fill_value(check._fill_value, np.bool) except (TypeError, ValueError): fill = _check_fill_value(None, np.bool) check._fill_value = fill return check def __eq__(self, other): return self._comparison(other, operator.eq) def __ne__(self, other): return self._comparison(other, operator.ne) def __le__(self, other): return self._comparison(other, operator.le) def __lt__(self, other): return self._comparison(other, operator.lt) def __ge__(self, other): return self._comparison(other, operator.ge) def __gt__(self, other): return self._comparison(other, operator.gt) def __add__(self, other): if self._delegate_binop(other): return NotImplemented return add(self, other) def __radd__(self, other): return add(other, self) def __sub__(self, other): if self._delegate_binop(other): return NotImplemented return subtract(self, other) def __rsub__(self, other): return subtract(other, self) def __mul__(self, other): if self._delegate_binop(other): return NotImplemented return multiply(self, other) def __rmul__(self, other): return multiply(other, self) def __div__(self, other): if self._delegate_binop(other): return NotImplemented return divide(self, other) def __truediv__(self, other): if self._delegate_binop(other): return NotImplemented return true_divide(self, other) def __rtruediv__(self, other): return true_divide(other, self) def __floordiv__(self, other): if self._delegate_binop(other): return NotImplemented return floor_divide(self, other) def __rfloordiv__(self, other): return floor_divide(other, self) def __pow__(self, other): if self._delegate_binop(other): return NotImplemented return power(self, other) def __rpow__(self, other): return power(other, self) def __iadd__(self, other): m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(0), other_data) self._data.__iadd__(other_data) return self def __isub__(self, other): m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(0), other_data) self._data.__isub__(other_data) return self def __imul__(self, other): m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__imul__(other_data) return self def __idiv__(self, other): other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) if dom_mask.any(): (_, fval) = ufunc_fills[np.divide] other_data = np.where(dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__idiv__(other_data) return self def __ifloordiv__(self, other): other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) if dom_mask.any(): (_, fval) = ufunc_fills[np.floor_divide] other_data = np.where(dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__ifloordiv__(other_data) return self def __itruediv__(self, other): other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) if dom_mask.any(): (_, fval) = ufunc_fills[np.true_divide] other_data = np.where(dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__itruediv__(other_data) return self def __ipow__(self, other): other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(1), other_data) other_mask = getmask(other) with np.errstate(divide='ignore', invalid='ignore'): self._data.__ipow__(other_data) invalid = np.logical_not(np.isfinite(self._data)) if invalid.any(): if self._mask is not nomask: self._mask |= invalid else: self._mask = invalid np.copyto(self._data, self.fill_value, where=invalid) new_mask = mask_or(other_mask, invalid) self._mask = mask_or(self._mask, new_mask) return self def __float__(self): if self.size > 1: raise TypeError('Only length-1 arrays can be converted to Python scalars') elif self._mask: warnings.warn('Warning: converting a masked element to nan.', stacklevel=2) return np.nan return float(self.item()) def __int__(self): if self.size > 1: raise TypeError('Only length-1 arrays can be converted to Python scalars') elif self._mask: raise MaskError('Cannot convert masked element to a Python int.') return int(self.item()) @property def imag(self): result = self._data.imag.view(type(self)) result.__setmask__(self._mask) return result get_imag = imag.fget @property def real(self): result = self._data.real.view(type(self)) result.__setmask__(self._mask) return result get_real = real.fget def count(self, axis=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} m = self._mask if isinstance(self.data, np.matrix): if m is nomask: m = np.zeros(self.shape, dtype=np.bool) m = m.view(type(self.data)) if m is nomask: if self.shape == (): if axis not in (None, 0): raise np.exceptions.AxisError(axis=axis, ndim=self.ndim) return 1 elif axis is None: if kwargs.get('keepdims', False): return np.array(self.size, dtype=np.intp, ndmin=self.ndim) return self.size axes = normalize_axis_tuple(axis, self.ndim) items = 1 for ax in axes: items *= self.shape[ax] if kwargs.get('keepdims', False): out_dims = list(self.shape) for a in axes: out_dims[a] = 1 else: out_dims = [d for (n, d) in enumerate(self.shape) if n not in axes] return np.full(out_dims, items, dtype=np.intp) if self is masked: return 0 return (~m).sum(axis=axis, dtype=np.intp, **kwargs) def ravel(self, order='C'): if order in 'kKaA': order = 'F' if self._data.flags.fnc else 'C' r = ndarray.ravel(self._data, order=order).view(type(self)) r._update_from(self) if self._mask is not nomask: r._mask = ndarray.ravel(self._mask, order=order).reshape(r.shape) else: r._mask = nomask return r def reshape(self, *s, **kwargs): kwargs.update(order=kwargs.get('order', 'C')) result = self._data.reshape(*s, **kwargs).view(type(self)) result._update_from(self) mask = self._mask if mask is not nomask: result._mask = mask.reshape(*s, **kwargs) return result def resize(self, newshape, refcheck=True, order=False): errmsg = 'A masked array does not own its data and therefore cannot be resized.\nUse the numpy.ma.resize function instead.' raise ValueError(errmsg) def put(self, indices, values, mode='raise'): if self._hardmask and self._mask is not nomask: mask = self._mask[indices] indices = narray(indices, copy=None) values = narray(values, copy=None, subok=True) values.resize(indices.shape) indices = indices[~mask] values = values[~mask] self._data.put(indices, values, mode=mode) if self._mask is nomask and getmask(values) is nomask: return m = getmaskarray(self) if getmask(values) is nomask: m.put(indices, False, mode=mode) else: m.put(indices, values._mask, mode=mode) m = make_mask(m, copy=False, shrink=True) self._mask = m return def ids(self): if self._mask is nomask: return (self.ctypes.data, id(nomask)) return (self.ctypes.data, self._mask.ctypes.data) def iscontiguous(self): return self.flags['CONTIGUOUS'] def all(self, axis=None, out=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} mask = _check_mask_axis(self._mask, axis, **kwargs) if out is None: d = self.filled(True).all(axis=axis, **kwargs).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: return masked return d self.filled(True).all(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out def any(self, axis=None, out=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} mask = _check_mask_axis(self._mask, axis, **kwargs) if out is None: d = self.filled(False).any(axis=axis, **kwargs).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: d = masked return d self.filled(False).any(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out def nonzero(self): return np.asarray(self.filled(0)).nonzero() def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): m = self._mask if m is nomask: result = super().trace(offset=offset, axis1=axis1, axis2=axis2, out=out) return result.astype(dtype) else: D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2) return D.astype(dtype).filled(0).sum(axis=-1, out=out) trace.__doc__ = ndarray.trace.__doc__ def dot(self, b, out=None, strict=False): return dot(self, b, out=out, strict=strict) def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) if out is None: result = self.filled(0).sum(axis, dtype=dtype, **kwargs) rndim = getattr(result, 'ndim', 0) if rndim: result = result.view(type(self)) result.__setmask__(newmask) elif newmask: result = masked return result result = self.filled(0).sum(axis, dtype=dtype, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask return out def cumsum(self, axis=None, dtype=None, out=None): result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(self.mask) return out result = result.view(type(self)) result.__setmask__(self._mask) return result def prod(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) if out is None: result = self.filled(1).prod(axis, dtype=dtype, **kwargs) rndim = getattr(result, 'ndim', 0) if rndim: result = result.view(type(self)) result.__setmask__(newmask) elif newmask: result = masked return result result = self.filled(1).prod(axis, dtype=dtype, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask return out product = prod def cumprod(self, axis=None, dtype=None, out=None): result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(self._mask) return out result = result.view(type(self)) result.__setmask__(self._mask) return result def mean(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} if self._mask is nomask: result = super().mean(axis=axis, dtype=dtype, **kwargs)[()] else: is_float16_result = False if dtype is None: if issubclass(self.dtype.type, (ntypes.integer, ntypes.bool)): dtype = mu.dtype('f8') elif issubclass(self.dtype.type, ntypes.float16): dtype = mu.dtype('f4') is_float16_result = True dsum = self.sum(axis=axis, dtype=dtype, **kwargs) cnt = self.count(axis=axis, **kwargs) if cnt.shape == () and cnt == 0: result = masked elif is_float16_result: result = self.dtype.type(dsum * 1.0 / cnt) else: result = dsum * 1.0 / cnt if out is not None: out.flat = result if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = getmask(result) return out return result def anom(self, axis=None, dtype=None): m = self.mean(axis, dtype) if not axis: return self - m else: return self - expand_dims(m, axis) def var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, mean=np._NoValue): kwargs = {} if keepdims is not np._NoValue: kwargs['keepdims'] = keepdims if self._mask is nomask: if mean is not np._NoValue: kwargs['mean'] = mean ret = super().var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)[()] if out is not None: if isinstance(out, MaskedArray): out.__setmask__(nomask) return out return ret cnt = self.count(axis=axis, **kwargs) - ddof if mean is not np._NoValue: danom = self - mean else: danom = self - self.mean(axis, dtype, keepdims=True) if iscomplexobj(self): danom = umath.absolute(danom) ** 2 else: danom *= danom dvar = divide(danom.sum(axis, **kwargs), cnt).view(type(self)) if dvar.ndim: dvar._mask = mask_or(self._mask.all(axis, **kwargs), cnt <= 0) dvar._update_from(self) elif getmask(dvar): dvar = masked if out is not None: if isinstance(out, MaskedArray): out.flat = 0 out.__setmask__(True) elif out.dtype.kind in 'biu': errmsg = 'Masked data information would be lost in one or more location.' raise MaskError(errmsg) else: out.flat = np.nan return out if out is not None: out.flat = dvar if isinstance(out, MaskedArray): out.__setmask__(dvar.mask) return out return dvar var.__doc__ = np.var.__doc__ def std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, mean=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} dvar = self.var(axis, dtype, out, ddof, **kwargs) if dvar is not masked: if out is not None: np.power(out, 0.5, out=out, casting='unsafe') return out dvar = sqrt(dvar) return dvar def round(self, decimals=0, out=None): result = self._data.round(decimals=decimals, out=out).view(type(self)) if result.ndim > 0: result._mask = self._mask result._update_from(self) elif self._mask: result = masked if out is None: return result if isinstance(out, MaskedArray): out.__setmask__(self._mask) return out def argsort(self, axis=np._NoValue, kind=None, order=None, endwith=True, fill_value=None, *, stable=False): if stable: raise ValueError('`stable` parameter is not supported for masked arrays.') if axis is np._NoValue: axis = _deprecate_argsort_axis(self) if fill_value is None: if endwith: if np.issubdtype(self.dtype, np.floating): fill_value = np.nan else: fill_value = minimum_fill_value(self) else: fill_value = maximum_fill_value(self) filled = self.filled(fill_value) return filled.argsort(axis=axis, kind=kind, order=order) def argmin(self, axis=None, fill_value=None, out=None, *, keepdims=np._NoValue): if fill_value is None: fill_value = minimum_fill_value(self) d = self.filled(fill_value).view(ndarray) keepdims = False if keepdims is np._NoValue else bool(keepdims) return d.argmin(axis, out=out, keepdims=keepdims) def argmax(self, axis=None, fill_value=None, out=None, *, keepdims=np._NoValue): if fill_value is None: fill_value = maximum_fill_value(self._data) d = self.filled(fill_value).view(ndarray) keepdims = False if keepdims is np._NoValue else bool(keepdims) return d.argmax(axis, out=out, keepdims=keepdims) def sort(self, axis=-1, kind=None, order=None, endwith=True, fill_value=None, *, stable=False): if stable: raise ValueError('`stable` parameter is not supported for masked arrays.') if self._mask is nomask: ndarray.sort(self, axis=axis, kind=kind, order=order) return if self is masked: return sidx = self.argsort(axis=axis, kind=kind, order=order, fill_value=fill_value, endwith=endwith) self[...] = np.take_along_axis(self, sidx, axis=axis) def min(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) if fill_value is None: fill_value = minimum_fill_value(self) if out is None: result = self.filled(fill_value).min(axis=axis, out=out, **kwargs).view(type(self)) if result.ndim: result.__setmask__(newmask) if newmask.ndim: np.copyto(result, result.fill_value, where=newmask) elif newmask: result = masked return result result = self.filled(fill_value).min(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask else: if out.dtype.kind in 'biu': errmsg = 'Masked data information would be lost in one or more location.' raise MaskError(errmsg) np.copyto(out, np.nan, where=newmask) return out def max(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) if fill_value is None: fill_value = maximum_fill_value(self) if out is None: result = self.filled(fill_value).max(axis=axis, out=out, **kwargs).view(type(self)) if result.ndim: result.__setmask__(newmask) if newmask.ndim: np.copyto(result, result.fill_value, where=newmask) elif newmask: result = masked return result result = self.filled(fill_value).max(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask else: if out.dtype.kind in 'biu': errmsg = 'Masked data information would be lost in one or more location.' raise MaskError(errmsg) np.copyto(out, np.nan, where=newmask) return out def ptp(self, axis=None, out=None, fill_value=None, keepdims=False): if out is None: result = self.max(axis=axis, fill_value=fill_value, keepdims=keepdims) result -= self.min(axis=axis, fill_value=fill_value, keepdims=keepdims) return result out.flat = self.max(axis=axis, out=out, fill_value=fill_value, keepdims=keepdims) min_value = self.min(axis=axis, fill_value=fill_value, keepdims=keepdims) np.subtract(out, min_value, out=out, casting='unsafe') return out def partition(self, *args, **kwargs): warnings.warn(f"Warning: 'partition' will ignore the 'mask' of the {self.__class__.__name__}.", stacklevel=2) return super().partition(*args, **kwargs) def argpartition(self, *args, **kwargs): warnings.warn(f"Warning: 'argpartition' will ignore the 'mask' of the {self.__class__.__name__}.", stacklevel=2) return super().argpartition(*args, **kwargs) def take(self, indices, axis=None, out=None, mode='raise'): (_data, _mask) = (self._data, self._mask) cls = type(self) maskindices = getmask(indices) if maskindices is not nomask: indices = indices.filled(0) if out is None: out = _data.take(indices, axis=axis, mode=mode)[...].view(cls) else: np.take(_data, indices, axis=axis, mode=mode, out=out) if isinstance(out, MaskedArray): if _mask is nomask: outmask = maskindices else: outmask = _mask.take(indices, axis=axis, mode=mode) outmask |= maskindices out.__setmask__(outmask) return out[()] copy = _arraymethod('copy') diagonal = _arraymethod('diagonal') flatten = _arraymethod('flatten') repeat = _arraymethod('repeat') squeeze = _arraymethod('squeeze') swapaxes = _arraymethod('swapaxes') T = property(fget=lambda self: self.transpose()) transpose = _arraymethod('transpose') @property def mT(self): if self.ndim < 2: raise ValueError('matrix transpose with ndim < 2 is undefined') if self._mask is nomask: return masked_array(data=self._data.mT) else: return masked_array(data=self.data.mT, mask=self.mask.mT) def tolist(self, fill_value=None): _mask = self._mask if _mask is nomask: return self._data.tolist() if fill_value is not None: return self.filled(fill_value).tolist() names = self.dtype.names if names: result = self._data.astype([(_, object) for _ in names]) for n in names: result[n][_mask[n]] = None return result.tolist() if _mask is nomask: return [None] inishape = self.shape result = np.array(self._data.ravel(), dtype=object) result[_mask.ravel()] = None result.shape = inishape return result.tolist() def tostring(self, fill_value=None, order='C'): warnings.warn('tostring() is deprecated. Use tobytes() instead.', DeprecationWarning, stacklevel=2) return self.tobytes(fill_value, order=order) def tobytes(self, fill_value=None, order='C'): return self.filled(fill_value).tobytes(order=order) def tofile(self, fid, sep='', format='%s'): raise NotImplementedError('MaskedArray.tofile() not implemented yet.') def toflex(self): ddtype = self.dtype _mask = self._mask if _mask is None: _mask = make_mask_none(self.shape, ddtype) mdtype = self._mask.dtype record = np.ndarray(shape=self.shape, dtype=[('_data', ddtype), ('_mask', mdtype)]) record['_data'] = self._data record['_mask'] = self._mask return record torecords = toflex def __getstate__(self): cf = 'CF'[self.flags.fnc] data_state = super().__reduce__()[2] return data_state + (getmaskarray(self).tobytes(cf), self._fill_value) def __setstate__(self, state): (_, shp, typ, isf, raw, msk, flv) = state super().__setstate__((shp, typ, isf, raw)) self._mask.__setstate__((shp, make_mask_descr(typ), isf, msk)) self.fill_value = flv def __reduce__(self): return (_mareconstruct, (self.__class__, self._baseclass, (0,), 'b'), self.__getstate__()) def __deepcopy__(self, memo=None): from copy import deepcopy copied = MaskedArray.__new__(type(self), self, copy=True) if memo is None: memo = {} memo[id(self)] = copied for (k, v) in self.__dict__.items(): copied.__dict__[k] = deepcopy(v, memo) if self.dtype.hasobject: copied._data[...] = deepcopy(copied._data) return copied def _mareconstruct(subtype, baseclass, baseshape, basetype): _data = ndarray.__new__(baseclass, baseshape, basetype) _mask = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype)) return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype) class mvoid(MaskedArray): def __new__(self, data, mask=nomask, dtype=None, fill_value=None, hardmask=False, copy=False, subok=True): copy = None if not copy else True _data = np.array(data, copy=copy, subok=subok, dtype=dtype) _data = _data.view(self) _data._hardmask = hardmask if mask is not nomask: if isinstance(mask, np.void): _data._mask = mask else: try: _data._mask = np.void(mask) except TypeError: mdtype = make_mask_descr(dtype) _data._mask = np.array(mask, dtype=mdtype)[()] if fill_value is not None: _data.fill_value = fill_value return _data @property def _data(self): return super()._data[()] def __getitem__(self, indx): m = self._mask if isinstance(m[indx], ndarray): return masked_array(data=self._data[indx], mask=m[indx], fill_value=self._fill_value[indx], hard_mask=self._hardmask) if m is not nomask and m[indx]: return masked return self._data[indx] def __setitem__(self, indx, value): self._data[indx] = value if self._hardmask: self._mask[indx] |= getattr(value, '_mask', False) else: self._mask[indx] = getattr(value, '_mask', False) def __str__(self): m = self._mask if m is nomask: return str(self._data) rdtype = _replace_dtype_fields(self._data.dtype, 'O') data_arr = super()._data res = data_arr.astype(rdtype) _recursive_printoption(res, self._mask, masked_print_option) return str(res) __repr__ = __str__ def __iter__(self): (_data, _mask) = (self._data, self._mask) if _mask is nomask: yield from _data else: for (d, m) in zip(_data, _mask): if m: yield masked else: yield d def __len__(self): return self._data.__len__() def filled(self, fill_value=None): return asarray(self).filled(fill_value)[()] def tolist(self): _mask = self._mask if _mask is nomask: return self._data.tolist() result = [] for (d, m) in zip(self._data, self._mask): if m: result.append(None) else: result.append(d.item()) return tuple(result) def isMaskedArray(x): return isinstance(x, MaskedArray) isarray = isMaskedArray isMA = isMaskedArray class MaskedConstant(MaskedArray): __singleton = None @classmethod def __has_singleton(cls): return cls.__singleton is not None and type(cls.__singleton) is cls def __new__(cls): if not cls.__has_singleton(): data = np.array(0.0) mask = np.array(True) data.flags.writeable = False mask.flags.writeable = False cls.__singleton = MaskedArray(data, mask=mask).view(cls) return cls.__singleton def __array_finalize__(self, obj): if not self.__has_singleton(): return super().__array_finalize__(obj) elif self is self.__singleton: pass else: self.__class__ = MaskedArray MaskedArray.__array_finalize__(self, obj) def __array_wrap__(self, obj, context=None, return_scalar=False): return self.view(MaskedArray).__array_wrap__(obj, context) def __str__(self): return str(masked_print_option._display) def __repr__(self): if self is MaskedConstant.__singleton: return 'masked' else: return object.__repr__(self) def __format__(self, format_spec): try: return object.__format__(self, format_spec) except TypeError: warnings.warn('Format strings passed to MaskedConstant are ignored, but in future may error or produce different behavior', FutureWarning, stacklevel=2) return object.__format__(self, '') def __reduce__(self): return (self.__class__, ()) def __iop__(self, other): return self __iadd__ = __isub__ = __imul__ = __ifloordiv__ = __itruediv__ = __ipow__ = __iop__ del __iop__ def copy(self, *args, **kwargs): return self def __copy__(self): return self def __deepcopy__(self, memo): return self def __setattr__(self, attr, value): if not self.__has_singleton(): return super().__setattr__(attr, value) elif self is self.__singleton: raise AttributeError(f'attributes of {self!r} are not writeable') else: return super().__setattr__(attr, value) masked = masked_singleton = MaskedConstant() masked_array = MaskedArray def array(data, dtype=None, copy=False, order=None, mask=nomask, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0): return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok, keep_mask=keep_mask, hard_mask=hard_mask, fill_value=fill_value, ndmin=ndmin, shrink=shrink, order=order) array.__doc__ = masked_array.__doc__ def is_masked(x): m = getmask(x) if m is nomask: return False elif m.any(): return True return False class _extrema_operation(_MaskedUFunc): def __init__(self, ufunc, compare, fill_value): super().__init__(ufunc) self.compare = compare self.fill_value_func = fill_value def __call__(self, a, b): return where(self.compare(a, b), a, b) def reduce(self, target, axis=np._NoValue): target = narray(target, copy=None, subok=True) m = getmask(target) if axis is np._NoValue and target.ndim > 1: warnings.warn(f'In the future the default for ma.{self.__name__}.reduce will be axis=0, not the current None, to match np.{self.__name__}.reduce. Explicitly pass 0 or None to silence this warning.', MaskedArrayFutureWarning, stacklevel=2) axis = None if axis is not np._NoValue: kwargs = dict(axis=axis) else: kwargs = dict() if m is nomask: t = self.f.reduce(target, **kwargs) else: target = target.filled(self.fill_value_func(target)).view(type(target)) t = self.f.reduce(target, **kwargs) m = umath.logical_and.reduce(m, **kwargs) if hasattr(t, '_mask'): t._mask = m elif m: t = masked return t def outer(self, a, b): ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: m = nomask else: ma = getmaskarray(a) mb = getmaskarray(b) m = logical_or.outer(ma, mb) result = self.f.outer(filled(a), filled(b)) if not isinstance(result, MaskedArray): result = result.view(MaskedArray) result._mask = m return result def min(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} try: return obj.min(axis=axis, fill_value=fill_value, out=out, **kwargs) except (AttributeError, TypeError): return asanyarray(obj).min(axis=axis, fill_value=fill_value, out=out, **kwargs) min.__doc__ = MaskedArray.min.__doc__ def max(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} try: return obj.max(axis=axis, fill_value=fill_value, out=out, **kwargs) except (AttributeError, TypeError): return asanyarray(obj).max(axis=axis, fill_value=fill_value, out=out, **kwargs) max.__doc__ = MaskedArray.max.__doc__ def ptp(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} try: return obj.ptp(axis, out=out, fill_value=fill_value, **kwargs) except (AttributeError, TypeError): return asanyarray(obj).ptp(axis=axis, fill_value=fill_value, out=out, **kwargs) ptp.__doc__ = MaskedArray.ptp.__doc__ class _frommethod: def __init__(self, methodname, reversed=False): self.__name__ = methodname self.__doc__ = self.getdoc() self.reversed = reversed def getdoc(self): meth = getattr(MaskedArray, self.__name__, None) or getattr(np, self.__name__, None) signature = self.__name__ + get_object_signature(meth) if meth is not None: doc = ' %s\n%s' % (signature, getattr(meth, '__doc__', None)) return doc def __call__(self, a, *args, **params): if self.reversed: args = list(args) (a, args[0]) = (args[0], a) marr = asanyarray(a) method_name = self.__name__ method = getattr(type(marr), method_name, None) if method is None: method = getattr(np, method_name) return method(marr, *args, **params) all = _frommethod('all') anomalies = anom = _frommethod('anom') any = _frommethod('any') compress = _frommethod('compress', reversed=True) cumprod = _frommethod('cumprod') cumsum = _frommethod('cumsum') copy = _frommethod('copy') diagonal = _frommethod('diagonal') harden_mask = _frommethod('harden_mask') ids = _frommethod('ids') maximum = _extrema_operation(umath.maximum, greater, maximum_fill_value) mean = _frommethod('mean') minimum = _extrema_operation(umath.minimum, less, minimum_fill_value) nonzero = _frommethod('nonzero') prod = _frommethod('prod') product = _frommethod('prod') ravel = _frommethod('ravel') repeat = _frommethod('repeat') shrink_mask = _frommethod('shrink_mask') soften_mask = _frommethod('soften_mask') std = _frommethod('std') sum = _frommethod('sum') swapaxes = _frommethod('swapaxes') trace = _frommethod('trace') var = _frommethod('var') count = _frommethod('count') def take(a, indices, axis=None, out=None, mode='raise'): a = masked_array(a) return a.take(indices, axis=axis, out=out, mode=mode) def power(a, b, third=None): if third is not None: raise MaskError('3-argument power not supported.') ma = getmask(a) mb = getmask(b) m = mask_or(ma, mb) fa = getdata(a) fb = getdata(b) if isinstance(a, MaskedArray): basetype = type(a) else: basetype = MaskedArray with np.errstate(divide='ignore', invalid='ignore'): result = np.where(m, fa, umath.power(fa, fb)).view(basetype) result._update_from(a) invalid = np.logical_not(np.isfinite(result.view(ndarray))) if m is not nomask: if not result.ndim: return masked result._mask = np.logical_or(m, invalid) if invalid.any(): if not result.ndim: return masked elif result._mask is nomask: result._mask = invalid result._data[invalid] = result.fill_value return result argmin = _frommethod('argmin') argmax = _frommethod('argmax') def argsort(a, axis=np._NoValue, kind=None, order=None, endwith=True, fill_value=None, *, stable=None): a = np.asanyarray(a) if axis is np._NoValue: axis = _deprecate_argsort_axis(a) if isinstance(a, MaskedArray): return a.argsort(axis=axis, kind=kind, order=order, endwith=endwith, fill_value=fill_value, stable=None) else: return a.argsort(axis=axis, kind=kind, order=order, stable=None) argsort.__doc__ = MaskedArray.argsort.__doc__ def sort(a, axis=-1, kind=None, order=None, endwith=True, fill_value=None, *, stable=None): a = np.array(a, copy=True, subok=True) if axis is None: a = a.flatten() axis = 0 if isinstance(a, MaskedArray): a.sort(axis=axis, kind=kind, order=order, endwith=endwith, fill_value=fill_value, stable=stable) else: a.sort(axis=axis, kind=kind, order=order, stable=stable) return a def compressed(x): return asanyarray(x).compressed() def concatenate(arrays, axis=0): d = np.concatenate([getdata(a) for a in arrays], axis) rcls = get_masked_subclass(*arrays) data = d.view(rcls) for x in arrays: if getmask(x) is not nomask: break else: return data dm = np.concatenate([getmaskarray(a) for a in arrays], axis) dm = dm.reshape(d.shape) data._mask = _shrink_mask(dm) return data def diag(v, k=0): output = np.diag(v, k).view(MaskedArray) if getmask(v) is not nomask: output._mask = np.diag(v._mask, k) return output def left_shift(a, n): m = getmask(a) if m is nomask: d = umath.left_shift(filled(a), n) return masked_array(d) else: d = umath.left_shift(filled(a, 0), n) return masked_array(d, mask=m) def right_shift(a, n): m = getmask(a) if m is nomask: d = umath.right_shift(filled(a), n) return masked_array(d) else: d = umath.right_shift(filled(a, 0), n) return masked_array(d, mask=m) def put(a, indices, values, mode='raise'): try: return a.put(indices, values, mode=mode) except AttributeError: return np.asarray(a).put(indices, values, mode=mode) def putmask(a, mask, values): if not isinstance(a, MaskedArray): a = a.view(MaskedArray) (valdata, valmask) = (getdata(values), getmask(values)) if getmask(a) is nomask: if valmask is not nomask: a._sharedmask = True a._mask = make_mask_none(a.shape, a.dtype) np.copyto(a._mask, valmask, where=mask) elif a._hardmask: if valmask is not nomask: m = a._mask.copy() np.copyto(m, valmask, where=mask) a.mask |= m else: if valmask is nomask: valmask = getmaskarray(values) np.copyto(a._mask, valmask, where=mask) np.copyto(a._data, valdata, where=mask) return def transpose(a, axes=None): try: return a.transpose(axes) except AttributeError: return np.asarray(a).transpose(axes).view(MaskedArray) def reshape(a, new_shape, order='C'): try: return a.reshape(new_shape, order=order) except AttributeError: _tmp = np.asarray(a).reshape(new_shape, order=order) return _tmp.view(MaskedArray) def resize(x, new_shape): m = getmask(x) if m is not nomask: m = np.resize(m, new_shape) result = np.resize(x, new_shape).view(get_masked_subclass(x)) if result.ndim: result._mask = m return result def ndim(obj): return np.ndim(getdata(obj)) ndim.__doc__ = np.ndim.__doc__ def shape(obj): return np.shape(getdata(obj)) shape.__doc__ = np.shape.__doc__ def size(obj, axis=None): return np.size(getdata(obj), axis) size.__doc__ = np.size.__doc__ def diff(a, /, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): if n == 0: return a if n < 0: raise ValueError('order must be non-negative but got ' + repr(n)) a = np.ma.asanyarray(a) if a.ndim == 0: raise ValueError('diff requires input that is at least one dimensional') combined = [] if prepend is not np._NoValue: prepend = np.ma.asanyarray(prepend) if prepend.ndim == 0: shape = list(a.shape) shape[axis] = 1 prepend = np.broadcast_to(prepend, tuple(shape)) combined.append(prepend) combined.append(a) if append is not np._NoValue: append = np.ma.asanyarray(append) if append.ndim == 0: shape = list(a.shape) shape[axis] = 1 append = np.broadcast_to(append, tuple(shape)) combined.append(append) if len(combined) > 1: a = np.ma.concatenate(combined, axis) return np.diff(a, n, axis) def where(condition, x=_NoValue, y=_NoValue): missing = (x is _NoValue, y is _NoValue).count(True) if missing == 1: raise ValueError("Must provide both 'x' and 'y' or neither.") if missing == 2: return nonzero(condition) cf = filled(condition, False) xd = getdata(x) yd = getdata(y) cm = getmaskarray(condition) xm = getmaskarray(x) ym = getmaskarray(y) if x is masked and y is not masked: xd = np.zeros((), dtype=yd.dtype) xm = np.ones((), dtype=ym.dtype) elif y is masked and x is not masked: yd = np.zeros((), dtype=xd.dtype) ym = np.ones((), dtype=xm.dtype) data = np.where(cf, xd, yd) mask = np.where(cf, xm, ym) mask = np.where(cm, np.ones((), dtype=mask.dtype), mask) mask = _shrink_mask(mask) return masked_array(data, mask=mask) def choose(indices, choices, out=None, mode='raise'): def fmask(x): if x is masked: return True return filled(x) def nmask(x): if x is masked: return True return getmask(x) c = filled(indices, 0) masks = [nmask(x) for x in choices] data = [fmask(x) for x in choices] outputmask = np.choose(c, masks, mode=mode) outputmask = make_mask(mask_or(outputmask, getmask(indices)), copy=False, shrink=True) d = np.choose(c, data, mode=mode, out=out).view(MaskedArray) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(outputmask) return out d.__setmask__(outputmask) return d def round_(a, decimals=0, out=None): if out is None: return np.round(a, decimals, out) else: np.round(getdata(a), decimals, out) if hasattr(out, '_mask'): out._mask = getmask(a) return out round = round_ def _mask_propagate(a, axis): a = array(a, subok=False) m = getmask(a) if m is nomask or not m.any() or axis is None: return a a._mask = a._mask.copy() axes = normalize_axis_tuple(axis, a.ndim) for ax in axes: a._mask |= m.any(axis=ax, keepdims=True) return a def dot(a, b, strict=False, out=None): if strict is True: if np.ndim(a) == 0 or np.ndim(b) == 0: pass elif b.ndim == 1: a = _mask_propagate(a, a.ndim - 1) b = _mask_propagate(b, b.ndim - 1) else: a = _mask_propagate(a, a.ndim - 1) b = _mask_propagate(b, b.ndim - 2) am = ~getmaskarray(a) bm = ~getmaskarray(b) if out is None: d = np.dot(filled(a, 0), filled(b, 0)) m = ~np.dot(am, bm) if np.ndim(d) == 0: d = np.asarray(d) r = d.view(get_masked_subclass(a, b)) r.__setmask__(m) return r else: d = np.dot(filled(a, 0), filled(b, 0), out._data) if out.mask.shape != d.shape: out._mask = np.empty(d.shape, MaskType) np.dot(am, bm, out._mask) np.logical_not(out._mask, out._mask) return out def inner(a, b): fa = filled(a, 0) fb = filled(b, 0) if fa.ndim == 0: fa.shape = (1,) if fb.ndim == 0: fb.shape = (1,) return np.inner(fa, fb).view(MaskedArray) inner.__doc__ = doc_note(np.inner.__doc__, 'Masked values are replaced by 0.') innerproduct = inner def outer(a, b): fa = filled(a, 0).ravel() fb = filled(b, 0).ravel() d = np.outer(fa, fb) ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: return masked_array(d) ma = getmaskarray(a) mb = getmaskarray(b) m = make_mask(1 - np.outer(1 - ma, 1 - mb), copy=False) return masked_array(d, mask=m) outer.__doc__ = doc_note(np.outer.__doc__, 'Masked values are replaced by 0.') outerproduct = outer def _convolve_or_correlate(f, a, v, mode, propagate_mask): if propagate_mask: mask = f(getmaskarray(a), np.ones(np.shape(v), dtype=bool), mode=mode) | f(np.ones(np.shape(a), dtype=bool), getmaskarray(v), mode=mode) data = f(getdata(a), getdata(v), mode=mode) else: mask = ~f(~getmaskarray(a), ~getmaskarray(v), mode=mode) data = f(filled(a, 0), filled(v, 0), mode=mode) return masked_array(data, mask=mask) def correlate(a, v, mode='valid', propagate_mask=True): return _convolve_or_correlate(np.correlate, a, v, mode, propagate_mask) def convolve(a, v, mode='full', propagate_mask=True): return _convolve_or_correlate(np.convolve, a, v, mode, propagate_mask) def allequal(a, b, fill_value=True): m = mask_or(getmask(a), getmask(b)) if m is nomask: x = getdata(a) y = getdata(b) d = umath.equal(x, y) return d.all() elif fill_value: x = getdata(a) y = getdata(b) d = umath.equal(x, y) dm = array(d, mask=m, copy=False) return dm.filled(True).all(None) else: return False def allclose(a, b, masked_equal=True, rtol=1e-05, atol=1e-08): x = masked_array(a, copy=False) y = masked_array(b, copy=False) if y.dtype.kind != 'm': dtype = np.result_type(y, 1.0) if y.dtype != dtype: y = masked_array(y, dtype=dtype, copy=False) m = mask_or(getmask(x), getmask(y)) xinf = np.isinf(masked_array(x, copy=False, mask=m)).filled(False) if not np.all(xinf == filled(np.isinf(y), False)): return False if not np.any(xinf): d = filled(less_equal(absolute(x - y), atol + rtol * absolute(y)), masked_equal) return np.all(d) if not np.all(filled(x[xinf] == y[xinf], masked_equal)): return False x = x[~xinf] y = y[~xinf] d = filled(less_equal(absolute(x - y), atol + rtol * absolute(y)), masked_equal) return np.all(d) def asarray(a, dtype=None, order=None): order = order or 'C' return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=False, order=order) def asanyarray(a, dtype=None): if isinstance(a, MaskedArray) and (dtype is None or dtype == a.dtype): return a return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True) def fromfile(file, dtype=float, count=-1, sep=''): raise NotImplementedError('fromfile() not yet implemented for a MaskedArray.') def fromflex(fxarray): return masked_array(fxarray['_data'], mask=fxarray['_mask']) class _convert2ma: __doc__ = None def __init__(self, funcname, np_ret, np_ma_ret, params=None): self._func = getattr(np, funcname) self.__doc__ = self.getdoc(np_ret, np_ma_ret) self._extras = params or {} def getdoc(self, np_ret, np_ma_ret): doc = getattr(self._func, '__doc__', None) sig = get_object_signature(self._func) if doc: doc = self._replace_return_type(doc, np_ret, np_ma_ret) if sig: sig = '%s%s\n' % (self._func.__name__, sig) doc = sig + doc return doc def _replace_return_type(self, doc, np_ret, np_ma_ret): if np_ret not in doc: raise RuntimeError(f'Failed to replace `{np_ret}` with `{np_ma_ret}`. The documentation string for return type, {np_ret}, is not found in the docstring for `np.{self._func.__name__}`. Fix the docstring for `np.{self._func.__name__}` or update the expected string for return type.') return doc.replace(np_ret, np_ma_ret) def __call__(self, *args, **params): _extras = self._extras common_params = set(params).intersection(_extras) for p in common_params: _extras[p] = params.pop(p) result = self._func.__call__(*args, **params).view(MaskedArray) if 'fill_value' in common_params: result.fill_value = _extras.get('fill_value', None) if 'hardmask' in common_params: result._hardmask = bool(_extras.get('hard_mask', False)) return result arange = _convert2ma('arange', params=dict(fill_value=None, hardmask=False), np_ret='arange : ndarray', np_ma_ret='arange : MaskedArray') clip = _convert2ma('clip', params=dict(fill_value=None, hardmask=False), np_ret='clipped_array : ndarray', np_ma_ret='clipped_array : MaskedArray') empty = _convert2ma('empty', params=dict(fill_value=None, hardmask=False), np_ret='out : ndarray', np_ma_ret='out : MaskedArray') empty_like = _convert2ma('empty_like', np_ret='out : ndarray', np_ma_ret='out : MaskedArray') frombuffer = _convert2ma('frombuffer', np_ret='out : ndarray', np_ma_ret='out: MaskedArray') fromfunction = _convert2ma('fromfunction', np_ret='fromfunction : any', np_ma_ret='fromfunction: MaskedArray') identity = _convert2ma('identity', params=dict(fill_value=None, hardmask=False), np_ret='out : ndarray', np_ma_ret='out : MaskedArray') indices = _convert2ma('indices', params=dict(fill_value=None, hardmask=False), np_ret='grid : one ndarray or tuple of ndarrays', np_ma_ret='grid : one MaskedArray or tuple of MaskedArrays') ones = _convert2ma('ones', params=dict(fill_value=None, hardmask=False), np_ret='out : ndarray', np_ma_ret='out : MaskedArray') ones_like = _convert2ma('ones_like', np_ret='out : ndarray', np_ma_ret='out : MaskedArray') squeeze = _convert2ma('squeeze', params=dict(fill_value=None, hardmask=False), np_ret='squeezed : ndarray', np_ma_ret='squeezed : MaskedArray') zeros = _convert2ma('zeros', params=dict(fill_value=None, hardmask=False), np_ret='out : ndarray', np_ma_ret='out : MaskedArray') zeros_like = _convert2ma('zeros_like', np_ret='out : ndarray', np_ma_ret='out : MaskedArray') def append(a, b, axis=None): return concatenate([a, b], axis) # File: numpy-main/numpy/ma/extras.py """""" __all__ = ['apply_along_axis', 'apply_over_axes', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'clump_masked', 'clump_unmasked', 'column_stack', 'compress_cols', 'compress_nd', 'compress_rowcols', 'compress_rows', 'count_masked', 'corrcoef', 'cov', 'diagflat', 'dot', 'dstack', 'ediff1d', 'flatnotmasked_contiguous', 'flatnotmasked_edges', 'hsplit', 'hstack', 'isin', 'in1d', 'intersect1d', 'mask_cols', 'mask_rowcols', 'mask_rows', 'masked_all', 'masked_all_like', 'median', 'mr_', 'ndenumerate', 'notmasked_contiguous', 'notmasked_edges', 'polyfit', 'row_stack', 'setdiff1d', 'setxor1d', 'stack', 'unique', 'union1d', 'vander', 'vstack'] import itertools import warnings from . import core as ma from .core import MaskedArray, MAError, add, array, asarray, concatenate, filled, count, getmask, getmaskarray, make_mask_descr, masked, masked_array, mask_or, nomask, ones, sort, zeros, getdata, get_masked_subclass, dot import numpy as np from numpy import ndarray, array as nxarray from numpy.lib.array_utils import normalize_axis_index, normalize_axis_tuple from numpy.lib._function_base_impl import _ureduce from numpy.lib._index_tricks_impl import AxisConcatenator def issequence(seq): return isinstance(seq, (ndarray, tuple, list)) def count_masked(arr, axis=None): m = getmaskarray(arr) return m.sum(axis) def masked_all(shape, dtype=float): a = masked_array(np.empty(shape, dtype), mask=np.ones(shape, make_mask_descr(dtype))) return a def masked_all_like(arr): a = np.empty_like(arr).view(MaskedArray) a._mask = np.ones(a.shape, dtype=make_mask_descr(a.dtype)) return a class _fromnxfunction: def __init__(self, funcname): self.__name__ = funcname self.__doc__ = self.getdoc() def getdoc(self): npfunc = getattr(np, self.__name__, None) doc = getattr(npfunc, '__doc__', None) if doc: sig = ma.get_object_signature(npfunc) doc = ma.doc_note(doc, 'The function is applied to both the _data and the _mask, if any.') if sig: sig = self.__name__ + sig + '\n\n' return sig + doc return def __call__(self, *args, **params): pass class _fromnxfunction_single(_fromnxfunction): def __call__(self, x, *args, **params): func = getattr(np, self.__name__) if isinstance(x, ndarray): _d = func(x.__array__(), *args, **params) _m = func(getmaskarray(x), *args, **params) return masked_array(_d, mask=_m) else: _d = func(np.asarray(x), *args, **params) _m = func(getmaskarray(x), *args, **params) return masked_array(_d, mask=_m) class _fromnxfunction_seq(_fromnxfunction): def __call__(self, x, *args, **params): func = getattr(np, self.__name__) _d = func(tuple([np.asarray(a) for a in x]), *args, **params) _m = func(tuple([getmaskarray(a) for a in x]), *args, **params) return masked_array(_d, mask=_m) class _fromnxfunction_args(_fromnxfunction): def __call__(self, *args, **params): func = getattr(np, self.__name__) arrays = [] args = list(args) while len(args) > 0 and issequence(args[0]): arrays.append(args.pop(0)) res = [] for x in arrays: _d = func(np.asarray(x), *args, **params) _m = func(getmaskarray(x), *args, **params) res.append(masked_array(_d, mask=_m)) if len(arrays) == 1: return res[0] return res class _fromnxfunction_allargs(_fromnxfunction): def __call__(self, *args, **params): func = getattr(np, self.__name__) res = [] for x in args: _d = func(np.asarray(x), **params) _m = func(getmaskarray(x), **params) res.append(masked_array(_d, mask=_m)) if len(args) == 1: return res[0] return res atleast_1d = _fromnxfunction_allargs('atleast_1d') atleast_2d = _fromnxfunction_allargs('atleast_2d') atleast_3d = _fromnxfunction_allargs('atleast_3d') vstack = row_stack = _fromnxfunction_seq('vstack') hstack = _fromnxfunction_seq('hstack') column_stack = _fromnxfunction_seq('column_stack') dstack = _fromnxfunction_seq('dstack') stack = _fromnxfunction_seq('stack') hsplit = _fromnxfunction_single('hsplit') diagflat = _fromnxfunction_single('diagflat') def flatten_inplace(seq): k = 0 while k != len(seq): while hasattr(seq[k], '__iter__'): seq[k:k + 1] = seq[k] k += 1 return seq def apply_along_axis(func1d, axis, arr, *args, **kwargs): arr = array(arr, copy=False, subok=True) nd = arr.ndim axis = normalize_axis_index(axis, nd) ind = [0] * (nd - 1) i = np.zeros(nd, 'O') indlist = list(range(nd)) indlist.remove(axis) i[axis] = slice(None, None) outshape = np.asarray(arr.shape).take(indlist) i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())], *args, **kwargs) asscalar = np.isscalar(res) if not asscalar: try: len(res) except TypeError: asscalar = True dtypes = [] if asscalar: dtypes.append(np.asarray(res).dtype) outarr = zeros(outshape, object) outarr[tuple(ind)] = res Ntot = np.prod(outshape) k = 1 while k < Ntot: ind[-1] += 1 n = -1 while ind[n] >= outshape[n] and n > 1 - nd: ind[n - 1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())], *args, **kwargs) outarr[tuple(ind)] = res dtypes.append(asarray(res).dtype) k += 1 else: res = array(res, copy=False, subok=True) j = i.copy() j[axis] = [slice(None, None)] * res.ndim j.put(indlist, ind) Ntot = np.prod(outshape) holdshape = outshape outshape = list(arr.shape) outshape[axis] = res.shape dtypes.append(asarray(res).dtype) outshape = flatten_inplace(outshape) outarr = zeros(outshape, object) outarr[tuple(flatten_inplace(j.tolist()))] = res k = 1 while k < Ntot: ind[-1] += 1 n = -1 while ind[n] >= holdshape[n] and n > 1 - nd: ind[n - 1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) j.put(indlist, ind) res = func1d(arr[tuple(i.tolist())], *args, **kwargs) outarr[tuple(flatten_inplace(j.tolist()))] = res dtypes.append(asarray(res).dtype) k += 1 max_dtypes = np.dtype(np.asarray(dtypes).max()) if not hasattr(arr, '_mask'): result = np.asarray(outarr, dtype=max_dtypes) else: result = asarray(outarr, dtype=max_dtypes) result.fill_value = ma.default_fill_value(result) return result apply_along_axis.__doc__ = np.apply_along_axis.__doc__ def apply_over_axes(func, a, axes): val = asarray(a) N = a.ndim if array(axes).ndim == 0: axes = (axes,) for axis in axes: if axis < 0: axis = N + axis args = (val, axis) res = func(*args) if res.ndim == val.ndim: val = res else: res = ma.expand_dims(res, axis) if res.ndim == val.ndim: val = res else: raise ValueError('function is not returning an array of the correct shape') return val if apply_over_axes.__doc__ is not None: apply_over_axes.__doc__ = np.apply_over_axes.__doc__[:np.apply_over_axes.__doc__.find('Notes')].rstrip() + '\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.ma.arange(24).reshape(2,3,4)\n >>> a[:,0,1] = np.ma.masked\n >>> a[:,1,:] = np.ma.masked\n >>> a\n masked_array(\n data=[[[0, --, 2, 3],\n [--, --, --, --],\n [8, 9, 10, 11]],\n [[12, --, 14, 15],\n [--, --, --, --],\n [20, 21, 22, 23]]],\n mask=[[[False, True, False, False],\n [ True, True, True, True],\n [False, False, False, False]],\n [[False, True, False, False],\n [ True, True, True, True],\n [False, False, False, False]]],\n fill_value=999999)\n >>> np.ma.apply_over_axes(np.ma.sum, a, [0,2])\n masked_array(\n data=[[[46],\n [--],\n [124]]],\n mask=[[[False],\n [ True],\n [False]]],\n fill_value=999999)\n\n Tuple axis arguments to ufuncs are equivalent:\n\n >>> np.ma.sum(a, axis=(0,2)).reshape((1,-1,1))\n masked_array(\n data=[[[46],\n [--],\n [124]]],\n mask=[[[False],\n [ True],\n [False]]],\n fill_value=999999)\n ' def average(a, axis=None, weights=None, returned=False, *, keepdims=np._NoValue): a = asarray(a) m = getmask(a) if axis is not None: axis = normalize_axis_tuple(axis, a.ndim, argname='axis') if keepdims is np._NoValue: keepdims_kw = {} else: keepdims_kw = {'keepdims': keepdims} if weights is None: avg = a.mean(axis, **keepdims_kw) scl = avg.dtype.type(a.count(axis)) else: wgt = asarray(weights) if issubclass(a.dtype.type, (np.integer, np.bool)): result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8') else: result_dtype = np.result_type(a.dtype, wgt.dtype) if a.shape != wgt.shape: if axis is None: raise TypeError('Axis must be specified when shapes of a and weights differ.') if wgt.shape != tuple((a.shape[ax] for ax in axis)): raise ValueError('Shape of weights must be consistent with shape of a along specified axis.') wgt = wgt.transpose(np.argsort(axis)) wgt = wgt.reshape(tuple((s if ax in axis else 1 for (ax, s) in enumerate(a.shape)))) if m is not nomask: wgt = wgt * ~a.mask wgt.mask |= a.mask scl = wgt.sum(axis=axis, dtype=result_dtype, **keepdims_kw) avg = np.multiply(a, wgt, dtype=result_dtype).sum(axis, **keepdims_kw) / scl if returned: if scl.shape != avg.shape: scl = np.broadcast_to(scl, avg.shape).copy() return (avg, scl) else: return avg def median(a, axis=None, out=None, overwrite_input=False, keepdims=False): if not hasattr(a, 'mask'): m = np.median(getdata(a, subok=True), axis=axis, out=out, overwrite_input=overwrite_input, keepdims=keepdims) if isinstance(m, np.ndarray) and 1 <= m.ndim: return masked_array(m, copy=False) else: return m return _ureduce(a, func=_median, keepdims=keepdims, axis=axis, out=out, overwrite_input=overwrite_input) def _median(a, axis=None, out=None, overwrite_input=False): if np.issubdtype(a.dtype, np.inexact): fill_value = np.inf else: fill_value = None if overwrite_input: if axis is None: asorted = a.ravel() asorted.sort(fill_value=fill_value) else: a.sort(axis=axis, fill_value=fill_value) asorted = a else: asorted = sort(a, axis=axis, fill_value=fill_value) if axis is None: axis = 0 else: axis = normalize_axis_index(axis, asorted.ndim) if asorted.shape[axis] == 0: indexer = [slice(None)] * asorted.ndim indexer[axis] = slice(0, 0) indexer = tuple(indexer) return np.ma.mean(asorted[indexer], axis=axis, out=out) if asorted.ndim == 1: (idx, odd) = divmod(count(asorted), 2) mid = asorted[idx + odd - 1:idx + 1] if np.issubdtype(asorted.dtype, np.inexact) and asorted.size > 0: s = mid.sum(out=out) if not odd: s = np.true_divide(s, 2.0, casting='safe', out=out) s = np.lib._utils_impl._median_nancheck(asorted, s, axis) else: s = mid.mean(out=out) if np.ma.is_masked(s) and (not np.all(asorted.mask)): return np.ma.minimum_fill_value(asorted) return s counts = count(asorted, axis=axis, keepdims=True) h = counts // 2 odd = counts % 2 == 1 l = np.where(odd, h, h - 1) lh = np.concatenate([l, h], axis=axis) low_high = np.take_along_axis(asorted, lh, axis=axis) def replace_masked(s): if np.ma.is_masked(s): rep = ~np.all(asorted.mask, axis=axis, keepdims=True) & s.mask s.data[rep] = np.ma.minimum_fill_value(asorted) s.mask[rep] = False replace_masked(low_high) if np.issubdtype(asorted.dtype, np.inexact): s = np.ma.sum(low_high, axis=axis, out=out) np.true_divide(s.data, 2.0, casting='unsafe', out=s.data) s = np.lib._utils_impl._median_nancheck(asorted, s, axis) else: s = np.ma.mean(low_high, axis=axis, out=out) return s def compress_nd(x, axis=None): x = asarray(x) m = getmask(x) if axis is None: axis = tuple(range(x.ndim)) else: axis = normalize_axis_tuple(axis, x.ndim) if m is nomask or not m.any(): return x._data if m.all(): return nxarray([]) data = x._data for ax in axis: axes = tuple(list(range(ax)) + list(range(ax + 1, x.ndim))) data = data[(slice(None),) * ax + (~m.any(axis=axes),)] return data def compress_rowcols(x, axis=None): if asarray(x).ndim != 2: raise NotImplementedError('compress_rowcols works for 2D arrays only.') return compress_nd(x, axis=axis) def compress_rows(a): a = asarray(a) if a.ndim != 2: raise NotImplementedError('compress_rows works for 2D arrays only.') return compress_rowcols(a, 0) def compress_cols(a): a = asarray(a) if a.ndim != 2: raise NotImplementedError('compress_cols works for 2D arrays only.') return compress_rowcols(a, 1) def mask_rowcols(a, axis=None): a = array(a, subok=False) if a.ndim != 2: raise NotImplementedError('mask_rowcols works for 2D arrays only.') m = getmask(a) if m is nomask or not m.any(): return a maskedval = m.nonzero() a._mask = a._mask.copy() if not axis: a[np.unique(maskedval[0])] = masked if axis in [None, 1, -1]: a[:, np.unique(maskedval[1])] = masked return a def mask_rows(a, axis=np._NoValue): if axis is not np._NoValue: warnings.warn('The axis argument has always been ignored, in future passing it will raise TypeError', DeprecationWarning, stacklevel=2) return mask_rowcols(a, 0) def mask_cols(a, axis=np._NoValue): if axis is not np._NoValue: warnings.warn('The axis argument has always been ignored, in future passing it will raise TypeError', DeprecationWarning, stacklevel=2) return mask_rowcols(a, 1) def ediff1d(arr, to_end=None, to_begin=None): arr = ma.asanyarray(arr).flat ed = arr[1:] - arr[:-1] arrays = [ed] if to_begin is not None: arrays.insert(0, to_begin) if to_end is not None: arrays.append(to_end) if len(arrays) != 1: ed = hstack(arrays) return ed def unique(ar1, return_index=False, return_inverse=False): output = np.unique(ar1, return_index=return_index, return_inverse=return_inverse) if isinstance(output, tuple): output = list(output) output[0] = output[0].view(MaskedArray) output = tuple(output) else: output = output.view(MaskedArray) return output def intersect1d(ar1, ar2, assume_unique=False): if assume_unique: aux = ma.concatenate((ar1, ar2)) else: aux = ma.concatenate((unique(ar1), unique(ar2))) aux.sort() return aux[:-1][aux[1:] == aux[:-1]] def setxor1d(ar1, ar2, assume_unique=False): if not assume_unique: ar1 = unique(ar1) ar2 = unique(ar2) aux = ma.concatenate((ar1, ar2), axis=None) if aux.size == 0: return aux aux.sort() auxf = aux.filled() flag = ma.concatenate(([True], auxf[1:] != auxf[:-1], [True])) flag2 = flag[1:] == flag[:-1] return aux[flag2] def in1d(ar1, ar2, assume_unique=False, invert=False): if not assume_unique: (ar1, rev_idx) = unique(ar1, return_inverse=True) ar2 = unique(ar2) ar = ma.concatenate((ar1, ar2)) order = ar.argsort(kind='mergesort') sar = ar[order] if invert: bool_ar = sar[1:] != sar[:-1] else: bool_ar = sar[1:] == sar[:-1] flag = ma.concatenate((bool_ar, [invert])) indx = order.argsort(kind='mergesort')[:len(ar1)] if assume_unique: return flag[indx] else: return flag[indx][rev_idx] def isin(element, test_elements, assume_unique=False, invert=False): element = ma.asarray(element) return in1d(element, test_elements, assume_unique=assume_unique, invert=invert).reshape(element.shape) def union1d(ar1, ar2): return unique(ma.concatenate((ar1, ar2), axis=None)) def setdiff1d(ar1, ar2, assume_unique=False): if assume_unique: ar1 = ma.asarray(ar1).ravel() else: ar1 = unique(ar1) ar2 = unique(ar2) return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)] def _covhelper(x, y=None, rowvar=True, allow_masked=True): x = ma.array(x, ndmin=2, copy=True, dtype=float) xmask = ma.getmaskarray(x) if not allow_masked and xmask.any(): raise ValueError('Cannot process masked data.') if x.shape[0] == 1: rowvar = True rowvar = int(bool(rowvar)) axis = 1 - rowvar if rowvar: tup = (slice(None), None) else: tup = (None, slice(None)) if y is None: if x.shape[0] > 2 ** 24 or x.shape[1] > 2 ** 24: xnm_dtype = np.float64 else: xnm_dtype = np.float32 xnotmask = np.logical_not(xmask).astype(xnm_dtype) else: y = array(y, copy=False, ndmin=2, dtype=float) ymask = ma.getmaskarray(y) if not allow_masked and ymask.any(): raise ValueError('Cannot process masked data.') if xmask.any() or ymask.any(): if y.shape == x.shape: common_mask = np.logical_or(xmask, ymask) if common_mask is not nomask: xmask = x._mask = y._mask = ymask = common_mask x._sharedmask = False y._sharedmask = False x = ma.concatenate((x, y), axis) if x.shape[0] > 2 ** 24 or x.shape[1] > 2 ** 24: xnm_dtype = np.float64 else: xnm_dtype = np.float32 xnotmask = np.logical_not(np.concatenate((xmask, ymask), axis)).astype(xnm_dtype) x -= x.mean(axis=rowvar)[tup] return (x, xnotmask, rowvar) def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None): if ddof is not None and ddof != int(ddof): raise ValueError('ddof must be an integer') if ddof is None: if bias: ddof = 0 else: ddof = 1 (x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked) if not rowvar: fact = np.dot(xnotmask.T, xnotmask) - ddof mask = np.less_equal(fact, 0, dtype=bool) with np.errstate(divide='ignore', invalid='ignore'): data = np.dot(filled(x.T, 0), filled(x.conj(), 0)) / fact result = ma.array(data, mask=mask).squeeze() else: fact = np.dot(xnotmask, xnotmask.T) - ddof mask = np.less_equal(fact, 0, dtype=bool) with np.errstate(divide='ignore', invalid='ignore'): data = np.dot(filled(x, 0), filled(x.T.conj(), 0)) / fact result = ma.array(data, mask=mask).squeeze() return result def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, allow_masked=True, ddof=np._NoValue): msg = 'bias and ddof have no effect and are deprecated' if bias is not np._NoValue or ddof is not np._NoValue: warnings.warn(msg, DeprecationWarning, stacklevel=2) corr = cov(x, y, rowvar, allow_masked=allow_masked) try: std = ma.sqrt(ma.diagonal(corr)) except ValueError: return ma.MaskedConstant() corr /= ma.multiply.outer(std, std) return corr class MAxisConcatenator(AxisConcatenator): __slots__ = () concatenate = staticmethod(concatenate) @classmethod def makemat(cls, arr): data = super().makemat(arr.data, copy=False) return array(data, mask=arr.mask) def __getitem__(self, key): if isinstance(key, str): raise MAError('Unavailable for masked array.') return super().__getitem__(key) class mr_class(MAxisConcatenator): __slots__ = () def __init__(self): MAxisConcatenator.__init__(self, 0) mr_ = mr_class() def ndenumerate(a, compressed=True): for (it, mask) in zip(np.ndenumerate(a), getmaskarray(a).flat): if not mask: yield it elif not compressed: yield (it[0], masked) def flatnotmasked_edges(a): m = getmask(a) if m is nomask or not np.any(m): return np.array([0, a.size - 1]) unmasked = np.flatnonzero(~m) if len(unmasked) > 0: return unmasked[[0, -1]] else: return None def notmasked_edges(a, axis=None): a = asarray(a) if axis is None or a.ndim == 1: return flatnotmasked_edges(a) m = getmaskarray(a) idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim)) return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]), tuple([idx[i].max(axis).compressed() for i in range(a.ndim)])] def flatnotmasked_contiguous(a): m = getmask(a) if m is nomask: return [slice(0, a.size)] i = 0 result = [] for (k, g) in itertools.groupby(m.ravel()): n = len(list(g)) if not k: result.append(slice(i, i + n)) i += n return result def notmasked_contiguous(a, axis=None): a = asarray(a) nd = a.ndim if nd > 2: raise NotImplementedError('Currently limited to at most 2D array.') if axis is None or nd == 1: return flatnotmasked_contiguous(a) result = [] other = (axis + 1) % 2 idx = [0, 0] idx[axis] = slice(None, None) for i in range(a.shape[other]): idx[other] = i result.append(flatnotmasked_contiguous(a[tuple(idx)])) return result def _ezclump(mask): if mask.ndim > 1: mask = mask.ravel() idx = (mask[1:] ^ mask[:-1]).nonzero() idx = idx[0] + 1 if mask[0]: if len(idx) == 0: return [slice(0, mask.size)] r = [slice(0, idx[0])] r.extend((slice(left, right) for (left, right) in zip(idx[1:-1:2], idx[2::2]))) else: if len(idx) == 0: return [] r = [slice(left, right) for (left, right) in zip(idx[:-1:2], idx[1::2])] if mask[-1]: r.append(slice(idx[-1], mask.size)) return r def clump_unmasked(a): mask = getattr(a, '_mask', nomask) if mask is nomask: return [slice(0, a.size)] return _ezclump(~mask) def clump_masked(a): mask = ma.getmask(a) if mask is nomask: return [] return _ezclump(mask) def vander(x, n=None): _vander = np.vander(x, n) m = getmask(x) if m is not nomask: _vander[m] = 0 return _vander vander.__doc__ = ma.doc_note(np.vander.__doc__, vander.__doc__) def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): x = asarray(x) y = asarray(y) m = getmask(x) if y.ndim == 1: m = mask_or(m, getmask(y)) elif y.ndim == 2: my = getmask(mask_rows(y)) if my is not nomask: m = mask_or(m, my[:, 0]) else: raise TypeError('Expected a 1D or 2D array for y!') if w is not None: w = asarray(w) if w.ndim != 1: raise TypeError('expected a 1-d array for weights') if w.shape[0] != y.shape[0]: raise TypeError('expected w and y to have the same length') m = mask_or(m, getmask(w)) if m is not nomask: not_m = ~m if w is not None: w = w[not_m] return np.polyfit(x[not_m], y[not_m], deg, rcond, full, w, cov) else: return np.polyfit(x, y, deg, rcond, full, w, cov) polyfit.__doc__ = ma.doc_note(np.polyfit.__doc__, polyfit.__doc__) # File: numpy-main/numpy/ma/mrecords.py """""" from numpy.ma import MAError, MaskedArray, masked, nomask, masked_array, getdata, getmaskarray, filled import numpy.ma as ma import warnings import numpy as np from numpy import dtype, ndarray, array as narray from numpy._core.records import recarray, fromarrays as recfromarrays, fromrecords as recfromrecords _byteorderconv = np._core.records._byteorderconv _check_fill_value = ma.core._check_fill_value __all__ = ['MaskedRecords', 'mrecarray', 'fromarrays', 'fromrecords', 'fromtextfile', 'addfield'] reserved_fields = ['_data', '_mask', '_fieldmask', 'dtype'] def _checknames(descr, names=None): ndescr = len(descr) default_names = ['f%i' % i for i in range(ndescr)] if names is None: new_names = default_names else: if isinstance(names, (tuple, list)): new_names = names elif isinstance(names, str): new_names = names.split(',') else: raise NameError(f'illegal input names {names!r}') nnames = len(new_names) if nnames < ndescr: new_names += default_names[nnames:] ndescr = [] for (n, d, t) in zip(new_names, default_names, descr.descr): if n in reserved_fields: if t[0] in reserved_fields: ndescr.append((d, t[1])) else: ndescr.append(t) else: ndescr.append((n, t[1])) return np.dtype(ndescr) def _get_fieldmask(self): mdescr = [(n, '|b1') for n in self.dtype.names] fdmask = np.empty(self.shape, dtype=mdescr) fdmask.flat = tuple([False] * len(mdescr)) return fdmask class MaskedRecords(MaskedArray): def __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, mask=nomask, hard_mask=False, fill_value=None, keep_mask=True, copy=False, **options): self = recarray.__new__(cls, shape, dtype=dtype, buf=buf, offset=offset, strides=strides, formats=formats, names=names, titles=titles, byteorder=byteorder, aligned=aligned) mdtype = ma.make_mask_descr(self.dtype) if mask is nomask or not np.size(mask): if not keep_mask: self._mask = tuple([False] * len(mdtype)) else: mask = np.array(mask, copy=copy) if mask.shape != self.shape: (nd, nm) = (self.size, mask.size) if nm == 1: mask = np.resize(mask, self.shape) elif nm == nd: mask = np.reshape(mask, self.shape) else: msg = 'Mask and data not compatible: data size is %i, ' + 'mask size is %i.' raise MAError(msg % (nd, nm)) if not keep_mask: self.__setmask__(mask) self._sharedmask = True else: if mask.dtype == mdtype: _mask = mask else: _mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) self._mask = _mask return self def __array_finalize__(self, obj): _mask = getattr(obj, '_mask', None) if _mask is None: objmask = getattr(obj, '_mask', nomask) _dtype = ndarray.__getattribute__(self, 'dtype') if objmask is nomask: _mask = ma.make_mask_none(self.shape, dtype=_dtype) else: mdescr = ma.make_mask_descr(_dtype) _mask = narray([tuple([m] * len(mdescr)) for m in objmask], dtype=mdescr).view(recarray) _dict = self.__dict__ _dict.update(_mask=_mask) self._update_from(obj) if _dict['_baseclass'] == ndarray: _dict['_baseclass'] = recarray return @property def _data(self): return ndarray.view(self, recarray) @property def _fieldmask(self): return self._mask def __len__(self): if self.ndim: return len(self._data) return len(self.dtype) def __getattribute__(self, attr): try: return object.__getattribute__(self, attr) except AttributeError: pass fielddict = ndarray.__getattribute__(self, 'dtype').fields try: res = fielddict[attr][:2] except (TypeError, KeyError) as e: raise AttributeError(f'record array has no attribute {attr}') from e _localdict = ndarray.__getattribute__(self, '__dict__') _data = ndarray.view(self, _localdict['_baseclass']) obj = _data.getfield(*res) if obj.dtype.names is not None: raise NotImplementedError('MaskedRecords is currently limited tosimple records.') hasmasked = False _mask = _localdict.get('_mask', None) if _mask is not None: try: _mask = _mask[attr] except IndexError: pass tp_len = len(_mask.dtype) hasmasked = _mask.view((bool, (tp_len,) if tp_len else ())).any() if obj.shape or hasmasked: obj = obj.view(MaskedArray) obj._baseclass = ndarray obj._isfield = True obj._mask = _mask _fill_value = _localdict.get('_fill_value', None) if _fill_value is not None: try: obj._fill_value = _fill_value[attr] except ValueError: obj._fill_value = None else: obj = obj.item() return obj def __setattr__(self, attr, val): if attr in ['mask', 'fieldmask']: self.__setmask__(val) return _localdict = object.__getattribute__(self, '__dict__') newattr = attr not in _localdict try: ret = object.__setattr__(self, attr, val) except Exception: fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} optinfo = ndarray.__getattribute__(self, '_optinfo') or {} if not (attr in fielddict or attr in optinfo): raise else: fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} if attr not in fielddict: return ret if newattr: try: object.__delattr__(self, attr) except Exception: return ret try: res = fielddict[attr][:2] except (TypeError, KeyError) as e: raise AttributeError(f'record array has no attribute {attr}') from e if val is masked: _fill_value = _localdict['_fill_value'] if _fill_value is not None: dval = _localdict['_fill_value'][attr] else: dval = val mval = True else: dval = filled(val) mval = getmaskarray(val) obj = ndarray.__getattribute__(self, '_data').setfield(dval, *res) _localdict['_mask'].__setitem__(attr, mval) return obj def __getitem__(self, indx): _localdict = self.__dict__ _mask = ndarray.__getattribute__(self, '_mask') _data = ndarray.view(self, _localdict['_baseclass']) if isinstance(indx, str): obj = _data[indx].view(MaskedArray) obj._mask = _mask[indx] obj._sharedmask = True fval = _localdict['_fill_value'] if fval is not None: obj._fill_value = fval[indx] if not obj.ndim and obj._mask: return masked return obj obj = np.asarray(_data[indx]).view(mrecarray) obj._mask = np.asarray(_mask[indx]).view(recarray) return obj def __setitem__(self, indx, value): MaskedArray.__setitem__(self, indx, value) if isinstance(indx, str): self._mask[indx] = ma.getmaskarray(value) def __str__(self): if self.size > 1: mstr = [f"({','.join([str(i) for i in s])})" for s in zip(*[getattr(self, f) for f in self.dtype.names])] return f"[{', '.join(mstr)}]" else: mstr = [f"{','.join([str(i) for i in s])}" for s in zip([getattr(self, f) for f in self.dtype.names])] return f"({', '.join(mstr)})" def __repr__(self): _names = self.dtype.names fmt = '%%%is : %%s' % (max([len(n) for n in _names]) + 4,) reprstr = [fmt % (f, getattr(self, f)) for f in self.dtype.names] reprstr.insert(0, 'masked_records(') reprstr.extend([fmt % (' fill_value', self.fill_value), ' )']) return str('\n'.join(reprstr)) def view(self, dtype=None, type=None): if dtype is None: if type is None: output = ndarray.view(self) else: output = ndarray.view(self, type) elif type is None: try: if issubclass(dtype, ndarray): output = ndarray.view(self, dtype) else: output = ndarray.view(self, dtype) except TypeError: dtype = np.dtype(dtype) if dtype.fields is None: basetype = self.__class__.__bases__[0] output = self.__array__().view(dtype, basetype) output._update_from(self) else: output = ndarray.view(self, dtype) output._fill_value = None else: output = ndarray.view(self, dtype, type) if getattr(output, '_mask', nomask) is not nomask: mdtype = ma.make_mask_descr(output.dtype) output._mask = self._mask.view(mdtype, ndarray) output._mask.shape = output.shape return output def harden_mask(self): self._hardmask = True def soften_mask(self): self._hardmask = False def copy(self): copied = self._data.copy().view(type(self)) copied._mask = self._mask.copy() return copied def tolist(self, fill_value=None): if fill_value is not None: return self.filled(fill_value).tolist() result = narray(self.filled().tolist(), dtype=object) mask = narray(self._mask.tolist()) result[mask] = None return result.tolist() def __getstate__(self): state = (1, self.shape, self.dtype, self.flags.fnc, self._data.tobytes(), self._mask.tobytes(), self._fill_value) return state def __setstate__(self, state): (ver, shp, typ, isf, raw, msk, flv) = state ndarray.__setstate__(self, (shp, typ, isf, raw)) mdtype = dtype([(k, np.bool) for (k, _) in self.dtype.descr]) self.__dict__['_mask'].__setstate__((shp, mdtype, isf, msk)) self.fill_value = flv def __reduce__(self): return (_mrreconstruct, (self.__class__, self._baseclass, (0,), 'b'), self.__getstate__()) def _mrreconstruct(subtype, baseclass, baseshape, basetype): _data = ndarray.__new__(baseclass, baseshape, basetype).view(subtype) _mask = ndarray.__new__(ndarray, baseshape, 'b1') return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype) mrecarray = MaskedRecords def fromarrays(arraylist, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, fill_value=None): datalist = [getdata(x) for x in arraylist] masklist = [np.atleast_1d(getmaskarray(x)) for x in arraylist] _array = recfromarrays(datalist, dtype=dtype, shape=shape, formats=formats, names=names, titles=titles, aligned=aligned, byteorder=byteorder).view(mrecarray) _array._mask.flat = list(zip(*masklist)) if fill_value is not None: _array.fill_value = fill_value return _array def fromrecords(reclist, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, fill_value=None, mask=nomask): _mask = getattr(reclist, '_mask', None) if isinstance(reclist, ndarray): if isinstance(reclist, MaskedArray): reclist = reclist.filled().view(ndarray) if dtype is None: dtype = reclist.dtype reclist = reclist.tolist() mrec = recfromrecords(reclist, dtype=dtype, shape=shape, formats=formats, names=names, titles=titles, aligned=aligned, byteorder=byteorder).view(mrecarray) if fill_value is not None: mrec.fill_value = fill_value if mask is not nomask: mask = np.asarray(mask) maskrecordlength = len(mask.dtype) if maskrecordlength: mrec._mask.flat = mask elif mask.ndim == 2: mrec._mask.flat = [tuple(m) for m in mask] else: mrec.__setmask__(mask) if _mask is not None: mrec._mask[:] = _mask return mrec def _guessvartypes(arr): vartypes = [] arr = np.asarray(arr) if arr.ndim == 2: arr = arr[0] elif arr.ndim > 2: raise ValueError('The array should be 2D at most!') for f in arr: try: int(f) except (ValueError, TypeError): try: float(f) except (ValueError, TypeError): try: complex(f) except (ValueError, TypeError): vartypes.append(arr.dtype) else: vartypes.append(np.dtype(complex)) else: vartypes.append(np.dtype(float)) else: vartypes.append(np.dtype(int)) return vartypes def openfile(fname): if hasattr(fname, 'readline'): return fname try: f = open(fname) except FileNotFoundError as e: raise FileNotFoundError(f"No such file: '{fname}'") from e if f.readline()[:2] != '\\x': f.seek(0, 0) return f f.close() raise NotImplementedError('Wow, binary file') def fromtextfile(fname, delimiter=None, commentchar='#', missingchar='', varnames=None, vartypes=None, *, delimitor=np._NoValue): if delimitor is not np._NoValue: if delimiter is not None: raise TypeError("fromtextfile() got multiple values for argument 'delimiter'") warnings.warn("The 'delimitor' keyword argument of numpy.ma.mrecords.fromtextfile() is deprecated since NumPy 1.22.0, use 'delimiter' instead.", DeprecationWarning, stacklevel=2) delimiter = delimitor ftext = openfile(fname) while True: line = ftext.readline() firstline = line[:line.find(commentchar)].strip() _varnames = firstline.split(delimiter) if len(_varnames) > 1: break if varnames is None: varnames = _varnames _variables = masked_array([line.strip().split(delimiter) for line in ftext if line[0] != commentchar and len(line) > 1]) (_, nfields) = _variables.shape ftext.close() if vartypes is None: vartypes = _guessvartypes(_variables[0]) else: vartypes = [np.dtype(v) for v in vartypes] if len(vartypes) != nfields: msg = 'Attempting to %i dtypes for %i fields!' msg += ' Reverting to default.' warnings.warn(msg % (len(vartypes), nfields), stacklevel=2) vartypes = _guessvartypes(_variables[0]) mdescr = list(zip(varnames, vartypes)) mfillv = [ma.default_fill_value(f) for f in vartypes] _mask = _variables.T == missingchar _datalist = [masked_array(a, mask=m, dtype=t, fill_value=f) for (a, m, t, f) in zip(_variables.T, _mask, vartypes, mfillv)] return fromarrays(_datalist, dtype=mdescr) def addfield(mrecord, newfield, newfieldname=None): _data = mrecord._data _mask = mrecord._mask if newfieldname is None or newfieldname in reserved_fields: newfieldname = 'f%i' % len(_data.dtype) newfield = ma.array(newfield) newdtype = np.dtype(_data.dtype.descr + [(newfieldname, newfield.dtype)]) newdata = recarray(_data.shape, newdtype) [newdata.setfield(_data.getfield(*f), *f) for f in _data.dtype.fields.values()] newdata.setfield(newfield._data, *newdata.dtype.fields[newfieldname]) newdata = newdata.view(MaskedRecords) newmdtype = np.dtype([(n, np.bool) for n in newdtype.names]) newmask = recarray(_data.shape, newmdtype) [newmask.setfield(_mask.getfield(*f), *f) for f in _mask.dtype.fields.values()] newmask.setfield(getmaskarray(newfield), *newmask.dtype.fields[newfieldname]) newdata._mask = newmask return newdata # File: numpy-main/numpy/ma/timer_comparison.py import timeit from functools import reduce import numpy as np import numpy._core.fromnumeric as fromnumeric from numpy.testing import build_err_msg pi = np.pi class ModuleTester: def __init__(self, module): self.module = module self.allequal = module.allequal self.arange = module.arange self.array = module.array self.concatenate = module.concatenate self.count = module.count self.equal = module.equal self.filled = module.filled self.getmask = module.getmask self.getmaskarray = module.getmaskarray self.id = id self.inner = module.inner self.make_mask = module.make_mask self.masked = module.masked self.masked_array = module.masked_array self.masked_values = module.masked_values self.mask_or = module.mask_or self.nomask = module.nomask self.ones = module.ones self.outer = module.outer self.repeat = module.repeat self.resize = module.resize self.sort = module.sort self.take = module.take self.transpose = module.transpose self.zeros = module.zeros self.MaskType = module.MaskType try: self.umath = module.umath except AttributeError: self.umath = module.core.umath self.testnames = [] def assert_array_compare(self, comparison, x, y, err_msg='', header='', fill_value=True): xf = self.filled(x) yf = self.filled(y) m = self.mask_or(self.getmask(x), self.getmask(y)) x = self.filled(self.masked_array(xf, mask=m), fill_value) y = self.filled(self.masked_array(yf, mask=m), fill_value) if x.dtype.char != 'O': x = x.astype(np.float64) if isinstance(x, np.ndarray) and x.size > 1: x[np.isnan(x)] = 0 elif np.isnan(x): x = 0 if y.dtype.char != 'O': y = y.astype(np.float64) if isinstance(y, np.ndarray) and y.size > 1: y[np.isnan(y)] = 0 elif np.isnan(y): y = 0 try: cond = (x.shape == () or y.shape == ()) or x.shape == y.shape if not cond: msg = build_err_msg([x, y], err_msg + f'\n(shapes {x.shape}, {y.shape} mismatch)', header=header, names=('x', 'y')) assert cond, msg val = comparison(x, y) if m is not self.nomask and fill_value: val = self.masked_array(val, mask=m) if isinstance(val, bool): cond = val reduced = [0] else: reduced = val.ravel() cond = reduced.all() reduced = reduced.tolist() if not cond: match = 100 - 100.0 * reduced.count(1) / len(reduced) msg = build_err_msg([x, y], err_msg + '\n(mismatch %s%%)' % (match,), header=header, names=('x', 'y')) assert cond, msg except ValueError as e: msg = build_err_msg([x, y], err_msg, header=header, names=('x', 'y')) raise ValueError(msg) from e def assert_array_equal(self, x, y, err_msg=''): self.assert_array_compare(self.equal, x, y, err_msg=err_msg, header='Arrays are not equal') @np.errstate(all='ignore') def test_0(self): x = np.array([1.0, 1.0, 1.0, -2.0, pi / 2.0, 4.0, 5.0, -10.0, 10.0, 1.0, 2.0, 3.0]) m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] xm = self.masked_array(x, mask=m) xm[0] @np.errstate(all='ignore') def test_1(self): x = np.array([1.0, 1.0, 1.0, -2.0, pi / 2.0, 4.0, 5.0, -10.0, 10.0, 1.0, 2.0, 3.0]) y = np.array([5.0, 0.0, 3.0, 2.0, -1.0, -4.0, 0.0, -10.0, 10.0, 1.0, 0.0, 3.0]) m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] xm = self.masked_array(x, mask=m1) ym = self.masked_array(y, mask=m2) xf = np.where(m1, 1e+20, x) xm.set_fill_value(1e+20) assert (xm - ym).filled(0).any() s = x.shape assert xm.size == reduce(lambda x, y: x * y, s) assert self.count(xm) == len(m1) - reduce(lambda x, y: x + y, m1) for s in [(4, 3), (6, 2)]: x.shape = s y.shape = s xm.shape = s ym.shape = s xf.shape = s assert self.count(xm) == len(m1) - reduce(lambda x, y: x + y, m1) @np.errstate(all='ignore') def test_2(self): x1 = np.array([1, 2, 4, 3]) x2 = self.array(x1, mask=[1, 0, 0, 0]) x3 = self.array(x1, mask=[0, 1, 0, 1]) x4 = self.array(x1) str(x2) repr(x2) assert type(x2[1]) is type(x1[1]) assert x1[1] == x2[1] x1[2] = 9 x2[2] = 9 self.assert_array_equal(x1, x2) x1[1:3] = 99 x2[1:3] = 99 x2[1] = self.masked x2[1:3] = self.masked x2[:] = x1 x2[1] = self.masked x3[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0]) x4[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0]) x1 = np.arange(5) * 1.0 x2 = self.masked_values(x1, 3.0) x1 = self.array([1, 'hello', 2, 3], object) x2 = np.array([1, 'hello', 2, 3], object) x1[1] x2[1] assert x1[1:1].shape == (0,) n = [0, 0, 1, 0, 0] m = self.make_mask(n) m2 = self.make_mask(m) assert m is m2 m3 = self.make_mask(m, copy=1) assert m is not m3 @np.errstate(all='ignore') def test_3(self): x4 = self.arange(4) x4[2] = self.masked y4 = self.resize(x4, (8,)) assert self.allequal(self.concatenate([x4, x4]), y4) assert self.allequal(self.getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]) y5 = self.repeat(x4, (2, 2, 2, 2), axis=0) self.assert_array_equal(y5, [0, 0, 1, 1, 2, 2, 3, 3]) y6 = self.repeat(x4, 2, axis=0) assert self.allequal(y5, y6) y7 = x4.repeat((2, 2, 2, 2), axis=0) assert self.allequal(y5, y7) y8 = x4.repeat(2, 0) assert self.allequal(y5, y8) @np.errstate(all='ignore') def test_4(self): x = self.arange(24) y = np.arange(24) x[5:6] = self.masked x = x.reshape(2, 3, 4) y = y.reshape(2, 3, 4) assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1))) assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1)) assert self.allequal(np.inner(self.filled(x, 0), self.filled(y, 0)), self.inner(x, y)) assert self.allequal(np.outer(self.filled(x, 0), self.filled(y, 0)), self.outer(x, y)) y = self.array(['abc', 1, 'def', 2, 3], object) y[2] = self.masked t = self.take(y, [0, 3, 4]) assert t[0] == 'abc' assert t[1] == 2 assert t[2] == 3 @np.errstate(all='ignore') def test_5(self): x = self.arange(10) y = self.arange(10) xm = self.arange(10) xm[2] = self.masked x += 1 assert self.allequal(x, y + 1) xm += 1 assert self.allequal(xm, y + 1) x = self.arange(10) xm = self.arange(10) xm[2] = self.masked x -= 1 assert self.allequal(x, y - 1) xm -= 1 assert self.allequal(xm, y - 1) x = self.arange(10) * 1.0 xm = self.arange(10) * 1.0 xm[2] = self.masked x *= 2.0 assert self.allequal(x, y * 2) xm *= 2.0 assert self.allequal(xm, y * 2) x = self.arange(10) * 2 xm = self.arange(10) * 2 xm[2] = self.masked x /= 2 assert self.allequal(x, y) xm /= 2 assert self.allequal(xm, y) x = self.arange(10) * 1.0 xm = self.arange(10) * 1.0 xm[2] = self.masked x /= 2.0 assert self.allequal(x, y / 2.0) xm /= self.arange(10) self.assert_array_equal(xm, self.ones((10,))) x = self.arange(10).astype(np.float64) xm = self.arange(10) xm[2] = self.masked x += 1.0 assert self.allequal(x, y + 1.0) @np.errstate(all='ignore') def test_6(self): x = self.arange(10, dtype=np.float64) y = self.arange(10) xm = self.arange(10, dtype=np.float64) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=np.float64) a[-1] = self.masked x += a xm += a assert self.allequal(x, y + a) assert self.allequal(xm, y + a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=np.float64) xm = self.arange(10, dtype=np.float64) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=np.float64) a[-1] = self.masked x -= a xm -= a assert self.allequal(x, y - a) assert self.allequal(xm, y - a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=np.float64) xm = self.arange(10, dtype=np.float64) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=np.float64) a[-1] = self.masked x *= a xm *= a assert self.allequal(x, y * a) assert self.allequal(xm, y * a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=np.float64) xm = self.arange(10, dtype=np.float64) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=np.float64) a[-1] = self.masked x /= a xm /= a @np.errstate(all='ignore') def test_7(self): d = (self.array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6), self.array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6)) for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate']: try: uf = getattr(self.umath, f) except AttributeError: uf = getattr(fromnumeric, f) mf = getattr(self.module, f) args = d[:uf.nin] ur = uf(*args) mr = mf(*args) self.assert_array_equal(ur.filled(0), mr.filled(0), f) self.assert_array_equal(ur._mask, mr._mask) @np.errstate(all='ignore') def test_99(self): ott = self.array([0.0, 1.0, 2.0, 3.0], mask=[1, 0, 0, 0]) self.assert_array_equal(2.0, self.average(ott, axis=0)) self.assert_array_equal(2.0, self.average(ott, weights=[1.0, 1.0, 2.0, 1.0])) (result, wts) = self.average(ott, weights=[1.0, 1.0, 2.0, 1.0], returned=1) self.assert_array_equal(2.0, result) assert wts == 4.0 ott[:] = self.masked assert self.average(ott, axis=0) is self.masked ott = self.array([0.0, 1.0, 2.0, 3.0], mask=[1, 0, 0, 0]) ott = ott.reshape(2, 2) ott[:, 1] = self.masked self.assert_array_equal(self.average(ott, axis=0), [2.0, 0.0]) assert self.average(ott, axis=1)[0] is self.masked self.assert_array_equal([2.0, 0.0], self.average(ott, axis=0)) (result, wts) = self.average(ott, axis=0, returned=1) self.assert_array_equal(wts, [1.0, 0.0]) w1 = [0, 1, 1, 1, 1, 0] w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]] x = self.arange(6) self.assert_array_equal(self.average(x, axis=0), 2.5) self.assert_array_equal(self.average(x, axis=0, weights=w1), 2.5) y = self.array([self.arange(6), 2.0 * self.arange(6)]) self.assert_array_equal(self.average(y, None), np.add.reduce(np.arange(6)) * 3.0 / 12.0) self.assert_array_equal(self.average(y, axis=0), np.arange(6) * 3.0 / 2.0) self.assert_array_equal(self.average(y, axis=1), [self.average(x, axis=0), self.average(x, axis=0) * 2.0]) self.assert_array_equal(self.average(y, None, weights=w2), 20.0 / 6.0) self.assert_array_equal(self.average(y, axis=0, weights=w2), [0.0, 1.0, 2.0, 3.0, 4.0, 10.0]) self.assert_array_equal(self.average(y, axis=1), [self.average(x, axis=0), self.average(x, axis=0) * 2.0]) m1 = self.zeros(6) m2 = [0, 0, 1, 1, 0, 0] m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]] m4 = self.ones(6) m5 = [0, 1, 1, 1, 1, 1] self.assert_array_equal(self.average(self.masked_array(x, m1), axis=0), 2.5) self.assert_array_equal(self.average(self.masked_array(x, m2), axis=0), 2.5) self.assert_array_equal(self.average(self.masked_array(x, m5), axis=0), 0.0) self.assert_array_equal(self.count(self.average(self.masked_array(x, m4), axis=0)), 0) z = self.masked_array(y, m3) self.assert_array_equal(self.average(z, None), 20.0 / 6.0) self.assert_array_equal(self.average(z, axis=0), [0.0, 1.0, 99.0, 99.0, 4.0, 7.5]) self.assert_array_equal(self.average(z, axis=1), [2.5, 5.0]) self.assert_array_equal(self.average(z, axis=0, weights=w2), [0.0, 1.0, 99.0, 99.0, 4.0, 10.0]) @np.errstate(all='ignore') def test_A(self): x = self.arange(24) x[5:6] = self.masked x = x.reshape(2, 3, 4) if __name__ == '__main__': setup_base = 'from __main__ import ModuleTester \nimport numpy\ntester = ModuleTester(module)\n' setup_cur = 'import numpy.ma.core as module\n' + setup_base (nrepeat, nloop) = (10, 10) for i in range(1, 8): func = 'tester.test_%i()' % i cur = timeit.Timer(func, setup_cur).repeat(nrepeat, nloop * 10) cur = np.sort(cur) print('#%i' % i + 50 * '.') print(eval('ModuleTester.test_%i.__doc__' % i)) print(f'core_current : {cur[0]:.3f} - {cur[1]:.3f}') # File: numpy-main/numpy/matlib.py import warnings warnings.warn('Importing from numpy.matlib is deprecated since 1.19.0. The matrix subclass is not the recommended way to represent matrices or deal with linear algebra (see https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). Please adjust your code to use regular ndarray. ', PendingDeprecationWarning, stacklevel=2) import numpy as np from numpy.matrixlib.defmatrix import matrix, asmatrix from numpy import * __version__ = np.__version__ __all__ = np.__all__[:] __all__ += ['rand', 'randn', 'repmat'] def empty(shape, dtype=None, order='C'): return ndarray.__new__(matrix, shape, dtype, order=order) def ones(shape, dtype=None, order='C'): a = ndarray.__new__(matrix, shape, dtype, order=order) a.fill(1) return a def zeros(shape, dtype=None, order='C'): a = ndarray.__new__(matrix, shape, dtype, order=order) a.fill(0) return a def identity(n, dtype=None): a = array([1] + n * [0], dtype=dtype) b = empty((n, n), dtype=dtype) b.flat = a return b def eye(n, M=None, k=0, dtype=float, order='C'): return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order)) def rand(*args): if isinstance(args[0], tuple): args = args[0] return asmatrix(np.random.rand(*args)) def randn(*args): if isinstance(args[0], tuple): args = args[0] return asmatrix(np.random.randn(*args)) def repmat(a, m, n): a = asanyarray(a) ndim = a.ndim if ndim == 0: (origrows, origcols) = (1, 1) elif ndim == 1: (origrows, origcols) = (1, a.shape[0]) else: (origrows, origcols) = a.shape rows = origrows * m cols = origcols * n c = a.reshape(1, a.size).repeat(m, 0).reshape(rows, origcols).repeat(n, 0) return c.reshape(rows, cols) # File: numpy-main/numpy/matrixlib/defmatrix.py __all__ = ['matrix', 'bmat', 'asmatrix'] import sys import warnings import ast from .._utils import set_module import numpy._core.numeric as N from numpy._core.numeric import concatenate, isscalar from numpy.linalg import matrix_power def _convert_from_string(data): for char in '[]': data = data.replace(char, '') rows = data.split(';') newdata = [] for (count, row) in enumerate(rows): trow = row.split(',') newrow = [] for col in trow: temp = col.split() newrow.extend(map(ast.literal_eval, temp)) if count == 0: Ncols = len(newrow) elif len(newrow) != Ncols: raise ValueError('Rows not the same size.') newdata.append(newrow) return newdata @set_module('numpy') def asmatrix(data, dtype=None): return matrix(data, dtype=dtype, copy=False) @set_module('numpy') class matrix(N.ndarray): __array_priority__ = 10.0 def __new__(subtype, data, dtype=None, copy=True): warnings.warn('the matrix subclass is not the recommended way to represent matrices or deal with linear algebra (see https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). Please adjust your code to use regular ndarray.', PendingDeprecationWarning, stacklevel=2) if isinstance(data, matrix): dtype2 = data.dtype if dtype is None: dtype = dtype2 if dtype2 == dtype and (not copy): return data return data.astype(dtype) if isinstance(data, N.ndarray): if dtype is None: intype = data.dtype else: intype = N.dtype(dtype) new = data.view(subtype) if intype != data.dtype: return new.astype(intype) if copy: return new.copy() else: return new if isinstance(data, str): data = _convert_from_string(data) copy = None if not copy else True arr = N.array(data, dtype=dtype, copy=copy) ndim = arr.ndim shape = arr.shape if ndim > 2: raise ValueError('matrix must be 2-dimensional') elif ndim == 0: shape = (1, 1) elif ndim == 1: shape = (1, shape[0]) order = 'C' if ndim == 2 and arr.flags.fortran: order = 'F' if not (order or arr.flags.contiguous): arr = arr.copy() ret = N.ndarray.__new__(subtype, shape, arr.dtype, buffer=arr, order=order) return ret def __array_finalize__(self, obj): self._getitem = False if isinstance(obj, matrix) and obj._getitem: return ndim = self.ndim if ndim == 2: return if ndim > 2: newshape = tuple([x for x in self.shape if x > 1]) ndim = len(newshape) if ndim == 2: self.shape = newshape return elif ndim > 2: raise ValueError('shape too large to be a matrix.') else: newshape = self.shape if ndim == 0: self.shape = (1, 1) elif ndim == 1: self.shape = (1, newshape[0]) return def __getitem__(self, index): self._getitem = True try: out = N.ndarray.__getitem__(self, index) finally: self._getitem = False if not isinstance(out, N.ndarray): return out if out.ndim == 0: return out[()] if out.ndim == 1: sh = out.shape[0] try: n = len(index) except Exception: n = 0 if n > 1 and isscalar(index[1]): out.shape = (sh, 1) else: out.shape = (1, sh) return out def __mul__(self, other): if isinstance(other, (N.ndarray, list, tuple)): return N.dot(self, asmatrix(other)) if isscalar(other) or not hasattr(other, '__rmul__'): return N.dot(self, other) return NotImplemented def __rmul__(self, other): return N.dot(other, self) def __imul__(self, other): self[:] = self * other return self def __pow__(self, other): return matrix_power(self, other) def __ipow__(self, other): self[:] = self ** other return self def __rpow__(self, other): return NotImplemented def _align(self, axis): if axis is None: return self[0, 0] elif axis == 0: return self elif axis == 1: return self.transpose() else: raise ValueError('unsupported axis') def _collapse(self, axis): if axis is None: return self[0, 0] else: return self def tolist(self): return self.__array__().tolist() def sum(self, axis=None, dtype=None, out=None): return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis) def squeeze(self, axis=None): return N.ndarray.squeeze(self, axis=axis) def flatten(self, order='C'): return N.ndarray.flatten(self, order=order) def mean(self, axis=None, dtype=None, out=None): return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis) def std(self, axis=None, dtype=None, out=None, ddof=0): return N.ndarray.std(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis) def var(self, axis=None, dtype=None, out=None, ddof=0): return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis) def prod(self, axis=None, dtype=None, out=None): return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis) def any(self, axis=None, out=None): return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis) def all(self, axis=None, out=None): return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis) def max(self, axis=None, out=None): return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis) def argmax(self, axis=None, out=None): return N.ndarray.argmax(self, axis, out)._align(axis) def min(self, axis=None, out=None): return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis) def argmin(self, axis=None, out=None): return N.ndarray.argmin(self, axis, out)._align(axis) def ptp(self, axis=None, out=None): return N.ptp(self, axis, out)._align(axis) @property def I(self): (M, N) = self.shape if M == N: from numpy.linalg import inv as func else: from numpy.linalg import pinv as func return asmatrix(func(self)) @property def A(self): return self.__array__() @property def A1(self): return self.__array__().ravel() def ravel(self, order='C'): return N.ndarray.ravel(self, order=order) @property def T(self): return self.transpose() @property def H(self): if issubclass(self.dtype.type, N.complexfloating): return self.transpose().conjugate() else: return self.transpose() getT = T.fget getA = A.fget getA1 = A1.fget getH = H.fget getI = I.fget def _from_string(str, gdict, ldict): rows = str.split(';') rowtup = [] for row in rows: trow = row.split(',') newrow = [] for x in trow: newrow.extend(x.split()) trow = newrow coltup = [] for col in trow: col = col.strip() try: thismat = ldict[col] except KeyError: try: thismat = gdict[col] except KeyError as e: raise NameError(f'name {col!r} is not defined') from None coltup.append(thismat) rowtup.append(concatenate(coltup, axis=-1)) return concatenate(rowtup, axis=0) @set_module('numpy') def bmat(obj, ldict=None, gdict=None): if isinstance(obj, str): if gdict is None: frame = sys._getframe().f_back glob_dict = frame.f_globals loc_dict = frame.f_locals else: glob_dict = gdict loc_dict = ldict return matrix(_from_string(obj, glob_dict, loc_dict)) if isinstance(obj, (tuple, list)): arr_rows = [] for row in obj: if isinstance(row, N.ndarray): return matrix(concatenate(obj, axis=-1)) else: arr_rows.append(concatenate(row, axis=-1)) return matrix(concatenate(arr_rows, axis=0)) if isinstance(obj, N.ndarray): return matrix(obj) # File: numpy-main/numpy/polynomial/__init__.py """""" from .polynomial import Polynomial from .chebyshev import Chebyshev from .legendre import Legendre from .hermite import Hermite from .hermite_e import HermiteE from .laguerre import Laguerre __all__ = ['set_default_printstyle', 'polynomial', 'Polynomial', 'chebyshev', 'Chebyshev', 'legendre', 'Legendre', 'hermite', 'Hermite', 'hermite_e', 'HermiteE', 'laguerre', 'Laguerre'] def set_default_printstyle(style): if style not in ('unicode', 'ascii'): raise ValueError(f"Unsupported format string '{style}'. Valid options are 'ascii' and 'unicode'") _use_unicode = True if style == 'ascii': _use_unicode = False from ._polybase import ABCPolyBase ABCPolyBase._use_unicode = _use_unicode from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester # File: numpy-main/numpy/polynomial/_polybase.py """""" import os import abc import numbers from typing import Callable import numpy as np from . import polyutils as pu __all__ = ['ABCPolyBase'] class ABCPolyBase(abc.ABC): __hash__ = None __array_ufunc__ = None maxpower = 100 _superscript_mapping = str.maketrans({'0': '⁰', '1': '¹', '2': '²', '3': '³', '4': '⁴', '5': '⁵', '6': '⁶', '7': '⁷', '8': '⁸', '9': '⁹'}) _subscript_mapping = str.maketrans({'0': '₀', '1': '₁', '2': '₂', '3': '₃', '4': '₄', '5': '₅', '6': '₆', '7': '₇', '8': '₈', '9': '₉'}) _use_unicode = not os.name == 'nt' @property def symbol(self): return self._symbol @property @abc.abstractmethod def domain(self): pass @property @abc.abstractmethod def window(self): pass @property @abc.abstractmethod def basis_name(self): pass @staticmethod @abc.abstractmethod def _add(c1, c2): pass @staticmethod @abc.abstractmethod def _sub(c1, c2): pass @staticmethod @abc.abstractmethod def _mul(c1, c2): pass @staticmethod @abc.abstractmethod def _div(c1, c2): pass @staticmethod @abc.abstractmethod def _pow(c, pow, maxpower=None): pass @staticmethod @abc.abstractmethod def _val(x, c): pass @staticmethod @abc.abstractmethod def _int(c, m, k, lbnd, scl): pass @staticmethod @abc.abstractmethod def _der(c, m, scl): pass @staticmethod @abc.abstractmethod def _fit(x, y, deg, rcond, full): pass @staticmethod @abc.abstractmethod def _line(off, scl): pass @staticmethod @abc.abstractmethod def _roots(c): pass @staticmethod @abc.abstractmethod def _fromroots(r): pass def has_samecoef(self, other): if len(self.coef) != len(other.coef): return False elif not np.all(self.coef == other.coef): return False else: return True def has_samedomain(self, other): return np.all(self.domain == other.domain) def has_samewindow(self, other): return np.all(self.window == other.window) def has_sametype(self, other): return isinstance(other, self.__class__) def _get_coefficients(self, other): if isinstance(other, ABCPolyBase): if not isinstance(other, self.__class__): raise TypeError('Polynomial types differ') elif not np.all(self.domain == other.domain): raise TypeError('Domains differ') elif not np.all(self.window == other.window): raise TypeError('Windows differ') elif self.symbol != other.symbol: raise ValueError('Polynomial symbols differ') return other.coef return other def __init__(self, coef, domain=None, window=None, symbol='x'): [coef] = pu.as_series([coef], trim=False) self.coef = coef if domain is not None: [domain] = pu.as_series([domain], trim=False) if len(domain) != 2: raise ValueError('Domain has wrong number of elements.') self.domain = domain if window is not None: [window] = pu.as_series([window], trim=False) if len(window) != 2: raise ValueError('Window has wrong number of elements.') self.window = window try: if not symbol.isidentifier(): raise ValueError('Symbol string must be a valid Python identifier') except AttributeError: raise TypeError('Symbol must be a non-empty string') self._symbol = symbol def __repr__(self): coef = repr(self.coef)[6:-1] domain = repr(self.domain)[6:-1] window = repr(self.window)[6:-1] name = self.__class__.__name__ return f"{name}({coef}, domain={domain}, window={window}, symbol='{self.symbol}')" def __format__(self, fmt_str): if fmt_str == '': return self.__str__() if fmt_str not in ('ascii', 'unicode'): raise ValueError(f"Unsupported format string '{fmt_str}' passed to {self.__class__}.__format__. Valid options are 'ascii' and 'unicode'") if fmt_str == 'ascii': return self._generate_string(self._str_term_ascii) return self._generate_string(self._str_term_unicode) def __str__(self): if self._use_unicode: return self._generate_string(self._str_term_unicode) return self._generate_string(self._str_term_ascii) def _generate_string(self, term_method): linewidth = np.get_printoptions().get('linewidth', 75) if linewidth < 1: linewidth = 1 out = pu.format_float(self.coef[0]) (off, scale) = self.mapparms() (scaled_symbol, needs_parens) = self._format_term(pu.format_float, off, scale) if needs_parens: scaled_symbol = '(' + scaled_symbol + ')' for (i, coef) in enumerate(self.coef[1:]): out += ' ' power = str(i + 1) try: if coef >= 0: next_term = '+ ' + pu.format_float(coef, parens=True) else: next_term = '- ' + pu.format_float(-coef, parens=True) except TypeError: next_term = f'+ {coef}' next_term += term_method(power, scaled_symbol) line_len = len(out.split('\n')[-1]) + len(next_term) if i < len(self.coef[1:]) - 1: line_len += 2 if line_len >= linewidth: next_term = next_term.replace(' ', '\n', 1) out += next_term return out @classmethod def _str_term_unicode(cls, i, arg_str): if cls.basis_name is None: raise NotImplementedError('Subclasses must define either a basis_name, or override _str_term_unicode(cls, i, arg_str)') return f'·{cls.basis_name}{i.translate(cls._subscript_mapping)}({arg_str})' @classmethod def _str_term_ascii(cls, i, arg_str): if cls.basis_name is None: raise NotImplementedError('Subclasses must define either a basis_name, or override _str_term_ascii(cls, i, arg_str)') return f' {cls.basis_name}_{i}({arg_str})' @classmethod def _repr_latex_term(cls, i, arg_str, needs_parens): if cls.basis_name is None: raise NotImplementedError('Subclasses must define either a basis name, or override _repr_latex_term(i, arg_str, needs_parens)') return f'{{{cls.basis_name}}}_{{{i}}}({arg_str})' @staticmethod def _repr_latex_scalar(x, parens=False): return '\\text{{{}}}'.format(pu.format_float(x, parens=parens)) def _format_term(self, scalar_format: Callable, off: float, scale: float): if off == 0 and scale == 1: term = self.symbol needs_parens = False elif scale == 1: term = f'{scalar_format(off)} + {self.symbol}' needs_parens = True elif off == 0: term = f'{scalar_format(scale)}{self.symbol}' needs_parens = True else: term = f'{scalar_format(off)} + {scalar_format(scale)}{self.symbol}' needs_parens = True return (term, needs_parens) def _repr_latex_(self): (off, scale) = self.mapparms() (term, needs_parens) = self._format_term(self._repr_latex_scalar, off, scale) mute = '\\color{{LightGray}}{{{}}}'.format parts = [] for (i, c) in enumerate(self.coef): if i == 0: coef_str = f'{self._repr_latex_scalar(c)}' elif not isinstance(c, numbers.Real): coef_str = f' + ({self._repr_latex_scalar(c)})' elif c >= 0: coef_str = f' + {self._repr_latex_scalar(c, parens=True)}' else: coef_str = f' - {self._repr_latex_scalar(-c, parens=True)}' term_str = self._repr_latex_term(i, term, needs_parens) if term_str == '1': part = coef_str else: part = f'{coef_str}\\,{term_str}' if c == 0: part = mute(part) parts.append(part) if parts: body = ''.join(parts) else: body = '0' return f'${self.symbol} \\mapsto {body}$' def __getstate__(self): ret = self.__dict__.copy() ret['coef'] = self.coef.copy() ret['domain'] = self.domain.copy() ret['window'] = self.window.copy() ret['symbol'] = self.symbol return ret def __setstate__(self, dict): self.__dict__ = dict def __call__(self, arg): arg = pu.mapdomain(arg, self.domain, self.window) return self._val(arg, self.coef) def __iter__(self): return iter(self.coef) def __len__(self): return len(self.coef) def __neg__(self): return self.__class__(-self.coef, self.domain, self.window, self.symbol) def __pos__(self): return self def __add__(self, other): othercoef = self._get_coefficients(other) try: coef = self._add(self.coef, othercoef) except Exception: return NotImplemented return self.__class__(coef, self.domain, self.window, self.symbol) def __sub__(self, other): othercoef = self._get_coefficients(other) try: coef = self._sub(self.coef, othercoef) except Exception: return NotImplemented return self.__class__(coef, self.domain, self.window, self.symbol) def __mul__(self, other): othercoef = self._get_coefficients(other) try: coef = self._mul(self.coef, othercoef) except Exception: return NotImplemented return self.__class__(coef, self.domain, self.window, self.symbol) def __truediv__(self, other): if not isinstance(other, numbers.Number) or isinstance(other, bool): raise TypeError(f"unsupported types for true division: '{type(self)}', '{type(other)}'") return self.__floordiv__(other) def __floordiv__(self, other): res = self.__divmod__(other) if res is NotImplemented: return res return res[0] def __mod__(self, other): res = self.__divmod__(other) if res is NotImplemented: return res return res[1] def __divmod__(self, other): othercoef = self._get_coefficients(other) try: (quo, rem) = self._div(self.coef, othercoef) except ZeroDivisionError: raise except Exception: return NotImplemented quo = self.__class__(quo, self.domain, self.window, self.symbol) rem = self.__class__(rem, self.domain, self.window, self.symbol) return (quo, rem) def __pow__(self, other): coef = self._pow(self.coef, other, maxpower=self.maxpower) res = self.__class__(coef, self.domain, self.window, self.symbol) return res def __radd__(self, other): try: coef = self._add(other, self.coef) except Exception: return NotImplemented return self.__class__(coef, self.domain, self.window, self.symbol) def __rsub__(self, other): try: coef = self._sub(other, self.coef) except Exception: return NotImplemented return self.__class__(coef, self.domain, self.window, self.symbol) def __rmul__(self, other): try: coef = self._mul(other, self.coef) except Exception: return NotImplemented return self.__class__(coef, self.domain, self.window, self.symbol) def __rdiv__(self, other): return self.__rfloordiv__(other) def __rtruediv__(self, other): return NotImplemented def __rfloordiv__(self, other): res = self.__rdivmod__(other) if res is NotImplemented: return res return res[0] def __rmod__(self, other): res = self.__rdivmod__(other) if res is NotImplemented: return res return res[1] def __rdivmod__(self, other): try: (quo, rem) = self._div(other, self.coef) except ZeroDivisionError: raise except Exception: return NotImplemented quo = self.__class__(quo, self.domain, self.window, self.symbol) rem = self.__class__(rem, self.domain, self.window, self.symbol) return (quo, rem) def __eq__(self, other): res = isinstance(other, self.__class__) and np.all(self.domain == other.domain) and np.all(self.window == other.window) and (self.coef.shape == other.coef.shape) and np.all(self.coef == other.coef) and (self.symbol == other.symbol) return res def __ne__(self, other): return not self.__eq__(other) def copy(self): return self.__class__(self.coef, self.domain, self.window, self.symbol) def degree(self): return len(self) - 1 def cutdeg(self, deg): return self.truncate(deg + 1) def trim(self, tol=0): coef = pu.trimcoef(self.coef, tol) return self.__class__(coef, self.domain, self.window, self.symbol) def truncate(self, size): isize = int(size) if isize != size or isize < 1: raise ValueError('size must be a positive integer') if isize >= len(self.coef): coef = self.coef else: coef = self.coef[:isize] return self.__class__(coef, self.domain, self.window, self.symbol) def convert(self, domain=None, kind=None, window=None): if kind is None: kind = self.__class__ if domain is None: domain = kind.domain if window is None: window = kind.window return self(kind.identity(domain, window=window, symbol=self.symbol)) def mapparms(self): return pu.mapparms(self.domain, self.window) def integ(self, m=1, k=[], lbnd=None): (off, scl) = self.mapparms() if lbnd is None: lbnd = 0 else: lbnd = off + scl * lbnd coef = self._int(self.coef, m, k, lbnd, 1.0 / scl) return self.__class__(coef, self.domain, self.window, self.symbol) def deriv(self, m=1): (off, scl) = self.mapparms() coef = self._der(self.coef, m, scl) return self.__class__(coef, self.domain, self.window, self.symbol) def roots(self): roots = self._roots(self.coef) return pu.mapdomain(roots, self.window, self.domain) def linspace(self, n=100, domain=None): if domain is None: domain = self.domain x = np.linspace(domain[0], domain[1], n) y = self(x) return (x, y) @classmethod def fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None, window=None, symbol='x'): if domain is None: domain = pu.getdomain(x) if domain[0] == domain[1]: domain[0] -= 1 domain[1] += 1 elif type(domain) is list and len(domain) == 0: domain = cls.domain if window is None: window = cls.window xnew = pu.mapdomain(x, domain, window) res = cls._fit(xnew, y, deg, w=w, rcond=rcond, full=full) if full: [coef, status] = res return (cls(coef, domain=domain, window=window, symbol=symbol), status) else: coef = res return cls(coef, domain=domain, window=window, symbol=symbol) @classmethod def fromroots(cls, roots, domain=[], window=None, symbol='x'): [roots] = pu.as_series([roots], trim=False) if domain is None: domain = pu.getdomain(roots) elif type(domain) is list and len(domain) == 0: domain = cls.domain if window is None: window = cls.window deg = len(roots) (off, scl) = pu.mapparms(domain, window) rnew = off + scl * roots coef = cls._fromroots(rnew) / scl ** deg return cls(coef, domain=domain, window=window, symbol=symbol) @classmethod def identity(cls, domain=None, window=None, symbol='x'): if domain is None: domain = cls.domain if window is None: window = cls.window (off, scl) = pu.mapparms(window, domain) coef = cls._line(off, scl) return cls(coef, domain, window, symbol) @classmethod def basis(cls, deg, domain=None, window=None, symbol='x'): if domain is None: domain = cls.domain if window is None: window = cls.window ideg = int(deg) if ideg != deg or ideg < 0: raise ValueError('deg must be non-negative integer') return cls([0] * ideg + [1], domain, window, symbol) @classmethod def cast(cls, series, domain=None, window=None): if domain is None: domain = cls.domain if window is None: window = cls.window return series.convert(domain, cls, window) # File: numpy-main/numpy/polynomial/chebyshev.py """""" import numpy as np import numpy.linalg as la from numpy.lib.array_utils import normalize_axis_index from . import polyutils as pu from ._polybase import ABCPolyBase __all__ = ['chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd', 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', 'chebval', 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots', 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1', 'chebpts2', 'Chebyshev', 'chebval2d', 'chebval3d', 'chebgrid2d', 'chebgrid3d', 'chebvander2d', 'chebvander3d', 'chebcompanion', 'chebgauss', 'chebweight', 'chebinterpolate'] chebtrim = pu.trimcoef def _cseries_to_zseries(c): n = c.size zs = np.zeros(2 * n - 1, dtype=c.dtype) zs[n - 1:] = c / 2 return zs + zs[::-1] def _zseries_to_cseries(zs): n = (zs.size + 1) // 2 c = zs[n - 1:].copy() c[1:n] *= 2 return c def _zseries_mul(z1, z2): return np.convolve(z1, z2) def _zseries_div(z1, z2): z1 = z1.copy() z2 = z2.copy() lc1 = len(z1) lc2 = len(z2) if lc2 == 1: z1 /= z2 return (z1, z1[:1] * 0) elif lc1 < lc2: return (z1[:1] * 0, z1) else: dlen = lc1 - lc2 scl = z2[0] z2 /= scl quo = np.empty(dlen + 1, dtype=z1.dtype) i = 0 j = dlen while i < j: r = z1[i] quo[i] = z1[i] quo[dlen - i] = r tmp = r * z2 z1[i:i + lc2] -= tmp z1[j:j + lc2] -= tmp i += 1 j -= 1 r = z1[i] quo[i] = r tmp = r * z2 z1[i:i + lc2] -= tmp quo /= scl rem = z1[i + 1:i - 1 + lc2].copy() return (quo, rem) def _zseries_der(zs): n = len(zs) // 2 ns = np.array([-1, 0, 1], dtype=zs.dtype) zs *= np.arange(-n, n + 1) * 2 (d, r) = _zseries_div(zs, ns) return d def _zseries_int(zs): n = 1 + len(zs) // 2 ns = np.array([-1, 0, 1], dtype=zs.dtype) zs = _zseries_mul(zs, ns) div = np.arange(-n, n + 1) * 2 zs[:n] /= div[:n] zs[n + 1:] /= div[n + 1:] zs[n] = 0 return zs def poly2cheb(pol): [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1): res = chebadd(chebmulx(res), pol[i]) return res def cheb2poly(c): from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n < 3: return c else: c0 = c[-2] c1 = c[-1] for i in range(n - 1, 1, -1): tmp = c0 c0 = polysub(c[i - 2], c1) c1 = polyadd(tmp, polymulx(c1) * 2) return polyadd(c0, polymulx(c1)) chebdomain = np.array([-1.0, 1.0]) chebzero = np.array([0]) chebone = np.array([1]) chebx = np.array([0, 1]) def chebline(off, scl): if scl != 0: return np.array([off, scl]) else: return np.array([off]) def chebfromroots(roots): return pu._fromroots(chebline, chebmul, roots) def chebadd(c1, c2): return pu._add(c1, c2) def chebsub(c1, c2): return pu._sub(c1, c2) def chebmulx(c): [c] = pu.as_series([c]) if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0] * 0 prd[1] = c[0] if len(c) > 1: tmp = c[1:] / 2 prd[2:] = tmp prd[0:-2] += tmp return prd def chebmul(c1, c2): [c1, c2] = pu.as_series([c1, c2]) z1 = _cseries_to_zseries(c1) z2 = _cseries_to_zseries(c2) prd = _zseries_mul(z1, z2) ret = _zseries_to_cseries(prd) return pu.trimseq(ret) def chebdiv(c1, c2): [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0: raise ZeroDivisionError lc1 = len(c1) lc2 = len(c2) if lc1 < lc2: return (c1[:1] * 0, c1) elif lc2 == 1: return (c1 / c2[-1], c1[:1] * 0) else: z1 = _cseries_to_zseries(c1) z2 = _cseries_to_zseries(c2) (quo, rem) = _zseries_div(z1, z2) quo = pu.trimseq(_zseries_to_cseries(quo)) rem = pu.trimseq(_zseries_to_cseries(rem)) return (quo, rem) def chebpow(c, pow, maxpower=16): [c] = pu.as_series([c]) power = int(pow) if power != pow or power < 0: raise ValueError('Power must be a non-negative integer.') elif maxpower is not None and power > maxpower: raise ValueError('Power is too large') elif power == 0: return np.array([1], dtype=c.dtype) elif power == 1: return c else: zs = _cseries_to_zseries(c) prd = zs for i in range(2, power + 1): prd = np.convolve(prd, zs) return _zseries_to_cseries(prd) def chebder(c, m=1, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt = pu._as_int(m, 'the order of derivation') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of derivation must be non-negative') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) n = len(c) if cnt >= n: c = c[:1] * 0 else: for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 2, -1): der[j - 1] = 2 * j * c[j] c[j - 2] += j * c[j] / (j - 2) if n > 1: der[1] = 4 * c[2] der[0] = c[1] c = der c = np.moveaxis(c, 0, iaxis) return c def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt = pu._as_int(m, 'the order of integration') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of integration must be non-negative') if len(k) > cnt: raise ValueError('Too many integration constants') if np.ndim(lbnd) != 0: raise ValueError('lbnd must be a scalar.') if np.ndim(scl) != 0: raise ValueError('scl must be a scalar.') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) k = list(k) + [0] * (cnt - len(k)) for i in range(cnt): n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0] * 0 tmp[1] = c[0] if n > 1: tmp[2] = c[1] / 4 for j in range(2, n): tmp[j + 1] = c[j] / (2 * (j + 1)) tmp[j - 1] -= c[j] / (2 * (j - 1)) tmp[0] += k[i] - chebval(lbnd, tmp) c = tmp c = np.moveaxis(c, 0, iaxis) return c def chebval(x, c, tensor=True): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,) * x.ndim) if len(c) == 1: c0 = c[0] c1 = 0 elif len(c) == 2: c0 = c[0] c1 = c[1] else: x2 = 2 * x c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1): tmp = c0 c0 = c[-i] - c1 c1 = tmp + c1 * x2 return c0 + c1 * x def chebval2d(x, y, c): return pu._valnd(chebval, c, x, y) def chebgrid2d(x, y, c): return pu._gridnd(chebval, c, x, y) def chebval3d(x, y, z, c): return pu._valnd(chebval, c, x, y, z) def chebgrid3d(x, y, z, c): return pu._gridnd(chebval, c, x, y, z) def chebvander(x, deg): ideg = pu._as_int(deg, 'deg') if ideg < 0: raise ValueError('deg must be non-negative') x = np.array(x, copy=None, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x * 0 + 1 if ideg > 0: x2 = 2 * x v[1] = x for i in range(2, ideg + 1): v[i] = v[i - 1] * x2 - v[i - 2] return np.moveaxis(v, 0, -1) def chebvander2d(x, y, deg): return pu._vander_nd_flat((chebvander, chebvander), (x, y), deg) def chebvander3d(x, y, z, deg): return pu._vander_nd_flat((chebvander, chebvander, chebvander), (x, y, z), deg) def chebfit(x, y, deg, rcond=None, full=False, w=None): return pu._fit(chebvander, x, y, deg, rcond, full, w) def chebcompanion(c): [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-c[0] / c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) scl = np.array([1.0] + [np.sqrt(0.5)] * (n - 1)) top = mat.reshape(-1)[1::n + 1] bot = mat.reshape(-1)[n::n + 1] top[0] = np.sqrt(0.5) top[1:] = 1 / 2 bot[...] = top mat[:, -1] -= c[:-1] / c[-1] * (scl / scl[-1]) * 0.5 return mat def chebroots(c): [c] = pu.as_series([c]) if len(c) < 2: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([-c[0] / c[1]]) m = chebcompanion(c)[::-1, ::-1] r = la.eigvals(m) r.sort() return r def chebinterpolate(func, deg, args=()): deg = np.asarray(deg) if deg.ndim > 0 or deg.dtype.kind not in 'iu' or deg.size == 0: raise TypeError('deg must be an int') if deg < 0: raise ValueError('expected deg >= 0') order = deg + 1 xcheb = chebpts1(order) yfunc = func(xcheb, *args) m = chebvander(xcheb, deg) c = np.dot(m.T, yfunc) c[0] /= order c[1:] /= 0.5 * order return c def chebgauss(deg): ideg = pu._as_int(deg, 'deg') if ideg <= 0: raise ValueError('deg must be a positive integer') x = np.cos(np.pi * np.arange(1, 2 * ideg, 2) / (2.0 * ideg)) w = np.ones(ideg) * (np.pi / ideg) return (x, w) def chebweight(x): w = 1.0 / (np.sqrt(1.0 + x) * np.sqrt(1.0 - x)) return w def chebpts1(npts): _npts = int(npts) if _npts != npts: raise ValueError('npts must be integer') if _npts < 1: raise ValueError('npts must be >= 1') x = 0.5 * np.pi / _npts * np.arange(-_npts + 1, _npts + 1, 2) return np.sin(x) def chebpts2(npts): _npts = int(npts) if _npts != npts: raise ValueError('npts must be integer') if _npts < 2: raise ValueError('npts must be >= 2') x = np.linspace(-np.pi, 0, _npts) return np.cos(x) class Chebyshev(ABCPolyBase): _add = staticmethod(chebadd) _sub = staticmethod(chebsub) _mul = staticmethod(chebmul) _div = staticmethod(chebdiv) _pow = staticmethod(chebpow) _val = staticmethod(chebval) _int = staticmethod(chebint) _der = staticmethod(chebder) _fit = staticmethod(chebfit) _line = staticmethod(chebline) _roots = staticmethod(chebroots) _fromroots = staticmethod(chebfromroots) @classmethod def interpolate(cls, func, deg, domain=None, args=()): if domain is None: domain = cls.domain xfunc = lambda x: func(pu.mapdomain(x, cls.window, domain), *args) coef = chebinterpolate(xfunc, deg) return cls(coef, domain=domain) domain = np.array(chebdomain) window = np.array(chebdomain) basis_name = 'T' # File: numpy-main/numpy/polynomial/hermite.py """""" import numpy as np import numpy.linalg as la from numpy.lib.array_utils import normalize_axis_index from . import polyutils as pu from ._polybase import ABCPolyBase __all__ = ['hermzero', 'hermone', 'hermx', 'hermdomain', 'hermline', 'hermadd', 'hermsub', 'hermmulx', 'hermmul', 'hermdiv', 'hermpow', 'hermval', 'hermder', 'hermint', 'herm2poly', 'poly2herm', 'hermfromroots', 'hermvander', 'hermfit', 'hermtrim', 'hermroots', 'Hermite', 'hermval2d', 'hermval3d', 'hermgrid2d', 'hermgrid3d', 'hermvander2d', 'hermvander3d', 'hermcompanion', 'hermgauss', 'hermweight'] hermtrim = pu.trimcoef def poly2herm(pol): [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1): res = hermadd(hermmulx(res), pol[i]) return res def herm2poly(c): from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n == 1: return c if n == 2: c[1] *= 2 return c else: c0 = c[-2] c1 = c[-1] for i in range(n - 1, 1, -1): tmp = c0 c0 = polysub(c[i - 2], c1 * (2 * (i - 1))) c1 = polyadd(tmp, polymulx(c1) * 2) return polyadd(c0, polymulx(c1) * 2) hermdomain = np.array([-1.0, 1.0]) hermzero = np.array([0]) hermone = np.array([1]) hermx = np.array([0, 1 / 2]) def hermline(off, scl): if scl != 0: return np.array([off, scl / 2]) else: return np.array([off]) def hermfromroots(roots): return pu._fromroots(hermline, hermmul, roots) def hermadd(c1, c2): return pu._add(c1, c2) def hermsub(c1, c2): return pu._sub(c1, c2) def hermmulx(c): [c] = pu.as_series([c]) if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0] * 0 prd[1] = c[0] / 2 for i in range(1, len(c)): prd[i + 1] = c[i] / 2 prd[i - 1] += c[i] * i return prd def hermmul(c1, c2): [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c = c2 xs = c1 else: c = c1 xs = c2 if len(c) == 1: c0 = c[0] * xs c1 = 0 elif len(c) == 2: c0 = c[0] * xs c1 = c[1] * xs else: nd = len(c) c0 = c[-2] * xs c1 = c[-1] * xs for i in range(3, len(c) + 1): tmp = c0 nd = nd - 1 c0 = hermsub(c[-i] * xs, c1 * (2 * (nd - 1))) c1 = hermadd(tmp, hermmulx(c1) * 2) return hermadd(c0, hermmulx(c1) * 2) def hermdiv(c1, c2): return pu._div(hermmul, c1, c2) def hermpow(c, pow, maxpower=16): return pu._pow(hermmul, c, pow, maxpower) def hermder(c, m=1, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt = pu._as_int(m, 'the order of derivation') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of derivation must be non-negative') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) n = len(c) if cnt >= n: c = c[:1] * 0 else: for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 0, -1): der[j - 1] = 2 * j * c[j] c = der c = np.moveaxis(c, 0, iaxis) return c def hermint(c, m=1, k=[], lbnd=0, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt = pu._as_int(m, 'the order of integration') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of integration must be non-negative') if len(k) > cnt: raise ValueError('Too many integration constants') if np.ndim(lbnd) != 0: raise ValueError('lbnd must be a scalar.') if np.ndim(scl) != 0: raise ValueError('scl must be a scalar.') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) k = list(k) + [0] * (cnt - len(k)) for i in range(cnt): n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0] * 0 tmp[1] = c[0] / 2 for j in range(1, n): tmp[j + 1] = c[j] / (2 * (j + 1)) tmp[0] += k[i] - hermval(lbnd, tmp) c = tmp c = np.moveaxis(c, 0, iaxis) return c def hermval(x, c, tensor=True): c = np.array(c, ndmin=1, copy=None) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,) * x.ndim) x2 = x * 2 if len(c) == 1: c0 = c[0] c1 = 0 elif len(c) == 2: c0 = c[0] c1 = c[1] else: nd = len(c) c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1): tmp = c0 nd = nd - 1 c0 = c[-i] - c1 * (2 * (nd - 1)) c1 = tmp + c1 * x2 return c0 + c1 * x2 def hermval2d(x, y, c): return pu._valnd(hermval, c, x, y) def hermgrid2d(x, y, c): return pu._gridnd(hermval, c, x, y) def hermval3d(x, y, z, c): return pu._valnd(hermval, c, x, y, z) def hermgrid3d(x, y, z, c): return pu._gridnd(hermval, c, x, y, z) def hermvander(x, deg): ideg = pu._as_int(deg, 'deg') if ideg < 0: raise ValueError('deg must be non-negative') x = np.array(x, copy=None, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x * 0 + 1 if ideg > 0: x2 = x * 2 v[1] = x2 for i in range(2, ideg + 1): v[i] = v[i - 1] * x2 - v[i - 2] * (2 * (i - 1)) return np.moveaxis(v, 0, -1) def hermvander2d(x, y, deg): return pu._vander_nd_flat((hermvander, hermvander), (x, y), deg) def hermvander3d(x, y, z, deg): return pu._vander_nd_flat((hermvander, hermvander, hermvander), (x, y, z), deg) def hermfit(x, y, deg, rcond=None, full=False, w=None): return pu._fit(hermvander, x, y, deg, rcond, full, w) def hermcompanion(c): [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-0.5 * c[0] / c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) scl = np.hstack((1.0, 1.0 / np.sqrt(2.0 * np.arange(n - 1, 0, -1)))) scl = np.multiply.accumulate(scl)[::-1] top = mat.reshape(-1)[1::n + 1] bot = mat.reshape(-1)[n::n + 1] top[...] = np.sqrt(0.5 * np.arange(1, n)) bot[...] = top mat[:, -1] -= scl * c[:-1] / (2.0 * c[-1]) return mat def hermroots(c): [c] = pu.as_series([c]) if len(c) <= 1: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([-0.5 * c[0] / c[1]]) m = hermcompanion(c)[::-1, ::-1] r = la.eigvals(m) r.sort() return r def _normed_hermite_n(x, n): if n == 0: return np.full(x.shape, 1 / np.sqrt(np.sqrt(np.pi))) c0 = 0.0 c1 = 1.0 / np.sqrt(np.sqrt(np.pi)) nd = float(n) for i in range(n - 1): tmp = c0 c0 = -c1 * np.sqrt((nd - 1.0) / nd) c1 = tmp + c1 * x * np.sqrt(2.0 / nd) nd = nd - 1.0 return c0 + c1 * x * np.sqrt(2) def hermgauss(deg): ideg = pu._as_int(deg, 'deg') if ideg <= 0: raise ValueError('deg must be a positive integer') c = np.array([0] * deg + [1], dtype=np.float64) m = hermcompanion(c) x = la.eigvalsh(m) dy = _normed_hermite_n(x, ideg) df = _normed_hermite_n(x, ideg - 1) * np.sqrt(2 * ideg) x -= dy / df fm = _normed_hermite_n(x, ideg - 1) fm /= np.abs(fm).max() w = 1 / (fm * fm) w = (w + w[::-1]) / 2 x = (x - x[::-1]) / 2 w *= np.sqrt(np.pi) / w.sum() return (x, w) def hermweight(x): w = np.exp(-x ** 2) return w class Hermite(ABCPolyBase): _add = staticmethod(hermadd) _sub = staticmethod(hermsub) _mul = staticmethod(hermmul) _div = staticmethod(hermdiv) _pow = staticmethod(hermpow) _val = staticmethod(hermval) _int = staticmethod(hermint) _der = staticmethod(hermder) _fit = staticmethod(hermfit) _line = staticmethod(hermline) _roots = staticmethod(hermroots) _fromroots = staticmethod(hermfromroots) domain = np.array(hermdomain) window = np.array(hermdomain) basis_name = 'H' # File: numpy-main/numpy/polynomial/hermite_e.py """""" import numpy as np import numpy.linalg as la from numpy.lib.array_utils import normalize_axis_index from . import polyutils as pu from ._polybase import ABCPolyBase __all__ = ['hermezero', 'hermeone', 'hermex', 'hermedomain', 'hermeline', 'hermeadd', 'hermesub', 'hermemulx', 'hermemul', 'hermediv', 'hermepow', 'hermeval', 'hermeder', 'hermeint', 'herme2poly', 'poly2herme', 'hermefromroots', 'hermevander', 'hermefit', 'hermetrim', 'hermeroots', 'HermiteE', 'hermeval2d', 'hermeval3d', 'hermegrid2d', 'hermegrid3d', 'hermevander2d', 'hermevander3d', 'hermecompanion', 'hermegauss', 'hermeweight'] hermetrim = pu.trimcoef def poly2herme(pol): [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1): res = hermeadd(hermemulx(res), pol[i]) return res def herme2poly(c): from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n == 1: return c if n == 2: return c else: c0 = c[-2] c1 = c[-1] for i in range(n - 1, 1, -1): tmp = c0 c0 = polysub(c[i - 2], c1 * (i - 1)) c1 = polyadd(tmp, polymulx(c1)) return polyadd(c0, polymulx(c1)) hermedomain = np.array([-1.0, 1.0]) hermezero = np.array([0]) hermeone = np.array([1]) hermex = np.array([0, 1]) def hermeline(off, scl): if scl != 0: return np.array([off, scl]) else: return np.array([off]) def hermefromroots(roots): return pu._fromroots(hermeline, hermemul, roots) def hermeadd(c1, c2): return pu._add(c1, c2) def hermesub(c1, c2): return pu._sub(c1, c2) def hermemulx(c): [c] = pu.as_series([c]) if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0] * 0 prd[1] = c[0] for i in range(1, len(c)): prd[i + 1] = c[i] prd[i - 1] += c[i] * i return prd def hermemul(c1, c2): [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c = c2 xs = c1 else: c = c1 xs = c2 if len(c) == 1: c0 = c[0] * xs c1 = 0 elif len(c) == 2: c0 = c[0] * xs c1 = c[1] * xs else: nd = len(c) c0 = c[-2] * xs c1 = c[-1] * xs for i in range(3, len(c) + 1): tmp = c0 nd = nd - 1 c0 = hermesub(c[-i] * xs, c1 * (nd - 1)) c1 = hermeadd(tmp, hermemulx(c1)) return hermeadd(c0, hermemulx(c1)) def hermediv(c1, c2): return pu._div(hermemul, c1, c2) def hermepow(c, pow, maxpower=16): return pu._pow(hermemul, c, pow, maxpower) def hermeder(c, m=1, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt = pu._as_int(m, 'the order of derivation') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of derivation must be non-negative') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) n = len(c) if cnt >= n: return c[:1] * 0 else: for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 0, -1): der[j - 1] = j * c[j] c = der c = np.moveaxis(c, 0, iaxis) return c def hermeint(c, m=1, k=[], lbnd=0, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt = pu._as_int(m, 'the order of integration') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of integration must be non-negative') if len(k) > cnt: raise ValueError('Too many integration constants') if np.ndim(lbnd) != 0: raise ValueError('lbnd must be a scalar.') if np.ndim(scl) != 0: raise ValueError('scl must be a scalar.') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) k = list(k) + [0] * (cnt - len(k)) for i in range(cnt): n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0] * 0 tmp[1] = c[0] for j in range(1, n): tmp[j + 1] = c[j] / (j + 1) tmp[0] += k[i] - hermeval(lbnd, tmp) c = tmp c = np.moveaxis(c, 0, iaxis) return c def hermeval(x, c, tensor=True): c = np.array(c, ndmin=1, copy=None) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,) * x.ndim) if len(c) == 1: c0 = c[0] c1 = 0 elif len(c) == 2: c0 = c[0] c1 = c[1] else: nd = len(c) c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1): tmp = c0 nd = nd - 1 c0 = c[-i] - c1 * (nd - 1) c1 = tmp + c1 * x return c0 + c1 * x def hermeval2d(x, y, c): return pu._valnd(hermeval, c, x, y) def hermegrid2d(x, y, c): return pu._gridnd(hermeval, c, x, y) def hermeval3d(x, y, z, c): return pu._valnd(hermeval, c, x, y, z) def hermegrid3d(x, y, z, c): return pu._gridnd(hermeval, c, x, y, z) def hermevander(x, deg): ideg = pu._as_int(deg, 'deg') if ideg < 0: raise ValueError('deg must be non-negative') x = np.array(x, copy=None, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x * 0 + 1 if ideg > 0: v[1] = x for i in range(2, ideg + 1): v[i] = v[i - 1] * x - v[i - 2] * (i - 1) return np.moveaxis(v, 0, -1) def hermevander2d(x, y, deg): return pu._vander_nd_flat((hermevander, hermevander), (x, y), deg) def hermevander3d(x, y, z, deg): return pu._vander_nd_flat((hermevander, hermevander, hermevander), (x, y, z), deg) def hermefit(x, y, deg, rcond=None, full=False, w=None): return pu._fit(hermevander, x, y, deg, rcond, full, w) def hermecompanion(c): [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-c[0] / c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) scl = np.hstack((1.0, 1.0 / np.sqrt(np.arange(n - 1, 0, -1)))) scl = np.multiply.accumulate(scl)[::-1] top = mat.reshape(-1)[1::n + 1] bot = mat.reshape(-1)[n::n + 1] top[...] = np.sqrt(np.arange(1, n)) bot[...] = top mat[:, -1] -= scl * c[:-1] / c[-1] return mat def hermeroots(c): [c] = pu.as_series([c]) if len(c) <= 1: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([-c[0] / c[1]]) m = hermecompanion(c)[::-1, ::-1] r = la.eigvals(m) r.sort() return r def _normed_hermite_e_n(x, n): if n == 0: return np.full(x.shape, 1 / np.sqrt(np.sqrt(2 * np.pi))) c0 = 0.0 c1 = 1.0 / np.sqrt(np.sqrt(2 * np.pi)) nd = float(n) for i in range(n - 1): tmp = c0 c0 = -c1 * np.sqrt((nd - 1.0) / nd) c1 = tmp + c1 * x * np.sqrt(1.0 / nd) nd = nd - 1.0 return c0 + c1 * x def hermegauss(deg): ideg = pu._as_int(deg, 'deg') if ideg <= 0: raise ValueError('deg must be a positive integer') c = np.array([0] * deg + [1]) m = hermecompanion(c) x = la.eigvalsh(m) dy = _normed_hermite_e_n(x, ideg) df = _normed_hermite_e_n(x, ideg - 1) * np.sqrt(ideg) x -= dy / df fm = _normed_hermite_e_n(x, ideg - 1) fm /= np.abs(fm).max() w = 1 / (fm * fm) w = (w + w[::-1]) / 2 x = (x - x[::-1]) / 2 w *= np.sqrt(2 * np.pi) / w.sum() return (x, w) def hermeweight(x): w = np.exp(-0.5 * x ** 2) return w class HermiteE(ABCPolyBase): _add = staticmethod(hermeadd) _sub = staticmethod(hermesub) _mul = staticmethod(hermemul) _div = staticmethod(hermediv) _pow = staticmethod(hermepow) _val = staticmethod(hermeval) _int = staticmethod(hermeint) _der = staticmethod(hermeder) _fit = staticmethod(hermefit) _line = staticmethod(hermeline) _roots = staticmethod(hermeroots) _fromroots = staticmethod(hermefromroots) domain = np.array(hermedomain) window = np.array(hermedomain) basis_name = 'He' # File: numpy-main/numpy/polynomial/laguerre.py """""" import numpy as np import numpy.linalg as la from numpy.lib.array_utils import normalize_axis_index from . import polyutils as pu from ._polybase import ABCPolyBase __all__ = ['lagzero', 'lagone', 'lagx', 'lagdomain', 'lagline', 'lagadd', 'lagsub', 'lagmulx', 'lagmul', 'lagdiv', 'lagpow', 'lagval', 'lagder', 'lagint', 'lag2poly', 'poly2lag', 'lagfromroots', 'lagvander', 'lagfit', 'lagtrim', 'lagroots', 'Laguerre', 'lagval2d', 'lagval3d', 'laggrid2d', 'laggrid3d', 'lagvander2d', 'lagvander3d', 'lagcompanion', 'laggauss', 'lagweight'] lagtrim = pu.trimcoef def poly2lag(pol): [pol] = pu.as_series([pol]) res = 0 for p in pol[::-1]: res = lagadd(lagmulx(res), p) return res def lag2poly(c): from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n == 1: return c else: c0 = c[-2] c1 = c[-1] for i in range(n - 1, 1, -1): tmp = c0 c0 = polysub(c[i - 2], c1 * (i - 1) / i) c1 = polyadd(tmp, polysub((2 * i - 1) * c1, polymulx(c1)) / i) return polyadd(c0, polysub(c1, polymulx(c1))) lagdomain = np.array([0.0, 1.0]) lagzero = np.array([0]) lagone = np.array([1]) lagx = np.array([1, -1]) def lagline(off, scl): if scl != 0: return np.array([off + scl, -scl]) else: return np.array([off]) def lagfromroots(roots): return pu._fromroots(lagline, lagmul, roots) def lagadd(c1, c2): return pu._add(c1, c2) def lagsub(c1, c2): return pu._sub(c1, c2) def lagmulx(c): [c] = pu.as_series([c]) if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0] prd[1] = -c[0] for i in range(1, len(c)): prd[i + 1] = -c[i] * (i + 1) prd[i] += c[i] * (2 * i + 1) prd[i - 1] -= c[i] * i return prd def lagmul(c1, c2): [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c = c2 xs = c1 else: c = c1 xs = c2 if len(c) == 1: c0 = c[0] * xs c1 = 0 elif len(c) == 2: c0 = c[0] * xs c1 = c[1] * xs else: nd = len(c) c0 = c[-2] * xs c1 = c[-1] * xs for i in range(3, len(c) + 1): tmp = c0 nd = nd - 1 c0 = lagsub(c[-i] * xs, c1 * (nd - 1) / nd) c1 = lagadd(tmp, lagsub((2 * nd - 1) * c1, lagmulx(c1)) / nd) return lagadd(c0, lagsub(c1, lagmulx(c1))) def lagdiv(c1, c2): return pu._div(lagmul, c1, c2) def lagpow(c, pow, maxpower=16): return pu._pow(lagmul, c, pow, maxpower) def lagder(c, m=1, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt = pu._as_int(m, 'the order of derivation') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of derivation must be non-negative') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) n = len(c) if cnt >= n: c = c[:1] * 0 else: for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 1, -1): der[j - 1] = -c[j] c[j - 1] += c[j] der[0] = -c[1] c = der c = np.moveaxis(c, 0, iaxis) return c def lagint(c, m=1, k=[], lbnd=0, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt = pu._as_int(m, 'the order of integration') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of integration must be non-negative') if len(k) > cnt: raise ValueError('Too many integration constants') if np.ndim(lbnd) != 0: raise ValueError('lbnd must be a scalar.') if np.ndim(scl) != 0: raise ValueError('scl must be a scalar.') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) k = list(k) + [0] * (cnt - len(k)) for i in range(cnt): n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0] tmp[1] = -c[0] for j in range(1, n): tmp[j] += c[j] tmp[j + 1] = -c[j] tmp[0] += k[i] - lagval(lbnd, tmp) c = tmp c = np.moveaxis(c, 0, iaxis) return c def lagval(x, c, tensor=True): c = np.array(c, ndmin=1, copy=None) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,) * x.ndim) if len(c) == 1: c0 = c[0] c1 = 0 elif len(c) == 2: c0 = c[0] c1 = c[1] else: nd = len(c) c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1): tmp = c0 nd = nd - 1 c0 = c[-i] - c1 * (nd - 1) / nd c1 = tmp + c1 * (2 * nd - 1 - x) / nd return c0 + c1 * (1 - x) def lagval2d(x, y, c): return pu._valnd(lagval, c, x, y) def laggrid2d(x, y, c): return pu._gridnd(lagval, c, x, y) def lagval3d(x, y, z, c): return pu._valnd(lagval, c, x, y, z) def laggrid3d(x, y, z, c): return pu._gridnd(lagval, c, x, y, z) def lagvander(x, deg): ideg = pu._as_int(deg, 'deg') if ideg < 0: raise ValueError('deg must be non-negative') x = np.array(x, copy=None, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x * 0 + 1 if ideg > 0: v[1] = 1 - x for i in range(2, ideg + 1): v[i] = (v[i - 1] * (2 * i - 1 - x) - v[i - 2] * (i - 1)) / i return np.moveaxis(v, 0, -1) def lagvander2d(x, y, deg): return pu._vander_nd_flat((lagvander, lagvander), (x, y), deg) def lagvander3d(x, y, z, deg): return pu._vander_nd_flat((lagvander, lagvander, lagvander), (x, y, z), deg) def lagfit(x, y, deg, rcond=None, full=False, w=None): return pu._fit(lagvander, x, y, deg, rcond, full, w) def lagcompanion(c): [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[1 + c[0] / c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) top = mat.reshape(-1)[1::n + 1] mid = mat.reshape(-1)[0::n + 1] bot = mat.reshape(-1)[n::n + 1] top[...] = -np.arange(1, n) mid[...] = 2.0 * np.arange(n) + 1.0 bot[...] = top mat[:, -1] += c[:-1] / c[-1] * n return mat def lagroots(c): [c] = pu.as_series([c]) if len(c) <= 1: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([1 + c[0] / c[1]]) m = lagcompanion(c)[::-1, ::-1] r = la.eigvals(m) r.sort() return r def laggauss(deg): ideg = pu._as_int(deg, 'deg') if ideg <= 0: raise ValueError('deg must be a positive integer') c = np.array([0] * deg + [1]) m = lagcompanion(c) x = la.eigvalsh(m) dy = lagval(x, c) df = lagval(x, lagder(c)) x -= dy / df fm = lagval(x, c[1:]) fm /= np.abs(fm).max() df /= np.abs(df).max() w = 1 / (fm * df) w /= w.sum() return (x, w) def lagweight(x): w = np.exp(-x) return w class Laguerre(ABCPolyBase): _add = staticmethod(lagadd) _sub = staticmethod(lagsub) _mul = staticmethod(lagmul) _div = staticmethod(lagdiv) _pow = staticmethod(lagpow) _val = staticmethod(lagval) _int = staticmethod(lagint) _der = staticmethod(lagder) _fit = staticmethod(lagfit) _line = staticmethod(lagline) _roots = staticmethod(lagroots) _fromroots = staticmethod(lagfromroots) domain = np.array(lagdomain) window = np.array(lagdomain) basis_name = 'L' # File: numpy-main/numpy/polynomial/legendre.py """""" import numpy as np import numpy.linalg as la from numpy.lib.array_utils import normalize_axis_index from . import polyutils as pu from ._polybase import ABCPolyBase __all__ = ['legzero', 'legone', 'legx', 'legdomain', 'legline', 'legadd', 'legsub', 'legmulx', 'legmul', 'legdiv', 'legpow', 'legval', 'legder', 'legint', 'leg2poly', 'poly2leg', 'legfromroots', 'legvander', 'legfit', 'legtrim', 'legroots', 'Legendre', 'legval2d', 'legval3d', 'leggrid2d', 'leggrid3d', 'legvander2d', 'legvander3d', 'legcompanion', 'leggauss', 'legweight'] legtrim = pu.trimcoef def poly2leg(pol): [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1): res = legadd(legmulx(res), pol[i]) return res def leg2poly(c): from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n < 3: return c else: c0 = c[-2] c1 = c[-1] for i in range(n - 1, 1, -1): tmp = c0 c0 = polysub(c[i - 2], c1 * (i - 1) / i) c1 = polyadd(tmp, polymulx(c1) * (2 * i - 1) / i) return polyadd(c0, polymulx(c1)) legdomain = np.array([-1.0, 1.0]) legzero = np.array([0]) legone = np.array([1]) legx = np.array([0, 1]) def legline(off, scl): if scl != 0: return np.array([off, scl]) else: return np.array([off]) def legfromroots(roots): return pu._fromroots(legline, legmul, roots) def legadd(c1, c2): return pu._add(c1, c2) def legsub(c1, c2): return pu._sub(c1, c2) def legmulx(c): [c] = pu.as_series([c]) if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0] * 0 prd[1] = c[0] for i in range(1, len(c)): j = i + 1 k = i - 1 s = i + j prd[j] = c[i] * j / s prd[k] += c[i] * i / s return prd def legmul(c1, c2): [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c = c2 xs = c1 else: c = c1 xs = c2 if len(c) == 1: c0 = c[0] * xs c1 = 0 elif len(c) == 2: c0 = c[0] * xs c1 = c[1] * xs else: nd = len(c) c0 = c[-2] * xs c1 = c[-1] * xs for i in range(3, len(c) + 1): tmp = c0 nd = nd - 1 c0 = legsub(c[-i] * xs, c1 * (nd - 1) / nd) c1 = legadd(tmp, legmulx(c1) * (2 * nd - 1) / nd) return legadd(c0, legmulx(c1)) def legdiv(c1, c2): return pu._div(legmul, c1, c2) def legpow(c, pow, maxpower=16): return pu._pow(legmul, c, pow, maxpower) def legder(c, m=1, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt = pu._as_int(m, 'the order of derivation') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of derivation must be non-negative') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) n = len(c) if cnt >= n: c = c[:1] * 0 else: for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 2, -1): der[j - 1] = (2 * j - 1) * c[j] c[j - 2] += c[j] if n > 1: der[1] = 3 * c[2] der[0] = c[1] c = der c = np.moveaxis(c, 0, iaxis) return c def legint(c, m=1, k=[], lbnd=0, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt = pu._as_int(m, 'the order of integration') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of integration must be non-negative') if len(k) > cnt: raise ValueError('Too many integration constants') if np.ndim(lbnd) != 0: raise ValueError('lbnd must be a scalar.') if np.ndim(scl) != 0: raise ValueError('scl must be a scalar.') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) k = list(k) + [0] * (cnt - len(k)) for i in range(cnt): n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0] * 0 tmp[1] = c[0] if n > 1: tmp[2] = c[1] / 3 for j in range(2, n): t = c[j] / (2 * j + 1) tmp[j + 1] = t tmp[j - 1] -= t tmp[0] += k[i] - legval(lbnd, tmp) c = tmp c = np.moveaxis(c, 0, iaxis) return c def legval(x, c, tensor=True): c = np.array(c, ndmin=1, copy=None) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,) * x.ndim) if len(c) == 1: c0 = c[0] c1 = 0 elif len(c) == 2: c0 = c[0] c1 = c[1] else: nd = len(c) c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1): tmp = c0 nd = nd - 1 c0 = c[-i] - c1 * (nd - 1) / nd c1 = tmp + c1 * x * (2 * nd - 1) / nd return c0 + c1 * x def legval2d(x, y, c): return pu._valnd(legval, c, x, y) def leggrid2d(x, y, c): return pu._gridnd(legval, c, x, y) def legval3d(x, y, z, c): return pu._valnd(legval, c, x, y, z) def leggrid3d(x, y, z, c): return pu._gridnd(legval, c, x, y, z) def legvander(x, deg): ideg = pu._as_int(deg, 'deg') if ideg < 0: raise ValueError('deg must be non-negative') x = np.array(x, copy=None, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x * 0 + 1 if ideg > 0: v[1] = x for i in range(2, ideg + 1): v[i] = (v[i - 1] * x * (2 * i - 1) - v[i - 2] * (i - 1)) / i return np.moveaxis(v, 0, -1) def legvander2d(x, y, deg): return pu._vander_nd_flat((legvander, legvander), (x, y), deg) def legvander3d(x, y, z, deg): return pu._vander_nd_flat((legvander, legvander, legvander), (x, y, z), deg) def legfit(x, y, deg, rcond=None, full=False, w=None): return pu._fit(legvander, x, y, deg, rcond, full, w) def legcompanion(c): [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-c[0] / c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) scl = 1.0 / np.sqrt(2 * np.arange(n) + 1) top = mat.reshape(-1)[1::n + 1] bot = mat.reshape(-1)[n::n + 1] top[...] = np.arange(1, n) * scl[:n - 1] * scl[1:n] bot[...] = top mat[:, -1] -= c[:-1] / c[-1] * (scl / scl[-1]) * (n / (2 * n - 1)) return mat def legroots(c): [c] = pu.as_series([c]) if len(c) < 2: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([-c[0] / c[1]]) m = legcompanion(c)[::-1, ::-1] r = la.eigvals(m) r.sort() return r def leggauss(deg): ideg = pu._as_int(deg, 'deg') if ideg <= 0: raise ValueError('deg must be a positive integer') c = np.array([0] * deg + [1]) m = legcompanion(c) x = la.eigvalsh(m) dy = legval(x, c) df = legval(x, legder(c)) x -= dy / df fm = legval(x, c[1:]) fm /= np.abs(fm).max() df /= np.abs(df).max() w = 1 / (fm * df) w = (w + w[::-1]) / 2 x = (x - x[::-1]) / 2 w *= 2.0 / w.sum() return (x, w) def legweight(x): w = x * 0.0 + 1.0 return w class Legendre(ABCPolyBase): _add = staticmethod(legadd) _sub = staticmethod(legsub) _mul = staticmethod(legmul) _div = staticmethod(legdiv) _pow = staticmethod(legpow) _val = staticmethod(legval) _int = staticmethod(legint) _der = staticmethod(legder) _fit = staticmethod(legfit) _line = staticmethod(legline) _roots = staticmethod(legroots) _fromroots = staticmethod(legfromroots) domain = np.array(legdomain) window = np.array(legdomain) basis_name = 'P' # File: numpy-main/numpy/polynomial/polynomial.py """""" __all__ = ['polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', 'polyadd', 'polysub', 'polymulx', 'polymul', 'polydiv', 'polypow', 'polyval', 'polyvalfromroots', 'polyder', 'polyint', 'polyfromroots', 'polyvander', 'polyfit', 'polytrim', 'polyroots', 'Polynomial', 'polyval2d', 'polyval3d', 'polygrid2d', 'polygrid3d', 'polyvander2d', 'polyvander3d', 'polycompanion'] import numpy as np import numpy.linalg as la from numpy.lib.array_utils import normalize_axis_index from . import polyutils as pu from ._polybase import ABCPolyBase polytrim = pu.trimcoef polydomain = np.array([-1.0, 1.0]) polyzero = np.array([0]) polyone = np.array([1]) polyx = np.array([0, 1]) def polyline(off, scl): if scl != 0: return np.array([off, scl]) else: return np.array([off]) def polyfromroots(roots): return pu._fromroots(polyline, polymul, roots) def polyadd(c1, c2): return pu._add(c1, c2) def polysub(c1, c2): return pu._sub(c1, c2) def polymulx(c): [c] = pu.as_series([c]) if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0] * 0 prd[1:] = c return prd def polymul(c1, c2): [c1, c2] = pu.as_series([c1, c2]) ret = np.convolve(c1, c2) return pu.trimseq(ret) def polydiv(c1, c2): [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0: raise ZeroDivisionError lc1 = len(c1) lc2 = len(c2) if lc1 < lc2: return (c1[:1] * 0, c1) elif lc2 == 1: return (c1 / c2[-1], c1[:1] * 0) else: dlen = lc1 - lc2 scl = c2[-1] c2 = c2[:-1] / scl i = dlen j = lc1 - 1 while i >= 0: c1[i:j] -= c2 * c1[j] i -= 1 j -= 1 return (c1[j + 1:] / scl, pu.trimseq(c1[:j + 1])) def polypow(c, pow, maxpower=None): return pu._pow(np.convolve, c, pow, maxpower) def polyder(c, m=1, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c + 0.0 cdt = c.dtype cnt = pu._as_int(m, 'the order of derivation') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of derivation must be non-negative') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) n = len(c) if cnt >= n: c = c[:1] * 0 else: for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=cdt) for j in range(n, 0, -1): der[j - 1] = j * c[j] c = der c = np.moveaxis(c, 0, iaxis) return c def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0): c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c + 0.0 cdt = c.dtype if not np.iterable(k): k = [k] cnt = pu._as_int(m, 'the order of integration') iaxis = pu._as_int(axis, 'the axis') if cnt < 0: raise ValueError('The order of integration must be non-negative') if len(k) > cnt: raise ValueError('Too many integration constants') if np.ndim(lbnd) != 0: raise ValueError('lbnd must be a scalar.') if np.ndim(scl) != 0: raise ValueError('scl must be a scalar.') iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c k = list(k) + [0] * (cnt - len(k)) c = np.moveaxis(c, iaxis, 0) for i in range(cnt): n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=cdt) tmp[0] = c[0] * 0 tmp[1] = c[0] for j in range(1, n): tmp[j + 1] = c[j] / (j + 1) tmp[0] += k[i] - polyval(lbnd, tmp) c = tmp c = np.moveaxis(c, 0, iaxis) return c def polyval(x, c, tensor=True): c = np.array(c, ndmin=1, copy=None) if c.dtype.char in '?bBhHiIlLqQpP': c = c + 0.0 if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,) * x.ndim) c0 = c[-1] + x * 0 for i in range(2, len(c) + 1): c0 = c[-i] + c0 * x return c0 def polyvalfromroots(x, r, tensor=True): r = np.array(r, ndmin=1, copy=None) if r.dtype.char in '?bBhHiIlLqQpP': r = r.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray): if tensor: r = r.reshape(r.shape + (1,) * x.ndim) elif x.ndim >= r.ndim: raise ValueError('x.ndim must be < r.ndim when tensor == False') return np.prod(x - r, axis=0) def polyval2d(x, y, c): return pu._valnd(polyval, c, x, y) def polygrid2d(x, y, c): return pu._gridnd(polyval, c, x, y) def polyval3d(x, y, z, c): return pu._valnd(polyval, c, x, y, z) def polygrid3d(x, y, z, c): return pu._gridnd(polyval, c, x, y, z) def polyvander(x, deg): ideg = pu._as_int(deg, 'deg') if ideg < 0: raise ValueError('deg must be non-negative') x = np.array(x, copy=None, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x * 0 + 1 if ideg > 0: v[1] = x for i in range(2, ideg + 1): v[i] = v[i - 1] * x return np.moveaxis(v, 0, -1) def polyvander2d(x, y, deg): return pu._vander_nd_flat((polyvander, polyvander), (x, y), deg) def polyvander3d(x, y, z, deg): return pu._vander_nd_flat((polyvander, polyvander, polyvander), (x, y, z), deg) def polyfit(x, y, deg, rcond=None, full=False, w=None): return pu._fit(polyvander, x, y, deg, rcond, full, w) def polycompanion(c): [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-c[0] / c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) bot = mat.reshape(-1)[n::n + 1] bot[...] = 1 mat[:, -1] -= c[:-1] / c[-1] return mat def polyroots(c): [c] = pu.as_series([c]) if len(c) < 2: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([-c[0] / c[1]]) m = polycompanion(c)[::-1, ::-1] r = la.eigvals(m) r.sort() return r class Polynomial(ABCPolyBase): _add = staticmethod(polyadd) _sub = staticmethod(polysub) _mul = staticmethod(polymul) _div = staticmethod(polydiv) _pow = staticmethod(polypow) _val = staticmethod(polyval) _int = staticmethod(polyint) _der = staticmethod(polyder) _fit = staticmethod(polyfit) _line = staticmethod(polyline) _roots = staticmethod(polyroots) _fromroots = staticmethod(polyfromroots) domain = np.array(polydomain) window = np.array(polydomain) basis_name = None @classmethod def _str_term_unicode(cls, i, arg_str): if i == '1': return f'·{arg_str}' else: return f'·{arg_str}{i.translate(cls._superscript_mapping)}' @staticmethod def _str_term_ascii(i, arg_str): if i == '1': return f' {arg_str}' else: return f' {arg_str}**{i}' @staticmethod def _repr_latex_term(i, arg_str, needs_parens): if needs_parens: arg_str = f'\\left({arg_str}\\right)' if i == 0: return '1' elif i == 1: return arg_str else: return f'{arg_str}^{{{i}}}' # File: numpy-main/numpy/polynomial/polyutils.py """""" import operator import functools import warnings import numpy as np from numpy._core.multiarray import dragon4_positional, dragon4_scientific from numpy.exceptions import RankWarning __all__ = ['as_series', 'trimseq', 'trimcoef', 'getdomain', 'mapdomain', 'mapparms', 'format_float'] def trimseq(seq): if len(seq) == 0 or seq[-1] != 0: return seq else: for i in range(len(seq) - 1, -1, -1): if seq[i] != 0: break return seq[:i + 1] def as_series(alist, trim=True): arrays = [np.array(a, ndmin=1, copy=None) for a in alist] for a in arrays: if a.size == 0: raise ValueError('Coefficient array is empty') if any((a.ndim != 1 for a in arrays)): raise ValueError('Coefficient array is not 1-d') if trim: arrays = [trimseq(a) for a in arrays] if any((a.dtype == np.dtype(object) for a in arrays)): ret = [] for a in arrays: if a.dtype != np.dtype(object): tmp = np.empty(len(a), dtype=np.dtype(object)) tmp[:] = a[:] ret.append(tmp) else: ret.append(a.copy()) else: try: dtype = np.common_type(*arrays) except Exception as e: raise ValueError('Coefficient arrays have no common type') from e ret = [np.array(a, copy=True, dtype=dtype) for a in arrays] return ret def trimcoef(c, tol=0): if tol < 0: raise ValueError('tol must be non-negative') [c] = as_series([c]) [ind] = np.nonzero(np.abs(c) > tol) if len(ind) == 0: return c[:1] * 0 else: return c[:ind[-1] + 1].copy() def getdomain(x): [x] = as_series([x], trim=False) if x.dtype.char in np.typecodes['Complex']: (rmin, rmax) = (x.real.min(), x.real.max()) (imin, imax) = (x.imag.min(), x.imag.max()) return np.array((complex(rmin, imin), complex(rmax, imax))) else: return np.array((x.min(), x.max())) def mapparms(old, new): oldlen = old[1] - old[0] newlen = new[1] - new[0] off = (old[1] * new[0] - old[0] * new[1]) / oldlen scl = newlen / oldlen return (off, scl) def mapdomain(x, old, new): if type(x) not in (int, float, complex) and (not isinstance(x, np.generic)): x = np.asanyarray(x) (off, scl) = mapparms(old, new) return off + scl * x def _nth_slice(i, ndim): sl = [np.newaxis] * ndim sl[i] = slice(None) return tuple(sl) def _vander_nd(vander_fs, points, degrees): n_dims = len(vander_fs) if n_dims != len(points): raise ValueError(f'Expected {n_dims} dimensions of sample points, got {len(points)}') if n_dims != len(degrees): raise ValueError(f'Expected {n_dims} dimensions of degrees, got {len(degrees)}') if n_dims == 0: raise ValueError('Unable to guess a dtype or shape when no points are given') points = tuple(np.asarray(tuple(points)) + 0.0) vander_arrays = (vander_fs[i](points[i], degrees[i])[(...,) + _nth_slice(i, n_dims)] for i in range(n_dims)) return functools.reduce(operator.mul, vander_arrays) def _vander_nd_flat(vander_fs, points, degrees): v = _vander_nd(vander_fs, points, degrees) return v.reshape(v.shape[:-len(degrees)] + (-1,)) def _fromroots(line_f, mul_f, roots): if len(roots) == 0: return np.ones(1) else: [roots] = as_series([roots], trim=False) roots.sort() p = [line_f(-r, 1) for r in roots] n = len(p) while n > 1: (m, r) = divmod(n, 2) tmp = [mul_f(p[i], p[i + m]) for i in range(m)] if r: tmp[0] = mul_f(tmp[0], p[-1]) p = tmp n = m return p[0] def _valnd(val_f, c, *args): args = [np.asanyarray(a) for a in args] shape0 = args[0].shape if not all((a.shape == shape0 for a in args[1:])): if len(args) == 3: raise ValueError('x, y, z are incompatible') elif len(args) == 2: raise ValueError('x, y are incompatible') else: raise ValueError('ordinates are incompatible') it = iter(args) x0 = next(it) c = val_f(x0, c) for xi in it: c = val_f(xi, c, tensor=False) return c def _gridnd(val_f, c, *args): for xi in args: c = val_f(xi, c) return c def _div(mul_f, c1, c2): [c1, c2] = as_series([c1, c2]) if c2[-1] == 0: raise ZeroDivisionError lc1 = len(c1) lc2 = len(c2) if lc1 < lc2: return (c1[:1] * 0, c1) elif lc2 == 1: return (c1 / c2[-1], c1[:1] * 0) else: quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype) rem = c1 for i in range(lc1 - lc2, -1, -1): p = mul_f([0] * i + [1], c2) q = rem[-1] / p[-1] rem = rem[:-1] - q * p[:-1] quo[i] = q return (quo, trimseq(rem)) def _add(c1, c2): [c1, c2] = as_series([c1, c2]) if len(c1) > len(c2): c1[:c2.size] += c2 ret = c1 else: c2[:c1.size] += c1 ret = c2 return trimseq(ret) def _sub(c1, c2): [c1, c2] = as_series([c1, c2]) if len(c1) > len(c2): c1[:c2.size] -= c2 ret = c1 else: c2 = -c2 c2[:c1.size] += c1 ret = c2 return trimseq(ret) def _fit(vander_f, x, y, deg, rcond=None, full=False, w=None): x = np.asarray(x) + 0.0 y = np.asarray(y) + 0.0 deg = np.asarray(deg) if deg.ndim > 1 or deg.dtype.kind not in 'iu' or deg.size == 0: raise TypeError('deg must be an int or non-empty 1-D array of int') if deg.min() < 0: raise ValueError('expected deg >= 0') if x.ndim != 1: raise TypeError('expected 1D vector for x') if x.size == 0: raise TypeError('expected non-empty vector for x') if y.ndim < 1 or y.ndim > 2: raise TypeError('expected 1D or 2D array for y') if len(x) != len(y): raise TypeError('expected x and y to have same length') if deg.ndim == 0: lmax = deg order = lmax + 1 van = vander_f(x, lmax) else: deg = np.sort(deg) lmax = deg[-1] order = len(deg) van = vander_f(x, lmax)[:, deg] lhs = van.T rhs = y.T if w is not None: w = np.asarray(w) + 0.0 if w.ndim != 1: raise TypeError('expected 1D vector for w') if len(x) != len(w): raise TypeError('expected x and w to have same length') lhs = lhs * w rhs = rhs * w if rcond is None: rcond = len(x) * np.finfo(x.dtype).eps if issubclass(lhs.dtype.type, np.complexfloating): scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) else: scl = np.sqrt(np.square(lhs).sum(1)) scl[scl == 0] = 1 (c, resids, rank, s) = np.linalg.lstsq(lhs.T / scl, rhs.T, rcond) c = (c.T / scl).T if deg.ndim > 0: if c.ndim == 2: cc = np.zeros((lmax + 1, c.shape[1]), dtype=c.dtype) else: cc = np.zeros(lmax + 1, dtype=c.dtype) cc[deg] = c c = cc if rank != order and (not full): msg = 'The fit may be poorly conditioned' warnings.warn(msg, RankWarning, stacklevel=2) if full: return (c, [resids, rank, s, rcond]) else: return c def _pow(mul_f, c, pow, maxpower): [c] = as_series([c]) power = int(pow) if power != pow or power < 0: raise ValueError('Power must be a non-negative integer.') elif maxpower is not None and power > maxpower: raise ValueError('Power is too large') elif power == 0: return np.array([1], dtype=c.dtype) elif power == 1: return c else: prd = c for i in range(2, power + 1): prd = mul_f(prd, c) return prd def _as_int(x, desc): try: return operator.index(x) except TypeError as e: raise TypeError(f'{desc} must be an integer, received {x}') from e def format_float(x, parens=False): if not np.issubdtype(type(x), np.floating): return str(x) opts = np.get_printoptions() if np.isnan(x): return opts['nanstr'] elif np.isinf(x): return opts['infstr'] exp_format = False if x != 0: a = np.abs(x) if a >= 100000000.0 or a < 10 ** min(0, -(opts['precision'] - 1) // 2): exp_format = True (trim, unique) = ('0', True) if opts['floatmode'] == 'fixed': (trim, unique) = ('k', False) if exp_format: s = dragon4_scientific(x, precision=opts['precision'], unique=unique, trim=trim, sign=opts['sign'] == '+') if parens: s = '(' + s + ')' else: s = dragon4_positional(x, precision=opts['precision'], fractional=True, unique=unique, trim=trim, sign=opts['sign'] == '+') return s # File: numpy-main/numpy/random/__init__.py """""" __all__ = ['beta', 'binomial', 'bytes', 'chisquare', 'choice', 'dirichlet', 'exponential', 'f', 'gamma', 'geometric', 'get_state', 'gumbel', 'hypergeometric', 'laplace', 'logistic', 'lognormal', 'logseries', 'multinomial', 'multivariate_normal', 'negative_binomial', 'noncentral_chisquare', 'noncentral_f', 'normal', 'pareto', 'permutation', 'poisson', 'power', 'rand', 'randint', 'randn', 'random', 'random_integers', 'random_sample', 'ranf', 'rayleigh', 'sample', 'seed', 'set_state', 'shuffle', 'standard_cauchy', 'standard_exponential', 'standard_gamma', 'standard_normal', 'standard_t', 'triangular', 'uniform', 'vonmises', 'wald', 'weibull', 'zipf'] from . import _pickle from . import _common from . import _bounded_integers from ._generator import Generator, default_rng from .bit_generator import SeedSequence, BitGenerator from ._mt19937 import MT19937 from ._pcg64 import PCG64, PCG64DXSM from ._philox import Philox from ._sfc64 import SFC64 from .mtrand import * __all__ += ['Generator', 'RandomState', 'SeedSequence', 'MT19937', 'Philox', 'PCG64', 'PCG64DXSM', 'SFC64', 'default_rng', 'BitGenerator'] def __RandomState_ctor(): return RandomState(seed=0) from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester # File: numpy-main/numpy/random/_examples/cffi/extending.py """""" import os import numpy as np import cffi from .parse import parse_distributions_h ffi = cffi.FFI() inc_dir = os.path.join(np.get_include(), 'numpy') ffi.cdef('\n typedef intptr_t npy_intp;\n typedef unsigned char npy_bool;\n\n') parse_distributions_h(ffi, inc_dir) lib = ffi.dlopen(np.random._generator.__file__) bit_gen = np.random.PCG64() rng = np.random.Generator(bit_gen) state = bit_gen.state interface = rng.bit_generator.cffi n = 100 vals_cffi = ffi.new('double[%d]' % n) lib.random_standard_normal_fill(interface.bit_generator, n, vals_cffi) bit_gen.state = state vals = rng.standard_normal(n) for i in range(n): assert vals[i] == vals_cffi[i] # File: numpy-main/numpy/random/_examples/cffi/parse.py import os def parse_distributions_h(ffi, inc_dir): with open(os.path.join(inc_dir, 'random', 'bitgen.h')) as fid: s = [] for line in fid: if line.strip().startswith('#'): continue s.append(line) ffi.cdef('\n'.join(s)) with open(os.path.join(inc_dir, 'random', 'distributions.h')) as fid: s = [] in_skip = 0 ignoring = False for line in fid: if ignoring: if line.strip().startswith('#endif'): ignoring = False continue if line.strip().startswith('#ifdef __cplusplus'): ignoring = True if line.strip().startswith('#'): continue if line.strip().startswith('static inline'): in_skip += line.count('{') continue elif in_skip > 0: in_skip += line.count('{') in_skip -= line.count('}') continue line = line.replace('DECLDIR', '') line = line.replace('RAND_INT_TYPE', 'int64_t') s.append(line) ffi.cdef('\n'.join(s)) # File: numpy-main/numpy/random/_examples/numba/extending.py import numpy as np import numba as nb from numpy.random import PCG64 from timeit import timeit bit_gen = PCG64() next_d = bit_gen.cffi.next_double state_addr = bit_gen.cffi.state_address def normals(n, state): out = np.empty(n) for i in range((n + 1) // 2): x1 = 2.0 * next_d(state) - 1.0 x2 = 2.0 * next_d(state) - 1.0 r2 = x1 * x1 + x2 * x2 while r2 >= 1.0 or r2 == 0.0: x1 = 2.0 * next_d(state) - 1.0 x2 = 2.0 * next_d(state) - 1.0 r2 = x1 * x1 + x2 * x2 f = np.sqrt(-2.0 * np.log(r2) / r2) out[2 * i] = f * x1 if 2 * i + 1 < n: out[2 * i + 1] = f * x2 return out normalsj = nb.jit(normals, nopython=True) n = 10000 def numbacall(): return normalsj(n, state_addr) rg = np.random.Generator(PCG64()) def numpycall(): return rg.normal(size=n) r1 = numbacall() r2 = numpycall() assert r1.shape == (n,) assert r1.shape == r2.shape t1 = timeit(numbacall, number=1000) print(f'{t1:.2f} secs for {n} PCG64 (Numba/PCG64) gaussian randoms') t2 = timeit(numpycall, number=1000) print(f'{t2:.2f} secs for {n} PCG64 (NumPy/PCG64) gaussian randoms') next_u32 = bit_gen.ctypes.next_uint32 ctypes_state = bit_gen.ctypes.state @nb.jit(nopython=True) def bounded_uint(lb, ub, state): mask = delta = ub - lb mask |= mask >> 1 mask |= mask >> 2 mask |= mask >> 4 mask |= mask >> 8 mask |= mask >> 16 val = next_u32(state) & mask while val > delta: val = next_u32(state) & mask return lb + val print(bounded_uint(323, 2394691, ctypes_state.value)) @nb.jit(nopython=True) def bounded_uints(lb, ub, n, state): out = np.empty(n, dtype=np.uint32) for i in range(n): out[i] = bounded_uint(lb, ub, state) bounded_uints(323, 2394691, 10000000, ctypes_state.value) # File: numpy-main/numpy/random/_examples/numba/extending_distributions.py """""" import os import numba as nb import numpy as np from cffi import FFI from numpy.random import PCG64 ffi = FFI() if os.path.exists('./distributions.dll'): lib = ffi.dlopen('./distributions.dll') elif os.path.exists('./libdistributions.so'): lib = ffi.dlopen('./libdistributions.so') else: raise RuntimeError('Required DLL/so file was not found.') ffi.cdef('\ndouble random_standard_normal(void *bitgen_state);\n') x = PCG64() xffi = x.cffi bit_generator = xffi.bit_generator random_standard_normal = lib.random_standard_normal def normals(n, bit_generator): out = np.empty(n) for i in range(n): out[i] = random_standard_normal(bit_generator) return out normalsj = nb.jit(normals, nopython=True) bit_generator_address = int(ffi.cast('uintptr_t', bit_generator)) norm = normalsj(1000, bit_generator_address) print(norm[:12]) # File: numpy-main/numpy/random/_pickle.py from .bit_generator import BitGenerator from .mtrand import RandomState from ._philox import Philox from ._pcg64 import PCG64, PCG64DXSM from ._sfc64 import SFC64 from ._generator import Generator from ._mt19937 import MT19937 BitGenerators = {'MT19937': MT19937, 'PCG64': PCG64, 'PCG64DXSM': PCG64DXSM, 'Philox': Philox, 'SFC64': SFC64} def __bit_generator_ctor(bit_generator: str | type[BitGenerator]='MT19937'): if isinstance(bit_generator, type): bit_gen_class = bit_generator elif bit_generator in BitGenerators: bit_gen_class = BitGenerators[bit_generator] else: raise ValueError(str(bit_generator) + ' is not a known BitGenerator module.') return bit_gen_class() def __generator_ctor(bit_generator_name='MT19937', bit_generator_ctor=__bit_generator_ctor): if isinstance(bit_generator_name, BitGenerator): return Generator(bit_generator_name) return Generator(bit_generator_ctor(bit_generator_name)) def __randomstate_ctor(bit_generator_name='MT19937', bit_generator_ctor=__bit_generator_ctor): if isinstance(bit_generator_name, BitGenerator): return RandomState(bit_generator_name) return RandomState(bit_generator_ctor(bit_generator_name)) # File: numpy-main/numpy/typing/__init__.py """""" from numpy._typing import ArrayLike, DTypeLike, NBitBase, NDArray __all__ = ['ArrayLike', 'DTypeLike', 'NBitBase', 'NDArray'] if __doc__ is not None: from numpy._typing._add_docstring import _docstrings __doc__ += _docstrings __doc__ += '\n.. autoclass:: numpy.typing.NBitBase\n' del _docstrings from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester # File: numpy-main/numpy/typing/mypy_plugin.py """""" from __future__ import annotations from typing import Final, TYPE_CHECKING, Callable import numpy as np if TYPE_CHECKING: from collections.abc import Iterable try: import mypy.types from mypy.types import Type from mypy.plugin import Plugin, AnalyzeTypeContext from mypy.nodes import MypyFile, ImportFrom, Statement from mypy.build import PRI_MED _HookFunc = Callable[[AnalyzeTypeContext], Type] MYPY_EX: None | ModuleNotFoundError = None except ModuleNotFoundError as ex: MYPY_EX = ex __all__: list[str] = [] def _get_precision_dict() -> dict[str, str]: names = [('_NBitByte', np.byte), ('_NBitShort', np.short), ('_NBitIntC', np.intc), ('_NBitIntP', np.intp), ('_NBitInt', np.int_), ('_NBitLong', np.long), ('_NBitLongLong', np.longlong), ('_NBitHalf', np.half), ('_NBitSingle', np.single), ('_NBitDouble', np.double), ('_NBitLongDouble', np.longdouble)] ret = {} module = 'numpy._typing' for (name, typ) in names: n: int = 8 * typ().dtype.itemsize ret[f'{module}._nbit.{name}'] = f'{module}._nbit_base._{n}Bit' return ret def _get_extended_precision_list() -> list[str]: extended_names = ['uint128', 'uint256', 'int128', 'int256', 'float80', 'float96', 'float128', 'float256', 'complex160', 'complex192', 'complex256', 'complex512'] return [i for i in extended_names if hasattr(np, i)] def _get_c_intp_name() -> str: char = np.dtype('n').char if char == 'i': return 'c_int' elif char == 'l': return 'c_long' elif char == 'q': return 'c_longlong' else: return 'c_long' _PRECISION_DICT: Final = _get_precision_dict() _EXTENDED_PRECISION_LIST: Final = _get_extended_precision_list() _C_INTP: Final = _get_c_intp_name() def _hook(ctx: AnalyzeTypeContext) -> Type: (typ, _, api) = ctx name = typ.name.split('.')[-1] name_new = _PRECISION_DICT[f'numpy._typing._nbit.{name}'] return api.named_type(name_new) if TYPE_CHECKING or MYPY_EX is None: def _index(iterable: Iterable[Statement], id: str) -> int: for (i, value) in enumerate(iterable): if getattr(value, 'id', None) == id: return i raise ValueError(f'Failed to identify a `ImportFrom` instance with the following id: {id!r}') def _override_imports(file: MypyFile, module: str, imports: list[tuple[str, None | str]]) -> None: import_obj = ImportFrom(module, 0, names=imports) import_obj.is_top_level = True for lst in [file.defs, file.imports]: i = _index(lst, module) lst[i] = import_obj class _NumpyPlugin(Plugin): def get_type_analyze_hook(self, fullname: str) -> None | _HookFunc: if fullname in _PRECISION_DICT: return _hook return None def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]: ret = [(PRI_MED, file.fullname, -1)] if file.fullname == 'numpy': _override_imports(file, 'numpy._typing._extended_precision', imports=[(v, v) for v in _EXTENDED_PRECISION_LIST]) elif file.fullname == 'numpy.ctypeslib': _override_imports(file, 'ctypes', imports=[(_C_INTP, '_c_intp')]) return ret def plugin(version: str) -> type[_NumpyPlugin]: return _NumpyPlugin else: def plugin(version: str) -> type[_NumpyPlugin]: raise MYPY_EX # File: numpy-main/pavement.py """""" import os import hashlib import textwrap import paver from paver.easy import Bunch, options, task, sh RELEASE_NOTES = 'doc/source/release/2.2.0-notes.rst' options(installers=Bunch(releasedir='release', installersdir=os.path.join('release', 'installers'))) def _compute_hash(idirs, hashfunc): released = paver.path.path(idirs).listdir() checksums = [] for fpath in sorted(released): with open(fpath, 'rb') as fin: fhash = hashfunc(fin.read()) checksums.append('%s %s' % (fhash.hexdigest(), os.path.basename(fpath))) return checksums def compute_md5(idirs): return _compute_hash(idirs, hashlib.md5) def compute_sha256(idirs): return _compute_hash(idirs, hashlib.sha256) def write_release_task(options, filename='README'): idirs = options.installers.installersdir notes = paver.path.path(RELEASE_NOTES) rst_readme = paver.path.path(filename + '.rst') md_readme = paver.path.path(filename + '.md') with open(rst_readme, 'w') as freadme: with open(notes) as fnotes: freadme.write(fnotes.read()) freadme.writelines(textwrap.dedent('\n Checksums\n =========\n\n MD5\n ---\n ::\n\n ')) freadme.writelines([f' {c}\n' for c in compute_md5(idirs)]) freadme.writelines(textwrap.dedent('\n SHA256\n ------\n ::\n\n ')) freadme.writelines([f' {c}\n' for c in compute_sha256(idirs)]) sh(f'pandoc -s -o {md_readme} {rst_readme}') if hasattr(options, 'gpg_key'): cmd = f'gpg --clearsign --armor --default_key {options.gpg_key}' else: cmd = 'gpg --clearsign --armor' sh(cmd + f' --output {rst_readme}.gpg {rst_readme}') sh(cmd + f' --output {md_readme}.gpg {md_readme}') @task def write_release(options): rdir = options.installers.releasedir write_release_task(options, os.path.join(rdir, 'README')) # File: numpy-main/tools/c_coverage/c_coverage_report.py """""" import os import re import sys from xml.sax.saxutils import quoteattr, escape try: import pygments if tuple([int(x) for x in pygments.__version__.split('.')]) < (0, 11): raise ImportError from pygments import highlight from pygments.lexers import CLexer from pygments.formatters import HtmlFormatter has_pygments = True except ImportError: print('This script requires pygments 0.11 or greater to generate HTML') has_pygments = False class FunctionHtmlFormatter(HtmlFormatter): def __init__(self, lines, **kwargs): HtmlFormatter.__init__(self, **kwargs) self.lines = lines def wrap(self, source, outfile): for (i, (c, t)) in enumerate(HtmlFormatter.wrap(self, source, outfile)): as_functions = self.lines.get(i - 1, None) if as_functions is not None: yield (0, '
[%2d]' % (quoteattr('as ' + ', '.join(as_functions)), len(as_functions))) else: yield (0, ' ') yield (c, t) if as_functions is not None: yield (0, '
') class SourceFile: def __init__(self, path): self.path = path self.lines = {} def mark_line(self, lineno, as_func=None): line = self.lines.setdefault(lineno, set()) if as_func is not None: as_func = as_func.split("'", 1)[0] line.add(as_func) def write_text(self, fd): with open(self.path, 'r') as source: for (i, line) in enumerate(source): if i + 1 in self.lines: fd.write('> ') else: fd.write('! ') fd.write(line) def write_html(self, fd): with open(self.path, 'r') as source: code = source.read() lexer = CLexer() formatter = FunctionHtmlFormatter(self.lines, full=True, linenos='inline') fd.write(highlight(code, lexer, formatter)) class SourceFiles: def __init__(self): self.files = {} self.prefix = None def get_file(self, path): if path not in self.files: self.files[path] = SourceFile(path) if self.prefix is None: self.prefix = path else: self.prefix = os.path.commonprefix([self.prefix, path]) return self.files[path] def clean_path(self, path): path = path[len(self.prefix):] return re.sub('[^A-Za-z0-9\\.]', '_', path) def write_text(self, root): for (path, source) in self.files.items(): with open(os.path.join(root, self.clean_path(path)), 'w') as fd: source.write_text(fd) def write_html(self, root): for (path, source) in self.files.items(): with open(os.path.join(root, self.clean_path(path) + '.html'), 'w') as fd: source.write_html(fd) with open(os.path.join(root, 'index.html'), 'w') as fd: fd.write('') paths = sorted(self.files.keys()) for path in paths: fd.write('

%s

' % (self.clean_path(path), escape(path[len(self.prefix):]))) fd.write('') def collect_stats(files, fd, pattern): line_regexs = [re.compile('(?P[0-9]+)(\\s[0-9]+)+'), re.compile('((jump)|(jcnd))=([0-9]+)\\s(?P[0-9]+)')] current_file = None current_function = None for line in fd: if re.match('f[lie]=.+', line): path = line.split('=', 2)[1].strip() if os.path.exists(path) and re.search(pattern, path): current_file = files.get_file(path) else: current_file = None elif re.match('fn=.+', line): current_function = line.split('=', 2)[1].strip() elif current_file is not None: for regex in line_regexs: match = regex.match(line) if match: lineno = int(match.group('lineno')) current_file.mark_line(lineno, current_function) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('callgrind_file', nargs='+', help='One or more callgrind files') parser.add_argument('-d', '--directory', default='coverage', help='Destination directory for output (default: %(default)s)') parser.add_argument('-p', '--pattern', default='numpy', help='Regex pattern to match against source file paths (default: %(default)s)') parser.add_argument('-f', '--format', action='append', default=[], choices=['text', 'html'], help='Output format(s) to generate. If option not provided, both will be generated.') args = parser.parse_args() files = SourceFiles() for log_file in args.callgrind_file: with open(log_file, 'r') as log_fd: collect_stats(files, log_fd, args.pattern) if not os.path.exists(args.directory): os.makedirs(args.directory) if args.format == []: formats = ['text', 'html'] else: formats = args.format if 'text' in formats: files.write_text(args.directory) if 'html' in formats: if not has_pygments: print('Pygments 0.11 or later is required to generate HTML') sys.exit(1) files.write_html(args.directory) # File: numpy-main/tools/changelog.py """""" import os import re from git import Repo from github import Github this_repo = Repo(os.path.join(os.path.dirname(__file__), '..')) author_msg = '\nA total of %d people contributed to this release. People with a "+" by their\nnames contributed a patch for the first time.\n' pull_request_msg = '\nA total of %d pull requests were merged for this release.\n' def get_authors(revision_range): (lst_release, cur_release) = [r.strip() for r in revision_range.split('..')] authors_pat = '^.*\\t(.*)$' grp1 = '--group=author' grp2 = '--group=trailer:co-authored-by' cur = this_repo.git.shortlog('-s', grp1, grp2, revision_range) pre = this_repo.git.shortlog('-s', grp1, grp2, lst_release) authors_cur = set(re.findall(authors_pat, cur, re.M)) authors_pre = set(re.findall(authors_pat, pre, re.M)) authors_cur.discard('Homu') authors_pre.discard('Homu') authors_cur.discard('dependabot-preview') authors_pre.discard('dependabot-preview') authors_new = [s + ' +' for s in authors_cur - authors_pre] authors_old = list(authors_cur & authors_pre) authors = authors_new + authors_old authors.sort() return authors def get_pull_requests(repo, revision_range): prnums = [] merges = this_repo.git.log('--oneline', '--merges', revision_range) issues = re.findall('Merge pull request \\#(\\d*)', merges) prnums.extend((int(s) for s in issues)) issues = re.findall('Auto merge of \\#(\\d*)', merges) prnums.extend((int(s) for s in issues)) commits = this_repo.git.log('--oneline', '--no-merges', '--first-parent', revision_range) issues = re.findall('^.*\\((\\#|gh-|gh-\\#)(\\d+)\\)$', commits, re.M) prnums.extend((int(s[1]) for s in issues)) prnums.sort() prs = [repo.get_pull(n) for n in prnums] return prs def main(token, revision_range): (lst_release, cur_release) = [r.strip() for r in revision_range.split('..')] github = Github(token) github_repo = github.get_repo('numpy/numpy') authors = get_authors(revision_range) heading = 'Contributors' print() print(heading) print('=' * len(heading)) print(author_msg % len(authors)) for s in authors: print('* ' + s) pull_requests = get_pull_requests(github_repo, revision_range) heading = 'Pull requests merged' pull_msg = '* `#{0} <{1}>`__: {2}' print() print(heading) print('=' * len(heading)) print(pull_request_msg % len(pull_requests)) for pull in pull_requests: title = re.sub('\\s+', ' ', pull.title.strip()) if len(title) > 60: remainder = re.sub('\\s.*$', '...', title[60:]) if len(remainder) > 20: remainder = title[:80] + '...' else: title = title[:60] + remainder print(pull_msg.format(pull.number, pull.html_url, title)) if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser(description='Generate author/pr lists for release') parser.add_argument('token', help='github access token') parser.add_argument('revision_range', help='..') args = parser.parse_args() main(args.token, args.revision_range) # File: numpy-main/tools/check_installed_files.py """""" import os import glob import sys import json CUR_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__))) ROOT_DIR = os.path.dirname(CUR_DIR) NUMPY_DIR = os.path.join(ROOT_DIR, 'numpy') changed_installed_path = {} def main(install_dir, tests_check): INSTALLED_DIR = os.path.join(ROOT_DIR, install_dir) if not os.path.exists(INSTALLED_DIR): raise ValueError(f'Provided install dir {INSTALLED_DIR} does not exist') numpy_test_files = get_files(NUMPY_DIR, kind='test') installed_test_files = get_files(INSTALLED_DIR, kind='test') if tests_check == '--no-tests': if len(installed_test_files) > 0: raise Exception("Test files aren't expected to be installed in %s, found %s" % (INSTALLED_DIR, installed_test_files)) print('----------- No test files were installed --------------') else: for test_file in numpy_test_files.keys(): if test_file not in installed_test_files.keys(): raise Exception('%s is not installed' % numpy_test_files[test_file]) print('----------- All the test files were installed --------------') numpy_pyi_files = get_files(NUMPY_DIR, kind='stub') installed_pyi_files = get_files(INSTALLED_DIR, kind='stub') for pyi_file in numpy_pyi_files.keys(): if pyi_file not in installed_pyi_files.keys(): if tests_check == '--no-tests' and 'tests' in numpy_pyi_files[pyi_file]: continue raise Exception('%s is not installed' % numpy_pyi_files[pyi_file]) print('----------- All the necessary .pyi files were installed --------------') def get_files(dir_to_check, kind='test'): files = dict() patterns = {'test': f'{dir_to_check}/**/test_*.py', 'stub': f'{dir_to_check}/**/*.pyi'} for path in glob.glob(patterns[kind], recursive=True): relpath = os.path.relpath(path, dir_to_check) files[relpath] = path if sys.version_info >= (3, 12): files = {k: v for (k, v) in files.items() if not k.startswith('distutils')} files = {k: v for (k, v) in files.items() if 'pythoncapi-compat' not in k} return files if __name__ == '__main__': if len(sys.argv) < 2: raise ValueError('Incorrect number of input arguments, need check_installation.py relpath/to/installed/numpy') install_dir = sys.argv[1] tests_check = '' if len(sys.argv) >= 3: tests_check = sys.argv[2] main(install_dir, tests_check) all_tags = set() with open(os.path.join('build', 'meson-info', 'intro-install_plan.json'), 'r') as f: targets = json.load(f) for key in targets.keys(): for values in list(targets[key].values()): if values['tag'] not in all_tags: all_tags.add(values['tag']) if all_tags != set(['runtime', 'python-runtime', 'devel', 'tests']): raise AssertionError(f'Found unexpected install tag: {all_tags}') # File: numpy-main/tools/check_openblas_version.py """""" import numpy import pprint import sys version = sys.argv[1] deps = numpy.show_config('dicts')['Build Dependencies'] assert 'blas' in deps print('Build Dependencies: blas') pprint.pprint(deps['blas']) assert deps['blas']['version'].split('.') >= version.split('.') assert deps['blas']['name'] == 'scipy-openblas' # File: numpy-main/tools/ci/push_docs_to_repo.py import argparse import subprocess import tempfile import os import sys import shutil parser = argparse.ArgumentParser(description='Upload files to a remote repo, replacing existing content') parser.add_argument('dir', help='directory of which content will be uploaded') parser.add_argument('remote', help='remote to which content will be pushed') parser.add_argument('--message', default='Commit bot upload', help='commit message to use') parser.add_argument('--committer', default='numpy-commit-bot', help='Name of the git committer') parser.add_argument('--email', default='numpy-commit-bot@nomail', help='Email of the git committer') parser.add_argument('--count', default=1, type=int, help='minimum number of expected files, defaults to 1') parser.add_argument('--force', action='store_true', help='hereby acknowledge that remote repo content will be overwritten') args = parser.parse_args() args.dir = os.path.abspath(args.dir) if not os.path.exists(args.dir): print('Content directory does not exist') sys.exit(1) count = len([name for name in os.listdir(args.dir) if os.path.isfile(os.path.join(args.dir, name))]) if count < args.count: print(f'Expected {args.count} top-directory files to upload, got {count}') sys.exit(1) def run(cmd, stdout=True): pipe = None if stdout else subprocess.DEVNULL try: subprocess.check_call(cmd, stdout=pipe, stderr=pipe) except subprocess.CalledProcessError: print('\n! Error executing: `%s;` aborting' % ' '.join(cmd)) sys.exit(1) workdir = tempfile.mkdtemp() os.chdir(workdir) run(['git', 'init']) run(['git', 'checkout', '-b', 'main']) run(['git', 'remote', 'add', 'origin', args.remote]) run(['git', 'config', '--local', 'user.name', args.committer]) run(['git', 'config', '--local', 'user.email', args.email]) print('- committing new content: "%s"' % args.message) run(['cp', '-R', os.path.join(args.dir, '.'), '.']) run(['git', 'add', '.'], stdout=False) run(['git', 'commit', '--allow-empty', '-m', args.message], stdout=False) print('- uploading as %s <%s>' % (args.committer, args.email)) if args.force: run(['git', 'push', 'origin', 'main', '--force']) else: print('\n!! No `--force` argument specified; aborting') print('!! Before enabling that flag, make sure you know what it does\n') sys.exit(1) shutil.rmtree(workdir) # File: numpy-main/tools/commitstats.py import re import numpy as np import os names = re.compile('r\\d+\\s\\|\\s(.*)\\s\\|\\s200') def get_count(filename, repo): mystr = open(filename).read() result = names.findall(mystr) u = np.unique(result) count = [(x, result.count(x), repo) for x in u] return count command = 'svn log -l 2300 > output.txt' os.chdir('..') os.system(command) count = get_count('output.txt', 'NumPy') os.chdir('../scipy') os.system(command) count.extend(get_count('output.txt', 'SciPy')) os.chdir('../scikits') os.system(command) count.extend(get_count('output.txt', 'SciKits')) count.sort() print('** SciPy and NumPy **') print('=====================') for val in count: print(val) # File: numpy-main/tools/download-wheels.py """""" import os import re import shutil import argparse import urllib3 from bs4 import BeautifulSoup __version__ = '0.1' STAGING_URL = 'https://anaconda.org/multibuild-wheels-staging/numpy' PREFIX = 'numpy' WHL = '-.*\\.whl$' ZIP = '\\.zip$' GZIP = '\\.tar\\.gz$' SUFFIX = f'({WHL}|{GZIP}|{ZIP})' def get_wheel_names(version): ret = [] http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED') tmpl = re.compile(f'^.*{PREFIX}-{version}{SUFFIX}') for i in range(1, 3): index_url = f'{STAGING_URL}/files?page={i}' index_html = http.request('GET', index_url) soup = BeautifulSoup(index_html.data, 'html.parser') ret += soup.find_all(string=tmpl) return ret def download_wheels(version, wheelhouse, test=False): http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED') wheel_names = get_wheel_names(version) for (i, wheel_name) in enumerate(wheel_names): wheel_url = f'{STAGING_URL}/{version}/download/{wheel_name}' wheel_path = os.path.join(wheelhouse, wheel_name) with open(wheel_path, 'wb') as f: with http.request('GET', wheel_url, preload_content=False) as r: info = r.info() length = int(info.get('Content-Length', '0')) if length == 0: length = 'unknown size' else: length = f'{length / 1024 / 1024:.2f}MB' print(f'{i + 1:<4}{wheel_name} {length}') if not test: shutil.copyfileobj(r, f) print(f'\nTotal files downloaded: {len(wheel_names)}') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('version', help='NumPy version to download.') parser.add_argument('-w', '--wheelhouse', default=os.path.join(os.getcwd(), 'release', 'installers'), help='Directory in which to store downloaded wheels\n[defaults to /release/installers]') parser.add_argument('-t', '--test', action='store_true', help='only list available wheels, do not download') args = parser.parse_args() wheelhouse = os.path.expanduser(args.wheelhouse) if not os.path.isdir(wheelhouse): raise RuntimeError(f"{wheelhouse} wheelhouse directory is not present. Perhaps you need to use the '-w' flag to specify one.") download_wheels(args.version, wheelhouse, test=args.test) # File: numpy-main/tools/find_deprecated_escaped_characters.py """""" def main(root): import ast import tokenize import warnings from pathlib import Path count = 0 base = Path(root) paths = base.rglob('*.py') if base.is_dir() else [base] for path in paths: with tokenize.open(str(path)) as f: with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') tree = ast.parse(f.read()) if w: print('file: ', str(path)) for e in w: print('line: ', e.lineno, ': ', e.message) print() count += len(w) print('Errors Found', count) if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser(description='Find deprecated escaped characters') parser.add_argument('root', help='directory or file to be checked') args = parser.parse_args() main(args.root) # File: numpy-main/tools/functions_missing_types.py """""" import argparse import ast import importlib import os NUMPY_ROOT = os.path.dirname(os.path.join(os.path.abspath(__file__), '..')) EXCLUDE_LIST = {'numpy': {'absolute_import', 'division', 'print_function', 'warnings', 'sys', 'os', 'math', 'Tester', '_core', 'get_array_wrap', 'int_asbuffer', 'numarray', 'oldnumeric', 'safe_eval', 'test', 'typeDict', 'bool', 'complex', 'float', 'int', 'long', 'object', 'str', 'unicode', 'alltrue', 'sometrue'}} class FindAttributes(ast.NodeVisitor): def __init__(self): self.attributes = set() def visit_FunctionDef(self, node): if node.name == '__getattr__': return self.attributes.add(node.name) return def visit_ClassDef(self, node): if not node.name.startswith('_'): self.attributes.add(node.name) return def visit_AnnAssign(self, node): self.attributes.add(node.target.id) def find_missing(module_name): module_path = os.path.join(NUMPY_ROOT, module_name.replace('.', os.sep), '__init__.pyi') module = importlib.import_module(module_name) module_attributes = {attribute for attribute in dir(module) if not attribute.startswith('_')} if os.path.isfile(module_path): with open(module_path) as f: tree = ast.parse(f.read()) ast_visitor = FindAttributes() ast_visitor.visit(tree) stubs_attributes = ast_visitor.attributes else: stubs_attributes = set() exclude_list = EXCLUDE_LIST.get(module_name, set()) missing = module_attributes - stubs_attributes - exclude_list print('\n'.join(sorted(missing))) def main(): parser = argparse.ArgumentParser() parser.add_argument('module') args = parser.parse_args() find_missing(args.module) if __name__ == '__main__': main() # File: numpy-main/tools/linter.py import os import sys import subprocess from argparse import ArgumentParser from git import Repo, exc CWD = os.path.abspath(os.path.dirname(__file__)) CONFIG = os.path.join(CWD, 'lint_diff.ini') EXCLUDE = ('numpy/typing/tests/data/', 'numpy/typing/_char_codes.py', 'numpy/__config__.py', 'numpy/f2py') class DiffLinter: def __init__(self, branch): self.branch = branch self.repo = Repo(os.path.join(CWD, '..')) self.head = self.repo.head.commit def get_branch_diff(self, uncommitted=False): try: commit = self.repo.merge_base(self.branch, self.head)[0] except exc.GitCommandError: print(f'Branch with name `{self.branch}` does not exist') sys.exit(1) exclude = [f':(exclude){i}' for i in EXCLUDE] if uncommitted: diff = self.repo.git.diff(self.head, '--unified=0', '***.py', *exclude) else: diff = self.repo.git.diff(commit, self.head, '--unified=0', '***.py', *exclude) return diff def run_pycodestyle(self, diff): res = subprocess.run(['pycodestyle', '--diff', '--config', CONFIG], input=diff, stdout=subprocess.PIPE, encoding='utf-8') return (res.returncode, res.stdout) def run_lint(self, uncommitted): diff = self.get_branch_diff(uncommitted) (retcode, errors) = self.run_pycodestyle(diff) errors and print(errors) sys.exit(retcode) if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--branch', type=str, default='main', help='The branch to diff against') parser.add_argument('--uncommitted', action='store_true', help='Check only uncommitted changes') args = parser.parse_args() DiffLinter(args.branch).run_lint(args.uncommitted) # File: numpy-main/tools/refguide_check.py """""" import copy import inspect import io import os import re import sys import warnings import docutils.core from argparse import ArgumentParser from docutils.parsers.rst import directives sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'doc', 'sphinxext')) from numpydoc.docscrape_sphinx import get_doc_object from sphinx.directives.other import SeeAlso, Only directives.register_directive('seealso', SeeAlso) directives.register_directive('only', Only) BASE_MODULE = 'numpy' PUBLIC_SUBMODULES = ['f2py', 'linalg', 'lib', 'lib.format', 'lib.mixins', 'lib.recfunctions', 'lib.scimath', 'lib.stride_tricks', 'lib.npyio', 'lib.introspect', 'lib.array_utils', 'fft', 'char', 'rec', 'ma', 'ma.extras', 'ma.mrecords', 'polynomial', 'polynomial.chebyshev', 'polynomial.hermite', 'polynomial.hermite_e', 'polynomial.laguerre', 'polynomial.legendre', 'polynomial.polynomial', 'matrixlib', 'random', 'strings', 'testing'] OTHER_MODULE_DOCS = {'fftpack.convolve': 'fftpack', 'io.wavfile': 'io', 'io.arff': 'io'} REFGUIDE_ALL_SKIPLIST = ['scipy\\.sparse\\.linalg', 'scipy\\.spatial\\.distance', 'scipy\\.linalg\\.blas\\.[sdczi].*', 'scipy\\.linalg\\.lapack\\.[sdczi].*'] REFGUIDE_AUTOSUMMARY_SKIPLIST = ['numpy\\.*'] def short_path(path, cwd=None): if not isinstance(path, str): return path if cwd is None: cwd = os.getcwd() abspath = os.path.abspath(path) relpath = os.path.relpath(path, cwd) if len(abspath) <= len(relpath): return abspath return relpath def find_names(module, names_dict): patterns = ['^\\s\\s\\s([a-z_0-9A-Z]+)(\\s+-+.*)?$', '^\\.\\. (?:data|function)::\\s*([a-z_0-9A-Z]+)\\s*$'] if module.__name__ == 'scipy.constants': patterns += ['^``([a-z_0-9A-Z]+)``'] patterns = [re.compile(pattern) for pattern in patterns] module_name = module.__name__ for line in module.__doc__.splitlines(): res = re.search('^\\s*\\.\\. (?:currentmodule|module):: ([a-z0-9A-Z_.]+)\\s*$', line) if res: module_name = res.group(1) continue for pattern in patterns: res = re.match(pattern, line) if res is not None: name = res.group(1) entry = f'{module_name}.{name}' names_dict.setdefault(module_name, set()).add(name) break def get_all_dict(module): if hasattr(module, '__all__'): all_dict = copy.deepcopy(module.__all__) else: all_dict = copy.deepcopy(dir(module)) all_dict = [name for name in all_dict if not name.startswith('_')] for name in ['absolute_import', 'division', 'print_function']: try: all_dict.remove(name) except ValueError: pass if not all_dict: all_dict.append('__doc__') all_dict = [name for name in all_dict if not inspect.ismodule(getattr(module, name, None))] deprecated = [] not_deprecated = [] for name in all_dict: f = getattr(module, name, None) if callable(f) and is_deprecated(f): deprecated.append(name) else: not_deprecated.append(name) others = set(dir(module)).difference(set(deprecated)).difference(set(not_deprecated)) return (not_deprecated, deprecated, others) def compare(all_dict, others, names, module_name): only_all = set() for name in all_dict: if name not in names: for pat in REFGUIDE_AUTOSUMMARY_SKIPLIST: if re.match(pat, module_name + '.' + name): break else: only_all.add(name) only_ref = set() missing = set() for name in names: if name not in all_dict: for pat in REFGUIDE_ALL_SKIPLIST: if re.match(pat, module_name + '.' + name): if name not in others: missing.add(name) break else: only_ref.add(name) return (only_all, only_ref, missing) def is_deprecated(f): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('error') try: f(**{'not a kwarg': None}) except DeprecationWarning: return True except Exception: pass return False def check_items(all_dict, names, deprecated, others, module_name, dots=True): num_all = len(all_dict) num_ref = len(names) output = '' output += 'Non-deprecated objects in __all__: %i\n' % num_all output += 'Objects in refguide: %i\n\n' % num_ref (only_all, only_ref, missing) = compare(all_dict, others, names, module_name) dep_in_ref = only_ref.intersection(deprecated) only_ref = only_ref.difference(deprecated) if len(dep_in_ref) > 0: output += 'Deprecated objects in refguide::\n\n' for name in sorted(deprecated): output += ' ' + name + '\n' if len(only_all) == len(only_ref) == len(missing) == 0: if dots: output_dot('.') return [(None, True, output)] else: if len(only_all) > 0: output += 'ERROR: objects in %s.__all__ but not in refguide::\n\n' % module_name for name in sorted(only_all): output += ' ' + name + '\n' output += '\nThis issue can be fixed by adding these objects to\n' output += 'the function listing in __init__.py for this module\n' if len(only_ref) > 0: output += 'ERROR: objects in refguide but not in %s.__all__::\n\n' % module_name for name in sorted(only_ref): output += ' ' + name + '\n' output += '\nThis issue should likely be fixed by removing these objects\n' output += 'from the function listing in __init__.py for this module\n' output += 'or adding them to __all__.\n' if len(missing) > 0: output += 'ERROR: missing objects::\n\n' for name in sorted(missing): output += ' ' + name + '\n' if dots: output_dot('F') return [(None, False, output)] def validate_rst_syntax(text, name, dots=True): if text is None: if dots: output_dot('E') return (False, 'ERROR: %s: no documentation' % (name,)) ok_unknown_items = set(['mod', 'doc', 'currentmodule', 'autosummary', 'data', 'attr', 'obj', 'versionadded', 'versionchanged', 'module', 'class', 'ref', 'func', 'toctree', 'moduleauthor', 'term', 'c:member', 'sectionauthor', 'codeauthor', 'eq', 'doi', 'DOI', 'arXiv', 'arxiv']) error_stream = io.StringIO() def resolve(name, is_label=False): return ('http://foo', name) token = '' docutils.core.publish_doctree(text, token, settings_overrides=dict(halt_level=5, traceback=True, default_reference_context='title-reference', default_role='emphasis', link_base='', resolve_name=resolve, stylesheet_path='', raw_enabled=0, file_insertion_enabled=0, warning_stream=error_stream)) error_msg = error_stream.getvalue() errors = error_msg.split(token) success = True output = '' for error in errors: lines = error.splitlines() if not lines: continue m = re.match('.*Unknown (?:interpreted text role|directive type) "(.*)".*$', lines[0]) if m: if m.group(1) in ok_unknown_items: continue m = re.match('.*Error in "math" directive:.*unknown option: "label"', ' '.join(lines), re.S) if m: continue output += name + lines[0] + '::\n ' + '\n '.join(lines[1:]).rstrip() + '\n' success = False if not success: output += ' ' + '-' * 72 + '\n' for (lineno, line) in enumerate(text.splitlines()): output += ' %-4d %s\n' % (lineno + 1, line) output += ' ' + '-' * 72 + '\n\n' if dots: output_dot('.' if success else 'F') return (success, output) def output_dot(msg='.', stream=sys.stderr): stream.write(msg) stream.flush() def check_rest(module, names, dots=True): try: skip_types = (dict, str, unicode, float, int) except NameError: skip_types = (dict, str, float, int) results = [] if module.__name__[6:] not in OTHER_MODULE_DOCS: results += [(module.__name__,) + validate_rst_syntax(inspect.getdoc(module), module.__name__, dots=dots)] for name in names: full_name = module.__name__ + '.' + name obj = getattr(module, name, None) if obj is None: results.append((full_name, False, '%s has no docstring' % (full_name,))) continue elif isinstance(obj, skip_types): continue if inspect.ismodule(obj): text = inspect.getdoc(obj) else: try: text = str(get_doc_object(obj)) except Exception: import traceback results.append((full_name, False, 'Error in docstring format!\n' + traceback.format_exc())) continue m = re.search('([\x00-\t\x0b-\x1f])', text) if m: msg = 'Docstring contains a non-printable character %r! Maybe forgot r"""?' % (m.group(1),) results.append((full_name, False, msg)) continue try: src_file = short_path(inspect.getsourcefile(obj)) except TypeError: src_file = None if src_file: file_full_name = src_file + ':' + full_name else: file_full_name = full_name results.append((full_name,) + validate_rst_syntax(text, file_full_name, dots=dots)) return results def main(argv): parser = ArgumentParser(usage=__doc__.lstrip()) parser.add_argument('module_names', metavar='SUBMODULES', default=[], nargs='*', help='Submodules to check (default: all public)') parser.add_argument('-v', '--verbose', action='count', default=0) args = parser.parse_args(argv) modules = [] names_dict = {} if not args.module_names: args.module_names = list(PUBLIC_SUBMODULES) + [BASE_MODULE] module_names = list(args.module_names) for name in module_names: if name in OTHER_MODULE_DOCS: name = OTHER_MODULE_DOCS[name] if name not in module_names: module_names.append(name) dots = True success = True results = [] errormsgs = [] for submodule_name in module_names: prefix = BASE_MODULE + '.' if not (submodule_name.startswith(prefix) or submodule_name == BASE_MODULE): module_name = prefix + submodule_name else: module_name = submodule_name __import__(module_name) module = sys.modules[module_name] if submodule_name not in OTHER_MODULE_DOCS: find_names(module, names_dict) if submodule_name in args.module_names: modules.append(module) if modules: print('Running checks for %d modules:' % (len(modules),)) for module in modules: if dots: sys.stderr.write(module.__name__ + ' ') sys.stderr.flush() (all_dict, deprecated, others) = get_all_dict(module) names = names_dict.get(module.__name__, set()) mod_results = [] mod_results += check_items(all_dict, names, deprecated, others, module.__name__) mod_results += check_rest(module, set(names).difference(deprecated), dots=dots) for v in mod_results: assert isinstance(v, tuple), v results.append((module, mod_results)) if dots: sys.stderr.write('\n') sys.stderr.flush() for (module, mod_results) in results: success = all((x[1] for x in mod_results)) if not success: errormsgs.append(f'failed checking {module.__name__}') if success and args.verbose == 0: continue print('') print('=' * len(module.__name__)) print(module.__name__) print('=' * len(module.__name__)) print('') for (name, success, output) in mod_results: if name is None: if not success or args.verbose >= 1: print(output.strip()) print('') elif not success or (args.verbose >= 2 and output.strip()): print(name) print('-' * len(name)) print('') print(output.strip()) print('') if len(errormsgs) == 0: print('\nOK: all checks passed!') sys.exit(0) else: print('\nERROR: ', '\n '.join(errormsgs)) sys.exit(1) if __name__ == '__main__': main(argv=sys.argv[1:]) # File: numpy-main/tools/wheels/check_license.py """""" import sys import re import argparse import pathlib def check_text(text): ok = 'Copyright (c)' in text and re.search('This binary distribution of \\w+ also bundles the following software', text) return ok def main(): p = argparse.ArgumentParser(usage=__doc__.rstrip()) p.add_argument('module', nargs='?', default='numpy') args = p.parse_args() sys.path.pop(0) __import__(args.module) mod = sys.modules[args.module] sitepkgs = pathlib.Path(mod.__file__).parent.parent distinfo_path = list(sitepkgs.glob('numpy-*.dist-info'))[0] license_txt = distinfo_path / 'LICENSE.txt' with open(license_txt, encoding='utf-8') as f: text = f.read() ok = check_text(text) if not ok: print('ERROR: License text {} does not contain expected text fragments\n'.format(license_txt)) print(text) sys.exit(1) sys.exit(0) if __name__ == '__main__': main()