content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
from collections.abc import Mapping\nfrom typing import Any, Final\n\nfrom .auxfuncs import isintent_dict as isintent_dict\n\n__version__: Final[str] = ...\nf2py_version: Final = "See `f2py -v`"\n\noptions: Final[dict[str, bool]]\n\nfgetdims1: Final[str] = ...\nfgetdims2: Final[str] = ...\nfgetdims2_sa: Final[str] = ...\n\ndef findf90modules(m: Mapping[str, object]) -> list[dict[str, Any]]: ...\ndef buildhooks(pymod: Mapping[str, object]) -> dict[str, Any]: ...\n
.venv\Lib\site-packages\numpy\f2py\f90mod_rules.pyi
f90mod_rules.pyi
Other
467
0.85
0.125
0
node-utils
131
2024-12-07T19:19:31.844468
BSD-3-Clause
false
5b9a1596de7aecfd6665517b68838fc7
"""\n\nRules for building C/API module with f2py2e.\n\nCopyright 1999 -- 2011 Pearu Peterson all rights reserved.\nCopyright 2011 -- present NumPy Developers.\nPermission to use, modify, and distribute this software is given under the\nterms of the NumPy License.\n\nNO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n"""\nimport copy\n\nfrom ._isocbind import isoc_kindmap\nfrom .auxfuncs import (\n getfortranname,\n isexternal,\n isfunction,\n isfunction_wrap,\n isintent_in,\n isintent_out,\n islogicalfunction,\n ismoduleroutine,\n isscalar,\n issubroutine,\n issubroutine_wrap,\n outmess,\n show,\n)\n\n\ndef var2fixfortran(vars, a, fa=None, f90mode=None):\n if fa is None:\n fa = a\n if a not in vars:\n show(vars)\n outmess(f'var2fixfortran: No definition for argument "{a}".\n')\n return ''\n if 'typespec' not in vars[a]:\n show(vars[a])\n outmess(f'var2fixfortran: No typespec for argument "{a}".\n')\n return ''\n vardef = vars[a]['typespec']\n if vardef == 'type' and 'typename' in vars[a]:\n vardef = f"{vardef}({vars[a]['typename']})"\n selector = {}\n lk = ''\n if 'kindselector' in vars[a]:\n selector = vars[a]['kindselector']\n lk = 'kind'\n elif 'charselector' in vars[a]:\n selector = vars[a]['charselector']\n lk = 'len'\n if '*' in selector:\n if f90mode:\n if selector['*'] in ['*', ':', '(*)']:\n vardef = f'{vardef}(len=*)'\n else:\n vardef = f"{vardef}({lk}={selector['*']})"\n elif selector['*'] in ['*', ':']:\n vardef = f"{vardef}*({selector['*']})"\n else:\n vardef = f"{vardef}*{selector['*']}"\n elif 'len' in selector:\n vardef = f"{vardef}(len={selector['len']}"\n if 'kind' in selector:\n vardef = f"{vardef},kind={selector['kind']})"\n else:\n vardef = f'{vardef})'\n elif 'kind' in selector:\n vardef = f"{vardef}(kind={selector['kind']})"\n\n vardef = f'{vardef} {fa}'\n if 'dimension' in vars[a]:\n vardef = f"{vardef}({','.join(vars[a]['dimension'])})"\n return vardef\n\ndef useiso_c_binding(rout):\n useisoc = False\n for key, value in rout['vars'].items():\n kind_value = value.get('kindselector', {}).get('kind')\n if kind_value in isoc_kindmap:\n return True\n return useisoc\n\ndef createfuncwrapper(rout, signature=0):\n assert isfunction(rout)\n\n extra_args = []\n vars = rout['vars']\n for a in rout['args']:\n v = rout['vars'][a]\n for i, d in enumerate(v.get('dimension', [])):\n if d == ':':\n dn = f'f2py_{a}_d{i}'\n dv = {'typespec': 'integer', 'intent': ['hide']}\n dv['='] = f'shape({a}, {i})'\n extra_args.append(dn)\n vars[dn] = dv\n v['dimension'][i] = dn\n rout['args'].extend(extra_args)\n need_interface = bool(extra_args)\n\n ret = ['']\n\n def add(line, ret=ret):\n ret[0] = f'{ret[0]}\n {line}'\n name = rout['name']\n fortranname = getfortranname(rout)\n f90mode = ismoduleroutine(rout)\n newname = f'{name}f2pywrap'\n\n if newname not in vars:\n vars[newname] = vars[name]\n args = [newname] + rout['args'][1:]\n else:\n args = [newname] + rout['args']\n\n l_tmpl = var2fixfortran(vars, name, '@@@NAME@@@', f90mode)\n if l_tmpl[:13] == 'character*(*)':\n if f90mode:\n l_tmpl = 'character(len=10)' + l_tmpl[13:]\n else:\n l_tmpl = 'character*10' + l_tmpl[13:]\n charselect = vars[name]['charselector']\n if charselect.get('*', '') == '(*)':\n charselect['*'] = '10'\n\n l1 = l_tmpl.replace('@@@NAME@@@', newname)\n rl = None\n\n useisoc = useiso_c_binding(rout)\n sargs = ', '.join(args)\n if f90mode:\n # gh-23598 fix warning\n # Essentially, this gets called again with modules where the name of the\n # function is added to the arguments, which is not required, and removed\n sargs = sargs.replace(f"{name}, ", '')\n args = [arg for arg in args if arg != name]\n rout['args'] = args\n add(f"subroutine f2pywrap_{rout['modulename']}_{name} ({sargs})")\n if not signature:\n add(f"use {rout['modulename']}, only : {fortranname}")\n if useisoc:\n add('use iso_c_binding')\n else:\n add(f'subroutine f2pywrap{name} ({sargs})')\n if useisoc:\n add('use iso_c_binding')\n if not need_interface:\n add(f'external {fortranname}')\n rl = l_tmpl.replace('@@@NAME@@@', '') + ' ' + fortranname\n\n if need_interface:\n for line in rout['saved_interface'].split('\n'):\n if line.lstrip().startswith('use ') and '__user__' not in line:\n add(line)\n\n args = args[1:]\n dumped_args = []\n for a in args:\n if isexternal(vars[a]):\n add(f'external {a}')\n dumped_args.append(a)\n for a in args:\n if a in dumped_args:\n continue\n if isscalar(vars[a]):\n add(var2fixfortran(vars, a, f90mode=f90mode))\n dumped_args.append(a)\n for a in args:\n if a in dumped_args:\n continue\n if isintent_in(vars[a]):\n add(var2fixfortran(vars, a, f90mode=f90mode))\n dumped_args.append(a)\n for a in args:\n if a in dumped_args:\n continue\n add(var2fixfortran(vars, a, f90mode=f90mode))\n\n add(l1)\n if rl is not None:\n add(rl)\n\n if need_interface:\n if f90mode:\n # f90 module already defines needed interface\n pass\n else:\n add('interface')\n add(rout['saved_interface'].lstrip())\n add('end interface')\n\n sargs = ', '.join([a for a in args if a not in extra_args])\n\n if not signature:\n if islogicalfunction(rout):\n add(f'{newname} = .not.(.not.{fortranname}({sargs}))')\n else:\n add(f'{newname} = {fortranname}({sargs})')\n if f90mode:\n add(f"end subroutine f2pywrap_{rout['modulename']}_{name}")\n else:\n add('end')\n return ret[0]\n\n\ndef createsubrwrapper(rout, signature=0):\n assert issubroutine(rout)\n\n extra_args = []\n vars = rout['vars']\n for a in rout['args']:\n v = rout['vars'][a]\n for i, d in enumerate(v.get('dimension', [])):\n if d == ':':\n dn = f'f2py_{a}_d{i}'\n dv = {'typespec': 'integer', 'intent': ['hide']}\n dv['='] = f'shape({a}, {i})'\n extra_args.append(dn)\n vars[dn] = dv\n v['dimension'][i] = dn\n rout['args'].extend(extra_args)\n need_interface = bool(extra_args)\n\n ret = ['']\n\n def add(line, ret=ret):\n ret[0] = f'{ret[0]}\n {line}'\n name = rout['name']\n fortranname = getfortranname(rout)\n f90mode = ismoduleroutine(rout)\n\n args = rout['args']\n\n useisoc = useiso_c_binding(rout)\n sargs = ', '.join(args)\n if f90mode:\n add(f"subroutine f2pywrap_{rout['modulename']}_{name} ({sargs})")\n if useisoc:\n add('use iso_c_binding')\n if not signature:\n add(f"use {rout['modulename']}, only : {fortranname}")\n else:\n add(f'subroutine f2pywrap{name} ({sargs})')\n if useisoc:\n add('use iso_c_binding')\n if not need_interface:\n add(f'external {fortranname}')\n\n if need_interface:\n for line in rout['saved_interface'].split('\n'):\n if line.lstrip().startswith('use ') and '__user__' not in line:\n add(line)\n\n dumped_args = []\n for a in args:\n if isexternal(vars[a]):\n add(f'external {a}')\n dumped_args.append(a)\n for a in args:\n if a in dumped_args:\n continue\n if isscalar(vars[a]):\n add(var2fixfortran(vars, a, f90mode=f90mode))\n dumped_args.append(a)\n for a in args:\n if a in dumped_args:\n continue\n add(var2fixfortran(vars, a, f90mode=f90mode))\n\n if need_interface:\n if f90mode:\n # f90 module already defines needed interface\n pass\n else:\n add('interface')\n for line in rout['saved_interface'].split('\n'):\n if line.lstrip().startswith('use ') and '__user__' in line:\n continue\n add(line)\n add('end interface')\n\n sargs = ', '.join([a for a in args if a not in extra_args])\n\n if not signature:\n add(f'call {fortranname}({sargs})')\n if f90mode:\n add(f"end subroutine f2pywrap_{rout['modulename']}_{name}")\n else:\n add('end')\n return ret[0]\n\n\ndef assubr(rout):\n if isfunction_wrap(rout):\n fortranname = getfortranname(rout)\n name = rout['name']\n outmess('\t\tCreating wrapper for Fortran function "%s"("%s")...\n' % (\n name, fortranname))\n rout = copy.copy(rout)\n fname = name\n rname = fname\n if 'result' in rout:\n rname = rout['result']\n rout['vars'][fname] = rout['vars'][rname]\n fvar = rout['vars'][fname]\n if not isintent_out(fvar):\n if 'intent' not in fvar:\n fvar['intent'] = []\n fvar['intent'].append('out')\n flag = 1\n for i in fvar['intent']:\n if i.startswith('out='):\n flag = 0\n break\n if flag:\n fvar['intent'].append(f'out={rname}')\n rout['args'][:] = [fname] + rout['args']\n return rout, createfuncwrapper(rout)\n if issubroutine_wrap(rout):\n fortranname = getfortranname(rout)\n name = rout['name']\n outmess('\t\tCreating wrapper for Fortran subroutine "%s"("%s")...\n'\n % (name, fortranname))\n rout = copy.copy(rout)\n return rout, createsubrwrapper(rout)\n return rout, ''\n
.venv\Lib\site-packages\numpy\f2py\func2subr.py
func2subr.py
Python
10,378
0.95
0.288754
0.017065
react-lib
114
2025-04-20T23:08:07.887627
Apache-2.0
false
4bf942a46e5721234bb42c0f83919970
from .auxfuncs import _Bool, _ROut, _Var\n\ndef var2fixfortran(vars: _Var, a: str, fa: str | None = None, f90mode: _Bool | None = None) -> str: ...\ndef useiso_c_binding(rout: _ROut) -> bool: ...\ndef createfuncwrapper(rout: _ROut, signature: int = 0) -> str: ...\ndef createsubrwrapper(rout: _ROut, signature: int = 0) -> str: ...\ndef assubr(rout: _ROut) -> tuple[dict[str, str], str]: ...\n
.venv\Lib\site-packages\numpy\f2py\func2subr.pyi
func2subr.pyi
Other
393
0.85
0.714286
0
node-utils
416
2024-10-16T04:56:15.516217
BSD-3-Clause
false
7a9fc9e4007ff3030a83993248deffc1
"""\n\nRules for building C/API module with f2py2e.\n\nHere is a skeleton of a new wrapper function (13Dec2001):\n\nwrapper_function(args)\n declarations\n get_python_arguments, say, `a' and `b'\n\n get_a_from_python\n if (successful) {\n\n get_b_from_python\n if (successful) {\n\n callfortran\n if (successful) {\n\n put_a_to_python\n if (successful) {\n\n put_b_to_python\n if (successful) {\n\n buildvalue = ...\n\n }\n\n }\n\n }\n\n }\n cleanup_b\n\n }\n cleanup_a\n\n return buildvalue\n\nCopyright 1999 -- 2011 Pearu Peterson all rights reserved.\nCopyright 2011 -- present NumPy Developers.\nPermission to use, modify, and distribute this software is given under the\nterms of the NumPy License.\n\nNO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n"""\nimport copy\nimport os\nimport sys\nimport time\nfrom pathlib import Path\n\n# __version__.version is now the same as the NumPy version\nfrom . import (\n __version__,\n capi_maps,\n cfuncs,\n common_rules,\n f90mod_rules,\n func2subr,\n use_rules,\n)\nfrom .auxfuncs import (\n applyrules,\n debugcapi,\n dictappend,\n errmess,\n gentitle,\n getargs2,\n hascallstatement,\n hasexternals,\n hasinitvalue,\n hasnote,\n hasresultnote,\n isarray,\n isarrayofstrings,\n isattr_value,\n ischaracter,\n ischaracter_or_characterarray,\n ischaracterarray,\n iscomplex,\n iscomplexarray,\n iscomplexfunction,\n iscomplexfunction_warn,\n isdummyroutine,\n isexternal,\n isfunction,\n isfunction_wrap,\n isint1,\n isint1array,\n isintent_aux,\n isintent_c,\n isintent_callback,\n isintent_copy,\n isintent_hide,\n isintent_inout,\n isintent_nothide,\n isintent_out,\n isintent_overwrite,\n islogical,\n islong_complex,\n islong_double,\n islong_doublefunction,\n islong_long,\n islong_longfunction,\n ismoduleroutine,\n isoptional,\n isrequired,\n isscalar,\n issigned_long_longarray,\n isstring,\n isstringarray,\n isstringfunction,\n issubroutine,\n issubroutine_wrap,\n isthreadsafe,\n isunsigned,\n isunsigned_char,\n isunsigned_chararray,\n isunsigned_long_long,\n isunsigned_long_longarray,\n isunsigned_short,\n isunsigned_shortarray,\n l_and,\n l_not,\n l_or,\n outmess,\n replace,\n requiresf90wrapper,\n stripcomma,\n)\n\nf2py_version = __version__.version\nnumpy_version = __version__.version\n\noptions = {}\nsepdict = {}\n# for k in ['need_cfuncs']: sepdict[k]=','\nfor k in ['decl',\n 'frompyobj',\n 'cleanupfrompyobj',\n 'topyarr', 'method',\n 'pyobjfrom', 'closepyobjfrom',\n 'freemem',\n 'userincludes',\n 'includes0', 'includes', 'typedefs', 'typedefs_generated',\n 'cppmacros', 'cfuncs', 'callbacks',\n 'latexdoc',\n 'restdoc',\n 'routine_defs', 'externroutines',\n 'initf2pywraphooks',\n 'commonhooks', 'initcommonhooks',\n 'f90modhooks', 'initf90modhooks']:\n sepdict[k] = '\n'\n\n#################### Rules for C/API module #################\n\ngenerationtime = int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))\nmodule_rules = {\n 'modulebody': """\\n/* 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 <pearu@cens.ioc.ee>.\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 <Python.h>\n#include <numpy/npy_os.h>\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\n if (PyType_Ready(&PyFortran_Type) < 0) {\n return NULL;\n }\n\n return m;\n}\n#ifdef __cplusplus\n}\n#endif\n""",\n 'separatorsfor': {'latexdoc': '\n\n',\n 'restdoc': '\n\n'},\n 'latexdoc': ['\\section{Module \\texttt{#texmodulename#}}\n',\n '#modnote#\n',\n '#latexdoc#'],\n 'restdoc': ['Module #modulename#\n' + '=' * 80,\n '\n#restdoc#']\n}\n\ndefmod_rules = [\n {'body': '/*eof body*/',\n 'method': '/*eof method*/',\n 'externroutines': '/*eof externroutines*/',\n 'routine_defs': '/*eof routine_defs*/',\n 'initf90modhooks': '/*eof initf90modhooks*/',\n 'initf2pywraphooks': '/*eof initf2pywraphooks*/',\n 'initcommonhooks': '/*eof initcommonhooks*/',\n 'latexdoc': '',\n 'restdoc': '',\n 'modnote': {hasnote: '#note#', l_not(hasnote): ''},\n }\n]\n\nroutine_rules = {\n 'separatorsfor': sepdict,\n '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""",\n 'routine_defs': '#routine_def#',\n 'initf2pywraphooks': '#initf2pywraphook#',\n 'externroutines': '#declfortranroutine#',\n 'doc': '#docreturn##name#(#docsignature#)',\n 'docshort': '#docreturn##name#(#docsignatureshort#)',\n 'docs': '" #docreturn##name#(#docsignature#)\\n"\n',\n 'need': ['arrayobject.h', 'CFUNCSMESS', 'MINMAX'],\n 'cppmacros': {debugcapi: '#define DEBUGCFUNCS'},\n 'latexdoc': ['\\subsection{Wrapper function \\texttt{#texname#}}\n',\n """\n\\noindent{{}\\verb@#docreturn##name#@{}}\\texttt{(#latexdocsignatureshort#)}\n#routnote#\n\n#latexdocstrsigns#\n"""],\n 'restdoc': ['Wrapped function ``#name#``\n' + '-' * 80,\n\n ]\n}\n\n################## Rules for C/API function ##############\n\nrout_rules = [\n { # Init\n 'separatorsfor': {'callfortranroutine': '\n', 'routdebugenter': '\n', 'decl': '\n',\n 'routdebugleave': '\n', 'routdebugfailure': '\n',\n 'setjmpbuf': ' || ',\n 'docstrreq': '\n', 'docstropt': '\n', 'docstrout': '\n',\n 'docstrcbs': '\n', 'docstrsigns': '\\n"\n"',\n 'latexdocstrsigns': '\n',\n 'latexdocstrreq': '\n', 'latexdocstropt': '\n',\n 'latexdocstrout': '\n', 'latexdocstrcbs': '\n',\n },\n 'kwlist': '', 'kwlistopt': '', 'callfortran': '', 'callfortranappend': '',\n 'docsign': '', 'docsignopt': '', 'decl': '/*decl*/',\n 'freemem': '/*freemem*/',\n 'docsignshort': '', 'docsignoptshort': '',\n 'docstrsigns': '', 'latexdocstrsigns': '',\n 'docstrreq': '\\nParameters\\n----------',\n 'docstropt': '\\nOther Parameters\\n----------------',\n 'docstrout': '\\nReturns\\n-------',\n 'docstrcbs': '\\nNotes\\n-----\\nCall-back functions::\\n',\n 'latexdocstrreq': '\\noindent Required arguments:',\n 'latexdocstropt': '\\noindent Optional arguments:',\n 'latexdocstrout': '\\noindent Return objects:',\n 'latexdocstrcbs': '\\noindent Call-back functions:',\n 'args_capi': '', 'keys_capi': '', 'functype': '',\n 'frompyobj': '/*frompyobj*/',\n # this list will be reversed\n 'cleanupfrompyobj': ['/*end of cleanupfrompyobj*/'],\n 'pyobjfrom': '/*pyobjfrom*/',\n # this list will be reversed\n 'closepyobjfrom': ['/*end of closepyobjfrom*/'],\n 'topyarr': '/*topyarr*/', 'routdebugleave': '/*routdebugleave*/',\n 'routdebugenter': '/*routdebugenter*/',\n 'routdebugfailure': '/*routdebugfailure*/',\n 'callfortranroutine': '/*callfortranroutine*/',\n 'argformat': '', 'keyformat': '', 'need_cfuncs': '',\n 'docreturn': '', 'return': '', 'returnformat': '', 'rformat': '',\n 'kwlistxa': '', 'keys_xa': '', 'xaformat': '', 'docsignxa': '', 'docsignxashort': '',\n 'initf2pywraphook': '',\n 'routnote': {hasnote: '--- #note#', l_not(hasnote): ''},\n }, {\n 'apiname': 'f2py_rout_#modulename#_#name#',\n 'pyname': '#modulename#.#name#',\n 'decl': '',\n '_check': l_not(ismoduleroutine)\n }, {\n 'apiname': 'f2py_rout_#modulename#_#f90modulename#_#name#',\n 'pyname': '#modulename#.#f90modulename#.#name#',\n 'decl': '',\n '_check': ismoduleroutine\n }, { # Subroutine\n 'functype': 'void',\n 'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',\n l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern void #fortranname#(#callprotoargument#);',\n ismoduleroutine: '',\n isdummyroutine: ''\n },\n 'routine_def': {\n l_not(l_or(ismoduleroutine, isintent_c, isdummyroutine)):\n ' {\"#name#\",-1,{{-1}},0,0,(char *)'\n ' #F_FUNC#(#fortranname#,#FORTRANNAME#),'\n ' (f2py_init_func)#apiname#,doc_#apiname#},',\n l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)):\n ' {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,'\n ' (f2py_init_func)#apiname#,doc_#apiname#},',\n l_and(l_not(ismoduleroutine), isdummyroutine):\n ' {\"#name#\",-1,{{-1}},0,0,NULL,'\n ' (f2py_init_func)#apiname#,doc_#apiname#},',\n },\n 'need': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'F_FUNC'},\n 'callfortranroutine': [\n {debugcapi: [\n """ fprintf(stderr,\"debug-capi:Fortran subroutine `#fortranname#(#callfortran#)\'\\n\");"""]},\n {hasexternals: """\\n if (#setjmpbuf#) {\n f2py_success = 0;\n } else {"""},\n {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},\n {hascallstatement: ''' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'''},\n {l_not(l_or(hascallstatement, isdummyroutine))\n : ' (*f2py_func)(#callfortran#);'},\n {isthreadsafe: ' Py_END_ALLOW_THREADS'},\n {hasexternals: """ }"""}\n ],\n '_check': l_and(issubroutine, l_not(issubroutine_wrap)),\n }, { # Wrapped function\n 'functype': 'void',\n 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);',\n isdummyroutine: '',\n },\n\n 'routine_def': {\n l_not(l_or(ismoduleroutine, isdummyroutine)):\n ' {\"#name#\",-1,{{-1}},0,0,(char *)'\n ' #F_WRAPPEDFUNC#(#name_lower#,#NAME#),'\n ' (f2py_init_func)#apiname#,doc_#apiname#},',\n isdummyroutine:\n ' {\"#name#\",-1,{{-1}},0,0,NULL,'\n ' (f2py_init_func)#apiname#,doc_#apiname#},',\n },\n '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_WRAPPEDFUNC#(#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 '''},\n 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']},\n 'callfortranroutine': [\n {debugcapi: [\n """ fprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]},\n {hasexternals: """\\n if (#setjmpbuf#) {\n f2py_success = 0;\n } else {"""},\n {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},\n {l_not(l_or(hascallstatement, isdummyroutine))\n : ' (*f2py_func)(#callfortran#);'},\n {hascallstatement:\n ' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'},\n {isthreadsafe: ' Py_END_ALLOW_THREADS'},\n {hasexternals: ' }'}\n ],\n '_check': isfunction_wrap,\n }, { # Wrapped subroutine\n 'functype': 'void',\n 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);',\n isdummyroutine: '',\n },\n\n 'routine_def': {\n l_not(l_or(ismoduleroutine, isdummyroutine)):\n ' {\"#name#\",-1,{{-1}},0,0,(char *)'\n ' #F_WRAPPEDFUNC#(#name_lower#,#NAME#),'\n ' (f2py_init_func)#apiname#,doc_#apiname#},',\n isdummyroutine:\n ' {\"#name#\",-1,{{-1}},0,0,NULL,'\n ' (f2py_init_func)#apiname#,doc_#apiname#},',\n },\n '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 '''},\n 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']},\n 'callfortranroutine': [\n {debugcapi: [\n """ fprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]},\n {hasexternals: """\\n if (#setjmpbuf#) {\n f2py_success = 0;\n } else {"""},\n {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},\n {l_not(l_or(hascallstatement, isdummyroutine))\n : ' (*f2py_func)(#callfortran#);'},\n {hascallstatement:\n ' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'},\n {isthreadsafe: ' Py_END_ALLOW_THREADS'},\n {hasexternals: ' }'}\n ],\n '_check': issubroutine_wrap,\n }, { # Function\n 'functype': '#ctype#',\n 'docreturn': {l_not(isintent_hide): '#rname#,'},\n 'docstrout': '#pydocsignout#',\n 'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}',\n {hasresultnote: '--- #resultnote#'}],\n 'callfortranroutine': [{l_and(debugcapi, isstringfunction): """\\n#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"""},\n {l_and(debugcapi, l_not(isstringfunction)): """\\n fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\");\n"""}\n ],\n '_check': l_and(isfunction, l_not(isfunction_wrap))\n }, { # Scalar function\n 'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern #ctype# #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',\n l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern #ctype# #fortranname#(#callprotoargument#);',\n isdummyroutine: ''\n },\n 'routine_def': {\n l_and(l_not(l_or(ismoduleroutine, isintent_c)),\n l_not(isdummyroutine)):\n (' {\"#name#\",-1,{{-1}},0,0,(char *)'\n ' #F_FUNC#(#fortranname#,#FORTRANNAME#),'\n ' (f2py_init_func)#apiname#,doc_#apiname#},'),\n l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)):\n (' {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,'\n ' (f2py_init_func)#apiname#,doc_#apiname#},'),\n isdummyroutine:\n ' {\"#name#\",-1,{{-1}},0,0,NULL,'\n '(f2py_init_func)#apiname#,doc_#apiname#},',\n },\n 'decl': [{iscomplexfunction_warn: ' #ctype# #name#_return_value={0,0};',\n l_not(iscomplexfunction): ' #ctype# #name#_return_value=0;'},\n {iscomplexfunction:\n ' PyObject *#name#_return_value_capi = Py_None;'}\n ],\n 'callfortranroutine': [\n {hasexternals: """\\n if (#setjmpbuf#) {\n f2py_success = 0;\n } else {"""},\n {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},\n {hascallstatement: ''' #callstatement#;\n/* #name#_return_value = (*f2py_func)(#callfortran#);*/\n'''},\n {l_not(l_or(hascallstatement, isdummyroutine))\n : ' #name#_return_value = (*f2py_func)(#callfortran#);'},\n {isthreadsafe: ' Py_END_ALLOW_THREADS'},\n {hasexternals: ' }'},\n {l_and(debugcapi, iscomplexfunction)\n : ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value.r,#name#_return_value.i);'},\n {l_and(debugcapi, l_not(iscomplexfunction)): ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value);'}],\n 'pyobjfrom': {iscomplexfunction: ' #name#_return_value_capi = pyobj_from_#ctype#1(#name#_return_value);'},\n 'need': [{l_not(isdummyroutine): 'F_FUNC'},\n {iscomplexfunction: 'pyobj_from_#ctype#1'},\n {islong_longfunction: 'long_long'},\n {islong_doublefunction: 'long_double'}],\n 'returnformat': {l_not(isintent_hide): '#rformat#'},\n 'return': {iscomplexfunction: ',#name#_return_value_capi',\n l_not(l_or(iscomplexfunction, isintent_hide)): ',#name#_return_value'},\n '_check': l_and(isfunction, l_not(isstringfunction), l_not(isfunction_wrap))\n }, { # String function # in use for --no-wrap\n 'declfortranroutine': 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',\n 'routine_def': {l_not(l_or(ismoduleroutine, isintent_c)):\n ' {\"#name#\",-1,{{-1}},0,0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},',\n l_and(l_not(ismoduleroutine), isintent_c):\n ' {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},'\n },\n 'decl': [' #ctype# #name#_return_value = NULL;',\n ' int #name#_return_value_len = 0;'],\n 'callfortran': '#name#_return_value,#name#_return_value_len,',\n 'callfortranroutine': [' #name#_return_value_len = #rlength#;',\n ' if ((#name#_return_value = (string)malloc(#name#_return_value_len+1) == NULL) {',\n ' PyErr_SetString(PyExc_MemoryError, \"out of memory\");',\n ' f2py_success = 0;',\n ' } else {',\n " (#name#_return_value)[#name#_return_value_len] = '\\0';",\n ' }',\n ' if (f2py_success) {',\n {hasexternals: """\\n if (#setjmpbuf#) {\n f2py_success = 0;\n } else {"""},\n {isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},\n """\\n#ifdef USESCOMPAQFORTRAN\n (*f2py_func)(#callcompaqfortran#);\n#else\n (*f2py_func)(#callfortran#);\n#endif\n""",\n {isthreadsafe: ' Py_END_ALLOW_THREADS'},\n {hasexternals: ' }'},\n {debugcapi:\n ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value_len,#name#_return_value);'},\n ' } /* if (f2py_success) after (string)malloc */',\n ],\n 'returnformat': '#rformat#',\n 'return': ',#name#_return_value',\n 'freemem': ' STRINGFREE(#name#_return_value);',\n 'need': ['F_FUNC', '#ctype#', 'STRINGFREE'],\n '_check': l_and(isstringfunction, l_not(isfunction_wrap)) # ???obsolete\n },\n { # Debugging\n 'routdebugenter': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#(#docsignature#)\\n");',\n 'routdebugleave': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: successful.\\n");',\n 'routdebugfailure': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: failure.\\n");',\n '_check': debugcapi\n }\n]\n\n################ Rules for arguments ##################\n\ntypedef_need_dict = {islong_long: 'long_long',\n islong_double: 'long_double',\n islong_complex: 'complex_long_double',\n isunsigned_char: 'unsigned_char',\n isunsigned_short: 'unsigned_short',\n isunsigned: 'unsigned',\n isunsigned_long_long: 'unsigned_long_long',\n isunsigned_chararray: 'unsigned_char',\n isunsigned_shortarray: 'unsigned_short',\n isunsigned_long_longarray: 'unsigned_long_long',\n issigned_long_longarray: 'long_long',\n isint1: 'signed_char',\n ischaracter_or_characterarray: 'character',\n }\n\naux_rules = [\n {\n 'separatorsfor': sepdict\n },\n { # Common\n 'frompyobj': [' /* Processing auxiliary variable #varname# */',\n {debugcapi: ' fprintf(stderr,"#vardebuginfo#\\n");'}, ],\n 'cleanupfrompyobj': ' /* End of cleaning variable #varname# */',\n 'need': typedef_need_dict,\n },\n # Scalars (not complex)\n { # Common\n 'decl': ' #ctype# #varname# = 0;',\n 'need': {hasinitvalue: 'math.h'},\n 'frompyobj': {hasinitvalue: ' #varname# = #init#;'},\n '_check': l_and(isscalar, l_not(iscomplex)),\n },\n {\n 'return': ',#varname#',\n 'docstrout': '#pydocsignout#',\n 'docreturn': '#outvarname#,',\n 'returnformat': '#varrformat#',\n '_check': l_and(isscalar, l_not(iscomplex), isintent_out),\n },\n # Complex scalars\n { # Common\n 'decl': ' #ctype# #varname#;',\n 'frompyobj': {hasinitvalue: ' #varname#.r = #init.r#, #varname#.i = #init.i#;'},\n '_check': iscomplex\n },\n # String\n { # Common\n 'decl': [' #ctype# #varname# = NULL;',\n ' int slen(#varname#);',\n ],\n 'need': ['len..'],\n '_check': isstring\n },\n # Array\n { # Common\n 'decl': [' #ctype# *#varname# = NULL;',\n ' npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};',\n ' const int #varname#_Rank = #rank#;',\n ],\n 'need': ['len..', {hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}],\n '_check': isarray\n },\n # Scalararray\n { # Common\n '_check': l_and(isarray, l_not(iscomplexarray))\n }, { # Not hidden\n '_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide)\n },\n # Integer*1 array\n {'need': '#ctype#',\n '_check': isint1array,\n '_depend': ''\n },\n # Integer*-1 array\n {'need': '#ctype#',\n '_check': l_or(isunsigned_chararray, isunsigned_char),\n '_depend': ''\n },\n # Integer*-2 array\n {'need': '#ctype#',\n '_check': isunsigned_shortarray,\n '_depend': ''\n },\n # Integer*-8 array\n {'need': '#ctype#',\n '_check': isunsigned_long_longarray,\n '_depend': ''\n },\n # Complexarray\n {'need': '#ctype#',\n '_check': iscomplexarray,\n '_depend': ''\n },\n # Stringarray\n {\n 'callfortranappend': {isarrayofstrings: 'flen(#varname#),'},\n 'need': 'string',\n '_check': isstringarray\n }\n]\n\narg_rules = [\n {\n 'separatorsfor': sepdict\n },\n { # Common\n 'frompyobj': [' /* Processing variable #varname# */',\n {debugcapi: ' fprintf(stderr,"#vardebuginfo#\\n");'}, ],\n 'cleanupfrompyobj': ' /* End of cleaning variable #varname# */',\n '_depend': '',\n 'need': typedef_need_dict,\n },\n # Doc signatures\n {\n 'docstropt': {l_and(isoptional, isintent_nothide): '#pydocsign#'},\n 'docstrreq': {l_and(isrequired, isintent_nothide): '#pydocsign#'},\n 'docstrout': {isintent_out: '#pydocsignout#'},\n 'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}',\n {hasnote: '--- #note#'}]},\n 'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}',\n {hasnote: '--- #note#'}]},\n 'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}',\n {l_and(hasnote, isintent_hide): '--- #note#',\n l_and(hasnote, isintent_nothide): '--- See above.'}]},\n 'depend': ''\n },\n # Required/Optional arguments\n {\n 'kwlist': '"#varname#",',\n 'docsign': '#varname#,',\n '_check': l_and(isintent_nothide, l_not(isoptional))\n },\n {\n 'kwlistopt': '"#varname#",',\n 'docsignopt': '#varname#=#showinit#,',\n 'docsignoptshort': '#varname#,',\n '_check': l_and(isintent_nothide, isoptional)\n },\n # Docstring/BuildValue\n {\n 'docreturn': '#outvarname#,',\n 'returnformat': '#varrformat#',\n '_check': isintent_out\n },\n # Externals (call-back functions)\n { # Common\n 'docsignxa': {isintent_nothide: '#varname#_extra_args=(),'},\n 'docsignxashort': {isintent_nothide: '#varname#_extra_args,'},\n 'docstropt': {isintent_nothide: '#varname#_extra_args : input tuple, optional\\n Default: ()'},\n 'docstrcbs': '#cbdocstr#',\n 'latexdocstrcbs': '\\item[] #cblatexdocstr#',\n 'latexdocstropt': {isintent_nothide: '\\item[]{{}\\verb@#varname#_extra_args := () input tuple@{}} --- Extra arguments for call-back function {{}\\verb@#varname#@{}}.'},\n 'decl': [' #cbname#_t #varname#_cb = { Py_None, NULL, 0 };',\n ' #cbname#_t *#varname#_cb_ptr = &#varname#_cb;',\n ' PyTupleObject *#varname#_xa_capi = NULL;',\n {l_not(isintent_callback):\n ' #cbname#_typedef #varname#_cptr;'}\n ],\n 'kwlistxa': {isintent_nothide: '"#varname#_extra_args",'},\n 'argformat': {isrequired: 'O'},\n 'keyformat': {isoptional: 'O'},\n 'xaformat': {isintent_nothide: 'O!'},\n 'args_capi': {isrequired: ',&#varname#_cb.capi'},\n 'keys_capi': {isoptional: ',&#varname#_cb.capi'},\n 'keys_xa': ',&PyTuple_Type,&#varname#_xa_capi',\n 'setjmpbuf': '(setjmp(#varname#_cb.jmpbuf))',\n 'callfortran': {l_not(isintent_callback): '#varname#_cptr,'},\n 'need': ['#cbname#', 'setjmp.h'],\n '_check': isexternal\n },\n {\n 'frompyobj': [{l_not(isintent_callback): """\\nif(F2PyCapsule_Check(#varname#_cb.capi)) {\n #varname#_cptr = F2PyCapsule_AsVoidPtr(#varname#_cb.capi);\n} else {\n #varname#_cptr = #cbname#;\n}\n"""}, {isintent_callback: """\\nif (#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"""},\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""",\n {debugcapi: ["""\\n fprintf(stderr,\"debug-capi:Assuming %d arguments; at most #maxnofargs#(-#nofoptargs#) is expected.\\n\",#varname#_cb.nofargs);\n CFUNCSMESSPY(\"for #varname#=\",#varname#_cb.capi);""",\n {l_not(isintent_callback): """ fprintf(stderr,\"#vardebugshowvalue# (call-back in C).\\n\",#cbname#);"""}]},\n """\\n CFUNCSMESS(\"Saving callback variables for `#varname#`.\\n\");\n #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);""",\n ],\n 'cleanupfrompyobj':\n """\\n 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 }""",\n 'need': ['SWAP', 'create_cb_arglist'],\n '_check': isexternal,\n '_depend': ''\n },\n # Scalars (not complex)\n { # Common\n 'decl': ' #ctype# #varname# = 0;',\n 'pyobjfrom': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'},\n 'callfortran': {l_or(isintent_c, isattr_value): '#varname#,', l_not(l_or(isintent_c, isattr_value)): '&#varname#,'},\n 'return': {isintent_out: ',#varname#'},\n '_check': l_and(isscalar, l_not(iscomplex))\n }, {\n 'need': {hasinitvalue: 'math.h'},\n '_check': l_and(isscalar, l_not(iscomplex)),\n }, { # Not hidden\n 'decl': ' PyObject *#varname#_capi = Py_None;',\n 'argformat': {isrequired: 'O'},\n 'keyformat': {isoptional: 'O'},\n 'args_capi': {isrequired: ',&#varname#_capi'},\n 'keys_capi': {isoptional: ',&#varname#_capi'},\n 'pyobjfrom': {isintent_inout: """\\n f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#);\n if (f2py_success) {"""},\n 'closepyobjfrom': {isintent_inout: " } /*if (f2py_success) of #varname# pyobjfrom*/"},\n 'need': {isintent_inout: 'try_pyarr_from_#ctype#'},\n '_check': l_and(isscalar, l_not(iscomplex), l_not(isstring),\n isintent_nothide)\n }, {\n 'frompyobj': [\n # hasinitvalue...\n # if pyobj is None:\n # varname = init\n # else\n # from_pyobj(varname)\n #\n # isoptional and noinitvalue...\n # if pyobj is not None:\n # from_pyobj(varname)\n # else:\n # varname is uninitialized\n #\n # ...\n # from_pyobj(varname)\n #\n {hasinitvalue: ' if (#varname#_capi == Py_None) #varname# = #init#; else',\n '_depend': ''},\n {l_and(isoptional, l_not(hasinitvalue)): ' if (#varname#_capi != Py_None)',\n '_depend': ''},\n {l_not(islogical): '''\\n f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");\n if (f2py_success) {'''},\n {islogical: '''\\n #varname# = (#ctype#)PyObject_IsTrue(#varname#_capi);\n f2py_success = 1;\n if (f2py_success) {'''},\n ],\n 'cleanupfrompyobj': ' } /*if (f2py_success) of #varname#*/',\n 'need': {l_not(islogical): '#ctype#_from_pyobj'},\n '_check': l_and(isscalar, l_not(iscomplex), isintent_nothide),\n '_depend': ''\n }, { # Hidden\n 'frompyobj': {hasinitvalue: ' #varname# = #init#;'},\n 'need': typedef_need_dict,\n '_check': l_and(isscalar, l_not(iscomplex), isintent_hide),\n '_depend': ''\n }, { # Common\n 'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'},\n '_check': l_and(isscalar, l_not(iscomplex)),\n '_depend': ''\n },\n # Complex scalars\n { # Common\n 'decl': ' #ctype# #varname#;',\n 'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'},\n 'pyobjfrom': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'},\n 'return': {isintent_out: ',#varname#_capi'},\n '_check': iscomplex\n }, { # Not hidden\n 'decl': ' PyObject *#varname#_capi = Py_None;',\n 'argformat': {isrequired: 'O'},\n 'keyformat': {isoptional: 'O'},\n 'args_capi': {isrequired: ',&#varname#_capi'},\n 'keys_capi': {isoptional: ',&#varname#_capi'},\n 'need': {isintent_inout: 'try_pyarr_from_#ctype#'},\n 'pyobjfrom': {isintent_inout: """\\n f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#);\n if (f2py_success) {"""},\n 'closepyobjfrom': {isintent_inout: " } /*if (f2py_success) of #varname# pyobjfrom*/"},\n '_check': l_and(iscomplex, isintent_nothide)\n }, {\n 'frompyobj': [{hasinitvalue: ' if (#varname#_capi==Py_None) {#varname#.r = #init.r#, #varname#.i = #init.i#;} else'},\n {l_and(isoptional, l_not(hasinitvalue))\n : ' if (#varname#_capi != Py_None)'},\n ' f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");'\n '\n if (f2py_success) {'],\n 'cleanupfrompyobj': ' } /*if (f2py_success) of #varname# frompyobj*/',\n 'need': ['#ctype#_from_pyobj'],\n '_check': l_and(iscomplex, isintent_nothide),\n '_depend': ''\n }, { # Hidden\n 'decl': {isintent_out: ' PyObject *#varname#_capi = Py_None;'},\n '_check': l_and(iscomplex, isintent_hide)\n }, {\n 'frompyobj': {hasinitvalue: ' #varname#.r = #init.r#, #varname#.i = #init.i#;'},\n '_check': l_and(iscomplex, isintent_hide),\n '_depend': ''\n }, { # Common\n 'pyobjfrom': {isintent_out: ' #varname#_capi = pyobj_from_#ctype#1(#varname#);'},\n 'need': ['pyobj_from_#ctype#1'],\n '_check': iscomplex\n }, {\n 'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'},\n '_check': iscomplex,\n '_depend': ''\n },\n # String\n { # Common\n 'decl': [' #ctype# #varname# = NULL;',\n ' int slen(#varname#);',\n ' PyObject *#varname#_capi = Py_None;'],\n 'callfortran': '#varname#,',\n 'callfortranappend': 'slen(#varname#),',\n 'pyobjfrom': [\n {debugcapi:\n ' fprintf(stderr,'\n '"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'},\n # The trailing null value for Fortran is blank.\n {l_and(isintent_out, l_not(isintent_c)):\n " STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"},\n ],\n 'return': {isintent_out: ',#varname#'},\n 'need': ['len..',\n {l_and(isintent_out, l_not(isintent_c)): 'STRINGPADN'}],\n '_check': isstring\n }, { # Common\n 'frompyobj': [\n """\\n slen(#varname#) = #elsize#;\n f2py_success = #ctype#_from_pyobj(&#varname#,&slen(#varname#),#init#,"""\n"""#varname#_capi,\"#ctype#_from_pyobj failed in converting #nth#"""\n"""`#varname#\' of #pyname# to C #ctype#\");\n if (f2py_success) {""",\n # The trailing null value for Fortran is blank.\n {l_not(isintent_c):\n " STRINGPADN(#varname#, slen(#varname#), '\\0', ' ');"},\n ],\n 'cleanupfrompyobj': """\\n STRINGFREE(#varname#);\n } /*if (f2py_success) of #varname#*/""",\n 'need': ['#ctype#_from_pyobj', 'len..', 'STRINGFREE',\n {l_not(isintent_c): 'STRINGPADN'}],\n '_check': isstring,\n '_depend': ''\n }, { # Not hidden\n 'argformat': {isrequired: 'O'},\n 'keyformat': {isoptional: 'O'},\n 'args_capi': {isrequired: ',&#varname#_capi'},\n 'keys_capi': {isoptional: ',&#varname#_capi'},\n 'pyobjfrom': [\n {l_and(isintent_inout, l_not(isintent_c)):\n " STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"},\n {isintent_inout: '''\\n f2py_success = try_pyarr_from_#ctype#(#varname#_capi, #varname#,\n slen(#varname#));\n if (f2py_success) {'''}],\n 'closepyobjfrom': {isintent_inout: ' } /*if (f2py_success) of #varname# pyobjfrom*/'},\n 'need': {isintent_inout: 'try_pyarr_from_#ctype#',\n l_and(isintent_inout, l_not(isintent_c)): 'STRINGPADN'},\n '_check': l_and(isstring, isintent_nothide)\n }, { # Hidden\n '_check': l_and(isstring, isintent_hide)\n }, {\n 'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'},\n '_check': isstring,\n '_depend': ''\n },\n # Array\n { # Common\n 'decl': [' #ctype# *#varname# = NULL;',\n ' npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};',\n ' const int #varname#_Rank = #rank#;',\n ' PyArrayObject *capi_#varname#_as_array = NULL;',\n ' int capi_#varname#_intent = 0;',\n {isstringarray: ' int slen(#varname#) = 0;'},\n ],\n 'callfortran': '#varname#,',\n 'callfortranappend': {isstringarray: 'slen(#varname#),'},\n 'return': {isintent_out: ',capi_#varname#_as_array'},\n 'need': 'len..',\n '_check': isarray\n }, { # intent(overwrite) array\n 'decl': ' int capi_overwrite_#varname# = 1;',\n 'kwlistxa': '"overwrite_#varname#",',\n 'xaformat': 'i',\n 'keys_xa': ',&capi_overwrite_#varname#',\n 'docsignxa': 'overwrite_#varname#=1,',\n 'docsignxashort': 'overwrite_#varname#,',\n 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 1',\n '_check': l_and(isarray, isintent_overwrite),\n }, {\n 'frompyobj': ' capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);',\n '_check': l_and(isarray, isintent_overwrite),\n '_depend': '',\n },\n { # intent(copy) array\n 'decl': ' int capi_overwrite_#varname# = 0;',\n 'kwlistxa': '"overwrite_#varname#",',\n 'xaformat': 'i',\n 'keys_xa': ',&capi_overwrite_#varname#',\n 'docsignxa': 'overwrite_#varname#=0,',\n 'docsignxashort': 'overwrite_#varname#,',\n 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 0',\n '_check': l_and(isarray, isintent_copy),\n }, {\n 'frompyobj': ' capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);',\n '_check': l_and(isarray, isintent_copy),\n '_depend': '',\n }, {\n 'need': [{hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}],\n '_check': isarray,\n '_depend': ''\n }, { # Not hidden\n 'decl': ' PyObject *#varname#_capi = Py_None;',\n 'argformat': {isrequired: 'O'},\n 'keyformat': {isoptional: 'O'},\n 'args_capi': {isrequired: ',&#varname#_capi'},\n 'keys_capi': {isoptional: ',&#varname#_capi'},\n '_check': l_and(isarray, isintent_nothide)\n }, {\n 'frompyobj': [\n ' #setdims#;',\n ' capi_#varname#_intent |= #intent#;',\n (' const char capi_errmess[] = "#modulename#.#pyname#:'\n ' failed to create array from the #nth# `#varname#`";'),\n {isintent_hide:\n ' capi_#varname#_as_array = ndarray_from_pyobj('\n ' #atype#,#elsize#,#varname#_Dims,#varname#_Rank,'\n ' capi_#varname#_intent,Py_None,capi_errmess);'},\n {isintent_nothide:\n ' capi_#varname#_as_array = ndarray_from_pyobj('\n ' #atype#,#elsize#,#varname#_Dims,#varname#_Rank,'\n ' capi_#varname#_intent,#varname#_capi,capi_errmess);'},\n """\\n 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""",\n {isstringarray:\n ' slen(#varname#) = f2py_itemsize(#varname#);'},\n {hasinitvalue: [\n {isintent_nothide:\n ' if (#varname#_capi == Py_None) {'},\n {isintent_hide: ' {'},\n {iscomplexarray: ' #ctype# capi_c;'},\n """\\n int *_i,capi_i=0;\n CFUNCSMESS(\"#name#: Initializing #varname#=#init#\\n\");\n struct ForcombCache cache;\n if (initforcomb(&cache, PyArray_DIMS(capi_#varname#_as_array),\n PyArray_NDIM(capi_#varname#_as_array),1)) {\n while ((_i = nextforcomb(&cache)))\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) {"""]},\n ],\n 'cleanupfrompyobj': [ # note that this list will be reversed\n ' } '\n '/* if (capi_#varname#_as_array == NULL) ... else of #varname# */',\n {l_not(l_or(isintent_out, isintent_hide)): """\\n if((PyObject *)capi_#varname#_as_array!=#varname#_capi) {\n Py_XDECREF(capi_#varname#_as_array); }"""},\n {l_and(isintent_hide, l_not(isintent_out))\n : """ Py_XDECREF(capi_#varname#_as_array);"""},\n {hasinitvalue: ' } /*if (f2py_success) of #varname# init*/'},\n ],\n '_check': isarray,\n '_depend': ''\n },\n # Scalararray\n { # Common\n '_check': l_and(isarray, l_not(iscomplexarray))\n }, { # Not hidden\n '_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide)\n },\n # Integer*1 array\n {'need': '#ctype#',\n '_check': isint1array,\n '_depend': ''\n },\n # Integer*-1 array\n {'need': '#ctype#',\n '_check': isunsigned_chararray,\n '_depend': ''\n },\n # Integer*-2 array\n {'need': '#ctype#',\n '_check': isunsigned_shortarray,\n '_depend': ''\n },\n # Integer*-8 array\n {'need': '#ctype#',\n '_check': isunsigned_long_longarray,\n '_depend': ''\n },\n # Complexarray\n {'need': '#ctype#',\n '_check': iscomplexarray,\n '_depend': ''\n },\n # Character\n {\n 'need': 'string',\n '_check': ischaracter,\n },\n # Character array\n {\n 'need': 'string',\n '_check': ischaracterarray,\n },\n # Stringarray\n {\n 'callfortranappend': {isarrayofstrings: 'flen(#varname#),'},\n 'need': 'string',\n '_check': isstringarray\n }\n]\n\n################# Rules for checking ###############\n\ncheck_rules = [\n {\n 'frompyobj': {debugcapi: ' fprintf(stderr,\"debug-capi:Checking `#check#\'\\n\");'},\n 'need': 'len..'\n }, {\n 'frompyobj': ' CHECKSCALAR(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {',\n 'cleanupfrompyobj': ' } /*CHECKSCALAR(#check#)*/',\n 'need': 'CHECKSCALAR',\n '_check': l_and(isscalar, l_not(iscomplex)),\n '_break': ''\n }, {\n 'frompyobj': ' CHECKSTRING(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {',\n 'cleanupfrompyobj': ' } /*CHECKSTRING(#check#)*/',\n 'need': 'CHECKSTRING',\n '_check': isstring,\n '_break': ''\n }, {\n 'need': 'CHECKARRAY',\n 'frompyobj': ' CHECKARRAY(#check#,\"#check#\",\"#nth# #varname#\") {',\n 'cleanupfrompyobj': ' } /*CHECKARRAY(#check#)*/',\n '_check': isarray,\n '_break': ''\n }, {\n 'need': 'CHECKGENERIC',\n 'frompyobj': ' CHECKGENERIC(#check#,\"#check#\",\"#nth# #varname#\") {',\n 'cleanupfrompyobj': ' } /*CHECKGENERIC(#check#)*/',\n }\n]\n\n########## Applying the rules. No need to modify what follows #############\n\n#################### Build C/API module #######################\n\n\ndef buildmodule(m, um):\n """\n Return\n """\n outmess(f" Building module \"{m['name']}\"...\n")\n ret = {}\n mod_rules = defmod_rules[:]\n vrd = capi_maps.modsign2map(m)\n rd = dictappend({'f2py_version': f2py_version}, vrd)\n funcwrappers = []\n funcwrappers2 = [] # F90 codes\n for n in m['interfaced']:\n nb = None\n for bi in m['body']:\n if bi['block'] not in ['interface', 'abstract interface']:\n errmess('buildmodule: Expected interface block. Skipping.\n')\n continue\n for b in bi['body']:\n if b['name'] == n:\n nb = b\n break\n\n if not nb:\n print(\n f'buildmodule: Could not find the body of interfaced routine "{n}". Skipping.\n', file=sys.stderr)\n continue\n nb_list = [nb]\n if 'entry' in nb:\n for k, a in nb['entry'].items():\n nb1 = copy.deepcopy(nb)\n del nb1['entry']\n nb1['name'] = k\n nb1['args'] = a\n nb_list.append(nb1)\n for nb in nb_list:\n # requiresf90wrapper must be called before buildapi as it\n # rewrites assumed shape arrays as automatic arrays.\n isf90 = requiresf90wrapper(nb)\n # options is in scope here\n if options['emptygen']:\n b_path = options['buildpath']\n m_name = vrd['modulename']\n outmess(' Generating possibly empty wrappers"\n')\n Path(f"{b_path}/{vrd['coutput']}").touch()\n if isf90:\n # f77 + f90 wrappers\n outmess(f' Maybe empty "{m_name}-f2pywrappers2.f90"\n')\n Path(f'{b_path}/{m_name}-f2pywrappers2.f90').touch()\n outmess(f' Maybe empty "{m_name}-f2pywrappers.f"\n')\n Path(f'{b_path}/{m_name}-f2pywrappers.f').touch()\n else:\n # only f77 wrappers\n outmess(f' Maybe empty "{m_name}-f2pywrappers.f"\n')\n Path(f'{b_path}/{m_name}-f2pywrappers.f').touch()\n api, wrap = buildapi(nb)\n if wrap:\n if isf90:\n funcwrappers2.append(wrap)\n else:\n funcwrappers.append(wrap)\n ar = applyrules(api, vrd)\n rd = dictappend(rd, ar)\n\n # Construct COMMON block support\n cr, wrap = common_rules.buildhooks(m)\n if wrap:\n funcwrappers.append(wrap)\n ar = applyrules(cr, vrd)\n rd = dictappend(rd, ar)\n\n # Construct F90 module support\n mr, wrap = f90mod_rules.buildhooks(m)\n if wrap:\n funcwrappers2.append(wrap)\n ar = applyrules(mr, vrd)\n rd = dictappend(rd, ar)\n\n for u in um:\n ar = use_rules.buildusevars(u, m['use'][u['name']])\n rd = dictappend(rd, ar)\n\n needs = cfuncs.get_needs()\n # Add mapped definitions\n needs['typedefs'] += [cvar for cvar in capi_maps.f2cmap_mapped #\n if cvar in typedef_need_dict.values()]\n code = {}\n for n in needs.keys():\n code[n] = []\n for k in needs[n]:\n c = ''\n if k in cfuncs.includes0:\n c = cfuncs.includes0[k]\n elif k in cfuncs.includes:\n c = cfuncs.includes[k]\n elif k in cfuncs.userincludes:\n c = cfuncs.userincludes[k]\n elif k in cfuncs.typedefs:\n c = cfuncs.typedefs[k]\n elif k in cfuncs.typedefs_generated:\n c = cfuncs.typedefs_generated[k]\n elif k in cfuncs.cppmacros:\n c = cfuncs.cppmacros[k]\n elif k in cfuncs.cfuncs:\n c = cfuncs.cfuncs[k]\n elif k in cfuncs.callbacks:\n c = cfuncs.callbacks[k]\n elif k in cfuncs.f90modhooks:\n c = cfuncs.f90modhooks[k]\n elif k in cfuncs.commonhooks:\n c = cfuncs.commonhooks[k]\n else:\n errmess(f'buildmodule: unknown need {repr(k)}.\n')\n continue\n code[n].append(c)\n mod_rules.append(code)\n for r in mod_rules:\n if ('_check' in r and r['_check'](m)) or ('_check' not in r):\n ar = applyrules(r, vrd, m)\n rd = dictappend(rd, ar)\n ar = applyrules(module_rules, rd)\n\n fn = os.path.join(options['buildpath'], vrd['coutput'])\n ret['csrc'] = fn\n with open(fn, 'w') as f:\n f.write(ar['modulebody'].replace('\t', 2 * ' '))\n outmess(f" Wrote C/API module \"{m['name']}\" to file \"{fn}\"\n")\n\n if options['dorestdoc']:\n fn = os.path.join(\n options['buildpath'], vrd['modulename'] + 'module.rest')\n with open(fn, 'w') as f:\n f.write('.. -*- rest -*-\n')\n f.write('\n'.join(ar['restdoc']))\n outmess(' ReST Documentation is saved to file "%s/%smodule.rest"\n' %\n (options['buildpath'], vrd['modulename']))\n if options['dolatexdoc']:\n fn = os.path.join(\n options['buildpath'], vrd['modulename'] + 'module.tex')\n ret['ltx'] = fn\n with open(fn, 'w') as f:\n f.write(\n f'% This file is auto-generated with f2py (version:{f2py_version})\n')\n if 'shortlatex' not in options:\n f.write(\n '\\documentclass{article}\n\\usepackage{a4wide}\n\\begin{document}\n\\tableofcontents\n\n')\n f.write('\n'.join(ar['latexdoc']))\n if 'shortlatex' not in options:\n f.write('\\end{document}')\n outmess(' Documentation is saved to file "%s/%smodule.tex"\n' %\n (options['buildpath'], vrd['modulename']))\n if funcwrappers:\n wn = os.path.join(options['buildpath'], vrd['f2py_wrapper_output'])\n ret['fsrc'] = wn\n with open(wn, 'w') as f:\n f.write('C -*- fortran -*-\n')\n f.write(\n f'C This file is autogenerated with f2py (version:{f2py_version})\n')\n f.write(\n 'C It contains Fortran 77 wrappers to fortran functions.\n')\n lines = []\n for l in ('\n\n'.join(funcwrappers) + '\n').split('\n'):\n if 0 <= l.find('!') < 66:\n # don't split comment lines\n lines.append(l + '\n')\n elif l and l[0] == ' ':\n while len(l) >= 66:\n lines.append(l[:66] + '\n &')\n l = l[66:]\n lines.append(l + '\n')\n else:\n lines.append(l + '\n')\n lines = ''.join(lines).replace('\n &\n', '\n')\n f.write(lines)\n outmess(f' Fortran 77 wrappers are saved to "{wn}\"\n')\n if funcwrappers2:\n wn = os.path.join(\n options['buildpath'], f"{vrd['modulename']}-f2pywrappers2.f90")\n ret['fsrc'] = wn\n with open(wn, 'w') as f:\n f.write('! -*- f90 -*-\n')\n f.write(\n f'! This file is autogenerated with f2py (version:{f2py_version})\n')\n f.write(\n '! It contains Fortran 90 wrappers to fortran functions.\n')\n lines = []\n for l in ('\n\n'.join(funcwrappers2) + '\n').split('\n'):\n if 0 <= l.find('!') < 72:\n # don't split comment lines\n lines.append(l + '\n')\n elif len(l) > 72 and l[0] == ' ':\n lines.append(l[:72] + '&\n &')\n l = l[72:]\n while len(l) > 66:\n lines.append(l[:66] + '&\n &')\n l = l[66:]\n lines.append(l + '\n')\n else:\n lines.append(l + '\n')\n lines = ''.join(lines).replace('\n &\n', '\n')\n f.write(lines)\n outmess(f' Fortran 90 wrappers are saved to "{wn}\"\n')\n return ret\n\n################## Build C/API function #############\n\n\nstnd = {1: 'st', 2: 'nd', 3: 'rd', 4: 'th', 5: 'th',\n 6: 'th', 7: 'th', 8: 'th', 9: 'th', 0: 'th'}\n\n\ndef buildapi(rout):\n rout, wrap = func2subr.assubr(rout)\n args, depargs = getargs2(rout)\n capi_maps.depargs = depargs\n var = rout['vars']\n\n if ismoduleroutine(rout):\n outmess(' Constructing wrapper function "%s.%s"...\n' %\n (rout['modulename'], rout['name']))\n else:\n outmess(f" Constructing wrapper function \"{rout['name']}\"...\n")\n # Routine\n vrd = capi_maps.routsign2map(rout)\n rd = dictappend({}, vrd)\n for r in rout_rules:\n if ('_check' in r and r['_check'](rout)) or ('_check' not in r):\n ar = applyrules(r, vrd, rout)\n rd = dictappend(rd, ar)\n\n # Args\n nth, nthk = 0, 0\n savevrd = {}\n for a in args:\n vrd = capi_maps.sign2map(a, var[a])\n if isintent_aux(var[a]):\n _rules = aux_rules\n else:\n _rules = arg_rules\n if not isintent_hide(var[a]):\n if not isoptional(var[a]):\n nth = nth + 1\n vrd['nth'] = repr(nth) + stnd[nth % 10] + ' argument'\n else:\n nthk = nthk + 1\n vrd['nth'] = repr(nthk) + stnd[nthk % 10] + ' keyword'\n else:\n vrd['nth'] = 'hidden'\n savevrd[a] = vrd\n for r in _rules:\n if '_depend' in r:\n continue\n if ('_check' in r and r['_check'](var[a])) or ('_check' not in r):\n ar = applyrules(r, vrd, var[a])\n rd = dictappend(rd, ar)\n if '_break' in r:\n break\n for a in depargs:\n if isintent_aux(var[a]):\n _rules = aux_rules\n else:\n _rules = arg_rules\n vrd = savevrd[a]\n for r in _rules:\n if '_depend' not in r:\n continue\n if ('_check' in r and r['_check'](var[a])) or ('_check' not in r):\n ar = applyrules(r, vrd, var[a])\n rd = dictappend(rd, ar)\n if '_break' in r:\n break\n if 'check' in var[a]:\n for c in var[a]['check']:\n vrd['check'] = c\n ar = applyrules(check_rules, vrd, var[a])\n rd = dictappend(rd, ar)\n if isinstance(rd['cleanupfrompyobj'], list):\n rd['cleanupfrompyobj'].reverse()\n if isinstance(rd['closepyobjfrom'], list):\n rd['closepyobjfrom'].reverse()\n rd['docsignature'] = stripcomma(replace('#docsign##docsignopt##docsignxa#',\n {'docsign': rd['docsign'],\n 'docsignopt': rd['docsignopt'],\n 'docsignxa': rd['docsignxa']}))\n optargs = stripcomma(replace('#docsignopt##docsignxa#',\n {'docsignxa': rd['docsignxashort'],\n 'docsignopt': rd['docsignoptshort']}\n ))\n if optargs == '':\n rd['docsignatureshort'] = stripcomma(\n replace('#docsign#', {'docsign': rd['docsign']}))\n else:\n rd['docsignatureshort'] = replace('#docsign#[#docsignopt#]',\n {'docsign': rd['docsign'],\n 'docsignopt': optargs,\n })\n rd['latexdocsignatureshort'] = rd['docsignatureshort'].replace('_', '\\_')\n rd['latexdocsignatureshort'] = rd[\n 'latexdocsignatureshort'].replace(',', ', ')\n cfs = stripcomma(replace('#callfortran##callfortranappend#', {\n 'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']}))\n if len(rd['callfortranappend']) > 1:\n rd['callcompaqfortran'] = stripcomma(replace('#callfortran# 0,#callfortranappend#', {\n 'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']}))\n else:\n rd['callcompaqfortran'] = cfs\n rd['callfortran'] = cfs\n if isinstance(rd['docreturn'], list):\n rd['docreturn'] = stripcomma(\n replace('#docreturn#', {'docreturn': rd['docreturn']})) + ' = '\n rd['docstrsigns'] = []\n rd['latexdocstrsigns'] = []\n for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']:\n if k in rd and isinstance(rd[k], list):\n rd['docstrsigns'] = rd['docstrsigns'] + rd[k]\n k = 'latex' + k\n if k in rd and isinstance(rd[k], list):\n rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] +\\n ['\\begin{description}'] + rd[k][1:] +\\n ['\\end{description}']\n\n ar = applyrules(routine_rules, rd)\n if ismoduleroutine(rout):\n outmess(f" {ar['docshort']}\n")\n else:\n outmess(f" {ar['docshort']}\n")\n return ar, wrap\n\n\n#################### EOF rules.py #######################\n
.venv\Lib\site-packages\numpy\f2py\rules.py
rules.py
Python
64,720
0.75
0.096992
0.106796
awesome-app
816
2024-08-09T12:44:55.992676
BSD-3-Clause
false
96c1b295cf7a91c1782d8aa132550968
from collections.abc import Callable, Iterable, Mapping\nfrom typing import Any, Final, TypeAlias\nfrom typing import Literal as L\n\nfrom typing_extensions import TypeVar\n\nfrom .__version__ import version\nfrom .auxfuncs import _Bool, _Var\n\n###\n\n_VT = TypeVar("_VT", default=str)\n\n_Predicate: TypeAlias = Callable[[_Var], _Bool]\n_RuleDict: TypeAlias = dict[str, _VT]\n_DefDict: TypeAlias = dict[_Predicate, _VT]\n\n###\n\nf2py_version: Final = version\nnumpy_version: Final = version\n\noptions: Final[dict[str, bool]] = ...\nsepdict: Final[dict[str, str]] = ...\n\ngenerationtime: Final[int] = ...\ntypedef_need_dict: Final[_DefDict[str]] = ...\n\nmodule_rules: Final[_RuleDict[str | list[str] | _RuleDict]] = ...\nroutine_rules: Final[_RuleDict[str | list[str] | _DefDict | _RuleDict]] = ...\ndefmod_rules: Final[list[_RuleDict[str | _DefDict]]] = ...\nrout_rules: Final[list[_RuleDict[str | Any]]] = ...\naux_rules: Final[list[_RuleDict[str | Any]]] = ...\narg_rules: Final[list[_RuleDict[str | Any]]] = ...\ncheck_rules: Final[list[_RuleDict[str | Any]]] = ...\n\nstnd: Final[dict[L[1, 2, 3, 4, 5, 6, 7, 8, 9, 0], L["st", "nd", "rd", "th"]]] = ...\n\ndef buildmodule(m: Mapping[str, str | Any], um: Iterable[Mapping[str, str | Any]]) -> _RuleDict: ...\ndef buildapi(rout: Mapping[str, str]) -> tuple[_RuleDict, str]: ...\n\n# namespace pollution\nk: str\n
.venv\Lib\site-packages\numpy\f2py\rules.pyi
rules.pyi
Other
1,369
0.95
0.046512
0.1
python-kit
126
2025-02-01T14:37:29.436244
GPL-3.0
false
197c1bbc52d318cdec3423399a39bb23
[bdist_rpm]\ndoc_files = docs/\n tests/
.venv\Lib\site-packages\numpy\f2py\setup.cfg
setup.cfg
Other
50
0.5
0
0
node-utils
46
2024-03-03T01:02:31.402896
MIT
false
e48436bd49630be0e8098dbcecbeea4c
"""Fortran/C symbolic expressions\n\nReferences:\n- J3/21-007: Draft Fortran 202x. https://j3-fortran.org/doc/year/21/21-007.pdf\n\nCopyright 1999 -- 2011 Pearu Peterson all rights reserved.\nCopyright 2011 -- present NumPy Developers.\nPermission to use, modify, and distribute this software is given under the\nterms of the NumPy License.\n\nNO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n"""\n\n# To analyze Fortran expressions to solve dimensions specifications,\n# for instances, we implement a minimal symbolic engine for parsing\n# expressions into a tree of expression instances. As a first\n# instance, we care only about arithmetic expressions involving\n# integers and operations like addition (+), subtraction (-),\n# multiplication (*), division (Fortran / is Python //, Fortran // is\n# concatenate), and exponentiation (**). In addition, .pyf files may\n# contain C expressions that support here is implemented as well.\n#\n# TODO: support logical constants (Op.BOOLEAN)\n# TODO: support logical operators (.AND., ...)\n# TODO: support defined operators (.MYOP., ...)\n#\n__all__ = ['Expr']\n\n\nimport re\nimport warnings\nfrom enum import Enum\nfrom math import gcd\n\n\nclass Language(Enum):\n """\n Used as Expr.tostring language argument.\n """\n Python = 0\n Fortran = 1\n C = 2\n\n\nclass Op(Enum):\n """\n Used as Expr op attribute.\n """\n INTEGER = 10\n REAL = 12\n COMPLEX = 15\n STRING = 20\n ARRAY = 30\n SYMBOL = 40\n TERNARY = 100\n APPLY = 200\n INDEXING = 210\n CONCAT = 220\n RELATIONAL = 300\n TERMS = 1000\n FACTORS = 2000\n REF = 3000\n DEREF = 3001\n\n\nclass RelOp(Enum):\n """\n Used in Op.RELATIONAL expression to specify the function part.\n """\n EQ = 1\n NE = 2\n LT = 3\n LE = 4\n GT = 5\n GE = 6\n\n @classmethod\n def fromstring(cls, s, language=Language.C):\n if language is Language.Fortran:\n return {'.eq.': RelOp.EQ, '.ne.': RelOp.NE,\n '.lt.': RelOp.LT, '.le.': RelOp.LE,\n '.gt.': RelOp.GT, '.ge.': RelOp.GE}[s.lower()]\n return {'==': RelOp.EQ, '!=': RelOp.NE, '<': RelOp.LT,\n '<=': RelOp.LE, '>': RelOp.GT, '>=': RelOp.GE}[s]\n\n def tostring(self, language=Language.C):\n if language is Language.Fortran:\n return {RelOp.EQ: '.eq.', RelOp.NE: '.ne.',\n RelOp.LT: '.lt.', RelOp.LE: '.le.',\n RelOp.GT: '.gt.', RelOp.GE: '.ge.'}[self]\n return {RelOp.EQ: '==', RelOp.NE: '!=',\n RelOp.LT: '<', RelOp.LE: '<=',\n RelOp.GT: '>', RelOp.GE: '>='}[self]\n\n\nclass ArithOp(Enum):\n """\n Used in Op.APPLY expression to specify the function part.\n """\n POS = 1\n NEG = 2\n ADD = 3\n SUB = 4\n MUL = 5\n DIV = 6\n POW = 7\n\n\nclass OpError(Exception):\n pass\n\n\nclass Precedence(Enum):\n """\n Used as Expr.tostring precedence argument.\n """\n ATOM = 0\n POWER = 1\n UNARY = 2\n PRODUCT = 3\n SUM = 4\n LT = 6\n EQ = 7\n LAND = 11\n LOR = 12\n TERNARY = 13\n ASSIGN = 14\n TUPLE = 15\n NONE = 100\n\n\ninteger_types = (int,)\nnumber_types = (int, float)\n\n\ndef _pairs_add(d, k, v):\n # Internal utility method for updating terms and factors data.\n c = d.get(k)\n if c is None:\n d[k] = v\n else:\n c = c + v\n if c:\n d[k] = c\n else:\n del d[k]\n\n\nclass ExprWarning(UserWarning):\n pass\n\n\ndef ewarn(message):\n warnings.warn(message, ExprWarning, stacklevel=2)\n\n\nclass Expr:\n """Represents a Fortran expression as a op-data pair.\n\n Expr instances are hashable and sortable.\n """\n\n @staticmethod\n def parse(s, language=Language.C):\n """Parse a Fortran expression to a Expr.\n """\n return fromstring(s, language=language)\n\n def __init__(self, op, data):\n assert isinstance(op, Op)\n\n # sanity checks\n if op is Op.INTEGER:\n # data is a 2-tuple of numeric object and a kind value\n # (default is 4)\n assert isinstance(data, tuple) and len(data) == 2\n assert isinstance(data[0], int)\n assert isinstance(data[1], (int, str)), data\n elif op is Op.REAL:\n # data is a 2-tuple of numeric object and a kind value\n # (default is 4)\n assert isinstance(data, tuple) and len(data) == 2\n assert isinstance(data[0], float)\n assert isinstance(data[1], (int, str)), data\n elif op is Op.COMPLEX:\n # data is a 2-tuple of constant expressions\n assert isinstance(data, tuple) and len(data) == 2\n elif op is Op.STRING:\n # data is a 2-tuple of quoted string and a kind value\n # (default is 1)\n assert isinstance(data, tuple) and len(data) == 2\n assert (isinstance(data[0], str)\n and data[0][::len(data[0]) - 1] in ('""', "''", '@@'))\n assert isinstance(data[1], (int, str)), data\n elif op is Op.SYMBOL:\n # data is any hashable object\n assert hash(data) is not None\n elif op in (Op.ARRAY, Op.CONCAT):\n # data is a tuple of expressions\n assert isinstance(data, tuple)\n assert all(isinstance(item, Expr) for item in data), data\n elif op in (Op.TERMS, Op.FACTORS):\n # data is {<term|base>:<coeff|exponent>} where dict values\n # are nonzero Python integers\n assert isinstance(data, dict)\n elif op is Op.APPLY:\n # data is (<function>, <operands>, <kwoperands>) where\n # operands are Expr instances\n assert isinstance(data, tuple) and len(data) == 3\n # function is any hashable object\n assert hash(data[0]) is not None\n assert isinstance(data[1], tuple)\n assert isinstance(data[2], dict)\n elif op is Op.INDEXING:\n # data is (<object>, <indices>)\n assert isinstance(data, tuple) and len(data) == 2\n # function is any hashable object\n assert hash(data[0]) is not None\n elif op is Op.TERNARY:\n # data is (<cond>, <expr1>, <expr2>)\n assert isinstance(data, tuple) and len(data) == 3\n elif op in (Op.REF, Op.DEREF):\n # data is Expr instance\n assert isinstance(data, Expr)\n elif op is Op.RELATIONAL:\n # data is (<relop>, <left>, <right>)\n assert isinstance(data, tuple) and len(data) == 3\n else:\n raise NotImplementedError(\n f'unknown op or missing sanity check: {op}')\n\n self.op = op\n self.data = data\n\n def __eq__(self, other):\n return (isinstance(other, Expr)\n and self.op is other.op\n and self.data == other.data)\n\n def __hash__(self):\n if self.op in (Op.TERMS, Op.FACTORS):\n data = tuple(sorted(self.data.items()))\n elif self.op is Op.APPLY:\n data = self.data[:2] + tuple(sorted(self.data[2].items()))\n else:\n data = self.data\n return hash((self.op, data))\n\n def __lt__(self, other):\n if isinstance(other, Expr):\n if self.op is not other.op:\n return self.op.value < other.op.value\n if self.op in (Op.TERMS, Op.FACTORS):\n return (tuple(sorted(self.data.items()))\n < tuple(sorted(other.data.items())))\n if self.op is Op.APPLY:\n if self.data[:2] != other.data[:2]:\n return self.data[:2] < other.data[:2]\n return tuple(sorted(self.data[2].items())) < tuple(\n sorted(other.data[2].items()))\n return self.data < other.data\n return NotImplemented\n\n def __le__(self, other): return self == other or self < other\n\n def __gt__(self, other): return not (self <= other)\n\n def __ge__(self, other): return not (self < other)\n\n def __repr__(self):\n return f'{type(self).__name__}({self.op}, {self.data!r})'\n\n def __str__(self):\n return self.tostring()\n\n def tostring(self, parent_precedence=Precedence.NONE,\n language=Language.Fortran):\n """Return a string representation of Expr.\n """\n if self.op in (Op.INTEGER, Op.REAL):\n precedence = (Precedence.SUM if self.data[0] < 0\n else Precedence.ATOM)\n r = str(self.data[0]) + (f'_{self.data[1]}'\n if self.data[1] != 4 else '')\n elif self.op is Op.COMPLEX:\n r = ', '.join(item.tostring(Precedence.TUPLE, language=language)\n for item in self.data)\n r = '(' + r + ')'\n precedence = Precedence.ATOM\n elif self.op is Op.SYMBOL:\n precedence = Precedence.ATOM\n r = str(self.data)\n elif self.op is Op.STRING:\n r = self.data[0]\n if self.data[1] != 1:\n r = self.data[1] + '_' + r\n precedence = Precedence.ATOM\n elif self.op is Op.ARRAY:\n r = ', '.join(item.tostring(Precedence.TUPLE, language=language)\n for item in self.data)\n r = '[' + r + ']'\n precedence = Precedence.ATOM\n elif self.op is Op.TERMS:\n terms = []\n for term, coeff in sorted(self.data.items()):\n if coeff < 0:\n op = ' - '\n coeff = -coeff\n else:\n op = ' + '\n if coeff == 1:\n term = term.tostring(Precedence.SUM, language=language)\n elif term == as_number(1):\n term = str(coeff)\n else:\n term = f'{coeff} * ' + term.tostring(\n Precedence.PRODUCT, language=language)\n if terms:\n terms.append(op)\n elif op == ' - ':\n terms.append('-')\n terms.append(term)\n r = ''.join(terms) or '0'\n precedence = Precedence.SUM if terms else Precedence.ATOM\n elif self.op is Op.FACTORS:\n factors = []\n tail = []\n for base, exp in sorted(self.data.items()):\n op = ' * '\n if exp == 1:\n factor = base.tostring(Precedence.PRODUCT,\n language=language)\n elif language is Language.C:\n if exp in range(2, 10):\n factor = base.tostring(Precedence.PRODUCT,\n language=language)\n factor = ' * '.join([factor] * exp)\n elif exp in range(-10, 0):\n factor = base.tostring(Precedence.PRODUCT,\n language=language)\n tail += [factor] * -exp\n continue\n else:\n factor = base.tostring(Precedence.TUPLE,\n language=language)\n factor = f'pow({factor}, {exp})'\n else:\n factor = base.tostring(Precedence.POWER,\n language=language) + f' ** {exp}'\n if factors:\n factors.append(op)\n factors.append(factor)\n if tail:\n if not factors:\n factors += ['1']\n factors += ['/', '(', ' * '.join(tail), ')']\n r = ''.join(factors) or '1'\n precedence = Precedence.PRODUCT if factors else Precedence.ATOM\n elif self.op is Op.APPLY:\n name, args, kwargs = self.data\n if name is ArithOp.DIV and language is Language.C:\n numer, denom = [arg.tostring(Precedence.PRODUCT,\n language=language)\n for arg in args]\n r = f'{numer} / {denom}'\n precedence = Precedence.PRODUCT\n else:\n args = [arg.tostring(Precedence.TUPLE, language=language)\n for arg in args]\n args += [k + '=' + v.tostring(Precedence.NONE)\n for k, v in kwargs.items()]\n r = f'{name}({", ".join(args)})'\n precedence = Precedence.ATOM\n elif self.op is Op.INDEXING:\n name = self.data[0]\n args = [arg.tostring(Precedence.TUPLE, language=language)\n for arg in self.data[1:]]\n r = f'{name}[{", ".join(args)}]'\n precedence = Precedence.ATOM\n elif self.op is Op.CONCAT:\n args = [arg.tostring(Precedence.PRODUCT, language=language)\n for arg in self.data]\n r = " // ".join(args)\n precedence = Precedence.PRODUCT\n elif self.op is Op.TERNARY:\n cond, expr1, expr2 = [a.tostring(Precedence.TUPLE,\n language=language)\n for a in self.data]\n if language is Language.C:\n r = f'({cond}?{expr1}:{expr2})'\n elif language is Language.Python:\n r = f'({expr1} if {cond} else {expr2})'\n elif language is Language.Fortran:\n r = f'merge({expr1}, {expr2}, {cond})'\n else:\n raise NotImplementedError(\n f'tostring for {self.op} and {language}')\n precedence = Precedence.ATOM\n elif self.op is Op.REF:\n r = '&' + self.data.tostring(Precedence.UNARY, language=language)\n precedence = Precedence.UNARY\n elif self.op is Op.DEREF:\n r = '*' + self.data.tostring(Precedence.UNARY, language=language)\n precedence = Precedence.UNARY\n elif self.op is Op.RELATIONAL:\n rop, left, right = self.data\n precedence = (Precedence.EQ if rop in (RelOp.EQ, RelOp.NE)\n else Precedence.LT)\n left = left.tostring(precedence, language=language)\n right = right.tostring(precedence, language=language)\n rop = rop.tostring(language=language)\n r = f'{left} {rop} {right}'\n else:\n raise NotImplementedError(f'tostring for op {self.op}')\n if parent_precedence.value < precedence.value:\n # If parent precedence is higher than operand precedence,\n # operand will be enclosed in parenthesis.\n return '(' + r + ')'\n return r\n\n def __pos__(self):\n return self\n\n def __neg__(self):\n return self * -1\n\n def __add__(self, other):\n other = as_expr(other)\n if isinstance(other, Expr):\n if self.op is other.op:\n if self.op in (Op.INTEGER, Op.REAL):\n return as_number(\n self.data[0] + other.data[0],\n max(self.data[1], other.data[1]))\n if self.op is Op.COMPLEX:\n r1, i1 = self.data\n r2, i2 = other.data\n return as_complex(r1 + r2, i1 + i2)\n if self.op is Op.TERMS:\n r = Expr(self.op, dict(self.data))\n for k, v in other.data.items():\n _pairs_add(r.data, k, v)\n return normalize(r)\n if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL):\n return self + as_complex(other)\n elif self.op in (Op.INTEGER, Op.REAL) and other.op is Op.COMPLEX:\n return as_complex(self) + other\n elif self.op is Op.REAL and other.op is Op.INTEGER:\n return self + as_real(other, kind=self.data[1])\n elif self.op is Op.INTEGER and other.op is Op.REAL:\n return as_real(self, kind=other.data[1]) + other\n return as_terms(self) + as_terms(other)\n return NotImplemented\n\n def __radd__(self, other):\n if isinstance(other, number_types):\n return as_number(other) + self\n return NotImplemented\n\n def __sub__(self, other):\n return self + (-other)\n\n def __rsub__(self, other):\n if isinstance(other, number_types):\n return as_number(other) - self\n return NotImplemented\n\n def __mul__(self, other):\n other = as_expr(other)\n if isinstance(other, Expr):\n if self.op is other.op:\n if self.op in (Op.INTEGER, Op.REAL):\n return as_number(self.data[0] * other.data[0],\n max(self.data[1], other.data[1]))\n elif self.op is Op.COMPLEX:\n r1, i1 = self.data\n r2, i2 = other.data\n return as_complex(r1 * r2 - i1 * i2, r1 * i2 + r2 * i1)\n\n if self.op is Op.FACTORS:\n r = Expr(self.op, dict(self.data))\n for k, v in other.data.items():\n _pairs_add(r.data, k, v)\n return normalize(r)\n elif self.op is Op.TERMS:\n r = Expr(self.op, {})\n for t1, c1 in self.data.items():\n for t2, c2 in other.data.items():\n _pairs_add(r.data, t1 * t2, c1 * c2)\n return normalize(r)\n\n if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL):\n return self * as_complex(other)\n elif other.op is Op.COMPLEX and self.op in (Op.INTEGER, Op.REAL):\n return as_complex(self) * other\n elif self.op is Op.REAL and other.op is Op.INTEGER:\n return self * as_real(other, kind=self.data[1])\n elif self.op is Op.INTEGER and other.op is Op.REAL:\n return as_real(self, kind=other.data[1]) * other\n\n if self.op is Op.TERMS:\n return self * as_terms(other)\n elif other.op is Op.TERMS:\n return as_terms(self) * other\n\n return as_factors(self) * as_factors(other)\n return NotImplemented\n\n def __rmul__(self, other):\n if isinstance(other, number_types):\n return as_number(other) * self\n return NotImplemented\n\n def __pow__(self, other):\n other = as_expr(other)\n if isinstance(other, Expr):\n if other.op is Op.INTEGER:\n exponent = other.data[0]\n # TODO: other kind not used\n if exponent == 0:\n return as_number(1)\n if exponent == 1:\n return self\n if exponent > 0:\n if self.op is Op.FACTORS:\n r = Expr(self.op, {})\n for k, v in self.data.items():\n r.data[k] = v * exponent\n return normalize(r)\n return self * (self ** (exponent - 1))\n elif exponent != -1:\n return (self ** (-exponent)) ** -1\n return Expr(Op.FACTORS, {self: exponent})\n return as_apply(ArithOp.POW, self, other)\n return NotImplemented\n\n def __truediv__(self, other):\n other = as_expr(other)\n if isinstance(other, Expr):\n # Fortran / is different from Python /:\n # - `/` is a truncate operation for integer operands\n return normalize(as_apply(ArithOp.DIV, self, other))\n return NotImplemented\n\n def __rtruediv__(self, other):\n other = as_expr(other)\n if isinstance(other, Expr):\n return other / self\n return NotImplemented\n\n def __floordiv__(self, other):\n other = as_expr(other)\n if isinstance(other, Expr):\n # Fortran // is different from Python //:\n # - `//` is a concatenate operation for string operands\n return normalize(Expr(Op.CONCAT, (self, other)))\n return NotImplemented\n\n def __rfloordiv__(self, other):\n other = as_expr(other)\n if isinstance(other, Expr):\n return other // self\n return NotImplemented\n\n def __call__(self, *args, **kwargs):\n # In Fortran, parenthesis () are use for both function call as\n # well as indexing operations.\n #\n # TODO: implement a method for deciding when __call__ should\n # return an INDEXING expression.\n return as_apply(self, *map(as_expr, args),\n **{k: as_expr(v) for k, v in kwargs.items()})\n\n def __getitem__(self, index):\n # Provided to support C indexing operations that .pyf files\n # may contain.\n index = as_expr(index)\n if not isinstance(index, tuple):\n index = index,\n if len(index) > 1:\n ewarn(f'C-index should be a single expression but got `{index}`')\n return Expr(Op.INDEXING, (self,) + index)\n\n def substitute(self, symbols_map):\n """Recursively substitute symbols with values in symbols map.\n\n Symbols map is a dictionary of symbol-expression pairs.\n """\n if self.op is Op.SYMBOL:\n value = symbols_map.get(self)\n if value is None:\n return self\n m = re.match(r'\A(@__f2py_PARENTHESIS_(\w+)_\d+@)\Z', self.data)\n if m:\n # complement to fromstring method\n items, paren = m.groups()\n if paren in ['ROUNDDIV', 'SQUARE']:\n return as_array(value)\n assert paren == 'ROUND', (paren, value)\n return value\n if self.op in (Op.INTEGER, Op.REAL, Op.STRING):\n return self\n if self.op in (Op.ARRAY, Op.COMPLEX):\n return Expr(self.op, tuple(item.substitute(symbols_map)\n for item in self.data))\n if self.op is Op.CONCAT:\n return normalize(Expr(self.op, tuple(item.substitute(symbols_map)\n for item in self.data)))\n if self.op is Op.TERMS:\n r = None\n for term, coeff in self.data.items():\n if r is None:\n r = term.substitute(symbols_map) * coeff\n else:\n r += term.substitute(symbols_map) * coeff\n if r is None:\n ewarn('substitute: empty TERMS expression interpreted as'\n ' int-literal 0')\n return as_number(0)\n return r\n if self.op is Op.FACTORS:\n r = None\n for base, exponent in self.data.items():\n if r is None:\n r = base.substitute(symbols_map) ** exponent\n else:\n r *= base.substitute(symbols_map) ** exponent\n if r is None:\n ewarn('substitute: empty FACTORS expression interpreted'\n ' as int-literal 1')\n return as_number(1)\n return r\n if self.op is Op.APPLY:\n target, args, kwargs = self.data\n if isinstance(target, Expr):\n target = target.substitute(symbols_map)\n args = tuple(a.substitute(symbols_map) for a in args)\n kwargs = {k: v.substitute(symbols_map)\n for k, v in kwargs.items()}\n return normalize(Expr(self.op, (target, args, kwargs)))\n if self.op is Op.INDEXING:\n func = self.data[0]\n if isinstance(func, Expr):\n func = func.substitute(symbols_map)\n args = tuple(a.substitute(symbols_map) for a in self.data[1:])\n return normalize(Expr(self.op, (func,) + args))\n if self.op is Op.TERNARY:\n operands = tuple(a.substitute(symbols_map) for a in self.data)\n return normalize(Expr(self.op, operands))\n if self.op in (Op.REF, Op.DEREF):\n return normalize(Expr(self.op, self.data.substitute(symbols_map)))\n if self.op is Op.RELATIONAL:\n rop, left, right = self.data\n left = left.substitute(symbols_map)\n right = right.substitute(symbols_map)\n return normalize(Expr(self.op, (rop, left, right)))\n raise NotImplementedError(f'substitute method for {self.op}: {self!r}')\n\n def traverse(self, visit, *args, **kwargs):\n """Traverse expression tree with visit function.\n\n The visit function is applied to an expression with given args\n and kwargs.\n\n Traverse call returns an expression returned by visit when not\n None, otherwise return a new normalized expression with\n traverse-visit sub-expressions.\n """\n result = visit(self, *args, **kwargs)\n if result is not None:\n return result\n\n if self.op in (Op.INTEGER, Op.REAL, Op.STRING, Op.SYMBOL):\n return self\n elif self.op in (Op.COMPLEX, Op.ARRAY, Op.CONCAT, Op.TERNARY):\n return normalize(Expr(self.op, tuple(\n item.traverse(visit, *args, **kwargs)\n for item in self.data)))\n elif self.op in (Op.TERMS, Op.FACTORS):\n data = {}\n for k, v in self.data.items():\n k = k.traverse(visit, *args, **kwargs)\n v = (v.traverse(visit, *args, **kwargs)\n if isinstance(v, Expr) else v)\n if k in data:\n v = data[k] + v\n data[k] = v\n return normalize(Expr(self.op, data))\n elif self.op is Op.APPLY:\n obj = self.data[0]\n func = (obj.traverse(visit, *args, **kwargs)\n if isinstance(obj, Expr) else obj)\n operands = tuple(operand.traverse(visit, *args, **kwargs)\n for operand in self.data[1])\n kwoperands = {k: v.traverse(visit, *args, **kwargs)\n for k, v in self.data[2].items()}\n return normalize(Expr(self.op, (func, operands, kwoperands)))\n elif self.op is Op.INDEXING:\n obj = self.data[0]\n obj = (obj.traverse(visit, *args, **kwargs)\n if isinstance(obj, Expr) else obj)\n indices = tuple(index.traverse(visit, *args, **kwargs)\n for index in self.data[1:])\n return normalize(Expr(self.op, (obj,) + indices))\n elif self.op in (Op.REF, Op.DEREF):\n return normalize(Expr(self.op,\n self.data.traverse(visit, *args, **kwargs)))\n elif self.op is Op.RELATIONAL:\n rop, left, right = self.data\n left = left.traverse(visit, *args, **kwargs)\n right = right.traverse(visit, *args, **kwargs)\n return normalize(Expr(self.op, (rop, left, right)))\n raise NotImplementedError(f'traverse method for {self.op}')\n\n def contains(self, other):\n """Check if self contains other.\n """\n found = []\n\n def visit(expr, found=found):\n if found:\n return expr\n elif expr == other:\n found.append(1)\n return expr\n\n self.traverse(visit)\n\n return len(found) != 0\n\n def symbols(self):\n """Return a set of symbols contained in self.\n """\n found = set()\n\n def visit(expr, found=found):\n if expr.op is Op.SYMBOL:\n found.add(expr)\n\n self.traverse(visit)\n\n return found\n\n def polynomial_atoms(self):\n """Return a set of expressions used as atoms in polynomial self.\n """\n found = set()\n\n def visit(expr, found=found):\n if expr.op is Op.FACTORS:\n for b in expr.data:\n b.traverse(visit)\n return expr\n if expr.op in (Op.TERMS, Op.COMPLEX):\n return\n if expr.op is Op.APPLY and isinstance(expr.data[0], ArithOp):\n if expr.data[0] is ArithOp.POW:\n expr.data[1][0].traverse(visit)\n return expr\n return\n if expr.op in (Op.INTEGER, Op.REAL):\n return expr\n\n found.add(expr)\n\n if expr.op in (Op.INDEXING, Op.APPLY):\n return expr\n\n self.traverse(visit)\n\n return found\n\n def linear_solve(self, symbol):\n """Return a, b such that a * symbol + b == self.\n\n If self is not linear with respect to symbol, raise RuntimeError.\n """\n b = self.substitute({symbol: as_number(0)})\n ax = self - b\n a = ax.substitute({symbol: as_number(1)})\n\n zero, _ = as_numer_denom(a * symbol - ax)\n\n if zero != as_number(0):\n raise RuntimeError(f'not a {symbol}-linear equation:'\n f' {a} * {symbol} + {b} == {self}')\n return a, b\n\n\ndef normalize(obj):\n """Normalize Expr and apply basic evaluation methods.\n """\n if not isinstance(obj, Expr):\n return obj\n\n if obj.op is Op.TERMS:\n d = {}\n for t, c in obj.data.items():\n if c == 0:\n continue\n if t.op is Op.COMPLEX and c != 1:\n t = t * c\n c = 1\n if t.op is Op.TERMS:\n for t1, c1 in t.data.items():\n _pairs_add(d, t1, c1 * c)\n else:\n _pairs_add(d, t, c)\n if len(d) == 0:\n # TODO: determine correct kind\n return as_number(0)\n elif len(d) == 1:\n (t, c), = d.items()\n if c == 1:\n return t\n return Expr(Op.TERMS, d)\n\n if obj.op is Op.FACTORS:\n coeff = 1\n d = {}\n for b, e in obj.data.items():\n if e == 0:\n continue\n if b.op is Op.TERMS and isinstance(e, integer_types) and e > 1:\n # expand integer powers of sums\n b = b * (b ** (e - 1))\n e = 1\n\n if b.op in (Op.INTEGER, Op.REAL):\n if e == 1:\n coeff *= b.data[0]\n elif e > 0:\n coeff *= b.data[0] ** e\n else:\n _pairs_add(d, b, e)\n elif b.op is Op.FACTORS:\n if e > 0 and isinstance(e, integer_types):\n for b1, e1 in b.data.items():\n _pairs_add(d, b1, e1 * e)\n else:\n _pairs_add(d, b, e)\n else:\n _pairs_add(d, b, e)\n if len(d) == 0 or coeff == 0:\n # TODO: determine correct kind\n assert isinstance(coeff, number_types)\n return as_number(coeff)\n elif len(d) == 1:\n (b, e), = d.items()\n if e == 1:\n t = b\n else:\n t = Expr(Op.FACTORS, d)\n if coeff == 1:\n return t\n return Expr(Op.TERMS, {t: coeff})\n elif coeff == 1:\n return Expr(Op.FACTORS, d)\n else:\n return Expr(Op.TERMS, {Expr(Op.FACTORS, d): coeff})\n\n if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV:\n dividend, divisor = obj.data[1]\n t1, c1 = as_term_coeff(dividend)\n t2, c2 = as_term_coeff(divisor)\n if isinstance(c1, integer_types) and isinstance(c2, integer_types):\n g = gcd(c1, c2)\n c1, c2 = c1 // g, c2 // g\n else:\n c1, c2 = c1 / c2, 1\n\n if t1.op is Op.APPLY and t1.data[0] is ArithOp.DIV:\n numer = t1.data[1][0] * c1\n denom = t1.data[1][1] * t2 * c2\n return as_apply(ArithOp.DIV, numer, denom)\n\n if t2.op is Op.APPLY and t2.data[0] is ArithOp.DIV:\n numer = t2.data[1][1] * t1 * c1\n denom = t2.data[1][0] * c2\n return as_apply(ArithOp.DIV, numer, denom)\n\n d = dict(as_factors(t1).data)\n for b, e in as_factors(t2).data.items():\n _pairs_add(d, b, -e)\n numer, denom = {}, {}\n for b, e in d.items():\n if e > 0:\n numer[b] = e\n else:\n denom[b] = -e\n numer = normalize(Expr(Op.FACTORS, numer)) * c1\n denom = normalize(Expr(Op.FACTORS, denom)) * c2\n\n if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] == 1:\n # TODO: denom kind not used\n return numer\n return as_apply(ArithOp.DIV, numer, denom)\n\n if obj.op is Op.CONCAT:\n lst = [obj.data[0]]\n for s in obj.data[1:]:\n last = lst[-1]\n if (\n last.op is Op.STRING\n and s.op is Op.STRING\n and last.data[0][0] in '"\''\n and s.data[0][0] == last.data[0][-1]\n ):\n new_last = as_string(last.data[0][:-1] + s.data[0][1:],\n max(last.data[1], s.data[1]))\n lst[-1] = new_last\n else:\n lst.append(s)\n if len(lst) == 1:\n return lst[0]\n return Expr(Op.CONCAT, tuple(lst))\n\n if obj.op is Op.TERNARY:\n cond, expr1, expr2 = map(normalize, obj.data)\n if cond.op is Op.INTEGER:\n return expr1 if cond.data[0] else expr2\n return Expr(Op.TERNARY, (cond, expr1, expr2))\n\n return obj\n\n\ndef as_expr(obj):\n """Convert non-Expr objects to Expr objects.\n """\n if isinstance(obj, complex):\n return as_complex(obj.real, obj.imag)\n if isinstance(obj, number_types):\n return as_number(obj)\n if isinstance(obj, str):\n # STRING expression holds string with boundary quotes, hence\n # applying repr:\n return as_string(repr(obj))\n if isinstance(obj, tuple):\n return tuple(map(as_expr, obj))\n return obj\n\n\ndef as_symbol(obj):\n """Return object as SYMBOL expression (variable or unparsed expression).\n """\n return Expr(Op.SYMBOL, obj)\n\n\ndef as_number(obj, kind=4):\n """Return object as INTEGER or REAL constant.\n """\n if isinstance(obj, int):\n return Expr(Op.INTEGER, (obj, kind))\n if isinstance(obj, float):\n return Expr(Op.REAL, (obj, kind))\n if isinstance(obj, Expr):\n if obj.op in (Op.INTEGER, Op.REAL):\n return obj\n raise OpError(f'cannot convert {obj} to INTEGER or REAL constant')\n\n\ndef as_integer(obj, kind=4):\n """Return object as INTEGER constant.\n """\n if isinstance(obj, int):\n return Expr(Op.INTEGER, (obj, kind))\n if isinstance(obj, Expr):\n if obj.op is Op.INTEGER:\n return obj\n raise OpError(f'cannot convert {obj} to INTEGER constant')\n\n\ndef as_real(obj, kind=4):\n """Return object as REAL constant.\n """\n if isinstance(obj, int):\n return Expr(Op.REAL, (float(obj), kind))\n if isinstance(obj, float):\n return Expr(Op.REAL, (obj, kind))\n if isinstance(obj, Expr):\n if obj.op is Op.REAL:\n return obj\n elif obj.op is Op.INTEGER:\n return Expr(Op.REAL, (float(obj.data[0]), kind))\n raise OpError(f'cannot convert {obj} to REAL constant')\n\n\ndef as_string(obj, kind=1):\n """Return object as STRING expression (string literal constant).\n """\n return Expr(Op.STRING, (obj, kind))\n\n\ndef as_array(obj):\n """Return object as ARRAY expression (array constant).\n """\n if isinstance(obj, Expr):\n obj = obj,\n return Expr(Op.ARRAY, obj)\n\n\ndef as_complex(real, imag=0):\n """Return object as COMPLEX expression (complex literal constant).\n """\n return Expr(Op.COMPLEX, (as_expr(real), as_expr(imag)))\n\n\ndef as_apply(func, *args, **kwargs):\n """Return object as APPLY expression (function call, constructor, etc.)\n """\n return Expr(Op.APPLY,\n (func, tuple(map(as_expr, args)),\n {k: as_expr(v) for k, v in kwargs.items()}))\n\n\ndef as_ternary(cond, expr1, expr2):\n """Return object as TERNARY expression (cond?expr1:expr2).\n """\n return Expr(Op.TERNARY, (cond, expr1, expr2))\n\n\ndef as_ref(expr):\n """Return object as referencing expression.\n """\n return Expr(Op.REF, expr)\n\n\ndef as_deref(expr):\n """Return object as dereferencing expression.\n """\n return Expr(Op.DEREF, expr)\n\n\ndef as_eq(left, right):\n return Expr(Op.RELATIONAL, (RelOp.EQ, left, right))\n\n\ndef as_ne(left, right):\n return Expr(Op.RELATIONAL, (RelOp.NE, left, right))\n\n\ndef as_lt(left, right):\n return Expr(Op.RELATIONAL, (RelOp.LT, left, right))\n\n\ndef as_le(left, right):\n return Expr(Op.RELATIONAL, (RelOp.LE, left, right))\n\n\ndef as_gt(left, right):\n return Expr(Op.RELATIONAL, (RelOp.GT, left, right))\n\n\ndef as_ge(left, right):\n return Expr(Op.RELATIONAL, (RelOp.GE, left, right))\n\n\ndef as_terms(obj):\n """Return expression as TERMS expression.\n """\n if isinstance(obj, Expr):\n obj = normalize(obj)\n if obj.op is Op.TERMS:\n return obj\n if obj.op is Op.INTEGER:\n return Expr(Op.TERMS, {as_integer(1, obj.data[1]): obj.data[0]})\n if obj.op is Op.REAL:\n return Expr(Op.TERMS, {as_real(1, obj.data[1]): obj.data[0]})\n return Expr(Op.TERMS, {obj: 1})\n raise OpError(f'cannot convert {type(obj)} to terms Expr')\n\n\ndef as_factors(obj):\n """Return expression as FACTORS expression.\n """\n if isinstance(obj, Expr):\n obj = normalize(obj)\n if obj.op is Op.FACTORS:\n return obj\n if obj.op is Op.TERMS:\n if len(obj.data) == 1:\n (term, coeff), = obj.data.items()\n if coeff == 1:\n return Expr(Op.FACTORS, {term: 1})\n return Expr(Op.FACTORS, {term: 1, Expr.number(coeff): 1})\n if (obj.op is Op.APPLY\n and obj.data[0] is ArithOp.DIV\n and not obj.data[2]):\n return Expr(Op.FACTORS, {obj.data[1][0]: 1, obj.data[1][1]: -1})\n return Expr(Op.FACTORS, {obj: 1})\n raise OpError(f'cannot convert {type(obj)} to terms Expr')\n\n\ndef as_term_coeff(obj):\n """Return expression as term-coefficient pair.\n """\n if isinstance(obj, Expr):\n obj = normalize(obj)\n if obj.op is Op.INTEGER:\n return as_integer(1, obj.data[1]), obj.data[0]\n if obj.op is Op.REAL:\n return as_real(1, obj.data[1]), obj.data[0]\n if obj.op is Op.TERMS:\n if len(obj.data) == 1:\n (term, coeff), = obj.data.items()\n return term, coeff\n # TODO: find common divisor of coefficients\n if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV:\n t, c = as_term_coeff(obj.data[1][0])\n return as_apply(ArithOp.DIV, t, obj.data[1][1]), c\n return obj, 1\n raise OpError(f'cannot convert {type(obj)} to term and coeff')\n\n\ndef as_numer_denom(obj):\n """Return expression as numer-denom pair.\n """\n if isinstance(obj, Expr):\n obj = normalize(obj)\n if obj.op in (Op.INTEGER, Op.REAL, Op.COMPLEX, Op.SYMBOL,\n Op.INDEXING, Op.TERNARY):\n return obj, as_number(1)\n elif obj.op is Op.APPLY:\n if obj.data[0] is ArithOp.DIV and not obj.data[2]:\n numers, denoms = map(as_numer_denom, obj.data[1])\n return numers[0] * denoms[1], numers[1] * denoms[0]\n return obj, as_number(1)\n elif obj.op is Op.TERMS:\n numers, denoms = [], []\n for term, coeff in obj.data.items():\n n, d = as_numer_denom(term)\n n = n * coeff\n numers.append(n)\n denoms.append(d)\n numer, denom = as_number(0), as_number(1)\n for i in range(len(numers)):\n n = numers[i]\n for j in range(len(numers)):\n if i != j:\n n *= denoms[j]\n numer += n\n denom *= denoms[i]\n if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] < 0:\n numer, denom = -numer, -denom\n return numer, denom\n elif obj.op is Op.FACTORS:\n numer, denom = as_number(1), as_number(1)\n for b, e in obj.data.items():\n bnumer, bdenom = as_numer_denom(b)\n if e > 0:\n numer *= bnumer ** e\n denom *= bdenom ** e\n elif e < 0:\n numer *= bdenom ** (-e)\n denom *= bnumer ** (-e)\n return numer, denom\n raise OpError(f'cannot convert {type(obj)} to numer and denom')\n\n\ndef _counter():\n # Used internally to generate unique dummy symbols\n counter = 0\n while True:\n counter += 1\n yield counter\n\n\nCOUNTER = _counter()\n\n\ndef eliminate_quotes(s):\n """Replace quoted substrings of input string.\n\n Return a new string and a mapping of replacements.\n """\n d = {}\n\n def repl(m):\n kind, value = m.groups()[:2]\n if kind:\n # remove trailing underscore\n kind = kind[:-1]\n p = {"'": "SINGLE", '"': "DOUBLE"}[value[0]]\n k = f'{kind}@__f2py_QUOTES_{p}_{COUNTER.__next__()}@'\n d[k] = value\n return k\n\n new_s = re.sub(r'({kind}_|)({single_quoted}|{double_quoted})'.format(\n kind=r'\w[\w\d_]*',\n single_quoted=r"('([^'\\]|(\\.))*')",\n double_quoted=r'("([^"\\]|(\\.))*")'),\n repl, s)\n\n assert '"' not in new_s\n assert "'" not in new_s\n\n return new_s, d\n\n\ndef insert_quotes(s, d):\n """Inverse of eliminate_quotes.\n """\n for k, v in d.items():\n kind = k[:k.find('@')]\n if kind:\n kind += '_'\n s = s.replace(k, kind + v)\n return s\n\n\ndef replace_parenthesis(s):\n """Replace substrings of input that are enclosed in parenthesis.\n\n Return a new string and a mapping of replacements.\n """\n # Find a parenthesis pair that appears first.\n\n # Fortran deliminator are `(`, `)`, `[`, `]`, `(/', '/)`, `/`.\n # We don't handle `/` deliminator because it is not a part of an\n # expression.\n left, right = None, None\n mn_i = len(s)\n for left_, right_ in (('(/', '/)'),\n '()',\n '{}', # to support C literal structs\n '[]'):\n i = s.find(left_)\n if i == -1:\n continue\n if i < mn_i:\n mn_i = i\n left, right = left_, right_\n\n if left is None:\n return s, {}\n\n i = mn_i\n j = s.find(right, i)\n\n while s.count(left, i + 1, j) != s.count(right, i + 1, j):\n j = s.find(right, j + 1)\n if j == -1:\n raise ValueError(f'Mismatch of {left + right} parenthesis in {s!r}')\n\n p = {'(': 'ROUND', '[': 'SQUARE', '{': 'CURLY', '(/': 'ROUNDDIV'}[left]\n\n k = f'@__f2py_PARENTHESIS_{p}_{COUNTER.__next__()}@'\n v = s[i + len(left):j]\n r, d = replace_parenthesis(s[j + len(right):])\n d[k] = v\n return s[:i] + k + r, d\n\n\ndef _get_parenthesis_kind(s):\n assert s.startswith('@__f2py_PARENTHESIS_'), s\n return s.split('_')[4]\n\n\ndef unreplace_parenthesis(s, d):\n """Inverse of replace_parenthesis.\n """\n for k, v in d.items():\n p = _get_parenthesis_kind(k)\n left = {'ROUND': '(', 'SQUARE': '[', 'CURLY': '{', 'ROUNDDIV': '(/'}[p]\n right = {'ROUND': ')', 'SQUARE': ']', 'CURLY': '}', 'ROUNDDIV': '/)'}[p]\n s = s.replace(k, left + v + right)\n return s\n\n\ndef fromstring(s, language=Language.C):\n """Create an expression from a string.\n\n This is a "lazy" parser, that is, only arithmetic operations are\n resolved, non-arithmetic operations are treated as symbols.\n """\n r = _FromStringWorker(language=language).parse(s)\n if isinstance(r, Expr):\n return r\n raise ValueError(f'failed to parse `{s}` to Expr instance: got `{r}`')\n\n\nclass _Pair:\n # Internal class to represent a pair of expressions\n\n def __init__(self, left, right):\n self.left = left\n self.right = right\n\n def substitute(self, symbols_map):\n left, right = self.left, self.right\n if isinstance(left, Expr):\n left = left.substitute(symbols_map)\n if isinstance(right, Expr):\n right = right.substitute(symbols_map)\n return _Pair(left, right)\n\n def __repr__(self):\n return f'{type(self).__name__}({self.left}, {self.right})'\n\n\nclass _FromStringWorker:\n\n def __init__(self, language=Language.C):\n self.original = None\n self.quotes_map = None\n self.language = language\n\n def finalize_string(self, s):\n return insert_quotes(s, self.quotes_map)\n\n def parse(self, inp):\n self.original = inp\n unquoted, self.quotes_map = eliminate_quotes(inp)\n return self.process(unquoted)\n\n def process(self, s, context='expr'):\n """Parse string within the given context.\n\n The context may define the result in case of ambiguous\n expressions. For instance, consider expressions `f(x, y)` and\n `(x, y) + (a, b)` where `f` is a function and pair `(x, y)`\n denotes complex number. Specifying context as "args" or\n "expr", the subexpression `(x, y)` will be parse to an\n argument list or to a complex number, respectively.\n """\n if isinstance(s, (list, tuple)):\n return type(s)(self.process(s_, context) for s_ in s)\n\n assert isinstance(s, str), (type(s), s)\n\n # replace subexpressions in parenthesis with f2py @-names\n r, raw_symbols_map = replace_parenthesis(s)\n r = r.strip()\n\n def restore(r):\n # restores subexpressions marked with f2py @-names\n if isinstance(r, (list, tuple)):\n return type(r)(map(restore, r))\n return unreplace_parenthesis(r, raw_symbols_map)\n\n # comma-separated tuple\n if ',' in r:\n operands = restore(r.split(','))\n if context == 'args':\n return tuple(self.process(operands))\n if context == 'expr':\n if len(operands) == 2:\n # complex number literal\n return as_complex(*self.process(operands))\n raise NotImplementedError(\n f'parsing comma-separated list (context={context}): {r}')\n\n # ternary operation\n m = re.match(r'\A([^?]+)[?]([^:]+)[:](.+)\Z', r)\n if m:\n assert context == 'expr', context\n oper, expr1, expr2 = restore(m.groups())\n oper = self.process(oper)\n expr1 = self.process(expr1)\n expr2 = self.process(expr2)\n return as_ternary(oper, expr1, expr2)\n\n # relational expression\n if self.language is Language.Fortran:\n m = re.match(\n r'\A(.+)\s*[.](eq|ne|lt|le|gt|ge)[.]\s*(.+)\Z', r, re.I)\n else:\n m = re.match(\n r'\A(.+)\s*([=][=]|[!][=]|[<][=]|[<]|[>][=]|[>])\s*(.+)\Z', r)\n if m:\n left, rop, right = m.groups()\n if self.language is Language.Fortran:\n rop = '.' + rop + '.'\n left, right = self.process(restore((left, right)))\n rop = RelOp.fromstring(rop, language=self.language)\n return Expr(Op.RELATIONAL, (rop, left, right))\n\n # keyword argument\n m = re.match(r'\A(\w[\w\d_]*)\s*[=](.*)\Z', r)\n if m:\n keyname, value = m.groups()\n value = restore(value)\n return _Pair(keyname, self.process(value))\n\n # addition/subtraction operations\n operands = re.split(r'((?<!\d[edED])[+-])', r)\n if len(operands) > 1:\n result = self.process(restore(operands[0] or '0'))\n for op, operand in zip(operands[1::2], operands[2::2]):\n operand = self.process(restore(operand))\n op = op.strip()\n if op == '+':\n result += operand\n else:\n assert op == '-'\n result -= operand\n return result\n\n # string concatenate operation\n if self.language is Language.Fortran and '//' in r:\n operands = restore(r.split('//'))\n return Expr(Op.CONCAT,\n tuple(self.process(operands)))\n\n # multiplication/division operations\n operands = re.split(r'(?<=[@\w\d_])\s*([*]|/)',\n (r if self.language is Language.C\n else r.replace('**', '@__f2py_DOUBLE_STAR@')))\n if len(operands) > 1:\n operands = restore(operands)\n if self.language is not Language.C:\n operands = [operand.replace('@__f2py_DOUBLE_STAR@', '**')\n for operand in operands]\n # Expression is an arithmetic product\n result = self.process(operands[0])\n for op, operand in zip(operands[1::2], operands[2::2]):\n operand = self.process(operand)\n op = op.strip()\n if op == '*':\n result *= operand\n else:\n assert op == '/'\n result /= operand\n return result\n\n # referencing/dereferencing\n if r.startswith(('*', '&')):\n op = {'*': Op.DEREF, '&': Op.REF}[r[0]]\n operand = self.process(restore(r[1:]))\n return Expr(op, operand)\n\n # exponentiation operations\n if self.language is not Language.C and '**' in r:\n operands = list(reversed(restore(r.split('**'))))\n result = self.process(operands[0])\n for operand in operands[1:]:\n operand = self.process(operand)\n result = operand ** result\n return result\n\n # int-literal-constant\n m = re.match(r'\A({digit_string})({kind}|)\Z'.format(\n digit_string=r'\d+',\n kind=r'_(\d+|\w[\w\d_]*)'), r)\n if m:\n value, _, kind = m.groups()\n if kind and kind.isdigit():\n kind = int(kind)\n return as_integer(int(value), kind or 4)\n\n # real-literal-constant\n m = re.match(r'\A({significant}({exponent}|)|\d+{exponent})({kind}|)\Z'\n .format(\n significant=r'[.]\d+|\d+[.]\d*',\n exponent=r'[edED][+-]?\d+',\n kind=r'_(\d+|\w[\w\d_]*)'), r)\n if m:\n value, _, _, kind = m.groups()\n if kind and kind.isdigit():\n kind = int(kind)\n value = value.lower()\n if 'd' in value:\n return as_real(float(value.replace('d', 'e')), kind or 8)\n return as_real(float(value), kind or 4)\n\n # string-literal-constant with kind parameter specification\n if r in self.quotes_map:\n kind = r[:r.find('@')]\n return as_string(self.quotes_map[r], kind or 1)\n\n # array constructor or literal complex constant or\n # parenthesized expression\n if r in raw_symbols_map:\n paren = _get_parenthesis_kind(r)\n items = self.process(restore(raw_symbols_map[r]),\n 'expr' if paren == 'ROUND' else 'args')\n if paren == 'ROUND':\n if isinstance(items, Expr):\n return items\n if paren in ['ROUNDDIV', 'SQUARE']:\n # Expression is a array constructor\n if isinstance(items, Expr):\n items = (items,)\n return as_array(items)\n\n # function call/indexing\n m = re.match(r'\A(.+)\s*(@__f2py_PARENTHESIS_(ROUND|SQUARE)_\d+@)\Z',\n r)\n if m:\n target, args, paren = m.groups()\n target = self.process(restore(target))\n args = self.process(restore(args)[1:-1], 'args')\n if not isinstance(args, tuple):\n args = args,\n if paren == 'ROUND':\n kwargs = {a.left: a.right for a in args\n if isinstance(a, _Pair)}\n args = tuple(a for a in args if not isinstance(a, _Pair))\n # Warning: this could also be Fortran indexing operation..\n return as_apply(target, *args, **kwargs)\n else:\n # Expression is a C/Python indexing operation\n # (e.g. used in .pyf files)\n assert paren == 'SQUARE'\n return target[args]\n\n # Fortran standard conforming identifier\n m = re.match(r'\A\w[\w\d_]*\Z', r)\n if m:\n return as_symbol(r)\n\n # fall-back to symbol\n r = self.finalize_string(restore(r))\n ewarn(\n f'fromstring: treating {r!r} as symbol (original={self.original})')\n return as_symbol(r)\n
.venv\Lib\site-packages\numpy\f2py\symbolic.py
symbolic.py
Python
54,730
0.75
0.245383
0.067835
node-utils
320
2023-08-23T16:58:49.818339
Apache-2.0
false
387754f16b71c13b51518acabe3e36f1
from collections.abc import Callable, Mapping\nfrom enum import Enum\nfrom typing import Any, Generic, ParamSpec, Self, TypeAlias, overload\nfrom typing import Literal as L\n\nfrom typing_extensions import TypeVar\n\n__all__ = ["Expr"]\n\n###\n\n_Tss = ParamSpec("_Tss")\n_ExprT = TypeVar("_ExprT", bound=Expr)\n_ExprT1 = TypeVar("_ExprT1", bound=Expr)\n_ExprT2 = TypeVar("_ExprT2", bound=Expr)\n_OpT_co = TypeVar("_OpT_co", bound=Op, default=Op, covariant=True)\n_LanguageT_co = TypeVar("_LanguageT_co", bound=Language, default=Language, covariant=True)\n_DataT_co = TypeVar("_DataT_co", default=Any, covariant=True)\n_LeftT_co = TypeVar("_LeftT_co", default=Any, covariant=True)\n_RightT_co = TypeVar("_RightT_co", default=Any, covariant=True)\n\n_RelCOrPy: TypeAlias = L["==", "!=", "<", "<=", ">", ">="]\n_RelFortran: TypeAlias = L[".eq.", ".ne.", ".lt.", ".le.", ".gt.", ".ge."]\n\n_ToExpr: TypeAlias = Expr | complex | str\n_ToExprN: TypeAlias = _ToExpr | tuple[_ToExprN, ...]\n_NestedString: TypeAlias = str | tuple[_NestedString, ...] | list[_NestedString]\n\n###\n\nclass OpError(Exception): ...\nclass ExprWarning(UserWarning): ...\n\nclass Language(Enum):\n Python = 0\n Fortran = 1\n C = 2\n\nclass Op(Enum):\n INTEGER = 10\n REAL = 12\n COMPLEX = 15\n STRING = 20\n ARRAY = 30\n SYMBOL = 40\n TERNARY = 100\n APPLY = 200\n INDEXING = 210\n CONCAT = 220\n RELATIONAL = 300\n TERMS = 1_000\n FACTORS = 2_000\n REF = 3_000\n DEREF = 3_001\n\nclass RelOp(Enum):\n EQ = 1\n NE = 2\n LT = 3\n LE = 4\n GT = 5\n GE = 6\n\n @overload\n @classmethod\n def fromstring(cls, s: _RelCOrPy, language: L[Language.C, Language.Python] = ...) -> RelOp: ...\n @overload\n @classmethod\n def fromstring(cls, s: _RelFortran, language: L[Language.Fortran]) -> RelOp: ...\n\n #\n @overload\n def tostring(self, /, language: L[Language.C, Language.Python] = ...) -> _RelCOrPy: ...\n @overload\n def tostring(self, /, language: L[Language.Fortran]) -> _RelFortran: ...\n\nclass ArithOp(Enum):\n POS = 1\n NEG = 2\n ADD = 3\n SUB = 4\n MUL = 5\n DIV = 6\n POW = 7\n\nclass Precedence(Enum):\n ATOM = 0\n POWER = 1\n UNARY = 2\n PRODUCT = 3\n SUM = 4\n LT = 6\n EQ = 7\n LAND = 11\n LOR = 12\n TERNARY = 13\n ASSIGN = 14\n TUPLE = 15\n NONE = 100\n\nclass Expr(Generic[_OpT_co, _DataT_co]):\n op: _OpT_co\n data: _DataT_co\n\n @staticmethod\n def parse(s: str, language: Language = ...) -> Expr: ...\n\n #\n def __init__(self, /, op: Op, data: _DataT_co) -> None: ...\n\n #\n def __lt__(self, other: Expr, /) -> bool: ...\n def __le__(self, other: Expr, /) -> bool: ...\n def __gt__(self, other: Expr, /) -> bool: ...\n def __ge__(self, other: Expr, /) -> bool: ...\n\n #\n def __pos__(self, /) -> Self: ...\n def __neg__(self, /) -> Expr: ...\n\n #\n def __add__(self, other: Expr, /) -> Expr: ...\n def __radd__(self, other: Expr, /) -> Expr: ...\n\n #\n def __sub__(self, other: Expr, /) -> Expr: ...\n def __rsub__(self, other: Expr, /) -> Expr: ...\n\n #\n def __mul__(self, other: Expr, /) -> Expr: ...\n def __rmul__(self, other: Expr, /) -> Expr: ...\n\n #\n def __pow__(self, other: Expr, /) -> Expr: ...\n\n #\n def __truediv__(self, other: Expr, /) -> Expr: ...\n def __rtruediv__(self, other: Expr, /) -> Expr: ...\n\n #\n def __floordiv__(self, other: Expr, /) -> Expr: ...\n def __rfloordiv__(self, other: Expr, /) -> Expr: ...\n\n #\n def __call__(\n self,\n /,\n *args: _ToExprN,\n **kwargs: _ToExprN,\n ) -> Expr[L[Op.APPLY], tuple[Self, tuple[Expr, ...], dict[str, Expr]]]: ...\n\n #\n @overload\n def __getitem__(self, index: _ExprT | tuple[_ExprT], /) -> Expr[L[Op.INDEXING], tuple[Self, _ExprT]]: ...\n @overload\n def __getitem__(self, index: _ToExpr | tuple[_ToExpr], /) -> Expr[L[Op.INDEXING], tuple[Self, Expr]]: ...\n\n #\n def substitute(self, /, symbols_map: Mapping[Expr, Expr]) -> Expr: ...\n\n #\n @overload\n def traverse(self, /, visit: Callable[_Tss, None], *args: _Tss.args, **kwargs: _Tss.kwargs) -> Expr: ...\n @overload\n def traverse(self, /, visit: Callable[_Tss, _ExprT], *args: _Tss.args, **kwargs: _Tss.kwargs) -> _ExprT: ...\n\n #\n def contains(self, /, other: Expr) -> bool: ...\n\n #\n def symbols(self, /) -> set[Expr]: ...\n def polynomial_atoms(self, /) -> set[Expr]: ...\n\n #\n def linear_solve(self, /, symbol: Expr) -> tuple[Expr, Expr]: ...\n\n #\n def tostring(self, /, parent_precedence: Precedence = ..., language: Language = ...) -> str: ...\n\nclass _Pair(Generic[_LeftT_co, _RightT_co]):\n left: _LeftT_co\n right: _RightT_co\n\n def __init__(self, /, left: _LeftT_co, right: _RightT_co) -> None: ...\n\n #\n @overload\n def substitute(self: _Pair[_ExprT1, _ExprT2], /, symbols_map: Mapping[Expr, Expr]) -> _Pair[Expr, Expr]: ...\n @overload\n def substitute(self: _Pair[_ExprT1, object], /, symbols_map: Mapping[Expr, Expr]) -> _Pair[Expr, Any]: ...\n @overload\n def substitute(self: _Pair[object, _ExprT2], /, symbols_map: Mapping[Expr, Expr]) -> _Pair[Any, Expr]: ...\n @overload\n def substitute(self, /, symbols_map: Mapping[Expr, Expr]) -> _Pair: ...\n\nclass _FromStringWorker(Generic[_LanguageT_co]):\n language: _LanguageT_co\n\n original: str | None\n quotes_map: dict[str, str]\n\n @overload\n def __init__(self: _FromStringWorker[L[Language.C]], /, language: L[Language.C] = ...) -> None: ...\n @overload\n def __init__(self, /, language: _LanguageT_co) -> None: ...\n\n #\n def finalize_string(self, /, s: str) -> str: ...\n\n #\n def parse(self, /, inp: str) -> Expr | _Pair: ...\n\n #\n @overload\n def process(self, /, s: str, context: str = "expr") -> Expr | _Pair: ...\n @overload\n def process(self, /, s: list[str], context: str = "expr") -> list[Expr | _Pair]: ...\n @overload\n def process(self, /, s: tuple[str, ...], context: str = "expr") -> tuple[Expr | _Pair, ...]: ...\n @overload\n def process(self, /, s: _NestedString, context: str = "expr") -> Any: ... # noqa: ANN401\n
.venv\Lib\site-packages\numpy\f2py\symbolic.pyi
symbolic.pyi
Other
6,304
0.95
0.257919
0.146067
node-utils
790
2024-03-01T07:05:28.499440
Apache-2.0
false
b969cb0cc8408a469b55b4879ebebb7f
"""\nBuild 'use others module data' mechanism for f2py2e.\n\nCopyright 1999 -- 2011 Pearu Peterson all rights reserved.\nCopyright 2011 -- present NumPy Developers.\nPermission to use, modify, and distribute this software is given under the\nterms of the NumPy License.\n\nNO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n"""\n__version__ = "$Revision: 1.3 $"[10:-1]\n\nf2py_version = 'See `f2py -v`'\n\n\nfrom .auxfuncs import applyrules, dictappend, gentitle, hasnote, outmess\n\nusemodule_rules = {\n '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""",\n 'method': '\t{\"get_#name#\",#apiname#,METH_VARARGS|METH_KEYWORDS,doc_#apiname#},',\n 'need': ['F_MODFUNC']\n}\n\n################\n\n\ndef buildusevars(m, r):\n ret = {}\n outmess(\n f"\t\tBuilding use variable hooks for module \"{m['name']}\" (feature only for F90/F95)...\n")\n varsmap = {}\n revmap = {}\n if 'map' in r:\n for k in r['map'].keys():\n if r['map'][k] in revmap:\n outmess('\t\t\tVariable "%s<=%s" is already mapped by "%s". Skipping.\n' % (\n r['map'][k], k, revmap[r['map'][k]]))\n else:\n revmap[r['map'][k]] = k\n if r.get('only'):\n for v in r['map'].keys():\n if r['map'][v] in m['vars']:\n\n if revmap[r['map'][v]] == v:\n varsmap[v] = r['map'][v]\n else:\n outmess(f"\t\t\tIgnoring map \"{v}=>{r['map'][v]}\". See above.\n")\n else:\n outmess(\n f"\t\t\tNo definition for variable \"{v}=>{r['map'][v]}\". Skipping.\n")\n else:\n for v in m['vars'].keys():\n varsmap[v] = revmap.get(v, v)\n for v in varsmap.keys():\n ret = dictappend(ret, buildusevar(v, varsmap[v], m['vars'], m['name']))\n return ret\n\n\ndef buildusevar(name, realname, vars, usemodulename):\n outmess('\t\t\tConstructing wrapper function for variable "%s=>%s"...\n' % (\n name, realname))\n ret = {}\n vrd = {'name': name,\n 'realname': realname,\n 'REALNAME': realname.upper(),\n 'usemodulename': usemodulename,\n 'USEMODULENAME': usemodulename.upper(),\n 'texname': name.replace('_', '\\_'),\n 'begintitle': gentitle(f'{name}=>{realname}'),\n 'endtitle': gentitle(f'end of {name}=>{realname}'),\n 'apiname': f'#modulename#_use_{realname}_from_{usemodulename}'\n }\n nummap = {0: 'Ro', 1: 'Ri', 2: 'Rii', 3: 'Riii', 4: 'Riv',\n 5: 'Rv', 6: 'Rvi', 7: 'Rvii', 8: 'Rviii', 9: 'Rix'}\n vrd['texnamename'] = name\n for i in nummap.keys():\n vrd['texnamename'] = vrd['texnamename'].replace(repr(i), nummap[i])\n if hasnote(vars[realname]):\n vrd['note'] = vars[realname]['note']\n rd = dictappend({}, vrd)\n\n print(name, realname, vars[realname])\n ret = applyrules(usemodule_rules, rd)\n return ret\n
.venv\Lib\site-packages\numpy\f2py\use_rules.py
use_rules.py
Python
3,475
0.95
0.191919
0.046512
python-kit
551
2024-12-09T12:48:35.336507
BSD-3-Clause
false
fcbb97fb4569440e51b6659cefb9288f
from collections.abc import Mapping\nfrom typing import Any, Final\n\n__version__: Final[str] = ...\nf2py_version: Final = "See `f2py -v`"\nusemodule_rules: Final[dict[str, str | list[str]]] = ...\n\ndef buildusevars(m: Mapping[str, object], r: Mapping[str, Mapping[str, object]]) -> dict[str, Any]: ...\ndef buildusevar(name: str, realname: str, vars: Mapping[str, Mapping[str, object]], usemodulename: str) -> dict[str, Any]: ...\n
.venv\Lib\site-packages\numpy\f2py\use_rules.pyi
use_rules.pyi
Other
433
0.85
0.222222
0
awesome-app
962
2023-12-21T07:16:17.967777
GPL-3.0
false
421bf151f7133ffbafe38a9c726880d2
"""\nISO_C_BINDING maps for f2py2e.\nOnly required declarations/macros/functions will be used.\n\nCopyright 1999 -- 2011 Pearu Peterson all rights reserved.\nCopyright 2011 -- present NumPy Developers.\nPermission to use, modify, and distribute this software is given under the\nterms of the NumPy License.\n\nNO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n"""\n# These map to keys in c2py_map, via forced casting for now, see gh-25229\niso_c_binding_map = {\n 'integer': {\n 'c_int': 'int',\n 'c_short': 'short', # 'short' <=> 'int' for now\n 'c_long': 'long', # 'long' <=> 'int' for now\n 'c_long_long': 'long_long',\n 'c_signed_char': 'signed_char',\n 'c_size_t': 'unsigned', # size_t <=> 'unsigned' for now\n 'c_int8_t': 'signed_char', # int8_t <=> 'signed_char' for now\n 'c_int16_t': 'short', # int16_t <=> 'short' for now\n 'c_int32_t': 'int', # int32_t <=> 'int' for now\n 'c_int64_t': 'long_long',\n 'c_int_least8_t': 'signed_char', # int_least8_t <=> 'signed_char' for now\n 'c_int_least16_t': 'short', # int_least16_t <=> 'short' for now\n 'c_int_least32_t': 'int', # int_least32_t <=> 'int' for now\n 'c_int_least64_t': 'long_long',\n 'c_int_fast8_t': 'signed_char', # int_fast8_t <=> 'signed_char' for now\n 'c_int_fast16_t': 'short', # int_fast16_t <=> 'short' for now\n 'c_int_fast32_t': 'int', # int_fast32_t <=> 'int' for now\n 'c_int_fast64_t': 'long_long',\n 'c_intmax_t': 'long_long', # intmax_t <=> 'long_long' for now\n 'c_intptr_t': 'long', # intptr_t <=> 'long' for now\n 'c_ptrdiff_t': 'long', # ptrdiff_t <=> 'long' for now\n },\n 'real': {\n 'c_float': 'float',\n 'c_double': 'double',\n 'c_long_double': 'long_double'\n },\n 'complex': {\n 'c_float_complex': 'complex_float',\n 'c_double_complex': 'complex_double',\n 'c_long_double_complex': 'complex_long_double'\n },\n 'logical': {\n 'c_bool': 'unsigned_char' # _Bool <=> 'unsigned_char' for now\n },\n 'character': {\n 'c_char': 'char'\n }\n}\n\n# TODO: See gh-25229\nisoc_c2pycode_map = {}\niso_c2py_map = {}\n\nisoc_kindmap = {}\nfor fortran_type, c_type_dict in iso_c_binding_map.items():\n for c_type in c_type_dict.keys():\n isoc_kindmap[c_type] = fortran_type\n
.venv\Lib\site-packages\numpy\f2py\_isocbind.py
_isocbind.py
Python
2,422
0.95
0.322581
0.034483
vue-tools
232
2023-08-17T18:53:57.821904
BSD-3-Clause
false
6e6cbb97e5f11d94ff8273b104deee6b
from typing import Any, Final\n\niso_c_binding_map: Final[dict[str, dict[str, str]]] = ...\n\nisoc_c2pycode_map: Final[dict[str, Any]] = {} # not implemented\niso_c2py_map: Final[dict[str, Any]] = {} # not implemented\n\nisoc_kindmap: Final[dict[str, str]] = ...\n\n# namespace pollution\nc_type: str\nc_type_dict: dict[str, str]\nfortran_type: str\n
.venv\Lib\site-packages\numpy\f2py\_isocbind.pyi
_isocbind.pyi
Other
352
0.95
0
0.111111
react-lib
644
2024-01-23T23:14:49.426398
BSD-3-Clause
false
df9736bed205b3702f00159895a6d018
import os\nimport re\n\n# START OF CODE VENDORED FROM `numpy.distutils.from_template`\n#############################################################\n"""\nprocess_file(filename)\n\n takes templated file .xxx.src and produces .xxx file where .xxx\n is .pyf .f90 or .f using the following template rules:\n\n '<..>' denotes a template.\n\n All function and subroutine blocks in a source file with names that\n contain '<..>' will be replicated according to the rules in '<..>'.\n\n The number of comma-separated words in '<..>' will determine the number of\n replicates.\n\n '<..>' may have two different forms, named and short. For example,\n\n named:\n <p=d,s,z,c> where anywhere inside a block '<p>' will be replaced with\n 'd', 's', 'z', and 'c' for each replicate of the block.\n\n <_c> is already defined: <_c=s,d,c,z>\n <_t> is already defined: <_t=real,double precision,complex,double complex>\n\n short:\n <s,d,c,z>, a short form of the named, useful when no <p> appears inside\n a block.\n\n In general, '<..>' contains a comma separated list of arbitrary\n expressions. If these expression must contain a comma|leftarrow|rightarrow,\n then prepend the comma|leftarrow|rightarrow with a backslash.\n\n If an expression matches '\\<index>' then it will be replaced\n by <index>-th expression.\n\n Note that all '<..>' forms in a block must have the same number of\n comma-separated entries.\n\n Predefined named template rules:\n <prefix=s,d,c,z>\n <ftype=real,double precision,complex,double complex>\n <ftypereal=real,double precision,\\0,\\1>\n <ctype=float,double,complex_float,complex_double>\n <ctypereal=float,double,\\0,\\1>\n"""\n\nroutine_start_re = re.compile(r'(\n|\A)(( (\$|\*))|)\s*(subroutine|function)\b', re.I)\nroutine_end_re = re.compile(r'\n\s*end\s*(subroutine|function)\b.*(\n|\Z)', re.I)\nfunction_start_re = re.compile(r'\n (\$|\*)\s*function\b', re.I)\n\ndef parse_structure(astr):\n """ Return a list of tuples for each function or subroutine each\n tuple is the start and end of a subroutine or function to be\n expanded.\n """\n\n spanlist = []\n ind = 0\n while True:\n m = routine_start_re.search(astr, ind)\n if m is None:\n break\n start = m.start()\n if function_start_re.match(astr, start, m.end()):\n while True:\n i = astr.rfind('\n', ind, start)\n if i == -1:\n break\n start = i\n if astr[i:i + 7] != '\n $':\n break\n start += 1\n m = routine_end_re.search(astr, m.end())\n ind = end = (m and m.end() - 1) or len(astr)\n spanlist.append((start, end))\n return spanlist\n\n\ntemplate_re = re.compile(r"<\s*(\w[\w\d]*)\s*>")\nnamed_re = re.compile(r"<\s*(\w[\w\d]*)\s*=\s*(.*?)\s*>")\nlist_re = re.compile(r"<\s*((.*?))\s*>")\n\ndef find_repl_patterns(astr):\n reps = named_re.findall(astr)\n names = {}\n for rep in reps:\n name = rep[0].strip() or unique_key(names)\n repl = rep[1].replace(r'\,', '@comma@')\n thelist = conv(repl)\n names[name] = thelist\n return names\n\ndef find_and_remove_repl_patterns(astr):\n names = find_repl_patterns(astr)\n astr = re.subn(named_re, '', astr)[0]\n return astr, names\n\n\nitem_re = re.compile(r"\A\\(?P<index>\d+)\Z")\ndef conv(astr):\n b = astr.split(',')\n l = [x.strip() for x in b]\n for i in range(len(l)):\n m = item_re.match(l[i])\n if m:\n j = int(m.group('index'))\n l[i] = l[j]\n return ','.join(l)\n\ndef unique_key(adict):\n """ Obtain a unique key given a dictionary."""\n allkeys = list(adict.keys())\n done = False\n n = 1\n while not done:\n newkey = f'__l{n}'\n if newkey in allkeys:\n n += 1\n else:\n done = True\n return newkey\n\n\ntemplate_name_re = re.compile(r'\A\s*(\w[\w\d]*)\s*\Z')\ndef expand_sub(substr, names):\n substr = substr.replace(r'\>', '@rightarrow@')\n substr = substr.replace(r'\<', '@leftarrow@')\n lnames = find_repl_patterns(substr)\n substr = named_re.sub(r"<\1>", substr) # get rid of definition templates\n\n def listrepl(mobj):\n thelist = conv(mobj.group(1).replace(r'\,', '@comma@'))\n if template_name_re.match(thelist):\n return f"<{thelist}>"\n name = None\n for key in lnames.keys(): # see if list is already in dictionary\n if lnames[key] == thelist:\n name = key\n if name is None: # this list is not in the dictionary yet\n name = unique_key(lnames)\n lnames[name] = thelist\n return f"<{name}>"\n\n # convert all lists to named templates\n # new names are constructed as needed\n substr = list_re.sub(listrepl, substr)\n\n numsubs = None\n base_rule = None\n rules = {}\n for r in template_re.findall(substr):\n if r not in rules:\n thelist = lnames.get(r, names.get(r, None))\n if thelist is None:\n raise ValueError(f'No replicates found for <{r}>')\n if r not in names and not thelist.startswith('_'):\n names[r] = thelist\n rule = [i.replace('@comma@', ',') for i in thelist.split(',')]\n num = len(rule)\n\n if numsubs is None:\n numsubs = num\n rules[r] = rule\n base_rule = r\n elif num == numsubs:\n rules[r] = rule\n else:\n rules_base_rule = ','.join(rules[base_rule])\n print("Mismatch in number of replacements "\n f"(base <{base_rule}={rules_base_rule}>) "\n f"for <{r}={thelist}>. Ignoring.")\n if not rules:\n return substr\n\n def namerepl(mobj):\n name = mobj.group(1)\n return rules.get(name, (k + 1) * [name])[k]\n\n newstr = ''\n for k in range(numsubs):\n newstr += template_re.sub(namerepl, substr) + '\n\n'\n\n newstr = newstr.replace('@rightarrow@', '>')\n newstr = newstr.replace('@leftarrow@', '<')\n return newstr\n\ndef process_str(allstr):\n newstr = allstr\n writestr = ''\n\n struct = parse_structure(newstr)\n\n oldend = 0\n names = {}\n names.update(_special_names)\n for sub in struct:\n cleanedstr, defs = find_and_remove_repl_patterns(newstr[oldend:sub[0]])\n writestr += cleanedstr\n names.update(defs)\n writestr += expand_sub(newstr[sub[0]:sub[1]], names)\n oldend = sub[1]\n writestr += newstr[oldend:]\n\n return writestr\n\n\ninclude_src_re = re.compile(r"(\n|\A)\s*include\s*['\"](?P<name>[\w\d./\\]+\.src)['\"]", re.I)\n\ndef resolve_includes(source):\n d = os.path.dirname(source)\n with open(source) as fid:\n lines = []\n for line in fid:\n m = include_src_re.match(line)\n if m:\n fn = m.group('name')\n if not os.path.isabs(fn):\n fn = os.path.join(d, fn)\n if os.path.isfile(fn):\n lines.extend(resolve_includes(fn))\n else:\n lines.append(line)\n else:\n lines.append(line)\n return lines\n\ndef process_file(source):\n lines = resolve_includes(source)\n return process_str(''.join(lines))\n\n\n_special_names = find_repl_patterns('''\n<_c=s,d,c,z>\n<_t=real,double precision,complex,double complex>\n<prefix=s,d,c,z>\n<ftype=real,double precision,complex,double complex>\n<ctype=float,double,complex_float,complex_double>\n<ftypereal=real,double precision,\\0,\\1>\n<ctypereal=float,double,\\0,\\1>\n''')\n\n# END OF CODE VENDORED FROM `numpy.distutils.from_template`\n###########################################################\n
.venv\Lib\site-packages\numpy\f2py\_src_pyf.py
_src_pyf.py
Python
7,942
0.95
0.206478
0.029412
python-kit
888
2024-08-24T00:28:30.646080
BSD-3-Clause
false
7d1ee9e7be0f1b34d87e5e60f48291a4
import re\nfrom collections.abc import Mapping\nfrom typing import Final\n\nfrom _typeshed import StrOrBytesPath\n\nroutine_start_re: Final[re.Pattern[str]] = ...\nroutine_end_re: Final[re.Pattern[str]] = ...\nfunction_start_re: Final[re.Pattern[str]] = ...\ntemplate_re: Final[re.Pattern[str]] = ...\nnamed_re: Final[re.Pattern[str]] = ...\nlist_re: Final[re.Pattern[str]] = ...\nitem_re: Final[re.Pattern[str]] = ...\ntemplate_name_re: Final[re.Pattern[str]] = ...\ninclude_src_re: Final[re.Pattern[str]] = ...\n\ndef parse_structure(astr: str) -> list[tuple[int, int]]: ...\ndef find_repl_patterns(astr: str) -> dict[str, str]: ...\ndef find_and_remove_repl_patterns(astr: str) -> tuple[str, dict[str, str]]: ...\ndef conv(astr: str) -> str: ...\n\n#\ndef unique_key(adict: Mapping[str, object]) -> str: ...\ndef expand_sub(substr: str, names: dict[str, str]) -> str: ...\ndef process_str(allstr: str) -> str: ...\n\n#\ndef resolve_includes(source: StrOrBytesPath) -> list[str]: ...\ndef process_file(source: StrOrBytesPath) -> str: ...\n
.venv\Lib\site-packages\numpy\f2py\_src_pyf.pyi
_src_pyf.pyi
Other
1,041
0.95
0.310345
0.083333
awesome-app
730
2025-02-07T21:57:37.311362
Apache-2.0
false
3255015854c74d8db84e785b7d964116
"""Fortran to Python Interface Generator.\n\nCopyright 1999 -- 2011 Pearu Peterson all rights reserved.\nCopyright 2011 -- present NumPy Developers.\nPermission to use, modify, and distribute this software is given under the terms\nof the NumPy License.\n\nNO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n"""\n__all__ = ['run_main', 'get_include']\n\nimport os\nimport subprocess\nimport sys\nimport warnings\n\nfrom numpy.exceptions import VisibleDeprecationWarning\n\nfrom . import diagnose, f2py2e\n\nrun_main = f2py2e.run_main\nmain = f2py2e.main\n\n\ndef get_include():\n """\n Return the directory that contains the ``fortranobject.c`` and ``.h`` files.\n\n .. note::\n\n This function is not needed when building an extension with\n `numpy.distutils` directly from ``.f`` and/or ``.pyf`` files\n in one go.\n\n Python extension modules built with f2py-generated code need to use\n ``fortranobject.c`` as a source file, and include the ``fortranobject.h``\n header. This function can be used to obtain the directory containing\n both of these files.\n\n Returns\n -------\n include_path : str\n Absolute path to the directory containing ``fortranobject.c`` and\n ``fortranobject.h``.\n\n Notes\n -----\n .. versionadded:: 1.21.1\n\n Unless the build system you are using has specific support for f2py,\n building a Python extension using a ``.pyf`` signature file is a two-step\n process. For a module ``mymod``:\n\n * Step 1: run ``python -m numpy.f2py mymod.pyf --quiet``. This\n generates ``mymodmodule.c`` and (if needed)\n ``mymod-f2pywrappers.f`` files next to ``mymod.pyf``.\n * Step 2: build your Python extension module. This requires the\n following source files:\n\n * ``mymodmodule.c``\n * ``mymod-f2pywrappers.f`` (if it was generated in Step 1)\n * ``fortranobject.c``\n\n See Also\n --------\n numpy.get_include : function that returns the numpy include directory\n\n """\n return os.path.join(os.path.dirname(__file__), 'src')\n\n\ndef __getattr__(attr):\n\n # Avoid importing things that aren't needed for building\n # which might import the main numpy module\n if attr == "test":\n from numpy._pytesttester import PytestTester\n test = PytestTester(__name__)\n return test\n\n else:\n raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")\n\n\ndef __dir__():\n return list(globals().keys() | {"test"})\n
.venv\Lib\site-packages\numpy\f2py\__init__.py
__init__.py
Python
2,534
0.95
0.127907
0.112903
vue-tools
594
2024-07-21T01:19:54.112597
Apache-2.0
false
e2ca6664e762510c283debc8cfc7fe67
from .f2py2e import main as main\nfrom .f2py2e import run_main\n\n__all__ = ["get_include", "run_main"]\n\ndef get_include() -> str: ...\n
.venv\Lib\site-packages\numpy\f2py\__init__.pyi
__init__.pyi
Other
138
0.85
0.166667
0
react-lib
184
2025-01-21T13:41:20.129222
BSD-3-Clause
false
c6fa1b9af85696dc66bc2efdaf80c4eb
# See:\n# https://web.archive.org/web/20140822061353/http://cens.ioc.ee/projects/f2py2e\nfrom numpy.f2py.f2py2e import main\n\nmain()\n
.venv\Lib\site-packages\numpy\f2py\__main__.py
__main__.py
Python
135
0.95
0
0.5
vue-tools
129
2024-07-22T08:59:20.641644
GPL-3.0
false
02435ea4a0b6bdf214bc8b8e938eecb0
from numpy.version import version # noqa: F401\n
.venv\Lib\site-packages\numpy\f2py\__version__.py
__version__.py
Python
49
0.75
0
0
python-kit
642
2024-01-30T17:36:56.773405
BSD-3-Clause
false
39ca37fc6281308b0779358aa4780e42
from numpy.version import version as version\n
.venv\Lib\site-packages\numpy\f2py\__version__.pyi
__version__.pyi
Other
46
0.65
0
0
python-kit
642
2025-02-11T05:00:59.473906
MIT
false
b5acf88d74a48f688b66a4f18fb88143
#define FORTRANOBJECT_C\n#include "fortranobject.h"\n\n#ifdef __cplusplus\nextern "C" {\n#endif\n\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\n/*\n This file implements: FortranObject, array_from_pyobj, copy_ND_array\n\n Author: Pearu Peterson <pearu@cens.ioc.ee>\n $Revision: 1.52 $\n $Date: 2005/07/11 07:44:20 $\n*/\n\nint\nF2PyDict_SetItemString(PyObject *dict, char *name, PyObject *obj)\n{\n if (obj == NULL) {\n fprintf(stderr, "Error loading %s\n", name);\n if (PyErr_Occurred()) {\n PyErr_Print();\n PyErr_Clear();\n }\n return -1;\n }\n return PyDict_SetItemString(dict, name, obj);\n}\n\n/*\n * Python-only fallback for thread-local callback pointers\n */\nvoid *\nF2PySwapThreadLocalCallbackPtr(char *key, void *ptr)\n{\n PyObject *local_dict, *value;\n void *prev;\n\n local_dict = PyThreadState_GetDict();\n if (local_dict == NULL) {\n Py_FatalError(\n "F2PySwapThreadLocalCallbackPtr: PyThreadState_GetDict "\n "failed");\n }\n\n value = PyDict_GetItemString(local_dict, key);\n if (value != NULL) {\n prev = PyLong_AsVoidPtr(value);\n if (PyErr_Occurred()) {\n Py_FatalError(\n "F2PySwapThreadLocalCallbackPtr: PyLong_AsVoidPtr failed");\n }\n }\n else {\n prev = NULL;\n }\n\n value = PyLong_FromVoidPtr((void *)ptr);\n if (value == NULL) {\n Py_FatalError(\n "F2PySwapThreadLocalCallbackPtr: PyLong_FromVoidPtr failed");\n }\n\n if (PyDict_SetItemString(local_dict, key, value) != 0) {\n Py_FatalError(\n "F2PySwapThreadLocalCallbackPtr: PyDict_SetItemString failed");\n }\n\n Py_DECREF(value);\n\n return prev;\n}\n\nvoid *\nF2PyGetThreadLocalCallbackPtr(char *key)\n{\n PyObject *local_dict, *value;\n void *prev;\n\n local_dict = PyThreadState_GetDict();\n if (local_dict == NULL) {\n Py_FatalError(\n "F2PyGetThreadLocalCallbackPtr: PyThreadState_GetDict failed");\n }\n\n value = PyDict_GetItemString(local_dict, key);\n if (value != NULL) {\n prev = PyLong_AsVoidPtr(value);\n if (PyErr_Occurred()) {\n Py_FatalError(\n "F2PyGetThreadLocalCallbackPtr: PyLong_AsVoidPtr failed");\n }\n }\n else {\n prev = NULL;\n }\n\n return prev;\n}\n\nstatic PyArray_Descr *\nget_descr_from_type_and_elsize(const int type_num, const int elsize) {\n PyArray_Descr * descr = PyArray_DescrFromType(type_num);\n if (type_num == NPY_STRING) {\n // PyArray_DescrFromType returns descr with elsize = 0.\n PyArray_DESCR_REPLACE(descr);\n if (descr == NULL) {\n return NULL;\n }\n PyDataType_SET_ELSIZE(descr, elsize);\n }\n return descr;\n}\n\n/************************* FortranObject *******************************/\n\ntypedef PyObject *(*fortranfunc)(PyObject *, PyObject *, PyObject *, void *);\n\nPyObject *\nPyFortranObject_New(FortranDataDef *defs, f2py_void_func init)\n{\n int i;\n PyFortranObject *fp = NULL;\n PyObject *v = NULL;\n if (init != NULL) { /* Initialize F90 module objects */\n (*(init))();\n }\n fp = PyObject_New(PyFortranObject, &PyFortran_Type);\n if (fp == NULL) {\n return NULL;\n }\n if ((fp->dict = PyDict_New()) == NULL) {\n Py_DECREF(fp);\n return NULL;\n }\n fp->len = 0;\n while (defs[fp->len].name != NULL) {\n fp->len++;\n }\n if (fp->len == 0) {\n goto fail;\n }\n fp->defs = defs;\n for (i = 0; i < fp->len; i++) {\n if (fp->defs[i].rank == -1) { /* Is Fortran routine */\n v = PyFortranObject_NewAsAttr(&(fp->defs[i]));\n if (v == NULL) {\n goto fail;\n }\n PyDict_SetItemString(fp->dict, fp->defs[i].name, v);\n Py_XDECREF(v);\n }\n else if ((fp->defs[i].data) !=\n NULL) { /* Is Fortran variable or array (not allocatable) */\n PyArray_Descr *\n descr = get_descr_from_type_and_elsize(fp->defs[i].type,\n fp->defs[i].elsize);\n if (descr == NULL) {\n goto fail;\n }\n v = PyArray_NewFromDescr(&PyArray_Type, descr, fp->defs[i].rank,\n fp->defs[i].dims.d, NULL, fp->defs[i].data,\n NPY_ARRAY_FARRAY, NULL);\n if (v == NULL) {\n Py_DECREF(descr);\n goto fail;\n }\n PyDict_SetItemString(fp->dict, fp->defs[i].name, v);\n Py_XDECREF(v);\n }\n }\n return (PyObject *)fp;\nfail:\n Py_XDECREF(fp);\n return NULL;\n}\n\nPyObject *\nPyFortranObject_NewAsAttr(FortranDataDef *defs)\n{ /* used for calling F90 module routines */\n PyFortranObject *fp = NULL;\n fp = PyObject_New(PyFortranObject, &PyFortran_Type);\n if (fp == NULL)\n return NULL;\n if ((fp->dict = PyDict_New()) == NULL) {\n PyObject_Del(fp);\n return NULL;\n }\n fp->len = 1;\n fp->defs = defs;\n if (defs->rank == -1) {\n PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("function %s", defs->name));\n } else if (defs->rank == 0) {\n PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("scalar %s", defs->name));\n } else {\n PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("array %s", defs->name));\n }\n return (PyObject *)fp;\n}\n\n/* Fortran methods */\n\nstatic void\nfortran_dealloc(PyFortranObject *fp)\n{\n Py_XDECREF(fp->dict);\n PyObject_Del(fp);\n}\n\n/* Returns number of bytes consumed from buf, or -1 on error. */\nstatic Py_ssize_t\nformat_def(char *buf, Py_ssize_t size, FortranDataDef def)\n{\n char *p = buf;\n int i;\n npy_intp n;\n\n n = PyOS_snprintf(p, size, "array(%" NPY_INTP_FMT, def.dims.d[0]);\n if (n < 0 || n >= size) {\n return -1;\n }\n p += n;\n size -= n;\n\n for (i = 1; i < def.rank; i++) {\n n = PyOS_snprintf(p, size, ",%" NPY_INTP_FMT, def.dims.d[i]);\n if (n < 0 || n >= size) {\n return -1;\n }\n p += n;\n size -= n;\n }\n\n if (size <= 0) {\n return -1;\n }\n\n *p++ = ')';\n size--;\n\n if (def.data == NULL) {\n static const char notalloc[] = ", not allocated";\n if ((size_t)size < sizeof(notalloc)) {\n return -1;\n }\n memcpy(p, notalloc, sizeof(notalloc));\n p += sizeof(notalloc);\n size -= sizeof(notalloc);\n }\n\n return p - buf;\n}\n\nstatic PyObject *\nfortran_doc(FortranDataDef def)\n{\n char *buf, *p;\n PyObject *s = NULL;\n Py_ssize_t n, origsize, size = 100;\n\n if (def.doc != NULL) {\n size += strlen(def.doc);\n }\n origsize = size;\n buf = p = (char *)PyMem_Malloc(size);\n if (buf == NULL) {\n return PyErr_NoMemory();\n }\n\n if (def.rank == -1) {\n if (def.doc) {\n n = strlen(def.doc);\n if (n > size) {\n goto fail;\n }\n memcpy(p, def.doc, n);\n p += n;\n size -= n;\n }\n else {\n n = PyOS_snprintf(p, size, "%s - no docs available", def.name);\n if (n < 0 || n >= size) {\n goto fail;\n }\n p += n;\n size -= n;\n }\n }\n else {\n PyArray_Descr *d = PyArray_DescrFromType(def.type);\n n = PyOS_snprintf(p, size, "%s : '%c'-", def.name, d->type);\n Py_DECREF(d);\n if (n < 0 || n >= size) {\n goto fail;\n }\n p += n;\n size -= n;\n\n if (def.data == NULL) {\n n = format_def(p, size, def);\n if (n < 0) {\n goto fail;\n }\n p += n;\n size -= n;\n }\n else if (def.rank > 0) {\n n = format_def(p, size, def);\n if (n < 0) {\n goto fail;\n }\n p += n;\n size -= n;\n }\n else {\n n = strlen("scalar");\n if (size < n) {\n goto fail;\n }\n memcpy(p, "scalar", n);\n p += n;\n size -= n;\n }\n }\n if (size <= 1) {\n goto fail;\n }\n *p++ = '\n';\n size--;\n\n /* p now points one beyond the last character of the string in buf */\n s = PyUnicode_FromStringAndSize(buf, p - buf);\n\n PyMem_Free(buf);\n return s;\n\nfail:\n fprintf(stderr,\n "fortranobject.c: fortran_doc: len(p)=%zd>%zd=size:"\n " too long docstring required, increase size\n",\n p - buf, origsize);\n PyMem_Free(buf);\n return NULL;\n}\n\nstatic FortranDataDef *save_def; /* save pointer of an allocatable array */\nstatic void\nset_data(char *d, npy_intp *f)\n{ /* callback from Fortran */\n if (*f) /* In fortran f=allocated(d) */\n save_def->data = d;\n else\n save_def->data = NULL;\n /* printf("set_data: d=%p,f=%d\n",d,*f); */\n}\n\nstatic PyObject *\nfortran_getattr(PyFortranObject *fp, char *name)\n{\n int i, j, k, flag;\n if (fp->dict != NULL) {\n // python 3.13 added PyDict_GetItemRef\n#if PY_VERSION_HEX < 0x030D0000\n PyObject *v = _PyDict_GetItemStringWithError(fp->dict, name);\n if (v == NULL && PyErr_Occurred()) {\n return NULL;\n }\n else if (v != NULL) {\n Py_INCREF(v);\n return v;\n }\n#else\n PyObject *v;\n int result = PyDict_GetItemStringRef(fp->dict, name, &v);\n if (result == -1) {\n return NULL;\n }\n else if (result == 1) {\n return v;\n }\n#endif\n\n }\n for (i = 0, j = 1; i < fp->len && (j = strcmp(name, fp->defs[i].name));\n i++)\n ;\n if (j == 0)\n if (fp->defs[i].rank != -1) { /* F90 allocatable array */\n if (fp->defs[i].func == NULL)\n return NULL;\n for (k = 0; k < fp->defs[i].rank; ++k) fp->defs[i].dims.d[k] = -1;\n save_def = &fp->defs[i];\n (*(fp->defs[i].func))(&fp->defs[i].rank, fp->defs[i].dims.d,\n set_data, &flag);\n if (flag == 2)\n k = fp->defs[i].rank + 1;\n else\n k = fp->defs[i].rank;\n if (fp->defs[i].data != NULL) { /* array is allocated */\n PyObject *v = PyArray_New(\n &PyArray_Type, k, fp->defs[i].dims.d, fp->defs[i].type,\n NULL, fp->defs[i].data, 0, NPY_ARRAY_FARRAY, NULL);\n if (v == NULL)\n return NULL;\n /* Py_INCREF(v); */\n return v;\n }\n else { /* array is not allocated */\n Py_RETURN_NONE;\n }\n }\n if (strcmp(name, "__dict__") == 0) {\n Py_INCREF(fp->dict);\n return fp->dict;\n }\n if (strcmp(name, "__doc__") == 0) {\n PyObject *s = PyUnicode_FromString(""), *s2, *s3;\n for (i = 0; i < fp->len; i++) {\n s2 = fortran_doc(fp->defs[i]);\n s3 = PyUnicode_Concat(s, s2);\n Py_DECREF(s2);\n Py_DECREF(s);\n s = s3;\n }\n if (PyDict_SetItemString(fp->dict, name, s))\n return NULL;\n return s;\n }\n if ((strcmp(name, "_cpointer") == 0) && (fp->len == 1)) {\n PyObject *cobj =\n F2PyCapsule_FromVoidPtr((void *)(fp->defs[0].data), NULL);\n if (PyDict_SetItemString(fp->dict, name, cobj))\n return NULL;\n return cobj;\n }\n PyObject *str, *ret;\n str = PyUnicode_FromString(name);\n ret = PyObject_GenericGetAttr((PyObject *)fp, str);\n Py_DECREF(str);\n return ret;\n}\n\nstatic int\nfortran_setattr(PyFortranObject *fp, char *name, PyObject *v)\n{\n int i, j, flag;\n PyArrayObject *arr = NULL;\n for (i = 0, j = 1; i < fp->len && (j = strcmp(name, fp->defs[i].name));\n i++)\n ;\n if (j == 0) {\n if (fp->defs[i].rank == -1) {\n PyErr_SetString(PyExc_AttributeError,\n "over-writing fortran routine");\n return -1;\n }\n if (fp->defs[i].func != NULL) { /* is allocatable array */\n npy_intp dims[F2PY_MAX_DIMS];\n int k;\n save_def = &fp->defs[i];\n if (v != Py_None) { /* set new value (reallocate if needed --\n see f2py generated code for more\n details ) */\n for (k = 0; k < fp->defs[i].rank; k++) dims[k] = -1;\n if ((arr = array_from_pyobj(fp->defs[i].type, dims,\n fp->defs[i].rank, F2PY_INTENT_IN,\n v)) == NULL)\n return -1;\n (*(fp->defs[i].func))(&fp->defs[i].rank, PyArray_DIMS(arr),\n set_data, &flag);\n }\n else { /* deallocate */\n for (k = 0; k < fp->defs[i].rank; k++) dims[k] = 0;\n (*(fp->defs[i].func))(&fp->defs[i].rank, dims, set_data,\n &flag);\n for (k = 0; k < fp->defs[i].rank; k++) dims[k] = -1;\n }\n memcpy(fp->defs[i].dims.d, dims,\n fp->defs[i].rank * sizeof(npy_intp));\n }\n else { /* not allocatable array */\n if ((arr = array_from_pyobj(fp->defs[i].type, fp->defs[i].dims.d,\n fp->defs[i].rank, F2PY_INTENT_IN,\n v)) == NULL)\n return -1;\n }\n if (fp->defs[i].data !=\n NULL) { /* copy Python object to Fortran array */\n npy_intp s = PyArray_MultiplyList(fp->defs[i].dims.d,\n PyArray_NDIM(arr));\n if (s == -1)\n s = PyArray_MultiplyList(PyArray_DIMS(arr), PyArray_NDIM(arr));\n if (s < 0 || (memcpy(fp->defs[i].data, PyArray_DATA(arr),\n s * PyArray_ITEMSIZE(arr))) == NULL) {\n if ((PyObject *)arr != v) {\n Py_DECREF(arr);\n }\n return -1;\n }\n if ((PyObject *)arr != v) {\n Py_DECREF(arr);\n }\n }\n else\n return (fp->defs[i].func == NULL ? -1 : 0);\n return 0; /* successful */\n }\n if (fp->dict == NULL) {\n fp->dict = PyDict_New();\n if (fp->dict == NULL)\n return -1;\n }\n if (v == NULL) {\n int rv = PyDict_DelItemString(fp->dict, name);\n if (rv < 0)\n PyErr_SetString(PyExc_AttributeError,\n "delete non-existing fortran attribute");\n return rv;\n }\n else\n return PyDict_SetItemString(fp->dict, name, v);\n}\n\nstatic PyObject *\nfortran_call(PyFortranObject *fp, PyObject *arg, PyObject *kw)\n{\n int i = 0;\n /* printf("fortran call\n name=%s,func=%p,data=%p,%p\n",fp->defs[i].name,\n fp->defs[i].func,fp->defs[i].data,&fp->defs[i].data); */\n if (fp->defs[i].rank == -1) { /* is Fortran routine */\n if (fp->defs[i].func == NULL) {\n PyErr_Format(PyExc_RuntimeError, "no function to call");\n return NULL;\n }\n else if (fp->defs[i].data == NULL)\n /* dummy routine */\n return (*((fortranfunc)(fp->defs[i].func)))((PyObject *)fp, arg,\n kw, NULL);\n else\n return (*((fortranfunc)(fp->defs[i].func)))(\n (PyObject *)fp, arg, kw, (void *)fp->defs[i].data);\n }\n PyErr_Format(PyExc_TypeError, "this fortran object is not callable");\n return NULL;\n}\n\nstatic PyObject *\nfortran_repr(PyFortranObject *fp)\n{\n PyObject *name = NULL, *repr = NULL;\n name = PyObject_GetAttrString((PyObject *)fp, "__name__");\n PyErr_Clear();\n if (name != NULL && PyUnicode_Check(name)) {\n repr = PyUnicode_FromFormat("<fortran %U>", name);\n }\n else {\n repr = PyUnicode_FromString("<fortran object>");\n }\n Py_XDECREF(name);\n return repr;\n}\n\nPyTypeObject PyFortran_Type = {\n PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fortran",\n .tp_basicsize = sizeof(PyFortranObject),\n .tp_dealloc = (destructor)fortran_dealloc,\n .tp_getattr = (getattrfunc)fortran_getattr,\n .tp_setattr = (setattrfunc)fortran_setattr,\n .tp_repr = (reprfunc)fortran_repr,\n .tp_call = (ternaryfunc)fortran_call,\n};\n\n/************************* f2py_report_atexit *******************************/\n\n#ifdef F2PY_REPORT_ATEXIT\nstatic int passed_time = 0;\nstatic int passed_counter = 0;\nstatic int passed_call_time = 0;\nstatic struct timeb start_time;\nstatic struct timeb stop_time;\nstatic struct timeb start_call_time;\nstatic struct timeb stop_call_time;\nstatic int cb_passed_time = 0;\nstatic int cb_passed_counter = 0;\nstatic int cb_passed_call_time = 0;\nstatic struct timeb cb_start_time;\nstatic struct timeb cb_stop_time;\nstatic struct timeb cb_start_call_time;\nstatic struct timeb cb_stop_call_time;\n\nextern void\nf2py_start_clock(void)\n{\n ftime(&start_time);\n}\nextern void\nf2py_start_call_clock(void)\n{\n f2py_stop_clock();\n ftime(&start_call_time);\n}\nextern void\nf2py_stop_clock(void)\n{\n ftime(&stop_time);\n passed_time += 1000 * (stop_time.time - start_time.time);\n passed_time += stop_time.millitm - start_time.millitm;\n}\nextern void\nf2py_stop_call_clock(void)\n{\n ftime(&stop_call_time);\n passed_call_time += 1000 * (stop_call_time.time - start_call_time.time);\n passed_call_time += stop_call_time.millitm - start_call_time.millitm;\n passed_counter += 1;\n f2py_start_clock();\n}\n\nextern void\nf2py_cb_start_clock(void)\n{\n ftime(&cb_start_time);\n}\nextern void\nf2py_cb_start_call_clock(void)\n{\n f2py_cb_stop_clock();\n ftime(&cb_start_call_time);\n}\nextern void\nf2py_cb_stop_clock(void)\n{\n ftime(&cb_stop_time);\n cb_passed_time += 1000 * (cb_stop_time.time - cb_start_time.time);\n cb_passed_time += cb_stop_time.millitm - cb_start_time.millitm;\n}\nextern void\nf2py_cb_stop_call_clock(void)\n{\n ftime(&cb_stop_call_time);\n cb_passed_call_time +=\n 1000 * (cb_stop_call_time.time - cb_start_call_time.time);\n cb_passed_call_time +=\n cb_stop_call_time.millitm - cb_start_call_time.millitm;\n cb_passed_counter += 1;\n f2py_cb_start_clock();\n}\n\nstatic int f2py_report_on_exit_been_here = 0;\nextern void\nf2py_report_on_exit(int exit_flag, void *name)\n{\n if (f2py_report_on_exit_been_here) {\n fprintf(stderr, " %s\n", (char *)name);\n return;\n }\n f2py_report_on_exit_been_here = 1;\n fprintf(stderr, " /-----------------------\\\n");\n fprintf(stderr, " < F2PY performance report >\n");\n fprintf(stderr, " \\-----------------------/\n");\n fprintf(stderr, "Overall time spent in ...\n");\n fprintf(stderr, "(a) wrapped (Fortran/C) functions : %8d msec\n",\n passed_call_time);\n fprintf(stderr, "(b) f2py interface, %6d calls : %8d msec\n",\n passed_counter, passed_time);\n fprintf(stderr, "(c) call-back (Python) functions : %8d msec\n",\n cb_passed_call_time);\n fprintf(stderr, "(d) f2py call-back interface, %6d calls : %8d msec\n",\n cb_passed_counter, cb_passed_time);\n\n fprintf(stderr,\n "(e) wrapped (Fortran/C) functions (actual) : %8d msec\n\n",\n passed_call_time - cb_passed_call_time - cb_passed_time);\n fprintf(stderr,\n "Use -DF2PY_REPORT_ATEXIT_DISABLE to disable this message.\n");\n fprintf(stderr, "Exit status: %d\n", exit_flag);\n fprintf(stderr, "Modules : %s\n", (char *)name);\n}\n#endif\n\n/********************** report on array copy ****************************/\n\n#ifdef F2PY_REPORT_ON_ARRAY_COPY\nstatic void\nf2py_report_on_array_copy(PyArrayObject *arr)\n{\n const npy_intp arr_size = PyArray_Size((PyObject *)arr);\n if (arr_size > F2PY_REPORT_ON_ARRAY_COPY) {\n fprintf(stderr,\n "copied an array: size=%ld, elsize=%" NPY_INTP_FMT "\n",\n arr_size, (npy_intp)PyArray_ITEMSIZE(arr));\n }\n}\nstatic void\nf2py_report_on_array_copy_fromany(void)\n{\n fprintf(stderr, "created an array from object\n");\n}\n\n#define F2PY_REPORT_ON_ARRAY_COPY_FROMARR \\n f2py_report_on_array_copy((PyArrayObject *)arr)\n#define F2PY_REPORT_ON_ARRAY_COPY_FROMANY f2py_report_on_array_copy_fromany()\n#else\n#define F2PY_REPORT_ON_ARRAY_COPY_FROMARR\n#define F2PY_REPORT_ON_ARRAY_COPY_FROMANY\n#endif\n\n/************************* array_from_obj *******************************/\n\n/*\n * File: array_from_pyobj.c\n *\n * Description:\n * ------------\n * Provides array_from_pyobj function that returns a contiguous array\n * object with the given dimensions and required storage order, either\n * in row-major (C) or column-major (Fortran) order. The function\n * array_from_pyobj is very flexible about its Python object argument\n * that can be any number, list, tuple, or array.\n *\n * array_from_pyobj is used in f2py generated Python extension\n * modules.\n *\n * Author: Pearu Peterson <pearu@cens.ioc.ee>\n * Created: 13-16 January 2002\n * $Id: fortranobject.c,v 1.52 2005/07/11 07:44:20 pearu Exp $\n */\n\nstatic int check_and_fix_dimensions(const PyArrayObject* arr,\n const int rank,\n npy_intp *dims,\n const char *errmess);\n\nstatic int\nfind_first_negative_dimension(const int rank, const npy_intp *dims)\n{\n int i;\n for (i = 0; i < rank; ++i) {\n if (dims[i] < 0) {\n return i;\n }\n }\n return -1;\n}\n\n#ifdef DEBUG_COPY_ND_ARRAY\nvoid\ndump_dims(int rank, npy_intp const *dims)\n{\n int i;\n printf("[");\n for (i = 0; i < rank; ++i) {\n printf("%3" NPY_INTP_FMT, dims[i]);\n }\n printf("]\n");\n}\nvoid\ndump_attrs(const PyArrayObject *obj)\n{\n const PyArrayObject_fields *arr = (const PyArrayObject_fields *)obj;\n int rank = PyArray_NDIM(arr);\n npy_intp size = PyArray_Size((PyObject *)arr);\n printf("\trank = %d, flags = %d, size = %" NPY_INTP_FMT "\n", rank,\n arr->flags, size);\n printf("\tstrides = ");\n dump_dims(rank, arr->strides);\n printf("\tdimensions = ");\n dump_dims(rank, arr->dimensions);\n}\n#endif\n\n#define SWAPTYPE(a, b, t) \\n { \\n t c; \\n c = (a); \\n (a) = (b); \\n (b) = c; \\n }\n\nstatic int\nswap_arrays(PyArrayObject *obj1, PyArrayObject *obj2)\n{\n PyArrayObject_fields *arr1 = (PyArrayObject_fields *)obj1,\n *arr2 = (PyArrayObject_fields *)obj2;\n SWAPTYPE(arr1->data, arr2->data, char *);\n SWAPTYPE(arr1->nd, arr2->nd, int);\n SWAPTYPE(arr1->dimensions, arr2->dimensions, npy_intp *);\n SWAPTYPE(arr1->strides, arr2->strides, npy_intp *);\n SWAPTYPE(arr1->base, arr2->base, PyObject *);\n SWAPTYPE(arr1->descr, arr2->descr, PyArray_Descr *);\n SWAPTYPE(arr1->flags, arr2->flags, int);\n /* SWAPTYPE(arr1->weakreflist,arr2->weakreflist,PyObject*); */\n return 0;\n}\n\n#define ARRAY_ISCOMPATIBLE(arr,type_num) \\n ((PyArray_ISINTEGER(arr) && PyTypeNum_ISINTEGER(type_num)) || \\n (PyArray_ISFLOAT(arr) && PyTypeNum_ISFLOAT(type_num)) || \\n (PyArray_ISCOMPLEX(arr) && PyTypeNum_ISCOMPLEX(type_num)) || \\n (PyArray_ISBOOL(arr) && PyTypeNum_ISBOOL(type_num)) || \\n (PyArray_ISSTRING(arr) && PyTypeNum_ISSTRING(type_num)))\n\nstatic int\nget_elsize(PyObject *obj) {\n /*\n get_elsize determines array itemsize from a Python object. Returns\n elsize if successful, -1 otherwise.\n\n Supported types of the input are: numpy.ndarray, bytes, str, tuple,\n list.\n */\n\n if (PyArray_Check(obj)) {\n return PyArray_ITEMSIZE((PyArrayObject *)obj);\n } else if (PyBytes_Check(obj)) {\n return PyBytes_GET_SIZE(obj);\n } else if (PyUnicode_Check(obj)) {\n return PyUnicode_GET_LENGTH(obj);\n } else if (PySequence_Check(obj)) {\n PyObject* fast = PySequence_Fast(obj, "f2py:fortranobject.c:get_elsize");\n if (fast != NULL) {\n Py_ssize_t i, n = PySequence_Fast_GET_SIZE(fast);\n int sz, elsize = 0;\n for (i=0; i<n; i++) {\n sz = get_elsize(PySequence_Fast_GET_ITEM(fast, i) /* borrowed */);\n if (sz > elsize) {\n elsize = sz;\n }\n }\n Py_DECREF(fast);\n return elsize;\n }\n }\n return -1;\n}\n\nextern PyArrayObject *\nndarray_from_pyobj(const int type_num,\n const int elsize_,\n npy_intp *dims,\n const int rank,\n const int intent,\n PyObject *obj,\n const char *errmess) {\n /*\n * Return an array with given element type and shape from a Python\n * object while taking into account the usage intent of the array.\n *\n * - element type is defined by type_num and elsize\n * - shape is defined by dims and rank\n *\n * ndarray_from_pyobj is used to convert Python object arguments\n * to numpy ndarrays with given type and shape that data is passed\n * to interfaced Fortran or C functions.\n *\n * errmess (if not NULL), contains a prefix of an error message\n * for an exception to be triggered within this function.\n *\n * Negative elsize value means that elsize is to be determined\n * from the Python object in runtime.\n *\n * Note on strings\n * ---------------\n *\n * String type (type_num == NPY_STRING) does not have fixed\n * element size and, by default, the type object sets it to\n * 0. Therefore, for string types, one has to use elsize\n * argument. For other types, elsize value is ignored.\n *\n * NumPy defines the type of a fixed-width string as\n * dtype('S<width>'). In addition, there is also dtype('c'), that\n * appears as dtype('S1') (these have the same type_num value),\n * but is actually different (.char attribute is either 'S' or\n * 'c', respectively).\n *\n * In Fortran, character arrays and strings are different\n * concepts. The relation between Fortran types, NumPy dtypes,\n * and type_num-elsize pairs, is defined as follows:\n *\n * character*5 foo | dtype('S5') | elsize=5, shape=()\n * character(5) foo | dtype('S1') | elsize=1, shape=(5)\n * character*5 foo(n) | dtype('S5') | elsize=5, shape=(n,)\n * character(5) foo(n) | dtype('S1') | elsize=1, shape=(5, n)\n * character*(*) foo | dtype('S') | elsize=-1, shape=()\n *\n * Note about reference counting\n * -----------------------------\n *\n * If the caller returns the array to Python, it must be done with\n * Py_BuildValue("N",arr). Otherwise, if obj!=arr then the caller\n * must call Py_DECREF(arr).\n *\n * Note on intent(cache,out,..)\n * ----------------------------\n * Don't expect correct data when returning intent(cache) array.\n *\n */\n char mess[F2PY_MESSAGE_BUFFER_SIZE];\n PyArrayObject *arr = NULL;\n int elsize = (elsize_ < 0 ? get_elsize(obj) : elsize_);\n if (elsize < 0) {\n if (errmess != NULL) {\n strcpy(mess, errmess);\n }\n sprintf(mess + strlen(mess),\n " -- failed to determine element size from %s",\n Py_TYPE(obj)->tp_name);\n PyErr_SetString(PyExc_SystemError, mess);\n return NULL;\n }\n PyArray_Descr * descr = get_descr_from_type_and_elsize(type_num, elsize); // new reference\n if (descr == NULL) {\n return NULL;\n }\n elsize = PyDataType_ELSIZE(descr);\n if ((intent & F2PY_INTENT_HIDE)\n || ((intent & F2PY_INTENT_CACHE) && (obj == Py_None))\n || ((intent & F2PY_OPTIONAL) && (obj == Py_None))\n ) {\n /* intent(cache), optional, intent(hide) */\n int ineg = find_first_negative_dimension(rank, dims);\n if (ineg >= 0) {\n int i;\n strcpy(mess, "failed to create intent(cache|hide)|optional array"\n "-- must have defined dimensions but got (");\n for(i = 0; i < rank; ++i)\n sprintf(mess + strlen(mess), "%" NPY_INTP_FMT ",", dims[i]);\n strcat(mess, ")");\n PyErr_SetString(PyExc_ValueError, mess);\n Py_DECREF(descr);\n return NULL;\n }\n arr = (PyArrayObject *) \\n PyArray_NewFromDescr(&PyArray_Type, descr, rank, dims,\n NULL, NULL, !(intent & F2PY_INTENT_C), NULL);\n if (arr == NULL) {\n Py_DECREF(descr);\n return NULL;\n }\n if (PyArray_ITEMSIZE(arr) != elsize) {\n strcpy(mess, "failed to create intent(cache|hide)|optional array");\n sprintf(mess+strlen(mess)," -- expected elsize=%d got %" NPY_INTP_FMT, elsize, (npy_intp)PyArray_ITEMSIZE(arr));\n PyErr_SetString(PyExc_ValueError,mess);\n Py_DECREF(arr);\n return NULL;\n }\n if (!(intent & F2PY_INTENT_CACHE)) {\n PyArray_FILLWBYTE(arr, 0);\n }\n return arr;\n }\n\n if (PyArray_Check(obj)) {\n arr = (PyArrayObject *)obj;\n if (intent & F2PY_INTENT_CACHE) {\n /* intent(cache) */\n if (PyArray_ISONESEGMENT(arr)\n && PyArray_ITEMSIZE(arr) >= elsize) {\n if (check_and_fix_dimensions(arr, rank, dims, errmess)) {\n Py_DECREF(descr);\n return NULL;\n }\n if (intent & F2PY_INTENT_OUT)\n Py_INCREF(arr);\n Py_DECREF(descr);\n return arr;\n }\n strcpy(mess, "failed to initialize intent(cache) array");\n if (!PyArray_ISONESEGMENT(arr))\n strcat(mess, " -- input must be in one segment");\n if (PyArray_ITEMSIZE(arr) < elsize)\n sprintf(mess + strlen(mess),\n " -- expected at least elsize=%d but got "\n "%" NPY_INTP_FMT,\n elsize, (npy_intp)PyArray_ITEMSIZE(arr));\n PyErr_SetString(PyExc_ValueError, mess);\n Py_DECREF(descr);\n return NULL;\n }\n\n /* here we have always intent(in) or intent(inout) or intent(inplace)\n */\n\n if (check_and_fix_dimensions(arr, rank, dims, errmess)) {\n Py_DECREF(descr);\n return NULL;\n }\n /*\n printf("intent alignment=%d\n", F2PY_GET_ALIGNMENT(intent));\n printf("alignment check=%d\n", F2PY_CHECK_ALIGNMENT(arr, intent));\n int i;\n for (i=1;i<=16;i++)\n printf("i=%d isaligned=%d\n", i, ARRAY_ISALIGNED(arr, i));\n */\n if ((! (intent & F2PY_INTENT_COPY)) &&\n PyArray_ITEMSIZE(arr) == elsize &&\n ARRAY_ISCOMPATIBLE(arr,type_num) &&\n F2PY_CHECK_ALIGNMENT(arr, intent)) {\n if ((intent & F2PY_INTENT_INOUT || intent & F2PY_INTENT_INPLACE)\n ? ((intent & F2PY_INTENT_C) ? PyArray_ISCARRAY(arr) : PyArray_ISFARRAY(arr))\n : ((intent & F2PY_INTENT_C) ? PyArray_ISCARRAY_RO(arr) : PyArray_ISFARRAY_RO(arr))) {\n if ((intent & F2PY_INTENT_OUT)) {\n Py_INCREF(arr);\n }\n /* Returning input array */\n Py_DECREF(descr);\n return arr;\n }\n }\n if (intent & F2PY_INTENT_INOUT) {\n strcpy(mess, "failed to initialize intent(inout) array");\n /* Must use PyArray_IS*ARRAY because intent(inout) requires\n * writable input */\n if ((intent & F2PY_INTENT_C) && !PyArray_ISCARRAY(arr))\n strcat(mess, " -- input not contiguous");\n if (!(intent & F2PY_INTENT_C) && !PyArray_ISFARRAY(arr))\n strcat(mess, " -- input not fortran contiguous");\n if (PyArray_ITEMSIZE(arr) != elsize)\n sprintf(mess + strlen(mess),\n " -- expected elsize=%d but got %" NPY_INTP_FMT,\n elsize,\n (npy_intp)PyArray_ITEMSIZE(arr)\n );\n if (!(ARRAY_ISCOMPATIBLE(arr, type_num))) {\n sprintf(mess + strlen(mess),\n " -- input '%c' not compatible to '%c'",\n PyArray_DESCR(arr)->type, descr->type);\n }\n if (!(F2PY_CHECK_ALIGNMENT(arr, intent)))\n sprintf(mess + strlen(mess), " -- input not %d-aligned",\n F2PY_GET_ALIGNMENT(intent));\n PyErr_SetString(PyExc_ValueError, mess);\n Py_DECREF(descr);\n return NULL;\n }\n\n /* here we have always intent(in) or intent(inplace) */\n\n {\n PyArrayObject * retarr = (PyArrayObject *) \\n PyArray_NewFromDescr(&PyArray_Type, descr, PyArray_NDIM(arr), PyArray_DIMS(arr),\n NULL, NULL, !(intent & F2PY_INTENT_C), NULL);\n if (retarr==NULL) {\n Py_DECREF(descr);\n return NULL;\n }\n F2PY_REPORT_ON_ARRAY_COPY_FROMARR;\n if (PyArray_CopyInto(retarr, arr)) {\n Py_DECREF(retarr);\n return NULL;\n }\n if (intent & F2PY_INTENT_INPLACE) {\n if (swap_arrays(arr,retarr)) {\n Py_DECREF(retarr);\n return NULL; /* XXX: set exception */\n }\n Py_XDECREF(retarr);\n if (intent & F2PY_INTENT_OUT)\n Py_INCREF(arr);\n } else {\n arr = retarr;\n }\n }\n return arr;\n }\n\n if ((intent & F2PY_INTENT_INOUT) || (intent & F2PY_INTENT_INPLACE) ||\n (intent & F2PY_INTENT_CACHE)) {\n PyErr_Format(PyExc_TypeError,\n "failed to initialize intent(inout|inplace|cache) "\n "array, input '%s' object is not an array",\n Py_TYPE(obj)->tp_name);\n Py_DECREF(descr);\n return NULL;\n }\n\n {\n F2PY_REPORT_ON_ARRAY_COPY_FROMANY;\n arr = (PyArrayObject *)PyArray_FromAny(\n obj, descr, 0, 0,\n ((intent & F2PY_INTENT_C) ? NPY_ARRAY_CARRAY\n : NPY_ARRAY_FARRAY) |\n NPY_ARRAY_FORCECAST,\n NULL);\n // Warning: in the case of NPY_STRING, PyArray_FromAny may\n // reset descr->elsize, e.g. dtype('S0') becomes dtype('S1').\n if (arr == NULL) {\n Py_DECREF(descr);\n return NULL;\n }\n if (type_num != NPY_STRING && PyArray_ITEMSIZE(arr) != elsize) {\n // This is internal sanity tests: elsize has been set to\n // descr->elsize in the beginning of this function.\n strcpy(mess, "failed to initialize intent(in) array");\n sprintf(mess + strlen(mess),\n " -- expected elsize=%d got %" NPY_INTP_FMT, elsize,\n (npy_intp)PyArray_ITEMSIZE(arr));\n PyErr_SetString(PyExc_ValueError, mess);\n Py_DECREF(arr);\n return NULL;\n }\n if (check_and_fix_dimensions(arr, rank, dims, errmess)) {\n Py_DECREF(arr);\n return NULL;\n }\n return arr;\n }\n}\n\nextern PyArrayObject *\narray_from_pyobj(const int type_num,\n npy_intp *dims,\n const int rank,\n const int intent,\n PyObject *obj) {\n /*\n Same as ndarray_from_pyobj but with elsize determined from type,\n if possible. Provided for backward compatibility.\n */\n PyArray_Descr* descr = PyArray_DescrFromType(type_num);\n int elsize = PyDataType_ELSIZE(descr);\n Py_DECREF(descr);\n return ndarray_from_pyobj(type_num, elsize, dims, rank, intent, obj, NULL);\n}\n\n/*****************************************/\n/* Helper functions for array_from_pyobj */\n/*****************************************/\n\nstatic int\ncheck_and_fix_dimensions(const PyArrayObject* arr, const int rank,\n npy_intp *dims, const char *errmess)\n{\n /*\n * This function fills in blanks (that are -1's) in dims list using\n * the dimensions from arr. It also checks that non-blank dims will\n * match with the corresponding values in arr dimensions.\n *\n * Returns 0 if the function is successful.\n *\n * If an error condition is detected, an exception is set and 1 is\n * returned.\n */\n char mess[F2PY_MESSAGE_BUFFER_SIZE];\n const npy_intp arr_size =\n (PyArray_NDIM(arr)) ? PyArray_Size((PyObject *)arr) : 1;\n#ifdef DEBUG_COPY_ND_ARRAY\n dump_attrs(arr);\n printf("check_and_fix_dimensions:init: dims=");\n dump_dims(rank, dims);\n#endif\n if (rank > PyArray_NDIM(arr)) { /* [1,2] -> [[1],[2]]; 1 -> [[1]] */\n npy_intp new_size = 1;\n int free_axe = -1;\n int i;\n npy_intp d;\n /* Fill dims where -1 or 0; check dimensions; calc new_size; */\n for (i = 0; i < PyArray_NDIM(arr); ++i) {\n d = PyArray_DIM(arr, i);\n if (dims[i] >= 0) {\n if (d > 1 && dims[i] != d) {\n PyErr_Format(\n PyExc_ValueError,\n "%d-th dimension must be fixed to %" NPY_INTP_FMT\n " but got %" NPY_INTP_FMT "\n",\n i, dims[i], d);\n return 1;\n }\n if (!dims[i])\n dims[i] = 1;\n }\n else {\n dims[i] = d ? d : 1;\n }\n new_size *= dims[i];\n }\n for (i = PyArray_NDIM(arr); i < rank; ++i)\n if (dims[i] > 1) {\n PyErr_Format(PyExc_ValueError,\n "%d-th dimension must be %" NPY_INTP_FMT\n " but got 0 (not defined).\n",\n i, dims[i]);\n return 1;\n }\n else if (free_axe < 0)\n free_axe = i;\n else\n dims[i] = 1;\n if (free_axe >= 0) {\n dims[free_axe] = arr_size / new_size;\n new_size *= dims[free_axe];\n }\n if (new_size != arr_size) {\n PyErr_Format(PyExc_ValueError,\n "unexpected array size: new_size=%" NPY_INTP_FMT\n ", got array with arr_size=%" NPY_INTP_FMT\n " (maybe too many free indices)\n",\n new_size, arr_size);\n return 1;\n }\n }\n else if (rank == PyArray_NDIM(arr)) {\n npy_intp new_size = 1;\n int i;\n npy_intp d;\n for (i = 0; i < rank; ++i) {\n d = PyArray_DIM(arr, i);\n if (dims[i] >= 0) {\n if (d > 1 && d != dims[i]) {\n if (errmess != NULL) {\n strcpy(mess, errmess);\n }\n sprintf(mess + strlen(mess),\n " -- %d-th dimension must be fixed to %"\n NPY_INTP_FMT " but got %" NPY_INTP_FMT,\n i, dims[i], d);\n PyErr_SetString(PyExc_ValueError, mess);\n return 1;\n }\n if (!dims[i])\n dims[i] = 1;\n }\n else\n dims[i] = d;\n new_size *= dims[i];\n }\n if (new_size != arr_size) {\n PyErr_Format(PyExc_ValueError,\n "unexpected array size: new_size=%" NPY_INTP_FMT\n ", got array with arr_size=%" NPY_INTP_FMT "\n",\n new_size, arr_size);\n return 1;\n }\n }\n else { /* [[1,2]] -> [[1],[2]] */\n int i, j;\n npy_intp d;\n int effrank;\n npy_intp size;\n for (i = 0, effrank = 0; i < PyArray_NDIM(arr); ++i)\n if (PyArray_DIM(arr, i) > 1)\n ++effrank;\n if (dims[rank - 1] >= 0)\n if (effrank > rank) {\n PyErr_Format(PyExc_ValueError,\n "too many axes: %d (effrank=%d), "\n "expected rank=%d\n",\n PyArray_NDIM(arr), effrank, rank);\n return 1;\n }\n\n for (i = 0, j = 0; i < rank; ++i) {\n while (j < PyArray_NDIM(arr) && PyArray_DIM(arr, j) < 2) ++j;\n if (j >= PyArray_NDIM(arr))\n d = 1;\n else\n d = PyArray_DIM(arr, j++);\n if (dims[i] >= 0) {\n if (d > 1 && d != dims[i]) {\n if (errmess != NULL) {\n strcpy(mess, errmess);\n }\n sprintf(mess + strlen(mess),\n " -- %d-th dimension must be fixed to %"\n NPY_INTP_FMT " but got %" NPY_INTP_FMT\n " (real index=%d)\n",\n i, dims[i], d, j-1);\n PyErr_SetString(PyExc_ValueError, mess);\n return 1;\n }\n if (!dims[i])\n dims[i] = 1;\n }\n else\n dims[i] = d;\n }\n\n for (i = rank; i < PyArray_NDIM(arr);\n ++i) { /* [[1,2],[3,4]] -> [1,2,3,4] */\n while (j < PyArray_NDIM(arr) && PyArray_DIM(arr, j) < 2) ++j;\n if (j >= PyArray_NDIM(arr))\n d = 1;\n else\n d = PyArray_DIM(arr, j++);\n dims[rank - 1] *= d;\n }\n for (i = 0, size = 1; i < rank; ++i) size *= dims[i];\n if (size != arr_size) {\n char msg[200];\n int len;\n snprintf(msg, sizeof(msg),\n "unexpected array size: size=%" NPY_INTP_FMT\n ", arr_size=%" NPY_INTP_FMT\n ", rank=%d, effrank=%d, arr.nd=%d, dims=[",\n size, arr_size, rank, effrank, PyArray_NDIM(arr));\n for (i = 0; i < rank; ++i) {\n len = strlen(msg);\n snprintf(msg + len, sizeof(msg) - len, " %" NPY_INTP_FMT,\n dims[i]);\n }\n len = strlen(msg);\n snprintf(msg + len, sizeof(msg) - len, " ], arr.dims=[");\n for (i = 0; i < PyArray_NDIM(arr); ++i) {\n len = strlen(msg);\n snprintf(msg + len, sizeof(msg) - len, " %" NPY_INTP_FMT,\n PyArray_DIM(arr, i));\n }\n len = strlen(msg);\n snprintf(msg + len, sizeof(msg) - len, " ]\n");\n PyErr_SetString(PyExc_ValueError, msg);\n return 1;\n }\n }\n#ifdef DEBUG_COPY_ND_ARRAY\n printf("check_and_fix_dimensions:end: dims=");\n dump_dims(rank, dims);\n#endif\n return 0;\n}\n\n/* End of file: array_from_pyobj.c */\n\n/************************* copy_ND_array *******************************/\n\nextern int\ncopy_ND_array(const PyArrayObject *arr, PyArrayObject *out)\n{\n F2PY_REPORT_ON_ARRAY_COPY_FROMARR;\n return PyArray_CopyInto(out, (PyArrayObject *)arr);\n}\n\n/********************* Various utility functions ***********************/\n\nextern int\nf2py_describe(PyObject *obj, char *buf) {\n /*\n Write the description of a Python object to buf. The caller must\n provide buffer with size sufficient to write the description.\n\n Return 1 on success.\n */\n char localbuf[F2PY_MESSAGE_BUFFER_SIZE];\n if (PyBytes_Check(obj)) {\n sprintf(localbuf, "%d-%s", (npy_int)PyBytes_GET_SIZE(obj), Py_TYPE(obj)->tp_name);\n } else if (PyUnicode_Check(obj)) {\n sprintf(localbuf, "%d-%s", (npy_int)PyUnicode_GET_LENGTH(obj), Py_TYPE(obj)->tp_name);\n } else if (PyArray_CheckScalar(obj)) {\n PyArrayObject* arr = (PyArrayObject*)obj;\n sprintf(localbuf, "%c%" NPY_INTP_FMT "-%s-scalar", PyArray_DESCR(arr)->kind, PyArray_ITEMSIZE(arr), Py_TYPE(obj)->tp_name);\n } else if (PyArray_Check(obj)) {\n int i;\n PyArrayObject* arr = (PyArrayObject*)obj;\n strcpy(localbuf, "(");\n for (i=0; i<PyArray_NDIM(arr); i++) {\n if (i) {\n strcat(localbuf, " ");\n }\n sprintf(localbuf + strlen(localbuf), "%" NPY_INTP_FMT ",", PyArray_DIM(arr, i));\n }\n sprintf(localbuf + strlen(localbuf), ")-%c%" NPY_INTP_FMT "-%s", PyArray_DESCR(arr)->kind, PyArray_ITEMSIZE(arr), Py_TYPE(obj)->tp_name);\n } else if (PySequence_Check(obj)) {\n sprintf(localbuf, "%d-%s", (npy_int)PySequence_Length(obj), Py_TYPE(obj)->tp_name);\n } else {\n sprintf(localbuf, "%s instance", Py_TYPE(obj)->tp_name);\n }\n // TODO: detect the size of buf and make sure that size(buf) >= size(localbuf).\n strcpy(buf, localbuf);\n return 1;\n}\n\nextern npy_intp\nf2py_size_impl(PyArrayObject* var, ...)\n{\n npy_intp sz = 0;\n npy_intp dim;\n npy_intp rank;\n va_list argp;\n va_start(argp, var);\n dim = va_arg(argp, npy_int);\n if (dim==-1)\n {\n sz = PyArray_SIZE(var);\n }\n else\n {\n rank = PyArray_NDIM(var);\n if (dim>=1 && dim<=rank)\n sz = PyArray_DIM(var, dim-1);\n else\n fprintf(stderr, "f2py_size: 2nd argument value=%" NPY_INTP_FMT\n " fails to satisfy 1<=value<=%" NPY_INTP_FMT\n ". Result will be 0.\n", dim, rank);\n }\n va_end(argp);\n return sz;\n}\n\n/*********************************************/\n/* Compatibility functions for Python >= 3.0 */\n/*********************************************/\n\nPyObject *\nF2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *))\n{\n PyObject *ret = PyCapsule_New(ptr, NULL, dtor);\n if (ret == NULL) {\n PyErr_Clear();\n }\n return ret;\n}\n\nvoid *\nF2PyCapsule_AsVoidPtr(PyObject *obj)\n{\n void *ret = PyCapsule_GetPointer(obj, NULL);\n if (ret == NULL) {\n PyErr_Clear();\n }\n return ret;\n}\n\nint\nF2PyCapsule_Check(PyObject *ptr)\n{\n return PyCapsule_CheckExact(ptr);\n}\n\n#ifdef __cplusplus\n}\n#endif\n/************************* EOF fortranobject.c *******************************/\n
.venv\Lib\site-packages\numpy\f2py\src\fortranobject.c
fortranobject.c
C
47,792
0.95
0.157382
0.121752
vue-tools
101
2024-09-01T10:50:25.642616
MIT
false
43768b012635338c71183cab8c88f762
#ifndef Py_FORTRANOBJECT_H\n#define Py_FORTRANOBJECT_H\n#ifdef __cplusplus\nextern "C" {\n#endif\n\n#include <Python.h>\n\n#ifndef NPY_NO_DEPRECATED_API\n#define NPY_NO_DEPRECATED_API NPY_API_VERSION\n#endif\n#ifdef FORTRANOBJECT_C\n#define NO_IMPORT_ARRAY\n#endif\n#define PY_ARRAY_UNIQUE_SYMBOL _npy_f2py_ARRAY_API\n#include "numpy/arrayobject.h"\n#include "numpy/npy_3kcompat.h"\n\n#ifdef F2PY_REPORT_ATEXIT\n#include <sys/timeb.h>\n// clang-format off\nextern void f2py_start_clock(void);\nextern void f2py_stop_clock(void);\nextern void f2py_start_call_clock(void);\nextern void f2py_stop_call_clock(void);\nextern void f2py_cb_start_clock(void);\nextern void f2py_cb_stop_clock(void);\nextern void f2py_cb_start_call_clock(void);\nextern void f2py_cb_stop_call_clock(void);\nextern void f2py_report_on_exit(int, void *);\n// clang-format on\n#endif\n\n#ifdef DMALLOC\n#include "dmalloc.h"\n#endif\n\n/* Fortran object interface */\n\n/*\n123456789-123456789-123456789-123456789-123456789-123456789-123456789-12\n\nPyFortranObject represents various Fortran objects:\nFortran (module) routines, COMMON blocks, module data.\n\nAuthor: Pearu Peterson <pearu@cens.ioc.ee>\n*/\n\n#define F2PY_MAX_DIMS 40\n#define F2PY_MESSAGE_BUFFER_SIZE 300 // Increase on "stack smashing detected"\n\ntypedef void (*f2py_set_data_func)(char *, npy_intp *);\ntypedef void (*f2py_void_func)(void);\ntypedef void (*f2py_init_func)(int *, npy_intp *, f2py_set_data_func, int *);\n\n/*typedef void* (*f2py_c_func)(void*,...);*/\n\ntypedef void *(*f2pycfunc)(void);\n\ntypedef struct {\n char *name; /* attribute (array||routine) name */\n int rank; /* array rank, 0 for scalar, max is F2PY_MAX_DIMS,\n || rank=-1 for Fortran routine */\n struct {\n npy_intp d[F2PY_MAX_DIMS];\n } dims; /* dimensions of the array, || not used */\n int type; /* PyArray_<type> || not used */\n int elsize; /* Element size || not used */\n char *data; /* pointer to array || Fortran routine */\n f2py_init_func func; /* initialization function for\n allocatable arrays:\n func(&rank,dims,set_ptr_func,name,len(name))\n || C/API wrapper for Fortran routine */\n char *doc; /* documentation string; only recommended\n for routines. */\n} FortranDataDef;\n\ntypedef struct {\n PyObject_HEAD\n int len; /* Number of attributes */\n FortranDataDef *defs; /* An array of FortranDataDef's */\n PyObject *dict; /* Fortran object attribute dictionary */\n} PyFortranObject;\n\n#define PyFortran_Check(op) (Py_TYPE(op) == &PyFortran_Type)\n#define PyFortran_Check1(op) (0 == strcmp(Py_TYPE(op)->tp_name, "fortran"))\n\nextern PyTypeObject PyFortran_Type;\nextern int\nF2PyDict_SetItemString(PyObject *dict, char *name, PyObject *obj);\nextern PyObject *\nPyFortranObject_New(FortranDataDef *defs, f2py_void_func init);\nextern PyObject *\nPyFortranObject_NewAsAttr(FortranDataDef *defs);\n\nPyObject *\nF2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *));\nvoid *\nF2PyCapsule_AsVoidPtr(PyObject *obj);\nint\nF2PyCapsule_Check(PyObject *ptr);\n\nextern void *\nF2PySwapThreadLocalCallbackPtr(char *key, void *ptr);\nextern void *\nF2PyGetThreadLocalCallbackPtr(char *key);\n\n#define ISCONTIGUOUS(m) (PyArray_FLAGS(m) & NPY_ARRAY_C_CONTIGUOUS)\n#define F2PY_INTENT_IN 1\n#define F2PY_INTENT_INOUT 2\n#define F2PY_INTENT_OUT 4\n#define F2PY_INTENT_HIDE 8\n#define F2PY_INTENT_CACHE 16\n#define F2PY_INTENT_COPY 32\n#define F2PY_INTENT_C 64\n#define F2PY_OPTIONAL 128\n#define F2PY_INTENT_INPLACE 256\n#define F2PY_INTENT_ALIGNED4 512\n#define F2PY_INTENT_ALIGNED8 1024\n#define F2PY_INTENT_ALIGNED16 2048\n\n#define ARRAY_ISALIGNED(ARR, SIZE) ((size_t)(PyArray_DATA(ARR)) % (SIZE) == 0)\n#define F2PY_ALIGN4(intent) (intent & F2PY_INTENT_ALIGNED4)\n#define F2PY_ALIGN8(intent) (intent & F2PY_INTENT_ALIGNED8)\n#define F2PY_ALIGN16(intent) (intent & F2PY_INTENT_ALIGNED16)\n\n#define F2PY_GET_ALIGNMENT(intent) \\n (F2PY_ALIGN4(intent) \\n ? 4 \\n : (F2PY_ALIGN8(intent) ? 8 : (F2PY_ALIGN16(intent) ? 16 : 1)))\n#define F2PY_CHECK_ALIGNMENT(arr, intent) \\n ARRAY_ISALIGNED(arr, F2PY_GET_ALIGNMENT(intent))\n#define F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr) ((PyArray_DESCR(arr)->type_num == NPY_STRING && PyArray_ITEMSIZE(arr) >= 1) \\n || PyArray_DESCR(arr)->type_num == NPY_UINT8)\n#define F2PY_IS_UNICODE_ARRAY(arr) (PyArray_DESCR(arr)->type_num == NPY_UNICODE)\n\nextern PyArrayObject *\nndarray_from_pyobj(const int type_num, const int elsize_, npy_intp *dims,\n const int rank, const int intent, PyObject *obj,\n const char *errmess);\n\nextern PyArrayObject *\narray_from_pyobj(const int type_num, npy_intp *dims, const int rank,\n const int intent, PyObject *obj);\nextern int\ncopy_ND_array(const PyArrayObject *in, PyArrayObject *out);\n\n#ifdef DEBUG_COPY_ND_ARRAY\nextern void\ndump_attrs(const PyArrayObject *arr);\n#endif\n\n extern int f2py_describe(PyObject *obj, char *buf);\n\n /* Utility CPP macros and functions that can be used in signature file\n expressions. See signature-file.rst for documentation.\n */\n\n#define f2py_itemsize(var) (PyArray_ITEMSIZE(capi_ ## var ## _as_array))\n#define f2py_size(var, ...) f2py_size_impl((PyArrayObject *)(capi_ ## var ## _as_array), ## __VA_ARGS__, -1)\n#define f2py_rank(var) var ## _Rank\n#define f2py_shape(var,dim) var ## _Dims[dim]\n#define f2py_len(var) f2py_shape(var,0)\n#define f2py_fshape(var,dim) f2py_shape(var,rank(var)-dim-1)\n#define f2py_flen(var) f2py_fshape(var,0)\n#define f2py_slen(var) capi_ ## var ## _len\n\n extern npy_intp f2py_size_impl(PyArrayObject* var, ...);\n\n#ifdef __cplusplus\n}\n#endif\n#endif /* !Py_FORTRANOBJECT_H */\n
.venv\Lib\site-packages\numpy\f2py\src\fortranobject.h
fortranobject.h
C
5,996
0.95
0.040462
0.458333
vue-tools
674
2024-02-22T22:50:25.751406
GPL-3.0
false
f5e999a44f35dcb44f5ab5d8bd1eb826
import pytest\n\nfrom numpy.f2py import crackfortran\nfrom numpy.testing import IS_WASM\n\nfrom . import util\n\n\n@pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")\n@pytest.mark.slow\nclass TestAbstractInterface(util.F2PyTest):\n sources = [util.getpath("tests", "src", "abstract_interface", "foo.f90")]\n\n skip = ["add1", "add2"]\n\n def test_abstract_interface(self):\n assert self.module.ops_module.foo(3, 5) == (8, 13)\n\n def test_parse_abstract_interface(self):\n # Test gh18403\n fpath = util.getpath("tests", "src", "abstract_interface",\n "gh18403_mod.f90")\n mod = crackfortran.crackfortran([str(fpath)])\n assert len(mod) == 1\n assert len(mod[0]["body"]) == 1\n assert mod[0]["body"][0]["block"] == "abstract interface"\n
.venv\Lib\site-packages\numpy\f2py\tests\test_abstract_interface.py
test_abstract_interface.py
Python
837
0.95
0.115385
0.052632
awesome-app
347
2025-02-02T23:03:00.343721
MIT
true
7efa0e13f2322f91a5ab270a8274e385
import copy\nimport platform\nimport sys\nfrom pathlib import Path\n\nimport pytest\n\nimport numpy as np\nfrom numpy._core._type_aliases import c_names_dict as _c_names_dict\n\nfrom . import util\n\nwrap = None\n\n# Extend core typeinfo with CHARACTER to test dtype('c')\nc_names_dict = dict(\n CHARACTER=np.dtype("c"),\n **_c_names_dict\n)\n\n\ndef get_testdir():\n testroot = Path(__file__).resolve().parent / "src"\n return testroot / "array_from_pyobj"\n\ndef setup_module():\n """\n Build the required testing extension module\n\n """\n global wrap\n\n if wrap is None:\n src = [\n get_testdir() / "wrapmodule.c",\n ]\n wrap = util.build_meson(src, module_name="test_array_from_pyobj_ext")\n\n\ndef flags_info(arr):\n flags = wrap.array_attrs(arr)[6]\n return flags2names(flags)\n\n\ndef flags2names(flags):\n info = []\n for flagname in [\n "CONTIGUOUS",\n "FORTRAN",\n "OWNDATA",\n "ENSURECOPY",\n "ENSUREARRAY",\n "ALIGNED",\n "NOTSWAPPED",\n "WRITEABLE",\n "WRITEBACKIFCOPY",\n "UPDATEIFCOPY",\n "BEHAVED",\n "BEHAVED_RO",\n "CARRAY",\n "FARRAY",\n ]:\n if abs(flags) & getattr(wrap, flagname, 0):\n info.append(flagname)\n return info\n\n\nclass Intent:\n def __init__(self, intent_list=[]):\n self.intent_list = intent_list[:]\n flags = 0\n for i in intent_list:\n if i == "optional":\n flags |= wrap.F2PY_OPTIONAL\n else:\n flags |= getattr(wrap, "F2PY_INTENT_" + i.upper())\n self.flags = flags\n\n def __getattr__(self, name):\n name = name.lower()\n if name == "in_":\n name = "in"\n return self.__class__(self.intent_list + [name])\n\n def __str__(self):\n return f"intent({','.join(self.intent_list)})"\n\n def __repr__(self):\n return f"Intent({self.intent_list!r})"\n\n def is_intent(self, *names):\n return all(name in self.intent_list for name in names)\n\n def is_intent_exact(self, *names):\n return len(self.intent_list) == len(names) and self.is_intent(*names)\n\n\nintent = Intent()\n\n_type_names = [\n "BOOL",\n "BYTE",\n "UBYTE",\n "SHORT",\n "USHORT",\n "INT",\n "UINT",\n "LONG",\n "ULONG",\n "LONGLONG",\n "ULONGLONG",\n "FLOAT",\n "DOUBLE",\n "CFLOAT",\n "STRING1",\n "STRING5",\n "CHARACTER",\n]\n\n_cast_dict = {"BOOL": ["BOOL"]}\n_cast_dict["BYTE"] = _cast_dict["BOOL"] + ["BYTE"]\n_cast_dict["UBYTE"] = _cast_dict["BOOL"] + ["UBYTE"]\n_cast_dict["BYTE"] = ["BYTE"]\n_cast_dict["UBYTE"] = ["UBYTE"]\n_cast_dict["SHORT"] = _cast_dict["BYTE"] + ["UBYTE", "SHORT"]\n_cast_dict["USHORT"] = _cast_dict["UBYTE"] + ["BYTE", "USHORT"]\n_cast_dict["INT"] = _cast_dict["SHORT"] + ["USHORT", "INT"]\n_cast_dict["UINT"] = _cast_dict["USHORT"] + ["SHORT", "UINT"]\n\n_cast_dict["LONG"] = _cast_dict["INT"] + ["LONG"]\n_cast_dict["ULONG"] = _cast_dict["UINT"] + ["ULONG"]\n\n_cast_dict["LONGLONG"] = _cast_dict["LONG"] + ["LONGLONG"]\n_cast_dict["ULONGLONG"] = _cast_dict["ULONG"] + ["ULONGLONG"]\n\n_cast_dict["FLOAT"] = _cast_dict["SHORT"] + ["USHORT", "FLOAT"]\n_cast_dict["DOUBLE"] = _cast_dict["INT"] + ["UINT", "FLOAT", "DOUBLE"]\n\n_cast_dict["CFLOAT"] = _cast_dict["FLOAT"] + ["CFLOAT"]\n\n_cast_dict['STRING1'] = ['STRING1']\n_cast_dict['STRING5'] = ['STRING5']\n_cast_dict['CHARACTER'] = ['CHARACTER']\n\n# 32 bit system malloc typically does not provide the alignment required by\n# 16 byte long double types this means the inout intent cannot be satisfied\n# and several tests fail as the alignment flag can be randomly true or false\n# when numpy gains an aligned allocator the tests could be enabled again\n#\n# Furthermore, on macOS ARM64, LONGDOUBLE is an alias for DOUBLE.\nif ((np.intp().dtype.itemsize != 4 or np.clongdouble().dtype.alignment <= 8)\n and sys.platform != "win32"\n and (platform.system(), platform.processor()) != ("Darwin", "arm")):\n _type_names.extend(["LONGDOUBLE", "CDOUBLE", "CLONGDOUBLE"])\n _cast_dict["LONGDOUBLE"] = _cast_dict["LONG"] + [\n "ULONG",\n "FLOAT",\n "DOUBLE",\n "LONGDOUBLE",\n ]\n _cast_dict["CLONGDOUBLE"] = _cast_dict["LONGDOUBLE"] + [\n "CFLOAT",\n "CDOUBLE",\n "CLONGDOUBLE",\n ]\n _cast_dict["CDOUBLE"] = _cast_dict["DOUBLE"] + ["CFLOAT", "CDOUBLE"]\n\n\nclass Type:\n _type_cache = {}\n\n def __new__(cls, name):\n if isinstance(name, np.dtype):\n dtype0 = name\n name = None\n for n, i in c_names_dict.items():\n if not isinstance(i, type) and dtype0.type is i.type:\n name = n\n break\n obj = cls._type_cache.get(name.upper(), None)\n if obj is not None:\n return obj\n obj = object.__new__(cls)\n obj._init(name)\n cls._type_cache[name.upper()] = obj\n return obj\n\n def _init(self, name):\n self.NAME = name.upper()\n\n if self.NAME == 'CHARACTER':\n info = c_names_dict[self.NAME]\n self.type_num = wrap.NPY_STRING\n self.elsize = 1\n self.dtype = np.dtype('c')\n elif self.NAME.startswith('STRING'):\n info = c_names_dict[self.NAME[:6]]\n self.type_num = wrap.NPY_STRING\n self.elsize = int(self.NAME[6:] or 0)\n self.dtype = np.dtype(f'S{self.elsize}')\n else:\n info = c_names_dict[self.NAME]\n self.type_num = getattr(wrap, 'NPY_' + self.NAME)\n self.elsize = info.itemsize\n self.dtype = np.dtype(info.type)\n\n assert self.type_num == info.num\n self.type = info.type\n self.dtypechar = info.char\n\n def __repr__(self):\n return (f"Type({self.NAME})|type_num={self.type_num},"\n f" dtype={self.dtype},"\n f" type={self.type}, elsize={self.elsize},"\n f" dtypechar={self.dtypechar}")\n\n def cast_types(self):\n return [self.__class__(_m) for _m in _cast_dict[self.NAME]]\n\n def all_types(self):\n return [self.__class__(_m) for _m in _type_names]\n\n def smaller_types(self):\n bits = c_names_dict[self.NAME].alignment\n types = []\n for name in _type_names:\n if c_names_dict[name].alignment < bits:\n types.append(Type(name))\n return types\n\n def equal_types(self):\n bits = c_names_dict[self.NAME].alignment\n types = []\n for name in _type_names:\n if name == self.NAME:\n continue\n if c_names_dict[name].alignment == bits:\n types.append(Type(name))\n return types\n\n def larger_types(self):\n bits = c_names_dict[self.NAME].alignment\n types = []\n for name in _type_names:\n if c_names_dict[name].alignment > bits:\n types.append(Type(name))\n return types\n\n\nclass Array:\n\n def __repr__(self):\n return (f'Array({self.type}, {self.dims}, {self.intent},'\n f' {self.obj})|arr={self.arr}')\n\n def __init__(self, typ, dims, intent, obj):\n self.type = typ\n self.dims = dims\n self.intent = intent\n self.obj_copy = copy.deepcopy(obj)\n self.obj = obj\n\n # arr.dtypechar may be different from typ.dtypechar\n self.arr = wrap.call(typ.type_num,\n typ.elsize,\n dims, intent.flags, obj)\n\n assert isinstance(self.arr, np.ndarray)\n\n self.arr_attr = wrap.array_attrs(self.arr)\n\n if len(dims) > 1:\n if self.intent.is_intent("c"):\n assert (intent.flags & wrap.F2PY_INTENT_C)\n assert not self.arr.flags["FORTRAN"]\n assert self.arr.flags["CONTIGUOUS"]\n assert (not self.arr_attr[6] & wrap.FORTRAN)\n else:\n assert (not intent.flags & wrap.F2PY_INTENT_C)\n assert self.arr.flags["FORTRAN"]\n assert not self.arr.flags["CONTIGUOUS"]\n assert (self.arr_attr[6] & wrap.FORTRAN)\n\n if obj is None:\n self.pyarr = None\n self.pyarr_attr = None\n return\n\n if intent.is_intent("cache"):\n assert isinstance(obj, np.ndarray), repr(type(obj))\n self.pyarr = np.array(obj).reshape(*dims).copy()\n else:\n self.pyarr = np.array(\n np.array(obj, dtype=typ.dtypechar).reshape(*dims),\n order=(self.intent.is_intent("c") and "C") or "F",\n )\n assert self.pyarr.dtype == typ\n self.pyarr.setflags(write=self.arr.flags["WRITEABLE"])\n assert self.pyarr.flags["OWNDATA"], (obj, intent)\n self.pyarr_attr = wrap.array_attrs(self.pyarr)\n\n if len(dims) > 1:\n if self.intent.is_intent("c"):\n assert not self.pyarr.flags["FORTRAN"]\n assert self.pyarr.flags["CONTIGUOUS"]\n assert (not self.pyarr_attr[6] & wrap.FORTRAN)\n else:\n assert self.pyarr.flags["FORTRAN"]\n assert not self.pyarr.flags["CONTIGUOUS"]\n assert (self.pyarr_attr[6] & wrap.FORTRAN)\n\n assert self.arr_attr[1] == self.pyarr_attr[1] # nd\n assert self.arr_attr[2] == self.pyarr_attr[2] # dimensions\n if self.arr_attr[1] <= 1:\n assert self.arr_attr[3] == self.pyarr_attr[3], repr((\n self.arr_attr[3],\n self.pyarr_attr[3],\n self.arr.tobytes(),\n self.pyarr.tobytes(),\n )) # strides\n assert self.arr_attr[5][-2:] == self.pyarr_attr[5][-2:], repr((\n self.arr_attr[5], self.pyarr_attr[5]\n )) # descr\n assert self.arr_attr[6] == self.pyarr_attr[6], repr((\n self.arr_attr[6],\n self.pyarr_attr[6],\n flags2names(0 * self.arr_attr[6] - self.pyarr_attr[6]),\n flags2names(self.arr_attr[6]),\n intent,\n )) # flags\n\n if intent.is_intent("cache"):\n assert self.arr_attr[5][3] >= self.type.elsize\n else:\n assert self.arr_attr[5][3] == self.type.elsize\n assert (self.arr_equal(self.pyarr, self.arr))\n\n if isinstance(self.obj, np.ndarray):\n if typ.elsize == Type(obj.dtype).elsize:\n if not intent.is_intent("copy") and self.arr_attr[1] <= 1:\n assert self.has_shared_memory()\n\n def arr_equal(self, arr1, arr2):\n if arr1.shape != arr2.shape:\n return False\n return (arr1 == arr2).all()\n\n def __str__(self):\n return str(self.arr)\n\n def has_shared_memory(self):\n """Check that created array shares data with input array."""\n if self.obj is self.arr:\n return True\n if not isinstance(self.obj, np.ndarray):\n return False\n obj_attr = wrap.array_attrs(self.obj)\n return obj_attr[0] == self.arr_attr[0]\n\n\nclass TestIntent:\n def test_in_out(self):\n assert str(intent.in_.out) == "intent(in,out)"\n assert intent.in_.c.is_intent("c")\n assert not intent.in_.c.is_intent_exact("c")\n assert intent.in_.c.is_intent_exact("c", "in")\n assert intent.in_.c.is_intent_exact("in", "c")\n assert not intent.in_.is_intent("c")\n\n\nclass TestSharedMemory:\n\n @pytest.fixture(autouse=True, scope="class", params=_type_names)\n def setup_type(self, request):\n request.cls.type = Type(request.param)\n request.cls.array = lambda self, dims, intent, obj: Array(\n Type(request.param), dims, intent, obj)\n\n @property\n def num2seq(self):\n if self.type.NAME.startswith('STRING'):\n elsize = self.type.elsize\n return ['1' * elsize, '2' * elsize]\n return [1, 2]\n\n @property\n def num23seq(self):\n if self.type.NAME.startswith('STRING'):\n elsize = self.type.elsize\n return [['1' * elsize, '2' * elsize, '3' * elsize],\n ['4' * elsize, '5' * elsize, '6' * elsize]]\n return [[1, 2, 3], [4, 5, 6]]\n\n def test_in_from_2seq(self):\n a = self.array([2], intent.in_, self.num2seq)\n assert not a.has_shared_memory()\n\n def test_in_from_2casttype(self):\n for t in self.type.cast_types():\n obj = np.array(self.num2seq, dtype=t.dtype)\n a = self.array([len(self.num2seq)], intent.in_, obj)\n if t.elsize == self.type.elsize:\n assert a.has_shared_memory(), repr((self.type.dtype, t.dtype))\n else:\n assert not a.has_shared_memory()\n\n @pytest.mark.parametrize("write", ["w", "ro"])\n @pytest.mark.parametrize("order", ["C", "F"])\n @pytest.mark.parametrize("inp", ["2seq", "23seq"])\n def test_in_nocopy(self, write, order, inp):\n """Test if intent(in) array can be passed without copies"""\n seq = getattr(self, "num" + inp)\n obj = np.array(seq, dtype=self.type.dtype, order=order)\n obj.setflags(write=(write == 'w'))\n a = self.array(obj.shape,\n ((order == 'C' and intent.in_.c) or intent.in_), obj)\n assert a.has_shared_memory()\n\n def test_inout_2seq(self):\n obj = np.array(self.num2seq, dtype=self.type.dtype)\n a = self.array([len(self.num2seq)], intent.inout, obj)\n assert a.has_shared_memory()\n\n try:\n a = self.array([2], intent.in_.inout, self.num2seq)\n except TypeError as msg:\n if not str(msg).startswith(\n "failed to initialize intent(inout|inplace|cache) array"):\n raise\n else:\n raise SystemError("intent(inout) should have failed on sequence")\n\n def test_f_inout_23seq(self):\n obj = np.array(self.num23seq, dtype=self.type.dtype, order="F")\n shape = (len(self.num23seq), len(self.num23seq[0]))\n a = self.array(shape, intent.in_.inout, obj)\n assert a.has_shared_memory()\n\n obj = np.array(self.num23seq, dtype=self.type.dtype, order="C")\n shape = (len(self.num23seq), len(self.num23seq[0]))\n try:\n a = self.array(shape, intent.in_.inout, obj)\n except ValueError as msg:\n if not str(msg).startswith(\n "failed to initialize intent(inout) array"):\n raise\n else:\n raise SystemError(\n "intent(inout) should have failed on improper array")\n\n def test_c_inout_23seq(self):\n obj = np.array(self.num23seq, dtype=self.type.dtype)\n shape = (len(self.num23seq), len(self.num23seq[0]))\n a = self.array(shape, intent.in_.c.inout, obj)\n assert a.has_shared_memory()\n\n def test_in_copy_from_2casttype(self):\n for t in self.type.cast_types():\n obj = np.array(self.num2seq, dtype=t.dtype)\n a = self.array([len(self.num2seq)], intent.in_.copy, obj)\n assert not a.has_shared_memory()\n\n def test_c_in_from_23seq(self):\n a = self.array(\n [len(self.num23seq), len(self.num23seq[0])], intent.in_,\n self.num23seq)\n assert not a.has_shared_memory()\n\n def test_in_from_23casttype(self):\n for t in self.type.cast_types():\n obj = np.array(self.num23seq, dtype=t.dtype)\n a = self.array(\n [len(self.num23seq), len(self.num23seq[0])], intent.in_, obj)\n assert not a.has_shared_memory()\n\n def test_f_in_from_23casttype(self):\n for t in self.type.cast_types():\n obj = np.array(self.num23seq, dtype=t.dtype, order="F")\n a = self.array(\n [len(self.num23seq), len(self.num23seq[0])], intent.in_, obj)\n if t.elsize == self.type.elsize:\n assert a.has_shared_memory()\n else:\n assert not a.has_shared_memory()\n\n def test_c_in_from_23casttype(self):\n for t in self.type.cast_types():\n obj = np.array(self.num23seq, dtype=t.dtype)\n a = self.array(\n [len(self.num23seq), len(self.num23seq[0])], intent.in_.c, obj)\n if t.elsize == self.type.elsize:\n assert a.has_shared_memory()\n else:\n assert not a.has_shared_memory()\n\n def test_f_copy_in_from_23casttype(self):\n for t in self.type.cast_types():\n obj = np.array(self.num23seq, dtype=t.dtype, order="F")\n a = self.array(\n [len(self.num23seq), len(self.num23seq[0])], intent.in_.copy,\n obj)\n assert not a.has_shared_memory()\n\n def test_c_copy_in_from_23casttype(self):\n for t in self.type.cast_types():\n obj = np.array(self.num23seq, dtype=t.dtype)\n a = self.array(\n [len(self.num23seq), len(self.num23seq[0])], intent.in_.c.copy,\n obj)\n assert not a.has_shared_memory()\n\n def test_in_cache_from_2casttype(self):\n for t in self.type.all_types():\n if t.elsize != self.type.elsize:\n continue\n obj = np.array(self.num2seq, dtype=t.dtype)\n shape = (len(self.num2seq), )\n a = self.array(shape, intent.in_.c.cache, obj)\n assert a.has_shared_memory()\n\n a = self.array(shape, intent.in_.cache, obj)\n assert a.has_shared_memory()\n\n obj = np.array(self.num2seq, dtype=t.dtype, order="F")\n a = self.array(shape, intent.in_.c.cache, obj)\n assert a.has_shared_memory()\n\n a = self.array(shape, intent.in_.cache, obj)\n assert a.has_shared_memory(), repr(t.dtype)\n\n try:\n a = self.array(shape, intent.in_.cache, obj[::-1])\n except ValueError as msg:\n if not str(msg).startswith(\n "failed to initialize intent(cache) array"):\n raise\n else:\n raise SystemError(\n "intent(cache) should have failed on multisegmented array")\n\n def test_in_cache_from_2casttype_failure(self):\n for t in self.type.all_types():\n if t.NAME == 'STRING':\n # string elsize is 0, so skipping the test\n continue\n if t.elsize >= self.type.elsize:\n continue\n is_int = np.issubdtype(t.dtype, np.integer)\n if is_int and int(self.num2seq[0]) > np.iinfo(t.dtype).max:\n # skip test if num2seq would trigger an overflow error\n continue\n obj = np.array(self.num2seq, dtype=t.dtype)\n shape = (len(self.num2seq), )\n try:\n self.array(shape, intent.in_.cache, obj) # Should succeed\n except ValueError as msg:\n if not str(msg).startswith(\n "failed to initialize intent(cache) array"):\n raise\n else:\n raise SystemError(\n "intent(cache) should have failed on smaller array")\n\n def test_cache_hidden(self):\n shape = (2, )\n a = self.array(shape, intent.cache.hide, None)\n assert a.arr.shape == shape\n\n shape = (2, 3)\n a = self.array(shape, intent.cache.hide, None)\n assert a.arr.shape == shape\n\n shape = (-1, 3)\n try:\n a = self.array(shape, intent.cache.hide, None)\n except ValueError as msg:\n if not str(msg).startswith(\n "failed to create intent(cache|hide)|optional array"):\n raise\n else:\n raise SystemError(\n "intent(cache) should have failed on undefined dimensions")\n\n def test_hidden(self):\n shape = (2, )\n a = self.array(shape, intent.hide, None)\n assert a.arr.shape == shape\n assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))\n\n shape = (2, 3)\n a = self.array(shape, intent.hide, None)\n assert a.arr.shape == shape\n assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))\n assert a.arr.flags["FORTRAN"] and not a.arr.flags["CONTIGUOUS"]\n\n shape = (2, 3)\n a = self.array(shape, intent.c.hide, None)\n assert a.arr.shape == shape\n assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))\n assert not a.arr.flags["FORTRAN"] and a.arr.flags["CONTIGUOUS"]\n\n shape = (-1, 3)\n try:\n a = self.array(shape, intent.hide, None)\n except ValueError as msg:\n if not str(msg).startswith(\n "failed to create intent(cache|hide)|optional array"):\n raise\n else:\n raise SystemError(\n "intent(hide) should have failed on undefined dimensions")\n\n def test_optional_none(self):\n shape = (2, )\n a = self.array(shape, intent.optional, None)\n assert a.arr.shape == shape\n assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))\n\n shape = (2, 3)\n a = self.array(shape, intent.optional, None)\n assert a.arr.shape == shape\n assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))\n assert a.arr.flags["FORTRAN"] and not a.arr.flags["CONTIGUOUS"]\n\n shape = (2, 3)\n a = self.array(shape, intent.c.optional, None)\n assert a.arr.shape == shape\n assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))\n assert not a.arr.flags["FORTRAN"] and a.arr.flags["CONTIGUOUS"]\n\n def test_optional_from_2seq(self):\n obj = self.num2seq\n shape = (len(obj), )\n a = self.array(shape, intent.optional, obj)\n assert a.arr.shape == shape\n assert not a.has_shared_memory()\n\n def test_optional_from_23seq(self):\n obj = self.num23seq\n shape = (len(obj), len(obj[0]))\n a = self.array(shape, intent.optional, obj)\n assert a.arr.shape == shape\n assert not a.has_shared_memory()\n\n a = self.array(shape, intent.optional.c, obj)\n assert a.arr.shape == shape\n assert not a.has_shared_memory()\n\n def test_inplace(self):\n obj = np.array(self.num23seq, dtype=self.type.dtype)\n assert not obj.flags["FORTRAN"] and obj.flags["CONTIGUOUS"]\n shape = obj.shape\n a = self.array(shape, intent.inplace, obj)\n assert obj[1][2] == a.arr[1][2], repr((obj, a.arr))\n a.arr[1][2] = 54\n assert obj[1][2] == a.arr[1][2] == np.array(54, dtype=self.type.dtype)\n assert a.arr is obj\n assert obj.flags["FORTRAN"] # obj attributes are changed inplace!\n assert not obj.flags["CONTIGUOUS"]\n\n def test_inplace_from_casttype(self):\n for t in self.type.cast_types():\n if t is self.type:\n continue\n obj = np.array(self.num23seq, dtype=t.dtype)\n assert obj.dtype.type == t.type\n assert obj.dtype.type is not self.type.type\n assert not obj.flags["FORTRAN"] and obj.flags["CONTIGUOUS"]\n shape = obj.shape\n a = self.array(shape, intent.inplace, obj)\n assert obj[1][2] == a.arr[1][2], repr((obj, a.arr))\n a.arr[1][2] = 54\n assert obj[1][2] == a.arr[1][2] == np.array(54,\n dtype=self.type.dtype)\n assert a.arr is obj\n assert obj.flags["FORTRAN"] # obj attributes changed inplace!\n assert not obj.flags["CONTIGUOUS"]\n assert obj.dtype.type is self.type.type # obj changed inplace!\n
.venv\Lib\site-packages\numpy\f2py\tests\test_array_from_pyobj.py
test_array_from_pyobj.py
Python
24,374
0.95
0.185841
0.01913
react-lib
600
2023-12-12T15:38:21.008133
Apache-2.0
true
1d7197fb777e961a3b060c4562651235
import os\nimport tempfile\n\nimport pytest\n\nfrom . import util\n\n\nclass TestAssumedShapeSumExample(util.F2PyTest):\n sources = [\n util.getpath("tests", "src", "assumed_shape", "foo_free.f90"),\n util.getpath("tests", "src", "assumed_shape", "foo_use.f90"),\n util.getpath("tests", "src", "assumed_shape", "precision.f90"),\n util.getpath("tests", "src", "assumed_shape", "foo_mod.f90"),\n util.getpath("tests", "src", "assumed_shape", ".f2py_f2cmap"),\n ]\n\n @pytest.mark.slow\n def test_all(self):\n r = self.module.fsum([1, 2])\n assert r == 3\n r = self.module.sum([1, 2])\n assert r == 3\n r = self.module.sum_with_use([1, 2])\n assert r == 3\n\n r = self.module.mod.sum([1, 2])\n assert r == 3\n r = self.module.mod.fsum([1, 2])\n assert r == 3\n\n\nclass TestF2cmapOption(TestAssumedShapeSumExample):\n def setup_method(self):\n # Use a custom file name for .f2py_f2cmap\n self.sources = list(self.sources)\n f2cmap_src = self.sources.pop(-1)\n\n self.f2cmap_file = tempfile.NamedTemporaryFile(delete=False)\n with open(f2cmap_src, "rb") as f:\n self.f2cmap_file.write(f.read())\n self.f2cmap_file.close()\n\n self.sources.append(self.f2cmap_file.name)\n self.options = ["--f2cmap", self.f2cmap_file.name]\n\n super().setup_method()\n\n def teardown_method(self):\n os.unlink(self.f2cmap_file.name)\n
.venv\Lib\site-packages\numpy\f2py\tests\test_assumed_shape.py
test_assumed_shape.py
Python
1,517
0.95
0.12
0.026316
node-utils
428
2024-11-16T14:25:06.110078
MIT
true
a6ea2bb547b5a457e9bf67068dbec491
import sys\n\nimport pytest\n\nfrom numpy.testing import IS_PYPY\n\nfrom . import util\n\n\n@pytest.mark.slow\nclass TestBlockDocString(util.F2PyTest):\n sources = [util.getpath("tests", "src", "block_docstring", "foo.f")]\n\n @pytest.mark.skipif(sys.platform == "win32",\n reason="Fails with MinGW64 Gfortran (Issue #9673)")\n @pytest.mark.xfail(IS_PYPY,\n reason="PyPy cannot modify tp_doc after PyType_Ready")\n def test_block_docstring(self):\n expected = "bar : 'i'-array(2,3)\n"\n assert self.module.block.__doc__ == expected\n
.venv\Lib\site-packages\numpy\f2py\tests\test_block_docstring.py
test_block_docstring.py
Python
604
0.95
0.1
0
awesome-app
41
2024-07-20T09:01:57.188867
MIT
true
347ef83dd98ccf807ce53e94ce0caa5e
import math\nimport platform\nimport sys\nimport textwrap\nimport threading\nimport time\nimport traceback\n\nimport pytest\n\nimport numpy as np\nfrom numpy.testing import IS_PYPY\n\nfrom . import util\n\n\nclass TestF77Callback(util.F2PyTest):\n sources = [util.getpath("tests", "src", "callback", "foo.f")]\n\n @pytest.mark.parametrize("name", ["t", "t2"])\n @pytest.mark.slow\n def test_all(self, name):\n self.check_function(name)\n\n @pytest.mark.xfail(IS_PYPY,\n reason="PyPy cannot modify tp_doc after PyType_Ready")\n def test_docstring(self):\n expected = textwrap.dedent("""\\n a = t(fun,[fun_extra_args])\n\n Wrapper for ``t``.\n\n Parameters\n ----------\n fun : call-back function\n\n Other Parameters\n ----------------\n fun_extra_args : input tuple, optional\n Default: ()\n\n Returns\n -------\n a : int\n\n Notes\n -----\n Call-back functions::\n\n def fun(): return a\n Return objects:\n a : int\n """)\n assert self.module.t.__doc__ == expected\n\n def check_function(self, name):\n t = getattr(self.module, name)\n r = t(lambda: 4)\n assert r == 4\n r = t(lambda a: 5, fun_extra_args=(6, ))\n assert r == 5\n r = t(lambda a: a, fun_extra_args=(6, ))\n assert r == 6\n r = t(lambda a: 5 + a, fun_extra_args=(7, ))\n assert r == 12\n r = t(math.degrees, fun_extra_args=(math.pi, ))\n assert r == 180\n r = t(math.degrees, fun_extra_args=(math.pi, ))\n assert r == 180\n\n r = t(self.module.func, fun_extra_args=(6, ))\n assert r == 17\n r = t(self.module.func0)\n assert r == 11\n r = t(self.module.func0._cpointer)\n assert r == 11\n\n class A:\n def __call__(self):\n return 7\n\n def mth(self):\n return 9\n\n a = A()\n r = t(a)\n assert r == 7\n r = t(a.mth)\n assert r == 9\n\n @pytest.mark.skipif(sys.platform == 'win32',\n reason='Fails with MinGW64 Gfortran (Issue #9673)')\n def test_string_callback(self):\n def callback(code):\n if code == "r":\n return 0\n else:\n return 1\n\n f = self.module.string_callback\n r = f(callback)\n assert r == 0\n\n @pytest.mark.skipif(sys.platform == 'win32',\n reason='Fails with MinGW64 Gfortran (Issue #9673)')\n def test_string_callback_array(self):\n # See gh-10027\n cu1 = np.zeros((1, ), "S8")\n cu2 = np.zeros((1, 8), "c")\n cu3 = np.array([""], "S8")\n\n def callback(cu, lencu):\n if cu.shape != (lencu,):\n return 1\n if cu.dtype != "S8":\n return 2\n if not np.all(cu == b""):\n return 3\n return 0\n\n f = self.module.string_callback_array\n for cu in [cu1, cu2, cu3]:\n res = f(callback, cu, cu.size)\n assert res == 0\n\n def test_threadsafety(self):\n # Segfaults if the callback handling is not threadsafe\n\n errors = []\n\n def cb():\n # Sleep here to make it more likely for another thread\n # to call their callback at the same time.\n time.sleep(1e-3)\n\n # Check reentrancy\n r = self.module.t(lambda: 123)\n assert r == 123\n\n return 42\n\n def runner(name):\n try:\n for j in range(50):\n r = self.module.t(cb)\n assert r == 42\n self.check_function(name)\n except Exception:\n errors.append(traceback.format_exc())\n\n threads = [\n threading.Thread(target=runner, args=(arg, ))\n for arg in ("t", "t2") for n in range(20)\n ]\n\n for t in threads:\n t.start()\n\n for t in threads:\n t.join()\n\n errors = "\n\n".join(errors)\n if errors:\n raise AssertionError(errors)\n\n def test_hidden_callback(self):\n try:\n self.module.hidden_callback(2)\n except Exception as msg:\n assert str(msg).startswith("Callback global_f not defined")\n\n try:\n self.module.hidden_callback2(2)\n except Exception as msg:\n assert str(msg).startswith("cb: Callback global_f not defined")\n\n self.module.global_f = lambda x: x + 1\n r = self.module.hidden_callback(2)\n assert r == 3\n\n self.module.global_f = lambda x: x + 2\n r = self.module.hidden_callback(2)\n assert r == 4\n\n del self.module.global_f\n try:\n self.module.hidden_callback(2)\n except Exception as msg:\n assert str(msg).startswith("Callback global_f not defined")\n\n self.module.global_f = lambda x=0: x + 3\n r = self.module.hidden_callback(2)\n assert r == 5\n\n # reproducer of gh18341\n r = self.module.hidden_callback2(2)\n assert r == 3\n\n\nclass TestF77CallbackPythonTLS(TestF77Callback):\n """\n Callback tests using Python thread-local storage instead of\n compiler-provided\n """\n\n options = ["-DF2PY_USE_PYTHON_TLS"]\n\n\nclass TestF90Callback(util.F2PyTest):\n sources = [util.getpath("tests", "src", "callback", "gh17797.f90")]\n\n @pytest.mark.slow\n def test_gh17797(self):\n def incr(x):\n return x + 123\n\n y = np.array([1, 2, 3], dtype=np.int64)\n r = self.module.gh17797(incr, y)\n assert r == 123 + 1 + 2 + 3\n\n\nclass TestGH18335(util.F2PyTest):\n """The reproduction of the reported issue requires specific input that\n extensions may break the issue conditions, so the reproducer is\n implemented as a separate test class. Do not extend this test with\n other tests!\n """\n sources = [util.getpath("tests", "src", "callback", "gh18335.f90")]\n\n @pytest.mark.slow\n def test_gh18335(self):\n def foo(x):\n x[0] += 1\n\n r = self.module.gh18335(foo)\n assert r == 123 + 1\n\n\nclass TestGH25211(util.F2PyTest):\n sources = [util.getpath("tests", "src", "callback", "gh25211.f"),\n util.getpath("tests", "src", "callback", "gh25211.pyf")]\n module_name = "callback2"\n\n def test_gh25211(self):\n def bar(x):\n return x * x\n\n res = self.module.foo(bar)\n assert res == 110\n\n\n@pytest.mark.slow\n@pytest.mark.xfail(condition=(platform.system().lower() == 'darwin'),\n run=False,\n reason="Callback aborts cause CI failures on macOS")\nclass TestCBFortranCallstatement(util.F2PyTest):\n sources = [util.getpath("tests", "src", "callback", "gh26681.f90")]\n options = ['--lower']\n\n def test_callstatement_fortran(self):\n with pytest.raises(ValueError, match='helpme') as exc:\n self.module.mypy_abort = self.module.utils.my_abort\n self.module.utils.do_something('helpme')\n
.venv\Lib\site-packages\numpy\f2py\tests\test_callback.py
test_callback.py
Python
7,362
0.95
0.18251
0.029268
python-kit
187
2024-06-04T07:29:04.188421
GPL-3.0
true
19c5db801c85bdc05aeebc7facba31bc
import textwrap\n\nimport pytest\n\nimport numpy as np\nfrom numpy.f2py.tests import util\nfrom numpy.testing import assert_array_equal, assert_equal, assert_raises\n\n\n@pytest.mark.slow\nclass TestCharacterString(util.F2PyTest):\n # options = ['--debug-capi', '--build-dir', '/tmp/test-build-f2py']\n suffix = '.f90'\n fprefix = 'test_character_string'\n length_list = ['1', '3', 'star']\n\n code = ''\n for length in length_list:\n fsuffix = length\n clength = {'star': '(*)'}.get(length, length)\n\n code += textwrap.dedent(f"""\n\n subroutine {fprefix}_input_{fsuffix}(c, o, n)\n character*{clength}, intent(in) :: c\n integer n\n !f2py integer, depend(c), intent(hide) :: n = slen(c)\n integer*1, dimension(n) :: o\n !f2py intent(out) o\n o = transfer(c, o)\n end subroutine {fprefix}_input_{fsuffix}\n\n subroutine {fprefix}_output_{fsuffix}(c, o, n)\n character*{clength}, intent(out) :: c\n integer n\n integer*1, dimension(n), intent(in) :: o\n !f2py integer, depend(o), intent(hide) :: n = len(o)\n c = transfer(o, c)\n end subroutine {fprefix}_output_{fsuffix}\n\n subroutine {fprefix}_array_input_{fsuffix}(c, o, m, n)\n integer m, i, n\n character*{clength}, intent(in), dimension(m) :: c\n !f2py integer, depend(c), intent(hide) :: m = len(c)\n !f2py integer, depend(c), intent(hide) :: n = f2py_itemsize(c)\n integer*1, dimension(m, n), intent(out) :: o\n do i=1,m\n o(i, :) = transfer(c(i), o(i, :))\n end do\n end subroutine {fprefix}_array_input_{fsuffix}\n\n subroutine {fprefix}_array_output_{fsuffix}(c, o, m, n)\n character*{clength}, intent(out), dimension(m) :: c\n integer n\n integer*1, dimension(m, n), intent(in) :: o\n !f2py character(f2py_len=n) :: c\n !f2py integer, depend(o), intent(hide) :: m = len(o)\n !f2py integer, depend(o), intent(hide) :: n = shape(o, 1)\n do i=1,m\n c(i) = transfer(o(i, :), c(i))\n end do\n end subroutine {fprefix}_array_output_{fsuffix}\n\n subroutine {fprefix}_2d_array_input_{fsuffix}(c, o, m1, m2, n)\n integer m1, m2, i, j, n\n character*{clength}, intent(in), dimension(m1, m2) :: c\n !f2py integer, depend(c), intent(hide) :: m1 = len(c)\n !f2py integer, depend(c), intent(hide) :: m2 = shape(c, 1)\n !f2py integer, depend(c), intent(hide) :: n = f2py_itemsize(c)\n integer*1, dimension(m1, m2, n), intent(out) :: o\n do i=1,m1\n do j=1,m2\n o(i, j, :) = transfer(c(i, j), o(i, j, :))\n end do\n end do\n end subroutine {fprefix}_2d_array_input_{fsuffix}\n """)\n\n @pytest.mark.parametrize("length", length_list)\n def test_input(self, length):\n fsuffix = {'(*)': 'star'}.get(length, length)\n f = getattr(self.module, self.fprefix + '_input_' + fsuffix)\n\n a = {'1': 'a', '3': 'abc', 'star': 'abcde' * 3}[length]\n\n assert_array_equal(f(a), np.array(list(map(ord, a)), dtype='u1'))\n\n @pytest.mark.parametrize("length", length_list[:-1])\n def test_output(self, length):\n fsuffix = length\n f = getattr(self.module, self.fprefix + '_output_' + fsuffix)\n\n a = {'1': 'a', '3': 'abc'}[length]\n\n assert_array_equal(f(np.array(list(map(ord, a)), dtype='u1')),\n a.encode())\n\n @pytest.mark.parametrize("length", length_list)\n def test_array_input(self, length):\n fsuffix = length\n f = getattr(self.module, self.fprefix + '_array_input_' + fsuffix)\n\n a = np.array([{'1': 'a', '3': 'abc', 'star': 'abcde' * 3}[length],\n {'1': 'A', '3': 'ABC', 'star': 'ABCDE' * 3}[length],\n ], dtype='S')\n\n expected = np.array([list(s) for s in a], dtype='u1')\n assert_array_equal(f(a), expected)\n\n @pytest.mark.parametrize("length", length_list)\n def test_array_output(self, length):\n fsuffix = length\n f = getattr(self.module, self.fprefix + '_array_output_' + fsuffix)\n\n expected = np.array(\n [{'1': 'a', '3': 'abc', 'star': 'abcde' * 3}[length],\n {'1': 'A', '3': 'ABC', 'star': 'ABCDE' * 3}[length]], dtype='S')\n\n a = np.array([list(s) for s in expected], dtype='u1')\n assert_array_equal(f(a), expected)\n\n @pytest.mark.parametrize("length", length_list)\n def test_2d_array_input(self, length):\n fsuffix = length\n f = getattr(self.module, self.fprefix + '_2d_array_input_' + fsuffix)\n\n a = np.array([[{'1': 'a', '3': 'abc', 'star': 'abcde' * 3}[length],\n {'1': 'A', '3': 'ABC', 'star': 'ABCDE' * 3}[length]],\n [{'1': 'f', '3': 'fgh', 'star': 'fghij' * 3}[length],\n {'1': 'F', '3': 'FGH', 'star': 'FGHIJ' * 3}[length]]],\n dtype='S')\n expected = np.array([[list(item) for item in row] for row in a],\n dtype='u1', order='F')\n assert_array_equal(f(a), expected)\n\n\nclass TestCharacter(util.F2PyTest):\n # options = ['--debug-capi', '--build-dir', '/tmp/test-build-f2py']\n suffix = '.f90'\n fprefix = 'test_character'\n\n code = textwrap.dedent(f"""\n subroutine {fprefix}_input(c, o)\n character, intent(in) :: c\n integer*1 o\n !f2py intent(out) o\n o = transfer(c, o)\n end subroutine {fprefix}_input\n\n subroutine {fprefix}_output(c, o)\n character :: c\n integer*1, intent(in) :: o\n !f2py intent(out) c\n c = transfer(o, c)\n end subroutine {fprefix}_output\n\n subroutine {fprefix}_input_output(c, o)\n character, intent(in) :: c\n character o\n !f2py intent(out) o\n o = c\n end subroutine {fprefix}_input_output\n\n subroutine {fprefix}_inout(c, n)\n character :: c, n\n !f2py intent(in) n\n !f2py intent(inout) c\n c = n\n end subroutine {fprefix}_inout\n\n function {fprefix}_return(o) result (c)\n character :: c\n character, intent(in) :: o\n c = transfer(o, c)\n end function {fprefix}_return\n\n subroutine {fprefix}_array_input(c, o)\n character, intent(in) :: c(3)\n integer*1 o(3)\n !f2py intent(out) o\n integer i\n do i=1,3\n o(i) = transfer(c(i), o(i))\n end do\n end subroutine {fprefix}_array_input\n\n subroutine {fprefix}_2d_array_input(c, o)\n character, intent(in) :: c(2, 3)\n integer*1 o(2, 3)\n !f2py intent(out) o\n integer i, j\n do i=1,2\n do j=1,3\n o(i, j) = transfer(c(i, j), o(i, j))\n end do\n end do\n end subroutine {fprefix}_2d_array_input\n\n subroutine {fprefix}_array_output(c, o)\n character :: c(3)\n integer*1, intent(in) :: o(3)\n !f2py intent(out) c\n do i=1,3\n c(i) = transfer(o(i), c(i))\n end do\n end subroutine {fprefix}_array_output\n\n subroutine {fprefix}_array_inout(c, n)\n character :: c(3), n(3)\n !f2py intent(in) n(3)\n !f2py intent(inout) c(3)\n do i=1,3\n c(i) = n(i)\n end do\n end subroutine {fprefix}_array_inout\n\n subroutine {fprefix}_2d_array_inout(c, n)\n character :: c(2, 3), n(2, 3)\n !f2py intent(in) n(2, 3)\n !f2py intent(inout) c(2. 3)\n integer i, j\n do i=1,2\n do j=1,3\n c(i, j) = n(i, j)\n end do\n end do\n end subroutine {fprefix}_2d_array_inout\n\n function {fprefix}_array_return(o) result (c)\n character, dimension(3) :: c\n character, intent(in) :: o(3)\n do i=1,3\n c(i) = o(i)\n end do\n end function {fprefix}_array_return\n\n function {fprefix}_optional(o) result (c)\n character, intent(in) :: o\n !f2py character o = "a"\n character :: c\n c = o\n end function {fprefix}_optional\n """)\n\n @pytest.mark.parametrize("dtype", ['c', 'S1'])\n def test_input(self, dtype):\n f = getattr(self.module, self.fprefix + '_input')\n\n assert_equal(f(np.array('a', dtype=dtype)), ord('a'))\n assert_equal(f(np.array(b'a', dtype=dtype)), ord('a'))\n assert_equal(f(np.array(['a'], dtype=dtype)), ord('a'))\n assert_equal(f(np.array('abc', dtype=dtype)), ord('a'))\n assert_equal(f(np.array([['a']], dtype=dtype)), ord('a'))\n\n def test_input_varia(self):\n f = getattr(self.module, self.fprefix + '_input')\n\n assert_equal(f('a'), ord('a'))\n assert_equal(f(b'a'), ord(b'a'))\n assert_equal(f(''), 0)\n assert_equal(f(b''), 0)\n assert_equal(f(b'\0'), 0)\n assert_equal(f('ab'), ord('a'))\n assert_equal(f(b'ab'), ord('a'))\n assert_equal(f(['a']), ord('a'))\n\n assert_equal(f(np.array(b'a')), ord('a'))\n assert_equal(f(np.array([b'a'])), ord('a'))\n a = np.array('a')\n assert_equal(f(a), ord('a'))\n a = np.array(['a'])\n assert_equal(f(a), ord('a'))\n\n try:\n f([])\n except IndexError as msg:\n if not str(msg).endswith(' got 0-list'):\n raise\n else:\n raise SystemError(f'{f.__name__} should have failed on empty list')\n\n try:\n f(97)\n except TypeError as msg:\n if not str(msg).endswith(' got int instance'):\n raise\n else:\n raise SystemError(f'{f.__name__} should have failed on int value')\n\n @pytest.mark.parametrize("dtype", ['c', 'S1', 'U1'])\n def test_array_input(self, dtype):\n f = getattr(self.module, self.fprefix + '_array_input')\n\n assert_array_equal(f(np.array(['a', 'b', 'c'], dtype=dtype)),\n np.array(list(map(ord, 'abc')), dtype='i1'))\n assert_array_equal(f(np.array([b'a', b'b', b'c'], dtype=dtype)),\n np.array(list(map(ord, 'abc')), dtype='i1'))\n\n def test_array_input_varia(self):\n f = getattr(self.module, self.fprefix + '_array_input')\n assert_array_equal(f(['a', 'b', 'c']),\n np.array(list(map(ord, 'abc')), dtype='i1'))\n assert_array_equal(f([b'a', b'b', b'c']),\n np.array(list(map(ord, 'abc')), dtype='i1'))\n\n try:\n f(['a', 'b', 'c', 'd'])\n except ValueError as msg:\n if not str(msg).endswith(\n 'th dimension must be fixed to 3 but got 4'):\n raise\n else:\n raise SystemError(\n f'{f.__name__} should have failed on wrong input')\n\n @pytest.mark.parametrize("dtype", ['c', 'S1', 'U1'])\n def test_2d_array_input(self, dtype):\n f = getattr(self.module, self.fprefix + '_2d_array_input')\n\n a = np.array([['a', 'b', 'c'],\n ['d', 'e', 'f']], dtype=dtype, order='F')\n expected = a.view(np.uint32 if dtype == 'U1' else np.uint8)\n assert_array_equal(f(a), expected)\n\n def test_output(self):\n f = getattr(self.module, self.fprefix + '_output')\n\n assert_equal(f(ord(b'a')), b'a')\n assert_equal(f(0), b'\0')\n\n def test_array_output(self):\n f = getattr(self.module, self.fprefix + '_array_output')\n\n assert_array_equal(f(list(map(ord, 'abc'))),\n np.array(list('abc'), dtype='S1'))\n\n def test_input_output(self):\n f = getattr(self.module, self.fprefix + '_input_output')\n\n assert_equal(f(b'a'), b'a')\n assert_equal(f('a'), b'a')\n assert_equal(f(''), b'\0')\n\n @pytest.mark.parametrize("dtype", ['c', 'S1'])\n def test_inout(self, dtype):\n f = getattr(self.module, self.fprefix + '_inout')\n\n a = np.array(list('abc'), dtype=dtype)\n f(a, 'A')\n assert_array_equal(a, np.array(list('Abc'), dtype=a.dtype))\n f(a[1:], 'B')\n assert_array_equal(a, np.array(list('ABc'), dtype=a.dtype))\n\n a = np.array(['abc'], dtype=dtype)\n f(a, 'A')\n assert_array_equal(a, np.array(['Abc'], dtype=a.dtype))\n\n def test_inout_varia(self):\n f = getattr(self.module, self.fprefix + '_inout')\n a = np.array('abc', dtype='S3')\n f(a, 'A')\n assert_array_equal(a, np.array('Abc', dtype=a.dtype))\n\n a = np.array(['abc'], dtype='S3')\n f(a, 'A')\n assert_array_equal(a, np.array(['Abc'], dtype=a.dtype))\n\n try:\n f('abc', 'A')\n except ValueError as msg:\n if not str(msg).endswith(' got 3-str'):\n raise\n else:\n raise SystemError(f'{f.__name__} should have failed on str value')\n\n @pytest.mark.parametrize("dtype", ['c', 'S1'])\n def test_array_inout(self, dtype):\n f = getattr(self.module, self.fprefix + '_array_inout')\n n = np.array(['A', 'B', 'C'], dtype=dtype, order='F')\n\n a = np.array(['a', 'b', 'c'], dtype=dtype, order='F')\n f(a, n)\n assert_array_equal(a, n)\n\n a = np.array(['a', 'b', 'c', 'd'], dtype=dtype)\n f(a[1:], n)\n assert_array_equal(a, np.array(['a', 'A', 'B', 'C'], dtype=dtype))\n\n a = np.array([['a', 'b', 'c']], dtype=dtype, order='F')\n f(a, n)\n assert_array_equal(a, np.array([['A', 'B', 'C']], dtype=dtype))\n\n a = np.array(['a', 'b', 'c', 'd'], dtype=dtype, order='F')\n try:\n f(a, n)\n except ValueError as msg:\n if not str(msg).endswith(\n 'th dimension must be fixed to 3 but got 4'):\n raise\n else:\n raise SystemError(\n f'{f.__name__} should have failed on wrong input')\n\n @pytest.mark.parametrize("dtype", ['c', 'S1'])\n def test_2d_array_inout(self, dtype):\n f = getattr(self.module, self.fprefix + '_2d_array_inout')\n n = np.array([['A', 'B', 'C'],\n ['D', 'E', 'F']],\n dtype=dtype, order='F')\n a = np.array([['a', 'b', 'c'],\n ['d', 'e', 'f']],\n dtype=dtype, order='F')\n f(a, n)\n assert_array_equal(a, n)\n\n def test_return(self):\n f = getattr(self.module, self.fprefix + '_return')\n\n assert_equal(f('a'), b'a')\n\n @pytest.mark.skip('fortran function returning array segfaults')\n def test_array_return(self):\n f = getattr(self.module, self.fprefix + '_array_return')\n\n a = np.array(list('abc'), dtype='S1')\n assert_array_equal(f(a), a)\n\n def test_optional(self):\n f = getattr(self.module, self.fprefix + '_optional')\n\n assert_equal(f(), b"a")\n assert_equal(f(b'B'), b"B")\n\n\nclass TestMiscCharacter(util.F2PyTest):\n # options = ['--debug-capi', '--build-dir', '/tmp/test-build-f2py']\n suffix = '.f90'\n fprefix = 'test_misc_character'\n\n code = textwrap.dedent(f"""\n subroutine {fprefix}_gh18684(x, y, m)\n character(len=5), dimension(m), intent(in) :: x\n character*5, dimension(m), intent(out) :: y\n integer i, m\n !f2py integer, intent(hide), depend(x) :: m = f2py_len(x)\n do i=1,m\n y(i) = x(i)\n end do\n end subroutine {fprefix}_gh18684\n\n subroutine {fprefix}_gh6308(x, i)\n integer i\n !f2py check(i>=0 && i<12) i\n character*5 name, x\n common name(12)\n name(i + 1) = x\n end subroutine {fprefix}_gh6308\n\n subroutine {fprefix}_gh4519(x)\n character(len=*), intent(in) :: x(:)\n !f2py intent(out) x\n integer :: i\n ! Uncomment for debug printing:\n !do i=1, size(x)\n ! print*, "x(",i,")=", x(i)\n !end do\n end subroutine {fprefix}_gh4519\n\n pure function {fprefix}_gh3425(x) result (y)\n character(len=*), intent(in) :: x\n character(len=len(x)) :: y\n integer :: i\n do i = 1, len(x)\n j = iachar(x(i:i))\n if (j>=iachar("a") .and. j<=iachar("z") ) then\n y(i:i) = achar(j-32)\n else\n y(i:i) = x(i:i)\n endif\n end do\n end function {fprefix}_gh3425\n\n subroutine {fprefix}_character_bc_new(x, y, z)\n character, intent(in) :: x\n character, intent(out) :: y\n !f2py character, depend(x) :: y = x\n !f2py character, dimension((x=='a'?1:2)), depend(x), intent(out) :: z\n character, dimension(*) :: z\n !f2py character, optional, check(x == 'a' || x == 'b') :: x = 'a'\n !f2py callstatement (*f2py_func)(&x, &y, z)\n !f2py callprotoargument character*, character*, character*\n if (y.eq.x) then\n y = x\n else\n y = 'e'\n endif\n z(1) = 'c'\n end subroutine {fprefix}_character_bc_new\n\n subroutine {fprefix}_character_bc_old(x, y, z)\n character, intent(in) :: x\n character, intent(out) :: y\n !f2py character, depend(x) :: y = x[0]\n !f2py character, dimension((*x=='a'?1:2)), depend(x), intent(out) :: z\n character, dimension(*) :: z\n !f2py character, optional, check(*x == 'a' || x[0] == 'b') :: x = 'a'\n !f2py callstatement (*f2py_func)(x, y, z)\n !f2py callprotoargument char*, char*, char*\n if (y.eq.x) then\n y = x\n else\n y = 'e'\n endif\n z(1) = 'c'\n end subroutine {fprefix}_character_bc_old\n """)\n\n @pytest.mark.slow\n def test_gh18684(self):\n # Test character(len=5) and character*5 usages\n f = getattr(self.module, self.fprefix + '_gh18684')\n x = np.array(["abcde", "fghij"], dtype='S5')\n y = f(x)\n\n assert_array_equal(x, y)\n\n def test_gh6308(self):\n # Test character string array in a common block\n f = getattr(self.module, self.fprefix + '_gh6308')\n\n assert_equal(self.module._BLNK_.name.dtype, np.dtype('S5'))\n assert_equal(len(self.module._BLNK_.name), 12)\n f("abcde", 0)\n assert_equal(self.module._BLNK_.name[0], b"abcde")\n f("12345", 5)\n assert_equal(self.module._BLNK_.name[5], b"12345")\n\n def test_gh4519(self):\n # Test array of assumed length strings\n f = getattr(self.module, self.fprefix + '_gh4519')\n\n for x, expected in [\n ('a', {'shape': (), 'dtype': np.dtype('S1')}),\n ('text', {'shape': (), 'dtype': np.dtype('S4')}),\n (np.array(['1', '2', '3'], dtype='S1'),\n {'shape': (3,), 'dtype': np.dtype('S1')}),\n (['1', '2', '34'],\n {'shape': (3,), 'dtype': np.dtype('S2')}),\n (['', ''], {'shape': (2,), 'dtype': np.dtype('S1')})]:\n r = f(x)\n for k, v in expected.items():\n assert_equal(getattr(r, k), v)\n\n def test_gh3425(self):\n # Test returning a copy of assumed length string\n f = getattr(self.module, self.fprefix + '_gh3425')\n # f is equivalent to bytes.upper\n\n assert_equal(f('abC'), b'ABC')\n assert_equal(f(''), b'')\n assert_equal(f('abC12d'), b'ABC12D')\n\n @pytest.mark.parametrize("state", ['new', 'old'])\n def test_character_bc(self, state):\n f = getattr(self.module, self.fprefix + '_character_bc_' + state)\n\n c, a = f()\n assert_equal(c, b'a')\n assert_equal(len(a), 1)\n\n c, a = f(b'b')\n assert_equal(c, b'b')\n assert_equal(len(a), 2)\n\n assert_raises(Exception, lambda: f(b'c'))\n\n\nclass TestStringScalarArr(util.F2PyTest):\n sources = [util.getpath("tests", "src", "string", "scalar_string.f90")]\n\n def test_char(self):\n for out in (self.module.string_test.string,\n self.module.string_test.string77):\n expected = ()\n assert out.shape == expected\n expected = '|S8'\n assert out.dtype == expected\n\n def test_char_arr(self):\n for out in (self.module.string_test.strarr,\n self.module.string_test.strarr77):\n expected = (5, 7)\n assert out.shape == expected\n expected = '|S12'\n assert out.dtype == expected\n\nclass TestStringAssumedLength(util.F2PyTest):\n sources = [util.getpath("tests", "src", "string", "gh24008.f")]\n\n def test_gh24008(self):\n self.module.greet("joe", "bob")\n\n@pytest.mark.slow\nclass TestStringOptionalInOut(util.F2PyTest):\n sources = [util.getpath("tests", "src", "string", "gh24662.f90")]\n\n def test_gh24662(self):\n self.module.string_inout_optional()\n a = np.array('hi', dtype='S32')\n self.module.string_inout_optional(a)\n assert "output string" in a.tobytes().decode()\n with pytest.raises(Exception): # noqa: B017\n aa = "Hi"\n self.module.string_inout_optional(aa)\n\n\n@pytest.mark.slow\nclass TestNewCharHandling(util.F2PyTest):\n # from v1.24 onwards, gh-19388\n sources = [\n util.getpath("tests", "src", "string", "gh25286.pyf"),\n util.getpath("tests", "src", "string", "gh25286.f90")\n ]\n module_name = "_char_handling_test"\n\n def test_gh25286(self):\n info = self.module.charint('T')\n assert info == 2\n\n@pytest.mark.slow\nclass TestBCCharHandling(util.F2PyTest):\n # SciPy style, "incorrect" bindings with a hook\n sources = [\n util.getpath("tests", "src", "string", "gh25286_bc.pyf"),\n util.getpath("tests", "src", "string", "gh25286.f90")\n ]\n module_name = "_char_handling_test"\n\n def test_gh25286(self):\n info = self.module.charint('T')\n assert info == 2\n
.venv\Lib\site-packages\numpy\f2py\tests\test_character.py
test_character.py
Python
22,572
0.95
0.112324
0.018797
python-kit
949
2025-01-22T13:34:56.304029
MIT
true
0d738bdf114fc4b4af47bab1a5d6faed
import pytest\n\nimport numpy as np\n\nfrom . import util\n\n\n@pytest.mark.slow\nclass TestCommonBlock(util.F2PyTest):\n sources = [util.getpath("tests", "src", "common", "block.f")]\n\n def test_common_block(self):\n self.module.initcb()\n assert self.module.block.long_bn == np.array(1.0, dtype=np.float64)\n assert self.module.block.string_bn == np.array("2", dtype="|S1")\n assert self.module.block.ok == np.array(3, dtype=np.int32)\n\n\nclass TestCommonWithUse(util.F2PyTest):\n sources = [util.getpath("tests", "src", "common", "gh19161.f90")]\n\n def test_common_gh19161(self):\n assert self.module.data.x == 0\n
.venv\Lib\site-packages\numpy\f2py\tests\test_common.py
test_common.py
Python
667
0.85
0.173913
0
node-utils
414
2025-02-25T12:59:45.931502
GPL-3.0
true
7691db91fd35b207841743a364cb1f41
import contextlib\nimport importlib\nimport io\nimport textwrap\nimport time\n\nimport pytest\n\nimport numpy as np\nfrom numpy.f2py import crackfortran\nfrom numpy.f2py.crackfortran import markinnerspaces, nameargspattern\n\nfrom . import util\n\n\nclass TestNoSpace(util.F2PyTest):\n # issue gh-15035: add handling for endsubroutine, endfunction with no space\n # between "end" and the block name\n sources = [util.getpath("tests", "src", "crackfortran", "gh15035.f")]\n\n def test_module(self):\n k = np.array([1, 2, 3], dtype=np.float64)\n w = np.array([1, 2, 3], dtype=np.float64)\n self.module.subb(k)\n assert np.allclose(k, w + 1)\n self.module.subc([w, k])\n assert np.allclose(k, w + 1)\n assert self.module.t0("23") == b"2"\n\n\nclass TestPublicPrivate:\n def test_defaultPrivate(self):\n fpath = util.getpath("tests", "src", "crackfortran", "privatemod.f90")\n mod = crackfortran.crackfortran([str(fpath)])\n assert len(mod) == 1\n mod = mod[0]\n assert "private" in mod["vars"]["a"]["attrspec"]\n assert "public" not in mod["vars"]["a"]["attrspec"]\n assert "private" in mod["vars"]["b"]["attrspec"]\n assert "public" not in mod["vars"]["b"]["attrspec"]\n assert "private" not in mod["vars"]["seta"]["attrspec"]\n assert "public" in mod["vars"]["seta"]["attrspec"]\n\n def test_defaultPublic(self, tmp_path):\n fpath = util.getpath("tests", "src", "crackfortran", "publicmod.f90")\n mod = crackfortran.crackfortran([str(fpath)])\n assert len(mod) == 1\n mod = mod[0]\n assert "private" in mod["vars"]["a"]["attrspec"]\n assert "public" not in mod["vars"]["a"]["attrspec"]\n assert "private" not in mod["vars"]["seta"]["attrspec"]\n assert "public" in mod["vars"]["seta"]["attrspec"]\n\n def test_access_type(self, tmp_path):\n fpath = util.getpath("tests", "src", "crackfortran", "accesstype.f90")\n mod = crackfortran.crackfortran([str(fpath)])\n assert len(mod) == 1\n tt = mod[0]['vars']\n assert set(tt['a']['attrspec']) == {'private', 'bind(c)'}\n assert set(tt['b_']['attrspec']) == {'public', 'bind(c)'}\n assert set(tt['c']['attrspec']) == {'public'}\n\n def test_nowrap_private_proceedures(self, tmp_path):\n fpath = util.getpath("tests", "src", "crackfortran", "gh23879.f90")\n mod = crackfortran.crackfortran([str(fpath)])\n assert len(mod) == 1\n pyf = crackfortran.crack2fortran(mod)\n assert 'bar' not in pyf\n\nclass TestModuleProcedure:\n def test_moduleOperators(self, tmp_path):\n fpath = util.getpath("tests", "src", "crackfortran", "operators.f90")\n mod = crackfortran.crackfortran([str(fpath)])\n assert len(mod) == 1\n mod = mod[0]\n assert "body" in mod and len(mod["body"]) == 9\n assert mod["body"][1]["name"] == "operator(.item.)"\n assert "implementedby" in mod["body"][1]\n assert mod["body"][1]["implementedby"] == \\n ["item_int", "item_real"]\n assert mod["body"][2]["name"] == "operator(==)"\n assert "implementedby" in mod["body"][2]\n assert mod["body"][2]["implementedby"] == ["items_are_equal"]\n assert mod["body"][3]["name"] == "assignment(=)"\n assert "implementedby" in mod["body"][3]\n assert mod["body"][3]["implementedby"] == \\n ["get_int", "get_real"]\n\n def test_notPublicPrivate(self, tmp_path):\n fpath = util.getpath("tests", "src", "crackfortran", "pubprivmod.f90")\n mod = crackfortran.crackfortran([str(fpath)])\n assert len(mod) == 1\n mod = mod[0]\n assert mod['vars']['a']['attrspec'] == ['private', ]\n assert mod['vars']['b']['attrspec'] == ['public', ]\n assert mod['vars']['seta']['attrspec'] == ['public', ]\n\n\nclass TestExternal(util.F2PyTest):\n # issue gh-17859: add external attribute support\n sources = [util.getpath("tests", "src", "crackfortran", "gh17859.f")]\n\n def test_external_as_statement(self):\n def incr(x):\n return x + 123\n\n r = self.module.external_as_statement(incr)\n assert r == 123\n\n def test_external_as_attribute(self):\n def incr(x):\n return x + 123\n\n r = self.module.external_as_attribute(incr)\n assert r == 123\n\n\nclass TestCrackFortran(util.F2PyTest):\n # gh-2848: commented lines between parameters in subroutine parameter lists\n sources = [util.getpath("tests", "src", "crackfortran", "gh2848.f90"),\n util.getpath("tests", "src", "crackfortran", "common_with_division.f")\n ]\n\n def test_gh2848(self):\n r = self.module.gh2848(1, 2)\n assert r == (1, 2)\n\n def test_common_with_division(self):\n assert len(self.module.mortmp.ctmp) == 11\n\nclass TestMarkinnerspaces:\n # gh-14118: markinnerspaces does not handle multiple quotations\n\n def test_do_not_touch_normal_spaces(self):\n test_list = ["a ", " a", "a b c", "'abcdefghij'"]\n for i in test_list:\n assert markinnerspaces(i) == i\n\n def test_one_relevant_space(self):\n assert markinnerspaces("a 'b c' \\' \\'") == "a 'b@_@c' \\' \\'"\n assert markinnerspaces(r'a "b c" \" \"') == r'a "b@_@c" \" \"'\n\n def test_ignore_inner_quotes(self):\n assert markinnerspaces("a 'b c\" \" d' e") == "a 'b@_@c\"@_@\"@_@d' e"\n assert markinnerspaces("a \"b c' ' d\" e") == "a \"b@_@c'@_@'@_@d\" e"\n\n def test_multiple_relevant_spaces(self):\n assert markinnerspaces("a 'b c' 'd e'") == "a 'b@_@c' 'd@_@e'"\n assert markinnerspaces(r'a "b c" "d e"') == r'a "b@_@c" "d@_@e"'\n\n\nclass TestDimSpec(util.F2PyTest):\n """This test suite tests various expressions that are used as dimension\n specifications.\n\n There exists two usage cases where analyzing dimensions\n specifications are important.\n\n In the first case, the size of output arrays must be defined based\n on the inputs to a Fortran function. Because Fortran supports\n arbitrary bases for indexing, for instance, `arr(lower:upper)`,\n f2py has to evaluate an expression `upper - lower + 1` where\n `lower` and `upper` are arbitrary expressions of input parameters.\n The evaluation is performed in C, so f2py has to translate Fortran\n expressions to valid C expressions (an alternative approach is\n that a developer specifies the corresponding C expressions in a\n .pyf file).\n\n In the second case, when user provides an input array with a given\n size but some hidden parameters used in dimensions specifications\n need to be determined based on the input array size. This is a\n harder problem because f2py has to solve the inverse problem: find\n a parameter `p` such that `upper(p) - lower(p) + 1` equals to the\n size of input array. In the case when this equation cannot be\n solved (e.g. because the input array size is wrong), raise an\n error before calling the Fortran function (that otherwise would\n likely crash Python process when the size of input arrays is\n wrong). f2py currently supports this case only when the equation\n is linear with respect to unknown parameter.\n\n """\n\n suffix = ".f90"\n\n code_template = textwrap.dedent("""\n function get_arr_size_{count}(a, n) result (length)\n integer, intent(in) :: n\n integer, dimension({dimspec}), intent(out) :: a\n integer length\n length = size(a)\n end function\n\n subroutine get_inv_arr_size_{count}(a, n)\n integer :: n\n ! the value of n is computed in f2py wrapper\n !f2py intent(out) n\n integer, dimension({dimspec}), intent(in) :: a\n if (a({first}).gt.0) then\n ! print*, "a=", a\n endif\n end subroutine\n """)\n\n linear_dimspecs = [\n "n", "2*n", "2:n", "n/2", "5 - n/2", "3*n:20", "n*(n+1):n*(n+5)",\n "2*n, n"\n ]\n nonlinear_dimspecs = ["2*n:3*n*n+2*n"]\n all_dimspecs = linear_dimspecs + nonlinear_dimspecs\n\n code = ""\n for count, dimspec in enumerate(all_dimspecs):\n lst = [(d.split(":")[0] if ":" in d else "1") for d in dimspec.split(',')]\n code += code_template.format(\n count=count,\n dimspec=dimspec,\n first=", ".join(lst),\n )\n\n @pytest.mark.parametrize("dimspec", all_dimspecs)\n @pytest.mark.slow\n def test_array_size(self, dimspec):\n\n count = self.all_dimspecs.index(dimspec)\n get_arr_size = getattr(self.module, f"get_arr_size_{count}")\n\n for n in [1, 2, 3, 4, 5]:\n sz, a = get_arr_size(n)\n assert a.size == sz\n\n @pytest.mark.parametrize("dimspec", all_dimspecs)\n def test_inv_array_size(self, dimspec):\n\n count = self.all_dimspecs.index(dimspec)\n get_arr_size = getattr(self.module, f"get_arr_size_{count}")\n get_inv_arr_size = getattr(self.module, f"get_inv_arr_size_{count}")\n\n for n in [1, 2, 3, 4, 5]:\n sz, a = get_arr_size(n)\n if dimspec in self.nonlinear_dimspecs:\n # one must specify n as input, the call we'll ensure\n # that a and n are compatible:\n n1 = get_inv_arr_size(a, n)\n else:\n # in case of linear dependence, n can be determined\n # from the shape of a:\n n1 = get_inv_arr_size(a)\n # n1 may be different from n (for instance, when `a` size\n # is a function of some `n` fraction) but it must produce\n # the same sized array\n sz1, _ = get_arr_size(n1)\n assert sz == sz1, (n, n1, sz, sz1)\n\n\nclass TestModuleDeclaration:\n def test_dependencies(self, tmp_path):\n fpath = util.getpath("tests", "src", "crackfortran", "foo_deps.f90")\n mod = crackfortran.crackfortran([str(fpath)])\n assert len(mod) == 1\n assert mod[0]["vars"]["abar"]["="] == "bar('abar')"\n\n\nclass TestEval(util.F2PyTest):\n def test_eval_scalar(self):\n eval_scalar = crackfortran._eval_scalar\n\n assert eval_scalar('123', {}) == '123'\n assert eval_scalar('12 + 3', {}) == '15'\n assert eval_scalar('a + b', {"a": 1, "b": 2}) == '3'\n assert eval_scalar('"123"', {}) == "'123'"\n\n\nclass TestFortranReader(util.F2PyTest):\n @pytest.mark.parametrize("encoding",\n ['ascii', 'utf-8', 'utf-16', 'utf-32'])\n def test_input_encoding(self, tmp_path, encoding):\n # gh-635\n f_path = tmp_path / f"input_with_{encoding}_encoding.f90"\n with f_path.open('w', encoding=encoding) as ff:\n ff.write("""\n subroutine foo()\n end subroutine foo\n """)\n mod = crackfortran.crackfortran([str(f_path)])\n assert mod[0]['name'] == 'foo'\n\n\n@pytest.mark.slow\nclass TestUnicodeComment(util.F2PyTest):\n sources = [util.getpath("tests", "src", "crackfortran", "unicode_comment.f90")]\n\n @pytest.mark.skipif(\n (importlib.util.find_spec("charset_normalizer") is None),\n reason="test requires charset_normalizer which is not installed",\n )\n def test_encoding_comment(self):\n self.module.foo(3)\n\n\nclass TestNameArgsPatternBacktracking:\n @pytest.mark.parametrize(\n ['adversary'],\n [\n ('@)@bind@(@',),\n ('@)@bind @(@',),\n ('@)@bind foo bar baz@(@',)\n ]\n )\n def test_nameargspattern_backtracking(self, adversary):\n '''address ReDOS vulnerability:\n https://github.com/numpy/numpy/issues/23338'''\n trials_per_batch = 12\n batches_per_regex = 4\n start_reps, end_reps = 15, 25\n for ii in range(start_reps, end_reps):\n repeated_adversary = adversary * ii\n # test times in small batches.\n # this gives us more chances to catch a bad regex\n # while still catching it before too long if it is bad\n for _ in range(batches_per_regex):\n times = []\n for _ in range(trials_per_batch):\n t0 = time.perf_counter()\n mtch = nameargspattern.search(repeated_adversary)\n times.append(time.perf_counter() - t0)\n # our pattern should be much faster than 0.2s per search\n # it's unlikely that a bad regex will pass even on fast CPUs\n assert np.median(times) < 0.2\n assert not mtch\n # if the adversary is capped with @)@, it becomes acceptable\n # according to the old version of the regex.\n # that should still be true.\n good_version_of_adversary = repeated_adversary + '@)@'\n assert nameargspattern.search(good_version_of_adversary)\n\nclass TestFunctionReturn(util.F2PyTest):\n sources = [util.getpath("tests", "src", "crackfortran", "gh23598.f90")]\n\n @pytest.mark.slow\n def test_function_rettype(self):\n # gh-23598\n assert self.module.intproduct(3, 4) == 12\n\n\nclass TestFortranGroupCounters(util.F2PyTest):\n def test_end_if_comment(self):\n # gh-23533\n fpath = util.getpath("tests", "src", "crackfortran", "gh23533.f")\n try:\n crackfortran.crackfortran([str(fpath)])\n except Exception as exc:\n assert False, f"'crackfortran.crackfortran' raised an exception {exc}"\n\n\nclass TestF77CommonBlockReader:\n def test_gh22648(self, tmp_path):\n fpath = util.getpath("tests", "src", "crackfortran", "gh22648.pyf")\n with contextlib.redirect_stdout(io.StringIO()) as stdout_f2py:\n mod = crackfortran.crackfortran([str(fpath)])\n assert "Mismatch" not in stdout_f2py.getvalue()\n\nclass TestParamEval:\n # issue gh-11612, array parameter parsing\n def test_param_eval_nested(self):\n v = '(/3.14, 4./)'\n g_params = {"kind": crackfortran._kind_func,\n "selected_int_kind": crackfortran._selected_int_kind_func,\n "selected_real_kind": crackfortran._selected_real_kind_func}\n params = {'dp': 8, 'intparamarray': {1: 3, 2: 5},\n 'nested': {1: 1, 2: 2, 3: 3}}\n dimspec = '(2)'\n ret = crackfortran.param_eval(v, g_params, params, dimspec=dimspec)\n assert ret == {1: 3.14, 2: 4.0}\n\n def test_param_eval_nonstandard_range(self):\n v = '(/ 6, 3, 1 /)'\n g_params = {"kind": crackfortran._kind_func,\n "selected_int_kind": crackfortran._selected_int_kind_func,\n "selected_real_kind": crackfortran._selected_real_kind_func}\n params = {}\n dimspec = '(-1:1)'\n ret = crackfortran.param_eval(v, g_params, params, dimspec=dimspec)\n assert ret == {-1: 6, 0: 3, 1: 1}\n\n def test_param_eval_empty_range(self):\n v = '6'\n g_params = {"kind": crackfortran._kind_func,\n "selected_int_kind": crackfortran._selected_int_kind_func,\n "selected_real_kind": crackfortran._selected_real_kind_func}\n params = {}\n dimspec = ''\n pytest.raises(ValueError, crackfortran.param_eval, v, g_params, params,\n dimspec=dimspec)\n\n def test_param_eval_non_array_param(self):\n v = '3.14_dp'\n g_params = {"kind": crackfortran._kind_func,\n "selected_int_kind": crackfortran._selected_int_kind_func,\n "selected_real_kind": crackfortran._selected_real_kind_func}\n params = {}\n ret = crackfortran.param_eval(v, g_params, params, dimspec=None)\n assert ret == '3.14_dp'\n\n def test_param_eval_too_many_dims(self):\n v = 'reshape((/ (i, i=1, 250) /), (/5, 10, 5/))'\n g_params = {"kind": crackfortran._kind_func,\n "selected_int_kind": crackfortran._selected_int_kind_func,\n "selected_real_kind": crackfortran._selected_real_kind_func}\n params = {}\n dimspec = '(0:4, 3:12, 5)'\n pytest.raises(ValueError, crackfortran.param_eval, v, g_params, params,\n dimspec=dimspec)\n\n@pytest.mark.slow\nclass TestLowerF2PYDirective(util.F2PyTest):\n sources = [util.getpath("tests", "src", "crackfortran", "gh27697.f90")]\n options = ['--lower']\n\n def test_no_lower_fail(self):\n with pytest.raises(ValueError, match='aborting directly') as exc:\n self.module.utils.my_abort('aborting directly')\n
.venv\Lib\site-packages\numpy\f2py\tests\test_crackfortran.py
test_crackfortran.py
Python
16,834
0.95
0.178147
0.068376
vue-tools
992
2024-11-03T07:32:50.977808
MIT
true
ab1acc60d9ccc3326597635c0c3832ce
import pytest\n\nimport numpy as np\nfrom numpy.f2py.crackfortran import crackfortran\n\nfrom . import util\n\n\nclass TestData(util.F2PyTest):\n sources = [util.getpath("tests", "src", "crackfortran", "data_stmts.f90")]\n\n # For gh-23276\n @pytest.mark.slow\n def test_data_stmts(self):\n assert self.module.cmplxdat.i == 2\n assert self.module.cmplxdat.j == 3\n assert self.module.cmplxdat.x == 1.5\n assert self.module.cmplxdat.y == 2.0\n assert self.module.cmplxdat.pi == 3.1415926535897932384626433832795028841971693993751058209749445923078164062\n assert self.module.cmplxdat.medium_ref_index == np.array(1. + 0.j)\n assert np.all(self.module.cmplxdat.z == np.array([3.5, 7.0]))\n assert np.all(self.module.cmplxdat.my_array == np.array([ 1. + 2.j, -3. + 4.j]))\n assert np.all(self.module.cmplxdat.my_real_array == np.array([ 1., 2., 3.]))\n assert np.all(self.module.cmplxdat.ref_index_one == np.array([13.0 + 21.0j]))\n assert np.all(self.module.cmplxdat.ref_index_two == np.array([-30.0 + 43.0j]))\n\n def test_crackedlines(self):\n mod = crackfortran(self.sources)\n assert mod[0]['vars']['x']['='] == '1.5'\n assert mod[0]['vars']['y']['='] == '2.0'\n assert mod[0]['vars']['pi']['='] == '3.1415926535897932384626433832795028841971693993751058209749445923078164062d0'\n assert mod[0]['vars']['my_real_array']['='] == '(/1.0d0, 2.0d0, 3.0d0/)'\n assert mod[0]['vars']['ref_index_one']['='] == '(13.0d0, 21.0d0)'\n assert mod[0]['vars']['ref_index_two']['='] == '(-30.0d0, 43.0d0)'\n assert mod[0]['vars']['my_array']['='] == '(/(1.0d0, 2.0d0), (-3.0d0, 4.0d0)/)'\n assert mod[0]['vars']['z']['='] == '(/3.5, 7.0/)'\n\nclass TestDataF77(util.F2PyTest):\n sources = [util.getpath("tests", "src", "crackfortran", "data_common.f")]\n\n # For gh-23276\n def test_data_stmts(self):\n assert self.module.mycom.mydata == 0\n\n def test_crackedlines(self):\n mod = crackfortran(str(self.sources[0]))\n print(mod[0]['vars'])\n assert mod[0]['vars']['mydata']['='] == '0'\n\n\nclass TestDataMultiplierF77(util.F2PyTest):\n sources = [util.getpath("tests", "src", "crackfortran", "data_multiplier.f")]\n\n # For gh-23276\n def test_data_stmts(self):\n assert self.module.mycom.ivar1 == 3\n assert self.module.mycom.ivar2 == 3\n assert self.module.mycom.ivar3 == 2\n assert self.module.mycom.ivar4 == 2\n assert self.module.mycom.evar5 == 0\n\n\nclass TestDataWithCommentsF77(util.F2PyTest):\n sources = [util.getpath("tests", "src", "crackfortran", "data_with_comments.f")]\n\n # For gh-23276\n def test_data_stmts(self):\n assert len(self.module.mycom.mytab) == 3\n assert self.module.mycom.mytab[0] == 0\n assert self.module.mycom.mytab[1] == 4\n assert self.module.mycom.mytab[2] == 0\n
.venv\Lib\site-packages\numpy\f2py\tests\test_data.py
test_data.py
Python
2,966
0.95
0.140845
0.071429
vue-tools
955
2024-02-04T05:06:34.799478
GPL-3.0
true
e8f33723128785fa07c02381547cd49c
from pathlib import Path\n\nimport pytest\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_equal\n\nfrom . import util\n\n\ndef get_docdir():\n parents = Path(__file__).resolve().parents\n try:\n # Assumes that spin is used to run tests\n nproot = parents[8]\n except IndexError:\n docdir = None\n else:\n docdir = nproot / "doc" / "source" / "f2py" / "code"\n if docdir and docdir.is_dir():\n return docdir\n # Assumes that an editable install is used to run tests\n return parents[3] / "doc" / "source" / "f2py" / "code"\n\n\npytestmark = pytest.mark.skipif(\n not get_docdir().is_dir(),\n reason=f"Could not find f2py documentation sources"\n f"({get_docdir()} does not exist)",\n)\n\ndef _path(*args):\n return get_docdir().joinpath(*args)\n\n@pytest.mark.slow\nclass TestDocAdvanced(util.F2PyTest):\n # options = ['--debug-capi', '--build-dir', '/tmp/build-f2py']\n sources = [_path('asterisk1.f90'), _path('asterisk2.f90'),\n _path('ftype.f')]\n\n def test_asterisk1(self):\n foo = self.module.foo1\n assert_equal(foo(), b'123456789A12')\n\n def test_asterisk2(self):\n foo = self.module.foo2\n assert_equal(foo(2), b'12')\n assert_equal(foo(12), b'123456789A12')\n assert_equal(foo(20), b'123456789A123456789B')\n\n def test_ftype(self):\n ftype = self.module\n ftype.foo()\n assert_equal(ftype.data.a, 0)\n ftype.data.a = 3\n ftype.data.x = [1, 2, 3]\n assert_equal(ftype.data.a, 3)\n assert_array_equal(ftype.data.x,\n np.array([1, 2, 3], dtype=np.float32))\n ftype.data.x[1] = 45\n assert_array_equal(ftype.data.x,\n np.array([1, 45, 3], dtype=np.float32))\n\n # TODO: implement test methods for other example Fortran codes\n
.venv\Lib\site-packages\numpy\f2py\tests\test_docs.py
test_docs.py
Python
1,919
0.95
0.140625
0.078431
react-lib
103
2024-10-14T23:54:47.208553
MIT
true
54674c78961aebc2b1454bd7069b4cdf
import numpy as np\n\nfrom . import util\n\n\nclass TestF2Cmap(util.F2PyTest):\n sources = [\n util.getpath("tests", "src", "f2cmap", "isoFortranEnvMap.f90"),\n util.getpath("tests", "src", "f2cmap", ".f2py_f2cmap")\n ]\n\n # gh-15095\n def test_gh15095(self):\n inp = np.ones(3)\n out = self.module.func1(inp)\n exp_out = 3\n assert out == exp_out\n
.venv\Lib\site-packages\numpy\f2py\tests\test_f2cmap.py
test_f2cmap.py
Python
404
0.95
0.117647
0.076923
node-utils
848
2024-11-01T03:03:25.669809
GPL-3.0
true
d82aa6c8eec0e207bba3fa433776b30d
import platform\nimport re\nimport shlex\nimport subprocess\nimport sys\nimport textwrap\nfrom collections import namedtuple\nfrom pathlib import Path\n\nimport pytest\n\nfrom numpy.f2py.f2py2e import main as f2pycli\nfrom numpy.testing._private.utils import NOGIL_BUILD\n\nfrom . import util\n\n#######################\n# F2PY Test utilities #\n######################\n\n# Tests for CLI commands which call meson will fail if no compilers are present, these are to be skipped\n\ndef compiler_check_f2pycli():\n if not util.has_fortran_compiler():\n pytest.skip("CLI command needs a Fortran compiler")\n else:\n f2pycli()\n\n#########################\n# CLI utils and classes #\n#########################\n\n\nPPaths = namedtuple("PPaths", "finp, f90inp, pyf, wrap77, wrap90, cmodf")\n\n\ndef get_io_paths(fname_inp, mname="untitled"):\n """Takes in a temporary file for testing and returns the expected output and input paths\n\n Here expected output is essentially one of any of the possible generated\n files.\n\n ..note::\n\n Since this does not actually run f2py, none of these are guaranteed to\n exist, and module names are typically incorrect\n\n Parameters\n ----------\n fname_inp : str\n The input filename\n mname : str, optional\n The name of the module, untitled by default\n\n Returns\n -------\n genp : NamedTuple PPaths\n The possible paths which are generated, not all of which exist\n """\n bpath = Path(fname_inp)\n return PPaths(\n finp=bpath.with_suffix(".f"),\n f90inp=bpath.with_suffix(".f90"),\n pyf=bpath.with_suffix(".pyf"),\n wrap77=bpath.with_name(f"{mname}-f2pywrappers.f"),\n wrap90=bpath.with_name(f"{mname}-f2pywrappers2.f90"),\n cmodf=bpath.with_name(f"{mname}module.c"),\n )\n\n\n################\n# CLI Fixtures #\n################\n\n\n@pytest.fixture(scope="session")\ndef hello_world_f90(tmpdir_factory):\n """Generates a single f90 file for testing"""\n fdat = util.getpath("tests", "src", "cli", "hiworld.f90").read_text()\n fn = tmpdir_factory.getbasetemp() / "hello.f90"\n fn.write_text(fdat, encoding="ascii")\n return fn\n\n\n@pytest.fixture(scope="session")\ndef gh23598_warn(tmpdir_factory):\n """F90 file for testing warnings in gh23598"""\n fdat = util.getpath("tests", "src", "crackfortran", "gh23598Warn.f90").read_text()\n fn = tmpdir_factory.getbasetemp() / "gh23598Warn.f90"\n fn.write_text(fdat, encoding="ascii")\n return fn\n\n\n@pytest.fixture(scope="session")\ndef gh22819_cli(tmpdir_factory):\n """F90 file for testing disallowed CLI arguments in ghff819"""\n fdat = util.getpath("tests", "src", "cli", "gh_22819.pyf").read_text()\n fn = tmpdir_factory.getbasetemp() / "gh_22819.pyf"\n fn.write_text(fdat, encoding="ascii")\n return fn\n\n\n@pytest.fixture(scope="session")\ndef hello_world_f77(tmpdir_factory):\n """Generates a single f77 file for testing"""\n fdat = util.getpath("tests", "src", "cli", "hi77.f").read_text()\n fn = tmpdir_factory.getbasetemp() / "hello.f"\n fn.write_text(fdat, encoding="ascii")\n return fn\n\n\n@pytest.fixture(scope="session")\ndef retreal_f77(tmpdir_factory):\n """Generates a single f77 file for testing"""\n fdat = util.getpath("tests", "src", "return_real", "foo77.f").read_text()\n fn = tmpdir_factory.getbasetemp() / "foo.f"\n fn.write_text(fdat, encoding="ascii")\n return fn\n\n@pytest.fixture(scope="session")\ndef f2cmap_f90(tmpdir_factory):\n """Generates a single f90 file for testing"""\n fdat = util.getpath("tests", "src", "f2cmap", "isoFortranEnvMap.f90").read_text()\n f2cmap = util.getpath("tests", "src", "f2cmap", ".f2py_f2cmap").read_text()\n fn = tmpdir_factory.getbasetemp() / "f2cmap.f90"\n fmap = tmpdir_factory.getbasetemp() / "mapfile"\n fn.write_text(fdat, encoding="ascii")\n fmap.write_text(f2cmap, encoding="ascii")\n return fn\n\n#########\n# Tests #\n#########\n\ndef test_gh22819_cli(capfd, gh22819_cli, monkeypatch):\n """Check that module names are handled correctly\n gh-22819\n Essentially, the -m name cannot be used to import the module, so the module\n named in the .pyf needs to be used instead\n\n CLI :: -m and a .pyf file\n """\n ipath = Path(gh22819_cli)\n monkeypatch.setattr(sys, "argv", f"f2py -m blah {ipath}".split())\n with util.switchdir(ipath.parent):\n f2pycli()\n gen_paths = [item.name for item in ipath.parent.rglob("*") if item.is_file()]\n assert "blahmodule.c" not in gen_paths # shouldn't be generated\n assert "blah-f2pywrappers.f" not in gen_paths\n assert "test_22819-f2pywrappers.f" in gen_paths\n assert "test_22819module.c" in gen_paths\n\n\ndef test_gh22819_many_pyf(capfd, gh22819_cli, monkeypatch):\n """Only one .pyf file allowed\n gh-22819\n CLI :: .pyf files\n """\n ipath = Path(gh22819_cli)\n monkeypatch.setattr(sys, "argv", f"f2py -m blah {ipath} hello.pyf".split())\n with util.switchdir(ipath.parent):\n with pytest.raises(ValueError, match="Only one .pyf file per call"):\n f2pycli()\n\n\ndef test_gh23598_warn(capfd, gh23598_warn, monkeypatch):\n foutl = get_io_paths(gh23598_warn, mname="test")\n ipath = foutl.f90inp\n monkeypatch.setattr(\n sys, "argv",\n f'f2py {ipath} -m test'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli() # Generate files\n wrapper = foutl.wrap90.read_text()\n assert "intproductf2pywrap, intpr" not in wrapper\n\n\ndef test_gen_pyf(capfd, hello_world_f90, monkeypatch):\n """Ensures that a signature file is generated via the CLI\n CLI :: -h\n """\n ipath = Path(hello_world_f90)\n opath = Path(hello_world_f90).stem + ".pyf"\n monkeypatch.setattr(sys, "argv", f'f2py -h {opath} {ipath}'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli() # Generate wrappers\n out, _ = capfd.readouterr()\n assert "Saving signatures to file" in out\n assert Path(f'{opath}').exists()\n\n\ndef test_gen_pyf_stdout(capfd, hello_world_f90, monkeypatch):\n """Ensures that a signature file can be dumped to stdout\n CLI :: -h\n """\n ipath = Path(hello_world_f90)\n monkeypatch.setattr(sys, "argv", f'f2py -h stdout {ipath}'.split())\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert "Saving signatures to file" in out\n assert "function hi() ! in " in out\n\n\ndef test_gen_pyf_no_overwrite(capfd, hello_world_f90, monkeypatch):\n """Ensures that the CLI refuses to overwrite signature files\n CLI :: -h without --overwrite-signature\n """\n ipath = Path(hello_world_f90)\n monkeypatch.setattr(sys, "argv", f'f2py -h faker.pyf {ipath}'.split())\n\n with util.switchdir(ipath.parent):\n Path("faker.pyf").write_text("Fake news", encoding="ascii")\n with pytest.raises(SystemExit):\n f2pycli() # Refuse to overwrite\n _, err = capfd.readouterr()\n assert "Use --overwrite-signature to overwrite" in err\n\n\n@pytest.mark.skipif(sys.version_info <= (3, 12), reason="Python 3.12 required")\ndef test_untitled_cli(capfd, hello_world_f90, monkeypatch):\n """Check that modules are named correctly\n\n CLI :: defaults\n """\n ipath = Path(hello_world_f90)\n monkeypatch.setattr(sys, "argv", f"f2py --backend meson -c {ipath}".split())\n with util.switchdir(ipath.parent):\n compiler_check_f2pycli()\n out, _ = capfd.readouterr()\n assert "untitledmodule.c" in out\n\n\n@pytest.mark.skipif((platform.system() != 'Linux') or (sys.version_info <= (3, 12)), reason='Compiler and 3.12 required')\ndef test_no_py312_distutils_fcompiler(capfd, hello_world_f90, monkeypatch):\n """Check that no distutils imports are performed on 3.12\n CLI :: --fcompiler --help-link --backend distutils\n """\n MNAME = "hi"\n foutl = get_io_paths(hello_world_f90, mname=MNAME)\n ipath = foutl.f90inp\n monkeypatch.setattr(\n sys, "argv", f"f2py {ipath} -c --fcompiler=gfortran -m {MNAME}".split()\n )\n with util.switchdir(ipath.parent):\n compiler_check_f2pycli()\n out, _ = capfd.readouterr()\n assert "--fcompiler cannot be used with meson" in out\n monkeypatch.setattr(\n sys, "argv", ["f2py", "--help-link"]\n )\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert "Use --dep for meson builds" in out\n MNAME = "hi2" # Needs to be different for a new -c\n monkeypatch.setattr(\n sys, "argv", f"f2py {ipath} -c -m {MNAME} --backend distutils".split()\n )\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert "Cannot use distutils backend with Python>=3.12" in out\n\n\n@pytest.mark.xfail\ndef test_f2py_skip(capfd, retreal_f77, monkeypatch):\n """Tests that functions can be skipped\n CLI :: skip:\n """\n foutl = get_io_paths(retreal_f77, mname="test")\n ipath = foutl.finp\n toskip = "t0 t4 t8 sd s8 s4"\n remaining = "td s0"\n monkeypatch.setattr(\n sys, "argv",\n f'f2py {ipath} -m test skip: {toskip}'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, err = capfd.readouterr()\n for skey in toskip.split():\n assert (\n f'buildmodule: Could not found the body of interfaced routine "{skey}". Skipping.'\n in err)\n for rkey in remaining.split():\n assert f'Constructing wrapper function "{rkey}"' in out\n\n\ndef test_f2py_only(capfd, retreal_f77, monkeypatch):\n """Test that functions can be kept by only:\n CLI :: only:\n """\n foutl = get_io_paths(retreal_f77, mname="test")\n ipath = foutl.finp\n toskip = "t0 t4 t8 sd s8 s4"\n tokeep = "td s0"\n monkeypatch.setattr(\n sys, "argv",\n f'f2py {ipath} -m test only: {tokeep}'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, err = capfd.readouterr()\n for skey in toskip.split():\n assert (\n f'buildmodule: Could not find the body of interfaced routine "{skey}". Skipping.'\n in err)\n for rkey in tokeep.split():\n assert f'Constructing wrapper function "{rkey}"' in out\n\n\ndef test_file_processing_switch(capfd, hello_world_f90, retreal_f77,\n monkeypatch):\n """Tests that it is possible to return to file processing mode\n CLI :: :\n BUG: numpy-gh #20520\n """\n foutl = get_io_paths(retreal_f77, mname="test")\n ipath = foutl.finp\n toskip = "t0 t4 t8 sd s8 s4"\n ipath2 = Path(hello_world_f90)\n tokeep = "td s0 hi" # hi is in ipath2\n mname = "blah"\n monkeypatch.setattr(\n sys,\n "argv",\n f'f2py {ipath} -m {mname} only: {tokeep} : {ipath2}'.split(\n ),\n )\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, err = capfd.readouterr()\n for skey in toskip.split():\n assert (\n f'buildmodule: Could not find the body of interfaced routine "{skey}". Skipping.'\n in err)\n for rkey in tokeep.split():\n assert f'Constructing wrapper function "{rkey}"' in out\n\n\ndef test_mod_gen_f77(capfd, hello_world_f90, monkeypatch):\n """Checks the generation of files based on a module name\n CLI :: -m\n """\n MNAME = "hi"\n foutl = get_io_paths(hello_world_f90, mname=MNAME)\n ipath = foutl.f90inp\n monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m {MNAME}'.split())\n with util.switchdir(ipath.parent):\n f2pycli()\n\n # Always generate C module\n assert Path.exists(foutl.cmodf)\n # File contains a function, check for F77 wrappers\n assert Path.exists(foutl.wrap77)\n\n\ndef test_mod_gen_gh25263(capfd, hello_world_f77, monkeypatch):\n """Check that pyf files are correctly generated with module structure\n CLI :: -m <name> -h pyf_file\n BUG: numpy-gh #20520\n """\n MNAME = "hi"\n foutl = get_io_paths(hello_world_f77, mname=MNAME)\n ipath = foutl.finp\n monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m {MNAME} -h hi.pyf'.split())\n with util.switchdir(ipath.parent):\n f2pycli()\n with Path('hi.pyf').open() as hipyf:\n pyfdat = hipyf.read()\n assert "python module hi" in pyfdat\n\n\ndef test_lower_cmod(capfd, hello_world_f77, monkeypatch):\n """Lowers cases by flag or when -h is present\n\n CLI :: --[no-]lower\n """\n foutl = get_io_paths(hello_world_f77, mname="test")\n ipath = foutl.finp\n capshi = re.compile(r"HI\(\)")\n capslo = re.compile(r"hi\(\)")\n # Case I: --lower is passed\n monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m test --lower'.split())\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert capslo.search(out) is not None\n assert capshi.search(out) is None\n # Case II: --no-lower is passed\n monkeypatch.setattr(sys, "argv",\n f'f2py {ipath} -m test --no-lower'.split())\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert capslo.search(out) is None\n assert capshi.search(out) is not None\n\n\ndef test_lower_sig(capfd, hello_world_f77, monkeypatch):\n """Lowers cases in signature files by flag or when -h is present\n\n CLI :: --[no-]lower -h\n """\n foutl = get_io_paths(hello_world_f77, mname="test")\n ipath = foutl.finp\n # Signature files\n capshi = re.compile(r"Block: HI")\n capslo = re.compile(r"Block: hi")\n # Case I: --lower is implied by -h\n # TODO: Clean up to prevent passing --overwrite-signature\n monkeypatch.setattr(\n sys,\n "argv",\n f'f2py {ipath} -h {foutl.pyf} -m test --overwrite-signature'.split(),\n )\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert capslo.search(out) is not None\n assert capshi.search(out) is None\n\n # Case II: --no-lower overrides -h\n monkeypatch.setattr(\n sys,\n "argv",\n f'f2py {ipath} -h {foutl.pyf} -m test --overwrite-signature --no-lower'\n .split(),\n )\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert capslo.search(out) is None\n assert capshi.search(out) is not None\n\n\ndef test_build_dir(capfd, hello_world_f90, monkeypatch):\n """Ensures that the build directory can be specified\n\n CLI :: --build-dir\n """\n ipath = Path(hello_world_f90)\n mname = "blah"\n odir = "tttmp"\n monkeypatch.setattr(sys, "argv",\n f'f2py -m {mname} {ipath} --build-dir {odir}'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert f"Wrote C/API module \"{mname}\"" in out\n\n\ndef test_overwrite(capfd, hello_world_f90, monkeypatch):\n """Ensures that the build directory can be specified\n\n CLI :: --overwrite-signature\n """\n ipath = Path(hello_world_f90)\n monkeypatch.setattr(\n sys, "argv",\n f'f2py -h faker.pyf {ipath} --overwrite-signature'.split())\n\n with util.switchdir(ipath.parent):\n Path("faker.pyf").write_text("Fake news", encoding="ascii")\n f2pycli()\n out, _ = capfd.readouterr()\n assert "Saving signatures to file" in out\n\n\ndef test_latexdoc(capfd, hello_world_f90, monkeypatch):\n """Ensures that TeX documentation is written out\n\n CLI :: --latex-doc\n """\n ipath = Path(hello_world_f90)\n mname = "blah"\n monkeypatch.setattr(sys, "argv",\n f'f2py -m {mname} {ipath} --latex-doc'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert "Documentation is saved to file" in out\n with Path(f"{mname}module.tex").open() as otex:\n assert "\\documentclass" in otex.read()\n\n\ndef test_nolatexdoc(capfd, hello_world_f90, monkeypatch):\n """Ensures that TeX documentation is written out\n\n CLI :: --no-latex-doc\n """\n ipath = Path(hello_world_f90)\n mname = "blah"\n monkeypatch.setattr(sys, "argv",\n f'f2py -m {mname} {ipath} --no-latex-doc'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert "Documentation is saved to file" not in out\n\n\ndef test_shortlatex(capfd, hello_world_f90, monkeypatch):\n """Ensures that truncated documentation is written out\n\n TODO: Test to ensure this has no effect without --latex-doc\n CLI :: --latex-doc --short-latex\n """\n ipath = Path(hello_world_f90)\n mname = "blah"\n monkeypatch.setattr(\n sys,\n "argv",\n f'f2py -m {mname} {ipath} --latex-doc --short-latex'.split(),\n )\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert "Documentation is saved to file" in out\n with Path(f"./{mname}module.tex").open() as otex:\n assert "\\documentclass" not in otex.read()\n\n\ndef test_restdoc(capfd, hello_world_f90, monkeypatch):\n """Ensures that RsT documentation is written out\n\n CLI :: --rest-doc\n """\n ipath = Path(hello_world_f90)\n mname = "blah"\n monkeypatch.setattr(sys, "argv",\n f'f2py -m {mname} {ipath} --rest-doc'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert "ReST Documentation is saved to file" in out\n with Path(f"./{mname}module.rest").open() as orst:\n assert r".. -*- rest -*-" in orst.read()\n\n\ndef test_norestexdoc(capfd, hello_world_f90, monkeypatch):\n """Ensures that TeX documentation is written out\n\n CLI :: --no-rest-doc\n """\n ipath = Path(hello_world_f90)\n mname = "blah"\n monkeypatch.setattr(sys, "argv",\n f'f2py -m {mname} {ipath} --no-rest-doc'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert "ReST Documentation is saved to file" not in out\n\n\ndef test_debugcapi(capfd, hello_world_f90, monkeypatch):\n """Ensures that debugging wrappers are written\n\n CLI :: --debug-capi\n """\n ipath = Path(hello_world_f90)\n mname = "blah"\n monkeypatch.setattr(sys, "argv",\n f'f2py -m {mname} {ipath} --debug-capi'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n with Path(f"./{mname}module.c").open() as ocmod:\n assert r"#define DEBUGCFUNCS" in ocmod.read()\n\n\n@pytest.mark.skip(reason="Consistently fails on CI; noisy so skip not xfail.")\ndef test_debugcapi_bld(hello_world_f90, monkeypatch):\n """Ensures that debugging wrappers work\n\n CLI :: --debug-capi -c\n """\n ipath = Path(hello_world_f90)\n mname = "blah"\n monkeypatch.setattr(sys, "argv",\n f'f2py -m {mname} {ipath} -c --debug-capi'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n cmd_run = shlex.split(f"{sys.executable} -c \"import blah; blah.hi()\"")\n rout = subprocess.run(cmd_run, capture_output=True, encoding='UTF-8')\n eout = ' Hello World\n'\n eerr = textwrap.dedent("""\\ndebug-capi:Python C/API function blah.hi()\ndebug-capi:float hi=:output,hidden,scalar\ndebug-capi:hi=0\ndebug-capi:Fortran subroutine `f2pywraphi(&hi)'\ndebug-capi:hi=0\ndebug-capi:Building return value.\ndebug-capi:Python C/API function blah.hi: successful.\ndebug-capi:Freeing memory.\n """)\n assert rout.stdout == eout\n assert rout.stderr == eerr\n\n\ndef test_wrapfunc_def(capfd, hello_world_f90, monkeypatch):\n """Ensures that fortran subroutine wrappers for F77 are included by default\n\n CLI :: --[no]-wrap-functions\n """\n # Implied\n ipath = Path(hello_world_f90)\n mname = "blah"\n monkeypatch.setattr(sys, "argv", f'f2py -m {mname} {ipath}'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert r"Fortran 77 wrappers are saved to" in out\n\n # Explicit\n monkeypatch.setattr(sys, "argv",\n f'f2py -m {mname} {ipath} --wrap-functions'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert r"Fortran 77 wrappers are saved to" in out\n\n\ndef test_nowrapfunc(capfd, hello_world_f90, monkeypatch):\n """Ensures that fortran subroutine wrappers for F77 can be disabled\n\n CLI :: --no-wrap-functions\n """\n ipath = Path(hello_world_f90)\n mname = "blah"\n monkeypatch.setattr(sys, "argv",\n f'f2py -m {mname} {ipath} --no-wrap-functions'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert r"Fortran 77 wrappers are saved to" not in out\n\n\ndef test_inclheader(capfd, hello_world_f90, monkeypatch):\n """Add to the include directories\n\n CLI :: -include\n TODO: Document this in the help string\n """\n ipath = Path(hello_world_f90)\n mname = "blah"\n monkeypatch.setattr(\n sys,\n "argv",\n f'f2py -m {mname} {ipath} -include<stdbool.h> -include<stdio.h> '.\n split(),\n )\n\n with util.switchdir(ipath.parent):\n f2pycli()\n with Path(f"./{mname}module.c").open() as ocmod:\n ocmr = ocmod.read()\n assert "#include <stdbool.h>" in ocmr\n assert "#include <stdio.h>" in ocmr\n\n\ndef test_inclpath():\n """Add to the include directories\n\n CLI :: --include-paths\n """\n # TODO: populate\n pass\n\n\ndef test_hlink():\n """Add to the include directories\n\n CLI :: --help-link\n """\n # TODO: populate\n pass\n\n\ndef test_f2cmap(capfd, f2cmap_f90, monkeypatch):\n """Check that Fortran-to-Python KIND specs can be passed\n\n CLI :: --f2cmap\n """\n ipath = Path(f2cmap_f90)\n monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} --f2cmap mapfile'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert "Reading f2cmap from 'mapfile' ..." in out\n assert "Mapping \"real(kind=real32)\" to \"float\"" in out\n assert "Mapping \"real(kind=real64)\" to \"double\"" in out\n assert "Mapping \"integer(kind=int64)\" to \"long_long\"" in out\n assert "Successfully applied user defined f2cmap changes" in out\n\n\ndef test_quiet(capfd, hello_world_f90, monkeypatch):\n """Reduce verbosity\n\n CLI :: --quiet\n """\n ipath = Path(hello_world_f90)\n monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} --quiet'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert len(out) == 0\n\n\ndef test_verbose(capfd, hello_world_f90, monkeypatch):\n """Increase verbosity\n\n CLI :: --verbose\n """\n ipath = Path(hello_world_f90)\n monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} --verbose'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n out, _ = capfd.readouterr()\n assert "analyzeline" in out\n\n\ndef test_version(capfd, monkeypatch):\n """Ensure version\n\n CLI :: -v\n """\n monkeypatch.setattr(sys, "argv", ["f2py", "-v"])\n # TODO: f2py2e should not call sys.exit() after printing the version\n with pytest.raises(SystemExit):\n f2pycli()\n out, _ = capfd.readouterr()\n import numpy as np\n assert np.__version__ == out.strip()\n\n\n@pytest.mark.skip(reason="Consistently fails on CI; noisy so skip not xfail.")\ndef test_npdistop(hello_world_f90, monkeypatch):\n """\n CLI :: -c\n """\n ipath = Path(hello_world_f90)\n monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} -c'.split())\n\n with util.switchdir(ipath.parent):\n f2pycli()\n cmd_run = shlex.split(f"{sys.executable} -c \"import blah; blah.hi()\"")\n rout = subprocess.run(cmd_run, capture_output=True, encoding='UTF-8')\n eout = ' Hello World\n'\n assert rout.stdout == eout\n\n\n@pytest.mark.skipif((platform.system() != 'Linux') or sys.version_info <= (3, 12),\n reason='Compiler and Python 3.12 or newer required')\ndef test_no_freethreading_compatible(hello_world_f90, monkeypatch):\n """\n CLI :: --no-freethreading-compatible\n """\n ipath = Path(hello_world_f90)\n monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} -c --no-freethreading-compatible'.split())\n\n with util.switchdir(ipath.parent):\n compiler_check_f2pycli()\n cmd = f"{sys.executable} -c \"import blah; blah.hi();"\n if NOGIL_BUILD:\n cmd += "import sys; assert sys._is_gil_enabled() is True\""\n else:\n cmd += "\""\n cmd_run = shlex.split(cmd)\n rout = subprocess.run(cmd_run, capture_output=True, encoding='UTF-8')\n eout = ' Hello World\n'\n assert rout.stdout == eout\n if NOGIL_BUILD:\n assert "The global interpreter lock (GIL) has been enabled to load module 'blah'" in rout.stderr\n assert rout.returncode == 0\n\n\n@pytest.mark.skipif((platform.system() != 'Linux') or sys.version_info <= (3, 12),\n reason='Compiler and Python 3.12 or newer required')\ndef test_freethreading_compatible(hello_world_f90, monkeypatch):\n """\n CLI :: --freethreading_compatible\n """\n ipath = Path(hello_world_f90)\n monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} -c --freethreading-compatible'.split())\n\n with util.switchdir(ipath.parent):\n compiler_check_f2pycli()\n cmd = f"{sys.executable} -c \"import blah; blah.hi();"\n if NOGIL_BUILD:\n cmd += "import sys; assert sys._is_gil_enabled() is False\""\n else:\n cmd += "\""\n cmd_run = shlex.split(cmd)\n rout = subprocess.run(cmd_run, capture_output=True, encoding='UTF-8')\n eout = ' Hello World\n'\n assert rout.stdout == eout\n assert rout.stderr == ""\n assert rout.returncode == 0\n\n\n# Numpy distutils flags\n# TODO: These should be tested separately\n\ndef test_npd_fcompiler():\n """\n CLI :: -c --fcompiler\n """\n # TODO: populate\n pass\n\n\ndef test_npd_compiler():\n """\n CLI :: -c --compiler\n """\n # TODO: populate\n pass\n\n\ndef test_npd_help_fcompiler():\n """\n CLI :: -c --help-fcompiler\n """\n # TODO: populate\n pass\n\n\ndef test_npd_f77exec():\n """\n CLI :: -c --f77exec\n """\n # TODO: populate\n pass\n\n\ndef test_npd_f90exec():\n """\n CLI :: -c --f90exec\n """\n # TODO: populate\n pass\n\n\ndef test_npd_f77flags():\n """\n CLI :: -c --f77flags\n """\n # TODO: populate\n pass\n\n\ndef test_npd_f90flags():\n """\n CLI :: -c --f90flags\n """\n # TODO: populate\n pass\n\n\ndef test_npd_opt():\n """\n CLI :: -c --opt\n """\n # TODO: populate\n pass\n\n\ndef test_npd_arch():\n """\n CLI :: -c --arch\n """\n # TODO: populate\n pass\n\n\ndef test_npd_noopt():\n """\n CLI :: -c --noopt\n """\n # TODO: populate\n pass\n\n\ndef test_npd_noarch():\n """\n CLI :: -c --noarch\n """\n # TODO: populate\n pass\n\n\ndef test_npd_debug():\n """\n CLI :: -c --debug\n """\n # TODO: populate\n pass\n\n\ndef test_npd_link_auto():\n """\n CLI :: -c --link-<resource>\n """\n # TODO: populate\n pass\n\n\ndef test_npd_lib():\n """\n CLI :: -c -L/path/to/lib/ -l<libname>\n """\n # TODO: populate\n pass\n\n\ndef test_npd_define():\n """\n CLI :: -D<define>\n """\n # TODO: populate\n pass\n\n\ndef test_npd_undefine():\n """\n CLI :: -U<name>\n """\n # TODO: populate\n pass\n\n\ndef test_npd_incl():\n """\n CLI :: -I/path/to/include/\n """\n # TODO: populate\n pass\n\n\ndef test_npd_linker():\n """\n CLI :: <filename>.o <filename>.so <filename>.a\n """\n # TODO: populate\n pass\n
.venv\Lib\site-packages\numpy\f2py\tests\test_f2py2e.py
test_f2py2e.py
Python
28,798
0.95
0.098548
0.059432
node-utils
84
2025-06-28T05:22:07.718524
BSD-3-Clause
true
aa82d7eae955218a2081ddb314dfc470
import pytest\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\n\nfrom . import util\n\n\nclass TestISOC(util.F2PyTest):\n sources = [\n util.getpath("tests", "src", "isocintrin", "isoCtests.f90"),\n ]\n\n # gh-24553\n @pytest.mark.slow\n def test_c_double(self):\n out = self.module.coddity.c_add(1, 2)\n exp_out = 3\n assert out == exp_out\n\n # gh-9693\n def test_bindc_function(self):\n out = self.module.coddity.wat(1, 20)\n exp_out = 8\n assert out == exp_out\n\n # gh-25207\n def test_bindc_kinds(self):\n out = self.module.coddity.c_add_int64(1, 20)\n exp_out = 21\n assert out == exp_out\n\n # gh-25207\n def test_bindc_add_arr(self):\n a = np.array([1, 2, 3])\n b = np.array([1, 2, 3])\n out = self.module.coddity.add_arr(a, b)\n exp_out = a * 2\n assert_allclose(out, exp_out)\n\n\ndef test_process_f2cmap_dict():\n from numpy.f2py.auxfuncs import process_f2cmap_dict\n\n f2cmap_all = {"integer": {"8": "rubbish_type"}}\n new_map = {"INTEGER": {"4": "int"}}\n c2py_map = {"int": "int", "rubbish_type": "long"}\n\n exp_map, exp_maptyp = ({"integer": {"8": "rubbish_type", "4": "int"}}, ["int"])\n\n # Call the function\n res_map, res_maptyp = process_f2cmap_dict(f2cmap_all, new_map, c2py_map)\n\n # Assert the result is as expected\n assert res_map == exp_map\n assert res_maptyp == exp_maptyp\n
.venv\Lib\site-packages\numpy\f2py\tests\test_isoc.py
test_isoc.py
Python
1,490
0.95
0.125
0.142857
node-utils
916
2024-01-17T02:11:01.343650
BSD-3-Clause
true
7108c87d7f56ffea493c8d69c3554d67
import platform\nimport sys\n\nimport pytest\n\nfrom numpy.f2py.crackfortran import (\n _selected_int_kind_func as selected_int_kind,\n)\nfrom numpy.f2py.crackfortran import (\n _selected_real_kind_func as selected_real_kind,\n)\n\nfrom . import util\n\n\nclass TestKind(util.F2PyTest):\n sources = [util.getpath("tests", "src", "kind", "foo.f90")]\n\n @pytest.mark.skipif(sys.maxsize < 2 ** 31 + 1,\n reason="Fails for 32 bit machines")\n def test_int(self):\n """Test `int` kind_func for integers up to 10**40."""\n selectedintkind = self.module.selectedintkind\n\n for i in range(40):\n assert selectedintkind(i) == selected_int_kind(\n i\n ), f"selectedintkind({i}): expected {selected_int_kind(i)!r} but got {selectedintkind(i)!r}"\n\n def test_real(self):\n """\n Test (processor-dependent) `real` kind_func for real numbers\n of up to 31 digits precision (extended/quadruple).\n """\n selectedrealkind = self.module.selectedrealkind\n\n for i in range(32):\n assert selectedrealkind(i) == selected_real_kind(\n i\n ), f"selectedrealkind({i}): expected {selected_real_kind(i)!r} but got {selectedrealkind(i)!r}"\n\n @pytest.mark.xfail(platform.machine().lower().startswith("ppc"),\n reason="Some PowerPC may not support full IEEE 754 precision")\n def test_quad_precision(self):\n """\n Test kind_func for quadruple precision [`real(16)`] of 32+ digits .\n """\n selectedrealkind = self.module.selectedrealkind\n\n for i in range(32, 40):\n assert selectedrealkind(i) == selected_real_kind(\n i\n ), f"selectedrealkind({i}): expected {selected_real_kind(i)!r} but got {selectedrealkind(i)!r}"\n
.venv\Lib\site-packages\numpy\f2py\tests\test_kind.py
test_kind.py
Python
1,878
0.85
0.207547
0
awesome-app
391
2025-06-15T19:47:57.134732
Apache-2.0
true
b4998ec2962697c6c3a243e00f268ea4
import textwrap\n\nimport pytest\n\nfrom numpy.testing import IS_PYPY\n\nfrom . import util\n\n\nclass TestMixed(util.F2PyTest):\n sources = [\n util.getpath("tests", "src", "mixed", "foo.f"),\n util.getpath("tests", "src", "mixed", "foo_fixed.f90"),\n util.getpath("tests", "src", "mixed", "foo_free.f90"),\n ]\n\n @pytest.mark.slow\n def test_all(self):\n assert self.module.bar11() == 11\n assert self.module.foo_fixed.bar12() == 12\n assert self.module.foo_free.bar13() == 13\n\n @pytest.mark.xfail(IS_PYPY,\n reason="PyPy cannot modify tp_doc after PyType_Ready")\n def test_docstring(self):\n expected = textwrap.dedent("""\\n a = bar11()\n\n Wrapper for ``bar11``.\n\n Returns\n -------\n a : int\n """)\n assert self.module.bar11.__doc__ == expected\n
.venv\Lib\site-packages\numpy\f2py\tests\test_mixed.py
test_mixed.py
Python
897
0.85
0.114286
0
vue-tools
880
2024-10-27T09:19:33.002802
Apache-2.0
true
fcdbb3b612c3422168458303ceafdcb5
import textwrap\n\nimport pytest\n\nfrom numpy.testing import IS_PYPY\n\nfrom . import util\n\n\n@pytest.mark.slow\nclass TestModuleFilterPublicEntities(util.F2PyTest):\n sources = [\n util.getpath(\n "tests", "src", "modules", "gh26920",\n "two_mods_with_one_public_routine.f90"\n )\n ]\n # we filter the only public function mod2\n only = ["mod1_func1", ]\n\n def test_gh26920(self):\n # if it compiles and can be loaded, things are fine\n pass\n\n\n@pytest.mark.slow\nclass TestModuleWithoutPublicEntities(util.F2PyTest):\n sources = [\n util.getpath(\n "tests", "src", "modules", "gh26920",\n "two_mods_with_no_public_entities.f90"\n )\n ]\n only = ["mod1_func1", ]\n\n def test_gh26920(self):\n # if it compiles and can be loaded, things are fine\n pass\n\n\n@pytest.mark.slow\nclass TestModuleDocString(util.F2PyTest):\n sources = [util.getpath("tests", "src", "modules", "module_data_docstring.f90")]\n\n @pytest.mark.xfail(IS_PYPY, reason="PyPy cannot modify tp_doc after PyType_Ready")\n def test_module_docstring(self):\n assert self.module.mod.__doc__ == textwrap.dedent(\n """\\n i : 'i'-scalar\n x : 'i'-array(4)\n a : 'f'-array(2,3)\n b : 'f'-array(-1,-1), not allocated\x00\n foo()\n\n Wrapper for ``foo``.\n\n"""\n )\n\n\n@pytest.mark.slow\nclass TestModuleAndSubroutine(util.F2PyTest):\n module_name = "example"\n sources = [\n util.getpath("tests", "src", "modules", "gh25337", "data.f90"),\n util.getpath("tests", "src", "modules", "gh25337", "use_data.f90"),\n ]\n\n def test_gh25337(self):\n self.module.data.set_shift(3)\n assert "data" in dir(self.module)\n\n\n@pytest.mark.slow\nclass TestUsedModule(util.F2PyTest):\n module_name = "fmath"\n sources = [\n util.getpath("tests", "src", "modules", "use_modules.f90"),\n ]\n\n def test_gh25867(self):\n compiled_mods = [x for x in dir(self.module) if "__" not in x]\n assert "useops" in compiled_mods\n assert self.module.useops.sum_and_double(3, 7) == 20\n assert "mathops" in compiled_mods\n assert self.module.mathops.add(3, 7) == 10\n
.venv\Lib\site-packages\numpy\f2py\tests\test_modules.py
test_modules.py
Python
2,384
0.95
0.192771
0.046154
vue-tools
436
2023-12-11T00:12:23.692325
GPL-3.0
true
677d5fb0276824e0098594ffd69e5907
import pytest\n\nimport numpy as np\n\nfrom . import util\n\n\nclass TestParameters(util.F2PyTest):\n # Check that intent(in out) translates as intent(inout)\n sources = [\n util.getpath("tests", "src", "parameter", "constant_real.f90"),\n util.getpath("tests", "src", "parameter", "constant_integer.f90"),\n util.getpath("tests", "src", "parameter", "constant_both.f90"),\n util.getpath("tests", "src", "parameter", "constant_compound.f90"),\n util.getpath("tests", "src", "parameter", "constant_non_compound.f90"),\n util.getpath("tests", "src", "parameter", "constant_array.f90"),\n ]\n\n @pytest.mark.slow\n def test_constant_real_single(self):\n # non-contiguous should raise error\n x = np.arange(6, dtype=np.float32)[::2]\n pytest.raises(ValueError, self.module.foo_single, x)\n\n # check values with contiguous array\n x = np.arange(3, dtype=np.float32)\n self.module.foo_single(x)\n assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])\n\n @pytest.mark.slow\n def test_constant_real_double(self):\n # non-contiguous should raise error\n x = np.arange(6, dtype=np.float64)[::2]\n pytest.raises(ValueError, self.module.foo_double, x)\n\n # check values with contiguous array\n x = np.arange(3, dtype=np.float64)\n self.module.foo_double(x)\n assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])\n\n @pytest.mark.slow\n def test_constant_compound_int(self):\n # non-contiguous should raise error\n x = np.arange(6, dtype=np.int32)[::2]\n pytest.raises(ValueError, self.module.foo_compound_int, x)\n\n # check values with contiguous array\n x = np.arange(3, dtype=np.int32)\n self.module.foo_compound_int(x)\n assert np.allclose(x, [0 + 1 + 2 * 6, 1, 2])\n\n @pytest.mark.slow\n def test_constant_non_compound_int(self):\n # check values\n x = np.arange(4, dtype=np.int32)\n self.module.foo_non_compound_int(x)\n assert np.allclose(x, [0 + 1 + 2 + 3 * 4, 1, 2, 3])\n\n @pytest.mark.slow\n def test_constant_integer_int(self):\n # non-contiguous should raise error\n x = np.arange(6, dtype=np.int32)[::2]\n pytest.raises(ValueError, self.module.foo_int, x)\n\n # check values with contiguous array\n x = np.arange(3, dtype=np.int32)\n self.module.foo_int(x)\n assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])\n\n @pytest.mark.slow\n def test_constant_integer_long(self):\n # non-contiguous should raise error\n x = np.arange(6, dtype=np.int64)[::2]\n pytest.raises(ValueError, self.module.foo_long, x)\n\n # check values with contiguous array\n x = np.arange(3, dtype=np.int64)\n self.module.foo_long(x)\n assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])\n\n @pytest.mark.slow\n def test_constant_both(self):\n # non-contiguous should raise error\n x = np.arange(6, dtype=np.float64)[::2]\n pytest.raises(ValueError, self.module.foo, x)\n\n # check values with contiguous array\n x = np.arange(3, dtype=np.float64)\n self.module.foo(x)\n assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])\n\n @pytest.mark.slow\n def test_constant_no(self):\n # non-contiguous should raise error\n x = np.arange(6, dtype=np.float64)[::2]\n pytest.raises(ValueError, self.module.foo_no, x)\n\n # check values with contiguous array\n x = np.arange(3, dtype=np.float64)\n self.module.foo_no(x)\n assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])\n\n @pytest.mark.slow\n def test_constant_sum(self):\n # non-contiguous should raise error\n x = np.arange(6, dtype=np.float64)[::2]\n pytest.raises(ValueError, self.module.foo_sum, x)\n\n # check values with contiguous array\n x = np.arange(3, dtype=np.float64)\n self.module.foo_sum(x)\n assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])\n\n def test_constant_array(self):\n x = np.arange(3, dtype=np.float64)\n y = np.arange(5, dtype=np.float64)\n z = self.module.foo_array(x, y)\n assert np.allclose(x, [0.0, 1. / 10, 2. / 10])\n assert np.allclose(y, [0.0, 1. * 10, 2. * 10, 3. * 10, 4. * 10])\n assert np.allclose(z, 19.0)\n\n def test_constant_array_any_index(self):\n x = np.arange(6, dtype=np.float64)\n y = self.module.foo_array_any_index(x)\n assert np.allclose(y, x.reshape((2, 3), order='F'))\n\n def test_constant_array_delims(self):\n x = self.module.foo_array_delims()\n assert x == 9\n
.venv\Lib\site-packages\numpy\f2py\tests\test_parameter.py
test_parameter.py
Python
4,763
0.95
0.100775
0.171429
awesome-app
679
2024-11-20T10:55:03.351532
MIT
true
a99e63f71138338eaba18ba6ebe212aa
# This test is ported from numpy.distutils\nfrom numpy.f2py._src_pyf import process_str\nfrom numpy.testing import assert_equal\n\npyf_src = """\npython module foo\n <_rd=real,double precision>\n interface\n subroutine <s,d>foosub(tol)\n <_rd>, intent(in,out) :: tol\n end subroutine <s,d>foosub\n end interface\nend python module foo\n"""\n\nexpected_pyf = """\npython module foo\n interface\n subroutine sfoosub(tol)\n real, intent(in,out) :: tol\n end subroutine sfoosub\n subroutine dfoosub(tol)\n double precision, intent(in,out) :: tol\n end subroutine dfoosub\n end interface\nend python module foo\n"""\n\n\ndef normalize_whitespace(s):\n """\n Remove leading and trailing whitespace, and convert internal\n stretches of whitespace to a single space.\n """\n return ' '.join(s.split())\n\n\ndef test_from_template():\n """Regression test for gh-10712."""\n pyf = process_str(pyf_src)\n normalized_pyf = normalize_whitespace(pyf)\n normalized_expected_pyf = normalize_whitespace(expected_pyf)\n assert_equal(normalized_pyf, normalized_expected_pyf)\n
.venv\Lib\site-packages\numpy\f2py\tests\test_pyf_src.py
test_pyf_src.py
Python
1,177
0.95
0.069767
0.027027
python-kit
562
2025-03-01T00:31:47.706137
BSD-3-Clause
true
a257c88c311e05467606da8177ec000f
"""See https://github.com/numpy/numpy/pull/10676.\n\n"""\nimport sys\n\nimport pytest\n\nfrom . import util\n\n\nclass TestQuotedCharacter(util.F2PyTest):\n sources = [util.getpath("tests", "src", "quoted_character", "foo.f")]\n\n @pytest.mark.skipif(sys.platform == "win32",\n reason="Fails with MinGW64 Gfortran (Issue #9673)")\n @pytest.mark.slow\n def test_quoted_character(self):\n assert self.module.foo() == (b"'", b'"', b";", b"!", b"(", b")")\n
.venv\Lib\site-packages\numpy\f2py\tests\test_quoted_character.py
test_quoted_character.py
Python
495
0.95
0.111111
0
awesome-app
151
2024-01-07T00:16:09.645509
Apache-2.0
true
709b0170e81ebd21e5e6d725fc6c1b4f
import os\nimport platform\n\nimport pytest\n\nimport numpy as np\nimport numpy.testing as npt\n\nfrom . import util\n\n\nclass TestIntentInOut(util.F2PyTest):\n # Check that intent(in out) translates as intent(inout)\n sources = [util.getpath("tests", "src", "regression", "inout.f90")]\n\n @pytest.mark.slow\n def test_inout(self):\n # non-contiguous should raise error\n x = np.arange(6, dtype=np.float32)[::2]\n pytest.raises(ValueError, self.module.foo, x)\n\n # check values with contiguous array\n x = np.arange(3, dtype=np.float32)\n self.module.foo(x)\n assert np.allclose(x, [3, 1, 2])\n\n\nclass TestDataOnlyMultiModule(util.F2PyTest):\n # Check that modules without subroutines work\n sources = [util.getpath("tests", "src", "regression", "datonly.f90")]\n\n @pytest.mark.slow\n def test_mdat(self):\n assert self.module.datonly.max_value == 100\n assert self.module.dat.max_ == 1009\n int_in = 5\n assert self.module.simple_subroutine(5) == 1014\n\n\nclass TestModuleWithDerivedType(util.F2PyTest):\n # Check that modules with derived types work\n sources = [util.getpath("tests", "src", "regression", "mod_derived_types.f90")]\n\n @pytest.mark.slow\n def test_mtypes(self):\n assert self.module.no_type_subroutine(10) == 110\n assert self.module.type_subroutine(10) == 210\n\n\nclass TestNegativeBounds(util.F2PyTest):\n # Check that negative bounds work correctly\n sources = [util.getpath("tests", "src", "negative_bounds", "issue_20853.f90")]\n\n @pytest.mark.slow\n def test_negbound(self):\n xvec = np.arange(12)\n xlow = -6\n xhigh = 4\n\n # Calculate the upper bound,\n # Keeping the 1 index in mind\n\n def ubound(xl, xh):\n return xh - xl + 1\n rval = self.module.foo(is_=xlow, ie_=xhigh,\n arr=xvec[:ubound(xlow, xhigh)])\n expval = np.arange(11, dtype=np.float32)\n assert np.allclose(rval, expval)\n\n\nclass TestNumpyVersionAttribute(util.F2PyTest):\n # Check that th attribute __f2py_numpy_version__ is present\n # in the compiled module and that has the value np.__version__.\n sources = [util.getpath("tests", "src", "regression", "inout.f90")]\n\n @pytest.mark.slow\n def test_numpy_version_attribute(self):\n\n # Check that self.module has an attribute named "__f2py_numpy_version__"\n assert hasattr(self.module, "__f2py_numpy_version__")\n\n # Check that the attribute __f2py_numpy_version__ is a string\n assert isinstance(self.module.__f2py_numpy_version__, str)\n\n # Check that __f2py_numpy_version__ has the value numpy.__version__\n assert np.__version__ == self.module.__f2py_numpy_version__\n\n\ndef test_include_path():\n incdir = np.f2py.get_include()\n fnames_in_dir = os.listdir(incdir)\n for fname in ("fortranobject.c", "fortranobject.h"):\n assert fname in fnames_in_dir\n\n\nclass TestIncludeFiles(util.F2PyTest):\n sources = [util.getpath("tests", "src", "regression", "incfile.f90")]\n options = [f"-I{util.getpath('tests', 'src', 'regression')}",\n f"--include-paths {util.getpath('tests', 'src', 'regression')}"]\n\n @pytest.mark.slow\n def test_gh25344(self):\n exp = 7.0\n res = self.module.add(3.0, 4.0)\n assert exp == res\n\nclass TestF77Comments(util.F2PyTest):\n # Check that comments are stripped from F77 continuation lines\n sources = [util.getpath("tests", "src", "regression", "f77comments.f")]\n\n @pytest.mark.slow\n def test_gh26148(self):\n x1 = np.array(3, dtype=np.int32)\n x2 = np.array(5, dtype=np.int32)\n res = self.module.testsub(x1, x2)\n assert res[0] == 8\n assert res[1] == 15\n\n @pytest.mark.slow\n def test_gh26466(self):\n # Check that comments after PARAMETER directions are stripped\n expected = np.arange(1, 11, dtype=np.float32) * 2\n res = self.module.testsub2()\n npt.assert_allclose(expected, res)\n\nclass TestF90Contiuation(util.F2PyTest):\n # Check that comments are stripped from F90 continuation lines\n sources = [util.getpath("tests", "src", "regression", "f90continuation.f90")]\n\n @pytest.mark.slow\n def test_gh26148b(self):\n x1 = np.array(3, dtype=np.int32)\n x2 = np.array(5, dtype=np.int32)\n res = self.module.testsub(x1, x2)\n assert res[0] == 8\n assert res[1] == 15\n\nclass TestLowerF2PYDirectives(util.F2PyTest):\n # Check variables are cased correctly\n sources = [util.getpath("tests", "src", "regression", "lower_f2py_fortran.f90")]\n\n @pytest.mark.slow\n def test_gh28014(self):\n self.module.inquire_next(3)\n assert True\n\n@pytest.mark.slow\ndef test_gh26623():\n # Including libraries with . should not generate an incorrect meson.build\n try:\n aa = util.build_module(\n [util.getpath("tests", "src", "regression", "f90continuation.f90")],\n ["-lfoo.bar"],\n module_name="Blah",\n )\n except RuntimeError as rerr:\n assert "lparen got assign" not in str(rerr)\n\n\n@pytest.mark.slow\n@pytest.mark.skipif(platform.system() not in ['Linux', 'Darwin'], reason='Unsupported on this platform for now')\ndef test_gh25784():\n # Compile dubious file using passed flags\n try:\n aa = util.build_module(\n [util.getpath("tests", "src", "regression", "f77fixedform.f95")],\n options=[\n # Meson will collect and dedup these to pass to fortran_args:\n "--f77flags='-ffixed-form -O2'",\n "--f90flags=\"-ffixed-form -Og\"",\n ],\n module_name="Blah",\n )\n except ImportError as rerr:\n assert "unknown_subroutine_" in str(rerr)\n\n\n@pytest.mark.slow\nclass TestAssignmentOnlyModules(util.F2PyTest):\n # Ensure that variables are exposed without functions or subroutines in a module\n sources = [util.getpath("tests", "src", "regression", "assignOnlyModule.f90")]\n\n @pytest.mark.slow\n def test_gh27167(self):\n assert (self.module.f_globals.n_max == 16)\n assert (self.module.f_globals.i_max == 18)\n assert (self.module.f_globals.j_max == 72)\n
.venv\Lib\site-packages\numpy\f2py\tests\test_regression.py
test_regression.py
Python
6,384
0.95
0.15508
0.144828
awesome-app
293
2024-12-03T14:54:20.025923
MIT
true
52d59d53a21d2eab88c485fa9c3fd481
import platform\n\nimport pytest\n\nfrom numpy import array\n\nfrom . import util\n\nIS_S390X = platform.machine() == "s390x"\n\n\n@pytest.mark.slow\nclass TestReturnCharacter(util.F2PyTest):\n def check_function(self, t, tname):\n if tname in ["t0", "t1", "s0", "s1"]:\n assert t("23") == b"2"\n r = t("ab")\n assert r == b"a"\n r = t(array("ab"))\n assert r == b"a"\n r = t(array(77, "u1"))\n assert r == b"M"\n elif tname in ["ts", "ss"]:\n assert t(23) == b"23"\n assert t("123456789abcdef") == b"123456789a"\n elif tname in ["t5", "s5"]:\n assert t(23) == b"23"\n assert t("ab") == b"ab"\n assert t("123456789abcdef") == b"12345"\n else:\n raise NotImplementedError\n\n\nclass TestFReturnCharacter(TestReturnCharacter):\n sources = [\n util.getpath("tests", "src", "return_character", "foo77.f"),\n util.getpath("tests", "src", "return_character", "foo90.f90"),\n ]\n\n @pytest.mark.xfail(IS_S390X, reason="callback returns ' '")\n @pytest.mark.parametrize("name", ["t0", "t1", "t5", "s0", "s1", "s5", "ss"])\n def test_all_f77(self, name):\n self.check_function(getattr(self.module, name), name)\n\n @pytest.mark.xfail(IS_S390X, reason="callback returns ' '")\n @pytest.mark.parametrize("name", ["t0", "t1", "t5", "ts", "s0", "s1", "s5", "ss"])\n def test_all_f90(self, name):\n self.check_function(getattr(self.module.f90_return_char, name), name)\n
.venv\Lib\site-packages\numpy\f2py\tests\test_return_character.py
test_return_character.py
Python
1,582
0.85
0.125
0
vue-tools
85
2023-08-30T14:41:25.526786
BSD-3-Clause
true
510290c35fda3d8554a3badbdc110494
import pytest\n\nfrom numpy import array\n\nfrom . import util\n\n\n@pytest.mark.slow\nclass TestReturnComplex(util.F2PyTest):\n def check_function(self, t, tname):\n if tname in ["t0", "t8", "s0", "s8"]:\n err = 1e-5\n else:\n err = 0.0\n assert abs(t(234j) - 234.0j) <= err\n assert abs(t(234.6) - 234.6) <= err\n assert abs(t(234) - 234.0) <= err\n assert abs(t(234.6 + 3j) - (234.6 + 3j)) <= err\n # assert abs(t('234')-234.)<=err\n # assert abs(t('234.6')-234.6)<=err\n assert abs(t(-234) + 234.0) <= err\n assert abs(t([234]) - 234.0) <= err\n assert abs(t((234, )) - 234.0) <= err\n assert abs(t(array(234)) - 234.0) <= err\n assert abs(t(array(23 + 4j, "F")) - (23 + 4j)) <= err\n assert abs(t(array([234])) - 234.0) <= err\n assert abs(t(array([[234]])) - 234.0) <= err\n assert abs(t(array([234]).astype("b")) + 22.0) <= err\n assert abs(t(array([234], "h")) - 234.0) <= err\n assert abs(t(array([234], "i")) - 234.0) <= err\n assert abs(t(array([234], "l")) - 234.0) <= err\n assert abs(t(array([234], "q")) - 234.0) <= err\n assert abs(t(array([234], "f")) - 234.0) <= err\n assert abs(t(array([234], "d")) - 234.0) <= err\n assert abs(t(array([234 + 3j], "F")) - (234 + 3j)) <= err\n assert abs(t(array([234], "D")) - 234.0) <= err\n\n # pytest.raises(TypeError, t, array([234], 'S1'))\n pytest.raises(TypeError, t, "abc")\n\n pytest.raises(IndexError, t, [])\n pytest.raises(IndexError, t, ())\n\n pytest.raises(TypeError, t, t)\n pytest.raises(TypeError, t, {})\n\n try:\n r = t(10**400)\n assert repr(r) in ["(inf+0j)", "(Infinity+0j)"]\n except OverflowError:\n pass\n\n\nclass TestFReturnComplex(TestReturnComplex):\n sources = [\n util.getpath("tests", "src", "return_complex", "foo77.f"),\n util.getpath("tests", "src", "return_complex", "foo90.f90"),\n ]\n\n @pytest.mark.parametrize("name", ["t0", "t8", "t16", "td", "s0", "s8", "s16", "sd"])\n def test_all_f77(self, name):\n self.check_function(getattr(self.module, name), name)\n\n @pytest.mark.parametrize("name", ["t0", "t8", "t16", "td", "s0", "s8", "s16", "sd"])\n def test_all_f90(self, name):\n self.check_function(getattr(self.module.f90_return_complex, name),\n name)\n
.venv\Lib\site-packages\numpy\f2py\tests\test_return_complex.py
test_return_complex.py
Python
2,507
0.95
0.104478
0.054545
node-utils
847
2025-02-17T05:45:07.921232
Apache-2.0
true
9602dfce065343d24d58392a8ea645e4
import pytest\n\nfrom numpy import array\n\nfrom . import util\n\n\n@pytest.mark.slow\nclass TestReturnInteger(util.F2PyTest):\n def check_function(self, t, tname):\n assert t(123) == 123\n assert t(123.6) == 123\n assert t("123") == 123\n assert t(-123) == -123\n assert t([123]) == 123\n assert t((123, )) == 123\n assert t(array(123)) == 123\n assert t(array(123, "b")) == 123\n assert t(array(123, "h")) == 123\n assert t(array(123, "i")) == 123\n assert t(array(123, "l")) == 123\n assert t(array(123, "B")) == 123\n assert t(array(123, "f")) == 123\n assert t(array(123, "d")) == 123\n\n # pytest.raises(ValueError, t, array([123],'S3'))\n pytest.raises(ValueError, t, "abc")\n\n pytest.raises(IndexError, t, [])\n pytest.raises(IndexError, t, ())\n\n pytest.raises(Exception, t, t)\n pytest.raises(Exception, t, {})\n\n if tname in ["t8", "s8"]:\n pytest.raises(OverflowError, t, 100000000000000000000000)\n pytest.raises(OverflowError, t, 10000000011111111111111.23)\n\n\nclass TestFReturnInteger(TestReturnInteger):\n sources = [\n util.getpath("tests", "src", "return_integer", "foo77.f"),\n util.getpath("tests", "src", "return_integer", "foo90.f90"),\n ]\n\n @pytest.mark.parametrize("name",\n ["t0", "t1", "t2", "t4", "t8", "s0", "s1", "s2", "s4", "s8"])\n def test_all_f77(self, name):\n self.check_function(getattr(self.module, name), name)\n\n @pytest.mark.parametrize("name",\n ["t0", "t1", "t2", "t4", "t8", "s0", "s1", "s2", "s4", "s8"])\n def test_all_f90(self, name):\n self.check_function(getattr(self.module.f90_return_integer, name),\n name)\n
.venv\Lib\site-packages\numpy\f2py\tests\test_return_integer.py
test_return_integer.py
Python
1,868
0.95
0.109091
0.023256
python-kit
164
2025-04-28T05:59:31.612472
Apache-2.0
true
35a97d8455c0cb8238d9f563afbb8981
import pytest\n\nfrom numpy import array\n\nfrom . import util\n\n\nclass TestReturnLogical(util.F2PyTest):\n def check_function(self, t):\n assert t(True) == 1\n assert t(False) == 0\n assert t(0) == 0\n assert t(None) == 0\n assert t(0.0) == 0\n assert t(0j) == 0\n assert t(1j) == 1\n assert t(234) == 1\n assert t(234.6) == 1\n assert t(234.6 + 3j) == 1\n assert t("234") == 1\n assert t("aaa") == 1\n assert t("") == 0\n assert t([]) == 0\n assert t(()) == 0\n assert t({}) == 0\n assert t(t) == 1\n assert t(-234) == 1\n assert t(10**100) == 1\n assert t([234]) == 1\n assert t((234, )) == 1\n assert t(array(234)) == 1\n assert t(array([234])) == 1\n assert t(array([[234]])) == 1\n assert t(array([127], "b")) == 1\n assert t(array([234], "h")) == 1\n assert t(array([234], "i")) == 1\n assert t(array([234], "l")) == 1\n assert t(array([234], "f")) == 1\n assert t(array([234], "d")) == 1\n assert t(array([234 + 3j], "F")) == 1\n assert t(array([234], "D")) == 1\n assert t(array(0)) == 0\n assert t(array([0])) == 0\n assert t(array([[0]])) == 0\n assert t(array([0j])) == 0\n assert t(array([1])) == 1\n pytest.raises(ValueError, t, array([0, 0]))\n\n\nclass TestFReturnLogical(TestReturnLogical):\n sources = [\n util.getpath("tests", "src", "return_logical", "foo77.f"),\n util.getpath("tests", "src", "return_logical", "foo90.f90"),\n ]\n\n @pytest.mark.slow\n @pytest.mark.parametrize("name", ["t0", "t1", "t2", "t4", "s0", "s1", "s2", "s4"])\n def test_all_f77(self, name):\n self.check_function(getattr(self.module, name))\n\n @pytest.mark.slow\n @pytest.mark.parametrize("name",\n ["t0", "t1", "t2", "t4", "t8", "s0", "s1", "s2", "s4", "s8"])\n def test_all_f90(self, name):\n self.check_function(getattr(self.module.f90_return_logical, name))\n
.venv\Lib\site-packages\numpy\f2py\tests\test_return_logical.py
test_return_logical.py
Python
2,113
0.85
0.076923
0
node-utils
305
2024-03-20T07:30:08.716390
BSD-3-Clause
true
cef7b535f2d1b0129af401700a931c82
import platform\n\nimport pytest\n\nfrom numpy import array\nfrom numpy.testing import IS_64BIT\n\nfrom . import util\n\n\n@pytest.mark.slow\nclass TestReturnReal(util.F2PyTest):\n def check_function(self, t, tname):\n if tname in ["t0", "t4", "s0", "s4"]:\n err = 1e-5\n else:\n err = 0.0\n assert abs(t(234) - 234.0) <= err\n assert abs(t(234.6) - 234.6) <= err\n assert abs(t("234") - 234) <= err\n assert abs(t("234.6") - 234.6) <= err\n assert abs(t(-234) + 234) <= err\n assert abs(t([234]) - 234) <= err\n assert abs(t((234, )) - 234.0) <= err\n assert abs(t(array(234)) - 234.0) <= err\n assert abs(t(array(234).astype("b")) + 22) <= err\n assert abs(t(array(234, "h")) - 234.0) <= err\n assert abs(t(array(234, "i")) - 234.0) <= err\n assert abs(t(array(234, "l")) - 234.0) <= err\n assert abs(t(array(234, "B")) - 234.0) <= err\n assert abs(t(array(234, "f")) - 234.0) <= err\n assert abs(t(array(234, "d")) - 234.0) <= err\n if tname in ["t0", "t4", "s0", "s4"]:\n assert t(1e200) == t(1e300) # inf\n\n # pytest.raises(ValueError, t, array([234], 'S1'))\n pytest.raises(ValueError, t, "abc")\n\n pytest.raises(IndexError, t, [])\n pytest.raises(IndexError, t, ())\n\n pytest.raises(Exception, t, t)\n pytest.raises(Exception, t, {})\n\n try:\n r = t(10**400)\n assert repr(r) in ["inf", "Infinity"]\n except OverflowError:\n pass\n\n\n@pytest.mark.skipif(\n platform.system() == "Darwin",\n reason="Prone to error when run with numpy/f2py/tests on mac os, "\n "but not when run in isolation",\n)\n@pytest.mark.skipif(\n not IS_64BIT, reason="32-bit builds are buggy"\n)\nclass TestCReturnReal(TestReturnReal):\n suffix = ".pyf"\n module_name = "c_ext_return_real"\n code = """\npython module c_ext_return_real\nusercode \'\'\'\nfloat t4(float value) { return value; }\nvoid s4(float *t4, float value) { *t4 = value; }\ndouble t8(double value) { return value; }\nvoid s8(double *t8, double value) { *t8 = value; }\n\'\'\'\ninterface\n function t4(value)\n real*4 intent(c) :: t4,value\n end\n function t8(value)\n real*8 intent(c) :: t8,value\n end\n subroutine s4(t4,value)\n intent(c) s4\n real*4 intent(out) :: t4\n real*4 intent(c) :: value\n end\n subroutine s8(t8,value)\n intent(c) s8\n real*8 intent(out) :: t8\n real*8 intent(c) :: value\n end\nend interface\nend python module c_ext_return_real\n """\n\n @pytest.mark.parametrize("name", ["t4", "t8", "s4", "s8"])\n def test_all(self, name):\n self.check_function(getattr(self.module, name), name)\n\n\nclass TestFReturnReal(TestReturnReal):\n sources = [\n util.getpath("tests", "src", "return_real", "foo77.f"),\n util.getpath("tests", "src", "return_real", "foo90.f90"),\n ]\n\n @pytest.mark.parametrize("name", ["t0", "t4", "t8", "td", "s0", "s4", "s8", "sd"])\n def test_all_f77(self, name):\n self.check_function(getattr(self.module, name), name)\n\n @pytest.mark.parametrize("name", ["t0", "t4", "t8", "td", "s0", "s4", "s8", "sd"])\n def test_all_f90(self, name):\n self.check_function(getattr(self.module.f90_return_real, name), name)\n
.venv\Lib\site-packages\numpy\f2py\tests\test_return_real.py
test_return_real.py
Python
3,382
0.95
0.110092
0.010753
react-lib
104
2024-04-18T13:09:58.913020
BSD-3-Clause
true
88b2cdd1ee21afc2546c86620c152716
import pytest\n\nfrom . import util\n\n\n@pytest.mark.slow\nclass TestRenamedFunc(util.F2PyTest):\n sources = [\n util.getpath("tests", "src", "routines", "funcfortranname.f"),\n util.getpath("tests", "src", "routines", "funcfortranname.pyf"),\n ]\n module_name = "funcfortranname"\n\n def test_gh25799(self):\n assert dir(self.module)\n assert self.module.funcfortranname_default(200, 12) == 212\n\n\n@pytest.mark.slow\nclass TestRenamedSubroutine(util.F2PyTest):\n sources = [\n util.getpath("tests", "src", "routines", "subrout.f"),\n util.getpath("tests", "src", "routines", "subrout.pyf"),\n ]\n module_name = "subrout"\n\n def test_renamed_subroutine(self):\n assert dir(self.module)\n assert self.module.subrout_default(200, 12) == 212\n
.venv\Lib\site-packages\numpy\f2py\tests\test_routines.py
test_routines.py
Python
824
0.85
0.137931
0
react-lib
593
2025-03-12T21:57:47.336910
MIT
true
5a6f346e41ffd0750f363df2da4a3e19
import platform\n\nimport pytest\n\nfrom numpy.testing import IS_64BIT\n\nfrom . import util\n\n\n@pytest.mark.skipif(\n platform.system() == "Darwin",\n reason="Prone to error when run with numpy/f2py/tests on mac os, "\n "but not when run in isolation",\n)\n@pytest.mark.skipif(\n not IS_64BIT, reason="32-bit builds are buggy"\n)\nclass TestMultiline(util.F2PyTest):\n suffix = ".pyf"\n module_name = "multiline"\n code = f"""\npython module {module_name}\n usercode '''\nvoid foo(int* x) {{\n char dummy = ';';\n *x = 42;\n}}\n'''\n interface\n subroutine foo(x)\n intent(c) foo\n integer intent(out) :: x\n end subroutine foo\n end interface\nend python module {module_name}\n """\n\n def test_multiline(self):\n assert self.module.foo() == 42\n\n\n@pytest.mark.skipif(\n platform.system() == "Darwin",\n reason="Prone to error when run with numpy/f2py/tests on mac os, "\n "but not when run in isolation",\n)\n@pytest.mark.skipif(\n not IS_64BIT, reason="32-bit builds are buggy"\n)\n@pytest.mark.slow\nclass TestCallstatement(util.F2PyTest):\n suffix = ".pyf"\n module_name = "callstatement"\n code = f"""\npython module {module_name}\n usercode '''\nvoid foo(int* x) {{\n}}\n'''\n interface\n subroutine foo(x)\n intent(c) foo\n integer intent(out) :: x\n callprotoargument int*\n callstatement {{ &\n ; &\n x = 42; &\n }}\n end subroutine foo\n end interface\nend python module {module_name}\n """\n\n def test_callstatement(self):\n assert self.module.foo() == 42\n
.venv\Lib\site-packages\numpy\f2py\tests\test_semicolon_split.py
test_semicolon_split.py
Python
1,702
0.85
0.053333
0.015152
vue-tools
185
2023-08-22T04:18:04.215052
GPL-3.0
true
241b109e3b736e25e174a3ba81076dc1
import pytest\n\nimport numpy as np\n\nfrom . import util\n\n\nclass TestSizeSumExample(util.F2PyTest):\n sources = [util.getpath("tests", "src", "size", "foo.f90")]\n\n @pytest.mark.slow\n def test_all(self):\n r = self.module.foo([[]])\n assert r == [0]\n\n r = self.module.foo([[1, 2]])\n assert r == [3]\n\n r = self.module.foo([[1, 2], [3, 4]])\n assert np.allclose(r, [3, 7])\n\n r = self.module.foo([[1, 2], [3, 4], [5, 6]])\n assert np.allclose(r, [3, 7, 11])\n\n @pytest.mark.slow\n def test_transpose(self):\n r = self.module.trans([[]])\n assert np.allclose(r.T, np.array([[]]))\n\n r = self.module.trans([[1, 2]])\n assert np.allclose(r, [[1.], [2.]])\n\n r = self.module.trans([[1, 2, 3], [4, 5, 6]])\n assert np.allclose(r, [[1, 4], [2, 5], [3, 6]])\n\n @pytest.mark.slow\n def test_flatten(self):\n r = self.module.flatten([[]])\n assert np.allclose(r, [])\n\n r = self.module.flatten([[1, 2]])\n assert np.allclose(r, [1, 2])\n\n r = self.module.flatten([[1, 2, 3], [4, 5, 6]])\n assert np.allclose(r, [1, 2, 3, 4, 5, 6])\n
.venv\Lib\site-packages\numpy\f2py\tests\test_size.py
test_size.py
Python
1,200
0.85
0.088889
0
react-lib
576
2025-06-08T08:48:38.263839
MIT
true
f4ca5ed1ad76fdbce392e65a6a35a718
import pytest\n\nimport numpy as np\n\nfrom . import util\n\n\nclass TestString(util.F2PyTest):\n sources = [util.getpath("tests", "src", "string", "char.f90")]\n\n @pytest.mark.slow\n def test_char(self):\n strings = np.array(["ab", "cd", "ef"], dtype="c").T\n inp, out = self.module.char_test.change_strings(\n strings, strings.shape[1])\n assert inp == pytest.approx(strings)\n expected = strings.copy()\n expected[1, :] = "AAA"\n assert out == pytest.approx(expected)\n\n\nclass TestDocStringArguments(util.F2PyTest):\n sources = [util.getpath("tests", "src", "string", "string.f")]\n\n def test_example(self):\n a = np.array(b"123\0\0")\n b = np.array(b"123\0\0")\n c = np.array(b"123")\n d = np.array(b"123")\n\n self.module.foo(a, b, c, d)\n\n assert a.tobytes() == b"123\0\0"\n assert b.tobytes() == b"B23\0\0"\n assert c.tobytes() == b"123"\n assert d.tobytes() == b"D23"\n\n\nclass TestFixedString(util.F2PyTest):\n sources = [util.getpath("tests", "src", "string", "fixed_string.f90")]\n\n @staticmethod\n def _sint(s, start=0, end=None):\n """Return the content of a string buffer as integer value.\n\n For example:\n _sint('1234') -> 4321\n _sint('123A') -> 17321\n """\n if isinstance(s, np.ndarray):\n s = s.tobytes()\n elif isinstance(s, str):\n s = s.encode()\n assert isinstance(s, bytes)\n if end is None:\n end = len(s)\n i = 0\n for j in range(start, min(end, len(s))):\n i += s[j] * 10**j\n return i\n\n def _get_input(self, intent="in"):\n if intent in ["in"]:\n yield ""\n yield "1"\n yield "1234"\n yield "12345"\n yield b""\n yield b"\0"\n yield b"1"\n yield b"\01"\n yield b"1\0"\n yield b"1234"\n yield b"12345"\n yield np.ndarray((), np.bytes_, buffer=b"") # array(b'', dtype='|S0')\n yield np.array(b"") # array(b'', dtype='|S1')\n yield np.array(b"\0")\n yield np.array(b"1")\n yield np.array(b"1\0")\n yield np.array(b"\01")\n yield np.array(b"1234")\n yield np.array(b"123\0")\n yield np.array(b"12345")\n\n def test_intent_in(self):\n for s in self._get_input():\n r = self.module.test_in_bytes4(s)\n # also checks that s is not changed inplace\n expected = self._sint(s, end=4)\n assert r == expected, s\n\n def test_intent_inout(self):\n for s in self._get_input(intent="inout"):\n rest = self._sint(s, start=4)\n r = self.module.test_inout_bytes4(s)\n expected = self._sint(s, end=4)\n assert r == expected\n\n # check that the rest of input string is preserved\n assert rest == self._sint(s, start=4)\n
.venv\Lib\site-packages\numpy\f2py\tests\test_string.py
test_string.py
Python
3,038
0.95
0.15
0.02439
python-kit
472
2025-03-14T16:58:50.199817
GPL-3.0
true
63a275591e8f2f786e8863558c6d10c6
import pytest\n\nfrom numpy.f2py.symbolic import (\n ArithOp,\n Expr,\n Language,\n Op,\n as_apply,\n as_array,\n as_complex,\n as_deref,\n as_eq,\n as_expr,\n as_factors,\n as_ge,\n as_gt,\n as_le,\n as_lt,\n as_ne,\n as_number,\n as_numer_denom,\n as_ref,\n as_string,\n as_symbol,\n as_terms,\n as_ternary,\n eliminate_quotes,\n fromstring,\n insert_quotes,\n normalize,\n)\n\nfrom . import util\n\n\nclass TestSymbolic(util.F2PyTest):\n def test_eliminate_quotes(self):\n def worker(s):\n r, d = eliminate_quotes(s)\n s1 = insert_quotes(r, d)\n assert s1 == s\n\n for kind in ["", "mykind_"]:\n worker(kind + '"1234" // "ABCD"')\n worker(kind + '"1234" // ' + kind + '"ABCD"')\n worker(kind + "\"1234\" // 'ABCD'")\n worker(kind + '"1234" // ' + kind + "'ABCD'")\n worker(kind + '"1\\"2\'AB\'34"')\n worker("a = " + kind + "'1\\'2\"AB\"34'")\n\n def test_sanity(self):\n x = as_symbol("x")\n y = as_symbol("y")\n z = as_symbol("z")\n\n assert x.op == Op.SYMBOL\n assert repr(x) == "Expr(Op.SYMBOL, 'x')"\n assert x == x\n assert x != y\n assert hash(x) is not None\n\n n = as_number(123)\n m = as_number(456)\n assert n.op == Op.INTEGER\n assert repr(n) == "Expr(Op.INTEGER, (123, 4))"\n assert n == n\n assert n != m\n assert hash(n) is not None\n\n fn = as_number(12.3)\n fm = as_number(45.6)\n assert fn.op == Op.REAL\n assert repr(fn) == "Expr(Op.REAL, (12.3, 4))"\n assert fn == fn\n assert fn != fm\n assert hash(fn) is not None\n\n c = as_complex(1, 2)\n c2 = as_complex(3, 4)\n assert c.op == Op.COMPLEX\n assert repr(c) == ("Expr(Op.COMPLEX, (Expr(Op.INTEGER, (1, 4)),"\n " Expr(Op.INTEGER, (2, 4))))")\n assert c == c\n assert c != c2\n assert hash(c) is not None\n\n s = as_string("'123'")\n s2 = as_string('"ABC"')\n assert s.op == Op.STRING\n assert repr(s) == "Expr(Op.STRING, (\"'123'\", 1))", repr(s)\n assert s == s\n assert s != s2\n\n a = as_array((n, m))\n b = as_array((n, ))\n assert a.op == Op.ARRAY\n assert repr(a) == ("Expr(Op.ARRAY, (Expr(Op.INTEGER, (123, 4)),"\n " Expr(Op.INTEGER, (456, 4))))")\n assert a == a\n assert a != b\n\n t = as_terms(x)\n u = as_terms(y)\n assert t.op == Op.TERMS\n assert repr(t) == "Expr(Op.TERMS, {Expr(Op.SYMBOL, 'x'): 1})"\n assert t == t\n assert t != u\n assert hash(t) is not None\n\n v = as_factors(x)\n w = as_factors(y)\n assert v.op == Op.FACTORS\n assert repr(v) == "Expr(Op.FACTORS, {Expr(Op.SYMBOL, 'x'): 1})"\n assert v == v\n assert w != v\n assert hash(v) is not None\n\n t = as_ternary(x, y, z)\n u = as_ternary(x, z, y)\n assert t.op == Op.TERNARY\n assert t == t\n assert t != u\n assert hash(t) is not None\n\n e = as_eq(x, y)\n f = as_lt(x, y)\n assert e.op == Op.RELATIONAL\n assert e == e\n assert e != f\n assert hash(e) is not None\n\n def test_tostring_fortran(self):\n x = as_symbol("x")\n y = as_symbol("y")\n z = as_symbol("z")\n n = as_number(123)\n m = as_number(456)\n a = as_array((n, m))\n c = as_complex(n, m)\n\n assert str(x) == "x"\n assert str(n) == "123"\n assert str(a) == "[123, 456]"\n assert str(c) == "(123, 456)"\n\n assert str(Expr(Op.TERMS, {x: 1})) == "x"\n assert str(Expr(Op.TERMS, {x: 2})) == "2 * x"\n assert str(Expr(Op.TERMS, {x: -1})) == "-x"\n assert str(Expr(Op.TERMS, {x: -2})) == "-2 * x"\n assert str(Expr(Op.TERMS, {x: 1, y: 1})) == "x + y"\n assert str(Expr(Op.TERMS, {x: -1, y: -1})) == "-x - y"\n assert str(Expr(Op.TERMS, {x: 2, y: 3})) == "2 * x + 3 * y"\n assert str(Expr(Op.TERMS, {x: -2, y: 3})) == "-2 * x + 3 * y"\n assert str(Expr(Op.TERMS, {x: 2, y: -3})) == "2 * x - 3 * y"\n\n assert str(Expr(Op.FACTORS, {x: 1})) == "x"\n assert str(Expr(Op.FACTORS, {x: 2})) == "x ** 2"\n assert str(Expr(Op.FACTORS, {x: -1})) == "x ** -1"\n assert str(Expr(Op.FACTORS, {x: -2})) == "x ** -2"\n assert str(Expr(Op.FACTORS, {x: 1, y: 1})) == "x * y"\n assert str(Expr(Op.FACTORS, {x: 2, y: 3})) == "x ** 2 * y ** 3"\n\n v = Expr(Op.FACTORS, {x: 2, Expr(Op.TERMS, {x: 1, y: 1}): 3})\n assert str(v) == "x ** 2 * (x + y) ** 3", str(v)\n v = Expr(Op.FACTORS, {x: 2, Expr(Op.FACTORS, {x: 1, y: 1}): 3})\n assert str(v) == "x ** 2 * (x * y) ** 3", str(v)\n\n assert str(Expr(Op.APPLY, ("f", (), {}))) == "f()"\n assert str(Expr(Op.APPLY, ("f", (x, ), {}))) == "f(x)"\n assert str(Expr(Op.APPLY, ("f", (x, y), {}))) == "f(x, y)"\n assert str(Expr(Op.INDEXING, ("f", x))) == "f[x]"\n\n assert str(as_ternary(x, y, z)) == "merge(y, z, x)"\n assert str(as_eq(x, y)) == "x .eq. y"\n assert str(as_ne(x, y)) == "x .ne. y"\n assert str(as_lt(x, y)) == "x .lt. y"\n assert str(as_le(x, y)) == "x .le. y"\n assert str(as_gt(x, y)) == "x .gt. y"\n assert str(as_ge(x, y)) == "x .ge. y"\n\n def test_tostring_c(self):\n language = Language.C\n x = as_symbol("x")\n y = as_symbol("y")\n z = as_symbol("z")\n n = as_number(123)\n\n assert Expr(Op.FACTORS, {x: 2}).tostring(language=language) == "x * x"\n assert (Expr(Op.FACTORS, {\n x + y: 2\n }).tostring(language=language) == "(x + y) * (x + y)")\n assert Expr(Op.FACTORS, {\n x: 12\n }).tostring(language=language) == "pow(x, 12)"\n\n assert as_apply(ArithOp.DIV, x,\n y).tostring(language=language) == "x / y"\n assert (as_apply(ArithOp.DIV, x,\n x + y).tostring(language=language) == "x / (x + y)")\n assert (as_apply(ArithOp.DIV, x - y, x +\n y).tostring(language=language) == "(x - y) / (x + y)")\n assert (x + (x - y) / (x + y) +\n n).tostring(language=language) == "123 + x + (x - y) / (x + y)"\n\n assert as_ternary(x, y, z).tostring(language=language) == "(x?y:z)"\n assert as_eq(x, y).tostring(language=language) == "x == y"\n assert as_ne(x, y).tostring(language=language) == "x != y"\n assert as_lt(x, y).tostring(language=language) == "x < y"\n assert as_le(x, y).tostring(language=language) == "x <= y"\n assert as_gt(x, y).tostring(language=language) == "x > y"\n assert as_ge(x, y).tostring(language=language) == "x >= y"\n\n def test_operations(self):\n x = as_symbol("x")\n y = as_symbol("y")\n z = as_symbol("z")\n\n assert x + x == Expr(Op.TERMS, {x: 2})\n assert x - x == Expr(Op.INTEGER, (0, 4))\n assert x + y == Expr(Op.TERMS, {x: 1, y: 1})\n assert x - y == Expr(Op.TERMS, {x: 1, y: -1})\n assert x * x == Expr(Op.FACTORS, {x: 2})\n assert x * y == Expr(Op.FACTORS, {x: 1, y: 1})\n\n assert +x == x\n assert -x == Expr(Op.TERMS, {x: -1}), repr(-x)\n assert 2 * x == Expr(Op.TERMS, {x: 2})\n assert 2 + x == Expr(Op.TERMS, {x: 1, as_number(1): 2})\n assert 2 * x + 3 * y == Expr(Op.TERMS, {x: 2, y: 3})\n assert (x + y) * 2 == Expr(Op.TERMS, {x: 2, y: 2})\n\n assert x**2 == Expr(Op.FACTORS, {x: 2})\n assert (x + y)**2 == Expr(\n Op.TERMS,\n {\n Expr(Op.FACTORS, {x: 2}): 1,\n Expr(Op.FACTORS, {y: 2}): 1,\n Expr(Op.FACTORS, {\n x: 1,\n y: 1\n }): 2,\n },\n )\n assert (x + y) * x == x**2 + x * y\n assert (x + y)**2 == x**2 + 2 * x * y + y**2\n assert (x + y)**2 + (x - y)**2 == 2 * x**2 + 2 * y**2\n assert (x + y) * z == x * z + y * z\n assert z * (x + y) == x * z + y * z\n\n assert (x / 2) == as_apply(ArithOp.DIV, x, as_number(2))\n assert (2 * x / 2) == x\n assert (3 * x / 2) == as_apply(ArithOp.DIV, 3 * x, as_number(2))\n assert (4 * x / 2) == 2 * x\n assert (5 * x / 2) == as_apply(ArithOp.DIV, 5 * x, as_number(2))\n assert (6 * x / 2) == 3 * x\n assert ((3 * 5) * x / 6) == as_apply(ArithOp.DIV, 5 * x, as_number(2))\n assert (30 * x**2 * y**4 / (24 * x**3 * y**3)) == as_apply(\n ArithOp.DIV, 5 * y, 4 * x)\n assert ((15 * x / 6) / 5) == as_apply(ArithOp.DIV, x,\n as_number(2)), (15 * x / 6) / 5\n assert (x / (5 / x)) == as_apply(ArithOp.DIV, x**2, as_number(5))\n\n assert (x / 2.0) == Expr(Op.TERMS, {x: 0.5})\n\n s = as_string('"ABC"')\n t = as_string('"123"')\n\n assert s // t == Expr(Op.STRING, ('"ABC123"', 1))\n assert s // x == Expr(Op.CONCAT, (s, x))\n assert x // s == Expr(Op.CONCAT, (x, s))\n\n c = as_complex(1.0, 2.0)\n assert -c == as_complex(-1.0, -2.0)\n assert c + c == as_expr((1 + 2j) * 2)\n assert c * c == as_expr((1 + 2j)**2)\n\n def test_substitute(self):\n x = as_symbol("x")\n y = as_symbol("y")\n z = as_symbol("z")\n a = as_array((x, y))\n\n assert x.substitute({x: y}) == y\n assert (x + y).substitute({x: z}) == y + z\n assert (x * y).substitute({x: z}) == y * z\n assert (x**4).substitute({x: z}) == z**4\n assert (x / y).substitute({x: z}) == z / y\n assert x.substitute({x: y + z}) == y + z\n assert a.substitute({x: y + z}) == as_array((y + z, y))\n\n assert as_ternary(x, y,\n z).substitute({x: y + z}) == as_ternary(y + z, y, z)\n assert as_eq(x, y).substitute({x: y + z}) == as_eq(y + z, y)\n\n def test_fromstring(self):\n\n x = as_symbol("x")\n y = as_symbol("y")\n z = as_symbol("z")\n f = as_symbol("f")\n s = as_string('"ABC"')\n t = as_string('"123"')\n a = as_array((x, y))\n\n assert fromstring("x") == x\n assert fromstring("+ x") == x\n assert fromstring("- x") == -x\n assert fromstring("x + y") == x + y\n assert fromstring("x + 1") == x + 1\n assert fromstring("x * y") == x * y\n assert fromstring("x * 2") == x * 2\n assert fromstring("x / y") == x / y\n assert fromstring("x ** 2", language=Language.Python) == x**2\n assert fromstring("x ** 2 ** 3", language=Language.Python) == x**2**3\n assert fromstring("(x + y) * z") == (x + y) * z\n\n assert fromstring("f(x)") == f(x)\n assert fromstring("f(x,y)") == f(x, y)\n assert fromstring("f[x]") == f[x]\n assert fromstring("f[x][y]") == f[x][y]\n\n assert fromstring('"ABC"') == s\n assert (normalize(\n fromstring('"ABC" // "123" ',\n language=Language.Fortran)) == s // t)\n assert fromstring('f("ABC")') == f(s)\n assert fromstring('MYSTRKIND_"ABC"') == as_string('"ABC"', "MYSTRKIND")\n\n assert fromstring("(/x, y/)") == a, fromstring("(/x, y/)")\n assert fromstring("f((/x, y/))") == f(a)\n assert fromstring("(/(x+y)*z/)") == as_array(((x + y) * z, ))\n\n assert fromstring("123") == as_number(123)\n assert fromstring("123_2") == as_number(123, 2)\n assert fromstring("123_myintkind") == as_number(123, "myintkind")\n\n assert fromstring("123.0") == as_number(123.0, 4)\n assert fromstring("123.0_4") == as_number(123.0, 4)\n assert fromstring("123.0_8") == as_number(123.0, 8)\n assert fromstring("123.0e0") == as_number(123.0, 4)\n assert fromstring("123.0d0") == as_number(123.0, 8)\n assert fromstring("123d0") == as_number(123.0, 8)\n assert fromstring("123e-0") == as_number(123.0, 4)\n assert fromstring("123d+0") == as_number(123.0, 8)\n assert fromstring("123.0_myrealkind") == as_number(123.0, "myrealkind")\n assert fromstring("3E4") == as_number(30000.0, 4)\n\n assert fromstring("(1, 2)") == as_complex(1, 2)\n assert fromstring("(1e2, PI)") == as_complex(as_number(100.0),\n as_symbol("PI"))\n\n assert fromstring("[1, 2]") == as_array((as_number(1), as_number(2)))\n\n assert fromstring("POINT(x, y=1)") == as_apply(as_symbol("POINT"),\n x,\n y=as_number(1))\n assert fromstring(\n 'PERSON(name="John", age=50, shape=(/34, 23/))') == as_apply(\n as_symbol("PERSON"),\n name=as_string('"John"'),\n age=as_number(50),\n shape=as_array((as_number(34), as_number(23))),\n )\n\n assert fromstring("x?y:z") == as_ternary(x, y, z)\n\n assert fromstring("*x") == as_deref(x)\n assert fromstring("**x") == as_deref(as_deref(x))\n assert fromstring("&x") == as_ref(x)\n assert fromstring("(*x) * (*y)") == as_deref(x) * as_deref(y)\n assert fromstring("(*x) * *y") == as_deref(x) * as_deref(y)\n assert fromstring("*x * *y") == as_deref(x) * as_deref(y)\n assert fromstring("*x**y") == as_deref(x) * as_deref(y)\n\n assert fromstring("x == y") == as_eq(x, y)\n assert fromstring("x != y") == as_ne(x, y)\n assert fromstring("x < y") == as_lt(x, y)\n assert fromstring("x > y") == as_gt(x, y)\n assert fromstring("x <= y") == as_le(x, y)\n assert fromstring("x >= y") == as_ge(x, y)\n\n assert fromstring("x .eq. y", language=Language.Fortran) == as_eq(x, y)\n assert fromstring("x .ne. y", language=Language.Fortran) == as_ne(x, y)\n assert fromstring("x .lt. y", language=Language.Fortran) == as_lt(x, y)\n assert fromstring("x .gt. y", language=Language.Fortran) == as_gt(x, y)\n assert fromstring("x .le. y", language=Language.Fortran) == as_le(x, y)\n assert fromstring("x .ge. y", language=Language.Fortran) == as_ge(x, y)\n\n def test_traverse(self):\n x = as_symbol("x")\n y = as_symbol("y")\n z = as_symbol("z")\n f = as_symbol("f")\n\n # Use traverse to substitute a symbol\n def replace_visit(s, r=z):\n if s == x:\n return r\n\n assert x.traverse(replace_visit) == z\n assert y.traverse(replace_visit) == y\n assert z.traverse(replace_visit) == z\n assert (f(y)).traverse(replace_visit) == f(y)\n assert (f(x)).traverse(replace_visit) == f(z)\n assert (f[y]).traverse(replace_visit) == f[y]\n assert (f[z]).traverse(replace_visit) == f[z]\n assert (x + y + z).traverse(replace_visit) == (2 * z + y)\n assert (x +\n f(y, x - z)).traverse(replace_visit) == (z +\n f(y, as_number(0)))\n assert as_eq(x, y).traverse(replace_visit) == as_eq(z, y)\n\n # Use traverse to collect symbols, method 1\n function_symbols = set()\n symbols = set()\n\n def collect_symbols(s):\n if s.op is Op.APPLY:\n oper = s.data[0]\n function_symbols.add(oper)\n if oper in symbols:\n symbols.remove(oper)\n elif s.op is Op.SYMBOL and s not in function_symbols:\n symbols.add(s)\n\n (x + f(y, x - z)).traverse(collect_symbols)\n assert function_symbols == {f}\n assert symbols == {x, y, z}\n\n # Use traverse to collect symbols, method 2\n def collect_symbols2(expr, symbols):\n if expr.op is Op.SYMBOL:\n symbols.add(expr)\n\n symbols = set()\n (x + f(y, x - z)).traverse(collect_symbols2, symbols)\n assert symbols == {x, y, z, f}\n\n # Use traverse to partially collect symbols\n def collect_symbols3(expr, symbols):\n if expr.op is Op.APPLY:\n # skip traversing function calls\n return expr\n if expr.op is Op.SYMBOL:\n symbols.add(expr)\n\n symbols = set()\n (x + f(y, x - z)).traverse(collect_symbols3, symbols)\n assert symbols == {x}\n\n def test_linear_solve(self):\n x = as_symbol("x")\n y = as_symbol("y")\n z = as_symbol("z")\n\n assert x.linear_solve(x) == (as_number(1), as_number(0))\n assert (x + 1).linear_solve(x) == (as_number(1), as_number(1))\n assert (2 * x).linear_solve(x) == (as_number(2), as_number(0))\n assert (2 * x + 3).linear_solve(x) == (as_number(2), as_number(3))\n assert as_number(3).linear_solve(x) == (as_number(0), as_number(3))\n assert y.linear_solve(x) == (as_number(0), y)\n assert (y * z).linear_solve(x) == (as_number(0), y * z)\n\n assert (x + y).linear_solve(x) == (as_number(1), y)\n assert (z * x + y).linear_solve(x) == (z, y)\n assert ((z + y) * x + y).linear_solve(x) == (z + y, y)\n assert (z * y * x + y).linear_solve(x) == (z * y, y)\n\n pytest.raises(RuntimeError, lambda: (x * x).linear_solve(x))\n\n def test_as_numer_denom(self):\n x = as_symbol("x")\n y = as_symbol("y")\n n = as_number(123)\n\n assert as_numer_denom(x) == (x, as_number(1))\n assert as_numer_denom(x / n) == (x, n)\n assert as_numer_denom(n / x) == (n, x)\n assert as_numer_denom(x / y) == (x, y)\n assert as_numer_denom(x * y) == (x * y, as_number(1))\n assert as_numer_denom(n + x / y) == (x + n * y, y)\n assert as_numer_denom(n + x / (y - x / n)) == (y * n**2, y * n - x)\n\n def test_polynomial_atoms(self):\n x = as_symbol("x")\n y = as_symbol("y")\n n = as_number(123)\n\n assert x.polynomial_atoms() == {x}\n assert n.polynomial_atoms() == set()\n assert (y[x]).polynomial_atoms() == {y[x]}\n assert (y(x)).polynomial_atoms() == {y(x)}\n assert (y(x) + x).polynomial_atoms() == {y(x), x}\n assert (y(x) * x[y]).polynomial_atoms() == {y(x), x[y]}\n assert (y(x)**x).polynomial_atoms() == {y(x)}\n
.venv\Lib\site-packages\numpy\f2py\tests\test_symbolic.py
test_symbolic.py
Python
18,837
0.95
0.050505
0.01182
react-lib
537
2024-08-02T14:22:15.202782
MIT
true
609c0aec8f9d7707c51c4eee020b1ede
import pytest\n\nfrom . import util\n\n\nclass TestValueAttr(util.F2PyTest):\n sources = [util.getpath("tests", "src", "value_attrspec", "gh21665.f90")]\n\n # gh-21665\n @pytest.mark.slow\n def test_gh21665(self):\n inp = 2\n out = self.module.fortfuncs.square(inp)\n exp_out = 4\n assert out == exp_out\n
.venv\Lib\site-packages\numpy\f2py\tests\test_value_attrspec.py
test_value_attrspec.py
Python
345
0.95
0.133333
0.090909
python-kit
16
2023-12-23T14:13:39.307740
BSD-3-Clause
true
2fdaddc4b41134a0338f1e41c36b6d2e
"""\nUtility functions for\n\n- building and importing modules on test time, using a temporary location\n- detecting if compilers are present\n- determining paths to tests\n\n"""\nimport atexit\nimport concurrent.futures\nimport contextlib\nimport glob\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nfrom importlib import import_module\nfrom pathlib import Path\n\nimport pytest\n\nimport numpy\nfrom numpy._utils import asunicode\nfrom numpy.f2py._backends._meson import MesonBackend\nfrom numpy.testing import IS_WASM, temppath\n\n#\n# Check if compilers are available at all...\n#\n\ndef check_language(lang, code_snippet=None):\n if sys.platform == "win32":\n pytest.skip("No Fortran tests on Windows (Issue #25134)", allow_module_level=True)\n tmpdir = tempfile.mkdtemp()\n try:\n meson_file = os.path.join(tmpdir, "meson.build")\n with open(meson_file, "w") as f:\n f.write("project('check_compilers')\n")\n f.write(f"add_languages('{lang}')\n")\n if code_snippet:\n f.write(f"{lang}_compiler = meson.get_compiler('{lang}')\n")\n f.write(f"{lang}_code = '''{code_snippet}'''\n")\n f.write(\n f"_have_{lang}_feature ="\n f"{lang}_compiler.compiles({lang}_code,"\n f" name: '{lang} feature check')\n"\n )\n try:\n runmeson = subprocess.run(\n ["meson", "setup", "btmp"],\n check=False,\n cwd=tmpdir,\n capture_output=True,\n )\n except subprocess.CalledProcessError:\n pytest.skip("meson not present, skipping compiler dependent test", allow_module_level=True)\n return runmeson.returncode == 0\n finally:\n shutil.rmtree(tmpdir)\n\n\nfortran77_code = '''\nC Example Fortran 77 code\n PROGRAM HELLO\n PRINT *, 'Hello, Fortran 77!'\n END\n'''\n\nfortran90_code = '''\n! Example Fortran 90 code\nprogram hello90\n type :: greeting\n character(len=20) :: text\n end type greeting\n\n type(greeting) :: greet\n greet%text = 'hello, fortran 90!'\n print *, greet%text\nend program hello90\n'''\n\n# Dummy class for caching relevant checks\nclass CompilerChecker:\n def __init__(self):\n self.compilers_checked = False\n self.has_c = False\n self.has_f77 = False\n self.has_f90 = False\n\n def check_compilers(self):\n if (not self.compilers_checked) and (not sys.platform == "cygwin"):\n with concurrent.futures.ThreadPoolExecutor() as executor:\n futures = [\n executor.submit(check_language, "c"),\n executor.submit(check_language, "fortran", fortran77_code),\n executor.submit(check_language, "fortran", fortran90_code)\n ]\n\n self.has_c = futures[0].result()\n self.has_f77 = futures[1].result()\n self.has_f90 = futures[2].result()\n\n self.compilers_checked = True\n\n\nif not IS_WASM:\n checker = CompilerChecker()\n checker.check_compilers()\n\ndef has_c_compiler():\n return checker.has_c\n\ndef has_f77_compiler():\n return checker.has_f77\n\ndef has_f90_compiler():\n return checker.has_f90\n\ndef has_fortran_compiler():\n return (checker.has_f90 and checker.has_f77)\n\n\n#\n# Maintaining a temporary module directory\n#\n\n_module_dir = None\n_module_num = 5403\n\nif sys.platform == "cygwin":\n NUMPY_INSTALL_ROOT = Path(__file__).parent.parent.parent\n _module_list = list(NUMPY_INSTALL_ROOT.glob("**/*.dll"))\n\n\ndef _cleanup():\n global _module_dir\n if _module_dir is not None:\n try:\n sys.path.remove(_module_dir)\n except ValueError:\n pass\n try:\n shutil.rmtree(_module_dir)\n except OSError:\n pass\n _module_dir = None\n\n\ndef get_module_dir():\n global _module_dir\n if _module_dir is None:\n _module_dir = tempfile.mkdtemp()\n atexit.register(_cleanup)\n if _module_dir not in sys.path:\n sys.path.insert(0, _module_dir)\n return _module_dir\n\n\ndef get_temp_module_name():\n # Assume single-threaded, and the module dir usable only by this thread\n global _module_num\n get_module_dir()\n name = "_test_ext_module_%d" % _module_num\n _module_num += 1\n if name in sys.modules:\n # this should not be possible, but check anyway\n raise RuntimeError("Temporary module name already in use.")\n return name\n\n\ndef _memoize(func):\n memo = {}\n\n def wrapper(*a, **kw):\n key = repr((a, kw))\n if key not in memo:\n try:\n memo[key] = func(*a, **kw)\n except Exception as e:\n memo[key] = e\n raise\n ret = memo[key]\n if isinstance(ret, Exception):\n raise ret\n return ret\n\n wrapper.__name__ = func.__name__\n return wrapper\n\n\n#\n# Building modules\n#\n\n\n@_memoize\ndef build_module(source_files, options=[], skip=[], only=[], module_name=None):\n """\n Compile and import a f2py module, built from the given files.\n\n """\n\n code = f"import sys; sys.path = {sys.path!r}; import numpy.f2py; numpy.f2py.main()"\n\n d = get_module_dir()\n # gh-27045 : Skip if no compilers are found\n if not has_fortran_compiler():\n pytest.skip("No Fortran compiler available")\n\n # Copy files\n dst_sources = []\n f2py_sources = []\n for fn in source_files:\n if not os.path.isfile(fn):\n raise RuntimeError(f"{fn} is not a file")\n dst = os.path.join(d, os.path.basename(fn))\n shutil.copyfile(fn, dst)\n dst_sources.append(dst)\n\n base, ext = os.path.splitext(dst)\n if ext in (".f90", ".f95", ".f", ".c", ".pyf"):\n f2py_sources.append(dst)\n\n assert f2py_sources\n\n # Prepare options\n if module_name is None:\n module_name = get_temp_module_name()\n gil_options = []\n if '--freethreading-compatible' not in options and '--no-freethreading-compatible' not in options:\n # default to disabling the GIL if unset in options\n gil_options = ['--freethreading-compatible']\n f2py_opts = ["-c", "-m", module_name] + options + gil_options + f2py_sources\n f2py_opts += ["--backend", "meson"]\n if skip:\n f2py_opts += ["skip:"] + skip\n if only:\n f2py_opts += ["only:"] + only\n\n # Build\n cwd = os.getcwd()\n try:\n os.chdir(d)\n cmd = [sys.executable, "-c", code] + f2py_opts\n p = subprocess.Popen(cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n out, err = p.communicate()\n if p.returncode != 0:\n raise RuntimeError(f"Running f2py failed: {cmd[4:]}\n{asunicode(out)}")\n finally:\n os.chdir(cwd)\n\n # Partial cleanup\n for fn in dst_sources:\n os.unlink(fn)\n\n # Rebase (Cygwin-only)\n if sys.platform == "cygwin":\n # If someone starts deleting modules after import, this will\n # need to change to record how big each module is, rather than\n # relying on rebase being able to find that from the files.\n _module_list.extend(\n glob.glob(os.path.join(d, f"{module_name:s}*"))\n )\n subprocess.check_call(\n ["/usr/bin/rebase", "--database", "--oblivious", "--verbose"]\n + _module_list\n )\n\n # Import\n return import_module(module_name)\n\n\n@_memoize\ndef build_code(source_code,\n options=[],\n skip=[],\n only=[],\n suffix=None,\n module_name=None):\n """\n Compile and import Fortran code using f2py.\n\n """\n if suffix is None:\n suffix = ".f"\n with temppath(suffix=suffix) as path:\n with open(path, "w") as f:\n f.write(source_code)\n return build_module([path],\n options=options,\n skip=skip,\n only=only,\n module_name=module_name)\n\n\n#\n# Building with meson\n#\n\n\nclass SimplifiedMesonBackend(MesonBackend):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def compile(self):\n self.write_meson_build(self.build_dir)\n self.run_meson(self.build_dir)\n\n\ndef build_meson(source_files, module_name=None, **kwargs):\n """\n Build a module via Meson and import it.\n """\n\n # gh-27045 : Skip if no compilers are found\n if not has_fortran_compiler():\n pytest.skip("No Fortran compiler available")\n\n build_dir = get_module_dir()\n if module_name is None:\n module_name = get_temp_module_name()\n\n # Initialize the MesonBackend\n backend = SimplifiedMesonBackend(\n modulename=module_name,\n sources=source_files,\n extra_objects=kwargs.get("extra_objects", []),\n build_dir=build_dir,\n include_dirs=kwargs.get("include_dirs", []),\n library_dirs=kwargs.get("library_dirs", []),\n libraries=kwargs.get("libraries", []),\n define_macros=kwargs.get("define_macros", []),\n undef_macros=kwargs.get("undef_macros", []),\n f2py_flags=kwargs.get("f2py_flags", []),\n sysinfo_flags=kwargs.get("sysinfo_flags", []),\n fc_flags=kwargs.get("fc_flags", []),\n flib_flags=kwargs.get("flib_flags", []),\n setup_flags=kwargs.get("setup_flags", []),\n remove_build_dir=kwargs.get("remove_build_dir", False),\n extra_dat=kwargs.get("extra_dat", {}),\n )\n\n backend.compile()\n\n # Import the compiled module\n sys.path.insert(0, f"{build_dir}/{backend.meson_build_dir}")\n return import_module(module_name)\n\n\n#\n# Unittest convenience\n#\n\n\nclass F2PyTest:\n code = None\n sources = None\n options = []\n skip = []\n only = []\n suffix = ".f"\n module = None\n _has_c_compiler = None\n _has_f77_compiler = None\n _has_f90_compiler = None\n\n @property\n def module_name(self):\n cls = type(self)\n return f'_{cls.__module__.rsplit(".", 1)[-1]}_{cls.__name__}_ext_module'\n\n @classmethod\n def setup_class(cls):\n if sys.platform == "win32":\n pytest.skip("Fails with MinGW64 Gfortran (Issue #9673)")\n F2PyTest._has_c_compiler = has_c_compiler()\n F2PyTest._has_f77_compiler = has_f77_compiler()\n F2PyTest._has_f90_compiler = has_f90_compiler()\n F2PyTest._has_fortran_compiler = has_fortran_compiler()\n\n def setup_method(self):\n if self.module is not None:\n return\n\n codes = self.sources or []\n if self.code:\n codes.append(self.suffix)\n\n needs_f77 = any(str(fn).endswith(".f") for fn in codes)\n needs_f90 = any(str(fn).endswith(".f90") for fn in codes)\n needs_pyf = any(str(fn).endswith(".pyf") for fn in codes)\n\n if needs_f77 and not self._has_f77_compiler:\n pytest.skip("No Fortran 77 compiler available")\n if needs_f90 and not self._has_f90_compiler:\n pytest.skip("No Fortran 90 compiler available")\n if needs_pyf and not self._has_fortran_compiler:\n pytest.skip("No Fortran compiler available")\n\n # Build the module\n if self.code is not None:\n self.module = build_code(\n self.code,\n options=self.options,\n skip=self.skip,\n only=self.only,\n suffix=self.suffix,\n module_name=self.module_name,\n )\n\n if self.sources is not None:\n self.module = build_module(\n self.sources,\n options=self.options,\n skip=self.skip,\n only=self.only,\n module_name=self.module_name,\n )\n\n\n#\n# Helper functions\n#\n\n\ndef getpath(*a):\n # Package root\n d = Path(numpy.f2py.__file__).parent.resolve()\n return d.joinpath(*a)\n\n\n@contextlib.contextmanager\ndef switchdir(path):\n curpath = Path.cwd()\n os.chdir(path)\n try:\n yield\n finally:\n os.chdir(curpath)\n
.venv\Lib\site-packages\numpy\f2py\tests\util.py
util.py
Python
12,554
0.95
0.171946
0.102778
vue-tools
707
2024-06-03T11:54:06.066832
BSD-3-Clause
true
3442f50fa29b6d3044f9daab8b0dcd73
import pytest\n\nfrom numpy.testing import IS_EDITABLE, IS_WASM\n\nif IS_WASM:\n pytest.skip(\n "WASM/Pyodide does not use or support Fortran",\n allow_module_level=True\n )\n\n\nif IS_EDITABLE:\n pytest.skip(\n "Editable install doesn't support tests with a compile step",\n allow_module_level=True\n )\n
.venv\Lib\site-packages\numpy\f2py\tests\__init__.py
__init__.py
Python
345
0.85
0.125
0
awesome-app
947
2025-04-05T16:35:56.699183
BSD-3-Clause
true
00111e98b442351da700056a5765bb06
module ops_module\n\n abstract interface\n subroutine op(x, y, z)\n integer, intent(in) :: x, y\n integer, intent(out) :: z\n end subroutine\n end interface\n\ncontains\n\n subroutine foo(x, y, r1, r2)\n integer, intent(in) :: x, y\n integer, intent(out) :: r1, r2\n procedure (op) add1, add2\n procedure (op), pointer::p\n p=>add1\n call p(x, y, r1)\n p=>add2\n call p(x, y, r2)\n end subroutine\nend module\n\nsubroutine add1(x, y, z)\n integer, intent(in) :: x, y\n integer, intent(out) :: z\n z = x + y\nend subroutine\n\nsubroutine add2(x, y, z)\n integer, intent(in) :: x, y\n integer, intent(out) :: z\n z = x + 2 * y\nend subroutine\n
.venv\Lib\site-packages\numpy\f2py\tests\src\abstract_interface\foo.f90
foo.f90
Other
692
0.7
0
0
node-utils
422
2024-10-27T22:01:42.791691
GPL-3.0
true
8a92e219be7c36cc6b0eff706161716b
module test\n abstract interface\n subroutine foo()\n end subroutine\n end interface\nend module test\n
.venv\Lib\site-packages\numpy\f2py\tests\src\abstract_interface\gh18403_mod.f90
gh18403_mod.f90
Other
111
0.7
0
0
awesome-app
859
2024-07-17T15:02:23.266332
GPL-3.0
true
25fb80bff7c0950e6857fea02a0a31e8
/*\n * This file was auto-generated with f2py (version:2_1330) and hand edited by\n * Pearu for testing purposes. Do not edit this file unless you know what you\n * are doing!!!\n */\n\n#ifdef __cplusplus\nextern "C" {\n#endif\n\n/*********************** See f2py2e/cfuncs.py: includes ***********************/\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include "fortranobject.h"\n#include <math.h>\n\nstatic PyObject *wrap_error;\nstatic PyObject *wrap_module;\n\n/************************************ call ************************************/\nstatic char doc_f2py_rout_wrap_call[] = "\\nFunction signature:\n\\n arr = call(type_num,dims,intent,obj)\n\\nRequired arguments:\n"\n" type_num : input int\n"\n" dims : input int-sequence\n"\n" intent : input int\n"\n" obj : input python object\n"\n"Return objects:\n"\n" arr : array";\nstatic PyObject *f2py_rout_wrap_call(PyObject *capi_self,\n PyObject *capi_args) {\n PyObject * volatile capi_buildvalue = NULL;\n int type_num = 0;\n int elsize = 0;\n npy_intp *dims = NULL;\n PyObject *dims_capi = Py_None;\n int rank = 0;\n int intent = 0;\n PyArrayObject *capi_arr_tmp = NULL;\n PyObject *arr_capi = Py_None;\n int i;\n\n if (!PyArg_ParseTuple(capi_args,"iiOiO|:wrap.call",\\n &type_num,&elsize,&dims_capi,&intent,&arr_capi))\n return NULL;\n rank = PySequence_Length(dims_capi);\n dims = malloc(rank*sizeof(npy_intp));\n for (i=0;i<rank;++i) {\n PyObject *tmp;\n tmp = PySequence_GetItem(dims_capi, i);\n if (tmp == NULL) {\n goto fail;\n }\n dims[i] = (npy_intp)PyLong_AsLong(tmp);\n Py_DECREF(tmp);\n if (dims[i] == -1 && PyErr_Occurred()) {\n goto fail;\n }\n }\n capi_arr_tmp = ndarray_from_pyobj(type_num,elsize,dims,rank,intent|F2PY_INTENT_OUT,arr_capi,"wrap.call failed");\n if (capi_arr_tmp == NULL) {\n free(dims);\n return NULL;\n }\n capi_buildvalue = Py_BuildValue("N",capi_arr_tmp);\n free(dims);\n return capi_buildvalue;\n\nfail:\n free(dims);\n return NULL;\n}\n\nstatic char doc_f2py_rout_wrap_attrs[] = "\\nFunction signature:\n\\n arr = array_attrs(arr)\n\\nRequired arguments:\n"\n" arr : input array object\n"\n"Return objects:\n"\n" data : data address in hex\n"\n" nd : int\n"\n" dimensions : tuple\n"\n" strides : tuple\n"\n" base : python object\n"\n" (kind,type,type_num,elsize,alignment) : 4-tuple\n"\n" flags : int\n"\n" itemsize : int\n"\n;\nstatic PyObject *f2py_rout_wrap_attrs(PyObject *capi_self,\n PyObject *capi_args) {\n PyObject *arr_capi = Py_None;\n PyArrayObject *arr = NULL;\n PyObject *dimensions = NULL;\n PyObject *strides = NULL;\n char s[100];\n int i;\n memset(s,0,100);\n if (!PyArg_ParseTuple(capi_args,"O!|:wrap.attrs",\n &PyArray_Type,&arr_capi))\n return NULL;\n arr = (PyArrayObject *)arr_capi;\n sprintf(s,"%p",PyArray_DATA(arr));\n dimensions = PyTuple_New(PyArray_NDIM(arr));\n strides = PyTuple_New(PyArray_NDIM(arr));\n for (i=0;i<PyArray_NDIM(arr);++i) {\n PyTuple_SetItem(dimensions,i,PyLong_FromLong(PyArray_DIM(arr,i)));\n PyTuple_SetItem(strides,i,PyLong_FromLong(PyArray_STRIDE(arr,i)));\n }\n return Py_BuildValue("siNNO(cciii)ii",s,PyArray_NDIM(arr),\n dimensions,strides,\n (PyArray_BASE(arr)==NULL?Py_None:PyArray_BASE(arr)),\n PyArray_DESCR(arr)->kind,\n PyArray_DESCR(arr)->type,\n PyArray_TYPE(arr),\n PyArray_ITEMSIZE(arr),\n PyDataType_ALIGNMENT(PyArray_DESCR(arr)),\n PyArray_FLAGS(arr),\n PyArray_ITEMSIZE(arr));\n}\n\nstatic PyMethodDef f2py_module_methods[] = {\n\n {"call",f2py_rout_wrap_call,METH_VARARGS,doc_f2py_rout_wrap_call},\n {"array_attrs",f2py_rout_wrap_attrs,METH_VARARGS,doc_f2py_rout_wrap_attrs},\n {NULL,NULL}\n};\n\nstatic struct PyModuleDef moduledef = {\n PyModuleDef_HEAD_INIT,\n "test_array_from_pyobj_ext",\n NULL,\n -1,\n f2py_module_methods,\n NULL,\n NULL,\n NULL,\n NULL\n};\n\nPyMODINIT_FUNC PyInit_test_array_from_pyobj_ext(void) {\n PyObject *m,*d, *s;\n m = wrap_module = PyModule_Create(&moduledef);\n Py_SET_TYPE(&PyFortran_Type, &PyType_Type);\n import_array();\n if (PyErr_Occurred())\n Py_FatalError("can't initialize module wrap (failed to import numpy)");\n d = PyModule_GetDict(m);\n s = PyUnicode_FromString("This module 'wrap' is auto-generated with f2py (version:2_1330).\nFunctions:\n"\n " arr = call(type_num,dims,intent,obj)\n"\n ".");\n PyDict_SetItemString(d, "__doc__", s);\n wrap_error = PyErr_NewException ("wrap.error", NULL, NULL);\n Py_DECREF(s);\n\n#define ADDCONST(NAME, CONST) \\n s = PyLong_FromLong(CONST); \\n PyDict_SetItemString(d, NAME, s); \\n Py_DECREF(s)\n\n ADDCONST("F2PY_INTENT_IN", F2PY_INTENT_IN);\n ADDCONST("F2PY_INTENT_INOUT", F2PY_INTENT_INOUT);\n ADDCONST("F2PY_INTENT_OUT", F2PY_INTENT_OUT);\n ADDCONST("F2PY_INTENT_HIDE", F2PY_INTENT_HIDE);\n ADDCONST("F2PY_INTENT_CACHE", F2PY_INTENT_CACHE);\n ADDCONST("F2PY_INTENT_COPY", F2PY_INTENT_COPY);\n ADDCONST("F2PY_INTENT_C", F2PY_INTENT_C);\n ADDCONST("F2PY_OPTIONAL", F2PY_OPTIONAL);\n ADDCONST("F2PY_INTENT_INPLACE", F2PY_INTENT_INPLACE);\n ADDCONST("NPY_BOOL", NPY_BOOL);\n ADDCONST("NPY_BYTE", NPY_BYTE);\n ADDCONST("NPY_UBYTE", NPY_UBYTE);\n ADDCONST("NPY_SHORT", NPY_SHORT);\n ADDCONST("NPY_USHORT", NPY_USHORT);\n ADDCONST("NPY_INT", NPY_INT);\n ADDCONST("NPY_UINT", NPY_UINT);\n ADDCONST("NPY_INTP", NPY_INTP);\n ADDCONST("NPY_UINTP", NPY_UINTP);\n ADDCONST("NPY_LONG", NPY_LONG);\n ADDCONST("NPY_ULONG", NPY_ULONG);\n ADDCONST("NPY_LONGLONG", NPY_LONGLONG);\n ADDCONST("NPY_ULONGLONG", NPY_ULONGLONG);\n ADDCONST("NPY_FLOAT", NPY_FLOAT);\n ADDCONST("NPY_DOUBLE", NPY_DOUBLE);\n ADDCONST("NPY_LONGDOUBLE", NPY_LONGDOUBLE);\n ADDCONST("NPY_CFLOAT", NPY_CFLOAT);\n ADDCONST("NPY_CDOUBLE", NPY_CDOUBLE);\n ADDCONST("NPY_CLONGDOUBLE", NPY_CLONGDOUBLE);\n ADDCONST("NPY_OBJECT", NPY_OBJECT);\n ADDCONST("NPY_STRING", NPY_STRING);\n ADDCONST("NPY_UNICODE", NPY_UNICODE);\n ADDCONST("NPY_VOID", NPY_VOID);\n ADDCONST("NPY_NTYPES_LEGACY", NPY_NTYPES_LEGACY);\n ADDCONST("NPY_NOTYPE", NPY_NOTYPE);\n ADDCONST("NPY_USERDEF", NPY_USERDEF);\n\n ADDCONST("CONTIGUOUS", NPY_ARRAY_C_CONTIGUOUS);\n ADDCONST("FORTRAN", NPY_ARRAY_F_CONTIGUOUS);\n ADDCONST("OWNDATA", NPY_ARRAY_OWNDATA);\n ADDCONST("FORCECAST", NPY_ARRAY_FORCECAST);\n ADDCONST("ENSURECOPY", NPY_ARRAY_ENSURECOPY);\n ADDCONST("ENSUREARRAY", NPY_ARRAY_ENSUREARRAY);\n ADDCONST("ALIGNED", NPY_ARRAY_ALIGNED);\n ADDCONST("WRITEABLE", NPY_ARRAY_WRITEABLE);\n ADDCONST("WRITEBACKIFCOPY", NPY_ARRAY_WRITEBACKIFCOPY);\n\n ADDCONST("BEHAVED", NPY_ARRAY_BEHAVED);\n ADDCONST("BEHAVED_NS", NPY_ARRAY_BEHAVED_NS);\n ADDCONST("CARRAY", NPY_ARRAY_CARRAY);\n ADDCONST("FARRAY", NPY_ARRAY_FARRAY);\n ADDCONST("CARRAY_RO", NPY_ARRAY_CARRAY_RO);\n ADDCONST("FARRAY_RO", NPY_ARRAY_FARRAY_RO);\n ADDCONST("DEFAULT", NPY_ARRAY_DEFAULT);\n ADDCONST("UPDATE_ALL", NPY_ARRAY_UPDATE_ALL);\n\n#undef ADDCONST\n\n if (PyErr_Occurred())\n Py_FatalError("can't initialize module wrap");\n\n#ifdef F2PY_REPORT_ATEXIT\n on_exit(f2py_report_on_exit,(void*)"array_from_pyobj.wrap.call");\n#endif\n\n#if Py_GIL_DISABLED\n // signal whether this module supports running with the GIL disabled\n PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);\n#endif\n\n return m;\n}\n#ifdef __cplusplus\n}\n#endif\n
.venv\Lib\site-packages\numpy\f2py\tests\src\array_from_pyobj\wrapmodule.c
wrapmodule.c
C
7,713
0.95
0.046809
0.102804
node-utils
787
2024-02-28T03:30:23.728365
MIT
true
d69fd5667c1da3b4591c89352f1ac647
dict(real=dict(rk="double"))\n
.venv\Lib\site-packages\numpy\f2py\tests\src\assumed_shape\.f2py_f2cmap
.f2py_f2cmap
Other
30
0.5
0
0
vue-tools
285
2024-09-12T07:17:51.731893
Apache-2.0
true
c04481aabab156da56c40fd22b95dc1e
\nsubroutine sum(x, res)\n implicit none\n real, intent(in) :: x(:)\n real, intent(out) :: res\n\n integer :: i\n\n !print *, "sum: size(x) = ", size(x)\n\n res = 0.0\n\n do i = 1, size(x)\n res = res + x(i)\n enddo\n\nend subroutine sum\n\nfunction fsum(x) result (res)\n implicit none\n real, intent(in) :: x(:)\n real :: res\n\n integer :: i\n\n !print *, "fsum: size(x) = ", size(x)\n\n res = 0.0\n\n do i = 1, size(x)\n res = res + x(i)\n enddo\n\nend function fsum\n
.venv\Lib\site-packages\numpy\f2py\tests\src\assumed_shape\foo_free.f90
foo_free.f90
Other
494
0.85
0.058824
0
python-kit
125
2024-08-19T23:05:12.935760
BSD-3-Clause
true
a69343f6056ba6a4324c66f8b9d9e50a
\nmodule mod\n\ncontains\n\nsubroutine sum(x, res)\n implicit none\n real, intent(in) :: x(:)\n real, intent(out) :: res\n\n integer :: i\n\n !print *, "sum: size(x) = ", size(x)\n\n res = 0.0\n\n do i = 1, size(x)\n res = res + x(i)\n enddo\n\nend subroutine sum\n\nfunction fsum(x) result (res)\n implicit none\n real, intent(in) :: x(:)\n real :: res\n\n integer :: i\n\n !print *, "fsum: size(x) = ", size(x)\n\n res = 0.0\n\n do i = 1, size(x)\n res = res + x(i)\n enddo\n\nend function fsum\n\n\nend module mod\n
.venv\Lib\site-packages\numpy\f2py\tests\src\assumed_shape\foo_mod.f90
foo_mod.f90
Other
540
0.85
0.04878
0
react-lib
606
2024-09-06T14:12:36.757260
BSD-3-Clause
true
0da3b3274b02317e14d693041cbde4ae
subroutine sum_with_use(x, res)\n use precision\n\n implicit none\n\n real(kind=rk), intent(in) :: x(:)\n real(kind=rk), intent(out) :: res\n\n integer :: i\n\n !print *, "size(x) = ", size(x)\n\n res = 0.0\n\n do i = 1, size(x)\n res = res + x(i)\n enddo\n\n end subroutine\n
.venv\Lib\site-packages\numpy\f2py\tests\src\assumed_shape\foo_use.f90
foo_use.f90
Other
288
0.7
0
0
node-utils
353
2024-03-22T15:20:06.669434
MIT
true
fd0decb55db8bd7394602783f2f5e70c
module precision\n integer, parameter :: rk = selected_real_kind(8)\n integer, parameter :: ik = selected_real_kind(4)\nend module\n
.venv\Lib\site-packages\numpy\f2py\tests\src\assumed_shape\precision.f90
precision.f90
Other
134
0.7
0
0
python-kit
560
2024-06-11T17:26:07.654461
MIT
true
7794551eb6822ffb885a9688ce95d98c
SUBROUTINE FOO()\n INTEGER BAR(2, 3)\n\n COMMON /BLOCK/ BAR\n RETURN\n END\n
.venv\Lib\site-packages\numpy\f2py\tests\src\block_docstring\foo.f
foo.f
Other
103
0.5
0
0
vue-tools
314
2024-03-28T19:05:48.409919
MIT
true
33138baf3d4995fbb1ee5a2268dc77fd
subroutine t(fun,a)\n integer a\ncf2py intent(out) a\n external fun\n call fun(a)\n end\n\n subroutine func(a)\ncf2py intent(in,out) a\n integer a\n a = a + 11\n end\n\n subroutine func0(a)\ncf2py intent(out) a\n integer a\n a = 11\n end\n\n subroutine t2(a)\ncf2py intent(callback) fun\n integer a\ncf2py intent(out) a\n external fun\n call fun(a)\n end\n\n subroutine string_callback(callback, a)\n external callback\n double precision callback\n double precision a\n character*1 r\ncf2py intent(out) a\n r = 'r'\n a = callback(r)\n end\n\n subroutine string_callback_array(callback, cu, lencu, a)\n external callback\n integer callback\n integer lencu\n character*8 cu(lencu)\n integer a\ncf2py intent(out) a\n\n a = callback(cu, lencu)\n end\n\n subroutine hidden_callback(a, r)\n external global_f\ncf2py intent(callback, hide) global_f\n integer a, r, global_f\ncf2py intent(out) r\n r = global_f(a)\n end\n\n subroutine hidden_callback2(a, r)\n external global_f\n integer a, r, global_f\ncf2py intent(out) r\n r = global_f(a)\n end\n
.venv\Lib\site-packages\numpy\f2py\tests\src\callback\foo.f
foo.f
Other
1,316
0.7
0
0
awesome-app
737
2024-03-24T05:11:33.539788
GPL-3.0
true
1176123399487c201983701981d88a86
function gh17797(f, y) result(r)\n external f\n integer(8) :: r, f\n integer(8), dimension(:) :: y\n r = f(0)\n r = r + sum(y)\nend function gh17797\n
.venv\Lib\site-packages\numpy\f2py\tests\src\callback\gh17797.f90
gh17797.f90
Other
155
0.85
0.285714
0
vue-tools
992
2024-12-08T22:14:14.061713
GPL-3.0
true
1abb23e4b6ebdbf91d09495df76f69cc
! When gh18335_workaround is defined as an extension,\n ! the issue cannot be reproduced.\n !subroutine gh18335_workaround(f, y)\n ! implicit none\n ! external f\n ! integer(kind=1) :: y(1)\n ! call f(y)\n !end subroutine gh18335_workaround\n\n function gh18335(f) result (r)\n implicit none\n external f\n integer(kind=1) :: y(1), r\n y(1) = 123\n call f(y)\n r = y(1)\n end function gh18335\n
.venv\Lib\site-packages\numpy\f2py\tests\src\callback\gh18335.f90
gh18335.f90
Other
523
0.85
0.117647
0
node-utils
860
2025-01-13T03:30:48.289826
GPL-3.0
true
5f79f4e299da117fc73d19f1a4d9fd56
SUBROUTINE FOO(FUN,R)\n EXTERNAL FUN\n INTEGER I\n REAL*8 R, FUN\nCf2py intent(out) r\n R = 0D0\n DO I=-5,5\n R = R + FUN(I)\n ENDDO\n END\n
.venv\Lib\site-packages\numpy\f2py\tests\src\callback\gh25211.f
gh25211.f
Other
189
0.7
0
0
python-kit
822
2024-10-19T12:40:34.082654
Apache-2.0
true
3a77138b80690bc9be0d25f1f42cff67
python module __user__routines\n interface\n function fun(i) result (r)\n integer :: i\n real*8 :: r\n end function fun\n end interface\nend python module __user__routines\n\npython module callback2\n interface\n subroutine foo(f,r)\n use __user__routines, f=>fun\n external f\n real*8 intent(out) :: r\n end subroutine foo\n end interface\nend python module callback2\n
.venv\Lib\site-packages\numpy\f2py\tests\src\callback\gh25211.pyf
gh25211.pyf
Other
465
0.85
0.111111
0
vue-tools
897
2024-01-08T08:27:39.508594
BSD-3-Clause
true
cba180edf6de31fb469e377eed167957
module utils\n implicit none\n contains\n subroutine my_abort(message)\n implicit none\n character(len=*), intent(in) :: message\n !f2py callstatement PyErr_SetString(PyExc_ValueError, message);f2py_success = 0;\n !f2py callprotoargument char*\n write(0,*) "THIS SHOULD NOT APPEAR"\n stop 1\n end subroutine my_abort\n\n subroutine do_something(message)\n !f2py intent(callback, hide) mypy_abort\n character(len=*), intent(in) :: message\n call mypy_abort(message)\n end subroutine do_something\nend module utils\n
.venv\Lib\site-packages\numpy\f2py\tests\src\callback\gh26681.f90
gh26681.f90
Other
584
0.7
0
0
awesome-app
981
2025-05-05T00:25:26.825566
GPL-3.0
true
f0309ae6cfeec708e60549e0eb9a25aa
python module test_22819\n interface\n subroutine hello()\n end subroutine hello\n end interface\nend python module test_22819\n
.venv\Lib\site-packages\numpy\f2py\tests\src\cli\gh_22819.pyf
gh_22819.pyf
Other
148
0.7
0
0
node-utils
92
2025-03-25T09:40:21.362780
Apache-2.0
true
10a12fb0fde126979312d9463555aed5
SUBROUTINE HI\n PRINT*, "HELLO WORLD"\n END SUBROUTINE\n
.venv\Lib\site-packages\numpy\f2py\tests\src\cli\hi77.f
hi77.f
Other
74
0.5
0
0
node-utils
824
2024-03-14T02:02:11.079757
Apache-2.0
true
ea12d2a40167ca60f2813275c8faa820
function hi()\n print*, "Hello World"\nend function\n
.venv\Lib\site-packages\numpy\f2py\tests\src\cli\hiworld.f90
hiworld.f90
Other
54
0.65
0.666667
0
react-lib
751
2024-09-04T07:33:40.745837
BSD-3-Clause
true
be2bc6d0669262fec7937d7fbb9aa7bc
SUBROUTINE INITCB\n DOUBLE PRECISION LONG\n CHARACTER STRING\n INTEGER OK\n \n COMMON /BLOCK/ LONG, STRING, OK\n LONG = 1.0\n STRING = '2'\n OK = 3\n RETURN\n END\n
.venv\Lib\site-packages\numpy\f2py\tests\src\common\block.f
block.f
Other
235
0.7
0
0
node-utils
118
2024-09-20T06:59:28.119250
Apache-2.0
true
95ef7f58d67a3c8f3c5c1265ef56ff20
module typedefmod\n use iso_fortran_env, only: real32\nend module typedefmod\n\nmodule data\n use typedefmod, only: real32\n implicit none\n real(kind=real32) :: x\n common/test/x\nend module data\n
.venv\Lib\site-packages\numpy\f2py\tests\src\common\gh19161.f90
gh19161.f90
Other
203
0.7
0
0
react-lib
444
2024-08-05T00:25:16.916776
Apache-2.0
true
8179a75d5f8f8e0529e24a01161c9238
module foo\n public\n type, private, bind(c) :: a\n integer :: i\n end type a\n type, bind(c) :: b_\n integer :: j\n end type b_\n public :: b_\n type :: c\n integer :: k\n end type c\nend module foo\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\accesstype.f90
accesstype.f90
Other
221
0.7
0
0
vue-tools
877
2024-03-05T17:40:04.634372
BSD-3-Clause
true
ac0d3ab2ee129daeca40e1fe8429bc2c
subroutine common_with_division\n integer lmu,lb,lub,lpmin\n parameter (lmu=1)\n parameter (lb=20)\nc crackfortran fails to parse this \nc parameter (lub=(lb-1)*lmu+1)\nc crackfortran can successfully parse this though\n parameter (lub=lb*lmu-lmu+1)\n parameter (lpmin=2)\n\nc crackfortran fails to parse this correctly \nc common /mortmp/ ctmp((lub*(lub+1)*(lub+1))/lpmin+1)\n \n common /mortmp/ ctmp(lub/lpmin+1)\n \n return\n end\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\common_with_division.f
common_with_division.f
Other
511
0.7
0
0
react-lib
420
2024-08-11T02:14:07.132264
MIT
true
86e1fad082edf592004eb4cca5dbc778
BLOCK DATA PARAM_INI\n COMMON /MYCOM/ MYDATA\n DATA MYDATA /0/\n END\n SUBROUTINE SUB1\n COMMON /MYCOM/ MYDATA\n MYDATA = MYDATA + 1\n END\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\data_common.f
data_common.f
Other
201
0.7
0
0
node-utils
10
2025-02-09T06:05:57.066633
BSD-3-Clause
true
837010ba3f26a7fd5e03ad68db05d2e6
BLOCK DATA MYBLK\n IMPLICIT DOUBLE PRECISION (A-H,O-Z)\n COMMON /MYCOM/ IVAR1, IVAR2, IVAR3, IVAR4, EVAR5\n DATA IVAR1, IVAR2, IVAR3, IVAR4, EVAR5 /2*3,2*2,0.0D0/\n END\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\data_multiplier.f
data_multiplier.f
Other
202
0.7
0
0
react-lib
853
2024-04-09T23:51:04.362167
MIT
true
d1dddcd2b6752ad64205876be6c77665
! gh-23276\nmodule cmplxdat\n implicit none\n integer :: i, j\n real :: x, y\n real, dimension(2) :: z\n real(kind=8) :: pi\n complex(kind=8), target :: medium_ref_index\n complex(kind=8), target :: ref_index_one, ref_index_two\n complex(kind=8), dimension(2) :: my_array\n real(kind=8), dimension(3) :: my_real_array = (/1.0d0, 2.0d0, 3.0d0/)\n\n data i, j / 2, 3 /\n data x, y / 1.5, 2.0 /\n data z / 3.5, 7.0 /\n data medium_ref_index / (1.d0, 0.d0) /\n data ref_index_one, ref_index_two / (13.0d0, 21.0d0), (-30.0d0, 43.0d0) /\n data my_array / (1.0d0, 2.0d0), (-3.0d0, 4.0d0) /\n data pi / 3.1415926535897932384626433832795028841971693993751058209749445923078164062d0 /\nend module cmplxdat\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\data_stmts.f90
data_stmts.f90
Other
713
0.7
0
0
node-utils
813
2025-07-02T10:37:43.428619
BSD-3-Clause
true
5b7f50cd33daebce1e699e465c77a362
BLOCK DATA PARAM_INI\n COMMON /MYCOM/ MYTAB\n INTEGER MYTAB(3)\n DATA MYTAB/\n * 0, ! 1 and more commenty stuff\n * 4, ! 2\n * 0 /\n END\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\data_with_comments.f
data_with_comments.f
Other
183
0.7
0
0.375
vue-tools
801
2025-05-18T12:57:31.835116
GPL-3.0
true
fda44d5052ac389077a7db308677ec09
module foo\n type bar\n character(len = 4) :: text\n end type bar\n type(bar), parameter :: abar = bar('abar')\nend module foo\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\foo_deps.f90
foo_deps.f90
Other
134
0.7
0
0
vue-tools
650
2024-03-22T18:01:12.005331
GPL-3.0
true
66e2afa1293c280ca72d5fe8dec98a8a
subroutine subb(k)\n real(8), intent(inout) :: k(:)\n k=k+1\n endsubroutine\n\n subroutine subc(w,k)\n real(8), intent(in) :: w(:)\n real(8), intent(out) :: k(size(w))\n k=w+1\n endsubroutine\n\n function t0(value)\n character value\n character t0\n t0 = value\n endfunction\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\gh15035.f
gh15035.f
Other
391
0.85
0.0625
0
react-lib
806
2023-07-22T21:38:06.115927
GPL-3.0
true
0b0c498ac445a7eb4f2dd5a93f2c7749
integer(8) function external_as_statement(fcn)\n implicit none\n external fcn\n integer(8) :: fcn\n external_as_statement = fcn(0)\n end\n\n integer(8) function external_as_attribute(fcn)\n implicit none\n integer(8), external :: fcn\n external_as_attribute = fcn(0)\n end\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\gh17859.f
gh17859.f
Other
352
0.85
0.166667
0
react-lib
258
2024-09-23T04:21:14.278942
Apache-2.0
true
1ed51b057e2ba7406d7d42ccc1ecefcf
python module iri16py ! in\n interface ! in :iri16py\n block data ! in :iri16py:iridreg_modified.for\n COMMON /fircom/ eden,tabhe,tabla,tabmo,tabza,tabfl\n end block data \n end interface \nend python module iri16py\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\gh22648.pyf
gh22648.pyf
Other
248
0.7
0.142857
0
python-kit
535
2023-12-03T01:30:02.791175
MIT
true
feb0071773cd892b8fff674ee2780a7c
SUBROUTINE EXAMPLE( )\n IF( .TRUE. ) THEN\n CALL DO_SOMETHING()\n END IF ! ** .TRUE. **\n END\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\gh23533.f
gh23533.f
Other
131
0.7
0
0
node-utils
212
2023-09-06T17:57:49.293473
GPL-3.0
true
e346e5a1dbeb9f7abb4ec665375f059b
integer function intproduct(a, b) result(res)\n integer, intent(in) :: a, b\n res = a*b\nend function\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\gh23598.f90
gh23598.f90
Other
105
0.85
0.5
0
react-lib
713
2024-03-29T02:03:55.928610
MIT
true
a87973d48a037bbdc2e2f76aec82d351
module test_bug\n implicit none\n private\n public :: intproduct\n\ncontains\n integer function intproduct(a, b) result(res)\n integer, intent(in) :: a, b\n res = a*b\n end function\nend module\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\gh23598Warn.f90
gh23598Warn.f90
Other
216
0.85
0.181818
0
node-utils
235
2023-12-31T18:07:35.762724
GPL-3.0
true
739654d0fd37ed065c53593a30608697
module gh23879\n implicit none\n private\n public :: foo\n\n contains\n\n subroutine foo(a, b)\n integer, intent(in) :: a\n integer, intent(out) :: b\n b = a\n call bar(b)\n end subroutine\n\n subroutine bar(x)\n integer, intent(inout) :: x\n x = 2*x\n end subroutine\n\n end module gh23879\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\gh23879.f90
gh23879.f90
Other
352
0.7
0
0
vue-tools
513
2025-04-08T17:50:24.402927
MIT
true
4530e88ba6bfb2db05c2db89d10dcd87
module utils\n implicit none\n contains\n subroutine my_abort(message)\n implicit none\n character(len=*), intent(in) :: message\n !f2py callstatement PyErr_SetString(PyExc_ValueError, message);f2py_success = 0;\n !f2py callprotoargument char*\n write(0,*) "THIS SHOULD NOT APPEAR"\n stop 1\n end subroutine my_abort\nend module utils\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\gh27697.f90
gh27697.f90
Other
376
0.7
0
0
vue-tools
986
2023-11-09T18:55:24.531202
Apache-2.0
true
ba93961467067fff54f7e6b6a67f563d
subroutine gh2848( &\n ! first 2 parameters\n par1, par2,&\n ! last 2 parameters\n par3, par4)\n\n integer, intent(in) :: par1, par2\n integer, intent(out) :: par3, par4\n\n par3 = par1\n par4 = par2\n\n end subroutine gh2848\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\gh2848.f90
gh2848.f90
Other
295
0.7
0
0
react-lib
21
2025-01-06T12:39:07.624144
Apache-2.0
true
87b969a23de007f2e5e1c8396b669089
module foo\n type bar\n character(len = 32) :: item\n end type bar\n interface operator(.item.)\n module procedure item_int, item_real\n end interface operator(.item.)\n interface operator(==)\n module procedure items_are_equal\n end interface operator(==)\n interface assignment(=)\n module procedure get_int, get_real\n end interface assignment(=)\ncontains\n function item_int(val) result(elem)\n integer, intent(in) :: val\n type(bar) :: elem\n\n write(elem%item, "(I32)") val\n end function item_int\n\n function item_real(val) result(elem)\n real, intent(in) :: val\n type(bar) :: elem\n\n write(elem%item, "(1PE32.12)") val\n end function item_real\n\n function items_are_equal(val1, val2) result(equal)\n type(bar), intent(in) :: val1, val2\n logical :: equal\n\n equal = (val1%item == val2%item)\n end function items_are_equal\n\n subroutine get_real(rval, item)\n real, intent(out) :: rval\n type(bar), intent(in) :: item\n\n read(item%item, *) rval\n end subroutine get_real\n\n subroutine get_int(rval, item)\n integer, intent(out) :: rval\n type(bar), intent(in) :: item\n\n read(item%item, *) rval\n end subroutine get_int\nend module foo\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\operators.f90
operators.f90
Other
1,233
0.85
0.122449
0
react-lib
234
2023-10-23T10:56:33.105606
MIT
true
624409b8666b2f12a3567dac8851433c
module foo\n private\n integer :: a\n public :: setA\n integer :: b\ncontains\n subroutine setA(v)\n integer, intent(in) :: v\n a = v\n end subroutine setA\nend module foo\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\privatemod.f90
privatemod.f90
Other
185
0.7
0
0
awesome-app
208
2025-06-02T12:33:05.539897
MIT
true
a1e7c4a56c18c206d932564ae0634543
module foo\n public\n integer, private :: a\n public :: setA\ncontains\n subroutine setA(v)\n integer, intent(in) :: v\n a = v\n end subroutine setA\nend module foo\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\publicmod.f90
publicmod.f90
Other
177
0.7
0
0
node-utils
430
2024-11-28T15:04:09.696142
Apache-2.0
true
3c8290983742684ffccf148cf7d9e769
module foo\n public\n integer, private :: a\n integer :: b\ncontains\n subroutine setA(v)\n integer, intent(in) :: v\n a = v\n end subroutine setA\nend module foo\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\pubprivmod.f90
pubprivmod.f90
Other
175
0.7
0
0
react-lib
760
2024-07-31T04:00:04.853489
BSD-3-Clause
true
66725a0921c571256633befdd0e51241
subroutine foo(x)\n real(8), intent(in) :: x\n ! Écrit à l'écran la valeur de x\nend subroutine\n
.venv\Lib\site-packages\numpy\f2py\tests\src\crackfortran\unicode_comment.f90
unicode_comment.f90
Other
102
0.5
0
0
react-lib
502
2023-08-08T11:37:27.773273
BSD-3-Clause
true
7a62e12f054da463c0dcf5a53a0df35f
dict(real=dict(real32='float', real64='double'), integer=dict(int64='long_long'))\n
.venv\Lib\site-packages\numpy\f2py\tests\src\f2cmap\.f2py_f2cmap
.f2py_f2cmap
Other
83
0.5
0
0
python-kit
139
2023-09-09T14:59:19.105823
Apache-2.0
true
6654f233e7cb583e6f858b0a4358034b
subroutine func1(n, x, res)\n use, intrinsic :: iso_fortran_env, only: int64, real64\n implicit none\n integer(int64), intent(in) :: n\n real(real64), intent(in) :: x(n)\n real(real64), intent(out) :: res\n!f2py intent(hide) :: n\n res = sum(x)\n end\n
.venv\Lib\site-packages\numpy\f2py\tests\src\f2cmap\isoFortranEnvMap.f90
isoFortranEnvMap.f90
Other
307
0.7
0
0
react-lib
596
2025-06-20T11:54:48.324120
MIT
true
1bc31127c6a28f8275f29e5a30e2c3d0
module coddity\n use iso_c_binding, only: c_double, c_int, c_int64_t\n implicit none\n contains\n subroutine c_add(a, b, c) bind(c, name="c_add")\n real(c_double), intent(in) :: a, b\n real(c_double), intent(out) :: c\n c = a + b\n end subroutine c_add\n ! gh-9693\n function wat(x, y) result(z) bind(c)\n integer(c_int), intent(in) :: x, y\n integer(c_int) :: z\n\n z = x + 7\n end function wat\n ! gh-25207\n subroutine c_add_int64(a, b, c) bind(c)\n integer(c_int64_t), intent(in) :: a, b\n integer(c_int64_t), intent(out) :: c\n c = a + b\n end subroutine c_add_int64\n ! gh-25207\n subroutine add_arr(A, B, C)\n integer(c_int64_t), intent(in) :: A(3)\n integer(c_int64_t), intent(in) :: B(3)\n integer(c_int64_t), intent(out) :: C(3)\n integer :: j\n\n do j = 1, 3\n C(j) = A(j)+B(j)\n end do\n end subroutine\n end module coddity\n
.venv\Lib\site-packages\numpy\f2py\tests\src\isocintrin\isoCtests.f90
isoCtests.f90
Other
1,032
0.85
0.058824
0
python-kit
267
2024-12-05T13:49:46.892810
GPL-3.0
true
d2e56f8bdbc73d46941de6f19e08c753
\n\nsubroutine selectedrealkind(p, r, res)\n implicit none\n \n integer, intent(in) :: p, r\n !f2py integer :: r=0\n integer, intent(out) :: res\n res = selected_real_kind(p, r)\n\nend subroutine\n\nsubroutine selectedintkind(p, res)\n implicit none\n\n integer, intent(in) :: p\n integer, intent(out) :: res\n res = selected_int_kind(p)\n\nend subroutine\n
.venv\Lib\site-packages\numpy\f2py\tests\src\kind\foo.f90
foo.f90
Other
367
0.7
0
0
react-lib
835
2024-09-21T04:26:10.082348
MIT
true
8b853660a733c8c56363d50285276941
subroutine bar11(a)\ncf2py intent(out) a\n integer a\n a = 11\n end\n
.venv\Lib\site-packages\numpy\f2py\tests\src\mixed\foo.f
foo.f
Other
90
0.5
0
0
react-lib
268
2025-03-03T04:03:01.027674
Apache-2.0
true
e19fbb5b38d296a8d72b8bbed1dbe7e7