Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step60/zero/11.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step60/zero/11.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
- ckpts/universal/global_step60/zero/14.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step60/zero/14.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
- ckpts/universal/global_step60/zero/17.post_attention_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step60/zero/4.post_attention_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step60/zero/4.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step60/zero/4.post_attention_layernorm.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/numpy/f2py/__init__.py +194 -0
- venv/lib/python3.10/site-packages/numpy/f2py/__init__.pyi +42 -0
- venv/lib/python3.10/site-packages/numpy/f2py/__main__.py +5 -0
- venv/lib/python3.10/site-packages/numpy/f2py/__version__.py +1 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_backends/__init__.py +9 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/_backend.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/_distutils.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/_meson.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_backends/_backend.py +46 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_backends/_distutils.py +75 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_backends/_meson.py +205 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_backends/meson.build.template +54 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_isocbind.py +62 -0
- venv/lib/python3.10/site-packages/numpy/f2py/_src_pyf.py +239 -0
- venv/lib/python3.10/site-packages/numpy/f2py/auxfuncs.py +988 -0
- venv/lib/python3.10/site-packages/numpy/f2py/capi_maps.py +819 -0
- venv/lib/python3.10/site-packages/numpy/f2py/cb_rules.py +644 -0
- venv/lib/python3.10/site-packages/numpy/f2py/cfuncs.py +1536 -0
- venv/lib/python3.10/site-packages/numpy/f2py/common_rules.py +146 -0
- venv/lib/python3.10/site-packages/numpy/f2py/crackfortran.py +0 -0
- venv/lib/python3.10/site-packages/numpy/f2py/diagnose.py +154 -0
- venv/lib/python3.10/site-packages/numpy/f2py/f2py2e.py +768 -0
- venv/lib/python3.10/site-packages/numpy/f2py/f90mod_rules.py +264 -0
- venv/lib/python3.10/site-packages/numpy/f2py/func2subr.py +323 -0
- venv/lib/python3.10/site-packages/numpy/f2py/rules.py +1568 -0
- venv/lib/python3.10/site-packages/numpy/f2py/setup.cfg +3 -0
- venv/lib/python3.10/site-packages/numpy/f2py/setup.py +74 -0
- venv/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.c +1423 -0
- venv/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.h +173 -0
- venv/lib/python3.10/site-packages/numpy/f2py/symbolic.py +1517 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/test_abstract_interface.py +25 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/test_array_from_pyobj.py +686 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/test_assumed_shape.py +49 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/test_block_docstring.py +17 -0
- venv/lib/python3.10/site-packages/numpy/f2py/tests/test_callback.py +243 -0
ckpts/universal/global_step60/zero/11.mlp.dense_4h_to_h.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:99a9b8f17bddbd04cf1feea10887beab07ac7c898b801e1356a578de57655bc3
|
3 |
+
size 33555627
|
ckpts/universal/global_step60/zero/11.mlp.dense_4h_to_h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:22f6a1b974ff327748f2181a5ec65649f99fd639edc3738b72dd82b2853cac8c
|
3 |
+
size 33555533
|
ckpts/universal/global_step60/zero/14.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:86a7ad8b22be2381c48aab135903df8a101b90a2114d890dc4fbdbf2e47d3b5c
|
3 |
+
size 33555627
|
ckpts/universal/global_step60/zero/14.mlp.dense_h_to_4h_swiglu.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a47c6a2ae99c85980c8cec1084022489fe521047b8979c41065b89c620637cec
|
3 |
+
size 33555533
|
ckpts/universal/global_step60/zero/17.post_attention_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6971754b8ccc71acdf6b144b95e3b20e678c24fdbfcf76bcff9318b733212361
|
3 |
+
size 9293
|
ckpts/universal/global_step60/zero/4.post_attention_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d06bbbca46d1d15bfe3723a1d4945804c7c4787dcb76bf75dbbb345c2d9e3fed
|
3 |
+
size 9372
|
ckpts/universal/global_step60/zero/4.post_attention_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:39a3adef985cc4688beaefc56a905ee69d196a752d806127ccaa6a045e27e274
|
3 |
+
size 9387
|
ckpts/universal/global_step60/zero/4.post_attention_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b0c1f9143d8bf3298026c06a9dfcda5d507858d6ccbbfcb15380120406e83be3
|
3 |
+
size 9293
|
venv/lib/python3.10/site-packages/numpy/f2py/__init__.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""Fortran to Python Interface Generator.
|
3 |
+
|
4 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
5 |
+
Copyright 2011 -- present NumPy Developers.
|
6 |
+
Permission to use, modify, and distribute this software is given under the terms
|
7 |
+
of the NumPy License.
|
8 |
+
|
9 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
10 |
+
"""
|
11 |
+
__all__ = ['run_main', 'compile', 'get_include']
|
12 |
+
|
13 |
+
import sys
|
14 |
+
import subprocess
|
15 |
+
import os
|
16 |
+
import warnings
|
17 |
+
|
18 |
+
from numpy.exceptions import VisibleDeprecationWarning
|
19 |
+
from . import f2py2e
|
20 |
+
from . import diagnose
|
21 |
+
|
22 |
+
run_main = f2py2e.run_main
|
23 |
+
main = f2py2e.main
|
24 |
+
|
25 |
+
|
26 |
+
def compile(source,
|
27 |
+
modulename='untitled',
|
28 |
+
extra_args='',
|
29 |
+
verbose=True,
|
30 |
+
source_fn=None,
|
31 |
+
extension='.f',
|
32 |
+
full_output=False
|
33 |
+
):
|
34 |
+
"""
|
35 |
+
Build extension module from a Fortran 77 source string with f2py.
|
36 |
+
|
37 |
+
Parameters
|
38 |
+
----------
|
39 |
+
source : str or bytes
|
40 |
+
Fortran source of module / subroutine to compile
|
41 |
+
|
42 |
+
.. versionchanged:: 1.16.0
|
43 |
+
Accept str as well as bytes
|
44 |
+
|
45 |
+
modulename : str, optional
|
46 |
+
The name of the compiled python module
|
47 |
+
extra_args : str or list, optional
|
48 |
+
Additional parameters passed to f2py
|
49 |
+
|
50 |
+
.. versionchanged:: 1.16.0
|
51 |
+
A list of args may also be provided.
|
52 |
+
|
53 |
+
verbose : bool, optional
|
54 |
+
Print f2py output to screen
|
55 |
+
source_fn : str, optional
|
56 |
+
Name of the file where the fortran source is written.
|
57 |
+
The default is to use a temporary file with the extension
|
58 |
+
provided by the ``extension`` parameter
|
59 |
+
extension : ``{'.f', '.f90'}``, optional
|
60 |
+
Filename extension if `source_fn` is not provided.
|
61 |
+
The extension tells which fortran standard is used.
|
62 |
+
The default is ``.f``, which implies F77 standard.
|
63 |
+
|
64 |
+
.. versionadded:: 1.11.0
|
65 |
+
|
66 |
+
full_output : bool, optional
|
67 |
+
If True, return a `subprocess.CompletedProcess` containing
|
68 |
+
the stdout and stderr of the compile process, instead of just
|
69 |
+
the status code.
|
70 |
+
|
71 |
+
.. versionadded:: 1.20.0
|
72 |
+
|
73 |
+
|
74 |
+
Returns
|
75 |
+
-------
|
76 |
+
result : int or `subprocess.CompletedProcess`
|
77 |
+
0 on success, or a `subprocess.CompletedProcess` if
|
78 |
+
``full_output=True``
|
79 |
+
|
80 |
+
Examples
|
81 |
+
--------
|
82 |
+
.. literalinclude:: ../../source/f2py/code/results/compile_session.dat
|
83 |
+
:language: python
|
84 |
+
|
85 |
+
"""
|
86 |
+
import tempfile
|
87 |
+
import shlex
|
88 |
+
|
89 |
+
if source_fn is None:
|
90 |
+
f, fname = tempfile.mkstemp(suffix=extension)
|
91 |
+
# f is a file descriptor so need to close it
|
92 |
+
# carefully -- not with .close() directly
|
93 |
+
os.close(f)
|
94 |
+
else:
|
95 |
+
fname = source_fn
|
96 |
+
|
97 |
+
if not isinstance(source, str):
|
98 |
+
source = str(source, 'utf-8')
|
99 |
+
try:
|
100 |
+
with open(fname, 'w') as f:
|
101 |
+
f.write(source)
|
102 |
+
|
103 |
+
args = ['-c', '-m', modulename, f.name]
|
104 |
+
|
105 |
+
if isinstance(extra_args, str):
|
106 |
+
is_posix = (os.name == 'posix')
|
107 |
+
extra_args = shlex.split(extra_args, posix=is_posix)
|
108 |
+
|
109 |
+
args.extend(extra_args)
|
110 |
+
|
111 |
+
c = [sys.executable,
|
112 |
+
'-c',
|
113 |
+
'import numpy.f2py as f2py2e;f2py2e.main()'] + args
|
114 |
+
try:
|
115 |
+
cp = subprocess.run(c, capture_output=True)
|
116 |
+
except OSError:
|
117 |
+
# preserve historic status code used by exec_command()
|
118 |
+
cp = subprocess.CompletedProcess(c, 127, stdout=b'', stderr=b'')
|
119 |
+
else:
|
120 |
+
if verbose:
|
121 |
+
print(cp.stdout.decode())
|
122 |
+
finally:
|
123 |
+
if source_fn is None:
|
124 |
+
os.remove(fname)
|
125 |
+
|
126 |
+
if full_output:
|
127 |
+
return cp
|
128 |
+
else:
|
129 |
+
return cp.returncode
|
130 |
+
|
131 |
+
|
132 |
+
def get_include():
|
133 |
+
"""
|
134 |
+
Return the directory that contains the ``fortranobject.c`` and ``.h`` files.
|
135 |
+
|
136 |
+
.. note::
|
137 |
+
|
138 |
+
This function is not needed when building an extension with
|
139 |
+
`numpy.distutils` directly from ``.f`` and/or ``.pyf`` files
|
140 |
+
in one go.
|
141 |
+
|
142 |
+
Python extension modules built with f2py-generated code need to use
|
143 |
+
``fortranobject.c`` as a source file, and include the ``fortranobject.h``
|
144 |
+
header. This function can be used to obtain the directory containing
|
145 |
+
both of these files.
|
146 |
+
|
147 |
+
Returns
|
148 |
+
-------
|
149 |
+
include_path : str
|
150 |
+
Absolute path to the directory containing ``fortranobject.c`` and
|
151 |
+
``fortranobject.h``.
|
152 |
+
|
153 |
+
Notes
|
154 |
+
-----
|
155 |
+
.. versionadded:: 1.21.1
|
156 |
+
|
157 |
+
Unless the build system you are using has specific support for f2py,
|
158 |
+
building a Python extension using a ``.pyf`` signature file is a two-step
|
159 |
+
process. For a module ``mymod``:
|
160 |
+
|
161 |
+
* Step 1: run ``python -m numpy.f2py mymod.pyf --quiet``. This
|
162 |
+
generates ``_mymodmodule.c`` and (if needed)
|
163 |
+
``_fblas-f2pywrappers.f`` files next to ``mymod.pyf``.
|
164 |
+
* Step 2: build your Python extension module. This requires the
|
165 |
+
following source files:
|
166 |
+
|
167 |
+
* ``_mymodmodule.c``
|
168 |
+
* ``_mymod-f2pywrappers.f`` (if it was generated in Step 1)
|
169 |
+
* ``fortranobject.c``
|
170 |
+
|
171 |
+
See Also
|
172 |
+
--------
|
173 |
+
numpy.get_include : function that returns the numpy include directory
|
174 |
+
|
175 |
+
"""
|
176 |
+
return os.path.join(os.path.dirname(__file__), 'src')
|
177 |
+
|
178 |
+
|
179 |
+
def __getattr__(attr):
|
180 |
+
|
181 |
+
# Avoid importing things that aren't needed for building
|
182 |
+
# which might import the main numpy module
|
183 |
+
if attr == "test":
|
184 |
+
from numpy._pytesttester import PytestTester
|
185 |
+
test = PytestTester(__name__)
|
186 |
+
return test
|
187 |
+
|
188 |
+
else:
|
189 |
+
raise AttributeError("module {!r} has no attribute "
|
190 |
+
"{!r}".format(__name__, attr))
|
191 |
+
|
192 |
+
|
193 |
+
def __dir__():
|
194 |
+
return list(globals().keys() | {"test"})
|
venv/lib/python3.10/site-packages/numpy/f2py/__init__.pyi
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import subprocess
|
3 |
+
from collections.abc import Iterable
|
4 |
+
from typing import Literal as L, Any, overload, TypedDict
|
5 |
+
|
6 |
+
from numpy._pytesttester import PytestTester
|
7 |
+
|
8 |
+
class _F2PyDictBase(TypedDict):
|
9 |
+
csrc: list[str]
|
10 |
+
h: list[str]
|
11 |
+
|
12 |
+
class _F2PyDict(_F2PyDictBase, total=False):
|
13 |
+
fsrc: list[str]
|
14 |
+
ltx: list[str]
|
15 |
+
|
16 |
+
__all__: list[str]
|
17 |
+
test: PytestTester
|
18 |
+
|
19 |
+
def run_main(comline_list: Iterable[str]) -> dict[str, _F2PyDict]: ...
|
20 |
+
|
21 |
+
@overload
|
22 |
+
def compile( # type: ignore[misc]
|
23 |
+
source: str | bytes,
|
24 |
+
modulename: str = ...,
|
25 |
+
extra_args: str | list[str] = ...,
|
26 |
+
verbose: bool = ...,
|
27 |
+
source_fn: None | str | bytes | os.PathLike[Any] = ...,
|
28 |
+
extension: L[".f", ".f90"] = ...,
|
29 |
+
full_output: L[False] = ...,
|
30 |
+
) -> int: ...
|
31 |
+
@overload
|
32 |
+
def compile(
|
33 |
+
source: str | bytes,
|
34 |
+
modulename: str = ...,
|
35 |
+
extra_args: str | list[str] = ...,
|
36 |
+
verbose: bool = ...,
|
37 |
+
source_fn: None | str | bytes | os.PathLike[Any] = ...,
|
38 |
+
extension: L[".f", ".f90"] = ...,
|
39 |
+
full_output: L[True] = ...,
|
40 |
+
) -> subprocess.CompletedProcess[bytes]: ...
|
41 |
+
|
42 |
+
def get_include() -> str: ...
|
venv/lib/python3.10/site-packages/numpy/f2py/__main__.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# See:
|
2 |
+
# https://web.archive.org/web/20140822061353/http://cens.ioc.ee/projects/f2py2e
|
3 |
+
from numpy.f2py.f2py2e import main
|
4 |
+
|
5 |
+
main()
|
venv/lib/python3.10/site-packages/numpy/f2py/__version__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from numpy.version import version
|
venv/lib/python3.10/site-packages/numpy/f2py/_backends/__init__.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
def f2py_build_generator(name):
|
2 |
+
if name == "meson":
|
3 |
+
from ._meson import MesonBackend
|
4 |
+
return MesonBackend
|
5 |
+
elif name == "distutils":
|
6 |
+
from ._distutils import DistutilsBackend
|
7 |
+
return DistutilsBackend
|
8 |
+
else:
|
9 |
+
raise ValueError(f"Unknown backend: {name}")
|
venv/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (498 Bytes). View file
|
|
venv/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/_backend.cpython-310.pyc
ADDED
Binary file (1.15 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/_distutils.cpython-310.pyc
ADDED
Binary file (2.24 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/_meson.cpython-310.pyc
ADDED
Binary file (7.45 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/f2py/_backends/_backend.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from abc import ABC, abstractmethod
|
4 |
+
|
5 |
+
|
6 |
+
class Backend(ABC):
|
7 |
+
def __init__(
|
8 |
+
self,
|
9 |
+
modulename,
|
10 |
+
sources,
|
11 |
+
extra_objects,
|
12 |
+
build_dir,
|
13 |
+
include_dirs,
|
14 |
+
library_dirs,
|
15 |
+
libraries,
|
16 |
+
define_macros,
|
17 |
+
undef_macros,
|
18 |
+
f2py_flags,
|
19 |
+
sysinfo_flags,
|
20 |
+
fc_flags,
|
21 |
+
flib_flags,
|
22 |
+
setup_flags,
|
23 |
+
remove_build_dir,
|
24 |
+
extra_dat,
|
25 |
+
):
|
26 |
+
self.modulename = modulename
|
27 |
+
self.sources = sources
|
28 |
+
self.extra_objects = extra_objects
|
29 |
+
self.build_dir = build_dir
|
30 |
+
self.include_dirs = include_dirs
|
31 |
+
self.library_dirs = library_dirs
|
32 |
+
self.libraries = libraries
|
33 |
+
self.define_macros = define_macros
|
34 |
+
self.undef_macros = undef_macros
|
35 |
+
self.f2py_flags = f2py_flags
|
36 |
+
self.sysinfo_flags = sysinfo_flags
|
37 |
+
self.fc_flags = fc_flags
|
38 |
+
self.flib_flags = flib_flags
|
39 |
+
self.setup_flags = setup_flags
|
40 |
+
self.remove_build_dir = remove_build_dir
|
41 |
+
self.extra_dat = extra_dat
|
42 |
+
|
43 |
+
@abstractmethod
|
44 |
+
def compile(self) -> None:
|
45 |
+
"""Compile the wrapper."""
|
46 |
+
pass
|
venv/lib/python3.10/site-packages/numpy/f2py/_backends/_distutils.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from ._backend import Backend
|
2 |
+
|
3 |
+
from numpy.distutils.core import setup, Extension
|
4 |
+
from numpy.distutils.system_info import get_info
|
5 |
+
from numpy.distutils.misc_util import dict_append
|
6 |
+
from numpy.exceptions import VisibleDeprecationWarning
|
7 |
+
import os
|
8 |
+
import sys
|
9 |
+
import shutil
|
10 |
+
import warnings
|
11 |
+
|
12 |
+
|
13 |
+
class DistutilsBackend(Backend):
|
14 |
+
def __init__(sef, *args, **kwargs):
|
15 |
+
warnings.warn(
|
16 |
+
"distutils has been deprecated since NumPy 1.26.x"
|
17 |
+
"Use the Meson backend instead, or generate wrappers"
|
18 |
+
"without -c and use a custom build script",
|
19 |
+
VisibleDeprecationWarning,
|
20 |
+
stacklevel=2,
|
21 |
+
)
|
22 |
+
super().__init__(*args, **kwargs)
|
23 |
+
|
24 |
+
def compile(self):
|
25 |
+
num_info = {}
|
26 |
+
if num_info:
|
27 |
+
self.include_dirs.extend(num_info.get("include_dirs", []))
|
28 |
+
ext_args = {
|
29 |
+
"name": self.modulename,
|
30 |
+
"sources": self.sources,
|
31 |
+
"include_dirs": self.include_dirs,
|
32 |
+
"library_dirs": self.library_dirs,
|
33 |
+
"libraries": self.libraries,
|
34 |
+
"define_macros": self.define_macros,
|
35 |
+
"undef_macros": self.undef_macros,
|
36 |
+
"extra_objects": self.extra_objects,
|
37 |
+
"f2py_options": self.f2py_flags,
|
38 |
+
}
|
39 |
+
|
40 |
+
if self.sysinfo_flags:
|
41 |
+
for n in self.sysinfo_flags:
|
42 |
+
i = get_info(n)
|
43 |
+
if not i:
|
44 |
+
print(
|
45 |
+
f"No {repr(n)} resources found"
|
46 |
+
"in system (try `f2py --help-link`)"
|
47 |
+
)
|
48 |
+
dict_append(ext_args, **i)
|
49 |
+
|
50 |
+
ext = Extension(**ext_args)
|
51 |
+
|
52 |
+
sys.argv = [sys.argv[0]] + self.setup_flags
|
53 |
+
sys.argv.extend(
|
54 |
+
[
|
55 |
+
"build",
|
56 |
+
"--build-temp",
|
57 |
+
self.build_dir,
|
58 |
+
"--build-base",
|
59 |
+
self.build_dir,
|
60 |
+
"--build-platlib",
|
61 |
+
".",
|
62 |
+
"--disable-optimization",
|
63 |
+
]
|
64 |
+
)
|
65 |
+
|
66 |
+
if self.fc_flags:
|
67 |
+
sys.argv.extend(["config_fc"] + self.fc_flags)
|
68 |
+
if self.flib_flags:
|
69 |
+
sys.argv.extend(["build_ext"] + self.flib_flags)
|
70 |
+
|
71 |
+
setup(ext_modules=[ext])
|
72 |
+
|
73 |
+
if self.remove_build_dir and os.path.exists(self.build_dir):
|
74 |
+
print(f"Removing build directory {self.build_dir}")
|
75 |
+
shutil.rmtree(self.build_dir)
|
venv/lib/python3.10/site-packages/numpy/f2py/_backends/_meson.py
ADDED
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import os
|
4 |
+
import errno
|
5 |
+
import shutil
|
6 |
+
import subprocess
|
7 |
+
import sys
|
8 |
+
from pathlib import Path
|
9 |
+
|
10 |
+
from ._backend import Backend
|
11 |
+
from string import Template
|
12 |
+
from itertools import chain
|
13 |
+
|
14 |
+
import warnings
|
15 |
+
|
16 |
+
|
17 |
+
class MesonTemplate:
|
18 |
+
"""Template meson build file generation class."""
|
19 |
+
|
20 |
+
def __init__(
|
21 |
+
self,
|
22 |
+
modulename: str,
|
23 |
+
sources: list[Path],
|
24 |
+
deps: list[str],
|
25 |
+
libraries: list[str],
|
26 |
+
library_dirs: list[Path],
|
27 |
+
include_dirs: list[Path],
|
28 |
+
object_files: list[Path],
|
29 |
+
linker_args: list[str],
|
30 |
+
c_args: list[str],
|
31 |
+
build_type: str,
|
32 |
+
python_exe: str,
|
33 |
+
):
|
34 |
+
self.modulename = modulename
|
35 |
+
self.build_template_path = (
|
36 |
+
Path(__file__).parent.absolute() / "meson.build.template"
|
37 |
+
)
|
38 |
+
self.sources = sources
|
39 |
+
self.deps = deps
|
40 |
+
self.libraries = libraries
|
41 |
+
self.library_dirs = library_dirs
|
42 |
+
if include_dirs is not None:
|
43 |
+
self.include_dirs = include_dirs
|
44 |
+
else:
|
45 |
+
self.include_dirs = []
|
46 |
+
self.substitutions = {}
|
47 |
+
self.objects = object_files
|
48 |
+
self.pipeline = [
|
49 |
+
self.initialize_template,
|
50 |
+
self.sources_substitution,
|
51 |
+
self.deps_substitution,
|
52 |
+
self.include_substitution,
|
53 |
+
self.libraries_substitution,
|
54 |
+
]
|
55 |
+
self.build_type = build_type
|
56 |
+
self.python_exe = python_exe
|
57 |
+
|
58 |
+
def meson_build_template(self) -> str:
|
59 |
+
if not self.build_template_path.is_file():
|
60 |
+
raise FileNotFoundError(
|
61 |
+
errno.ENOENT,
|
62 |
+
"Meson build template"
|
63 |
+
f" {self.build_template_path.absolute()}"
|
64 |
+
" does not exist.",
|
65 |
+
)
|
66 |
+
return self.build_template_path.read_text()
|
67 |
+
|
68 |
+
def initialize_template(self) -> None:
|
69 |
+
self.substitutions["modulename"] = self.modulename
|
70 |
+
self.substitutions["buildtype"] = self.build_type
|
71 |
+
self.substitutions["python"] = self.python_exe
|
72 |
+
|
73 |
+
def sources_substitution(self) -> None:
|
74 |
+
indent = " " * 21
|
75 |
+
self.substitutions["source_list"] = f",\n{indent}".join(
|
76 |
+
[f"{indent}'{source}'" for source in self.sources]
|
77 |
+
)
|
78 |
+
|
79 |
+
def deps_substitution(self) -> None:
|
80 |
+
indent = " " * 21
|
81 |
+
self.substitutions["dep_list"] = f",\n{indent}".join(
|
82 |
+
[f"{indent}dependency('{dep}')" for dep in self.deps]
|
83 |
+
)
|
84 |
+
|
85 |
+
def libraries_substitution(self) -> None:
|
86 |
+
self.substitutions["lib_dir_declarations"] = "\n".join(
|
87 |
+
[
|
88 |
+
f"lib_dir_{i} = declare_dependency(link_args : ['-L{lib_dir}'])"
|
89 |
+
for i, lib_dir in enumerate(self.library_dirs)
|
90 |
+
]
|
91 |
+
)
|
92 |
+
|
93 |
+
self.substitutions["lib_declarations"] = "\n".join(
|
94 |
+
[
|
95 |
+
f"{lib} = declare_dependency(link_args : ['-l{lib}'])"
|
96 |
+
for lib in self.libraries
|
97 |
+
]
|
98 |
+
)
|
99 |
+
|
100 |
+
indent = " " * 21
|
101 |
+
self.substitutions["lib_list"] = f"\n{indent}".join(
|
102 |
+
[f"{indent}{lib}," for lib in self.libraries]
|
103 |
+
)
|
104 |
+
self.substitutions["lib_dir_list"] = f"\n{indent}".join(
|
105 |
+
[f"{indent}lib_dir_{i}," for i in range(len(self.library_dirs))]
|
106 |
+
)
|
107 |
+
|
108 |
+
def include_substitution(self) -> None:
|
109 |
+
indent = " " * 21
|
110 |
+
self.substitutions["inc_list"] = f",\n{indent}".join(
|
111 |
+
[f"{indent}'{inc}'" for inc in self.include_dirs]
|
112 |
+
)
|
113 |
+
|
114 |
+
def generate_meson_build(self):
|
115 |
+
for node in self.pipeline:
|
116 |
+
node()
|
117 |
+
template = Template(self.meson_build_template())
|
118 |
+
return template.substitute(self.substitutions)
|
119 |
+
|
120 |
+
|
121 |
+
class MesonBackend(Backend):
|
122 |
+
def __init__(self, *args, **kwargs):
|
123 |
+
super().__init__(*args, **kwargs)
|
124 |
+
self.dependencies = self.extra_dat.get("dependencies", [])
|
125 |
+
self.meson_build_dir = "bbdir"
|
126 |
+
self.build_type = (
|
127 |
+
"debug" if any("debug" in flag for flag in self.fc_flags) else "release"
|
128 |
+
)
|
129 |
+
|
130 |
+
def _move_exec_to_root(self, build_dir: Path):
|
131 |
+
walk_dir = Path(build_dir) / self.meson_build_dir
|
132 |
+
path_objects = chain(
|
133 |
+
walk_dir.glob(f"{self.modulename}*.so"),
|
134 |
+
walk_dir.glob(f"{self.modulename}*.pyd"),
|
135 |
+
)
|
136 |
+
# Same behavior as distutils
|
137 |
+
# https://github.com/numpy/numpy/issues/24874#issuecomment-1835632293
|
138 |
+
for path_object in path_objects:
|
139 |
+
dest_path = Path.cwd() / path_object.name
|
140 |
+
if dest_path.exists():
|
141 |
+
dest_path.unlink()
|
142 |
+
shutil.copy2(path_object, dest_path)
|
143 |
+
os.remove(path_object)
|
144 |
+
|
145 |
+
def write_meson_build(self, build_dir: Path) -> None:
|
146 |
+
"""Writes the meson build file at specified location"""
|
147 |
+
meson_template = MesonTemplate(
|
148 |
+
self.modulename,
|
149 |
+
self.sources,
|
150 |
+
self.dependencies,
|
151 |
+
self.libraries,
|
152 |
+
self.library_dirs,
|
153 |
+
self.include_dirs,
|
154 |
+
self.extra_objects,
|
155 |
+
self.flib_flags,
|
156 |
+
self.fc_flags,
|
157 |
+
self.build_type,
|
158 |
+
sys.executable,
|
159 |
+
)
|
160 |
+
src = meson_template.generate_meson_build()
|
161 |
+
Path(build_dir).mkdir(parents=True, exist_ok=True)
|
162 |
+
meson_build_file = Path(build_dir) / "meson.build"
|
163 |
+
meson_build_file.write_text(src)
|
164 |
+
return meson_build_file
|
165 |
+
|
166 |
+
def _run_subprocess_command(self, command, cwd):
|
167 |
+
subprocess.run(command, cwd=cwd, check=True)
|
168 |
+
|
169 |
+
def run_meson(self, build_dir: Path):
|
170 |
+
setup_command = ["meson", "setup", self.meson_build_dir]
|
171 |
+
self._run_subprocess_command(setup_command, build_dir)
|
172 |
+
compile_command = ["meson", "compile", "-C", self.meson_build_dir]
|
173 |
+
self._run_subprocess_command(compile_command, build_dir)
|
174 |
+
|
175 |
+
def compile(self) -> None:
|
176 |
+
self.sources = _prepare_sources(self.modulename, self.sources, self.build_dir)
|
177 |
+
self.write_meson_build(self.build_dir)
|
178 |
+
self.run_meson(self.build_dir)
|
179 |
+
self._move_exec_to_root(self.build_dir)
|
180 |
+
|
181 |
+
|
182 |
+
def _prepare_sources(mname, sources, bdir):
|
183 |
+
extended_sources = sources.copy()
|
184 |
+
Path(bdir).mkdir(parents=True, exist_ok=True)
|
185 |
+
# Copy sources
|
186 |
+
for source in sources:
|
187 |
+
if Path(source).exists() and Path(source).is_file():
|
188 |
+
shutil.copy(source, bdir)
|
189 |
+
generated_sources = [
|
190 |
+
Path(f"{mname}module.c"),
|
191 |
+
Path(f"{mname}-f2pywrappers2.f90"),
|
192 |
+
Path(f"{mname}-f2pywrappers.f"),
|
193 |
+
]
|
194 |
+
bdir = Path(bdir)
|
195 |
+
for generated_source in generated_sources:
|
196 |
+
if generated_source.exists():
|
197 |
+
shutil.copy(generated_source, bdir / generated_source.name)
|
198 |
+
extended_sources.append(generated_source.name)
|
199 |
+
generated_source.unlink()
|
200 |
+
extended_sources = [
|
201 |
+
Path(source).name
|
202 |
+
for source in extended_sources
|
203 |
+
if not Path(source).suffix == ".pyf"
|
204 |
+
]
|
205 |
+
return extended_sources
|
venv/lib/python3.10/site-packages/numpy/f2py/_backends/meson.build.template
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
project('${modulename}',
|
2 |
+
['c', 'fortran'],
|
3 |
+
version : '0.1',
|
4 |
+
meson_version: '>= 1.1.0',
|
5 |
+
default_options : [
|
6 |
+
'warning_level=1',
|
7 |
+
'buildtype=${buildtype}'
|
8 |
+
])
|
9 |
+
fc = meson.get_compiler('fortran')
|
10 |
+
|
11 |
+
py = import('python').find_installation('${python}', pure: false)
|
12 |
+
py_dep = py.dependency()
|
13 |
+
|
14 |
+
incdir_numpy = run_command(py,
|
15 |
+
['-c', 'import os; os.chdir(".."); import numpy; print(numpy.get_include())'],
|
16 |
+
check : true
|
17 |
+
).stdout().strip()
|
18 |
+
|
19 |
+
incdir_f2py = run_command(py,
|
20 |
+
['-c', 'import os; os.chdir(".."); import numpy.f2py; print(numpy.f2py.get_include())'],
|
21 |
+
check : true
|
22 |
+
).stdout().strip()
|
23 |
+
|
24 |
+
inc_np = include_directories(incdir_numpy)
|
25 |
+
np_dep = declare_dependency(include_directories: inc_np)
|
26 |
+
|
27 |
+
incdir_f2py = incdir_numpy / '..' / '..' / 'f2py' / 'src'
|
28 |
+
inc_f2py = include_directories(incdir_f2py)
|
29 |
+
fortranobject_c = incdir_f2py / 'fortranobject.c'
|
30 |
+
|
31 |
+
inc_np = include_directories(incdir_numpy, incdir_f2py)
|
32 |
+
# gh-25000
|
33 |
+
quadmath_dep = fc.find_library('quadmath', required: false)
|
34 |
+
|
35 |
+
${lib_declarations}
|
36 |
+
${lib_dir_declarations}
|
37 |
+
|
38 |
+
py.extension_module('${modulename}',
|
39 |
+
[
|
40 |
+
${source_list},
|
41 |
+
fortranobject_c
|
42 |
+
],
|
43 |
+
include_directories: [
|
44 |
+
inc_np,
|
45 |
+
${inc_list}
|
46 |
+
],
|
47 |
+
dependencies : [
|
48 |
+
py_dep,
|
49 |
+
quadmath_dep,
|
50 |
+
${dep_list}
|
51 |
+
${lib_list}
|
52 |
+
${lib_dir_list}
|
53 |
+
],
|
54 |
+
install : true)
|
venv/lib/python3.10/site-packages/numpy/f2py/_isocbind.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
ISO_C_BINDING maps for f2py2e.
|
3 |
+
Only required declarations/macros/functions will be used.
|
4 |
+
|
5 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
6 |
+
Copyright 2011 -- present NumPy Developers.
|
7 |
+
Permission to use, modify, and distribute this software is given under the
|
8 |
+
terms of the NumPy License.
|
9 |
+
|
10 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
11 |
+
"""
|
12 |
+
# These map to keys in c2py_map, via forced casting for now, see gh-25229
|
13 |
+
iso_c_binding_map = {
|
14 |
+
'integer': {
|
15 |
+
'c_int': 'int',
|
16 |
+
'c_short': 'short', # 'short' <=> 'int' for now
|
17 |
+
'c_long': 'long', # 'long' <=> 'int' for now
|
18 |
+
'c_long_long': 'long_long',
|
19 |
+
'c_signed_char': 'signed_char',
|
20 |
+
'c_size_t': 'unsigned', # size_t <=> 'unsigned' for now
|
21 |
+
'c_int8_t': 'signed_char', # int8_t <=> 'signed_char' for now
|
22 |
+
'c_int16_t': 'short', # int16_t <=> 'short' for now
|
23 |
+
'c_int32_t': 'int', # int32_t <=> 'int' for now
|
24 |
+
'c_int64_t': 'long_long',
|
25 |
+
'c_int_least8_t': 'signed_char', # int_least8_t <=> 'signed_char' for now
|
26 |
+
'c_int_least16_t': 'short', # int_least16_t <=> 'short' for now
|
27 |
+
'c_int_least32_t': 'int', # int_least32_t <=> 'int' for now
|
28 |
+
'c_int_least64_t': 'long_long',
|
29 |
+
'c_int_fast8_t': 'signed_char', # int_fast8_t <=> 'signed_char' for now
|
30 |
+
'c_int_fast16_t': 'short', # int_fast16_t <=> 'short' for now
|
31 |
+
'c_int_fast32_t': 'int', # int_fast32_t <=> 'int' for now
|
32 |
+
'c_int_fast64_t': 'long_long',
|
33 |
+
'c_intmax_t': 'long_long', # intmax_t <=> 'long_long' for now
|
34 |
+
'c_intptr_t': 'long', # intptr_t <=> 'long' for now
|
35 |
+
'c_ptrdiff_t': 'long', # ptrdiff_t <=> 'long' for now
|
36 |
+
},
|
37 |
+
'real': {
|
38 |
+
'c_float': 'float',
|
39 |
+
'c_double': 'double',
|
40 |
+
'c_long_double': 'long_double'
|
41 |
+
},
|
42 |
+
'complex': {
|
43 |
+
'c_float_complex': 'complex_float',
|
44 |
+
'c_double_complex': 'complex_double',
|
45 |
+
'c_long_double_complex': 'complex_long_double'
|
46 |
+
},
|
47 |
+
'logical': {
|
48 |
+
'c_bool': 'unsigned_char' # _Bool <=> 'unsigned_char' for now
|
49 |
+
},
|
50 |
+
'character': {
|
51 |
+
'c_char': 'char'
|
52 |
+
}
|
53 |
+
}
|
54 |
+
|
55 |
+
# TODO: See gh-25229
|
56 |
+
isoc_c2pycode_map = {}
|
57 |
+
iso_c2py_map = {}
|
58 |
+
|
59 |
+
isoc_kindmap = {}
|
60 |
+
for fortran_type, c_type_dict in iso_c_binding_map.items():
|
61 |
+
for c_type in c_type_dict.keys():
|
62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
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
# START OF CODE VENDORED FROM `numpy.distutils.from_template`
|
4 |
+
#############################################################
|
5 |
+
"""
|
6 |
+
process_file(filename)
|
7 |
+
|
8 |
+
takes templated file .xxx.src and produces .xxx file where .xxx
|
9 |
+
is .pyf .f90 or .f using the following template rules:
|
10 |
+
|
11 |
+
'<..>' denotes a template.
|
12 |
+
|
13 |
+
All function and subroutine blocks in a source file with names that
|
14 |
+
contain '<..>' will be replicated according to the rules in '<..>'.
|
15 |
+
|
16 |
+
The number of comma-separated words in '<..>' will determine the number of
|
17 |
+
replicates.
|
18 |
+
|
19 |
+
'<..>' may have two different forms, named and short. For example,
|
20 |
+
|
21 |
+
named:
|
22 |
+
<p=d,s,z,c> where anywhere inside a block '<p>' will be replaced with
|
23 |
+
'd', 's', 'z', and 'c' for each replicate of the block.
|
24 |
+
|
25 |
+
<_c> is already defined: <_c=s,d,c,z>
|
26 |
+
<_t> is already defined: <_t=real,double precision,complex,double complex>
|
27 |
+
|
28 |
+
short:
|
29 |
+
<s,d,c,z>, a short form of the named, useful when no <p> appears inside
|
30 |
+
a block.
|
31 |
+
|
32 |
+
In general, '<..>' contains a comma separated list of arbitrary
|
33 |
+
expressions. If these expression must contain a comma|leftarrow|rightarrow,
|
34 |
+
then prepend the comma|leftarrow|rightarrow with a backslash.
|
35 |
+
|
36 |
+
If an expression matches '\\<index>' then it will be replaced
|
37 |
+
by <index>-th expression.
|
38 |
+
|
39 |
+
Note that all '<..>' forms in a block must have the same number of
|
40 |
+
comma-separated entries.
|
41 |
+
|
42 |
+
Predefined named template rules:
|
43 |
+
<prefix=s,d,c,z>
|
44 |
+
<ftype=real,double precision,complex,double complex>
|
45 |
+
<ftypereal=real,double precision,\\0,\\1>
|
46 |
+
<ctype=float,double,complex_float,complex_double>
|
47 |
+
<ctypereal=float,double,\\0,\\1>
|
48 |
+
"""
|
49 |
+
|
50 |
+
routine_start_re = re.compile(r'(\n|\A)(( (\$|\*))|)\s*(subroutine|function)\b', re.I)
|
51 |
+
routine_end_re = re.compile(r'\n\s*end\s*(subroutine|function)\b.*(\n|\Z)', re.I)
|
52 |
+
function_start_re = re.compile(r'\n (\$|\*)\s*function\b', re.I)
|
53 |
+
|
54 |
+
def parse_structure(astr):
|
55 |
+
""" Return a list of tuples for each function or subroutine each
|
56 |
+
tuple is the start and end of a subroutine or function to be
|
57 |
+
expanded.
|
58 |
+
"""
|
59 |
+
|
60 |
+
spanlist = []
|
61 |
+
ind = 0
|
62 |
+
while True:
|
63 |
+
m = routine_start_re.search(astr, ind)
|
64 |
+
if m is None:
|
65 |
+
break
|
66 |
+
start = m.start()
|
67 |
+
if function_start_re.match(astr, start, m.end()):
|
68 |
+
while True:
|
69 |
+
i = astr.rfind('\n', ind, start)
|
70 |
+
if i==-1:
|
71 |
+
break
|
72 |
+
start = i
|
73 |
+
if astr[i:i+7]!='\n $':
|
74 |
+
break
|
75 |
+
start += 1
|
76 |
+
m = routine_end_re.search(astr, m.end())
|
77 |
+
ind = end = m and m.end()-1 or len(astr)
|
78 |
+
spanlist.append((start, end))
|
79 |
+
return spanlist
|
80 |
+
|
81 |
+
template_re = re.compile(r"<\s*(\w[\w\d]*)\s*>")
|
82 |
+
named_re = re.compile(r"<\s*(\w[\w\d]*)\s*=\s*(.*?)\s*>")
|
83 |
+
list_re = re.compile(r"<\s*((.*?))\s*>")
|
84 |
+
|
85 |
+
def find_repl_patterns(astr):
|
86 |
+
reps = named_re.findall(astr)
|
87 |
+
names = {}
|
88 |
+
for rep in reps:
|
89 |
+
name = rep[0].strip() or unique_key(names)
|
90 |
+
repl = rep[1].replace(r'\,', '@comma@')
|
91 |
+
thelist = conv(repl)
|
92 |
+
names[name] = thelist
|
93 |
+
return names
|
94 |
+
|
95 |
+
def find_and_remove_repl_patterns(astr):
|
96 |
+
names = find_repl_patterns(astr)
|
97 |
+
astr = re.subn(named_re, '', astr)[0]
|
98 |
+
return astr, names
|
99 |
+
|
100 |
+
item_re = re.compile(r"\A\\(?P<index>\d+)\Z")
|
101 |
+
def conv(astr):
|
102 |
+
b = astr.split(',')
|
103 |
+
l = [x.strip() for x in b]
|
104 |
+
for i in range(len(l)):
|
105 |
+
m = item_re.match(l[i])
|
106 |
+
if m:
|
107 |
+
j = int(m.group('index'))
|
108 |
+
l[i] = l[j]
|
109 |
+
return ','.join(l)
|
110 |
+
|
111 |
+
def unique_key(adict):
|
112 |
+
""" Obtain a unique key given a dictionary."""
|
113 |
+
allkeys = list(adict.keys())
|
114 |
+
done = False
|
115 |
+
n = 1
|
116 |
+
while not done:
|
117 |
+
newkey = '__l%s' % (n)
|
118 |
+
if newkey in allkeys:
|
119 |
+
n += 1
|
120 |
+
else:
|
121 |
+
done = True
|
122 |
+
return newkey
|
123 |
+
|
124 |
+
|
125 |
+
template_name_re = re.compile(r'\A\s*(\w[\w\d]*)\s*\Z')
|
126 |
+
def expand_sub(substr, names):
|
127 |
+
substr = substr.replace(r'\>', '@rightarrow@')
|
128 |
+
substr = substr.replace(r'\<', '@leftarrow@')
|
129 |
+
lnames = find_repl_patterns(substr)
|
130 |
+
substr = named_re.sub(r"<\1>", substr) # get rid of definition templates
|
131 |
+
|
132 |
+
def listrepl(mobj):
|
133 |
+
thelist = conv(mobj.group(1).replace(r'\,', '@comma@'))
|
134 |
+
if template_name_re.match(thelist):
|
135 |
+
return "<%s>" % (thelist)
|
136 |
+
name = None
|
137 |
+
for key in lnames.keys(): # see if list is already in dictionary
|
138 |
+
if lnames[key] == thelist:
|
139 |
+
name = key
|
140 |
+
if name is None: # this list is not in the dictionary yet
|
141 |
+
name = unique_key(lnames)
|
142 |
+
lnames[name] = thelist
|
143 |
+
return "<%s>" % name
|
144 |
+
|
145 |
+
substr = list_re.sub(listrepl, substr) # convert all lists to named templates
|
146 |
+
# newnames are constructed as needed
|
147 |
+
|
148 |
+
numsubs = None
|
149 |
+
base_rule = None
|
150 |
+
rules = {}
|
151 |
+
for r in template_re.findall(substr):
|
152 |
+
if r not in rules:
|
153 |
+
thelist = lnames.get(r, names.get(r, None))
|
154 |
+
if thelist is None:
|
155 |
+
raise ValueError('No replicates found for <%s>' % (r))
|
156 |
+
if r not in names and not thelist.startswith('_'):
|
157 |
+
names[r] = thelist
|
158 |
+
rule = [i.replace('@comma@', ',') for i in thelist.split(',')]
|
159 |
+
num = len(rule)
|
160 |
+
|
161 |
+
if numsubs is None:
|
162 |
+
numsubs = num
|
163 |
+
rules[r] = rule
|
164 |
+
base_rule = r
|
165 |
+
elif num == numsubs:
|
166 |
+
rules[r] = rule
|
167 |
+
else:
|
168 |
+
print("Mismatch in number of replacements (base <{}={}>) "
|
169 |
+
"for <{}={}>. Ignoring.".format(base_rule, ','.join(rules[base_rule]), r, thelist))
|
170 |
+
if not rules:
|
171 |
+
return substr
|
172 |
+
|
173 |
+
def namerepl(mobj):
|
174 |
+
name = mobj.group(1)
|
175 |
+
return rules.get(name, (k+1)*[name])[k]
|
176 |
+
|
177 |
+
newstr = ''
|
178 |
+
for k in range(numsubs):
|
179 |
+
newstr += template_re.sub(namerepl, substr) + '\n\n'
|
180 |
+
|
181 |
+
newstr = newstr.replace('@rightarrow@', '>')
|
182 |
+
newstr = newstr.replace('@leftarrow@', '<')
|
183 |
+
return newstr
|
184 |
+
|
185 |
+
def process_str(allstr):
|
186 |
+
newstr = allstr
|
187 |
+
writestr = ''
|
188 |
+
|
189 |
+
struct = parse_structure(newstr)
|
190 |
+
|
191 |
+
oldend = 0
|
192 |
+
names = {}
|
193 |
+
names.update(_special_names)
|
194 |
+
for sub in struct:
|
195 |
+
cleanedstr, defs = find_and_remove_repl_patterns(newstr[oldend:sub[0]])
|
196 |
+
writestr += cleanedstr
|
197 |
+
names.update(defs)
|
198 |
+
writestr += expand_sub(newstr[sub[0]:sub[1]], names)
|
199 |
+
oldend = sub[1]
|
200 |
+
writestr += newstr[oldend:]
|
201 |
+
|
202 |
+
return writestr
|
203 |
+
|
204 |
+
include_src_re = re.compile(r"(\n|\A)\s*include\s*['\"](?P<name>[\w\d./\\]+\.src)['\"]", re.I)
|
205 |
+
|
206 |
+
def resolve_includes(source):
|
207 |
+
d = os.path.dirname(source)
|
208 |
+
with open(source) as fid:
|
209 |
+
lines = []
|
210 |
+
for line in fid:
|
211 |
+
m = include_src_re.match(line)
|
212 |
+
if m:
|
213 |
+
fn = m.group('name')
|
214 |
+
if not os.path.isabs(fn):
|
215 |
+
fn = os.path.join(d, fn)
|
216 |
+
if os.path.isfile(fn):
|
217 |
+
lines.extend(resolve_includes(fn))
|
218 |
+
else:
|
219 |
+
lines.append(line)
|
220 |
+
else:
|
221 |
+
lines.append(line)
|
222 |
+
return lines
|
223 |
+
|
224 |
+
def process_file(source):
|
225 |
+
lines = resolve_includes(source)
|
226 |
+
return process_str(''.join(lines))
|
227 |
+
|
228 |
+
_special_names = find_repl_patterns('''
|
229 |
+
<_c=s,d,c,z>
|
230 |
+
<_t=real,double precision,complex,double complex>
|
231 |
+
<prefix=s,d,c,z>
|
232 |
+
<ftype=real,double precision,complex,double complex>
|
233 |
+
<ctype=float,double,complex_float,complex_double>
|
234 |
+
<ftypereal=real,double precision,\\0,\\1>
|
235 |
+
<ctypereal=float,double,\\0,\\1>
|
236 |
+
''')
|
237 |
+
|
238 |
+
# END OF CODE VENDORED FROM `numpy.distutils.from_template`
|
239 |
+
###########################################################
|
venv/lib/python3.10/site-packages/numpy/f2py/auxfuncs.py
ADDED
@@ -0,0 +1,988 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Auxiliary functions for f2py2e.
|
3 |
+
|
4 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
5 |
+
Copyright 2011 -- present NumPy Developers.
|
6 |
+
Permission to use, modify, and distribute this software is given under the
|
7 |
+
terms of the NumPy (BSD style) LICENSE.
|
8 |
+
|
9 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
10 |
+
"""
|
11 |
+
import pprint
|
12 |
+
import sys
|
13 |
+
import re
|
14 |
+
import types
|
15 |
+
from functools import reduce
|
16 |
+
from copy import deepcopy
|
17 |
+
|
18 |
+
from . import __version__
|
19 |
+
from . import cfuncs
|
20 |
+
|
21 |
+
__all__ = [
|
22 |
+
'applyrules', 'debugcapi', 'dictappend', 'errmess', 'gentitle',
|
23 |
+
'getargs2', 'getcallprotoargument', 'getcallstatement',
|
24 |
+
'getfortranname', 'getpymethoddef', 'getrestdoc', 'getusercode',
|
25 |
+
'getusercode1', 'getdimension', 'hasbody', 'hascallstatement', 'hascommon',
|
26 |
+
'hasexternals', 'hasinitvalue', 'hasnote', 'hasresultnote',
|
27 |
+
'isallocatable', 'isarray', 'isarrayofstrings',
|
28 |
+
'ischaracter', 'ischaracterarray', 'ischaracter_or_characterarray',
|
29 |
+
'iscomplex',
|
30 |
+
'iscomplexarray', 'iscomplexfunction', 'iscomplexfunction_warn',
|
31 |
+
'isdouble', 'isdummyroutine', 'isexternal', 'isfunction',
|
32 |
+
'isfunction_wrap', 'isint1', 'isint1array', 'isinteger', 'isintent_aux',
|
33 |
+
'isintent_c', 'isintent_callback', 'isintent_copy', 'isintent_dict',
|
34 |
+
'isintent_hide', 'isintent_in', 'isintent_inout', 'isintent_inplace',
|
35 |
+
'isintent_nothide', 'isintent_out', 'isintent_overwrite', 'islogical',
|
36 |
+
'islogicalfunction', 'islong_complex', 'islong_double',
|
37 |
+
'islong_doublefunction', 'islong_long', 'islong_longfunction',
|
38 |
+
'ismodule', 'ismoduleroutine', 'isoptional', 'isprivate', 'isrequired',
|
39 |
+
'isroutine', 'isscalar', 'issigned_long_longarray', 'isstring',
|
40 |
+
'isstringarray', 'isstring_or_stringarray', 'isstringfunction',
|
41 |
+
'issubroutine', 'get_f2py_modulename',
|
42 |
+
'issubroutine_wrap', 'isthreadsafe', 'isunsigned', 'isunsigned_char',
|
43 |
+
'isunsigned_chararray', 'isunsigned_long_long',
|
44 |
+
'isunsigned_long_longarray', 'isunsigned_short',
|
45 |
+
'isunsigned_shortarray', 'l_and', 'l_not', 'l_or', 'outmess',
|
46 |
+
'replace', 'show', 'stripcomma', 'throw_error', 'isattr_value',
|
47 |
+
'getuseblocks', 'process_f2cmap_dict'
|
48 |
+
]
|
49 |
+
|
50 |
+
|
51 |
+
f2py_version = __version__.version
|
52 |
+
|
53 |
+
|
54 |
+
errmess = sys.stderr.write
|
55 |
+
show = pprint.pprint
|
56 |
+
|
57 |
+
options = {}
|
58 |
+
debugoptions = []
|
59 |
+
wrapfuncs = 1
|
60 |
+
|
61 |
+
|
62 |
+
def outmess(t):
|
63 |
+
if options.get('verbose', 1):
|
64 |
+
sys.stdout.write(t)
|
65 |
+
|
66 |
+
|
67 |
+
def debugcapi(var):
|
68 |
+
return 'capi' in debugoptions
|
69 |
+
|
70 |
+
|
71 |
+
def _ischaracter(var):
|
72 |
+
return 'typespec' in var and var['typespec'] == 'character' and \
|
73 |
+
not isexternal(var)
|
74 |
+
|
75 |
+
|
76 |
+
def _isstring(var):
|
77 |
+
return 'typespec' in var and var['typespec'] == 'character' and \
|
78 |
+
not isexternal(var)
|
79 |
+
|
80 |
+
|
81 |
+
def ischaracter_or_characterarray(var):
|
82 |
+
return _ischaracter(var) and 'charselector' not in var
|
83 |
+
|
84 |
+
|
85 |
+
def ischaracter(var):
|
86 |
+
return ischaracter_or_characterarray(var) and not isarray(var)
|
87 |
+
|
88 |
+
|
89 |
+
def ischaracterarray(var):
|
90 |
+
return ischaracter_or_characterarray(var) and isarray(var)
|
91 |
+
|
92 |
+
|
93 |
+
def isstring_or_stringarray(var):
|
94 |
+
return _ischaracter(var) and 'charselector' in var
|
95 |
+
|
96 |
+
|
97 |
+
def isstring(var):
|
98 |
+
return isstring_or_stringarray(var) and not isarray(var)
|
99 |
+
|
100 |
+
|
101 |
+
def isstringarray(var):
|
102 |
+
return isstring_or_stringarray(var) and isarray(var)
|
103 |
+
|
104 |
+
|
105 |
+
def isarrayofstrings(var): # obsolete?
|
106 |
+
# leaving out '*' for now so that `character*(*) a(m)` and `character
|
107 |
+
# a(m,*)` are treated differently. Luckily `character**` is illegal.
|
108 |
+
return isstringarray(var) and var['dimension'][-1] == '(*)'
|
109 |
+
|
110 |
+
|
111 |
+
def isarray(var):
|
112 |
+
return 'dimension' in var and not isexternal(var)
|
113 |
+
|
114 |
+
|
115 |
+
def isscalar(var):
|
116 |
+
return not (isarray(var) or isstring(var) or isexternal(var))
|
117 |
+
|
118 |
+
|
119 |
+
def iscomplex(var):
|
120 |
+
return isscalar(var) and \
|
121 |
+
var.get('typespec') in ['complex', 'double complex']
|
122 |
+
|
123 |
+
|
124 |
+
def islogical(var):
|
125 |
+
return isscalar(var) and var.get('typespec') == 'logical'
|
126 |
+
|
127 |
+
|
128 |
+
def isinteger(var):
|
129 |
+
return isscalar(var) and var.get('typespec') == 'integer'
|
130 |
+
|
131 |
+
|
132 |
+
def isreal(var):
|
133 |
+
return isscalar(var) and var.get('typespec') == 'real'
|
134 |
+
|
135 |
+
|
136 |
+
def get_kind(var):
|
137 |
+
try:
|
138 |
+
return var['kindselector']['*']
|
139 |
+
except KeyError:
|
140 |
+
try:
|
141 |
+
return var['kindselector']['kind']
|
142 |
+
except KeyError:
|
143 |
+
pass
|
144 |
+
|
145 |
+
|
146 |
+
def isint1(var):
|
147 |
+
return var.get('typespec') == 'integer' \
|
148 |
+
and get_kind(var) == '1' and not isarray(var)
|
149 |
+
|
150 |
+
|
151 |
+
def islong_long(var):
|
152 |
+
if not isscalar(var):
|
153 |
+
return 0
|
154 |
+
if var.get('typespec') not in ['integer', 'logical']:
|
155 |
+
return 0
|
156 |
+
return get_kind(var) == '8'
|
157 |
+
|
158 |
+
|
159 |
+
def isunsigned_char(var):
|
160 |
+
if not isscalar(var):
|
161 |
+
return 0
|
162 |
+
if var.get('typespec') != 'integer':
|
163 |
+
return 0
|
164 |
+
return get_kind(var) == '-1'
|
165 |
+
|
166 |
+
|
167 |
+
def isunsigned_short(var):
|
168 |
+
if not isscalar(var):
|
169 |
+
return 0
|
170 |
+
if var.get('typespec') != 'integer':
|
171 |
+
return 0
|
172 |
+
return get_kind(var) == '-2'
|
173 |
+
|
174 |
+
|
175 |
+
def isunsigned(var):
|
176 |
+
if not isscalar(var):
|
177 |
+
return 0
|
178 |
+
if var.get('typespec') != 'integer':
|
179 |
+
return 0
|
180 |
+
return get_kind(var) == '-4'
|
181 |
+
|
182 |
+
|
183 |
+
def isunsigned_long_long(var):
|
184 |
+
if not isscalar(var):
|
185 |
+
return 0
|
186 |
+
if var.get('typespec') != 'integer':
|
187 |
+
return 0
|
188 |
+
return get_kind(var) == '-8'
|
189 |
+
|
190 |
+
|
191 |
+
def isdouble(var):
|
192 |
+
if not isscalar(var):
|
193 |
+
return 0
|
194 |
+
if not var.get('typespec') == 'real':
|
195 |
+
return 0
|
196 |
+
return get_kind(var) == '8'
|
197 |
+
|
198 |
+
|
199 |
+
def islong_double(var):
|
200 |
+
if not isscalar(var):
|
201 |
+
return 0
|
202 |
+
if not var.get('typespec') == 'real':
|
203 |
+
return 0
|
204 |
+
return get_kind(var) == '16'
|
205 |
+
|
206 |
+
|
207 |
+
def islong_complex(var):
|
208 |
+
if not iscomplex(var):
|
209 |
+
return 0
|
210 |
+
return get_kind(var) == '32'
|
211 |
+
|
212 |
+
|
213 |
+
def iscomplexarray(var):
|
214 |
+
return isarray(var) and \
|
215 |
+
var.get('typespec') in ['complex', 'double complex']
|
216 |
+
|
217 |
+
|
218 |
+
def isint1array(var):
|
219 |
+
return isarray(var) and var.get('typespec') == 'integer' \
|
220 |
+
and get_kind(var) == '1'
|
221 |
+
|
222 |
+
|
223 |
+
def isunsigned_chararray(var):
|
224 |
+
return isarray(var) and var.get('typespec') in ['integer', 'logical']\
|
225 |
+
and get_kind(var) == '-1'
|
226 |
+
|
227 |
+
|
228 |
+
def isunsigned_shortarray(var):
|
229 |
+
return isarray(var) and var.get('typespec') in ['integer', 'logical']\
|
230 |
+
and get_kind(var) == '-2'
|
231 |
+
|
232 |
+
|
233 |
+
def isunsignedarray(var):
|
234 |
+
return isarray(var) and var.get('typespec') in ['integer', 'logical']\
|
235 |
+
and get_kind(var) == '-4'
|
236 |
+
|
237 |
+
|
238 |
+
def isunsigned_long_longarray(var):
|
239 |
+
return isarray(var) and var.get('typespec') in ['integer', 'logical']\
|
240 |
+
and get_kind(var) == '-8'
|
241 |
+
|
242 |
+
|
243 |
+
def issigned_chararray(var):
|
244 |
+
return isarray(var) and var.get('typespec') in ['integer', 'logical']\
|
245 |
+
and get_kind(var) == '1'
|
246 |
+
|
247 |
+
|
248 |
+
def issigned_shortarray(var):
|
249 |
+
return isarray(var) and var.get('typespec') in ['integer', 'logical']\
|
250 |
+
and get_kind(var) == '2'
|
251 |
+
|
252 |
+
|
253 |
+
def issigned_array(var):
|
254 |
+
return isarray(var) and var.get('typespec') in ['integer', 'logical']\
|
255 |
+
and get_kind(var) == '4'
|
256 |
+
|
257 |
+
|
258 |
+
def issigned_long_longarray(var):
|
259 |
+
return isarray(var) and var.get('typespec') in ['integer', 'logical']\
|
260 |
+
and get_kind(var) == '8'
|
261 |
+
|
262 |
+
|
263 |
+
def isallocatable(var):
|
264 |
+
return 'attrspec' in var and 'allocatable' in var['attrspec']
|
265 |
+
|
266 |
+
|
267 |
+
def ismutable(var):
|
268 |
+
return not ('dimension' not in var or isstring(var))
|
269 |
+
|
270 |
+
|
271 |
+
def ismoduleroutine(rout):
|
272 |
+
return 'modulename' in rout
|
273 |
+
|
274 |
+
|
275 |
+
def ismodule(rout):
|
276 |
+
return 'block' in rout and 'module' == rout['block']
|
277 |
+
|
278 |
+
|
279 |
+
def isfunction(rout):
|
280 |
+
return 'block' in rout and 'function' == rout['block']
|
281 |
+
|
282 |
+
|
283 |
+
def isfunction_wrap(rout):
|
284 |
+
if isintent_c(rout):
|
285 |
+
return 0
|
286 |
+
return wrapfuncs and isfunction(rout) and (not isexternal(rout))
|
287 |
+
|
288 |
+
|
289 |
+
def issubroutine(rout):
|
290 |
+
return 'block' in rout and 'subroutine' == rout['block']
|
291 |
+
|
292 |
+
|
293 |
+
def issubroutine_wrap(rout):
|
294 |
+
if isintent_c(rout):
|
295 |
+
return 0
|
296 |
+
return issubroutine(rout) and hasassumedshape(rout)
|
297 |
+
|
298 |
+
def isattr_value(var):
|
299 |
+
return 'value' in var.get('attrspec', [])
|
300 |
+
|
301 |
+
|
302 |
+
def hasassumedshape(rout):
|
303 |
+
if rout.get('hasassumedshape'):
|
304 |
+
return True
|
305 |
+
for a in rout['args']:
|
306 |
+
for d in rout['vars'].get(a, {}).get('dimension', []):
|
307 |
+
if d == ':':
|
308 |
+
rout['hasassumedshape'] = True
|
309 |
+
return True
|
310 |
+
return False
|
311 |
+
|
312 |
+
|
313 |
+
def requiresf90wrapper(rout):
|
314 |
+
return ismoduleroutine(rout) or hasassumedshape(rout)
|
315 |
+
|
316 |
+
|
317 |
+
def isroutine(rout):
|
318 |
+
return isfunction(rout) or issubroutine(rout)
|
319 |
+
|
320 |
+
|
321 |
+
def islogicalfunction(rout):
|
322 |
+
if not isfunction(rout):
|
323 |
+
return 0
|
324 |
+
if 'result' in rout:
|
325 |
+
a = rout['result']
|
326 |
+
else:
|
327 |
+
a = rout['name']
|
328 |
+
if a in rout['vars']:
|
329 |
+
return islogical(rout['vars'][a])
|
330 |
+
return 0
|
331 |
+
|
332 |
+
|
333 |
+
def islong_longfunction(rout):
|
334 |
+
if not isfunction(rout):
|
335 |
+
return 0
|
336 |
+
if 'result' in rout:
|
337 |
+
a = rout['result']
|
338 |
+
else:
|
339 |
+
a = rout['name']
|
340 |
+
if a in rout['vars']:
|
341 |
+
return islong_long(rout['vars'][a])
|
342 |
+
return 0
|
343 |
+
|
344 |
+
|
345 |
+
def islong_doublefunction(rout):
|
346 |
+
if not isfunction(rout):
|
347 |
+
return 0
|
348 |
+
if 'result' in rout:
|
349 |
+
a = rout['result']
|
350 |
+
else:
|
351 |
+
a = rout['name']
|
352 |
+
if a in rout['vars']:
|
353 |
+
return islong_double(rout['vars'][a])
|
354 |
+
return 0
|
355 |
+
|
356 |
+
|
357 |
+
def iscomplexfunction(rout):
|
358 |
+
if not isfunction(rout):
|
359 |
+
return 0
|
360 |
+
if 'result' in rout:
|
361 |
+
a = rout['result']
|
362 |
+
else:
|
363 |
+
a = rout['name']
|
364 |
+
if a in rout['vars']:
|
365 |
+
return iscomplex(rout['vars'][a])
|
366 |
+
return 0
|
367 |
+
|
368 |
+
|
369 |
+
def iscomplexfunction_warn(rout):
|
370 |
+
if iscomplexfunction(rout):
|
371 |
+
outmess("""\
|
372 |
+
**************************************************************
|
373 |
+
Warning: code with a function returning complex value
|
374 |
+
may not work correctly with your Fortran compiler.
|
375 |
+
When using GNU gcc/g77 compilers, codes should work
|
376 |
+
correctly for callbacks with:
|
377 |
+
f2py -c -DF2PY_CB_RETURNCOMPLEX
|
378 |
+
**************************************************************\n""")
|
379 |
+
return 1
|
380 |
+
return 0
|
381 |
+
|
382 |
+
|
383 |
+
def isstringfunction(rout):
|
384 |
+
if not isfunction(rout):
|
385 |
+
return 0
|
386 |
+
if 'result' in rout:
|
387 |
+
a = rout['result']
|
388 |
+
else:
|
389 |
+
a = rout['name']
|
390 |
+
if a in rout['vars']:
|
391 |
+
return isstring(rout['vars'][a])
|
392 |
+
return 0
|
393 |
+
|
394 |
+
|
395 |
+
def hasexternals(rout):
|
396 |
+
return 'externals' in rout and rout['externals']
|
397 |
+
|
398 |
+
|
399 |
+
def isthreadsafe(rout):
|
400 |
+
return 'f2pyenhancements' in rout and \
|
401 |
+
'threadsafe' in rout['f2pyenhancements']
|
402 |
+
|
403 |
+
|
404 |
+
def hasvariables(rout):
|
405 |
+
return 'vars' in rout and rout['vars']
|
406 |
+
|
407 |
+
|
408 |
+
def isoptional(var):
|
409 |
+
return ('attrspec' in var and 'optional' in var['attrspec'] and
|
410 |
+
'required' not in var['attrspec']) and isintent_nothide(var)
|
411 |
+
|
412 |
+
|
413 |
+
def isexternal(var):
|
414 |
+
return 'attrspec' in var and 'external' in var['attrspec']
|
415 |
+
|
416 |
+
|
417 |
+
def getdimension(var):
|
418 |
+
dimpattern = r"\((.*?)\)"
|
419 |
+
if 'attrspec' in var.keys():
|
420 |
+
if any('dimension' in s for s in var['attrspec']):
|
421 |
+
return [re.findall(dimpattern, v) for v in var['attrspec']][0]
|
422 |
+
|
423 |
+
|
424 |
+
def isrequired(var):
|
425 |
+
return not isoptional(var) and isintent_nothide(var)
|
426 |
+
|
427 |
+
|
428 |
+
def isintent_in(var):
|
429 |
+
if 'intent' not in var:
|
430 |
+
return 1
|
431 |
+
if 'hide' in var['intent']:
|
432 |
+
return 0
|
433 |
+
if 'inplace' in var['intent']:
|
434 |
+
return 0
|
435 |
+
if 'in' in var['intent']:
|
436 |
+
return 1
|
437 |
+
if 'out' in var['intent']:
|
438 |
+
return 0
|
439 |
+
if 'inout' in var['intent']:
|
440 |
+
return 0
|
441 |
+
if 'outin' in var['intent']:
|
442 |
+
return 0
|
443 |
+
return 1
|
444 |
+
|
445 |
+
|
446 |
+
def isintent_inout(var):
|
447 |
+
return ('intent' in var and ('inout' in var['intent'] or
|
448 |
+
'outin' in var['intent']) and 'in' not in var['intent'] and
|
449 |
+
'hide' not in var['intent'] and 'inplace' not in var['intent'])
|
450 |
+
|
451 |
+
|
452 |
+
def isintent_out(var):
|
453 |
+
return 'out' in var.get('intent', [])
|
454 |
+
|
455 |
+
|
456 |
+
def isintent_hide(var):
|
457 |
+
return ('intent' in var and ('hide' in var['intent'] or
|
458 |
+
('out' in var['intent'] and 'in' not in var['intent'] and
|
459 |
+
(not l_or(isintent_inout, isintent_inplace)(var)))))
|
460 |
+
|
461 |
+
|
462 |
+
def isintent_nothide(var):
|
463 |
+
return not isintent_hide(var)
|
464 |
+
|
465 |
+
|
466 |
+
def isintent_c(var):
|
467 |
+
return 'c' in var.get('intent', [])
|
468 |
+
|
469 |
+
|
470 |
+
def isintent_cache(var):
|
471 |
+
return 'cache' in var.get('intent', [])
|
472 |
+
|
473 |
+
|
474 |
+
def isintent_copy(var):
|
475 |
+
return 'copy' in var.get('intent', [])
|
476 |
+
|
477 |
+
|
478 |
+
def isintent_overwrite(var):
|
479 |
+
return 'overwrite' in var.get('intent', [])
|
480 |
+
|
481 |
+
|
482 |
+
def isintent_callback(var):
|
483 |
+
return 'callback' in var.get('intent', [])
|
484 |
+
|
485 |
+
|
486 |
+
def isintent_inplace(var):
|
487 |
+
return 'inplace' in var.get('intent', [])
|
488 |
+
|
489 |
+
|
490 |
+
def isintent_aux(var):
|
491 |
+
return 'aux' in var.get('intent', [])
|
492 |
+
|
493 |
+
|
494 |
+
def isintent_aligned4(var):
|
495 |
+
return 'aligned4' in var.get('intent', [])
|
496 |
+
|
497 |
+
|
498 |
+
def isintent_aligned8(var):
|
499 |
+
return 'aligned8' in var.get('intent', [])
|
500 |
+
|
501 |
+
|
502 |
+
def isintent_aligned16(var):
|
503 |
+
return 'aligned16' in var.get('intent', [])
|
504 |
+
|
505 |
+
|
506 |
+
isintent_dict = {isintent_in: 'INTENT_IN', isintent_inout: 'INTENT_INOUT',
|
507 |
+
isintent_out: 'INTENT_OUT', isintent_hide: 'INTENT_HIDE',
|
508 |
+
isintent_cache: 'INTENT_CACHE',
|
509 |
+
isintent_c: 'INTENT_C', isoptional: 'OPTIONAL',
|
510 |
+
isintent_inplace: 'INTENT_INPLACE',
|
511 |
+
isintent_aligned4: 'INTENT_ALIGNED4',
|
512 |
+
isintent_aligned8: 'INTENT_ALIGNED8',
|
513 |
+
isintent_aligned16: 'INTENT_ALIGNED16',
|
514 |
+
}
|
515 |
+
|
516 |
+
|
517 |
+
def isprivate(var):
|
518 |
+
return 'attrspec' in var and 'private' in var['attrspec']
|
519 |
+
|
520 |
+
|
521 |
+
def hasinitvalue(var):
|
522 |
+
return '=' in var
|
523 |
+
|
524 |
+
|
525 |
+
def hasinitvalueasstring(var):
|
526 |
+
if not hasinitvalue(var):
|
527 |
+
return 0
|
528 |
+
return var['='][0] in ['"', "'"]
|
529 |
+
|
530 |
+
|
531 |
+
def hasnote(var):
|
532 |
+
return 'note' in var
|
533 |
+
|
534 |
+
|
535 |
+
def hasresultnote(rout):
|
536 |
+
if not isfunction(rout):
|
537 |
+
return 0
|
538 |
+
if 'result' in rout:
|
539 |
+
a = rout['result']
|
540 |
+
else:
|
541 |
+
a = rout['name']
|
542 |
+
if a in rout['vars']:
|
543 |
+
return hasnote(rout['vars'][a])
|
544 |
+
return 0
|
545 |
+
|
546 |
+
|
547 |
+
def hascommon(rout):
|
548 |
+
return 'common' in rout
|
549 |
+
|
550 |
+
|
551 |
+
def containscommon(rout):
|
552 |
+
if hascommon(rout):
|
553 |
+
return 1
|
554 |
+
if hasbody(rout):
|
555 |
+
for b in rout['body']:
|
556 |
+
if containscommon(b):
|
557 |
+
return 1
|
558 |
+
return 0
|
559 |
+
|
560 |
+
|
561 |
+
def containsmodule(block):
|
562 |
+
if ismodule(block):
|
563 |
+
return 1
|
564 |
+
if not hasbody(block):
|
565 |
+
return 0
|
566 |
+
for b in block['body']:
|
567 |
+
if containsmodule(b):
|
568 |
+
return 1
|
569 |
+
return 0
|
570 |
+
|
571 |
+
|
572 |
+
def hasbody(rout):
|
573 |
+
return 'body' in rout
|
574 |
+
|
575 |
+
|
576 |
+
def hascallstatement(rout):
|
577 |
+
return getcallstatement(rout) is not None
|
578 |
+
|
579 |
+
|
580 |
+
def istrue(var):
|
581 |
+
return 1
|
582 |
+
|
583 |
+
|
584 |
+
def isfalse(var):
|
585 |
+
return 0
|
586 |
+
|
587 |
+
|
588 |
+
class F2PYError(Exception):
|
589 |
+
pass
|
590 |
+
|
591 |
+
|
592 |
+
class throw_error:
|
593 |
+
|
594 |
+
def __init__(self, mess):
|
595 |
+
self.mess = mess
|
596 |
+
|
597 |
+
def __call__(self, var):
|
598 |
+
mess = '\n\n var = %s\n Message: %s\n' % (var, self.mess)
|
599 |
+
raise F2PYError(mess)
|
600 |
+
|
601 |
+
|
602 |
+
def l_and(*f):
|
603 |
+
l1, l2 = 'lambda v', []
|
604 |
+
for i in range(len(f)):
|
605 |
+
l1 = '%s,f%d=f[%d]' % (l1, i, i)
|
606 |
+
l2.append('f%d(v)' % (i))
|
607 |
+
return eval('%s:%s' % (l1, ' and '.join(l2)))
|
608 |
+
|
609 |
+
|
610 |
+
def l_or(*f):
|
611 |
+
l1, l2 = 'lambda v', []
|
612 |
+
for i in range(len(f)):
|
613 |
+
l1 = '%s,f%d=f[%d]' % (l1, i, i)
|
614 |
+
l2.append('f%d(v)' % (i))
|
615 |
+
return eval('%s:%s' % (l1, ' or '.join(l2)))
|
616 |
+
|
617 |
+
|
618 |
+
def l_not(f):
|
619 |
+
return eval('lambda v,f=f:not f(v)')
|
620 |
+
|
621 |
+
|
622 |
+
def isdummyroutine(rout):
|
623 |
+
try:
|
624 |
+
return rout['f2pyenhancements']['fortranname'] == ''
|
625 |
+
except KeyError:
|
626 |
+
return 0
|
627 |
+
|
628 |
+
|
629 |
+
def getfortranname(rout):
|
630 |
+
try:
|
631 |
+
name = rout['f2pyenhancements']['fortranname']
|
632 |
+
if name == '':
|
633 |
+
raise KeyError
|
634 |
+
if not name:
|
635 |
+
errmess('Failed to use fortranname from %s\n' %
|
636 |
+
(rout['f2pyenhancements']))
|
637 |
+
raise KeyError
|
638 |
+
except KeyError:
|
639 |
+
name = rout['name']
|
640 |
+
return name
|
641 |
+
|
642 |
+
|
643 |
+
def getmultilineblock(rout, blockname, comment=1, counter=0):
|
644 |
+
try:
|
645 |
+
r = rout['f2pyenhancements'].get(blockname)
|
646 |
+
except KeyError:
|
647 |
+
return
|
648 |
+
if not r:
|
649 |
+
return
|
650 |
+
if counter > 0 and isinstance(r, str):
|
651 |
+
return
|
652 |
+
if isinstance(r, list):
|
653 |
+
if counter >= len(r):
|
654 |
+
return
|
655 |
+
r = r[counter]
|
656 |
+
if r[:3] == "'''":
|
657 |
+
if comment:
|
658 |
+
r = '\t/* start ' + blockname + \
|
659 |
+
' multiline (' + repr(counter) + ') */\n' + r[3:]
|
660 |
+
else:
|
661 |
+
r = r[3:]
|
662 |
+
if r[-3:] == "'''":
|
663 |
+
if comment:
|
664 |
+
r = r[:-3] + '\n\t/* end multiline (' + repr(counter) + ')*/'
|
665 |
+
else:
|
666 |
+
r = r[:-3]
|
667 |
+
else:
|
668 |
+
errmess("%s multiline block should end with `'''`: %s\n"
|
669 |
+
% (blockname, repr(r)))
|
670 |
+
return r
|
671 |
+
|
672 |
+
|
673 |
+
def getcallstatement(rout):
|
674 |
+
return getmultilineblock(rout, 'callstatement')
|
675 |
+
|
676 |
+
|
677 |
+
def getcallprotoargument(rout, cb_map={}):
|
678 |
+
r = getmultilineblock(rout, 'callprotoargument', comment=0)
|
679 |
+
if r:
|
680 |
+
return r
|
681 |
+
if hascallstatement(rout):
|
682 |
+
outmess(
|
683 |
+
'warning: callstatement is defined without callprotoargument\n')
|
684 |
+
return
|
685 |
+
from .capi_maps import getctype
|
686 |
+
arg_types, arg_types2 = [], []
|
687 |
+
if l_and(isstringfunction, l_not(isfunction_wrap))(rout):
|
688 |
+
arg_types.extend(['char*', 'size_t'])
|
689 |
+
for n in rout['args']:
|
690 |
+
var = rout['vars'][n]
|
691 |
+
if isintent_callback(var):
|
692 |
+
continue
|
693 |
+
if n in cb_map:
|
694 |
+
ctype = cb_map[n] + '_typedef'
|
695 |
+
else:
|
696 |
+
ctype = getctype(var)
|
697 |
+
if l_and(isintent_c, l_or(isscalar, iscomplex))(var):
|
698 |
+
pass
|
699 |
+
elif isstring(var):
|
700 |
+
pass
|
701 |
+
else:
|
702 |
+
if not isattr_value(var):
|
703 |
+
ctype = ctype + '*'
|
704 |
+
if ((isstring(var)
|
705 |
+
or isarrayofstrings(var) # obsolete?
|
706 |
+
or isstringarray(var))):
|
707 |
+
arg_types2.append('size_t')
|
708 |
+
arg_types.append(ctype)
|
709 |
+
|
710 |
+
proto_args = ','.join(arg_types + arg_types2)
|
711 |
+
if not proto_args:
|
712 |
+
proto_args = 'void'
|
713 |
+
return proto_args
|
714 |
+
|
715 |
+
|
716 |
+
def getusercode(rout):
|
717 |
+
return getmultilineblock(rout, 'usercode')
|
718 |
+
|
719 |
+
|
720 |
+
def getusercode1(rout):
|
721 |
+
return getmultilineblock(rout, 'usercode', counter=1)
|
722 |
+
|
723 |
+
|
724 |
+
def getpymethoddef(rout):
|
725 |
+
return getmultilineblock(rout, 'pymethoddef')
|
726 |
+
|
727 |
+
|
728 |
+
def getargs(rout):
|
729 |
+
sortargs, args = [], []
|
730 |
+
if 'args' in rout:
|
731 |
+
args = rout['args']
|
732 |
+
if 'sortvars' in rout:
|
733 |
+
for a in rout['sortvars']:
|
734 |
+
if a in args:
|
735 |
+
sortargs.append(a)
|
736 |
+
for a in args:
|
737 |
+
if a not in sortargs:
|
738 |
+
sortargs.append(a)
|
739 |
+
else:
|
740 |
+
sortargs = rout['args']
|
741 |
+
return args, sortargs
|
742 |
+
|
743 |
+
|
744 |
+
def getargs2(rout):
|
745 |
+
sortargs, args = [], rout.get('args', [])
|
746 |
+
auxvars = [a for a in rout['vars'].keys() if isintent_aux(rout['vars'][a])
|
747 |
+
and a not in args]
|
748 |
+
args = auxvars + args
|
749 |
+
if 'sortvars' in rout:
|
750 |
+
for a in rout['sortvars']:
|
751 |
+
if a in args:
|
752 |
+
sortargs.append(a)
|
753 |
+
for a in args:
|
754 |
+
if a not in sortargs:
|
755 |
+
sortargs.append(a)
|
756 |
+
else:
|
757 |
+
sortargs = auxvars + rout['args']
|
758 |
+
return args, sortargs
|
759 |
+
|
760 |
+
|
761 |
+
def getrestdoc(rout):
|
762 |
+
if 'f2pymultilines' not in rout:
|
763 |
+
return None
|
764 |
+
k = None
|
765 |
+
if rout['block'] == 'python module':
|
766 |
+
k = rout['block'], rout['name']
|
767 |
+
return rout['f2pymultilines'].get(k, None)
|
768 |
+
|
769 |
+
|
770 |
+
def gentitle(name):
|
771 |
+
ln = (80 - len(name) - 6) // 2
|
772 |
+
return '/*%s %s %s*/' % (ln * '*', name, ln * '*')
|
773 |
+
|
774 |
+
|
775 |
+
def flatlist(lst):
|
776 |
+
if isinstance(lst, list):
|
777 |
+
return reduce(lambda x, y, f=flatlist: x + f(y), lst, [])
|
778 |
+
return [lst]
|
779 |
+
|
780 |
+
|
781 |
+
def stripcomma(s):
|
782 |
+
if s and s[-1] == ',':
|
783 |
+
return s[:-1]
|
784 |
+
return s
|
785 |
+
|
786 |
+
|
787 |
+
def replace(str, d, defaultsep=''):
|
788 |
+
if isinstance(d, list):
|
789 |
+
return [replace(str, _m, defaultsep) for _m in d]
|
790 |
+
if isinstance(str, list):
|
791 |
+
return [replace(_m, d, defaultsep) for _m in str]
|
792 |
+
for k in 2 * list(d.keys()):
|
793 |
+
if k == 'separatorsfor':
|
794 |
+
continue
|
795 |
+
if 'separatorsfor' in d and k in d['separatorsfor']:
|
796 |
+
sep = d['separatorsfor'][k]
|
797 |
+
else:
|
798 |
+
sep = defaultsep
|
799 |
+
if isinstance(d[k], list):
|
800 |
+
str = str.replace('#%s#' % (k), sep.join(flatlist(d[k])))
|
801 |
+
else:
|
802 |
+
str = str.replace('#%s#' % (k), d[k])
|
803 |
+
return str
|
804 |
+
|
805 |
+
|
806 |
+
def dictappend(rd, ar):
|
807 |
+
if isinstance(ar, list):
|
808 |
+
for a in ar:
|
809 |
+
rd = dictappend(rd, a)
|
810 |
+
return rd
|
811 |
+
for k in ar.keys():
|
812 |
+
if k[0] == '_':
|
813 |
+
continue
|
814 |
+
if k in rd:
|
815 |
+
if isinstance(rd[k], str):
|
816 |
+
rd[k] = [rd[k]]
|
817 |
+
if isinstance(rd[k], list):
|
818 |
+
if isinstance(ar[k], list):
|
819 |
+
rd[k] = rd[k] + ar[k]
|
820 |
+
else:
|
821 |
+
rd[k].append(ar[k])
|
822 |
+
elif isinstance(rd[k], dict):
|
823 |
+
if isinstance(ar[k], dict):
|
824 |
+
if k == 'separatorsfor':
|
825 |
+
for k1 in ar[k].keys():
|
826 |
+
if k1 not in rd[k]:
|
827 |
+
rd[k][k1] = ar[k][k1]
|
828 |
+
else:
|
829 |
+
rd[k] = dictappend(rd[k], ar[k])
|
830 |
+
else:
|
831 |
+
rd[k] = ar[k]
|
832 |
+
return rd
|
833 |
+
|
834 |
+
|
835 |
+
def applyrules(rules, d, var={}):
|
836 |
+
ret = {}
|
837 |
+
if isinstance(rules, list):
|
838 |
+
for r in rules:
|
839 |
+
rr = applyrules(r, d, var)
|
840 |
+
ret = dictappend(ret, rr)
|
841 |
+
if '_break' in rr:
|
842 |
+
break
|
843 |
+
return ret
|
844 |
+
if '_check' in rules and (not rules['_check'](var)):
|
845 |
+
return ret
|
846 |
+
if 'need' in rules:
|
847 |
+
res = applyrules({'needs': rules['need']}, d, var)
|
848 |
+
if 'needs' in res:
|
849 |
+
cfuncs.append_needs(res['needs'])
|
850 |
+
|
851 |
+
for k in rules.keys():
|
852 |
+
if k == 'separatorsfor':
|
853 |
+
ret[k] = rules[k]
|
854 |
+
continue
|
855 |
+
if isinstance(rules[k], str):
|
856 |
+
ret[k] = replace(rules[k], d)
|
857 |
+
elif isinstance(rules[k], list):
|
858 |
+
ret[k] = []
|
859 |
+
for i in rules[k]:
|
860 |
+
ar = applyrules({k: i}, d, var)
|
861 |
+
if k in ar:
|
862 |
+
ret[k].append(ar[k])
|
863 |
+
elif k[0] == '_':
|
864 |
+
continue
|
865 |
+
elif isinstance(rules[k], dict):
|
866 |
+
ret[k] = []
|
867 |
+
for k1 in rules[k].keys():
|
868 |
+
if isinstance(k1, types.FunctionType) and k1(var):
|
869 |
+
if isinstance(rules[k][k1], list):
|
870 |
+
for i in rules[k][k1]:
|
871 |
+
if isinstance(i, dict):
|
872 |
+
res = applyrules({'supertext': i}, d, var)
|
873 |
+
if 'supertext' in res:
|
874 |
+
i = res['supertext']
|
875 |
+
else:
|
876 |
+
i = ''
|
877 |
+
ret[k].append(replace(i, d))
|
878 |
+
else:
|
879 |
+
i = rules[k][k1]
|
880 |
+
if isinstance(i, dict):
|
881 |
+
res = applyrules({'supertext': i}, d)
|
882 |
+
if 'supertext' in res:
|
883 |
+
i = res['supertext']
|
884 |
+
else:
|
885 |
+
i = ''
|
886 |
+
ret[k].append(replace(i, d))
|
887 |
+
else:
|
888 |
+
errmess('applyrules: ignoring rule %s.\n' % repr(rules[k]))
|
889 |
+
if isinstance(ret[k], list):
|
890 |
+
if len(ret[k]) == 1:
|
891 |
+
ret[k] = ret[k][0]
|
892 |
+
if ret[k] == []:
|
893 |
+
del ret[k]
|
894 |
+
return ret
|
895 |
+
|
896 |
+
_f2py_module_name_match = re.compile(r'\s*python\s*module\s*(?P<name>[\w_]+)',
|
897 |
+
re.I).match
|
898 |
+
_f2py_user_module_name_match = re.compile(r'\s*python\s*module\s*(?P<name>[\w_]*?'
|
899 |
+
r'__user__[\w_]*)', re.I).match
|
900 |
+
|
901 |
+
def get_f2py_modulename(source):
|
902 |
+
name = None
|
903 |
+
with open(source) as f:
|
904 |
+
for line in f:
|
905 |
+
m = _f2py_module_name_match(line)
|
906 |
+
if m:
|
907 |
+
if _f2py_user_module_name_match(line): # skip *__user__* names
|
908 |
+
continue
|
909 |
+
name = m.group('name')
|
910 |
+
break
|
911 |
+
return name
|
912 |
+
|
913 |
+
def getuseblocks(pymod):
|
914 |
+
all_uses = []
|
915 |
+
for inner in pymod['body']:
|
916 |
+
for modblock in inner['body']:
|
917 |
+
if modblock.get('use'):
|
918 |
+
all_uses.extend([x for x in modblock.get("use").keys() if "__" not in x])
|
919 |
+
return all_uses
|
920 |
+
|
921 |
+
def process_f2cmap_dict(f2cmap_all, new_map, c2py_map, verbose = False):
|
922 |
+
"""
|
923 |
+
Update the Fortran-to-C type mapping dictionary with new mappings and
|
924 |
+
return a list of successfully mapped C types.
|
925 |
+
|
926 |
+
This function integrates a new mapping dictionary into an existing
|
927 |
+
Fortran-to-C type mapping dictionary. It ensures that all keys are in
|
928 |
+
lowercase and validates new entries against a given C-to-Python mapping
|
929 |
+
dictionary. Redefinitions and invalid entries are reported with a warning.
|
930 |
+
|
931 |
+
Parameters
|
932 |
+
----------
|
933 |
+
f2cmap_all : dict
|
934 |
+
The existing Fortran-to-C type mapping dictionary that will be updated.
|
935 |
+
It should be a dictionary of dictionaries where the main keys represent
|
936 |
+
Fortran types and the nested dictionaries map Fortran type specifiers
|
937 |
+
to corresponding C types.
|
938 |
+
|
939 |
+
new_map : dict
|
940 |
+
A dictionary containing new type mappings to be added to `f2cmap_all`.
|
941 |
+
The structure should be similar to `f2cmap_all`, with keys representing
|
942 |
+
Fortran types and values being dictionaries of type specifiers and their
|
943 |
+
C type equivalents.
|
944 |
+
|
945 |
+
c2py_map : dict
|
946 |
+
A dictionary used for validating the C types in `new_map`. It maps C
|
947 |
+
types to corresponding Python types and is used to ensure that the C
|
948 |
+
types specified in `new_map` are valid.
|
949 |
+
|
950 |
+
verbose : boolean
|
951 |
+
A flag used to provide information about the types mapped
|
952 |
+
|
953 |
+
Returns
|
954 |
+
-------
|
955 |
+
tuple of (dict, list)
|
956 |
+
The updated Fortran-to-C type mapping dictionary and a list of
|
957 |
+
successfully mapped C types.
|
958 |
+
"""
|
959 |
+
f2cmap_mapped = []
|
960 |
+
|
961 |
+
new_map_lower = {}
|
962 |
+
for k, d1 in new_map.items():
|
963 |
+
d1_lower = {k1.lower(): v1 for k1, v1 in d1.items()}
|
964 |
+
new_map_lower[k.lower()] = d1_lower
|
965 |
+
|
966 |
+
for k, d1 in new_map_lower.items():
|
967 |
+
if k not in f2cmap_all:
|
968 |
+
f2cmap_all[k] = {}
|
969 |
+
|
970 |
+
for k1, v1 in d1.items():
|
971 |
+
if v1 in c2py_map:
|
972 |
+
if k1 in f2cmap_all[k]:
|
973 |
+
outmess(
|
974 |
+
"\tWarning: redefinition of {'%s':{'%s':'%s'->'%s'}}\n"
|
975 |
+
% (k, k1, f2cmap_all[k][k1], v1)
|
976 |
+
)
|
977 |
+
f2cmap_all[k][k1] = v1
|
978 |
+
if verbose:
|
979 |
+
outmess('\tMapping "%s(kind=%s)" to "%s"\n' % (k, k1, v1))
|
980 |
+
f2cmap_mapped.append(v1)
|
981 |
+
else:
|
982 |
+
if verbose:
|
983 |
+
errmess(
|
984 |
+
"\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n"
|
985 |
+
% (k, k1, v1, v1, list(c2py_map.keys()))
|
986 |
+
)
|
987 |
+
|
988 |
+
return f2cmap_all, f2cmap_mapped
|
venv/lib/python3.10/site-packages/numpy/f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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
3 |
+
Copyright 2011 -- present NumPy Developers.
|
4 |
+
Permission to use, modify, and distribute this software is given under the
|
5 |
+
terms of the NumPy License.
|
6 |
+
|
7 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
8 |
+
"""
|
9 |
+
from . import __version__
|
10 |
+
f2py_version = __version__.version
|
11 |
+
|
12 |
+
import copy
|
13 |
+
import re
|
14 |
+
import os
|
15 |
+
from .crackfortran import markoutercomma
|
16 |
+
from . import cb_rules
|
17 |
+
from ._isocbind import iso_c_binding_map, isoc_c2pycode_map, iso_c2py_map
|
18 |
+
|
19 |
+
# The environment provided by auxfuncs.py is needed for some calls to eval.
|
20 |
+
# As the needed functions cannot be determined by static inspection of the
|
21 |
+
# code, it is safest to use import * pending a major refactoring of f2py.
|
22 |
+
from .auxfuncs import *
|
23 |
+
|
24 |
+
__all__ = [
|
25 |
+
'getctype', 'getstrlength', 'getarrdims', 'getpydocsign',
|
26 |
+
'getarrdocsign', 'getinit', 'sign2map', 'routsign2map', 'modsign2map',
|
27 |
+
'cb_sign2map', 'cb_routsign2map', 'common_sign2map', 'process_f2cmap_dict'
|
28 |
+
]
|
29 |
+
|
30 |
+
|
31 |
+
depargs = []
|
32 |
+
lcb_map = {}
|
33 |
+
lcb2_map = {}
|
34 |
+
# forced casting: mainly caused by the fact that Python or Numeric
|
35 |
+
# C/APIs do not support the corresponding C types.
|
36 |
+
c2py_map = {'double': 'float',
|
37 |
+
'float': 'float', # forced casting
|
38 |
+
'long_double': 'float', # forced casting
|
39 |
+
'char': 'int', # forced casting
|
40 |
+
'signed_char': 'int', # forced casting
|
41 |
+
'unsigned_char': 'int', # forced casting
|
42 |
+
'short': 'int', # forced casting
|
43 |
+
'unsigned_short': 'int', # forced casting
|
44 |
+
'int': 'int', # forced casting
|
45 |
+
'long': 'int',
|
46 |
+
'long_long': 'long',
|
47 |
+
'unsigned': 'int', # forced casting
|
48 |
+
'complex_float': 'complex', # forced casting
|
49 |
+
'complex_double': 'complex',
|
50 |
+
'complex_long_double': 'complex', # forced casting
|
51 |
+
'string': 'string',
|
52 |
+
'character': 'bytes',
|
53 |
+
}
|
54 |
+
|
55 |
+
c2capi_map = {'double': 'NPY_DOUBLE',
|
56 |
+
'float': 'NPY_FLOAT',
|
57 |
+
'long_double': 'NPY_LONGDOUBLE',
|
58 |
+
'char': 'NPY_BYTE',
|
59 |
+
'unsigned_char': 'NPY_UBYTE',
|
60 |
+
'signed_char': 'NPY_BYTE',
|
61 |
+
'short': 'NPY_SHORT',
|
62 |
+
'unsigned_short': 'NPY_USHORT',
|
63 |
+
'int': 'NPY_INT',
|
64 |
+
'unsigned': 'NPY_UINT',
|
65 |
+
'long': 'NPY_LONG',
|
66 |
+
'unsigned_long': 'NPY_ULONG',
|
67 |
+
'long_long': 'NPY_LONGLONG',
|
68 |
+
'unsigned_long_long': 'NPY_ULONGLONG',
|
69 |
+
'complex_float': 'NPY_CFLOAT',
|
70 |
+
'complex_double': 'NPY_CDOUBLE',
|
71 |
+
'complex_long_double': 'NPY_CDOUBLE',
|
72 |
+
'string': 'NPY_STRING',
|
73 |
+
'character': 'NPY_STRING'}
|
74 |
+
|
75 |
+
c2pycode_map = {'double': 'd',
|
76 |
+
'float': 'f',
|
77 |
+
'long_double': 'g',
|
78 |
+
'char': 'b',
|
79 |
+
'unsigned_char': 'B',
|
80 |
+
'signed_char': 'b',
|
81 |
+
'short': 'h',
|
82 |
+
'unsigned_short': 'H',
|
83 |
+
'int': 'i',
|
84 |
+
'unsigned': 'I',
|
85 |
+
'long': 'l',
|
86 |
+
'unsigned_long': 'L',
|
87 |
+
'long_long': 'q',
|
88 |
+
'unsigned_long_long': 'Q',
|
89 |
+
'complex_float': 'F',
|
90 |
+
'complex_double': 'D',
|
91 |
+
'complex_long_double': 'G',
|
92 |
+
'string': 'S',
|
93 |
+
'character': 'c'}
|
94 |
+
|
95 |
+
# https://docs.python.org/3/c-api/arg.html#building-values
|
96 |
+
c2buildvalue_map = {'double': 'd',
|
97 |
+
'float': 'f',
|
98 |
+
'char': 'b',
|
99 |
+
'signed_char': 'b',
|
100 |
+
'short': 'h',
|
101 |
+
'int': 'i',
|
102 |
+
'long': 'l',
|
103 |
+
'long_long': 'L',
|
104 |
+
'complex_float': 'N',
|
105 |
+
'complex_double': 'N',
|
106 |
+
'complex_long_double': 'N',
|
107 |
+
'string': 'y',
|
108 |
+
'character': 'c'}
|
109 |
+
|
110 |
+
f2cmap_all = {'real': {'': 'float', '4': 'float', '8': 'double',
|
111 |
+
'12': 'long_double', '16': 'long_double'},
|
112 |
+
'integer': {'': 'int', '1': 'signed_char', '2': 'short',
|
113 |
+
'4': 'int', '8': 'long_long',
|
114 |
+
'-1': 'unsigned_char', '-2': 'unsigned_short',
|
115 |
+
'-4': 'unsigned', '-8': 'unsigned_long_long'},
|
116 |
+
'complex': {'': 'complex_float', '8': 'complex_float',
|
117 |
+
'16': 'complex_double', '24': 'complex_long_double',
|
118 |
+
'32': 'complex_long_double'},
|
119 |
+
'complexkind': {'': 'complex_float', '4': 'complex_float',
|
120 |
+
'8': 'complex_double', '12': 'complex_long_double',
|
121 |
+
'16': 'complex_long_double'},
|
122 |
+
'logical': {'': 'int', '1': 'char', '2': 'short', '4': 'int',
|
123 |
+
'8': 'long_long'},
|
124 |
+
'double complex': {'': 'complex_double'},
|
125 |
+
'double precision': {'': 'double'},
|
126 |
+
'byte': {'': 'char'},
|
127 |
+
}
|
128 |
+
|
129 |
+
# Add ISO_C handling
|
130 |
+
c2pycode_map.update(isoc_c2pycode_map)
|
131 |
+
c2py_map.update(iso_c2py_map)
|
132 |
+
f2cmap_all, _ = process_f2cmap_dict(f2cmap_all, iso_c_binding_map, c2py_map)
|
133 |
+
# End ISO_C handling
|
134 |
+
f2cmap_default = copy.deepcopy(f2cmap_all)
|
135 |
+
|
136 |
+
f2cmap_mapped = []
|
137 |
+
|
138 |
+
def load_f2cmap_file(f2cmap_file):
|
139 |
+
global f2cmap_all, f2cmap_mapped
|
140 |
+
|
141 |
+
f2cmap_all = copy.deepcopy(f2cmap_default)
|
142 |
+
|
143 |
+
if f2cmap_file is None:
|
144 |
+
# Default value
|
145 |
+
f2cmap_file = '.f2py_f2cmap'
|
146 |
+
if not os.path.isfile(f2cmap_file):
|
147 |
+
return
|
148 |
+
|
149 |
+
# User defined additions to f2cmap_all.
|
150 |
+
# f2cmap_file must contain a dictionary of dictionaries, only. For
|
151 |
+
# example, {'real':{'low':'float'}} means that Fortran 'real(low)' is
|
152 |
+
# interpreted as C 'float'. This feature is useful for F90/95 users if
|
153 |
+
# they use PARAMETERS in type specifications.
|
154 |
+
try:
|
155 |
+
outmess('Reading f2cmap from {!r} ...\n'.format(f2cmap_file))
|
156 |
+
with open(f2cmap_file) as f:
|
157 |
+
d = eval(f.read().lower(), {}, {})
|
158 |
+
f2cmap_all, f2cmap_mapped = process_f2cmap_dict(f2cmap_all, d, c2py_map, True)
|
159 |
+
outmess('Successfully applied user defined f2cmap changes\n')
|
160 |
+
except Exception as msg:
|
161 |
+
errmess('Failed to apply user defined f2cmap changes: %s. Skipping.\n' % (msg))
|
162 |
+
|
163 |
+
|
164 |
+
cformat_map = {'double': '%g',
|
165 |
+
'float': '%g',
|
166 |
+
'long_double': '%Lg',
|
167 |
+
'char': '%d',
|
168 |
+
'signed_char': '%d',
|
169 |
+
'unsigned_char': '%hhu',
|
170 |
+
'short': '%hd',
|
171 |
+
'unsigned_short': '%hu',
|
172 |
+
'int': '%d',
|
173 |
+
'unsigned': '%u',
|
174 |
+
'long': '%ld',
|
175 |
+
'unsigned_long': '%lu',
|
176 |
+
'long_long': '%ld',
|
177 |
+
'complex_float': '(%g,%g)',
|
178 |
+
'complex_double': '(%g,%g)',
|
179 |
+
'complex_long_double': '(%Lg,%Lg)',
|
180 |
+
'string': '\\"%s\\"',
|
181 |
+
'character': "'%c'",
|
182 |
+
}
|
183 |
+
|
184 |
+
# Auxiliary functions
|
185 |
+
|
186 |
+
|
187 |
+
def getctype(var):
|
188 |
+
"""
|
189 |
+
Determines C type
|
190 |
+
"""
|
191 |
+
ctype = 'void'
|
192 |
+
if isfunction(var):
|
193 |
+
if 'result' in var:
|
194 |
+
a = var['result']
|
195 |
+
else:
|
196 |
+
a = var['name']
|
197 |
+
if a in var['vars']:
|
198 |
+
return getctype(var['vars'][a])
|
199 |
+
else:
|
200 |
+
errmess('getctype: function %s has no return value?!\n' % a)
|
201 |
+
elif issubroutine(var):
|
202 |
+
return ctype
|
203 |
+
elif ischaracter_or_characterarray(var):
|
204 |
+
return 'character'
|
205 |
+
elif isstring_or_stringarray(var):
|
206 |
+
return 'string'
|
207 |
+
elif 'typespec' in var and var['typespec'].lower() in f2cmap_all:
|
208 |
+
typespec = var['typespec'].lower()
|
209 |
+
f2cmap = f2cmap_all[typespec]
|
210 |
+
ctype = f2cmap[''] # default type
|
211 |
+
if 'kindselector' in var:
|
212 |
+
if '*' in var['kindselector']:
|
213 |
+
try:
|
214 |
+
ctype = f2cmap[var['kindselector']['*']]
|
215 |
+
except KeyError:
|
216 |
+
errmess('getctype: "%s %s %s" not supported.\n' %
|
217 |
+
(var['typespec'], '*', var['kindselector']['*']))
|
218 |
+
elif 'kind' in var['kindselector']:
|
219 |
+
if typespec + 'kind' in f2cmap_all:
|
220 |
+
f2cmap = f2cmap_all[typespec + 'kind']
|
221 |
+
try:
|
222 |
+
ctype = f2cmap[var['kindselector']['kind']]
|
223 |
+
except KeyError:
|
224 |
+
if typespec in f2cmap_all:
|
225 |
+
f2cmap = f2cmap_all[typespec]
|
226 |
+
try:
|
227 |
+
ctype = f2cmap[str(var['kindselector']['kind'])]
|
228 |
+
except KeyError:
|
229 |
+
errmess('getctype: "%s(kind=%s)" is mapped to C "%s" (to override define dict(%s = dict(%s="<C typespec>")) in %s/.f2py_f2cmap file).\n'
|
230 |
+
% (typespec, var['kindselector']['kind'], ctype,
|
231 |
+
typespec, var['kindselector']['kind'], os.getcwd()))
|
232 |
+
else:
|
233 |
+
if not isexternal(var):
|
234 |
+
errmess('getctype: No C-type found in "%s", assuming void.\n' % var)
|
235 |
+
return ctype
|
236 |
+
|
237 |
+
|
238 |
+
def f2cexpr(expr):
|
239 |
+
"""Rewrite Fortran expression as f2py supported C expression.
|
240 |
+
|
241 |
+
Due to the lack of a proper expression parser in f2py, this
|
242 |
+
function uses a heuristic approach that assumes that Fortran
|
243 |
+
arithmetic expressions are valid C arithmetic expressions when
|
244 |
+
mapping Fortran function calls to the corresponding C function/CPP
|
245 |
+
macros calls.
|
246 |
+
|
247 |
+
"""
|
248 |
+
# TODO: support Fortran `len` function with optional kind parameter
|
249 |
+
expr = re.sub(r'\blen\b', 'f2py_slen', expr)
|
250 |
+
return expr
|
251 |
+
|
252 |
+
|
253 |
+
def getstrlength(var):
|
254 |
+
if isstringfunction(var):
|
255 |
+
if 'result' in var:
|
256 |
+
a = var['result']
|
257 |
+
else:
|
258 |
+
a = var['name']
|
259 |
+
if a in var['vars']:
|
260 |
+
return getstrlength(var['vars'][a])
|
261 |
+
else:
|
262 |
+
errmess('getstrlength: function %s has no return value?!\n' % a)
|
263 |
+
if not isstring(var):
|
264 |
+
errmess(
|
265 |
+
'getstrlength: expected a signature of a string but got: %s\n' % (repr(var)))
|
266 |
+
len = '1'
|
267 |
+
if 'charselector' in var:
|
268 |
+
a = var['charselector']
|
269 |
+
if '*' in a:
|
270 |
+
len = a['*']
|
271 |
+
elif 'len' in a:
|
272 |
+
len = f2cexpr(a['len'])
|
273 |
+
if re.match(r'\(\s*(\*|:)\s*\)', len) or re.match(r'(\*|:)', len):
|
274 |
+
if isintent_hide(var):
|
275 |
+
errmess('getstrlength:intent(hide): expected a string with defined length but got: %s\n' % (
|
276 |
+
repr(var)))
|
277 |
+
len = '-1'
|
278 |
+
return len
|
279 |
+
|
280 |
+
|
281 |
+
def getarrdims(a, var, verbose=0):
|
282 |
+
ret = {}
|
283 |
+
if isstring(var) and not isarray(var):
|
284 |
+
ret['size'] = getstrlength(var)
|
285 |
+
ret['rank'] = '0'
|
286 |
+
ret['dims'] = ''
|
287 |
+
elif isscalar(var):
|
288 |
+
ret['size'] = '1'
|
289 |
+
ret['rank'] = '0'
|
290 |
+
ret['dims'] = ''
|
291 |
+
elif isarray(var):
|
292 |
+
dim = copy.copy(var['dimension'])
|
293 |
+
ret['size'] = '*'.join(dim)
|
294 |
+
try:
|
295 |
+
ret['size'] = repr(eval(ret['size']))
|
296 |
+
except Exception:
|
297 |
+
pass
|
298 |
+
ret['dims'] = ','.join(dim)
|
299 |
+
ret['rank'] = repr(len(dim))
|
300 |
+
ret['rank*[-1]'] = repr(len(dim) * [-1])[1:-1]
|
301 |
+
for i in range(len(dim)): # solve dim for dependencies
|
302 |
+
v = []
|
303 |
+
if dim[i] in depargs:
|
304 |
+
v = [dim[i]]
|
305 |
+
else:
|
306 |
+
for va in depargs:
|
307 |
+
if re.match(r'.*?\b%s\b.*' % va, dim[i]):
|
308 |
+
v.append(va)
|
309 |
+
for va in v:
|
310 |
+
if depargs.index(va) > depargs.index(a):
|
311 |
+
dim[i] = '*'
|
312 |
+
break
|
313 |
+
ret['setdims'], i = '', -1
|
314 |
+
for d in dim:
|
315 |
+
i = i + 1
|
316 |
+
if d not in ['*', ':', '(*)', '(:)']:
|
317 |
+
ret['setdims'] = '%s#varname#_Dims[%d]=%s,' % (
|
318 |
+
ret['setdims'], i, d)
|
319 |
+
if ret['setdims']:
|
320 |
+
ret['setdims'] = ret['setdims'][:-1]
|
321 |
+
ret['cbsetdims'], i = '', -1
|
322 |
+
for d in var['dimension']:
|
323 |
+
i = i + 1
|
324 |
+
if d not in ['*', ':', '(*)', '(:)']:
|
325 |
+
ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % (
|
326 |
+
ret['cbsetdims'], i, d)
|
327 |
+
elif isintent_in(var):
|
328 |
+
outmess('getarrdims:warning: assumed shape array, using 0 instead of %r\n'
|
329 |
+
% (d))
|
330 |
+
ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % (
|
331 |
+
ret['cbsetdims'], i, 0)
|
332 |
+
elif verbose:
|
333 |
+
errmess(
|
334 |
+
'getarrdims: If in call-back function: array argument %s must have bounded dimensions: got %s\n' % (repr(a), repr(d)))
|
335 |
+
if ret['cbsetdims']:
|
336 |
+
ret['cbsetdims'] = ret['cbsetdims'][:-1]
|
337 |
+
# if not isintent_c(var):
|
338 |
+
# var['dimension'].reverse()
|
339 |
+
return ret
|
340 |
+
|
341 |
+
|
342 |
+
def getpydocsign(a, var):
|
343 |
+
global lcb_map
|
344 |
+
if isfunction(var):
|
345 |
+
if 'result' in var:
|
346 |
+
af = var['result']
|
347 |
+
else:
|
348 |
+
af = var['name']
|
349 |
+
if af in var['vars']:
|
350 |
+
return getpydocsign(af, var['vars'][af])
|
351 |
+
else:
|
352 |
+
errmess('getctype: function %s has no return value?!\n' % af)
|
353 |
+
return '', ''
|
354 |
+
sig, sigout = a, a
|
355 |
+
opt = ''
|
356 |
+
if isintent_in(var):
|
357 |
+
opt = 'input'
|
358 |
+
elif isintent_inout(var):
|
359 |
+
opt = 'in/output'
|
360 |
+
out_a = a
|
361 |
+
if isintent_out(var):
|
362 |
+
for k in var['intent']:
|
363 |
+
if k[:4] == 'out=':
|
364 |
+
out_a = k[4:]
|
365 |
+
break
|
366 |
+
init = ''
|
367 |
+
ctype = getctype(var)
|
368 |
+
|
369 |
+
if hasinitvalue(var):
|
370 |
+
init, showinit = getinit(a, var)
|
371 |
+
init = ', optional\\n Default: %s' % showinit
|
372 |
+
if isscalar(var):
|
373 |
+
if isintent_inout(var):
|
374 |
+
sig = '%s : %s rank-0 array(%s,\'%s\')%s' % (a, opt, c2py_map[ctype],
|
375 |
+
c2pycode_map[ctype], init)
|
376 |
+
else:
|
377 |
+
sig = '%s : %s %s%s' % (a, opt, c2py_map[ctype], init)
|
378 |
+
sigout = '%s : %s' % (out_a, c2py_map[ctype])
|
379 |
+
elif isstring(var):
|
380 |
+
if isintent_inout(var):
|
381 |
+
sig = '%s : %s rank-0 array(string(len=%s),\'c\')%s' % (
|
382 |
+
a, opt, getstrlength(var), init)
|
383 |
+
else:
|
384 |
+
sig = '%s : %s string(len=%s)%s' % (
|
385 |
+
a, opt, getstrlength(var), init)
|
386 |
+
sigout = '%s : string(len=%s)' % (out_a, getstrlength(var))
|
387 |
+
elif isarray(var):
|
388 |
+
dim = var['dimension']
|
389 |
+
rank = repr(len(dim))
|
390 |
+
sig = '%s : %s rank-%s array(\'%s\') with bounds (%s)%s' % (a, opt, rank,
|
391 |
+
c2pycode_map[
|
392 |
+
ctype],
|
393 |
+
','.join(dim), init)
|
394 |
+
if a == out_a:
|
395 |
+
sigout = '%s : rank-%s array(\'%s\') with bounds (%s)'\
|
396 |
+
% (a, rank, c2pycode_map[ctype], ','.join(dim))
|
397 |
+
else:
|
398 |
+
sigout = '%s : rank-%s array(\'%s\') with bounds (%s) and %s storage'\
|
399 |
+
% (out_a, rank, c2pycode_map[ctype], ','.join(dim), a)
|
400 |
+
elif isexternal(var):
|
401 |
+
ua = ''
|
402 |
+
if a in lcb_map and lcb_map[a] in lcb2_map and 'argname' in lcb2_map[lcb_map[a]]:
|
403 |
+
ua = lcb2_map[lcb_map[a]]['argname']
|
404 |
+
if not ua == a:
|
405 |
+
ua = ' => %s' % ua
|
406 |
+
else:
|
407 |
+
ua = ''
|
408 |
+
sig = '%s : call-back function%s' % (a, ua)
|
409 |
+
sigout = sig
|
410 |
+
else:
|
411 |
+
errmess(
|
412 |
+
'getpydocsign: Could not resolve docsignature for "%s".\n' % a)
|
413 |
+
return sig, sigout
|
414 |
+
|
415 |
+
|
416 |
+
def getarrdocsign(a, var):
|
417 |
+
ctype = getctype(var)
|
418 |
+
if isstring(var) and (not isarray(var)):
|
419 |
+
sig = '%s : rank-0 array(string(len=%s),\'c\')' % (a,
|
420 |
+
getstrlength(var))
|
421 |
+
elif isscalar(var):
|
422 |
+
sig = '%s : rank-0 array(%s,\'%s\')' % (a, c2py_map[ctype],
|
423 |
+
c2pycode_map[ctype],)
|
424 |
+
elif isarray(var):
|
425 |
+
dim = var['dimension']
|
426 |
+
rank = repr(len(dim))
|
427 |
+
sig = '%s : rank-%s array(\'%s\') with bounds (%s)' % (a, rank,
|
428 |
+
c2pycode_map[
|
429 |
+
ctype],
|
430 |
+
','.join(dim))
|
431 |
+
return sig
|
432 |
+
|
433 |
+
|
434 |
+
def getinit(a, var):
|
435 |
+
if isstring(var):
|
436 |
+
init, showinit = '""', "''"
|
437 |
+
else:
|
438 |
+
init, showinit = '', ''
|
439 |
+
if hasinitvalue(var):
|
440 |
+
init = var['=']
|
441 |
+
showinit = init
|
442 |
+
if iscomplex(var) or iscomplexarray(var):
|
443 |
+
ret = {}
|
444 |
+
|
445 |
+
try:
|
446 |
+
v = var["="]
|
447 |
+
if ',' in v:
|
448 |
+
ret['init.r'], ret['init.i'] = markoutercomma(
|
449 |
+
v[1:-1]).split('@,@')
|
450 |
+
else:
|
451 |
+
v = eval(v, {}, {})
|
452 |
+
ret['init.r'], ret['init.i'] = str(v.real), str(v.imag)
|
453 |
+
except Exception:
|
454 |
+
raise ValueError(
|
455 |
+
'getinit: expected complex number `(r,i)\' but got `%s\' as initial value of %r.' % (init, a))
|
456 |
+
if isarray(var):
|
457 |
+
init = '(capi_c.r=%s,capi_c.i=%s,capi_c)' % (
|
458 |
+
ret['init.r'], ret['init.i'])
|
459 |
+
elif isstring(var):
|
460 |
+
if not init:
|
461 |
+
init, showinit = '""', "''"
|
462 |
+
if init[0] == "'":
|
463 |
+
init = '"%s"' % (init[1:-1].replace('"', '\\"'))
|
464 |
+
if init[0] == '"':
|
465 |
+
showinit = "'%s'" % (init[1:-1])
|
466 |
+
return init, showinit
|
467 |
+
|
468 |
+
|
469 |
+
def get_elsize(var):
|
470 |
+
if isstring(var) or isstringarray(var):
|
471 |
+
elsize = getstrlength(var)
|
472 |
+
# override with user-specified length when available:
|
473 |
+
elsize = var['charselector'].get('f2py_len', elsize)
|
474 |
+
return elsize
|
475 |
+
if ischaracter(var) or ischaracterarray(var):
|
476 |
+
return '1'
|
477 |
+
# for numerical types, PyArray_New* functions ignore specified
|
478 |
+
# elsize, so we just return 1 and let elsize be determined at
|
479 |
+
# runtime, see fortranobject.c
|
480 |
+
return '1'
|
481 |
+
|
482 |
+
|
483 |
+
def sign2map(a, var):
|
484 |
+
"""
|
485 |
+
varname,ctype,atype
|
486 |
+
init,init.r,init.i,pytype
|
487 |
+
vardebuginfo,vardebugshowvalue,varshowvalue
|
488 |
+
varrformat
|
489 |
+
|
490 |
+
intent
|
491 |
+
"""
|
492 |
+
out_a = a
|
493 |
+
if isintent_out(var):
|
494 |
+
for k in var['intent']:
|
495 |
+
if k[:4] == 'out=':
|
496 |
+
out_a = k[4:]
|
497 |
+
break
|
498 |
+
ret = {'varname': a, 'outvarname': out_a, 'ctype': getctype(var)}
|
499 |
+
intent_flags = []
|
500 |
+
for f, s in isintent_dict.items():
|
501 |
+
if f(var):
|
502 |
+
intent_flags.append('F2PY_%s' % s)
|
503 |
+
if intent_flags:
|
504 |
+
# TODO: Evaluate intent_flags here.
|
505 |
+
ret['intent'] = '|'.join(intent_flags)
|
506 |
+
else:
|
507 |
+
ret['intent'] = 'F2PY_INTENT_IN'
|
508 |
+
if isarray(var):
|
509 |
+
ret['varrformat'] = 'N'
|
510 |
+
elif ret['ctype'] in c2buildvalue_map:
|
511 |
+
ret['varrformat'] = c2buildvalue_map[ret['ctype']]
|
512 |
+
else:
|
513 |
+
ret['varrformat'] = 'O'
|
514 |
+
ret['init'], ret['showinit'] = getinit(a, var)
|
515 |
+
if hasinitvalue(var) and iscomplex(var) and not isarray(var):
|
516 |
+
ret['init.r'], ret['init.i'] = markoutercomma(
|
517 |
+
ret['init'][1:-1]).split('@,@')
|
518 |
+
if isexternal(var):
|
519 |
+
ret['cbnamekey'] = a
|
520 |
+
if a in lcb_map:
|
521 |
+
ret['cbname'] = lcb_map[a]
|
522 |
+
ret['maxnofargs'] = lcb2_map[lcb_map[a]]['maxnofargs']
|
523 |
+
ret['nofoptargs'] = lcb2_map[lcb_map[a]]['nofoptargs']
|
524 |
+
ret['cbdocstr'] = lcb2_map[lcb_map[a]]['docstr']
|
525 |
+
ret['cblatexdocstr'] = lcb2_map[lcb_map[a]]['latexdocstr']
|
526 |
+
else:
|
527 |
+
ret['cbname'] = a
|
528 |
+
errmess('sign2map: Confused: external %s is not in lcb_map%s.\n' % (
|
529 |
+
a, list(lcb_map.keys())))
|
530 |
+
if isstring(var):
|
531 |
+
ret['length'] = getstrlength(var)
|
532 |
+
if isarray(var):
|
533 |
+
ret = dictappend(ret, getarrdims(a, var))
|
534 |
+
dim = copy.copy(var['dimension'])
|
535 |
+
if ret['ctype'] in c2capi_map:
|
536 |
+
ret['atype'] = c2capi_map[ret['ctype']]
|
537 |
+
ret['elsize'] = get_elsize(var)
|
538 |
+
# Debug info
|
539 |
+
if debugcapi(var):
|
540 |
+
il = [isintent_in, 'input', isintent_out, 'output',
|
541 |
+
isintent_inout, 'inoutput', isrequired, 'required',
|
542 |
+
isoptional, 'optional', isintent_hide, 'hidden',
|
543 |
+
iscomplex, 'complex scalar',
|
544 |
+
l_and(isscalar, l_not(iscomplex)), 'scalar',
|
545 |
+
isstring, 'string', isarray, 'array',
|
546 |
+
iscomplexarray, 'complex array', isstringarray, 'string array',
|
547 |
+
iscomplexfunction, 'complex function',
|
548 |
+
l_and(isfunction, l_not(iscomplexfunction)), 'function',
|
549 |
+
isexternal, 'callback',
|
550 |
+
isintent_callback, 'callback',
|
551 |
+
isintent_aux, 'auxiliary',
|
552 |
+
]
|
553 |
+
rl = []
|
554 |
+
for i in range(0, len(il), 2):
|
555 |
+
if il[i](var):
|
556 |
+
rl.append(il[i + 1])
|
557 |
+
if isstring(var):
|
558 |
+
rl.append('slen(%s)=%s' % (a, ret['length']))
|
559 |
+
if isarray(var):
|
560 |
+
ddim = ','.join(
|
561 |
+
map(lambda x, y: '%s|%s' % (x, y), var['dimension'], dim))
|
562 |
+
rl.append('dims(%s)' % ddim)
|
563 |
+
if isexternal(var):
|
564 |
+
ret['vardebuginfo'] = 'debug-capi:%s=>%s:%s' % (
|
565 |
+
a, ret['cbname'], ','.join(rl))
|
566 |
+
else:
|
567 |
+
ret['vardebuginfo'] = 'debug-capi:%s %s=%s:%s' % (
|
568 |
+
ret['ctype'], a, ret['showinit'], ','.join(rl))
|
569 |
+
if isscalar(var):
|
570 |
+
if ret['ctype'] in cformat_map:
|
571 |
+
ret['vardebugshowvalue'] = 'debug-capi:%s=%s' % (
|
572 |
+
a, cformat_map[ret['ctype']])
|
573 |
+
if isstring(var):
|
574 |
+
ret['vardebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (
|
575 |
+
a, a)
|
576 |
+
if isexternal(var):
|
577 |
+
ret['vardebugshowvalue'] = 'debug-capi:%s=%%p' % (a)
|
578 |
+
if ret['ctype'] in cformat_map:
|
579 |
+
ret['varshowvalue'] = '#name#:%s=%s' % (a, cformat_map[ret['ctype']])
|
580 |
+
ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
|
581 |
+
if isstring(var):
|
582 |
+
ret['varshowvalue'] = '#name#:slen(%s)=%%d %s=\\"%%s\\"' % (a, a)
|
583 |
+
ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
|
584 |
+
if hasnote(var):
|
585 |
+
ret['note'] = var['note']
|
586 |
+
return ret
|
587 |
+
|
588 |
+
|
589 |
+
def routsign2map(rout):
|
590 |
+
"""
|
591 |
+
name,NAME,begintitle,endtitle
|
592 |
+
rname,ctype,rformat
|
593 |
+
routdebugshowvalue
|
594 |
+
"""
|
595 |
+
global lcb_map
|
596 |
+
name = rout['name']
|
597 |
+
fname = getfortranname(rout)
|
598 |
+
ret = {'name': name,
|
599 |
+
'texname': name.replace('_', '\\_'),
|
600 |
+
'name_lower': name.lower(),
|
601 |
+
'NAME': name.upper(),
|
602 |
+
'begintitle': gentitle(name),
|
603 |
+
'endtitle': gentitle('end of %s' % name),
|
604 |
+
'fortranname': fname,
|
605 |
+
'FORTRANNAME': fname.upper(),
|
606 |
+
'callstatement': getcallstatement(rout) or '',
|
607 |
+
'usercode': getusercode(rout) or '',
|
608 |
+
'usercode1': getusercode1(rout) or '',
|
609 |
+
}
|
610 |
+
if '_' in fname:
|
611 |
+
ret['F_FUNC'] = 'F_FUNC_US'
|
612 |
+
else:
|
613 |
+
ret['F_FUNC'] = 'F_FUNC'
|
614 |
+
if '_' in name:
|
615 |
+
ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC_US'
|
616 |
+
else:
|
617 |
+
ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC'
|
618 |
+
lcb_map = {}
|
619 |
+
if 'use' in rout:
|
620 |
+
for u in rout['use'].keys():
|
621 |
+
if u in cb_rules.cb_map:
|
622 |
+
for un in cb_rules.cb_map[u]:
|
623 |
+
ln = un[0]
|
624 |
+
if 'map' in rout['use'][u]:
|
625 |
+
for k in rout['use'][u]['map'].keys():
|
626 |
+
if rout['use'][u]['map'][k] == un[0]:
|
627 |
+
ln = k
|
628 |
+
break
|
629 |
+
lcb_map[ln] = un[1]
|
630 |
+
elif 'externals' in rout and rout['externals']:
|
631 |
+
errmess('routsign2map: Confused: function %s has externals %s but no "use" statement.\n' % (
|
632 |
+
ret['name'], repr(rout['externals'])))
|
633 |
+
ret['callprotoargument'] = getcallprotoargument(rout, lcb_map) or ''
|
634 |
+
if isfunction(rout):
|
635 |
+
if 'result' in rout:
|
636 |
+
a = rout['result']
|
637 |
+
else:
|
638 |
+
a = rout['name']
|
639 |
+
ret['rname'] = a
|
640 |
+
ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, rout)
|
641 |
+
ret['ctype'] = getctype(rout['vars'][a])
|
642 |
+
if hasresultnote(rout):
|
643 |
+
ret['resultnote'] = rout['vars'][a]['note']
|
644 |
+
rout['vars'][a]['note'] = ['See elsewhere.']
|
645 |
+
if ret['ctype'] in c2buildvalue_map:
|
646 |
+
ret['rformat'] = c2buildvalue_map[ret['ctype']]
|
647 |
+
else:
|
648 |
+
ret['rformat'] = 'O'
|
649 |
+
errmess('routsign2map: no c2buildvalue key for type %s\n' %
|
650 |
+
(repr(ret['ctype'])))
|
651 |
+
if debugcapi(rout):
|
652 |
+
if ret['ctype'] in cformat_map:
|
653 |
+
ret['routdebugshowvalue'] = 'debug-capi:%s=%s' % (
|
654 |
+
a, cformat_map[ret['ctype']])
|
655 |
+
if isstringfunction(rout):
|
656 |
+
ret['routdebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (
|
657 |
+
a, a)
|
658 |
+
if isstringfunction(rout):
|
659 |
+
ret['rlength'] = getstrlength(rout['vars'][a])
|
660 |
+
if ret['rlength'] == '-1':
|
661 |
+
errmess('routsign2map: expected explicit specification of the length of the string returned by the fortran function %s; taking 10.\n' % (
|
662 |
+
repr(rout['name'])))
|
663 |
+
ret['rlength'] = '10'
|
664 |
+
if hasnote(rout):
|
665 |
+
ret['note'] = rout['note']
|
666 |
+
rout['note'] = ['See elsewhere.']
|
667 |
+
return ret
|
668 |
+
|
669 |
+
|
670 |
+
def modsign2map(m):
|
671 |
+
"""
|
672 |
+
modulename
|
673 |
+
"""
|
674 |
+
if ismodule(m):
|
675 |
+
ret = {'f90modulename': m['name'],
|
676 |
+
'F90MODULENAME': m['name'].upper(),
|
677 |
+
'texf90modulename': m['name'].replace('_', '\\_')}
|
678 |
+
else:
|
679 |
+
ret = {'modulename': m['name'],
|
680 |
+
'MODULENAME': m['name'].upper(),
|
681 |
+
'texmodulename': m['name'].replace('_', '\\_')}
|
682 |
+
ret['restdoc'] = getrestdoc(m) or []
|
683 |
+
if hasnote(m):
|
684 |
+
ret['note'] = m['note']
|
685 |
+
ret['usercode'] = getusercode(m) or ''
|
686 |
+
ret['usercode1'] = getusercode1(m) or ''
|
687 |
+
if m['body']:
|
688 |
+
ret['interface_usercode'] = getusercode(m['body'][0]) or ''
|
689 |
+
else:
|
690 |
+
ret['interface_usercode'] = ''
|
691 |
+
ret['pymethoddef'] = getpymethoddef(m) or ''
|
692 |
+
if 'coutput' in m:
|
693 |
+
ret['coutput'] = m['coutput']
|
694 |
+
if 'f2py_wrapper_output' in m:
|
695 |
+
ret['f2py_wrapper_output'] = m['f2py_wrapper_output']
|
696 |
+
return ret
|
697 |
+
|
698 |
+
|
699 |
+
def cb_sign2map(a, var, index=None):
|
700 |
+
ret = {'varname': a}
|
701 |
+
ret['varname_i'] = ret['varname']
|
702 |
+
ret['ctype'] = getctype(var)
|
703 |
+
if ret['ctype'] in c2capi_map:
|
704 |
+
ret['atype'] = c2capi_map[ret['ctype']]
|
705 |
+
ret['elsize'] = get_elsize(var)
|
706 |
+
if ret['ctype'] in cformat_map:
|
707 |
+
ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
|
708 |
+
if isarray(var):
|
709 |
+
ret = dictappend(ret, getarrdims(a, var))
|
710 |
+
ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
|
711 |
+
if hasnote(var):
|
712 |
+
ret['note'] = var['note']
|
713 |
+
var['note'] = ['See elsewhere.']
|
714 |
+
return ret
|
715 |
+
|
716 |
+
|
717 |
+
def cb_routsign2map(rout, um):
|
718 |
+
"""
|
719 |
+
name,begintitle,endtitle,argname
|
720 |
+
ctype,rctype,maxnofargs,nofoptargs,returncptr
|
721 |
+
"""
|
722 |
+
ret = {'name': 'cb_%s_in_%s' % (rout['name'], um),
|
723 |
+
'returncptr': ''}
|
724 |
+
if isintent_callback(rout):
|
725 |
+
if '_' in rout['name']:
|
726 |
+
F_FUNC = 'F_FUNC_US'
|
727 |
+
else:
|
728 |
+
F_FUNC = 'F_FUNC'
|
729 |
+
ret['callbackname'] = '%s(%s,%s)' \
|
730 |
+
% (F_FUNC,
|
731 |
+
rout['name'].lower(),
|
732 |
+
rout['name'].upper(),
|
733 |
+
)
|
734 |
+
ret['static'] = 'extern'
|
735 |
+
else:
|
736 |
+
ret['callbackname'] = ret['name']
|
737 |
+
ret['static'] = 'static'
|
738 |
+
ret['argname'] = rout['name']
|
739 |
+
ret['begintitle'] = gentitle(ret['name'])
|
740 |
+
ret['endtitle'] = gentitle('end of %s' % ret['name'])
|
741 |
+
ret['ctype'] = getctype(rout)
|
742 |
+
ret['rctype'] = 'void'
|
743 |
+
if ret['ctype'] == 'string':
|
744 |
+
ret['rctype'] = 'void'
|
745 |
+
else:
|
746 |
+
ret['rctype'] = ret['ctype']
|
747 |
+
if ret['rctype'] != 'void':
|
748 |
+
if iscomplexfunction(rout):
|
749 |
+
ret['returncptr'] = """
|
750 |
+
#ifdef F2PY_CB_RETURNCOMPLEX
|
751 |
+
return_value=
|
752 |
+
#endif
|
753 |
+
"""
|
754 |
+
else:
|
755 |
+
ret['returncptr'] = 'return_value='
|
756 |
+
if ret['ctype'] in cformat_map:
|
757 |
+
ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
|
758 |
+
if isstringfunction(rout):
|
759 |
+
ret['strlength'] = getstrlength(rout)
|
760 |
+
if isfunction(rout):
|
761 |
+
if 'result' in rout:
|
762 |
+
a = rout['result']
|
763 |
+
else:
|
764 |
+
a = rout['name']
|
765 |
+
if hasnote(rout['vars'][a]):
|
766 |
+
ret['note'] = rout['vars'][a]['note']
|
767 |
+
rout['vars'][a]['note'] = ['See elsewhere.']
|
768 |
+
ret['rname'] = a
|
769 |
+
ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, rout)
|
770 |
+
if iscomplexfunction(rout):
|
771 |
+
ret['rctype'] = """
|
772 |
+
#ifdef F2PY_CB_RETURNCOMPLEX
|
773 |
+
#ctype#
|
774 |
+
#else
|
775 |
+
void
|
776 |
+
#endif
|
777 |
+
"""
|
778 |
+
else:
|
779 |
+
if hasnote(rout):
|
780 |
+
ret['note'] = rout['note']
|
781 |
+
rout['note'] = ['See elsewhere.']
|
782 |
+
nofargs = 0
|
783 |
+
nofoptargs = 0
|
784 |
+
if 'args' in rout and 'vars' in rout:
|
785 |
+
for a in rout['args']:
|
786 |
+
var = rout['vars'][a]
|
787 |
+
if l_or(isintent_in, isintent_inout)(var):
|
788 |
+
nofargs = nofargs + 1
|
789 |
+
if isoptional(var):
|
790 |
+
nofoptargs = nofoptargs + 1
|
791 |
+
ret['maxnofargs'] = repr(nofargs)
|
792 |
+
ret['nofoptargs'] = repr(nofoptargs)
|
793 |
+
if hasnote(rout) and isfunction(rout) and 'result' in rout:
|
794 |
+
ret['routnote'] = rout['note']
|
795 |
+
rout['note'] = ['See elsewhere.']
|
796 |
+
return ret
|
797 |
+
|
798 |
+
|
799 |
+
def common_sign2map(a, var): # obsolute
|
800 |
+
ret = {'varname': a, 'ctype': getctype(var)}
|
801 |
+
if isstringarray(var):
|
802 |
+
ret['ctype'] = 'char'
|
803 |
+
if ret['ctype'] in c2capi_map:
|
804 |
+
ret['atype'] = c2capi_map[ret['ctype']]
|
805 |
+
ret['elsize'] = get_elsize(var)
|
806 |
+
if ret['ctype'] in cformat_map:
|
807 |
+
ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
|
808 |
+
if isarray(var):
|
809 |
+
ret = dictappend(ret, getarrdims(a, var))
|
810 |
+
elif isstring(var):
|
811 |
+
ret['size'] = getstrlength(var)
|
812 |
+
ret['rank'] = '1'
|
813 |
+
ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
|
814 |
+
if hasnote(var):
|
815 |
+
ret['note'] = var['note']
|
816 |
+
var['note'] = ['See elsewhere.']
|
817 |
+
# for strings this returns 0-rank but actually is 1-rank
|
818 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Build call-back mechanism for f2py2e.
|
3 |
+
|
4 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
5 |
+
Copyright 2011 -- present NumPy Developers.
|
6 |
+
Permission to use, modify, and distribute this software is given under the
|
7 |
+
terms of the NumPy License.
|
8 |
+
|
9 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
10 |
+
"""
|
11 |
+
from . import __version__
|
12 |
+
from .auxfuncs import (
|
13 |
+
applyrules, debugcapi, dictappend, errmess, getargs, hasnote, isarray,
|
14 |
+
iscomplex, iscomplexarray, iscomplexfunction, isfunction, isintent_c,
|
15 |
+
isintent_hide, isintent_in, isintent_inout, isintent_nothide,
|
16 |
+
isintent_out, isoptional, isrequired, isscalar, isstring,
|
17 |
+
isstringfunction, issubroutine, l_and, l_not, l_or, outmess, replace,
|
18 |
+
stripcomma, throw_error
|
19 |
+
)
|
20 |
+
from . import cfuncs
|
21 |
+
|
22 |
+
f2py_version = __version__.version
|
23 |
+
|
24 |
+
|
25 |
+
################## Rules for callback function ##############
|
26 |
+
|
27 |
+
cb_routine_rules = {
|
28 |
+
'cbtypedefs': 'typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);',
|
29 |
+
'body': """
|
30 |
+
#begintitle#
|
31 |
+
typedef struct {
|
32 |
+
PyObject *capi;
|
33 |
+
PyTupleObject *args_capi;
|
34 |
+
int nofargs;
|
35 |
+
jmp_buf jmpbuf;
|
36 |
+
} #name#_t;
|
37 |
+
|
38 |
+
#if defined(F2PY_THREAD_LOCAL_DECL) && !defined(F2PY_USE_PYTHON_TLS)
|
39 |
+
|
40 |
+
static F2PY_THREAD_LOCAL_DECL #name#_t *_active_#name# = NULL;
|
41 |
+
|
42 |
+
static #name#_t *swap_active_#name#(#name#_t *ptr) {
|
43 |
+
#name#_t *prev = _active_#name#;
|
44 |
+
_active_#name# = ptr;
|
45 |
+
return prev;
|
46 |
+
}
|
47 |
+
|
48 |
+
static #name#_t *get_active_#name#(void) {
|
49 |
+
return _active_#name#;
|
50 |
+
}
|
51 |
+
|
52 |
+
#else
|
53 |
+
|
54 |
+
static #name#_t *swap_active_#name#(#name#_t *ptr) {
|
55 |
+
char *key = "__f2py_cb_#name#";
|
56 |
+
return (#name#_t *)F2PySwapThreadLocalCallbackPtr(key, ptr);
|
57 |
+
}
|
58 |
+
|
59 |
+
static #name#_t *get_active_#name#(void) {
|
60 |
+
char *key = "__f2py_cb_#name#";
|
61 |
+
return (#name#_t *)F2PyGetThreadLocalCallbackPtr(key);
|
62 |
+
}
|
63 |
+
|
64 |
+
#endif
|
65 |
+
|
66 |
+
/*typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);*/
|
67 |
+
#static# #rctype# #callbackname# (#optargs##args##strarglens##noargs#) {
|
68 |
+
#name#_t cb_local = { NULL, NULL, 0 };
|
69 |
+
#name#_t *cb = NULL;
|
70 |
+
PyTupleObject *capi_arglist = NULL;
|
71 |
+
PyObject *capi_return = NULL;
|
72 |
+
PyObject *capi_tmp = NULL;
|
73 |
+
PyObject *capi_arglist_list = NULL;
|
74 |
+
int capi_j,capi_i = 0;
|
75 |
+
int capi_longjmp_ok = 1;
|
76 |
+
#decl#
|
77 |
+
#ifdef F2PY_REPORT_ATEXIT
|
78 |
+
f2py_cb_start_clock();
|
79 |
+
#endif
|
80 |
+
cb = get_active_#name#();
|
81 |
+
if (cb == NULL) {
|
82 |
+
capi_longjmp_ok = 0;
|
83 |
+
cb = &cb_local;
|
84 |
+
}
|
85 |
+
capi_arglist = cb->args_capi;
|
86 |
+
CFUNCSMESS(\"cb:Call-back function #name# (maxnofargs=#maxnofargs#(-#nofoptargs#))\\n\");
|
87 |
+
CFUNCSMESSPY(\"cb:#name#_capi=\",cb->capi);
|
88 |
+
if (cb->capi==NULL) {
|
89 |
+
capi_longjmp_ok = 0;
|
90 |
+
cb->capi = PyObject_GetAttrString(#modulename#_module,\"#argname#\");
|
91 |
+
CFUNCSMESSPY(\"cb:#name#_capi=\",cb->capi);
|
92 |
+
}
|
93 |
+
if (cb->capi==NULL) {
|
94 |
+
PyErr_SetString(#modulename#_error,\"cb: Callback #argname# not defined (as an argument or module #modulename# attribute).\\n\");
|
95 |
+
goto capi_fail;
|
96 |
+
}
|
97 |
+
if (F2PyCapsule_Check(cb->capi)) {
|
98 |
+
#name#_typedef #name#_cptr;
|
99 |
+
#name#_cptr = F2PyCapsule_AsVoidPtr(cb->capi);
|
100 |
+
#returncptr#(*#name#_cptr)(#optargs_nm##args_nm##strarglens_nm#);
|
101 |
+
#return#
|
102 |
+
}
|
103 |
+
if (capi_arglist==NULL) {
|
104 |
+
capi_longjmp_ok = 0;
|
105 |
+
capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#argname#_extra_args\");
|
106 |
+
if (capi_tmp) {
|
107 |
+
capi_arglist = (PyTupleObject *)PySequence_Tuple(capi_tmp);
|
108 |
+
Py_DECREF(capi_tmp);
|
109 |
+
if (capi_arglist==NULL) {
|
110 |
+
PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#argname#_extra_args to tuple.\\n\");
|
111 |
+
goto capi_fail;
|
112 |
+
}
|
113 |
+
} else {
|
114 |
+
PyErr_Clear();
|
115 |
+
capi_arglist = (PyTupleObject *)Py_BuildValue(\"()\");
|
116 |
+
}
|
117 |
+
}
|
118 |
+
if (capi_arglist == NULL) {
|
119 |
+
PyErr_SetString(#modulename#_error,\"Callback #argname# argument list is not set.\\n\");
|
120 |
+
goto capi_fail;
|
121 |
+
}
|
122 |
+
#setdims#
|
123 |
+
#ifdef PYPY_VERSION
|
124 |
+
#define CAPI_ARGLIST_SETITEM(idx, value) PyList_SetItem((PyObject *)capi_arglist_list, idx, value)
|
125 |
+
capi_arglist_list = PySequence_List(capi_arglist);
|
126 |
+
if (capi_arglist_list == NULL) goto capi_fail;
|
127 |
+
#else
|
128 |
+
#define CAPI_ARGLIST_SETITEM(idx, value) PyTuple_SetItem((PyObject *)capi_arglist, idx, value)
|
129 |
+
#endif
|
130 |
+
#pyobjfrom#
|
131 |
+
#undef CAPI_ARGLIST_SETITEM
|
132 |
+
#ifdef PYPY_VERSION
|
133 |
+
CFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist_list);
|
134 |
+
#else
|
135 |
+
CFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist);
|
136 |
+
#endif
|
137 |
+
CFUNCSMESS(\"cb:Call-back calling Python function #argname#.\\n\");
|
138 |
+
#ifdef F2PY_REPORT_ATEXIT
|
139 |
+
f2py_cb_start_call_clock();
|
140 |
+
#endif
|
141 |
+
#ifdef PYPY_VERSION
|
142 |
+
capi_return = PyObject_CallObject(cb->capi,(PyObject *)capi_arglist_list);
|
143 |
+
Py_DECREF(capi_arglist_list);
|
144 |
+
capi_arglist_list = NULL;
|
145 |
+
#else
|
146 |
+
capi_return = PyObject_CallObject(cb->capi,(PyObject *)capi_arglist);
|
147 |
+
#endif
|
148 |
+
#ifdef F2PY_REPORT_ATEXIT
|
149 |
+
f2py_cb_stop_call_clock();
|
150 |
+
#endif
|
151 |
+
CFUNCSMESSPY(\"cb:capi_return=\",capi_return);
|
152 |
+
if (capi_return == NULL) {
|
153 |
+
fprintf(stderr,\"capi_return is NULL\\n\");
|
154 |
+
goto capi_fail;
|
155 |
+
}
|
156 |
+
if (capi_return == Py_None) {
|
157 |
+
Py_DECREF(capi_return);
|
158 |
+
capi_return = Py_BuildValue(\"()\");
|
159 |
+
}
|
160 |
+
else if (!PyTuple_Check(capi_return)) {
|
161 |
+
capi_return = Py_BuildValue(\"(N)\",capi_return);
|
162 |
+
}
|
163 |
+
capi_j = PyTuple_Size(capi_return);
|
164 |
+
capi_i = 0;
|
165 |
+
#frompyobj#
|
166 |
+
CFUNCSMESS(\"cb:#name#:successful\\n\");
|
167 |
+
Py_DECREF(capi_return);
|
168 |
+
#ifdef F2PY_REPORT_ATEXIT
|
169 |
+
f2py_cb_stop_clock();
|
170 |
+
#endif
|
171 |
+
goto capi_return_pt;
|
172 |
+
capi_fail:
|
173 |
+
fprintf(stderr,\"Call-back #name# failed.\\n\");
|
174 |
+
Py_XDECREF(capi_return);
|
175 |
+
Py_XDECREF(capi_arglist_list);
|
176 |
+
if (capi_longjmp_ok) {
|
177 |
+
longjmp(cb->jmpbuf,-1);
|
178 |
+
}
|
179 |
+
capi_return_pt:
|
180 |
+
;
|
181 |
+
#return#
|
182 |
+
}
|
183 |
+
#endtitle#
|
184 |
+
""",
|
185 |
+
'need': ['setjmp.h', 'CFUNCSMESS', 'F2PY_THREAD_LOCAL_DECL'],
|
186 |
+
'maxnofargs': '#maxnofargs#',
|
187 |
+
'nofoptargs': '#nofoptargs#',
|
188 |
+
'docstr': """\
|
189 |
+
def #argname#(#docsignature#): return #docreturn#\\n\\
|
190 |
+
#docstrsigns#""",
|
191 |
+
'latexdocstr': """
|
192 |
+
{{}\\verb@def #argname#(#latexdocsignature#): return #docreturn#@{}}
|
193 |
+
#routnote#
|
194 |
+
|
195 |
+
#latexdocstrsigns#""",
|
196 |
+
'docstrshort': 'def #argname#(#docsignature#): return #docreturn#'
|
197 |
+
}
|
198 |
+
cb_rout_rules = [
|
199 |
+
{ # Init
|
200 |
+
'separatorsfor': {'decl': '\n',
|
201 |
+
'args': ',', 'optargs': '', 'pyobjfrom': '\n', 'freemem': '\n',
|
202 |
+
'args_td': ',', 'optargs_td': '',
|
203 |
+
'args_nm': ',', 'optargs_nm': '',
|
204 |
+
'frompyobj': '\n', 'setdims': '\n',
|
205 |
+
'docstrsigns': '\\n"\n"',
|
206 |
+
'latexdocstrsigns': '\n',
|
207 |
+
'latexdocstrreq': '\n', 'latexdocstropt': '\n',
|
208 |
+
'latexdocstrout': '\n', 'latexdocstrcbs': '\n',
|
209 |
+
},
|
210 |
+
'decl': '/*decl*/', 'pyobjfrom': '/*pyobjfrom*/', 'frompyobj': '/*frompyobj*/',
|
211 |
+
'args': [], 'optargs': '', 'return': '', 'strarglens': '', 'freemem': '/*freemem*/',
|
212 |
+
'args_td': [], 'optargs_td': '', 'strarglens_td': '',
|
213 |
+
'args_nm': [], 'optargs_nm': '', 'strarglens_nm': '',
|
214 |
+
'noargs': '',
|
215 |
+
'setdims': '/*setdims*/',
|
216 |
+
'docstrsigns': '', 'latexdocstrsigns': '',
|
217 |
+
'docstrreq': ' Required arguments:',
|
218 |
+
'docstropt': ' Optional arguments:',
|
219 |
+
'docstrout': ' Return objects:',
|
220 |
+
'docstrcbs': ' Call-back functions:',
|
221 |
+
'docreturn': '', 'docsign': '', 'docsignopt': '',
|
222 |
+
'latexdocstrreq': '\\noindent Required arguments:',
|
223 |
+
'latexdocstropt': '\\noindent Optional arguments:',
|
224 |
+
'latexdocstrout': '\\noindent Return objects:',
|
225 |
+
'latexdocstrcbs': '\\noindent Call-back functions:',
|
226 |
+
'routnote': {hasnote: '--- #note#', l_not(hasnote): ''},
|
227 |
+
}, { # Function
|
228 |
+
'decl': ' #ctype# return_value = 0;',
|
229 |
+
'frompyobj': [
|
230 |
+
{debugcapi: ' CFUNCSMESS("cb:Getting return_value->");'},
|
231 |
+
'''\
|
232 |
+
if (capi_j>capi_i) {
|
233 |
+
GETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,
|
234 |
+
"#ctype#_from_pyobj failed in converting return_value of"
|
235 |
+
" call-back function #name# to C #ctype#\\n");
|
236 |
+
} else {
|
237 |
+
fprintf(stderr,"Warning: call-back function #name# did not provide"
|
238 |
+
" return value (index=%d, type=#ctype#)\\n",capi_i);
|
239 |
+
}''',
|
240 |
+
{debugcapi:
|
241 |
+
' fprintf(stderr,"#showvalueformat#.\\n",return_value);'}
|
242 |
+
],
|
243 |
+
'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, 'GETSCALARFROMPYTUPLE'],
|
244 |
+
'return': ' return return_value;',
|
245 |
+
'_check': l_and(isfunction, l_not(isstringfunction), l_not(iscomplexfunction))
|
246 |
+
},
|
247 |
+
{ # String function
|
248 |
+
'pyobjfrom': {debugcapi: ' fprintf(stderr,"debug-capi:cb:#name#:%d:\\n",return_value_len);'},
|
249 |
+
'args': '#ctype# return_value,int return_value_len',
|
250 |
+
'args_nm': 'return_value,&return_value_len',
|
251 |
+
'args_td': '#ctype# ,int',
|
252 |
+
'frompyobj': [
|
253 |
+
{debugcapi: ' CFUNCSMESS("cb:Getting return_value->\\"");'},
|
254 |
+
"""\
|
255 |
+
if (capi_j>capi_i) {
|
256 |
+
GETSTRFROMPYTUPLE(capi_return,capi_i++,return_value,return_value_len);
|
257 |
+
} else {
|
258 |
+
fprintf(stderr,"Warning: call-back function #name# did not provide"
|
259 |
+
" return value (index=%d, type=#ctype#)\\n",capi_i);
|
260 |
+
}""",
|
261 |
+
{debugcapi:
|
262 |
+
' fprintf(stderr,"#showvalueformat#\\".\\n",return_value);'}
|
263 |
+
],
|
264 |
+
'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'},
|
265 |
+
'string.h', 'GETSTRFROMPYTUPLE'],
|
266 |
+
'return': 'return;',
|
267 |
+
'_check': isstringfunction
|
268 |
+
},
|
269 |
+
{ # Complex function
|
270 |
+
'optargs': """
|
271 |
+
#ifndef F2PY_CB_RETURNCOMPLEX
|
272 |
+
#ctype# *return_value
|
273 |
+
#endif
|
274 |
+
""",
|
275 |
+
'optargs_nm': """
|
276 |
+
#ifndef F2PY_CB_RETURNCOMPLEX
|
277 |
+
return_value
|
278 |
+
#endif
|
279 |
+
""",
|
280 |
+
'optargs_td': """
|
281 |
+
#ifndef F2PY_CB_RETURNCOMPLEX
|
282 |
+
#ctype# *
|
283 |
+
#endif
|
284 |
+
""",
|
285 |
+
'decl': """
|
286 |
+
#ifdef F2PY_CB_RETURNCOMPLEX
|
287 |
+
#ctype# return_value = {0, 0};
|
288 |
+
#endif
|
289 |
+
""",
|
290 |
+
'frompyobj': [
|
291 |
+
{debugcapi: ' CFUNCSMESS("cb:Getting return_value->");'},
|
292 |
+
"""\
|
293 |
+
if (capi_j>capi_i) {
|
294 |
+
#ifdef F2PY_CB_RETURNCOMPLEX
|
295 |
+
GETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,
|
296 |
+
\"#ctype#_from_pyobj failed in converting return_value of call-back\"
|
297 |
+
\" function #name# to C #ctype#\\n\");
|
298 |
+
#else
|
299 |
+
GETSCALARFROMPYTUPLE(capi_return,capi_i++,return_value,#ctype#,
|
300 |
+
\"#ctype#_from_pyobj failed in converting return_value of call-back\"
|
301 |
+
\" function #name# to C #ctype#\\n\");
|
302 |
+
#endif
|
303 |
+
} else {
|
304 |
+
fprintf(stderr,
|
305 |
+
\"Warning: call-back function #name# did not provide\"
|
306 |
+
\" return value (index=%d, type=#ctype#)\\n\",capi_i);
|
307 |
+
}""",
|
308 |
+
{debugcapi: """\
|
309 |
+
#ifdef F2PY_CB_RETURNCOMPLEX
|
310 |
+
fprintf(stderr,\"#showvalueformat#.\\n\",(return_value).r,(return_value).i);
|
311 |
+
#else
|
312 |
+
fprintf(stderr,\"#showvalueformat#.\\n\",(*return_value).r,(*return_value).i);
|
313 |
+
#endif
|
314 |
+
"""}
|
315 |
+
],
|
316 |
+
'return': """
|
317 |
+
#ifdef F2PY_CB_RETURNCOMPLEX
|
318 |
+
return return_value;
|
319 |
+
#else
|
320 |
+
return;
|
321 |
+
#endif
|
322 |
+
""",
|
323 |
+
'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'},
|
324 |
+
'string.h', 'GETSCALARFROMPYTUPLE', '#ctype#'],
|
325 |
+
'_check': iscomplexfunction
|
326 |
+
},
|
327 |
+
{'docstrout': ' #pydocsignout#',
|
328 |
+
'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}',
|
329 |
+
{hasnote: '--- #note#'}],
|
330 |
+
'docreturn': '#rname#,',
|
331 |
+
'_check': isfunction},
|
332 |
+
{'_check': issubroutine, 'return': 'return;'}
|
333 |
+
]
|
334 |
+
|
335 |
+
cb_arg_rules = [
|
336 |
+
{ # Doc
|
337 |
+
'docstropt': {l_and(isoptional, isintent_nothide): ' #pydocsign#'},
|
338 |
+
'docstrreq': {l_and(isrequired, isintent_nothide): ' #pydocsign#'},
|
339 |
+
'docstrout': {isintent_out: ' #pydocsignout#'},
|
340 |
+
'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}',
|
341 |
+
{hasnote: '--- #note#'}]},
|
342 |
+
'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}',
|
343 |
+
{hasnote: '--- #note#'}]},
|
344 |
+
'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}',
|
345 |
+
{l_and(hasnote, isintent_hide): '--- #note#',
|
346 |
+
l_and(hasnote, isintent_nothide): '--- See above.'}]},
|
347 |
+
'docsign': {l_and(isrequired, isintent_nothide): '#varname#,'},
|
348 |
+
'docsignopt': {l_and(isoptional, isintent_nothide): '#varname#,'},
|
349 |
+
'depend': ''
|
350 |
+
},
|
351 |
+
{
|
352 |
+
'args': {
|
353 |
+
l_and(isscalar, isintent_c): '#ctype# #varname_i#',
|
354 |
+
l_and(isscalar, l_not(isintent_c)): '#ctype# *#varname_i#_cb_capi',
|
355 |
+
isarray: '#ctype# *#varname_i#',
|
356 |
+
isstring: '#ctype# #varname_i#'
|
357 |
+
},
|
358 |
+
'args_nm': {
|
359 |
+
l_and(isscalar, isintent_c): '#varname_i#',
|
360 |
+
l_and(isscalar, l_not(isintent_c)): '#varname_i#_cb_capi',
|
361 |
+
isarray: '#varname_i#',
|
362 |
+
isstring: '#varname_i#'
|
363 |
+
},
|
364 |
+
'args_td': {
|
365 |
+
l_and(isscalar, isintent_c): '#ctype#',
|
366 |
+
l_and(isscalar, l_not(isintent_c)): '#ctype# *',
|
367 |
+
isarray: '#ctype# *',
|
368 |
+
isstring: '#ctype#'
|
369 |
+
},
|
370 |
+
'need': {l_or(isscalar, isarray, isstring): '#ctype#'},
|
371 |
+
# untested with multiple args
|
372 |
+
'strarglens': {isstring: ',int #varname_i#_cb_len'},
|
373 |
+
'strarglens_td': {isstring: ',int'}, # untested with multiple args
|
374 |
+
# untested with multiple args
|
375 |
+
'strarglens_nm': {isstring: ',#varname_i#_cb_len'},
|
376 |
+
},
|
377 |
+
{ # Scalars
|
378 |
+
'decl': {l_not(isintent_c): ' #ctype# #varname_i#=(*#varname_i#_cb_capi);'},
|
379 |
+
'error': {l_and(isintent_c, isintent_out,
|
380 |
+
throw_error('intent(c,out) is forbidden for callback scalar arguments')):
|
381 |
+
''},
|
382 |
+
'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->");'},
|
383 |
+
{isintent_out:
|
384 |
+
' if (capi_j>capi_i)\n GETSCALARFROMPYTUPLE(capi_return,capi_i++,#varname_i#_cb_capi,#ctype#,"#ctype#_from_pyobj failed in converting argument #varname# of call-back function #name# to C #ctype#\\n");'},
|
385 |
+
{l_and(debugcapi, l_and(l_not(iscomplex), isintent_c)):
|
386 |
+
' fprintf(stderr,"#showvalueformat#.\\n",#varname_i#);'},
|
387 |
+
{l_and(debugcapi, l_and(l_not(iscomplex), l_not( isintent_c))):
|
388 |
+
' fprintf(stderr,"#showvalueformat#.\\n",*#varname_i#_cb_capi);'},
|
389 |
+
{l_and(debugcapi, l_and(iscomplex, isintent_c)):
|
390 |
+
' fprintf(stderr,"#showvalueformat#.\\n",(#varname_i#).r,(#varname_i#).i);'},
|
391 |
+
{l_and(debugcapi, l_and(iscomplex, l_not( isintent_c))):
|
392 |
+
' fprintf(stderr,"#showvalueformat#.\\n",(*#varname_i#_cb_capi).r,(*#varname_i#_cb_capi).i);'},
|
393 |
+
],
|
394 |
+
'need': [{isintent_out: ['#ctype#_from_pyobj', 'GETSCALARFROMPYTUPLE']},
|
395 |
+
{debugcapi: 'CFUNCSMESS'}],
|
396 |
+
'_check': isscalar
|
397 |
+
}, {
|
398 |
+
'pyobjfrom': [{isintent_in: """\
|
399 |
+
if (cb->nofargs>capi_i)
|
400 |
+
if (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1(#varname_i#)))
|
401 |
+
goto capi_fail;"""},
|
402 |
+
{isintent_inout: """\
|
403 |
+
if (cb->nofargs>capi_i)
|
404 |
+
if (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#_cb_capi)))
|
405 |
+
goto capi_fail;"""}],
|
406 |
+
'need': [{isintent_in: 'pyobj_from_#ctype#1'},
|
407 |
+
{isintent_inout: 'pyarr_from_p_#ctype#1'},
|
408 |
+
{iscomplex: '#ctype#'}],
|
409 |
+
'_check': l_and(isscalar, isintent_nothide),
|
410 |
+
'_optional': ''
|
411 |
+
}, { # String
|
412 |
+
'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->\\"");'},
|
413 |
+
""" if (capi_j>capi_i)
|
414 |
+
GETSTRFROMPYTUPLE(capi_return,capi_i++,#varname_i#,#varname_i#_cb_len);""",
|
415 |
+
{debugcapi:
|
416 |
+
' fprintf(stderr,"#showvalueformat#\\":%d:.\\n",#varname_i#,#varname_i#_cb_len);'},
|
417 |
+
],
|
418 |
+
'need': ['#ctype#', 'GETSTRFROMPYTUPLE',
|
419 |
+
{debugcapi: 'CFUNCSMESS'}, 'string.h'],
|
420 |
+
'_check': l_and(isstring, isintent_out)
|
421 |
+
}, {
|
422 |
+
'pyobjfrom': [
|
423 |
+
{debugcapi:
|
424 |
+
(' fprintf(stderr,"debug-capi:cb:#varname#=#showvalueformat#:'
|
425 |
+
'%d:\\n",#varname_i#,#varname_i#_cb_len);')},
|
426 |
+
{isintent_in: """\
|
427 |
+
if (cb->nofargs>capi_i)
|
428 |
+
if (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1size(#varname_i#,#varname_i#_cb_len)))
|
429 |
+
goto capi_fail;"""},
|
430 |
+
{isintent_inout: """\
|
431 |
+
if (cb->nofargs>capi_i) {
|
432 |
+
int #varname_i#_cb_dims[] = {#varname_i#_cb_len};
|
433 |
+
if (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#,#varname_i#_cb_dims)))
|
434 |
+
goto capi_fail;
|
435 |
+
}"""}],
|
436 |
+
'need': [{isintent_in: 'pyobj_from_#ctype#1size'},
|
437 |
+
{isintent_inout: 'pyarr_from_p_#ctype#1'}],
|
438 |
+
'_check': l_and(isstring, isintent_nothide),
|
439 |
+
'_optional': ''
|
440 |
+
},
|
441 |
+
# Array ...
|
442 |
+
{
|
443 |
+
'decl': ' npy_intp #varname_i#_Dims[#rank#] = {#rank*[-1]#};',
|
444 |
+
'setdims': ' #cbsetdims#;',
|
445 |
+
'_check': isarray,
|
446 |
+
'_depend': ''
|
447 |
+
},
|
448 |
+
{
|
449 |
+
'pyobjfrom': [{debugcapi: ' fprintf(stderr,"debug-capi:cb:#varname#\\n");'},
|
450 |
+
{isintent_c: """\
|
451 |
+
if (cb->nofargs>capi_i) {
|
452 |
+
/* tmp_arr will be inserted to capi_arglist_list that will be
|
453 |
+
destroyed when leaving callback function wrapper together
|
454 |
+
with tmp_arr. */
|
455 |
+
PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,
|
456 |
+
#rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,#elsize#,
|
457 |
+
NPY_ARRAY_CARRAY,NULL);
|
458 |
+
""",
|
459 |
+
l_not(isintent_c): """\
|
460 |
+
if (cb->nofargs>capi_i) {
|
461 |
+
/* tmp_arr will be inserted to capi_arglist_list that will be
|
462 |
+
destroyed when leaving callback function wrapper together
|
463 |
+
with tmp_arr. */
|
464 |
+
PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,
|
465 |
+
#rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,#elsize#,
|
466 |
+
NPY_ARRAY_FARRAY,NULL);
|
467 |
+
""",
|
468 |
+
},
|
469 |
+
"""
|
470 |
+
if (tmp_arr==NULL)
|
471 |
+
goto capi_fail;
|
472 |
+
if (CAPI_ARGLIST_SETITEM(capi_i++,(PyObject *)tmp_arr))
|
473 |
+
goto capi_fail;
|
474 |
+
}"""],
|
475 |
+
'_check': l_and(isarray, isintent_nothide, l_or(isintent_in, isintent_inout)),
|
476 |
+
'_optional': '',
|
477 |
+
}, {
|
478 |
+
'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->");'},
|
479 |
+
""" if (capi_j>capi_i) {
|
480 |
+
PyArrayObject *rv_cb_arr = NULL;
|
481 |
+
if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail;
|
482 |
+
rv_cb_arr = array_from_pyobj(#atype#,#varname_i#_Dims,#rank#,F2PY_INTENT_IN""",
|
483 |
+
{isintent_c: '|F2PY_INTENT_C'},
|
484 |
+
""",capi_tmp);
|
485 |
+
if (rv_cb_arr == NULL) {
|
486 |
+
fprintf(stderr,\"rv_cb_arr is NULL\\n\");
|
487 |
+
goto capi_fail;
|
488 |
+
}
|
489 |
+
MEMCOPY(#varname_i#,PyArray_DATA(rv_cb_arr),PyArray_NBYTES(rv_cb_arr));
|
490 |
+
if (capi_tmp != (PyObject *)rv_cb_arr) {
|
491 |
+
Py_DECREF(rv_cb_arr);
|
492 |
+
}
|
493 |
+
}""",
|
494 |
+
{debugcapi: ' fprintf(stderr,"<-.\\n");'},
|
495 |
+
],
|
496 |
+
'need': ['MEMCOPY', {iscomplexarray: '#ctype#'}],
|
497 |
+
'_check': l_and(isarray, isintent_out)
|
498 |
+
}, {
|
499 |
+
'docreturn': '#varname#,',
|
500 |
+
'_check': isintent_out
|
501 |
+
}
|
502 |
+
]
|
503 |
+
|
504 |
+
################## Build call-back module #############
|
505 |
+
cb_map = {}
|
506 |
+
|
507 |
+
|
508 |
+
def buildcallbacks(m):
|
509 |
+
cb_map[m['name']] = []
|
510 |
+
for bi in m['body']:
|
511 |
+
if bi['block'] == 'interface':
|
512 |
+
for b in bi['body']:
|
513 |
+
if b:
|
514 |
+
buildcallback(b, m['name'])
|
515 |
+
else:
|
516 |
+
errmess('warning: empty body for %s\n' % (m['name']))
|
517 |
+
|
518 |
+
|
519 |
+
def buildcallback(rout, um):
|
520 |
+
from . import capi_maps
|
521 |
+
|
522 |
+
outmess(' Constructing call-back function "cb_%s_in_%s"\n' %
|
523 |
+
(rout['name'], um))
|
524 |
+
args, depargs = getargs(rout)
|
525 |
+
capi_maps.depargs = depargs
|
526 |
+
var = rout['vars']
|
527 |
+
vrd = capi_maps.cb_routsign2map(rout, um)
|
528 |
+
rd = dictappend({}, vrd)
|
529 |
+
cb_map[um].append([rout['name'], rd['name']])
|
530 |
+
for r in cb_rout_rules:
|
531 |
+
if ('_check' in r and r['_check'](rout)) or ('_check' not in r):
|
532 |
+
ar = applyrules(r, vrd, rout)
|
533 |
+
rd = dictappend(rd, ar)
|
534 |
+
savevrd = {}
|
535 |
+
for i, a in enumerate(args):
|
536 |
+
vrd = capi_maps.cb_sign2map(a, var[a], index=i)
|
537 |
+
savevrd[a] = vrd
|
538 |
+
for r in cb_arg_rules:
|
539 |
+
if '_depend' in r:
|
540 |
+
continue
|
541 |
+
if '_optional' in r and isoptional(var[a]):
|
542 |
+
continue
|
543 |
+
if ('_check' in r and r['_check'](var[a])) or ('_check' not in r):
|
544 |
+
ar = applyrules(r, vrd, var[a])
|
545 |
+
rd = dictappend(rd, ar)
|
546 |
+
if '_break' in r:
|
547 |
+
break
|
548 |
+
for a in args:
|
549 |
+
vrd = savevrd[a]
|
550 |
+
for r in cb_arg_rules:
|
551 |
+
if '_depend' in r:
|
552 |
+
continue
|
553 |
+
if ('_optional' not in r) or ('_optional' in r and isrequired(var[a])):
|
554 |
+
continue
|
555 |
+
if ('_check' in r and r['_check'](var[a])) or ('_check' not in r):
|
556 |
+
ar = applyrules(r, vrd, var[a])
|
557 |
+
rd = dictappend(rd, ar)
|
558 |
+
if '_break' in r:
|
559 |
+
break
|
560 |
+
for a in depargs:
|
561 |
+
vrd = savevrd[a]
|
562 |
+
for r in cb_arg_rules:
|
563 |
+
if '_depend' not in r:
|
564 |
+
continue
|
565 |
+
if '_optional' in r:
|
566 |
+
continue
|
567 |
+
if ('_check' in r and r['_check'](var[a])) or ('_check' not in r):
|
568 |
+
ar = applyrules(r, vrd, var[a])
|
569 |
+
rd = dictappend(rd, ar)
|
570 |
+
if '_break' in r:
|
571 |
+
break
|
572 |
+
if 'args' in rd and 'optargs' in rd:
|
573 |
+
if isinstance(rd['optargs'], list):
|
574 |
+
rd['optargs'] = rd['optargs'] + ["""
|
575 |
+
#ifndef F2PY_CB_RETURNCOMPLEX
|
576 |
+
,
|
577 |
+
#endif
|
578 |
+
"""]
|
579 |
+
rd['optargs_nm'] = rd['optargs_nm'] + ["""
|
580 |
+
#ifndef F2PY_CB_RETURNCOMPLEX
|
581 |
+
,
|
582 |
+
#endif
|
583 |
+
"""]
|
584 |
+
rd['optargs_td'] = rd['optargs_td'] + ["""
|
585 |
+
#ifndef F2PY_CB_RETURNCOMPLEX
|
586 |
+
,
|
587 |
+
#endif
|
588 |
+
"""]
|
589 |
+
if isinstance(rd['docreturn'], list):
|
590 |
+
rd['docreturn'] = stripcomma(
|
591 |
+
replace('#docreturn#', {'docreturn': rd['docreturn']}))
|
592 |
+
optargs = stripcomma(replace('#docsignopt#',
|
593 |
+
{'docsignopt': rd['docsignopt']}
|
594 |
+
))
|
595 |
+
if optargs == '':
|
596 |
+
rd['docsignature'] = stripcomma(
|
597 |
+
replace('#docsign#', {'docsign': rd['docsign']}))
|
598 |
+
else:
|
599 |
+
rd['docsignature'] = replace('#docsign#[#docsignopt#]',
|
600 |
+
{'docsign': rd['docsign'],
|
601 |
+
'docsignopt': optargs,
|
602 |
+
})
|
603 |
+
rd['latexdocsignature'] = rd['docsignature'].replace('_', '\\_')
|
604 |
+
rd['latexdocsignature'] = rd['latexdocsignature'].replace(',', ', ')
|
605 |
+
rd['docstrsigns'] = []
|
606 |
+
rd['latexdocstrsigns'] = []
|
607 |
+
for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']:
|
608 |
+
if k in rd and isinstance(rd[k], list):
|
609 |
+
rd['docstrsigns'] = rd['docstrsigns'] + rd[k]
|
610 |
+
k = 'latex' + k
|
611 |
+
if k in rd and isinstance(rd[k], list):
|
612 |
+
rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] +\
|
613 |
+
['\\begin{description}'] + rd[k][1:] +\
|
614 |
+
['\\end{description}']
|
615 |
+
if 'args' not in rd:
|
616 |
+
rd['args'] = ''
|
617 |
+
rd['args_td'] = ''
|
618 |
+
rd['args_nm'] = ''
|
619 |
+
if not (rd.get('args') or rd.get('optargs') or rd.get('strarglens')):
|
620 |
+
rd['noargs'] = 'void'
|
621 |
+
|
622 |
+
ar = applyrules(cb_routine_rules, rd)
|
623 |
+
cfuncs.callbacks[rd['name']] = ar['body']
|
624 |
+
if isinstance(ar['need'], str):
|
625 |
+
ar['need'] = [ar['need']]
|
626 |
+
|
627 |
+
if 'need' in rd:
|
628 |
+
for t in cfuncs.typedefs.keys():
|
629 |
+
if t in rd['need']:
|
630 |
+
ar['need'].append(t)
|
631 |
+
|
632 |
+
cfuncs.typedefs_generated[rd['name'] + '_typedef'] = ar['cbtypedefs']
|
633 |
+
ar['need'].append(rd['name'] + '_typedef')
|
634 |
+
cfuncs.needs[rd['name']] = ar['need']
|
635 |
+
|
636 |
+
capi_maps.lcb2_map[rd['name']] = {'maxnofargs': ar['maxnofargs'],
|
637 |
+
'nofoptargs': ar['nofoptargs'],
|
638 |
+
'docstr': ar['docstr'],
|
639 |
+
'latexdocstr': ar['latexdocstr'],
|
640 |
+
'argname': rd['argname']
|
641 |
+
}
|
642 |
+
outmess(' %s\n' % (ar['docstrshort']))
|
643 |
+
return
|
644 |
+
################## Build call-back function #############
|
venv/lib/python3.10/site-packages/numpy/f2py/cfuncs.py
ADDED
@@ -0,0 +1,1536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
C declarations, CPP macros, and C functions for f2py2e.
|
4 |
+
Only required declarations/macros/functions will be used.
|
5 |
+
|
6 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
7 |
+
Copyright 2011 -- present NumPy Developers.
|
8 |
+
Permission to use, modify, and distribute this software is given under the
|
9 |
+
terms of the NumPy License.
|
10 |
+
|
11 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
12 |
+
"""
|
13 |
+
import sys
|
14 |
+
import copy
|
15 |
+
|
16 |
+
from . import __version__
|
17 |
+
|
18 |
+
f2py_version = __version__.version
|
19 |
+
errmess = sys.stderr.write
|
20 |
+
|
21 |
+
##################### Definitions ##################
|
22 |
+
|
23 |
+
outneeds = {'includes0': [], 'includes': [], 'typedefs': [], 'typedefs_generated': [],
|
24 |
+
'userincludes': [],
|
25 |
+
'cppmacros': [], 'cfuncs': [], 'callbacks': [], 'f90modhooks': [],
|
26 |
+
'commonhooks': []}
|
27 |
+
needs = {}
|
28 |
+
includes0 = {'includes0': '/*need_includes0*/'}
|
29 |
+
includes = {'includes': '/*need_includes*/'}
|
30 |
+
userincludes = {'userincludes': '/*need_userincludes*/'}
|
31 |
+
typedefs = {'typedefs': '/*need_typedefs*/'}
|
32 |
+
typedefs_generated = {'typedefs_generated': '/*need_typedefs_generated*/'}
|
33 |
+
cppmacros = {'cppmacros': '/*need_cppmacros*/'}
|
34 |
+
cfuncs = {'cfuncs': '/*need_cfuncs*/'}
|
35 |
+
callbacks = {'callbacks': '/*need_callbacks*/'}
|
36 |
+
f90modhooks = {'f90modhooks': '/*need_f90modhooks*/',
|
37 |
+
'initf90modhooksstatic': '/*initf90modhooksstatic*/',
|
38 |
+
'initf90modhooksdynamic': '/*initf90modhooksdynamic*/',
|
39 |
+
}
|
40 |
+
commonhooks = {'commonhooks': '/*need_commonhooks*/',
|
41 |
+
'initcommonhooks': '/*need_initcommonhooks*/',
|
42 |
+
}
|
43 |
+
|
44 |
+
############ Includes ###################
|
45 |
+
|
46 |
+
includes0['math.h'] = '#include <math.h>'
|
47 |
+
includes0['string.h'] = '#include <string.h>'
|
48 |
+
includes0['setjmp.h'] = '#include <setjmp.h>'
|
49 |
+
|
50 |
+
includes['arrayobject.h'] = '''#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API
|
51 |
+
#include "arrayobject.h"'''
|
52 |
+
includes['npy_math.h'] = '#include "numpy/npy_math.h"'
|
53 |
+
|
54 |
+
includes['arrayobject.h'] = '#include "fortranobject.h"'
|
55 |
+
includes['stdarg.h'] = '#include <stdarg.h>'
|
56 |
+
|
57 |
+
############# Type definitions ###############
|
58 |
+
|
59 |
+
typedefs['unsigned_char'] = 'typedef unsigned char unsigned_char;'
|
60 |
+
typedefs['unsigned_short'] = 'typedef unsigned short unsigned_short;'
|
61 |
+
typedefs['unsigned_long'] = 'typedef unsigned long unsigned_long;'
|
62 |
+
typedefs['signed_char'] = 'typedef signed char signed_char;'
|
63 |
+
typedefs['long_long'] = """
|
64 |
+
#if defined(NPY_OS_WIN32)
|
65 |
+
typedef __int64 long_long;
|
66 |
+
#else
|
67 |
+
typedef long long long_long;
|
68 |
+
typedef unsigned long long unsigned_long_long;
|
69 |
+
#endif
|
70 |
+
"""
|
71 |
+
typedefs['unsigned_long_long'] = """
|
72 |
+
#if defined(NPY_OS_WIN32)
|
73 |
+
typedef __uint64 long_long;
|
74 |
+
#else
|
75 |
+
typedef unsigned long long unsigned_long_long;
|
76 |
+
#endif
|
77 |
+
"""
|
78 |
+
typedefs['long_double'] = """
|
79 |
+
#ifndef _LONG_DOUBLE
|
80 |
+
typedef long double long_double;
|
81 |
+
#endif
|
82 |
+
"""
|
83 |
+
typedefs[
|
84 |
+
'complex_long_double'] = 'typedef struct {long double r,i;} complex_long_double;'
|
85 |
+
typedefs['complex_float'] = 'typedef struct {float r,i;} complex_float;'
|
86 |
+
typedefs['complex_double'] = 'typedef struct {double r,i;} complex_double;'
|
87 |
+
typedefs['string'] = """typedef char * string;"""
|
88 |
+
typedefs['character'] = """typedef char character;"""
|
89 |
+
|
90 |
+
|
91 |
+
############### CPP macros ####################
|
92 |
+
cppmacros['CFUNCSMESS'] = """
|
93 |
+
#ifdef DEBUGCFUNCS
|
94 |
+
#define CFUNCSMESS(mess) fprintf(stderr,\"debug-capi:\"mess);
|
95 |
+
#define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \\
|
96 |
+
PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\
|
97 |
+
fprintf(stderr,\"\\n\");
|
98 |
+
#else
|
99 |
+
#define CFUNCSMESS(mess)
|
100 |
+
#define CFUNCSMESSPY(mess,obj)
|
101 |
+
#endif
|
102 |
+
"""
|
103 |
+
cppmacros['F_FUNC'] = """
|
104 |
+
#if defined(PREPEND_FORTRAN)
|
105 |
+
#if defined(NO_APPEND_FORTRAN)
|
106 |
+
#if defined(UPPERCASE_FORTRAN)
|
107 |
+
#define F_FUNC(f,F) _##F
|
108 |
+
#else
|
109 |
+
#define F_FUNC(f,F) _##f
|
110 |
+
#endif
|
111 |
+
#else
|
112 |
+
#if defined(UPPERCASE_FORTRAN)
|
113 |
+
#define F_FUNC(f,F) _##F##_
|
114 |
+
#else
|
115 |
+
#define F_FUNC(f,F) _##f##_
|
116 |
+
#endif
|
117 |
+
#endif
|
118 |
+
#else
|
119 |
+
#if defined(NO_APPEND_FORTRAN)
|
120 |
+
#if defined(UPPERCASE_FORTRAN)
|
121 |
+
#define F_FUNC(f,F) F
|
122 |
+
#else
|
123 |
+
#define F_FUNC(f,F) f
|
124 |
+
#endif
|
125 |
+
#else
|
126 |
+
#if defined(UPPERCASE_FORTRAN)
|
127 |
+
#define F_FUNC(f,F) F##_
|
128 |
+
#else
|
129 |
+
#define F_FUNC(f,F) f##_
|
130 |
+
#endif
|
131 |
+
#endif
|
132 |
+
#endif
|
133 |
+
#if defined(UNDERSCORE_G77)
|
134 |
+
#define F_FUNC_US(f,F) F_FUNC(f##_,F##_)
|
135 |
+
#else
|
136 |
+
#define F_FUNC_US(f,F) F_FUNC(f,F)
|
137 |
+
#endif
|
138 |
+
"""
|
139 |
+
cppmacros['F_WRAPPEDFUNC'] = """
|
140 |
+
#if defined(PREPEND_FORTRAN)
|
141 |
+
#if defined(NO_APPEND_FORTRAN)
|
142 |
+
#if defined(UPPERCASE_FORTRAN)
|
143 |
+
#define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F
|
144 |
+
#else
|
145 |
+
#define F_WRAPPEDFUNC(f,F) _f2pywrap##f
|
146 |
+
#endif
|
147 |
+
#else
|
148 |
+
#if defined(UPPERCASE_FORTRAN)
|
149 |
+
#define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F##_
|
150 |
+
#else
|
151 |
+
#define F_WRAPPEDFUNC(f,F) _f2pywrap##f##_
|
152 |
+
#endif
|
153 |
+
#endif
|
154 |
+
#else
|
155 |
+
#if defined(NO_APPEND_FORTRAN)
|
156 |
+
#if defined(UPPERCASE_FORTRAN)
|
157 |
+
#define F_WRAPPEDFUNC(f,F) F2PYWRAP##F
|
158 |
+
#else
|
159 |
+
#define F_WRAPPEDFUNC(f,F) f2pywrap##f
|
160 |
+
#endif
|
161 |
+
#else
|
162 |
+
#if defined(UPPERCASE_FORTRAN)
|
163 |
+
#define F_WRAPPEDFUNC(f,F) F2PYWRAP##F##_
|
164 |
+
#else
|
165 |
+
#define F_WRAPPEDFUNC(f,F) f2pywrap##f##_
|
166 |
+
#endif
|
167 |
+
#endif
|
168 |
+
#endif
|
169 |
+
#if defined(UNDERSCORE_G77)
|
170 |
+
#define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f##_,F##_)
|
171 |
+
#else
|
172 |
+
#define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f,F)
|
173 |
+
#endif
|
174 |
+
"""
|
175 |
+
cppmacros['F_MODFUNC'] = """
|
176 |
+
#if defined(F90MOD2CCONV1) /*E.g. Compaq Fortran */
|
177 |
+
#if defined(NO_APPEND_FORTRAN)
|
178 |
+
#define F_MODFUNCNAME(m,f) $ ## m ## $ ## f
|
179 |
+
#else
|
180 |
+
#define F_MODFUNCNAME(m,f) $ ## m ## $ ## f ## _
|
181 |
+
#endif
|
182 |
+
#endif
|
183 |
+
|
184 |
+
#if defined(F90MOD2CCONV2) /*E.g. IBM XL Fortran, not tested though */
|
185 |
+
#if defined(NO_APPEND_FORTRAN)
|
186 |
+
#define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f
|
187 |
+
#else
|
188 |
+
#define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f ## _
|
189 |
+
#endif
|
190 |
+
#endif
|
191 |
+
|
192 |
+
#if defined(F90MOD2CCONV3) /*E.g. MIPSPro Compilers */
|
193 |
+
#if defined(NO_APPEND_FORTRAN)
|
194 |
+
#define F_MODFUNCNAME(m,f) f ## .in. ## m
|
195 |
+
#else
|
196 |
+
#define F_MODFUNCNAME(m,f) f ## .in. ## m ## _
|
197 |
+
#endif
|
198 |
+
#endif
|
199 |
+
/*
|
200 |
+
#if defined(UPPERCASE_FORTRAN)
|
201 |
+
#define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(M,F)
|
202 |
+
#else
|
203 |
+
#define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(m,f)
|
204 |
+
#endif
|
205 |
+
*/
|
206 |
+
|
207 |
+
#define F_MODFUNC(m,f) (*(f2pymodstruct##m##.##f))
|
208 |
+
"""
|
209 |
+
cppmacros['SWAPUNSAFE'] = """
|
210 |
+
#define SWAP(a,b) (size_t)(a) = ((size_t)(a) ^ (size_t)(b));\\
|
211 |
+
(size_t)(b) = ((size_t)(a) ^ (size_t)(b));\\
|
212 |
+
(size_t)(a) = ((size_t)(a) ^ (size_t)(b))
|
213 |
+
"""
|
214 |
+
cppmacros['SWAP'] = """
|
215 |
+
#define SWAP(a,b,t) {\\
|
216 |
+
t *c;\\
|
217 |
+
c = a;\\
|
218 |
+
a = b;\\
|
219 |
+
b = c;}
|
220 |
+
"""
|
221 |
+
# cppmacros['ISCONTIGUOUS']='#define ISCONTIGUOUS(m) (PyArray_FLAGS(m) &
|
222 |
+
# NPY_ARRAY_C_CONTIGUOUS)'
|
223 |
+
cppmacros['PRINTPYOBJERR'] = """
|
224 |
+
#define PRINTPYOBJERR(obj)\\
|
225 |
+
fprintf(stderr,\"#modulename#.error is related to \");\\
|
226 |
+
PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\
|
227 |
+
fprintf(stderr,\"\\n\");
|
228 |
+
"""
|
229 |
+
cppmacros['MINMAX'] = """
|
230 |
+
#ifndef max
|
231 |
+
#define max(a,b) ((a > b) ? (a) : (b))
|
232 |
+
#endif
|
233 |
+
#ifndef min
|
234 |
+
#define min(a,b) ((a < b) ? (a) : (b))
|
235 |
+
#endif
|
236 |
+
#ifndef MAX
|
237 |
+
#define MAX(a,b) ((a > b) ? (a) : (b))
|
238 |
+
#endif
|
239 |
+
#ifndef MIN
|
240 |
+
#define MIN(a,b) ((a < b) ? (a) : (b))
|
241 |
+
#endif
|
242 |
+
"""
|
243 |
+
cppmacros['len..'] = """
|
244 |
+
/* See fortranobject.h for definitions. The macros here are provided for BC. */
|
245 |
+
#define rank f2py_rank
|
246 |
+
#define shape f2py_shape
|
247 |
+
#define fshape f2py_shape
|
248 |
+
#define len f2py_len
|
249 |
+
#define flen f2py_flen
|
250 |
+
#define slen f2py_slen
|
251 |
+
#define size f2py_size
|
252 |
+
"""
|
253 |
+
cppmacros['pyobj_from_char1'] = r"""
|
254 |
+
#define pyobj_from_char1(v) (PyLong_FromLong(v))
|
255 |
+
"""
|
256 |
+
cppmacros['pyobj_from_short1'] = r"""
|
257 |
+
#define pyobj_from_short1(v) (PyLong_FromLong(v))
|
258 |
+
"""
|
259 |
+
needs['pyobj_from_int1'] = ['signed_char']
|
260 |
+
cppmacros['pyobj_from_int1'] = r"""
|
261 |
+
#define pyobj_from_int1(v) (PyLong_FromLong(v))
|
262 |
+
"""
|
263 |
+
cppmacros['pyobj_from_long1'] = r"""
|
264 |
+
#define pyobj_from_long1(v) (PyLong_FromLong(v))
|
265 |
+
"""
|
266 |
+
needs['pyobj_from_long_long1'] = ['long_long']
|
267 |
+
cppmacros['pyobj_from_long_long1'] = """
|
268 |
+
#ifdef HAVE_LONG_LONG
|
269 |
+
#define pyobj_from_long_long1(v) (PyLong_FromLongLong(v))
|
270 |
+
#else
|
271 |
+
#warning HAVE_LONG_LONG is not available. Redefining pyobj_from_long_long.
|
272 |
+
#define pyobj_from_long_long1(v) (PyLong_FromLong(v))
|
273 |
+
#endif
|
274 |
+
"""
|
275 |
+
needs['pyobj_from_long_double1'] = ['long_double']
|
276 |
+
cppmacros['pyobj_from_long_double1'] = """
|
277 |
+
#define pyobj_from_long_double1(v) (PyFloat_FromDouble(v))"""
|
278 |
+
cppmacros['pyobj_from_double1'] = """
|
279 |
+
#define pyobj_from_double1(v) (PyFloat_FromDouble(v))"""
|
280 |
+
cppmacros['pyobj_from_float1'] = """
|
281 |
+
#define pyobj_from_float1(v) (PyFloat_FromDouble(v))"""
|
282 |
+
needs['pyobj_from_complex_long_double1'] = ['complex_long_double']
|
283 |
+
cppmacros['pyobj_from_complex_long_double1'] = """
|
284 |
+
#define pyobj_from_complex_long_double1(v) (PyComplex_FromDoubles(v.r,v.i))"""
|
285 |
+
needs['pyobj_from_complex_double1'] = ['complex_double']
|
286 |
+
cppmacros['pyobj_from_complex_double1'] = """
|
287 |
+
#define pyobj_from_complex_double1(v) (PyComplex_FromDoubles(v.r,v.i))"""
|
288 |
+
needs['pyobj_from_complex_float1'] = ['complex_float']
|
289 |
+
cppmacros['pyobj_from_complex_float1'] = """
|
290 |
+
#define pyobj_from_complex_float1(v) (PyComplex_FromDoubles(v.r,v.i))"""
|
291 |
+
needs['pyobj_from_string1'] = ['string']
|
292 |
+
cppmacros['pyobj_from_string1'] = """
|
293 |
+
#define pyobj_from_string1(v) (PyUnicode_FromString((char *)v))"""
|
294 |
+
needs['pyobj_from_string1size'] = ['string']
|
295 |
+
cppmacros['pyobj_from_string1size'] = """
|
296 |
+
#define pyobj_from_string1size(v,len) (PyUnicode_FromStringAndSize((char *)v, len))"""
|
297 |
+
needs['TRYPYARRAYTEMPLATE'] = ['PRINTPYOBJERR']
|
298 |
+
cppmacros['TRYPYARRAYTEMPLATE'] = """
|
299 |
+
/* New SciPy */
|
300 |
+
#define TRYPYARRAYTEMPLATECHAR case NPY_STRING: *(char *)(PyArray_DATA(arr))=*v; break;
|
301 |
+
#define TRYPYARRAYTEMPLATELONG case NPY_LONG: *(long *)(PyArray_DATA(arr))=*v; break;
|
302 |
+
#define TRYPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr,PyArray_DATA(arr),pyobj_from_ ## ctype ## 1(*v)); break;
|
303 |
+
|
304 |
+
#define TRYPYARRAYTEMPLATE(ctype,typecode) \\
|
305 |
+
PyArrayObject *arr = NULL;\\
|
306 |
+
if (!obj) return -2;\\
|
307 |
+
if (!PyArray_Check(obj)) return -1;\\
|
308 |
+
if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\
|
309 |
+
if (PyArray_DESCR(arr)->type==typecode) {*(ctype *)(PyArray_DATA(arr))=*v; return 1;}\\
|
310 |
+
switch (PyArray_TYPE(arr)) {\\
|
311 |
+
case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\
|
312 |
+
case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=*v; break;\\
|
313 |
+
case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=*v; break;\\
|
314 |
+
case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\
|
315 |
+
case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\
|
316 |
+
case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\
|
317 |
+
case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=(*v!=0); break;\\
|
318 |
+
case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=*v; break;\\
|
319 |
+
case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=*v; break;\\
|
320 |
+
case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=*v; break;\\
|
321 |
+
case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=*v; break;\\
|
322 |
+
case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=*v; break;\\
|
323 |
+
case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=*v; break;\\
|
324 |
+
case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=*v; break;\\
|
325 |
+
case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=*v; break;\\
|
326 |
+
case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\
|
327 |
+
case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\
|
328 |
+
case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_ ## ctype ## 1(*v)); break;\\
|
329 |
+
default: return -2;\\
|
330 |
+
};\\
|
331 |
+
return 1
|
332 |
+
"""
|
333 |
+
|
334 |
+
needs['TRYCOMPLEXPYARRAYTEMPLATE'] = ['PRINTPYOBJERR']
|
335 |
+
cppmacros['TRYCOMPLEXPYARRAYTEMPLATE'] = """
|
336 |
+
#define TRYCOMPLEXPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;
|
337 |
+
#define TRYCOMPLEXPYARRAYTEMPLATE(ctype,typecode)\\
|
338 |
+
PyArrayObject *arr = NULL;\\
|
339 |
+
if (!obj) return -2;\\
|
340 |
+
if (!PyArray_Check(obj)) return -1;\\
|
341 |
+
if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYCOMPLEXPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\
|
342 |
+
if (PyArray_DESCR(arr)->type==typecode) {\\
|
343 |
+
*(ctype *)(PyArray_DATA(arr))=(*v).r;\\
|
344 |
+
*(ctype *)(PyArray_DATA(arr)+sizeof(ctype))=(*v).i;\\
|
345 |
+
return 1;\\
|
346 |
+
}\\
|
347 |
+
switch (PyArray_TYPE(arr)) {\\
|
348 |
+
case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r;\\
|
349 |
+
*(npy_double *)(PyArray_DATA(arr)+sizeof(npy_double))=(*v).i;\\
|
350 |
+
break;\\
|
351 |
+
case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r;\\
|
352 |
+
*(npy_float *)(PyArray_DATA(arr)+sizeof(npy_float))=(*v).i;\\
|
353 |
+
break;\\
|
354 |
+
case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r; break;\\
|
355 |
+
case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=(*v).r; break;\\
|
356 |
+
case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r; break;\\
|
357 |
+
case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=(*v).r; break;\\
|
358 |
+
case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=(*v).r; break;\\
|
359 |
+
case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=(*v).r; break;\\
|
360 |
+
case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=(*v).r; break;\\
|
361 |
+
case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=((*v).r!=0 && (*v).i!=0); break;\\
|
362 |
+
case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=(*v).r; break;\\
|
363 |
+
case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=(*v).r; break;\\
|
364 |
+
case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=(*v).r; break;\\
|
365 |
+
case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=(*v).r; break;\\
|
366 |
+
case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=(*v).r; break;\\
|
367 |
+
case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r; break;\\
|
368 |
+
case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r;\\
|
369 |
+
*(npy_longdouble *)(PyArray_DATA(arr)+sizeof(npy_longdouble))=(*v).i;\\
|
370 |
+
break;\\
|
371 |
+
case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;\\
|
372 |
+
default: return -2;\\
|
373 |
+
};\\
|
374 |
+
return -1;
|
375 |
+
"""
|
376 |
+
# cppmacros['NUMFROMARROBJ']="""
|
377 |
+
# define NUMFROMARROBJ(typenum,ctype) \\
|
378 |
+
# if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\
|
379 |
+
# else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\
|
380 |
+
# if (arr) {\\
|
381 |
+
# if (PyArray_TYPE(arr)==NPY_OBJECT) {\\
|
382 |
+
# if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\
|
383 |
+
# goto capi_fail;\\
|
384 |
+
# } else {\\
|
385 |
+
# (PyArray_DESCR(arr)->cast[typenum])(PyArray_DATA(arr),1,(char*)v,1,1);\\
|
386 |
+
# }\\
|
387 |
+
# if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\
|
388 |
+
# return 1;\\
|
389 |
+
# }
|
390 |
+
# """
|
391 |
+
# XXX: Note that CNUMFROMARROBJ is identical with NUMFROMARROBJ
|
392 |
+
# cppmacros['CNUMFROMARROBJ']="""
|
393 |
+
# define CNUMFROMARROBJ(typenum,ctype) \\
|
394 |
+
# if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\
|
395 |
+
# else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\
|
396 |
+
# if (arr) {\\
|
397 |
+
# if (PyArray_TYPE(arr)==NPY_OBJECT) {\\
|
398 |
+
# if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\
|
399 |
+
# goto capi_fail;\\
|
400 |
+
# } else {\\
|
401 |
+
# (PyArray_DESCR(arr)->cast[typenum])((void *)(PyArray_DATA(arr)),1,(void *)(v),1,1);\\
|
402 |
+
# }\\
|
403 |
+
# if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\
|
404 |
+
# return 1;\\
|
405 |
+
# }
|
406 |
+
# """
|
407 |
+
|
408 |
+
|
409 |
+
needs['GETSTRFROMPYTUPLE'] = ['STRINGCOPYN', 'PRINTPYOBJERR']
|
410 |
+
cppmacros['GETSTRFROMPYTUPLE'] = """
|
411 |
+
#define GETSTRFROMPYTUPLE(tuple,index,str,len) {\\
|
412 |
+
PyObject *rv_cb_str = PyTuple_GetItem((tuple),(index));\\
|
413 |
+
if (rv_cb_str == NULL)\\
|
414 |
+
goto capi_fail;\\
|
415 |
+
if (PyBytes_Check(rv_cb_str)) {\\
|
416 |
+
str[len-1]='\\0';\\
|
417 |
+
STRINGCOPYN((str),PyBytes_AS_STRING((PyBytesObject*)rv_cb_str),(len));\\
|
418 |
+
} else {\\
|
419 |
+
PRINTPYOBJERR(rv_cb_str);\\
|
420 |
+
PyErr_SetString(#modulename#_error,\"string object expected\");\\
|
421 |
+
goto capi_fail;\\
|
422 |
+
}\\
|
423 |
+
}
|
424 |
+
"""
|
425 |
+
cppmacros['GETSCALARFROMPYTUPLE'] = """
|
426 |
+
#define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\\
|
427 |
+
if ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\\
|
428 |
+
if (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\\
|
429 |
+
goto capi_fail;\\
|
430 |
+
}
|
431 |
+
"""
|
432 |
+
|
433 |
+
cppmacros['FAILNULL'] = """\
|
434 |
+
#define FAILNULL(p) do { \\
|
435 |
+
if ((p) == NULL) { \\
|
436 |
+
PyErr_SetString(PyExc_MemoryError, "NULL pointer found"); \\
|
437 |
+
goto capi_fail; \\
|
438 |
+
} \\
|
439 |
+
} while (0)
|
440 |
+
"""
|
441 |
+
needs['MEMCOPY'] = ['string.h', 'FAILNULL']
|
442 |
+
cppmacros['MEMCOPY'] = """
|
443 |
+
#define MEMCOPY(to,from,n)\\
|
444 |
+
do { FAILNULL(to); FAILNULL(from); (void)memcpy(to,from,n); } while (0)
|
445 |
+
"""
|
446 |
+
cppmacros['STRINGMALLOC'] = """
|
447 |
+
#define STRINGMALLOC(str,len)\\
|
448 |
+
if ((str = (string)malloc(len+1)) == NULL) {\\
|
449 |
+
PyErr_SetString(PyExc_MemoryError, \"out of memory\");\\
|
450 |
+
goto capi_fail;\\
|
451 |
+
} else {\\
|
452 |
+
(str)[len] = '\\0';\\
|
453 |
+
}
|
454 |
+
"""
|
455 |
+
cppmacros['STRINGFREE'] = """
|
456 |
+
#define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0)
|
457 |
+
"""
|
458 |
+
needs['STRINGPADN'] = ['string.h']
|
459 |
+
cppmacros['STRINGPADN'] = """
|
460 |
+
/*
|
461 |
+
STRINGPADN replaces null values with padding values from the right.
|
462 |
+
|
463 |
+
`to` must have size of at least N bytes.
|
464 |
+
|
465 |
+
If the `to[N-1]` has null value, then replace it and all the
|
466 |
+
preceding, nulls with the given padding.
|
467 |
+
|
468 |
+
STRINGPADN(to, N, PADDING, NULLVALUE) is an inverse operation.
|
469 |
+
*/
|
470 |
+
#define STRINGPADN(to, N, NULLVALUE, PADDING) \\
|
471 |
+
do { \\
|
472 |
+
int _m = (N); \\
|
473 |
+
char *_to = (to); \\
|
474 |
+
for (_m -= 1; _m >= 0 && _to[_m] == NULLVALUE; _m--) { \\
|
475 |
+
_to[_m] = PADDING; \\
|
476 |
+
} \\
|
477 |
+
} while (0)
|
478 |
+
"""
|
479 |
+
needs['STRINGCOPYN'] = ['string.h', 'FAILNULL']
|
480 |
+
cppmacros['STRINGCOPYN'] = """
|
481 |
+
/*
|
482 |
+
STRINGCOPYN copies N bytes.
|
483 |
+
|
484 |
+
`to` and `from` buffers must have sizes of at least N bytes.
|
485 |
+
*/
|
486 |
+
#define STRINGCOPYN(to,from,N) \\
|
487 |
+
do { \\
|
488 |
+
int _m = (N); \\
|
489 |
+
char *_to = (to); \\
|
490 |
+
char *_from = (from); \\
|
491 |
+
FAILNULL(_to); FAILNULL(_from); \\
|
492 |
+
(void)strncpy(_to, _from, _m); \\
|
493 |
+
} while (0)
|
494 |
+
"""
|
495 |
+
needs['STRINGCOPY'] = ['string.h', 'FAILNULL']
|
496 |
+
cppmacros['STRINGCOPY'] = """
|
497 |
+
#define STRINGCOPY(to,from)\\
|
498 |
+
do { FAILNULL(to); FAILNULL(from); (void)strcpy(to,from); } while (0)
|
499 |
+
"""
|
500 |
+
cppmacros['CHECKGENERIC'] = """
|
501 |
+
#define CHECKGENERIC(check,tcheck,name) \\
|
502 |
+
if (!(check)) {\\
|
503 |
+
PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\
|
504 |
+
/*goto capi_fail;*/\\
|
505 |
+
} else """
|
506 |
+
cppmacros['CHECKARRAY'] = """
|
507 |
+
#define CHECKARRAY(check,tcheck,name) \\
|
508 |
+
if (!(check)) {\\
|
509 |
+
PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\
|
510 |
+
/*goto capi_fail;*/\\
|
511 |
+
} else """
|
512 |
+
cppmacros['CHECKSTRING'] = """
|
513 |
+
#define CHECKSTRING(check,tcheck,name,show,var)\\
|
514 |
+
if (!(check)) {\\
|
515 |
+
char errstring[256];\\
|
516 |
+
sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, slen(var), var);\\
|
517 |
+
PyErr_SetString(#modulename#_error, errstring);\\
|
518 |
+
/*goto capi_fail;*/\\
|
519 |
+
} else """
|
520 |
+
cppmacros['CHECKSCALAR'] = """
|
521 |
+
#define CHECKSCALAR(check,tcheck,name,show,var)\\
|
522 |
+
if (!(check)) {\\
|
523 |
+
char errstring[256];\\
|
524 |
+
sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, var);\\
|
525 |
+
PyErr_SetString(#modulename#_error,errstring);\\
|
526 |
+
/*goto capi_fail;*/\\
|
527 |
+
} else """
|
528 |
+
# cppmacros['CHECKDIMS']="""
|
529 |
+
# define CHECKDIMS(dims,rank) \\
|
530 |
+
# for (int i=0;i<(rank);i++)\\
|
531 |
+
# if (dims[i]<0) {\\
|
532 |
+
# fprintf(stderr,\"Unspecified array argument requires a complete dimension specification.\\n\");\\
|
533 |
+
# goto capi_fail;\\
|
534 |
+
# }
|
535 |
+
# """
|
536 |
+
cppmacros[
|
537 |
+
'ARRSIZE'] = '#define ARRSIZE(dims,rank) (_PyArray_multiply_list(dims,rank))'
|
538 |
+
cppmacros['OLDPYNUM'] = """
|
539 |
+
#ifdef OLDPYNUM
|
540 |
+
#error You need to install NumPy version 0.13 or higher. See https://scipy.org/install.html
|
541 |
+
#endif
|
542 |
+
"""
|
543 |
+
cppmacros["F2PY_THREAD_LOCAL_DECL"] = """
|
544 |
+
#ifndef F2PY_THREAD_LOCAL_DECL
|
545 |
+
#if defined(_MSC_VER)
|
546 |
+
#define F2PY_THREAD_LOCAL_DECL __declspec(thread)
|
547 |
+
#elif defined(NPY_OS_MINGW)
|
548 |
+
#define F2PY_THREAD_LOCAL_DECL __thread
|
549 |
+
#elif defined(__STDC_VERSION__) \\
|
550 |
+
&& (__STDC_VERSION__ >= 201112L) \\
|
551 |
+
&& !defined(__STDC_NO_THREADS__) \\
|
552 |
+
&& (!defined(__GLIBC__) || __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 12)) \\
|
553 |
+
&& !defined(NPY_OS_OPENBSD) && !defined(NPY_OS_HAIKU)
|
554 |
+
/* __STDC_NO_THREADS__ was first defined in a maintenance release of glibc 2.12,
|
555 |
+
see https://lists.gnu.org/archive/html/commit-hurd/2012-07/msg00180.html,
|
556 |
+
so `!defined(__STDC_NO_THREADS__)` may give false positive for the existence
|
557 |
+
of `threads.h` when using an older release of glibc 2.12
|
558 |
+
See gh-19437 for details on OpenBSD */
|
559 |
+
#include <threads.h>
|
560 |
+
#define F2PY_THREAD_LOCAL_DECL thread_local
|
561 |
+
#elif defined(__GNUC__) \\
|
562 |
+
&& (__GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 4)))
|
563 |
+
#define F2PY_THREAD_LOCAL_DECL __thread
|
564 |
+
#endif
|
565 |
+
#endif
|
566 |
+
"""
|
567 |
+
################# C functions ###############
|
568 |
+
|
569 |
+
cfuncs['calcarrindex'] = """
|
570 |
+
static int calcarrindex(int *i,PyArrayObject *arr) {
|
571 |
+
int k,ii = i[0];
|
572 |
+
for (k=1; k < PyArray_NDIM(arr); k++)
|
573 |
+
ii += (ii*(PyArray_DIM(arr,k) - 1)+i[k]); /* assuming contiguous arr */
|
574 |
+
return ii;
|
575 |
+
}"""
|
576 |
+
cfuncs['calcarrindextr'] = """
|
577 |
+
static int calcarrindextr(int *i,PyArrayObject *arr) {
|
578 |
+
int k,ii = i[PyArray_NDIM(arr)-1];
|
579 |
+
for (k=1; k < PyArray_NDIM(arr); k++)
|
580 |
+
ii += (ii*(PyArray_DIM(arr,PyArray_NDIM(arr)-k-1) - 1)+i[PyArray_NDIM(arr)-k-1]); /* assuming contiguous arr */
|
581 |
+
return ii;
|
582 |
+
}"""
|
583 |
+
cfuncs['forcomb'] = """
|
584 |
+
static struct { int nd;npy_intp *d;int *i,*i_tr,tr; } forcombcache;
|
585 |
+
static int initforcomb(npy_intp *dims,int nd,int tr) {
|
586 |
+
int k;
|
587 |
+
if (dims==NULL) return 0;
|
588 |
+
if (nd<0) return 0;
|
589 |
+
forcombcache.nd = nd;
|
590 |
+
forcombcache.d = dims;
|
591 |
+
forcombcache.tr = tr;
|
592 |
+
if ((forcombcache.i = (int *)malloc(sizeof(int)*nd))==NULL) return 0;
|
593 |
+
if ((forcombcache.i_tr = (int *)malloc(sizeof(int)*nd))==NULL) return 0;
|
594 |
+
for (k=1;k<nd;k++) {
|
595 |
+
forcombcache.i[k] = forcombcache.i_tr[nd-k-1] = 0;
|
596 |
+
}
|
597 |
+
forcombcache.i[0] = forcombcache.i_tr[nd-1] = -1;
|
598 |
+
return 1;
|
599 |
+
}
|
600 |
+
static int *nextforcomb(void) {
|
601 |
+
int j,*i,*i_tr,k;
|
602 |
+
int nd=forcombcache.nd;
|
603 |
+
if ((i=forcombcache.i) == NULL) return NULL;
|
604 |
+
if ((i_tr=forcombcache.i_tr) == NULL) return NULL;
|
605 |
+
if (forcombcache.d == NULL) return NULL;
|
606 |
+
i[0]++;
|
607 |
+
if (i[0]==forcombcache.d[0]) {
|
608 |
+
j=1;
|
609 |
+
while ((j<nd) && (i[j]==forcombcache.d[j]-1)) j++;
|
610 |
+
if (j==nd) {
|
611 |
+
free(i);
|
612 |
+
free(i_tr);
|
613 |
+
return NULL;
|
614 |
+
}
|
615 |
+
for (k=0;k<j;k++) i[k] = i_tr[nd-k-1] = 0;
|
616 |
+
i[j]++;
|
617 |
+
i_tr[nd-j-1]++;
|
618 |
+
} else
|
619 |
+
i_tr[nd-1]++;
|
620 |
+
if (forcombcache.tr) return i_tr;
|
621 |
+
return i;
|
622 |
+
}"""
|
623 |
+
needs['try_pyarr_from_string'] = ['STRINGCOPYN', 'PRINTPYOBJERR', 'string']
|
624 |
+
cfuncs['try_pyarr_from_string'] = """
|
625 |
+
/*
|
626 |
+
try_pyarr_from_string copies str[:len(obj)] to the data of an `ndarray`.
|
627 |
+
|
628 |
+
If obj is an `ndarray`, it is assumed to be contiguous.
|
629 |
+
|
630 |
+
If the specified len==-1, str must be null-terminated.
|
631 |
+
*/
|
632 |
+
static int try_pyarr_from_string(PyObject *obj,
|
633 |
+
const string str, const int len) {
|
634 |
+
#ifdef DEBUGCFUNCS
|
635 |
+
fprintf(stderr, "try_pyarr_from_string(str='%s', len=%d, obj=%p)\\n",
|
636 |
+
(char*)str,len, obj);
|
637 |
+
#endif
|
638 |
+
if (!obj) return -2; /* Object missing */
|
639 |
+
if (obj == Py_None) return -1; /* None */
|
640 |
+
if (!PyArray_Check(obj)) goto capi_fail; /* not an ndarray */
|
641 |
+
if (PyArray_Check(obj)) {
|
642 |
+
PyArrayObject *arr = (PyArrayObject *)obj;
|
643 |
+
assert(ISCONTIGUOUS(arr));
|
644 |
+
string buf = PyArray_DATA(arr);
|
645 |
+
npy_intp n = len;
|
646 |
+
if (n == -1) {
|
647 |
+
/* Assuming null-terminated str. */
|
648 |
+
n = strlen(str);
|
649 |
+
}
|
650 |
+
if (n > PyArray_NBYTES(arr)) {
|
651 |
+
n = PyArray_NBYTES(arr);
|
652 |
+
}
|
653 |
+
STRINGCOPYN(buf, str, n);
|
654 |
+
return 1;
|
655 |
+
}
|
656 |
+
capi_fail:
|
657 |
+
PRINTPYOBJERR(obj);
|
658 |
+
PyErr_SetString(#modulename#_error, \"try_pyarr_from_string failed\");
|
659 |
+
return 0;
|
660 |
+
}
|
661 |
+
"""
|
662 |
+
needs['string_from_pyobj'] = ['string', 'STRINGMALLOC', 'STRINGCOPYN']
|
663 |
+
cfuncs['string_from_pyobj'] = """
|
664 |
+
/*
|
665 |
+
Create a new string buffer `str` of at most length `len` from a
|
666 |
+
Python string-like object `obj`.
|
667 |
+
|
668 |
+
The string buffer has given size (len) or the size of inistr when len==-1.
|
669 |
+
|
670 |
+
The string buffer is padded with blanks: in Fortran, trailing blanks
|
671 |
+
are insignificant contrary to C nulls.
|
672 |
+
*/
|
673 |
+
static int
|
674 |
+
string_from_pyobj(string *str, int *len, const string inistr, PyObject *obj,
|
675 |
+
const char *errmess)
|
676 |
+
{
|
677 |
+
PyObject *tmp = NULL;
|
678 |
+
string buf = NULL;
|
679 |
+
npy_intp n = -1;
|
680 |
+
#ifdef DEBUGCFUNCS
|
681 |
+
fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",
|
682 |
+
(char*)str, *len, (char *)inistr, obj);
|
683 |
+
#endif
|
684 |
+
if (obj == Py_None) {
|
685 |
+
n = strlen(inistr);
|
686 |
+
buf = inistr;
|
687 |
+
}
|
688 |
+
else if (PyArray_Check(obj)) {
|
689 |
+
PyArrayObject *arr = (PyArrayObject *)obj;
|
690 |
+
if (!ISCONTIGUOUS(arr)) {
|
691 |
+
PyErr_SetString(PyExc_ValueError,
|
692 |
+
\"array object is non-contiguous.\");
|
693 |
+
goto capi_fail;
|
694 |
+
}
|
695 |
+
n = PyArray_NBYTES(arr);
|
696 |
+
buf = PyArray_DATA(arr);
|
697 |
+
n = strnlen(buf, n);
|
698 |
+
}
|
699 |
+
else {
|
700 |
+
if (PyBytes_Check(obj)) {
|
701 |
+
tmp = obj;
|
702 |
+
Py_INCREF(tmp);
|
703 |
+
}
|
704 |
+
else if (PyUnicode_Check(obj)) {
|
705 |
+
tmp = PyUnicode_AsASCIIString(obj);
|
706 |
+
}
|
707 |
+
else {
|
708 |
+
PyObject *tmp2;
|
709 |
+
tmp2 = PyObject_Str(obj);
|
710 |
+
if (tmp2) {
|
711 |
+
tmp = PyUnicode_AsASCIIString(tmp2);
|
712 |
+
Py_DECREF(tmp2);
|
713 |
+
}
|
714 |
+
else {
|
715 |
+
tmp = NULL;
|
716 |
+
}
|
717 |
+
}
|
718 |
+
if (tmp == NULL) goto capi_fail;
|
719 |
+
n = PyBytes_GET_SIZE(tmp);
|
720 |
+
buf = PyBytes_AS_STRING(tmp);
|
721 |
+
}
|
722 |
+
if (*len == -1) {
|
723 |
+
/* TODO: change the type of `len` so that we can remove this */
|
724 |
+
if (n > NPY_MAX_INT) {
|
725 |
+
PyErr_SetString(PyExc_OverflowError,
|
726 |
+
"object too large for a 32-bit int");
|
727 |
+
goto capi_fail;
|
728 |
+
}
|
729 |
+
*len = n;
|
730 |
+
}
|
731 |
+
else if (*len < n) {
|
732 |
+
/* discard the last (len-n) bytes of input buf */
|
733 |
+
n = *len;
|
734 |
+
}
|
735 |
+
if (n < 0 || *len < 0 || buf == NULL) {
|
736 |
+
goto capi_fail;
|
737 |
+
}
|
738 |
+
STRINGMALLOC(*str, *len); // *str is allocated with size (*len + 1)
|
739 |
+
if (n < *len) {
|
740 |
+
/*
|
741 |
+
Pad fixed-width string with nulls. The caller will replace
|
742 |
+
nulls with blanks when the corresponding argument is not
|
743 |
+
intent(c).
|
744 |
+
*/
|
745 |
+
memset(*str + n, '\\0', *len - n);
|
746 |
+
}
|
747 |
+
STRINGCOPYN(*str, buf, n);
|
748 |
+
Py_XDECREF(tmp);
|
749 |
+
return 1;
|
750 |
+
capi_fail:
|
751 |
+
Py_XDECREF(tmp);
|
752 |
+
{
|
753 |
+
PyObject* err = PyErr_Occurred();
|
754 |
+
if (err == NULL) {
|
755 |
+
err = #modulename#_error;
|
756 |
+
}
|
757 |
+
PyErr_SetString(err, errmess);
|
758 |
+
}
|
759 |
+
return 0;
|
760 |
+
}
|
761 |
+
"""
|
762 |
+
|
763 |
+
cfuncs['character_from_pyobj'] = """
|
764 |
+
static int
|
765 |
+
character_from_pyobj(character* v, PyObject *obj, const char *errmess) {
|
766 |
+
if (PyBytes_Check(obj)) {
|
767 |
+
/* empty bytes has trailing null, so dereferencing is always safe */
|
768 |
+
*v = PyBytes_AS_STRING(obj)[0];
|
769 |
+
return 1;
|
770 |
+
} else if (PyUnicode_Check(obj)) {
|
771 |
+
PyObject* tmp = PyUnicode_AsASCIIString(obj);
|
772 |
+
if (tmp != NULL) {
|
773 |
+
*v = PyBytes_AS_STRING(tmp)[0];
|
774 |
+
Py_DECREF(tmp);
|
775 |
+
return 1;
|
776 |
+
}
|
777 |
+
} else if (PyArray_Check(obj)) {
|
778 |
+
PyArrayObject* arr = (PyArrayObject*)obj;
|
779 |
+
if (F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr)) {
|
780 |
+
*v = PyArray_BYTES(arr)[0];
|
781 |
+
return 1;
|
782 |
+
} else if (F2PY_IS_UNICODE_ARRAY(arr)) {
|
783 |
+
// TODO: update when numpy will support 1-byte and
|
784 |
+
// 2-byte unicode dtypes
|
785 |
+
PyObject* tmp = PyUnicode_FromKindAndData(
|
786 |
+
PyUnicode_4BYTE_KIND,
|
787 |
+
PyArray_BYTES(arr),
|
788 |
+
(PyArray_NBYTES(arr)>0?1:0));
|
789 |
+
if (tmp != NULL) {
|
790 |
+
if (character_from_pyobj(v, tmp, errmess)) {
|
791 |
+
Py_DECREF(tmp);
|
792 |
+
return 1;
|
793 |
+
}
|
794 |
+
Py_DECREF(tmp);
|
795 |
+
}
|
796 |
+
}
|
797 |
+
} else if (PySequence_Check(obj)) {
|
798 |
+
PyObject* tmp = PySequence_GetItem(obj,0);
|
799 |
+
if (tmp != NULL) {
|
800 |
+
if (character_from_pyobj(v, tmp, errmess)) {
|
801 |
+
Py_DECREF(tmp);
|
802 |
+
return 1;
|
803 |
+
}
|
804 |
+
Py_DECREF(tmp);
|
805 |
+
}
|
806 |
+
}
|
807 |
+
{
|
808 |
+
/* TODO: This error (and most other) error handling needs cleaning. */
|
809 |
+
char mess[F2PY_MESSAGE_BUFFER_SIZE];
|
810 |
+
strcpy(mess, errmess);
|
811 |
+
PyObject* err = PyErr_Occurred();
|
812 |
+
if (err == NULL) {
|
813 |
+
err = PyExc_TypeError;
|
814 |
+
Py_INCREF(err);
|
815 |
+
}
|
816 |
+
else {
|
817 |
+
Py_INCREF(err);
|
818 |
+
PyErr_Clear();
|
819 |
+
}
|
820 |
+
sprintf(mess + strlen(mess),
|
821 |
+
" -- expected str|bytes|sequence-of-str-or-bytes, got ");
|
822 |
+
f2py_describe(obj, mess + strlen(mess));
|
823 |
+
PyErr_SetString(err, mess);
|
824 |
+
Py_DECREF(err);
|
825 |
+
}
|
826 |
+
return 0;
|
827 |
+
}
|
828 |
+
"""
|
829 |
+
|
830 |
+
# TODO: These should be dynamically generated, too many mapped to int things,
|
831 |
+
# see note in _isocbind.py
|
832 |
+
needs['char_from_pyobj'] = ['int_from_pyobj']
|
833 |
+
cfuncs['char_from_pyobj'] = """
|
834 |
+
static int
|
835 |
+
char_from_pyobj(char* v, PyObject *obj, const char *errmess) {
|
836 |
+
int i = 0;
|
837 |
+
if (int_from_pyobj(&i, obj, errmess)) {
|
838 |
+
*v = (char)i;
|
839 |
+
return 1;
|
840 |
+
}
|
841 |
+
return 0;
|
842 |
+
}
|
843 |
+
"""
|
844 |
+
|
845 |
+
|
846 |
+
needs['signed_char_from_pyobj'] = ['int_from_pyobj', 'signed_char']
|
847 |
+
cfuncs['signed_char_from_pyobj'] = """
|
848 |
+
static int
|
849 |
+
signed_char_from_pyobj(signed_char* v, PyObject *obj, const char *errmess) {
|
850 |
+
int i = 0;
|
851 |
+
if (int_from_pyobj(&i, obj, errmess)) {
|
852 |
+
*v = (signed_char)i;
|
853 |
+
return 1;
|
854 |
+
}
|
855 |
+
return 0;
|
856 |
+
}
|
857 |
+
"""
|
858 |
+
|
859 |
+
|
860 |
+
needs['short_from_pyobj'] = ['int_from_pyobj']
|
861 |
+
cfuncs['short_from_pyobj'] = """
|
862 |
+
static int
|
863 |
+
short_from_pyobj(short* v, PyObject *obj, const char *errmess) {
|
864 |
+
int i = 0;
|
865 |
+
if (int_from_pyobj(&i, obj, errmess)) {
|
866 |
+
*v = (short)i;
|
867 |
+
return 1;
|
868 |
+
}
|
869 |
+
return 0;
|
870 |
+
}
|
871 |
+
"""
|
872 |
+
|
873 |
+
|
874 |
+
cfuncs['int_from_pyobj'] = """
|
875 |
+
static int
|
876 |
+
int_from_pyobj(int* v, PyObject *obj, const char *errmess)
|
877 |
+
{
|
878 |
+
PyObject* tmp = NULL;
|
879 |
+
|
880 |
+
if (PyLong_Check(obj)) {
|
881 |
+
*v = Npy__PyLong_AsInt(obj);
|
882 |
+
return !(*v == -1 && PyErr_Occurred());
|
883 |
+
}
|
884 |
+
|
885 |
+
tmp = PyNumber_Long(obj);
|
886 |
+
if (tmp) {
|
887 |
+
*v = Npy__PyLong_AsInt(tmp);
|
888 |
+
Py_DECREF(tmp);
|
889 |
+
return !(*v == -1 && PyErr_Occurred());
|
890 |
+
}
|
891 |
+
|
892 |
+
if (PyComplex_Check(obj)) {
|
893 |
+
PyErr_Clear();
|
894 |
+
tmp = PyObject_GetAttrString(obj,\"real\");
|
895 |
+
}
|
896 |
+
else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
|
897 |
+
/*pass*/;
|
898 |
+
}
|
899 |
+
else if (PySequence_Check(obj)) {
|
900 |
+
PyErr_Clear();
|
901 |
+
tmp = PySequence_GetItem(obj, 0);
|
902 |
+
}
|
903 |
+
|
904 |
+
if (tmp) {
|
905 |
+
if (int_from_pyobj(v, tmp, errmess)) {
|
906 |
+
Py_DECREF(tmp);
|
907 |
+
return 1;
|
908 |
+
}
|
909 |
+
Py_DECREF(tmp);
|
910 |
+
}
|
911 |
+
|
912 |
+
{
|
913 |
+
PyObject* err = PyErr_Occurred();
|
914 |
+
if (err == NULL) {
|
915 |
+
err = #modulename#_error;
|
916 |
+
}
|
917 |
+
PyErr_SetString(err, errmess);
|
918 |
+
}
|
919 |
+
return 0;
|
920 |
+
}
|
921 |
+
"""
|
922 |
+
|
923 |
+
|
924 |
+
cfuncs['long_from_pyobj'] = """
|
925 |
+
static int
|
926 |
+
long_from_pyobj(long* v, PyObject *obj, const char *errmess) {
|
927 |
+
PyObject* tmp = NULL;
|
928 |
+
|
929 |
+
if (PyLong_Check(obj)) {
|
930 |
+
*v = PyLong_AsLong(obj);
|
931 |
+
return !(*v == -1 && PyErr_Occurred());
|
932 |
+
}
|
933 |
+
|
934 |
+
tmp = PyNumber_Long(obj);
|
935 |
+
if (tmp) {
|
936 |
+
*v = PyLong_AsLong(tmp);
|
937 |
+
Py_DECREF(tmp);
|
938 |
+
return !(*v == -1 && PyErr_Occurred());
|
939 |
+
}
|
940 |
+
|
941 |
+
if (PyComplex_Check(obj)) {
|
942 |
+
PyErr_Clear();
|
943 |
+
tmp = PyObject_GetAttrString(obj,\"real\");
|
944 |
+
}
|
945 |
+
else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
|
946 |
+
/*pass*/;
|
947 |
+
}
|
948 |
+
else if (PySequence_Check(obj)) {
|
949 |
+
PyErr_Clear();
|
950 |
+
tmp = PySequence_GetItem(obj, 0);
|
951 |
+
}
|
952 |
+
|
953 |
+
if (tmp) {
|
954 |
+
if (long_from_pyobj(v, tmp, errmess)) {
|
955 |
+
Py_DECREF(tmp);
|
956 |
+
return 1;
|
957 |
+
}
|
958 |
+
Py_DECREF(tmp);
|
959 |
+
}
|
960 |
+
{
|
961 |
+
PyObject* err = PyErr_Occurred();
|
962 |
+
if (err == NULL) {
|
963 |
+
err = #modulename#_error;
|
964 |
+
}
|
965 |
+
PyErr_SetString(err, errmess);
|
966 |
+
}
|
967 |
+
return 0;
|
968 |
+
}
|
969 |
+
"""
|
970 |
+
|
971 |
+
|
972 |
+
needs['long_long_from_pyobj'] = ['long_long']
|
973 |
+
cfuncs['long_long_from_pyobj'] = """
|
974 |
+
static int
|
975 |
+
long_long_from_pyobj(long_long* v, PyObject *obj, const char *errmess)
|
976 |
+
{
|
977 |
+
PyObject* tmp = NULL;
|
978 |
+
|
979 |
+
if (PyLong_Check(obj)) {
|
980 |
+
*v = PyLong_AsLongLong(obj);
|
981 |
+
return !(*v == -1 && PyErr_Occurred());
|
982 |
+
}
|
983 |
+
|
984 |
+
tmp = PyNumber_Long(obj);
|
985 |
+
if (tmp) {
|
986 |
+
*v = PyLong_AsLongLong(tmp);
|
987 |
+
Py_DECREF(tmp);
|
988 |
+
return !(*v == -1 && PyErr_Occurred());
|
989 |
+
}
|
990 |
+
|
991 |
+
if (PyComplex_Check(obj)) {
|
992 |
+
PyErr_Clear();
|
993 |
+
tmp = PyObject_GetAttrString(obj,\"real\");
|
994 |
+
}
|
995 |
+
else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
|
996 |
+
/*pass*/;
|
997 |
+
}
|
998 |
+
else if (PySequence_Check(obj)) {
|
999 |
+
PyErr_Clear();
|
1000 |
+
tmp = PySequence_GetItem(obj, 0);
|
1001 |
+
}
|
1002 |
+
|
1003 |
+
if (tmp) {
|
1004 |
+
if (long_long_from_pyobj(v, tmp, errmess)) {
|
1005 |
+
Py_DECREF(tmp);
|
1006 |
+
return 1;
|
1007 |
+
}
|
1008 |
+
Py_DECREF(tmp);
|
1009 |
+
}
|
1010 |
+
{
|
1011 |
+
PyObject* err = PyErr_Occurred();
|
1012 |
+
if (err == NULL) {
|
1013 |
+
err = #modulename#_error;
|
1014 |
+
}
|
1015 |
+
PyErr_SetString(err,errmess);
|
1016 |
+
}
|
1017 |
+
return 0;
|
1018 |
+
}
|
1019 |
+
"""
|
1020 |
+
|
1021 |
+
|
1022 |
+
needs['long_double_from_pyobj'] = ['double_from_pyobj', 'long_double']
|
1023 |
+
cfuncs['long_double_from_pyobj'] = """
|
1024 |
+
static int
|
1025 |
+
long_double_from_pyobj(long_double* v, PyObject *obj, const char *errmess)
|
1026 |
+
{
|
1027 |
+
double d=0;
|
1028 |
+
if (PyArray_CheckScalar(obj)){
|
1029 |
+
if PyArray_IsScalar(obj, LongDouble) {
|
1030 |
+
PyArray_ScalarAsCtype(obj, v);
|
1031 |
+
return 1;
|
1032 |
+
}
|
1033 |
+
else if (PyArray_Check(obj) && PyArray_TYPE(obj) == NPY_LONGDOUBLE) {
|
1034 |
+
(*v) = *((npy_longdouble *)PyArray_DATA(obj));
|
1035 |
+
return 1;
|
1036 |
+
}
|
1037 |
+
}
|
1038 |
+
if (double_from_pyobj(&d, obj, errmess)) {
|
1039 |
+
*v = (long_double)d;
|
1040 |
+
return 1;
|
1041 |
+
}
|
1042 |
+
return 0;
|
1043 |
+
}
|
1044 |
+
"""
|
1045 |
+
|
1046 |
+
|
1047 |
+
cfuncs['double_from_pyobj'] = """
|
1048 |
+
static int
|
1049 |
+
double_from_pyobj(double* v, PyObject *obj, const char *errmess)
|
1050 |
+
{
|
1051 |
+
PyObject* tmp = NULL;
|
1052 |
+
if (PyFloat_Check(obj)) {
|
1053 |
+
*v = PyFloat_AsDouble(obj);
|
1054 |
+
return !(*v == -1.0 && PyErr_Occurred());
|
1055 |
+
}
|
1056 |
+
|
1057 |
+
tmp = PyNumber_Float(obj);
|
1058 |
+
if (tmp) {
|
1059 |
+
*v = PyFloat_AsDouble(tmp);
|
1060 |
+
Py_DECREF(tmp);
|
1061 |
+
return !(*v == -1.0 && PyErr_Occurred());
|
1062 |
+
}
|
1063 |
+
|
1064 |
+
if (PyComplex_Check(obj)) {
|
1065 |
+
PyErr_Clear();
|
1066 |
+
tmp = PyObject_GetAttrString(obj,\"real\");
|
1067 |
+
}
|
1068 |
+
else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
|
1069 |
+
/*pass*/;
|
1070 |
+
}
|
1071 |
+
else if (PySequence_Check(obj)) {
|
1072 |
+
PyErr_Clear();
|
1073 |
+
tmp = PySequence_GetItem(obj, 0);
|
1074 |
+
}
|
1075 |
+
|
1076 |
+
if (tmp) {
|
1077 |
+
if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;}
|
1078 |
+
Py_DECREF(tmp);
|
1079 |
+
}
|
1080 |
+
{
|
1081 |
+
PyObject* err = PyErr_Occurred();
|
1082 |
+
if (err==NULL) err = #modulename#_error;
|
1083 |
+
PyErr_SetString(err,errmess);
|
1084 |
+
}
|
1085 |
+
return 0;
|
1086 |
+
}
|
1087 |
+
"""
|
1088 |
+
|
1089 |
+
|
1090 |
+
needs['float_from_pyobj'] = ['double_from_pyobj']
|
1091 |
+
cfuncs['float_from_pyobj'] = """
|
1092 |
+
static int
|
1093 |
+
float_from_pyobj(float* v, PyObject *obj, const char *errmess)
|
1094 |
+
{
|
1095 |
+
double d=0.0;
|
1096 |
+
if (double_from_pyobj(&d,obj,errmess)) {
|
1097 |
+
*v = (float)d;
|
1098 |
+
return 1;
|
1099 |
+
}
|
1100 |
+
return 0;
|
1101 |
+
}
|
1102 |
+
"""
|
1103 |
+
|
1104 |
+
|
1105 |
+
needs['complex_long_double_from_pyobj'] = ['complex_long_double', 'long_double',
|
1106 |
+
'complex_double_from_pyobj', 'npy_math.h']
|
1107 |
+
cfuncs['complex_long_double_from_pyobj'] = """
|
1108 |
+
static int
|
1109 |
+
complex_long_double_from_pyobj(complex_long_double* v, PyObject *obj, const char *errmess)
|
1110 |
+
{
|
1111 |
+
complex_double cd = {0.0,0.0};
|
1112 |
+
if (PyArray_CheckScalar(obj)){
|
1113 |
+
if PyArray_IsScalar(obj, CLongDouble) {
|
1114 |
+
PyArray_ScalarAsCtype(obj, v);
|
1115 |
+
return 1;
|
1116 |
+
}
|
1117 |
+
else if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_CLONGDOUBLE) {
|
1118 |
+
(*v).r = npy_creall(*(((npy_clongdouble *)PyArray_DATA(obj))));
|
1119 |
+
(*v).i = npy_cimagl(*(((npy_clongdouble *)PyArray_DATA(obj))));
|
1120 |
+
return 1;
|
1121 |
+
}
|
1122 |
+
}
|
1123 |
+
if (complex_double_from_pyobj(&cd,obj,errmess)) {
|
1124 |
+
(*v).r = (long_double)cd.r;
|
1125 |
+
(*v).i = (long_double)cd.i;
|
1126 |
+
return 1;
|
1127 |
+
}
|
1128 |
+
return 0;
|
1129 |
+
}
|
1130 |
+
"""
|
1131 |
+
|
1132 |
+
|
1133 |
+
needs['complex_double_from_pyobj'] = ['complex_double', 'npy_math.h']
|
1134 |
+
cfuncs['complex_double_from_pyobj'] = """
|
1135 |
+
static int
|
1136 |
+
complex_double_from_pyobj(complex_double* v, PyObject *obj, const char *errmess) {
|
1137 |
+
Py_complex c;
|
1138 |
+
if (PyComplex_Check(obj)) {
|
1139 |
+
c = PyComplex_AsCComplex(obj);
|
1140 |
+
(*v).r = c.real;
|
1141 |
+
(*v).i = c.imag;
|
1142 |
+
return 1;
|
1143 |
+
}
|
1144 |
+
if (PyArray_IsScalar(obj, ComplexFloating)) {
|
1145 |
+
if (PyArray_IsScalar(obj, CFloat)) {
|
1146 |
+
npy_cfloat new;
|
1147 |
+
PyArray_ScalarAsCtype(obj, &new);
|
1148 |
+
(*v).r = (double)npy_crealf(new);
|
1149 |
+
(*v).i = (double)npy_cimagf(new);
|
1150 |
+
}
|
1151 |
+
else if (PyArray_IsScalar(obj, CLongDouble)) {
|
1152 |
+
npy_clongdouble new;
|
1153 |
+
PyArray_ScalarAsCtype(obj, &new);
|
1154 |
+
(*v).r = (double)npy_creall(new);
|
1155 |
+
(*v).i = (double)npy_cimagl(new);
|
1156 |
+
}
|
1157 |
+
else { /* if (PyArray_IsScalar(obj, CDouble)) */
|
1158 |
+
PyArray_ScalarAsCtype(obj, v);
|
1159 |
+
}
|
1160 |
+
return 1;
|
1161 |
+
}
|
1162 |
+
if (PyArray_CheckScalar(obj)) { /* 0-dim array or still array scalar */
|
1163 |
+
PyArrayObject *arr;
|
1164 |
+
if (PyArray_Check(obj)) {
|
1165 |
+
arr = (PyArrayObject *)PyArray_Cast((PyArrayObject *)obj, NPY_CDOUBLE);
|
1166 |
+
}
|
1167 |
+
else {
|
1168 |
+
arr = (PyArrayObject *)PyArray_FromScalar(obj, PyArray_DescrFromType(NPY_CDOUBLE));
|
1169 |
+
}
|
1170 |
+
if (arr == NULL) {
|
1171 |
+
return 0;
|
1172 |
+
}
|
1173 |
+
(*v).r = npy_creal(*(((npy_cdouble *)PyArray_DATA(arr))));
|
1174 |
+
(*v).i = npy_cimag(*(((npy_cdouble *)PyArray_DATA(arr))));
|
1175 |
+
Py_DECREF(arr);
|
1176 |
+
return 1;
|
1177 |
+
}
|
1178 |
+
/* Python does not provide PyNumber_Complex function :-( */
|
1179 |
+
(*v).i = 0.0;
|
1180 |
+
if (PyFloat_Check(obj)) {
|
1181 |
+
(*v).r = PyFloat_AsDouble(obj);
|
1182 |
+
return !((*v).r == -1.0 && PyErr_Occurred());
|
1183 |
+
}
|
1184 |
+
if (PyLong_Check(obj)) {
|
1185 |
+
(*v).r = PyLong_AsDouble(obj);
|
1186 |
+
return !((*v).r == -1.0 && PyErr_Occurred());
|
1187 |
+
}
|
1188 |
+
if (PySequence_Check(obj) && !(PyBytes_Check(obj) || PyUnicode_Check(obj))) {
|
1189 |
+
PyObject *tmp = PySequence_GetItem(obj,0);
|
1190 |
+
if (tmp) {
|
1191 |
+
if (complex_double_from_pyobj(v,tmp,errmess)) {
|
1192 |
+
Py_DECREF(tmp);
|
1193 |
+
return 1;
|
1194 |
+
}
|
1195 |
+
Py_DECREF(tmp);
|
1196 |
+
}
|
1197 |
+
}
|
1198 |
+
{
|
1199 |
+
PyObject* err = PyErr_Occurred();
|
1200 |
+
if (err==NULL)
|
1201 |
+
err = PyExc_TypeError;
|
1202 |
+
PyErr_SetString(err,errmess);
|
1203 |
+
}
|
1204 |
+
return 0;
|
1205 |
+
}
|
1206 |
+
"""
|
1207 |
+
|
1208 |
+
|
1209 |
+
needs['complex_float_from_pyobj'] = [
|
1210 |
+
'complex_float', 'complex_double_from_pyobj']
|
1211 |
+
cfuncs['complex_float_from_pyobj'] = """
|
1212 |
+
static int
|
1213 |
+
complex_float_from_pyobj(complex_float* v,PyObject *obj,const char *errmess)
|
1214 |
+
{
|
1215 |
+
complex_double cd={0.0,0.0};
|
1216 |
+
if (complex_double_from_pyobj(&cd,obj,errmess)) {
|
1217 |
+
(*v).r = (float)cd.r;
|
1218 |
+
(*v).i = (float)cd.i;
|
1219 |
+
return 1;
|
1220 |
+
}
|
1221 |
+
return 0;
|
1222 |
+
}
|
1223 |
+
"""
|
1224 |
+
|
1225 |
+
|
1226 |
+
cfuncs['try_pyarr_from_character'] = """
|
1227 |
+
static int try_pyarr_from_character(PyObject* obj, character* v) {
|
1228 |
+
PyArrayObject *arr = (PyArrayObject*)obj;
|
1229 |
+
if (!obj) return -2;
|
1230 |
+
if (PyArray_Check(obj)) {
|
1231 |
+
if (F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr)) {
|
1232 |
+
*(character *)(PyArray_DATA(arr)) = *v;
|
1233 |
+
return 1;
|
1234 |
+
}
|
1235 |
+
}
|
1236 |
+
{
|
1237 |
+
char mess[F2PY_MESSAGE_BUFFER_SIZE];
|
1238 |
+
PyObject* err = PyErr_Occurred();
|
1239 |
+
if (err == NULL) {
|
1240 |
+
err = PyExc_ValueError;
|
1241 |
+
strcpy(mess, "try_pyarr_from_character failed"
|
1242 |
+
" -- expected bytes array-scalar|array, got ");
|
1243 |
+
f2py_describe(obj, mess + strlen(mess));
|
1244 |
+
PyErr_SetString(err, mess);
|
1245 |
+
}
|
1246 |
+
}
|
1247 |
+
return 0;
|
1248 |
+
}
|
1249 |
+
"""
|
1250 |
+
|
1251 |
+
needs['try_pyarr_from_char'] = ['pyobj_from_char1', 'TRYPYARRAYTEMPLATE']
|
1252 |
+
cfuncs[
|
1253 |
+
'try_pyarr_from_char'] = 'static int try_pyarr_from_char(PyObject* obj,char* v) {\n TRYPYARRAYTEMPLATE(char,\'c\');\n}\n'
|
1254 |
+
needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'unsigned_char']
|
1255 |
+
cfuncs[
|
1256 |
+
'try_pyarr_from_unsigned_char'] = 'static int try_pyarr_from_unsigned_char(PyObject* obj,unsigned_char* v) {\n TRYPYARRAYTEMPLATE(unsigned_char,\'b\');\n}\n'
|
1257 |
+
needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'signed_char']
|
1258 |
+
cfuncs[
|
1259 |
+
'try_pyarr_from_signed_char'] = 'static int try_pyarr_from_signed_char(PyObject* obj,signed_char* v) {\n TRYPYARRAYTEMPLATE(signed_char,\'1\');\n}\n'
|
1260 |
+
needs['try_pyarr_from_short'] = ['pyobj_from_short1', 'TRYPYARRAYTEMPLATE']
|
1261 |
+
cfuncs[
|
1262 |
+
'try_pyarr_from_short'] = 'static int try_pyarr_from_short(PyObject* obj,short* v) {\n TRYPYARRAYTEMPLATE(short,\'s\');\n}\n'
|
1263 |
+
needs['try_pyarr_from_int'] = ['pyobj_from_int1', 'TRYPYARRAYTEMPLATE']
|
1264 |
+
cfuncs[
|
1265 |
+
'try_pyarr_from_int'] = 'static int try_pyarr_from_int(PyObject* obj,int* v) {\n TRYPYARRAYTEMPLATE(int,\'i\');\n}\n'
|
1266 |
+
needs['try_pyarr_from_long'] = ['pyobj_from_long1', 'TRYPYARRAYTEMPLATE']
|
1267 |
+
cfuncs[
|
1268 |
+
'try_pyarr_from_long'] = 'static int try_pyarr_from_long(PyObject* obj,long* v) {\n TRYPYARRAYTEMPLATE(long,\'l\');\n}\n'
|
1269 |
+
needs['try_pyarr_from_long_long'] = [
|
1270 |
+
'pyobj_from_long_long1', 'TRYPYARRAYTEMPLATE', 'long_long']
|
1271 |
+
cfuncs[
|
1272 |
+
'try_pyarr_from_long_long'] = 'static int try_pyarr_from_long_long(PyObject* obj,long_long* v) {\n TRYPYARRAYTEMPLATE(long_long,\'L\');\n}\n'
|
1273 |
+
needs['try_pyarr_from_float'] = ['pyobj_from_float1', 'TRYPYARRAYTEMPLATE']
|
1274 |
+
cfuncs[
|
1275 |
+
'try_pyarr_from_float'] = 'static int try_pyarr_from_float(PyObject* obj,float* v) {\n TRYPYARRAYTEMPLATE(float,\'f\');\n}\n'
|
1276 |
+
needs['try_pyarr_from_double'] = ['pyobj_from_double1', 'TRYPYARRAYTEMPLATE']
|
1277 |
+
cfuncs[
|
1278 |
+
'try_pyarr_from_double'] = 'static int try_pyarr_from_double(PyObject* obj,double* v) {\n TRYPYARRAYTEMPLATE(double,\'d\');\n}\n'
|
1279 |
+
needs['try_pyarr_from_complex_float'] = [
|
1280 |
+
'pyobj_from_complex_float1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_float']
|
1281 |
+
cfuncs[
|
1282 |
+
'try_pyarr_from_complex_float'] = 'static int try_pyarr_from_complex_float(PyObject* obj,complex_float* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(float,\'F\');\n}\n'
|
1283 |
+
needs['try_pyarr_from_complex_double'] = [
|
1284 |
+
'pyobj_from_complex_double1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_double']
|
1285 |
+
cfuncs[
|
1286 |
+
'try_pyarr_from_complex_double'] = 'static int try_pyarr_from_complex_double(PyObject* obj,complex_double* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(double,\'D\');\n}\n'
|
1287 |
+
|
1288 |
+
|
1289 |
+
needs['create_cb_arglist'] = ['CFUNCSMESS', 'PRINTPYOBJERR', 'MINMAX']
|
1290 |
+
# create the list of arguments to be used when calling back to python
|
1291 |
+
cfuncs['create_cb_arglist'] = """
|
1292 |
+
static int
|
1293 |
+
create_cb_arglist(PyObject* fun, PyTupleObject* xa , const int maxnofargs,
|
1294 |
+
const int nofoptargs, int *nofargs, PyTupleObject **args,
|
1295 |
+
const char *errmess)
|
1296 |
+
{
|
1297 |
+
PyObject *tmp = NULL;
|
1298 |
+
PyObject *tmp_fun = NULL;
|
1299 |
+
Py_ssize_t tot, opt, ext, siz, i, di = 0;
|
1300 |
+
CFUNCSMESS(\"create_cb_arglist\\n\");
|
1301 |
+
tot=opt=ext=siz=0;
|
1302 |
+
/* Get the total number of arguments */
|
1303 |
+
if (PyFunction_Check(fun)) {
|
1304 |
+
tmp_fun = fun;
|
1305 |
+
Py_INCREF(tmp_fun);
|
1306 |
+
}
|
1307 |
+
else {
|
1308 |
+
di = 1;
|
1309 |
+
if (PyObject_HasAttrString(fun,\"im_func\")) {
|
1310 |
+
tmp_fun = PyObject_GetAttrString(fun,\"im_func\");
|
1311 |
+
}
|
1312 |
+
else if (PyObject_HasAttrString(fun,\"__call__\")) {
|
1313 |
+
tmp = PyObject_GetAttrString(fun,\"__call__\");
|
1314 |
+
if (PyObject_HasAttrString(tmp,\"im_func\"))
|
1315 |
+
tmp_fun = PyObject_GetAttrString(tmp,\"im_func\");
|
1316 |
+
else {
|
1317 |
+
tmp_fun = fun; /* built-in function */
|
1318 |
+
Py_INCREF(tmp_fun);
|
1319 |
+
tot = maxnofargs;
|
1320 |
+
if (PyCFunction_Check(fun)) {
|
1321 |
+
/* In case the function has a co_argcount (like on PyPy) */
|
1322 |
+
di = 0;
|
1323 |
+
}
|
1324 |
+
if (xa != NULL)
|
1325 |
+
tot += PyTuple_Size((PyObject *)xa);
|
1326 |
+
}
|
1327 |
+
Py_XDECREF(tmp);
|
1328 |
+
}
|
1329 |
+
else if (PyFortran_Check(fun) || PyFortran_Check1(fun)) {
|
1330 |
+
tot = maxnofargs;
|
1331 |
+
if (xa != NULL)
|
1332 |
+
tot += PyTuple_Size((PyObject *)xa);
|
1333 |
+
tmp_fun = fun;
|
1334 |
+
Py_INCREF(tmp_fun);
|
1335 |
+
}
|
1336 |
+
else if (F2PyCapsule_Check(fun)) {
|
1337 |
+
tot = maxnofargs;
|
1338 |
+
if (xa != NULL)
|
1339 |
+
ext = PyTuple_Size((PyObject *)xa);
|
1340 |
+
if(ext>0) {
|
1341 |
+
fprintf(stderr,\"extra arguments tuple cannot be used with PyCapsule call-back\\n\");
|
1342 |
+
goto capi_fail;
|
1343 |
+
}
|
1344 |
+
tmp_fun = fun;
|
1345 |
+
Py_INCREF(tmp_fun);
|
1346 |
+
}
|
1347 |
+
}
|
1348 |
+
|
1349 |
+
if (tmp_fun == NULL) {
|
1350 |
+
fprintf(stderr,
|
1351 |
+
\"Call-back argument must be function|instance|instance.__call__|f2py-function \"
|
1352 |
+
\"but got %s.\\n\",
|
1353 |
+
((fun == NULL) ? \"NULL\" : Py_TYPE(fun)->tp_name));
|
1354 |
+
goto capi_fail;
|
1355 |
+
}
|
1356 |
+
|
1357 |
+
if (PyObject_HasAttrString(tmp_fun,\"__code__\")) {
|
1358 |
+
if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) {
|
1359 |
+
PyObject *tmp_argcount = PyObject_GetAttrString(tmp,\"co_argcount\");
|
1360 |
+
Py_DECREF(tmp);
|
1361 |
+
if (tmp_argcount == NULL) {
|
1362 |
+
goto capi_fail;
|
1363 |
+
}
|
1364 |
+
tot = PyLong_AsSsize_t(tmp_argcount) - di;
|
1365 |
+
Py_DECREF(tmp_argcount);
|
1366 |
+
}
|
1367 |
+
}
|
1368 |
+
/* Get the number of optional arguments */
|
1369 |
+
if (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) {
|
1370 |
+
if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\")))
|
1371 |
+
opt = PyTuple_Size(tmp);
|
1372 |
+
Py_XDECREF(tmp);
|
1373 |
+
}
|
1374 |
+
/* Get the number of extra arguments */
|
1375 |
+
if (xa != NULL)
|
1376 |
+
ext = PyTuple_Size((PyObject *)xa);
|
1377 |
+
/* Calculate the size of call-backs argument list */
|
1378 |
+
siz = MIN(maxnofargs+ext,tot);
|
1379 |
+
*nofargs = MAX(0,siz-ext);
|
1380 |
+
|
1381 |
+
#ifdef DEBUGCFUNCS
|
1382 |
+
fprintf(stderr,
|
1383 |
+
\"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),\"
|
1384 |
+
\"tot,opt,ext,siz,nofargs = %d(-%d), %zd, %zd, %zd, %zd, %d\\n\",
|
1385 |
+
maxnofargs, nofoptargs, tot, opt, ext, siz, *nofargs);
|
1386 |
+
#endif
|
1387 |
+
|
1388 |
+
if (siz < tot-opt) {
|
1389 |
+
fprintf(stderr,
|
1390 |
+
\"create_cb_arglist: Failed to build argument list \"
|
1391 |
+
\"(siz) with enough arguments (tot-opt) required by \"
|
1392 |
+
\"user-supplied function (siz,tot,opt=%zd, %zd, %zd).\\n\",
|
1393 |
+
siz, tot, opt);
|
1394 |
+
goto capi_fail;
|
1395 |
+
}
|
1396 |
+
|
1397 |
+
/* Initialize argument list */
|
1398 |
+
*args = (PyTupleObject *)PyTuple_New(siz);
|
1399 |
+
for (i=0;i<*nofargs;i++) {
|
1400 |
+
Py_INCREF(Py_None);
|
1401 |
+
PyTuple_SET_ITEM((PyObject *)(*args),i,Py_None);
|
1402 |
+
}
|
1403 |
+
if (xa != NULL)
|
1404 |
+
for (i=(*nofargs);i<siz;i++) {
|
1405 |
+
tmp = PyTuple_GetItem((PyObject *)xa,i-(*nofargs));
|
1406 |
+
Py_INCREF(tmp);
|
1407 |
+
PyTuple_SET_ITEM(*args,i,tmp);
|
1408 |
+
}
|
1409 |
+
CFUNCSMESS(\"create_cb_arglist-end\\n\");
|
1410 |
+
Py_DECREF(tmp_fun);
|
1411 |
+
return 1;
|
1412 |
+
|
1413 |
+
capi_fail:
|
1414 |
+
if (PyErr_Occurred() == NULL)
|
1415 |
+
PyErr_SetString(#modulename#_error, errmess);
|
1416 |
+
Py_XDECREF(tmp_fun);
|
1417 |
+
return 0;
|
1418 |
+
}
|
1419 |
+
"""
|
1420 |
+
|
1421 |
+
|
1422 |
+
def buildcfuncs():
|
1423 |
+
from .capi_maps import c2capi_map
|
1424 |
+
for k in c2capi_map.keys():
|
1425 |
+
m = 'pyarr_from_p_%s1' % k
|
1426 |
+
cppmacros[
|
1427 |
+
m] = '#define %s(v) (PyArray_SimpleNewFromData(0,NULL,%s,(char *)v))' % (m, c2capi_map[k])
|
1428 |
+
k = 'string'
|
1429 |
+
m = 'pyarr_from_p_%s1' % k
|
1430 |
+
# NPY_CHAR compatibility, NPY_STRING with itemsize 1
|
1431 |
+
cppmacros[
|
1432 |
+
m] = '#define %s(v,dims) (PyArray_New(&PyArray_Type, 1, dims, NPY_STRING, NULL, v, 1, NPY_ARRAY_CARRAY, NULL))' % (m)
|
1433 |
+
|
1434 |
+
|
1435 |
+
############ Auxiliary functions for sorting needs ###################
|
1436 |
+
|
1437 |
+
def append_needs(need, flag=1):
|
1438 |
+
# This function modifies the contents of the global `outneeds` dict.
|
1439 |
+
if isinstance(need, list):
|
1440 |
+
for n in need:
|
1441 |
+
append_needs(n, flag)
|
1442 |
+
elif isinstance(need, str):
|
1443 |
+
if not need:
|
1444 |
+
return
|
1445 |
+
if need in includes0:
|
1446 |
+
n = 'includes0'
|
1447 |
+
elif need in includes:
|
1448 |
+
n = 'includes'
|
1449 |
+
elif need in typedefs:
|
1450 |
+
n = 'typedefs'
|
1451 |
+
elif need in typedefs_generated:
|
1452 |
+
n = 'typedefs_generated'
|
1453 |
+
elif need in cppmacros:
|
1454 |
+
n = 'cppmacros'
|
1455 |
+
elif need in cfuncs:
|
1456 |
+
n = 'cfuncs'
|
1457 |
+
elif need in callbacks:
|
1458 |
+
n = 'callbacks'
|
1459 |
+
elif need in f90modhooks:
|
1460 |
+
n = 'f90modhooks'
|
1461 |
+
elif need in commonhooks:
|
1462 |
+
n = 'commonhooks'
|
1463 |
+
else:
|
1464 |
+
errmess('append_needs: unknown need %s\n' % (repr(need)))
|
1465 |
+
return
|
1466 |
+
if need in outneeds[n]:
|
1467 |
+
return
|
1468 |
+
if flag:
|
1469 |
+
tmp = {}
|
1470 |
+
if need in needs:
|
1471 |
+
for nn in needs[need]:
|
1472 |
+
t = append_needs(nn, 0)
|
1473 |
+
if isinstance(t, dict):
|
1474 |
+
for nnn in t.keys():
|
1475 |
+
if nnn in tmp:
|
1476 |
+
tmp[nnn] = tmp[nnn] + t[nnn]
|
1477 |
+
else:
|
1478 |
+
tmp[nnn] = t[nnn]
|
1479 |
+
for nn in tmp.keys():
|
1480 |
+
for nnn in tmp[nn]:
|
1481 |
+
if nnn not in outneeds[nn]:
|
1482 |
+
outneeds[nn] = [nnn] + outneeds[nn]
|
1483 |
+
outneeds[n].append(need)
|
1484 |
+
else:
|
1485 |
+
tmp = {}
|
1486 |
+
if need in needs:
|
1487 |
+
for nn in needs[need]:
|
1488 |
+
t = append_needs(nn, flag)
|
1489 |
+
if isinstance(t, dict):
|
1490 |
+
for nnn in t.keys():
|
1491 |
+
if nnn in tmp:
|
1492 |
+
tmp[nnn] = t[nnn] + tmp[nnn]
|
1493 |
+
else:
|
1494 |
+
tmp[nnn] = t[nnn]
|
1495 |
+
if n not in tmp:
|
1496 |
+
tmp[n] = []
|
1497 |
+
tmp[n].append(need)
|
1498 |
+
return tmp
|
1499 |
+
else:
|
1500 |
+
errmess('append_needs: expected list or string but got :%s\n' %
|
1501 |
+
(repr(need)))
|
1502 |
+
|
1503 |
+
|
1504 |
+
def get_needs():
|
1505 |
+
# This function modifies the contents of the global `outneeds` dict.
|
1506 |
+
res = {}
|
1507 |
+
for n in outneeds.keys():
|
1508 |
+
out = []
|
1509 |
+
saveout = copy.copy(outneeds[n])
|
1510 |
+
while len(outneeds[n]) > 0:
|
1511 |
+
if outneeds[n][0] not in needs:
|
1512 |
+
out.append(outneeds[n][0])
|
1513 |
+
del outneeds[n][0]
|
1514 |
+
else:
|
1515 |
+
flag = 0
|
1516 |
+
for k in outneeds[n][1:]:
|
1517 |
+
if k in needs[outneeds[n][0]]:
|
1518 |
+
flag = 1
|
1519 |
+
break
|
1520 |
+
if flag:
|
1521 |
+
outneeds[n] = outneeds[n][1:] + [outneeds[n][0]]
|
1522 |
+
else:
|
1523 |
+
out.append(outneeds[n][0])
|
1524 |
+
del outneeds[n][0]
|
1525 |
+
if saveout and (0 not in map(lambda x, y: x == y, saveout, outneeds[n])) \
|
1526 |
+
and outneeds[n] != []:
|
1527 |
+
print(n, saveout)
|
1528 |
+
errmess(
|
1529 |
+
'get_needs: no progress in sorting needs, probably circular dependence, skipping.\n')
|
1530 |
+
out = out + saveout
|
1531 |
+
break
|
1532 |
+
saveout = copy.copy(outneeds[n])
|
1533 |
+
if out == []:
|
1534 |
+
out = [n]
|
1535 |
+
res[n] = out
|
1536 |
+
return res
|
venv/lib/python3.10/site-packages/numpy/f2py/common_rules.py
ADDED
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Build common block mechanism for f2py2e.
|
3 |
+
|
4 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
5 |
+
Copyright 2011 -- present NumPy Developers.
|
6 |
+
Permission to use, modify, and distribute this software is given under the
|
7 |
+
terms of the NumPy License
|
8 |
+
|
9 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
10 |
+
"""
|
11 |
+
from . import __version__
|
12 |
+
f2py_version = __version__.version
|
13 |
+
|
14 |
+
from .auxfuncs import (
|
15 |
+
hasbody, hascommon, hasnote, isintent_hide, outmess, getuseblocks
|
16 |
+
)
|
17 |
+
from . import capi_maps
|
18 |
+
from . import func2subr
|
19 |
+
from .crackfortran import rmbadname
|
20 |
+
|
21 |
+
|
22 |
+
def findcommonblocks(block, top=1):
|
23 |
+
ret = []
|
24 |
+
if hascommon(block):
|
25 |
+
for key, value in block['common'].items():
|
26 |
+
vars_ = {v: block['vars'][v] for v in value}
|
27 |
+
ret.append((key, value, vars_))
|
28 |
+
elif hasbody(block):
|
29 |
+
for b in block['body']:
|
30 |
+
ret = ret + findcommonblocks(b, 0)
|
31 |
+
if top:
|
32 |
+
tret = []
|
33 |
+
names = []
|
34 |
+
for t in ret:
|
35 |
+
if t[0] not in names:
|
36 |
+
names.append(t[0])
|
37 |
+
tret.append(t)
|
38 |
+
return tret
|
39 |
+
return ret
|
40 |
+
|
41 |
+
|
42 |
+
def buildhooks(m):
|
43 |
+
ret = {'commonhooks': [], 'initcommonhooks': [],
|
44 |
+
'docs': ['"COMMON blocks:\\n"']}
|
45 |
+
fwrap = ['']
|
46 |
+
|
47 |
+
def fadd(line, s=fwrap):
|
48 |
+
s[0] = '%s\n %s' % (s[0], line)
|
49 |
+
chooks = ['']
|
50 |
+
|
51 |
+
def cadd(line, s=chooks):
|
52 |
+
s[0] = '%s\n%s' % (s[0], line)
|
53 |
+
ihooks = ['']
|
54 |
+
|
55 |
+
def iadd(line, s=ihooks):
|
56 |
+
s[0] = '%s\n%s' % (s[0], line)
|
57 |
+
doc = ['']
|
58 |
+
|
59 |
+
def dadd(line, s=doc):
|
60 |
+
s[0] = '%s\n%s' % (s[0], line)
|
61 |
+
for (name, vnames, vars) in findcommonblocks(m):
|
62 |
+
lower_name = name.lower()
|
63 |
+
hnames, inames = [], []
|
64 |
+
for n in vnames:
|
65 |
+
if isintent_hide(vars[n]):
|
66 |
+
hnames.append(n)
|
67 |
+
else:
|
68 |
+
inames.append(n)
|
69 |
+
if hnames:
|
70 |
+
outmess('\t\tConstructing COMMON block support for "%s"...\n\t\t %s\n\t\t Hidden: %s\n' % (
|
71 |
+
name, ','.join(inames), ','.join(hnames)))
|
72 |
+
else:
|
73 |
+
outmess('\t\tConstructing COMMON block support for "%s"...\n\t\t %s\n' % (
|
74 |
+
name, ','.join(inames)))
|
75 |
+
fadd('subroutine f2pyinit%s(setupfunc)' % name)
|
76 |
+
for usename in getuseblocks(m):
|
77 |
+
fadd(f'use {usename}')
|
78 |
+
fadd('external setupfunc')
|
79 |
+
for n in vnames:
|
80 |
+
fadd(func2subr.var2fixfortran(vars, n))
|
81 |
+
if name == '_BLNK_':
|
82 |
+
fadd('common %s' % (','.join(vnames)))
|
83 |
+
else:
|
84 |
+
fadd('common /%s/ %s' % (name, ','.join(vnames)))
|
85 |
+
fadd('call setupfunc(%s)' % (','.join(inames)))
|
86 |
+
fadd('end\n')
|
87 |
+
cadd('static FortranDataDef f2py_%s_def[] = {' % (name))
|
88 |
+
idims = []
|
89 |
+
for n in inames:
|
90 |
+
ct = capi_maps.getctype(vars[n])
|
91 |
+
elsize = capi_maps.get_elsize(vars[n])
|
92 |
+
at = capi_maps.c2capi_map[ct]
|
93 |
+
dm = capi_maps.getarrdims(n, vars[n])
|
94 |
+
if dm['dims']:
|
95 |
+
idims.append('(%s)' % (dm['dims']))
|
96 |
+
else:
|
97 |
+
idims.append('')
|
98 |
+
dms = dm['dims'].strip()
|
99 |
+
if not dms:
|
100 |
+
dms = '-1'
|
101 |
+
cadd('\t{\"%s\",%s,{{%s}},%s, %s},'
|
102 |
+
% (n, dm['rank'], dms, at, elsize))
|
103 |
+
cadd('\t{NULL}\n};')
|
104 |
+
inames1 = rmbadname(inames)
|
105 |
+
inames1_tps = ','.join(['char *' + s for s in inames1])
|
106 |
+
cadd('static void f2py_setup_%s(%s) {' % (name, inames1_tps))
|
107 |
+
cadd('\tint i_f2py=0;')
|
108 |
+
for n in inames1:
|
109 |
+
cadd('\tf2py_%s_def[i_f2py++].data = %s;' % (name, n))
|
110 |
+
cadd('}')
|
111 |
+
if '_' in lower_name:
|
112 |
+
F_FUNC = 'F_FUNC_US'
|
113 |
+
else:
|
114 |
+
F_FUNC = 'F_FUNC'
|
115 |
+
cadd('extern void %s(f2pyinit%s,F2PYINIT%s)(void(*)(%s));'
|
116 |
+
% (F_FUNC, lower_name, name.upper(),
|
117 |
+
','.join(['char*'] * len(inames1))))
|
118 |
+
cadd('static void f2py_init_%s(void) {' % name)
|
119 |
+
cadd('\t%s(f2pyinit%s,F2PYINIT%s)(f2py_setup_%s);'
|
120 |
+
% (F_FUNC, lower_name, name.upper(), name))
|
121 |
+
cadd('}\n')
|
122 |
+
iadd('\ttmp = PyFortranObject_New(f2py_%s_def,f2py_init_%s);' % (name, name))
|
123 |
+
iadd('\tif (tmp == NULL) return NULL;')
|
124 |
+
iadd('\tif (F2PyDict_SetItemString(d, \"%s\", tmp) == -1) return NULL;'
|
125 |
+
% name)
|
126 |
+
iadd('\tPy_DECREF(tmp);')
|
127 |
+
tname = name.replace('_', '\\_')
|
128 |
+
dadd('\\subsection{Common block \\texttt{%s}}\n' % (tname))
|
129 |
+
dadd('\\begin{description}')
|
130 |
+
for n in inames:
|
131 |
+
dadd('\\item[]{{}\\verb@%s@{}}' %
|
132 |
+
(capi_maps.getarrdocsign(n, vars[n])))
|
133 |
+
if hasnote(vars[n]):
|
134 |
+
note = vars[n]['note']
|
135 |
+
if isinstance(note, list):
|
136 |
+
note = '\n'.join(note)
|
137 |
+
dadd('--- %s' % (note))
|
138 |
+
dadd('\\end{description}')
|
139 |
+
ret['docs'].append(
|
140 |
+
'"\t/%s/ %s\\n"' % (name, ','.join(map(lambda v, d: v + d, inames, idims))))
|
141 |
+
ret['commonhooks'] = chooks
|
142 |
+
ret['initcommonhooks'] = ihooks
|
143 |
+
ret['latexdoc'] = doc[0]
|
144 |
+
if len(ret['docs']) <= 1:
|
145 |
+
ret['docs'] = ''
|
146 |
+
return ret, fwrap[0]
|
venv/lib/python3.10/site-packages/numpy/f2py/crackfortran.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/lib/python3.10/site-packages/numpy/f2py/diagnose.py
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
import os
|
3 |
+
import sys
|
4 |
+
import tempfile
|
5 |
+
|
6 |
+
|
7 |
+
def run_command(cmd):
|
8 |
+
print('Running %r:' % (cmd))
|
9 |
+
os.system(cmd)
|
10 |
+
print('------')
|
11 |
+
|
12 |
+
|
13 |
+
def run():
|
14 |
+
_path = os.getcwd()
|
15 |
+
os.chdir(tempfile.gettempdir())
|
16 |
+
print('------')
|
17 |
+
print('os.name=%r' % (os.name))
|
18 |
+
print('------')
|
19 |
+
print('sys.platform=%r' % (sys.platform))
|
20 |
+
print('------')
|
21 |
+
print('sys.version:')
|
22 |
+
print(sys.version)
|
23 |
+
print('------')
|
24 |
+
print('sys.prefix:')
|
25 |
+
print(sys.prefix)
|
26 |
+
print('------')
|
27 |
+
print('sys.path=%r' % (':'.join(sys.path)))
|
28 |
+
print('------')
|
29 |
+
|
30 |
+
try:
|
31 |
+
import numpy
|
32 |
+
has_newnumpy = 1
|
33 |
+
except ImportError as e:
|
34 |
+
print('Failed to import new numpy:', e)
|
35 |
+
has_newnumpy = 0
|
36 |
+
|
37 |
+
try:
|
38 |
+
from numpy.f2py import f2py2e
|
39 |
+
has_f2py2e = 1
|
40 |
+
except ImportError as e:
|
41 |
+
print('Failed to import f2py2e:', e)
|
42 |
+
has_f2py2e = 0
|
43 |
+
|
44 |
+
try:
|
45 |
+
import numpy.distutils
|
46 |
+
has_numpy_distutils = 2
|
47 |
+
except ImportError:
|
48 |
+
try:
|
49 |
+
import numpy_distutils
|
50 |
+
has_numpy_distutils = 1
|
51 |
+
except ImportError as e:
|
52 |
+
print('Failed to import numpy_distutils:', e)
|
53 |
+
has_numpy_distutils = 0
|
54 |
+
|
55 |
+
if has_newnumpy:
|
56 |
+
try:
|
57 |
+
print('Found new numpy version %r in %s' %
|
58 |
+
(numpy.__version__, numpy.__file__))
|
59 |
+
except Exception as msg:
|
60 |
+
print('error:', msg)
|
61 |
+
print('------')
|
62 |
+
|
63 |
+
if has_f2py2e:
|
64 |
+
try:
|
65 |
+
print('Found f2py2e version %r in %s' %
|
66 |
+
(f2py2e.__version__.version, f2py2e.__file__))
|
67 |
+
except Exception as msg:
|
68 |
+
print('error:', msg)
|
69 |
+
print('------')
|
70 |
+
|
71 |
+
if has_numpy_distutils:
|
72 |
+
try:
|
73 |
+
if has_numpy_distutils == 2:
|
74 |
+
print('Found numpy.distutils version %r in %r' % (
|
75 |
+
numpy.distutils.__version__,
|
76 |
+
numpy.distutils.__file__))
|
77 |
+
else:
|
78 |
+
print('Found numpy_distutils version %r in %r' % (
|
79 |
+
numpy_distutils.numpy_distutils_version.numpy_distutils_version,
|
80 |
+
numpy_distutils.__file__))
|
81 |
+
print('------')
|
82 |
+
except Exception as msg:
|
83 |
+
print('error:', msg)
|
84 |
+
print('------')
|
85 |
+
try:
|
86 |
+
if has_numpy_distutils == 1:
|
87 |
+
print(
|
88 |
+
'Importing numpy_distutils.command.build_flib ...', end=' ')
|
89 |
+
import numpy_distutils.command.build_flib as build_flib
|
90 |
+
print('ok')
|
91 |
+
print('------')
|
92 |
+
try:
|
93 |
+
print(
|
94 |
+
'Checking availability of supported Fortran compilers:')
|
95 |
+
for compiler_class in build_flib.all_compilers:
|
96 |
+
compiler_class(verbose=1).is_available()
|
97 |
+
print('------')
|
98 |
+
except Exception as msg:
|
99 |
+
print('error:', msg)
|
100 |
+
print('------')
|
101 |
+
except Exception as msg:
|
102 |
+
print(
|
103 |
+
'error:', msg, '(ignore it, build_flib is obsolute for numpy.distutils 0.2.2 and up)')
|
104 |
+
print('------')
|
105 |
+
try:
|
106 |
+
if has_numpy_distutils == 2:
|
107 |
+
print('Importing numpy.distutils.fcompiler ...', end=' ')
|
108 |
+
import numpy.distutils.fcompiler as fcompiler
|
109 |
+
else:
|
110 |
+
print('Importing numpy_distutils.fcompiler ...', end=' ')
|
111 |
+
import numpy_distutils.fcompiler as fcompiler
|
112 |
+
print('ok')
|
113 |
+
print('------')
|
114 |
+
try:
|
115 |
+
print('Checking availability of supported Fortran compilers:')
|
116 |
+
fcompiler.show_fcompilers()
|
117 |
+
print('------')
|
118 |
+
except Exception as msg:
|
119 |
+
print('error:', msg)
|
120 |
+
print('------')
|
121 |
+
except Exception as msg:
|
122 |
+
print('error:', msg)
|
123 |
+
print('------')
|
124 |
+
try:
|
125 |
+
if has_numpy_distutils == 2:
|
126 |
+
print('Importing numpy.distutils.cpuinfo ...', end=' ')
|
127 |
+
from numpy.distutils.cpuinfo import cpuinfo
|
128 |
+
print('ok')
|
129 |
+
print('------')
|
130 |
+
else:
|
131 |
+
try:
|
132 |
+
print(
|
133 |
+
'Importing numpy_distutils.command.cpuinfo ...', end=' ')
|
134 |
+
from numpy_distutils.command.cpuinfo import cpuinfo
|
135 |
+
print('ok')
|
136 |
+
print('------')
|
137 |
+
except Exception as msg:
|
138 |
+
print('error:', msg, '(ignore it)')
|
139 |
+
print('Importing numpy_distutils.cpuinfo ...', end=' ')
|
140 |
+
from numpy_distutils.cpuinfo import cpuinfo
|
141 |
+
print('ok')
|
142 |
+
print('------')
|
143 |
+
cpu = cpuinfo()
|
144 |
+
print('CPU information:', end=' ')
|
145 |
+
for name in dir(cpuinfo):
|
146 |
+
if name[0] == '_' and name[1] != '_' and getattr(cpu, name[1:])():
|
147 |
+
print(name[1:], end=' ')
|
148 |
+
print('------')
|
149 |
+
except Exception as msg:
|
150 |
+
print('error:', msg)
|
151 |
+
print('------')
|
152 |
+
os.chdir(_path)
|
153 |
+
if __name__ == "__main__":
|
154 |
+
run()
|
venv/lib/python3.10/site-packages/numpy/f2py/f2py2e.py
ADDED
@@ -0,0 +1,768 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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son all rights reserved.
|
8 |
+
Copyright 2011 -- present NumPy Developers.
|
9 |
+
Permission to use, modify, and distribute this software is given under the
|
10 |
+
terms of the NumPy License.
|
11 |
+
|
12 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
13 |
+
"""
|
14 |
+
import sys
|
15 |
+
import os
|
16 |
+
import pprint
|
17 |
+
import re
|
18 |
+
from pathlib import Path
|
19 |
+
from itertools import dropwhile
|
20 |
+
import argparse
|
21 |
+
import copy
|
22 |
+
|
23 |
+
from . import crackfortran
|
24 |
+
from . import rules
|
25 |
+
from . import cb_rules
|
26 |
+
from . import auxfuncs
|
27 |
+
from . import cfuncs
|
28 |
+
from . import f90mod_rules
|
29 |
+
from . import __version__
|
30 |
+
from . import capi_maps
|
31 |
+
from numpy.f2py._backends import f2py_build_generator
|
32 |
+
|
33 |
+
f2py_version = __version__.version
|
34 |
+
numpy_version = __version__.version
|
35 |
+
errmess = sys.stderr.write
|
36 |
+
# outmess=sys.stdout.write
|
37 |
+
show = pprint.pprint
|
38 |
+
outmess = auxfuncs.outmess
|
39 |
+
MESON_ONLY_VER = (sys.version_info >= (3, 12))
|
40 |
+
|
41 |
+
__usage__ =\
|
42 |
+
f"""Usage:
|
43 |
+
|
44 |
+
1) To construct extension module sources:
|
45 |
+
|
46 |
+
f2py [<options>] <fortran files> [[[only:]||[skip:]] \\
|
47 |
+
<fortran functions> ] \\
|
48 |
+
[: <fortran files> ...]
|
49 |
+
|
50 |
+
2) To compile fortran files and build extension modules:
|
51 |
+
|
52 |
+
f2py -c [<options>, <build_flib options>, <extra options>] <fortran files>
|
53 |
+
|
54 |
+
3) To generate signature files:
|
55 |
+
|
56 |
+
f2py -h <filename.pyf> ...< same options as in (1) >
|
57 |
+
|
58 |
+
Description: This program generates a Python C/API file (<modulename>module.c)
|
59 |
+
that contains wrappers for given fortran functions so that they
|
60 |
+
can be called from Python. With the -c option the corresponding
|
61 |
+
extension modules are built.
|
62 |
+
|
63 |
+
Options:
|
64 |
+
|
65 |
+
-h <filename> Write signatures of the fortran routines to file <filename>
|
66 |
+
and exit. You can then edit <filename> and use it instead
|
67 |
+
of <fortran files>. If <filename>==stdout then the
|
68 |
+
signatures are printed to stdout.
|
69 |
+
<fortran functions> Names of fortran routines for which Python C/API
|
70 |
+
functions will be generated. Default is all that are found
|
71 |
+
in <fortran files>.
|
72 |
+
<fortran files> Paths to fortran/signature files that will be scanned for
|
73 |
+
<fortran functions> in order to determine their signatures.
|
74 |
+
skip: Ignore fortran functions that follow until `:'.
|
75 |
+
only: Use only fortran functions that follow until `:'.
|
76 |
+
: Get back to <fortran files> mode.
|
77 |
+
|
78 |
+
-m <modulename> Name of the module; f2py generates a Python/C API
|
79 |
+
file <modulename>module.c or extension module <modulename>.
|
80 |
+
Default is 'untitled'.
|
81 |
+
|
82 |
+
'-include<header>' Writes additional headers in the C wrapper, can be passed
|
83 |
+
multiple times, generates #include <header> each time.
|
84 |
+
|
85 |
+
--[no-]lower Do [not] lower the cases in <fortran files>. By default,
|
86 |
+
--lower is assumed with -h key, and --no-lower without -h key.
|
87 |
+
|
88 |
+
--build-dir <dirname> All f2py generated files are created in <dirname>.
|
89 |
+
Default is tempfile.mkdtemp().
|
90 |
+
|
91 |
+
--overwrite-signature Overwrite existing signature file.
|
92 |
+
|
93 |
+
--[no-]latex-doc Create (or not) <modulename>module.tex.
|
94 |
+
Default is --no-latex-doc.
|
95 |
+
--short-latex Create 'incomplete' LaTeX document (without commands
|
96 |
+
\\documentclass, \\tableofcontents, and \\begin{{document}},
|
97 |
+
\\end{{document}}).
|
98 |
+
|
99 |
+
--[no-]rest-doc Create (or not) <modulename>module.rst.
|
100 |
+
Default is --no-rest-doc.
|
101 |
+
|
102 |
+
--debug-capi Create C/API code that reports the state of the wrappers
|
103 |
+
during runtime. Useful for debugging.
|
104 |
+
|
105 |
+
--[no-]wrap-functions Create Fortran subroutine wrappers to Fortran 77
|
106 |
+
functions. --wrap-functions is default because it ensures
|
107 |
+
maximum portability/compiler independence.
|
108 |
+
|
109 |
+
--include-paths <path1>:<path2>:... Search include files from the given
|
110 |
+
directories.
|
111 |
+
|
112 |
+
--help-link [..] List system resources found by system_info.py. See also
|
113 |
+
--link-<resource> switch below. [..] is optional list
|
114 |
+
of resources names. E.g. try 'f2py --help-link lapack_opt'.
|
115 |
+
|
116 |
+
--f2cmap <filename> Load Fortran-to-Python KIND specification from the given
|
117 |
+
file. Default: .f2py_f2cmap in current directory.
|
118 |
+
|
119 |
+
--quiet Run quietly.
|
120 |
+
--verbose Run with extra verbosity.
|
121 |
+
--skip-empty-wrappers Only generate wrapper files when needed.
|
122 |
+
-v Print f2py version ID and exit.
|
123 |
+
|
124 |
+
|
125 |
+
build backend options (only effective with -c)
|
126 |
+
[NO_MESON] is used to indicate an option not meant to be used
|
127 |
+
with the meson backend or above Python 3.12:
|
128 |
+
|
129 |
+
--fcompiler= Specify Fortran compiler type by vendor [NO_MESON]
|
130 |
+
--compiler= Specify distutils C compiler type [NO_MESON]
|
131 |
+
|
132 |
+
--help-fcompiler List available Fortran compilers and exit [NO_MESON]
|
133 |
+
--f77exec= Specify the path to F77 compiler [NO_MESON]
|
134 |
+
--f90exec= Specify the path to F90 compiler [NO_MESON]
|
135 |
+
--f77flags= Specify F77 compiler flags
|
136 |
+
--f90flags= Specify F90 compiler flags
|
137 |
+
--opt= Specify optimization flags [NO_MESON]
|
138 |
+
--arch= Specify architecture specific optimization flags [NO_MESON]
|
139 |
+
--noopt Compile without optimization [NO_MESON]
|
140 |
+
--noarch Compile without arch-dependent optimization [NO_MESON]
|
141 |
+
--debug Compile with debugging information
|
142 |
+
|
143 |
+
--dep <dependency>
|
144 |
+
Specify a meson dependency for the module. This may
|
145 |
+
be passed multiple times for multiple dependencies.
|
146 |
+
Dependencies are stored in a list for further processing.
|
147 |
+
|
148 |
+
Example: --dep lapack --dep scalapack
|
149 |
+
This will identify "lapack" and "scalapack" as dependencies
|
150 |
+
and remove them from argv, leaving a dependencies list
|
151 |
+
containing ["lapack", "scalapack"].
|
152 |
+
|
153 |
+
--backend <backend_type>
|
154 |
+
Specify the build backend for the compilation process.
|
155 |
+
The supported backends are 'meson' and 'distutils'.
|
156 |
+
If not specified, defaults to 'distutils'. On
|
157 |
+
Python 3.12 or higher, the default is 'meson'.
|
158 |
+
|
159 |
+
Extra options (only effective with -c):
|
160 |
+
|
161 |
+
--link-<resource> Link extension module with <resource> as defined
|
162 |
+
by numpy.distutils/system_info.py. E.g. to link
|
163 |
+
with optimized LAPACK libraries (vecLib on MacOSX,
|
164 |
+
ATLAS elsewhere), use --link-lapack_opt.
|
165 |
+
See also --help-link switch. [NO_MESON]
|
166 |
+
|
167 |
+
-L/path/to/lib/ -l<libname>
|
168 |
+
-D<define> -U<name>
|
169 |
+
-I/path/to/include/
|
170 |
+
<filename>.o <filename>.so <filename>.a
|
171 |
+
|
172 |
+
Using the following macros may be required with non-gcc Fortran
|
173 |
+
compilers:
|
174 |
+
-DPREPEND_FORTRAN -DNO_APPEND_FORTRAN -DUPPERCASE_FORTRAN
|
175 |
+
-DUNDERSCORE_G77
|
176 |
+
|
177 |
+
When using -DF2PY_REPORT_ATEXIT, a performance report of F2PY
|
178 |
+
interface is printed out at exit (platforms: Linux).
|
179 |
+
|
180 |
+
When using -DF2PY_REPORT_ON_ARRAY_COPY=<int>, a message is
|
181 |
+
sent to stderr whenever F2PY interface makes a copy of an
|
182 |
+
array. Integer <int> sets the threshold for array sizes when
|
183 |
+
a message should be shown.
|
184 |
+
|
185 |
+
Version: {f2py_version}
|
186 |
+
numpy Version: {numpy_version}
|
187 |
+
License: NumPy license (see LICENSE.txt in the NumPy source code)
|
188 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
189 |
+
Copyright 2011 -- present NumPy Developers.
|
190 |
+
https://numpy.org/doc/stable/f2py/index.html\n"""
|
191 |
+
|
192 |
+
|
193 |
+
def scaninputline(inputline):
|
194 |
+
files, skipfuncs, onlyfuncs, debug = [], [], [], []
|
195 |
+
f, f2, f3, f5, f6, f8, f9, f10 = 1, 0, 0, 0, 0, 0, 0, 0
|
196 |
+
verbose = 1
|
197 |
+
emptygen = True
|
198 |
+
dolc = -1
|
199 |
+
dolatexdoc = 0
|
200 |
+
dorestdoc = 0
|
201 |
+
wrapfuncs = 1
|
202 |
+
buildpath = '.'
|
203 |
+
include_paths, inputline = get_includes(inputline)
|
204 |
+
signsfile, modulename = None, None
|
205 |
+
options = {'buildpath': buildpath,
|
206 |
+
'coutput': None,
|
207 |
+
'f2py_wrapper_output': None}
|
208 |
+
for l in inputline:
|
209 |
+
if l == '':
|
210 |
+
pass
|
211 |
+
elif l == 'only:':
|
212 |
+
f = 0
|
213 |
+
elif l == 'skip:':
|
214 |
+
f = -1
|
215 |
+
elif l == ':':
|
216 |
+
f = 1
|
217 |
+
elif l[:8] == '--debug-':
|
218 |
+
debug.append(l[8:])
|
219 |
+
elif l == '--lower':
|
220 |
+
dolc = 1
|
221 |
+
elif l == '--build-dir':
|
222 |
+
f6 = 1
|
223 |
+
elif l == '--no-lower':
|
224 |
+
dolc = 0
|
225 |
+
elif l == '--quiet':
|
226 |
+
verbose = 0
|
227 |
+
elif l == '--verbose':
|
228 |
+
verbose += 1
|
229 |
+
elif l == '--latex-doc':
|
230 |
+
dolatexdoc = 1
|
231 |
+
elif l == '--no-latex-doc':
|
232 |
+
dolatexdoc = 0
|
233 |
+
elif l == '--rest-doc':
|
234 |
+
dorestdoc = 1
|
235 |
+
elif l == '--no-rest-doc':
|
236 |
+
dorestdoc = 0
|
237 |
+
elif l == '--wrap-functions':
|
238 |
+
wrapfuncs = 1
|
239 |
+
elif l == '--no-wrap-functions':
|
240 |
+
wrapfuncs = 0
|
241 |
+
elif l == '--short-latex':
|
242 |
+
options['shortlatex'] = 1
|
243 |
+
elif l == '--coutput':
|
244 |
+
f8 = 1
|
245 |
+
elif l == '--f2py-wrapper-output':
|
246 |
+
f9 = 1
|
247 |
+
elif l == '--f2cmap':
|
248 |
+
f10 = 1
|
249 |
+
elif l == '--overwrite-signature':
|
250 |
+
options['h-overwrite'] = 1
|
251 |
+
elif l == '-h':
|
252 |
+
f2 = 1
|
253 |
+
elif l == '-m':
|
254 |
+
f3 = 1
|
255 |
+
elif l[:2] == '-v':
|
256 |
+
print(f2py_version)
|
257 |
+
sys.exit()
|
258 |
+
elif l == '--show-compilers':
|
259 |
+
f5 = 1
|
260 |
+
elif l[:8] == '-include':
|
261 |
+
cfuncs.outneeds['userincludes'].append(l[9:-1])
|
262 |
+
cfuncs.userincludes[l[9:-1]] = '#include ' + l[8:]
|
263 |
+
elif l == '--skip-empty-wrappers':
|
264 |
+
emptygen = False
|
265 |
+
elif l[0] == '-':
|
266 |
+
errmess('Unknown option %s\n' % repr(l))
|
267 |
+
sys.exit()
|
268 |
+
elif f2:
|
269 |
+
f2 = 0
|
270 |
+
signsfile = l
|
271 |
+
elif f3:
|
272 |
+
f3 = 0
|
273 |
+
modulename = l
|
274 |
+
elif f6:
|
275 |
+
f6 = 0
|
276 |
+
buildpath = l
|
277 |
+
elif f8:
|
278 |
+
f8 = 0
|
279 |
+
options["coutput"] = l
|
280 |
+
elif f9:
|
281 |
+
f9 = 0
|
282 |
+
options["f2py_wrapper_output"] = l
|
283 |
+
elif f10:
|
284 |
+
f10 = 0
|
285 |
+
options["f2cmap_file"] = l
|
286 |
+
elif f == 1:
|
287 |
+
try:
|
288 |
+
with open(l):
|
289 |
+
pass
|
290 |
+
files.append(l)
|
291 |
+
except OSError as detail:
|
292 |
+
errmess(f'OSError: {detail!s}. Skipping file "{l!s}".\n')
|
293 |
+
elif f == -1:
|
294 |
+
skipfuncs.append(l)
|
295 |
+
elif f == 0:
|
296 |
+
onlyfuncs.append(l)
|
297 |
+
if not f5 and not files and not modulename:
|
298 |
+
print(__usage__)
|
299 |
+
sys.exit()
|
300 |
+
if not os.path.isdir(buildpath):
|
301 |
+
if not verbose:
|
302 |
+
outmess('Creating build directory %s\n' % (buildpath))
|
303 |
+
os.mkdir(buildpath)
|
304 |
+
if signsfile:
|
305 |
+
signsfile = os.path.join(buildpath, signsfile)
|
306 |
+
if signsfile and os.path.isfile(signsfile) and 'h-overwrite' not in options:
|
307 |
+
errmess(
|
308 |
+
'Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n' % (signsfile))
|
309 |
+
sys.exit()
|
310 |
+
|
311 |
+
options['emptygen'] = emptygen
|
312 |
+
options['debug'] = debug
|
313 |
+
options['verbose'] = verbose
|
314 |
+
if dolc == -1 and not signsfile:
|
315 |
+
options['do-lower'] = 0
|
316 |
+
else:
|
317 |
+
options['do-lower'] = dolc
|
318 |
+
if modulename:
|
319 |
+
options['module'] = modulename
|
320 |
+
if signsfile:
|
321 |
+
options['signsfile'] = signsfile
|
322 |
+
if onlyfuncs:
|
323 |
+
options['onlyfuncs'] = onlyfuncs
|
324 |
+
if skipfuncs:
|
325 |
+
options['skipfuncs'] = skipfuncs
|
326 |
+
options['dolatexdoc'] = dolatexdoc
|
327 |
+
options['dorestdoc'] = dorestdoc
|
328 |
+
options['wrapfuncs'] = wrapfuncs
|
329 |
+
options['buildpath'] = buildpath
|
330 |
+
options['include_paths'] = include_paths
|
331 |
+
options.setdefault('f2cmap_file', None)
|
332 |
+
return files, options
|
333 |
+
|
334 |
+
|
335 |
+
def callcrackfortran(files, options):
|
336 |
+
rules.options = options
|
337 |
+
crackfortran.debug = options['debug']
|
338 |
+
crackfortran.verbose = options['verbose']
|
339 |
+
if 'module' in options:
|
340 |
+
crackfortran.f77modulename = options['module']
|
341 |
+
if 'skipfuncs' in options:
|
342 |
+
crackfortran.skipfuncs = options['skipfuncs']
|
343 |
+
if 'onlyfuncs' in options:
|
344 |
+
crackfortran.onlyfuncs = options['onlyfuncs']
|
345 |
+
crackfortran.include_paths[:] = options['include_paths']
|
346 |
+
crackfortran.dolowercase = options['do-lower']
|
347 |
+
postlist = crackfortran.crackfortran(files)
|
348 |
+
if 'signsfile' in options:
|
349 |
+
outmess('Saving signatures to file "%s"\n' % (options['signsfile']))
|
350 |
+
pyf = crackfortran.crack2fortran(postlist)
|
351 |
+
if options['signsfile'][-6:] == 'stdout':
|
352 |
+
sys.stdout.write(pyf)
|
353 |
+
else:
|
354 |
+
with open(options['signsfile'], 'w') as f:
|
355 |
+
f.write(pyf)
|
356 |
+
if options["coutput"] is None:
|
357 |
+
for mod in postlist:
|
358 |
+
mod["coutput"] = "%smodule.c" % mod["name"]
|
359 |
+
else:
|
360 |
+
for mod in postlist:
|
361 |
+
mod["coutput"] = options["coutput"]
|
362 |
+
if options["f2py_wrapper_output"] is None:
|
363 |
+
for mod in postlist:
|
364 |
+
mod["f2py_wrapper_output"] = "%s-f2pywrappers.f" % mod["name"]
|
365 |
+
else:
|
366 |
+
for mod in postlist:
|
367 |
+
mod["f2py_wrapper_output"] = options["f2py_wrapper_output"]
|
368 |
+
return postlist
|
369 |
+
|
370 |
+
|
371 |
+
def buildmodules(lst):
|
372 |
+
cfuncs.buildcfuncs()
|
373 |
+
outmess('Building modules...\n')
|
374 |
+
modules, mnames, isusedby = [], [], {}
|
375 |
+
for item in lst:
|
376 |
+
if '__user__' in item['name']:
|
377 |
+
cb_rules.buildcallbacks(item)
|
378 |
+
else:
|
379 |
+
if 'use' in item:
|
380 |
+
for u in item['use'].keys():
|
381 |
+
if u not in isusedby:
|
382 |
+
isusedby[u] = []
|
383 |
+
isusedby[u].append(item['name'])
|
384 |
+
modules.append(item)
|
385 |
+
mnames.append(item['name'])
|
386 |
+
ret = {}
|
387 |
+
for module, name in zip(modules, mnames):
|
388 |
+
if name in isusedby:
|
389 |
+
outmess('\tSkipping module "%s" which is used by %s.\n' % (
|
390 |
+
name, ','.join('"%s"' % s for s in isusedby[name])))
|
391 |
+
else:
|
392 |
+
um = []
|
393 |
+
if 'use' in module:
|
394 |
+
for u in module['use'].keys():
|
395 |
+
if u in isusedby and u in mnames:
|
396 |
+
um.append(modules[mnames.index(u)])
|
397 |
+
else:
|
398 |
+
outmess(
|
399 |
+
f'\tModule "{name}" uses nonexisting "{u}" '
|
400 |
+
'which will be ignored.\n')
|
401 |
+
ret[name] = {}
|
402 |
+
dict_append(ret[name], rules.buildmodule(module, um))
|
403 |
+
return ret
|
404 |
+
|
405 |
+
|
406 |
+
def dict_append(d_out, d_in):
|
407 |
+
for (k, v) in d_in.items():
|
408 |
+
if k not in d_out:
|
409 |
+
d_out[k] = []
|
410 |
+
if isinstance(v, list):
|
411 |
+
d_out[k] = d_out[k] + v
|
412 |
+
else:
|
413 |
+
d_out[k].append(v)
|
414 |
+
|
415 |
+
|
416 |
+
def run_main(comline_list):
|
417 |
+
"""
|
418 |
+
Equivalent to running::
|
419 |
+
|
420 |
+
f2py <args>
|
421 |
+
|
422 |
+
where ``<args>=string.join(<list>,' ')``, but in Python. Unless
|
423 |
+
``-h`` is used, this function returns a dictionary containing
|
424 |
+
information on generated modules and their dependencies on source
|
425 |
+
files.
|
426 |
+
|
427 |
+
You cannot build extension modules with this function, that is,
|
428 |
+
using ``-c`` is not allowed. Use the ``compile`` command instead.
|
429 |
+
|
430 |
+
Examples
|
431 |
+
--------
|
432 |
+
The command ``f2py -m scalar scalar.f`` can be executed from Python as
|
433 |
+
follows.
|
434 |
+
|
435 |
+
.. literalinclude:: ../../source/f2py/code/results/run_main_session.dat
|
436 |
+
:language: python
|
437 |
+
|
438 |
+
"""
|
439 |
+
crackfortran.reset_global_f2py_vars()
|
440 |
+
f2pydir = os.path.dirname(os.path.abspath(cfuncs.__file__))
|
441 |
+
fobjhsrc = os.path.join(f2pydir, 'src', 'fortranobject.h')
|
442 |
+
fobjcsrc = os.path.join(f2pydir, 'src', 'fortranobject.c')
|
443 |
+
# gh-22819 -- begin
|
444 |
+
parser = make_f2py_compile_parser()
|
445 |
+
args, comline_list = parser.parse_known_args(comline_list)
|
446 |
+
pyf_files, _ = filter_files("", "[.]pyf([.]src|)", comline_list)
|
447 |
+
# Checks that no existing modulename is defined in a pyf file
|
448 |
+
# TODO: Remove all this when scaninputline is replaced
|
449 |
+
if args.module_name:
|
450 |
+
if "-h" in comline_list:
|
451 |
+
modname = (
|
452 |
+
args.module_name
|
453 |
+
) # Directly use from args when -h is present
|
454 |
+
else:
|
455 |
+
modname = validate_modulename(
|
456 |
+
pyf_files, args.module_name
|
457 |
+
) # Validate modname when -h is not present
|
458 |
+
comline_list += ['-m', modname] # needed for the rest of scaninputline
|
459 |
+
# gh-22819 -- end
|
460 |
+
files, options = scaninputline(comline_list)
|
461 |
+
auxfuncs.options = options
|
462 |
+
capi_maps.load_f2cmap_file(options['f2cmap_file'])
|
463 |
+
postlist = callcrackfortran(files, options)
|
464 |
+
isusedby = {}
|
465 |
+
for plist in postlist:
|
466 |
+
if 'use' in plist:
|
467 |
+
for u in plist['use'].keys():
|
468 |
+
if u not in isusedby:
|
469 |
+
isusedby[u] = []
|
470 |
+
isusedby[u].append(plist['name'])
|
471 |
+
for plist in postlist:
|
472 |
+
if plist['block'] == 'python module' and '__user__' in plist['name']:
|
473 |
+
if plist['name'] in isusedby:
|
474 |
+
# if not quiet:
|
475 |
+
outmess(
|
476 |
+
f'Skipping Makefile build for module "{plist["name"]}" '
|
477 |
+
'which is used by {}\n'.format(
|
478 |
+
','.join(f'"{s}"' for s in isusedby[plist['name']])))
|
479 |
+
if 'signsfile' in options:
|
480 |
+
if options['verbose'] > 1:
|
481 |
+
outmess(
|
482 |
+
'Stopping. Edit the signature file and then run f2py on the signature file: ')
|
483 |
+
outmess('%s %s\n' %
|
484 |
+
(os.path.basename(sys.argv[0]), options['signsfile']))
|
485 |
+
return
|
486 |
+
for plist in postlist:
|
487 |
+
if plist['block'] != 'python module':
|
488 |
+
if 'python module' not in options:
|
489 |
+
errmess(
|
490 |
+
'Tip: If your original code is Fortran source then you must use -m option.\n')
|
491 |
+
raise TypeError('All blocks must be python module blocks but got %s' % (
|
492 |
+
repr(plist['block'])))
|
493 |
+
auxfuncs.debugoptions = options['debug']
|
494 |
+
f90mod_rules.options = options
|
495 |
+
auxfuncs.wrapfuncs = options['wrapfuncs']
|
496 |
+
|
497 |
+
ret = buildmodules(postlist)
|
498 |
+
|
499 |
+
for mn in ret.keys():
|
500 |
+
dict_append(ret[mn], {'csrc': fobjcsrc, 'h': fobjhsrc})
|
501 |
+
return ret
|
502 |
+
|
503 |
+
|
504 |
+
def filter_files(prefix, suffix, files, remove_prefix=None):
|
505 |
+
"""
|
506 |
+
Filter files by prefix and suffix.
|
507 |
+
"""
|
508 |
+
filtered, rest = [], []
|
509 |
+
match = re.compile(prefix + r'.*' + suffix + r'\Z').match
|
510 |
+
if remove_prefix:
|
511 |
+
ind = len(prefix)
|
512 |
+
else:
|
513 |
+
ind = 0
|
514 |
+
for file in [x.strip() for x in files]:
|
515 |
+
if match(file):
|
516 |
+
filtered.append(file[ind:])
|
517 |
+
else:
|
518 |
+
rest.append(file)
|
519 |
+
return filtered, rest
|
520 |
+
|
521 |
+
|
522 |
+
def get_prefix(module):
|
523 |
+
p = os.path.dirname(os.path.dirname(module.__file__))
|
524 |
+
return p
|
525 |
+
|
526 |
+
|
527 |
+
class CombineIncludePaths(argparse.Action):
|
528 |
+
def __call__(self, parser, namespace, values, option_string=None):
|
529 |
+
include_paths_set = set(getattr(namespace, 'include_paths', []) or [])
|
530 |
+
if option_string == "--include_paths":
|
531 |
+
outmess("Use --include-paths or -I instead of --include_paths which will be removed")
|
532 |
+
if option_string == "--include-paths" or option_string == "--include_paths":
|
533 |
+
include_paths_set.update(values.split(':'))
|
534 |
+
else:
|
535 |
+
include_paths_set.add(values)
|
536 |
+
setattr(namespace, 'include_paths', list(include_paths_set))
|
537 |
+
|
538 |
+
def include_parser():
|
539 |
+
parser = argparse.ArgumentParser(add_help=False)
|
540 |
+
parser.add_argument("-I", dest="include_paths", action=CombineIncludePaths)
|
541 |
+
parser.add_argument("--include-paths", dest="include_paths", action=CombineIncludePaths)
|
542 |
+
parser.add_argument("--include_paths", dest="include_paths", action=CombineIncludePaths)
|
543 |
+
return parser
|
544 |
+
|
545 |
+
def get_includes(iline):
|
546 |
+
iline = (' '.join(iline)).split()
|
547 |
+
parser = include_parser()
|
548 |
+
args, remain = parser.parse_known_args(iline)
|
549 |
+
ipaths = args.include_paths
|
550 |
+
if args.include_paths is None:
|
551 |
+
ipaths = []
|
552 |
+
return ipaths, remain
|
553 |
+
|
554 |
+
def make_f2py_compile_parser():
|
555 |
+
parser = argparse.ArgumentParser(add_help=False)
|
556 |
+
parser.add_argument("--dep", action="append", dest="dependencies")
|
557 |
+
parser.add_argument("--backend", choices=['meson', 'distutils'], default='distutils')
|
558 |
+
parser.add_argument("-m", dest="module_name")
|
559 |
+
return parser
|
560 |
+
|
561 |
+
def preparse_sysargv():
|
562 |
+
# To keep backwards bug compatibility, newer flags are handled by argparse,
|
563 |
+
# and `sys.argv` is passed to the rest of `f2py` as is.
|
564 |
+
parser = make_f2py_compile_parser()
|
565 |
+
|
566 |
+
args, remaining_argv = parser.parse_known_args()
|
567 |
+
sys.argv = [sys.argv[0]] + remaining_argv
|
568 |
+
|
569 |
+
backend_key = args.backend
|
570 |
+
if MESON_ONLY_VER and backend_key == 'distutils':
|
571 |
+
outmess("Cannot use distutils backend with Python>=3.12,"
|
572 |
+
" using meson backend instead.\n")
|
573 |
+
backend_key = "meson"
|
574 |
+
|
575 |
+
return {
|
576 |
+
"dependencies": args.dependencies or [],
|
577 |
+
"backend": backend_key,
|
578 |
+
"modulename": args.module_name,
|
579 |
+
}
|
580 |
+
|
581 |
+
def run_compile():
|
582 |
+
"""
|
583 |
+
Do it all in one call!
|
584 |
+
"""
|
585 |
+
import tempfile
|
586 |
+
|
587 |
+
# Collect dependency flags, preprocess sys.argv
|
588 |
+
argy = preparse_sysargv()
|
589 |
+
modulename = argy["modulename"]
|
590 |
+
if modulename is None:
|
591 |
+
modulename = 'untitled'
|
592 |
+
dependencies = argy["dependencies"]
|
593 |
+
backend_key = argy["backend"]
|
594 |
+
build_backend = f2py_build_generator(backend_key)
|
595 |
+
|
596 |
+
i = sys.argv.index('-c')
|
597 |
+
del sys.argv[i]
|
598 |
+
|
599 |
+
remove_build_dir = 0
|
600 |
+
try:
|
601 |
+
i = sys.argv.index('--build-dir')
|
602 |
+
except ValueError:
|
603 |
+
i = None
|
604 |
+
if i is not None:
|
605 |
+
build_dir = sys.argv[i + 1]
|
606 |
+
del sys.argv[i + 1]
|
607 |
+
del sys.argv[i]
|
608 |
+
else:
|
609 |
+
remove_build_dir = 1
|
610 |
+
build_dir = tempfile.mkdtemp()
|
611 |
+
|
612 |
+
_reg1 = re.compile(r'--link-')
|
613 |
+
sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)]
|
614 |
+
sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags]
|
615 |
+
if sysinfo_flags:
|
616 |
+
sysinfo_flags = [f[7:] for f in sysinfo_flags]
|
617 |
+
|
618 |
+
_reg2 = re.compile(
|
619 |
+
r'--((no-|)(wrap-functions|lower)|debug-capi|quiet|skip-empty-wrappers)|-include')
|
620 |
+
f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)]
|
621 |
+
sys.argv = [_m for _m in sys.argv if _m not in f2py_flags]
|
622 |
+
f2py_flags2 = []
|
623 |
+
fl = 0
|
624 |
+
for a in sys.argv[1:]:
|
625 |
+
if a in ['only:', 'skip:']:
|
626 |
+
fl = 1
|
627 |
+
elif a == ':':
|
628 |
+
fl = 0
|
629 |
+
if fl or a == ':':
|
630 |
+
f2py_flags2.append(a)
|
631 |
+
if f2py_flags2 and f2py_flags2[-1] != ':':
|
632 |
+
f2py_flags2.append(':')
|
633 |
+
f2py_flags.extend(f2py_flags2)
|
634 |
+
sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2]
|
635 |
+
_reg3 = re.compile(
|
636 |
+
r'--((f(90)?compiler(-exec|)|compiler)=|help-compiler)')
|
637 |
+
flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)]
|
638 |
+
sys.argv = [_m for _m in sys.argv if _m not in flib_flags]
|
639 |
+
_reg4 = re.compile(
|
640 |
+
r'--((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help-fcompiler))')
|
641 |
+
fc_flags = [_m for _m in sys.argv[1:] if _reg4.match(_m)]
|
642 |
+
sys.argv = [_m for _m in sys.argv if _m not in fc_flags]
|
643 |
+
|
644 |
+
del_list = []
|
645 |
+
for s in flib_flags:
|
646 |
+
v = '--fcompiler='
|
647 |
+
if s[:len(v)] == v:
|
648 |
+
if MESON_ONLY_VER or backend_key == 'meson':
|
649 |
+
outmess(
|
650 |
+
"--fcompiler cannot be used with meson,"
|
651 |
+
"set compiler with the FC environment variable\n"
|
652 |
+
)
|
653 |
+
else:
|
654 |
+
from numpy.distutils import fcompiler
|
655 |
+
fcompiler.load_all_fcompiler_classes()
|
656 |
+
allowed_keys = list(fcompiler.fcompiler_class.keys())
|
657 |
+
nv = ov = s[len(v):].lower()
|
658 |
+
if ov not in allowed_keys:
|
659 |
+
vmap = {} # XXX
|
660 |
+
try:
|
661 |
+
nv = vmap[ov]
|
662 |
+
except KeyError:
|
663 |
+
if ov not in vmap.values():
|
664 |
+
print('Unknown vendor: "%s"' % (s[len(v):]))
|
665 |
+
nv = ov
|
666 |
+
i = flib_flags.index(s)
|
667 |
+
flib_flags[i] = '--fcompiler=' + nv
|
668 |
+
continue
|
669 |
+
for s in del_list:
|
670 |
+
i = flib_flags.index(s)
|
671 |
+
del flib_flags[i]
|
672 |
+
assert len(flib_flags) <= 2, repr(flib_flags)
|
673 |
+
|
674 |
+
_reg5 = re.compile(r'--(verbose)')
|
675 |
+
setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)]
|
676 |
+
sys.argv = [_m for _m in sys.argv if _m not in setup_flags]
|
677 |
+
|
678 |
+
if '--quiet' in f2py_flags:
|
679 |
+
setup_flags.append('--quiet')
|
680 |
+
|
681 |
+
# Ugly filter to remove everything but sources
|
682 |
+
sources = sys.argv[1:]
|
683 |
+
f2cmapopt = '--f2cmap'
|
684 |
+
if f2cmapopt in sys.argv:
|
685 |
+
i = sys.argv.index(f2cmapopt)
|
686 |
+
f2py_flags.extend(sys.argv[i:i + 2])
|
687 |
+
del sys.argv[i + 1], sys.argv[i]
|
688 |
+
sources = sys.argv[1:]
|
689 |
+
|
690 |
+
pyf_files, _sources = filter_files("", "[.]pyf([.]src|)", sources)
|
691 |
+
sources = pyf_files + _sources
|
692 |
+
modulename = validate_modulename(pyf_files, modulename)
|
693 |
+
extra_objects, sources = filter_files('', '[.](o|a|so|dylib)', sources)
|
694 |
+
library_dirs, sources = filter_files('-L', '', sources, remove_prefix=1)
|
695 |
+
libraries, sources = filter_files('-l', '', sources, remove_prefix=1)
|
696 |
+
undef_macros, sources = filter_files('-U', '', sources, remove_prefix=1)
|
697 |
+
define_macros, sources = filter_files('-D', '', sources, remove_prefix=1)
|
698 |
+
for i in range(len(define_macros)):
|
699 |
+
name_value = define_macros[i].split('=', 1)
|
700 |
+
if len(name_value) == 1:
|
701 |
+
name_value.append(None)
|
702 |
+
if len(name_value) == 2:
|
703 |
+
define_macros[i] = tuple(name_value)
|
704 |
+
else:
|
705 |
+
print('Invalid use of -D:', name_value)
|
706 |
+
|
707 |
+
# Construct wrappers / signatures / things
|
708 |
+
if backend_key == 'meson':
|
709 |
+
if not pyf_files:
|
710 |
+
outmess('Using meson backend\nWill pass --lower to f2py\nSee https://numpy.org/doc/stable/f2py/buildtools/meson.html\n')
|
711 |
+
f2py_flags.append('--lower')
|
712 |
+
run_main(f" {' '.join(f2py_flags)} -m {modulename} {' '.join(sources)}".split())
|
713 |
+
else:
|
714 |
+
run_main(f" {' '.join(f2py_flags)} {' '.join(pyf_files)}".split())
|
715 |
+
|
716 |
+
# Order matters here, includes are needed for run_main above
|
717 |
+
include_dirs, sources = get_includes(sources)
|
718 |
+
# Now use the builder
|
719 |
+
builder = build_backend(
|
720 |
+
modulename,
|
721 |
+
sources,
|
722 |
+
extra_objects,
|
723 |
+
build_dir,
|
724 |
+
include_dirs,
|
725 |
+
library_dirs,
|
726 |
+
libraries,
|
727 |
+
define_macros,
|
728 |
+
undef_macros,
|
729 |
+
f2py_flags,
|
730 |
+
sysinfo_flags,
|
731 |
+
fc_flags,
|
732 |
+
flib_flags,
|
733 |
+
setup_flags,
|
734 |
+
remove_build_dir,
|
735 |
+
{"dependencies": dependencies},
|
736 |
+
)
|
737 |
+
|
738 |
+
builder.compile()
|
739 |
+
|
740 |
+
|
741 |
+
def validate_modulename(pyf_files, modulename='untitled'):
|
742 |
+
if len(pyf_files) > 1:
|
743 |
+
raise ValueError("Only one .pyf file per call")
|
744 |
+
if pyf_files:
|
745 |
+
pyff = pyf_files[0]
|
746 |
+
pyf_modname = auxfuncs.get_f2py_modulename(pyff)
|
747 |
+
if modulename != pyf_modname:
|
748 |
+
outmess(
|
749 |
+
f"Ignoring -m {modulename}.\n"
|
750 |
+
f"{pyff} defines {pyf_modname} to be the modulename.\n"
|
751 |
+
)
|
752 |
+
modulename = pyf_modname
|
753 |
+
return modulename
|
754 |
+
|
755 |
+
def main():
|
756 |
+
if '--help-link' in sys.argv[1:]:
|
757 |
+
sys.argv.remove('--help-link')
|
758 |
+
if MESON_ONLY_VER:
|
759 |
+
outmess("Use --dep for meson builds\n")
|
760 |
+
else:
|
761 |
+
from numpy.distutils.system_info import show_all
|
762 |
+
show_all()
|
763 |
+
return
|
764 |
+
|
765 |
+
if '-c' in sys.argv[1:]:
|
766 |
+
run_compile()
|
767 |
+
else:
|
768 |
+
run_main(sys.argv[1:])
|
venv/lib/python3.10/site-packages/numpy/f2py/f90mod_rules.py
ADDED
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Build F90 module support for f2py2e.
|
3 |
+
|
4 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
5 |
+
Copyright 2011 -- present NumPy Developers.
|
6 |
+
Permission to use, modify, and distribute this software is given under the
|
7 |
+
terms of the NumPy License.
|
8 |
+
|
9 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
10 |
+
"""
|
11 |
+
__version__ = "$Revision: 1.27 $"[10:-1]
|
12 |
+
|
13 |
+
f2py_version = 'See `f2py -v`'
|
14 |
+
|
15 |
+
import numpy as np
|
16 |
+
|
17 |
+
from . import capi_maps
|
18 |
+
from . import func2subr
|
19 |
+
from .crackfortran import undo_rmbadname, undo_rmbadname1
|
20 |
+
|
21 |
+
# The environment provided by auxfuncs.py is needed for some calls to eval.
|
22 |
+
# As the needed functions cannot be determined by static inspection of the
|
23 |
+
# code, it is safest to use import * pending a major refactoring of f2py.
|
24 |
+
from .auxfuncs import *
|
25 |
+
|
26 |
+
options = {}
|
27 |
+
|
28 |
+
|
29 |
+
def findf90modules(m):
|
30 |
+
if ismodule(m):
|
31 |
+
return [m]
|
32 |
+
if not hasbody(m):
|
33 |
+
return []
|
34 |
+
ret = []
|
35 |
+
for b in m['body']:
|
36 |
+
if ismodule(b):
|
37 |
+
ret.append(b)
|
38 |
+
else:
|
39 |
+
ret = ret + findf90modules(b)
|
40 |
+
return ret
|
41 |
+
|
42 |
+
fgetdims1 = """\
|
43 |
+
external f2pysetdata
|
44 |
+
logical ns
|
45 |
+
integer r,i
|
46 |
+
integer(%d) s(*)
|
47 |
+
ns = .FALSE.
|
48 |
+
if (allocated(d)) then
|
49 |
+
do i=1,r
|
50 |
+
if ((size(d,i).ne.s(i)).and.(s(i).ge.0)) then
|
51 |
+
ns = .TRUE.
|
52 |
+
end if
|
53 |
+
end do
|
54 |
+
if (ns) then
|
55 |
+
deallocate(d)
|
56 |
+
end if
|
57 |
+
end if
|
58 |
+
if ((.not.allocated(d)).and.(s(1).ge.1)) then""" % np.intp().itemsize
|
59 |
+
|
60 |
+
fgetdims2 = """\
|
61 |
+
end if
|
62 |
+
if (allocated(d)) then
|
63 |
+
do i=1,r
|
64 |
+
s(i) = size(d,i)
|
65 |
+
end do
|
66 |
+
end if
|
67 |
+
flag = 1
|
68 |
+
call f2pysetdata(d,allocated(d))"""
|
69 |
+
|
70 |
+
fgetdims2_sa = """\
|
71 |
+
end if
|
72 |
+
if (allocated(d)) then
|
73 |
+
do i=1,r
|
74 |
+
s(i) = size(d,i)
|
75 |
+
end do
|
76 |
+
!s(r) must be equal to len(d(1))
|
77 |
+
end if
|
78 |
+
flag = 2
|
79 |
+
call f2pysetdata(d,allocated(d))"""
|
80 |
+
|
81 |
+
|
82 |
+
def buildhooks(pymod):
|
83 |
+
from . import rules
|
84 |
+
ret = {'f90modhooks': [], 'initf90modhooks': [], 'body': [],
|
85 |
+
'need': ['F_FUNC', 'arrayobject.h'],
|
86 |
+
'separatorsfor': {'includes0': '\n', 'includes': '\n'},
|
87 |
+
'docs': ['"Fortran 90/95 modules:\\n"'],
|
88 |
+
'latexdoc': []}
|
89 |
+
fhooks = ['']
|
90 |
+
|
91 |
+
def fadd(line, s=fhooks):
|
92 |
+
s[0] = '%s\n %s' % (s[0], line)
|
93 |
+
doc = ['']
|
94 |
+
|
95 |
+
def dadd(line, s=doc):
|
96 |
+
s[0] = '%s\n%s' % (s[0], line)
|
97 |
+
|
98 |
+
usenames = getuseblocks(pymod)
|
99 |
+
for m in findf90modules(pymod):
|
100 |
+
sargs, fargs, efargs, modobjs, notvars, onlyvars = [], [], [], [], [
|
101 |
+
m['name']], []
|
102 |
+
sargsp = []
|
103 |
+
ifargs = []
|
104 |
+
mfargs = []
|
105 |
+
if hasbody(m):
|
106 |
+
for b in m['body']:
|
107 |
+
notvars.append(b['name'])
|
108 |
+
for n in m['vars'].keys():
|
109 |
+
var = m['vars'][n]
|
110 |
+
if (n not in notvars) and (not l_or(isintent_hide, isprivate)(var)):
|
111 |
+
onlyvars.append(n)
|
112 |
+
mfargs.append(n)
|
113 |
+
outmess('\t\tConstructing F90 module support for "%s"...\n' %
|
114 |
+
(m['name']))
|
115 |
+
if m['name'] in usenames and not onlyvars:
|
116 |
+
outmess(f"\t\t\tSkipping {m['name']} since it is in 'use'...\n")
|
117 |
+
continue
|
118 |
+
if onlyvars:
|
119 |
+
outmess('\t\t Variables: %s\n' % (' '.join(onlyvars)))
|
120 |
+
chooks = ['']
|
121 |
+
|
122 |
+
def cadd(line, s=chooks):
|
123 |
+
s[0] = '%s\n%s' % (s[0], line)
|
124 |
+
ihooks = ['']
|
125 |
+
|
126 |
+
def iadd(line, s=ihooks):
|
127 |
+
s[0] = '%s\n%s' % (s[0], line)
|
128 |
+
|
129 |
+
vrd = capi_maps.modsign2map(m)
|
130 |
+
cadd('static FortranDataDef f2py_%s_def[] = {' % (m['name']))
|
131 |
+
dadd('\\subsection{Fortran 90/95 module \\texttt{%s}}\n' % (m['name']))
|
132 |
+
if hasnote(m):
|
133 |
+
note = m['note']
|
134 |
+
if isinstance(note, list):
|
135 |
+
note = '\n'.join(note)
|
136 |
+
dadd(note)
|
137 |
+
if onlyvars:
|
138 |
+
dadd('\\begin{description}')
|
139 |
+
for n in onlyvars:
|
140 |
+
var = m['vars'][n]
|
141 |
+
modobjs.append(n)
|
142 |
+
ct = capi_maps.getctype(var)
|
143 |
+
at = capi_maps.c2capi_map[ct]
|
144 |
+
dm = capi_maps.getarrdims(n, var)
|
145 |
+
dms = dm['dims'].replace('*', '-1').strip()
|
146 |
+
dms = dms.replace(':', '-1').strip()
|
147 |
+
if not dms:
|
148 |
+
dms = '-1'
|
149 |
+
use_fgetdims2 = fgetdims2
|
150 |
+
cadd('\t{"%s",%s,{{%s}},%s, %s},' %
|
151 |
+
(undo_rmbadname1(n), dm['rank'], dms, at,
|
152 |
+
capi_maps.get_elsize(var)))
|
153 |
+
dadd('\\item[]{{}\\verb@%s@{}}' %
|
154 |
+
(capi_maps.getarrdocsign(n, var)))
|
155 |
+
if hasnote(var):
|
156 |
+
note = var['note']
|
157 |
+
if isinstance(note, list):
|
158 |
+
note = '\n'.join(note)
|
159 |
+
dadd('--- %s' % (note))
|
160 |
+
if isallocatable(var):
|
161 |
+
fargs.append('f2py_%s_getdims_%s' % (m['name'], n))
|
162 |
+
efargs.append(fargs[-1])
|
163 |
+
sargs.append(
|
164 |
+
'void (*%s)(int*,npy_intp*,void(*)(char*,npy_intp*),int*)' % (n))
|
165 |
+
sargsp.append('void (*)(int*,npy_intp*,void(*)(char*,npy_intp*),int*)')
|
166 |
+
iadd('\tf2py_%s_def[i_f2py++].func = %s;' % (m['name'], n))
|
167 |
+
fadd('subroutine %s(r,s,f2pysetdata,flag)' % (fargs[-1]))
|
168 |
+
fadd('use %s, only: d => %s\n' %
|
169 |
+
(m['name'], undo_rmbadname1(n)))
|
170 |
+
fadd('integer flag\n')
|
171 |
+
fhooks[0] = fhooks[0] + fgetdims1
|
172 |
+
dms = range(1, int(dm['rank']) + 1)
|
173 |
+
fadd(' allocate(d(%s))\n' %
|
174 |
+
(','.join(['s(%s)' % i for i in dms])))
|
175 |
+
fhooks[0] = fhooks[0] + use_fgetdims2
|
176 |
+
fadd('end subroutine %s' % (fargs[-1]))
|
177 |
+
else:
|
178 |
+
fargs.append(n)
|
179 |
+
sargs.append('char *%s' % (n))
|
180 |
+
sargsp.append('char*')
|
181 |
+
iadd('\tf2py_%s_def[i_f2py++].data = %s;' % (m['name'], n))
|
182 |
+
if onlyvars:
|
183 |
+
dadd('\\end{description}')
|
184 |
+
if hasbody(m):
|
185 |
+
for b in m['body']:
|
186 |
+
if not isroutine(b):
|
187 |
+
outmess("f90mod_rules.buildhooks:"
|
188 |
+
f" skipping {b['block']} {b['name']}\n")
|
189 |
+
continue
|
190 |
+
modobjs.append('%s()' % (b['name']))
|
191 |
+
b['modulename'] = m['name']
|
192 |
+
api, wrap = rules.buildapi(b)
|
193 |
+
if isfunction(b):
|
194 |
+
fhooks[0] = fhooks[0] + wrap
|
195 |
+
fargs.append('f2pywrap_%s_%s' % (m['name'], b['name']))
|
196 |
+
ifargs.append(func2subr.createfuncwrapper(b, signature=1))
|
197 |
+
else:
|
198 |
+
if wrap:
|
199 |
+
fhooks[0] = fhooks[0] + wrap
|
200 |
+
fargs.append('f2pywrap_%s_%s' % (m['name'], b['name']))
|
201 |
+
ifargs.append(
|
202 |
+
func2subr.createsubrwrapper(b, signature=1))
|
203 |
+
else:
|
204 |
+
fargs.append(b['name'])
|
205 |
+
mfargs.append(fargs[-1])
|
206 |
+
api['externroutines'] = []
|
207 |
+
ar = applyrules(api, vrd)
|
208 |
+
ar['docs'] = []
|
209 |
+
ar['docshort'] = []
|
210 |
+
ret = dictappend(ret, ar)
|
211 |
+
cadd(('\t{"%s",-1,{{-1}},0,0,NULL,(void *)'
|
212 |
+
'f2py_rout_#modulename#_%s_%s,'
|
213 |
+
'doc_f2py_rout_#modulename#_%s_%s},')
|
214 |
+
% (b['name'], m['name'], b['name'], m['name'], b['name']))
|
215 |
+
sargs.append('char *%s' % (b['name']))
|
216 |
+
sargsp.append('char *')
|
217 |
+
iadd('\tf2py_%s_def[i_f2py++].data = %s;' %
|
218 |
+
(m['name'], b['name']))
|
219 |
+
cadd('\t{NULL}\n};\n')
|
220 |
+
iadd('}')
|
221 |
+
ihooks[0] = 'static void f2py_setup_%s(%s) {\n\tint i_f2py=0;%s' % (
|
222 |
+
m['name'], ','.join(sargs), ihooks[0])
|
223 |
+
if '_' in m['name']:
|
224 |
+
F_FUNC = 'F_FUNC_US'
|
225 |
+
else:
|
226 |
+
F_FUNC = 'F_FUNC'
|
227 |
+
iadd('extern void %s(f2pyinit%s,F2PYINIT%s)(void (*)(%s));'
|
228 |
+
% (F_FUNC, m['name'], m['name'].upper(), ','.join(sargsp)))
|
229 |
+
iadd('static void f2py_init_%s(void) {' % (m['name']))
|
230 |
+
iadd('\t%s(f2pyinit%s,F2PYINIT%s)(f2py_setup_%s);'
|
231 |
+
% (F_FUNC, m['name'], m['name'].upper(), m['name']))
|
232 |
+
iadd('}\n')
|
233 |
+
ret['f90modhooks'] = ret['f90modhooks'] + chooks + ihooks
|
234 |
+
ret['initf90modhooks'] = ['\tPyDict_SetItemString(d, "%s", PyFortranObject_New(f2py_%s_def,f2py_init_%s));' % (
|
235 |
+
m['name'], m['name'], m['name'])] + ret['initf90modhooks']
|
236 |
+
fadd('')
|
237 |
+
fadd('subroutine f2pyinit%s(f2pysetupfunc)' % (m['name']))
|
238 |
+
if mfargs:
|
239 |
+
for a in undo_rmbadname(mfargs):
|
240 |
+
fadd('use %s, only : %s' % (m['name'], a))
|
241 |
+
if ifargs:
|
242 |
+
fadd(' '.join(['interface'] + ifargs))
|
243 |
+
fadd('end interface')
|
244 |
+
fadd('external f2pysetupfunc')
|
245 |
+
if efargs:
|
246 |
+
for a in undo_rmbadname(efargs):
|
247 |
+
fadd('external %s' % (a))
|
248 |
+
fadd('call f2pysetupfunc(%s)' % (','.join(undo_rmbadname(fargs))))
|
249 |
+
fadd('end subroutine f2pyinit%s\n' % (m['name']))
|
250 |
+
|
251 |
+
dadd('\n'.join(ret['latexdoc']).replace(
|
252 |
+
r'\subsection{', r'\subsubsection{'))
|
253 |
+
|
254 |
+
ret['latexdoc'] = []
|
255 |
+
ret['docs'].append('"\t%s --- %s"' % (m['name'],
|
256 |
+
','.join(undo_rmbadname(modobjs))))
|
257 |
+
|
258 |
+
ret['routine_defs'] = ''
|
259 |
+
ret['doc'] = []
|
260 |
+
ret['docshort'] = []
|
261 |
+
ret['latexdoc'] = doc[0]
|
262 |
+
if len(ret['docs']) <= 1:
|
263 |
+
ret['docs'] = ''
|
264 |
+
return ret, fhooks[0]
|
venv/lib/python3.10/site-packages/numpy/f2py/func2subr.py
ADDED
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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building C/API module with f2py2e.
|
4 |
+
|
5 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
6 |
+
Copyright 2011 -- present NumPy Developers.
|
7 |
+
Permission to use, modify, and distribute this software is given under the
|
8 |
+
terms of the NumPy License.
|
9 |
+
|
10 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
11 |
+
"""
|
12 |
+
import copy
|
13 |
+
|
14 |
+
from .auxfuncs import (
|
15 |
+
getfortranname, isexternal, isfunction, isfunction_wrap, isintent_in,
|
16 |
+
isintent_out, islogicalfunction, ismoduleroutine, isscalar,
|
17 |
+
issubroutine, issubroutine_wrap, outmess, show
|
18 |
+
)
|
19 |
+
|
20 |
+
from ._isocbind import isoc_kindmap
|
21 |
+
|
22 |
+
def var2fixfortran(vars, a, fa=None, f90mode=None):
|
23 |
+
if fa is None:
|
24 |
+
fa = a
|
25 |
+
if a not in vars:
|
26 |
+
show(vars)
|
27 |
+
outmess('var2fixfortran: No definition for argument "%s".\n' % a)
|
28 |
+
return ''
|
29 |
+
if 'typespec' not in vars[a]:
|
30 |
+
show(vars[a])
|
31 |
+
outmess('var2fixfortran: No typespec for argument "%s".\n' % a)
|
32 |
+
return ''
|
33 |
+
vardef = vars[a]['typespec']
|
34 |
+
if vardef == 'type' and 'typename' in vars[a]:
|
35 |
+
vardef = '%s(%s)' % (vardef, vars[a]['typename'])
|
36 |
+
selector = {}
|
37 |
+
lk = ''
|
38 |
+
if 'kindselector' in vars[a]:
|
39 |
+
selector = vars[a]['kindselector']
|
40 |
+
lk = 'kind'
|
41 |
+
elif 'charselector' in vars[a]:
|
42 |
+
selector = vars[a]['charselector']
|
43 |
+
lk = 'len'
|
44 |
+
if '*' in selector:
|
45 |
+
if f90mode:
|
46 |
+
if selector['*'] in ['*', ':', '(*)']:
|
47 |
+
vardef = '%s(len=*)' % (vardef)
|
48 |
+
else:
|
49 |
+
vardef = '%s(%s=%s)' % (vardef, lk, selector['*'])
|
50 |
+
else:
|
51 |
+
if selector['*'] in ['*', ':']:
|
52 |
+
vardef = '%s*(%s)' % (vardef, selector['*'])
|
53 |
+
else:
|
54 |
+
vardef = '%s*%s' % (vardef, selector['*'])
|
55 |
+
else:
|
56 |
+
if 'len' in selector:
|
57 |
+
vardef = '%s(len=%s' % (vardef, selector['len'])
|
58 |
+
if 'kind' in selector:
|
59 |
+
vardef = '%s,kind=%s)' % (vardef, selector['kind'])
|
60 |
+
else:
|
61 |
+
vardef = '%s)' % (vardef)
|
62 |
+
elif 'kind' in selector:
|
63 |
+
vardef = '%s(kind=%s)' % (vardef, selector['kind'])
|
64 |
+
|
65 |
+
vardef = '%s %s' % (vardef, fa)
|
66 |
+
if 'dimension' in vars[a]:
|
67 |
+
vardef = '%s(%s)' % (vardef, ','.join(vars[a]['dimension']))
|
68 |
+
return vardef
|
69 |
+
|
70 |
+
def useiso_c_binding(rout):
|
71 |
+
useisoc = False
|
72 |
+
for key, value in rout['vars'].items():
|
73 |
+
kind_value = value.get('kindselector', {}).get('kind')
|
74 |
+
if kind_value in isoc_kindmap:
|
75 |
+
return True
|
76 |
+
return useisoc
|
77 |
+
|
78 |
+
def createfuncwrapper(rout, signature=0):
|
79 |
+
assert isfunction(rout)
|
80 |
+
|
81 |
+
extra_args = []
|
82 |
+
vars = rout['vars']
|
83 |
+
for a in rout['args']:
|
84 |
+
v = rout['vars'][a]
|
85 |
+
for i, d in enumerate(v.get('dimension', [])):
|
86 |
+
if d == ':':
|
87 |
+
dn = 'f2py_%s_d%s' % (a, i)
|
88 |
+
dv = dict(typespec='integer', intent=['hide'])
|
89 |
+
dv['='] = 'shape(%s, %s)' % (a, i)
|
90 |
+
extra_args.append(dn)
|
91 |
+
vars[dn] = dv
|
92 |
+
v['dimension'][i] = dn
|
93 |
+
rout['args'].extend(extra_args)
|
94 |
+
need_interface = bool(extra_args)
|
95 |
+
|
96 |
+
ret = ['']
|
97 |
+
|
98 |
+
def add(line, ret=ret):
|
99 |
+
ret[0] = '%s\n %s' % (ret[0], line)
|
100 |
+
name = rout['name']
|
101 |
+
fortranname = getfortranname(rout)
|
102 |
+
f90mode = ismoduleroutine(rout)
|
103 |
+
newname = '%sf2pywrap' % (name)
|
104 |
+
|
105 |
+
if newname not in vars:
|
106 |
+
vars[newname] = vars[name]
|
107 |
+
args = [newname] + rout['args'][1:]
|
108 |
+
else:
|
109 |
+
args = [newname] + rout['args']
|
110 |
+
|
111 |
+
l_tmpl = var2fixfortran(vars, name, '@@@NAME@@@', f90mode)
|
112 |
+
if l_tmpl[:13] == 'character*(*)':
|
113 |
+
if f90mode:
|
114 |
+
l_tmpl = 'character(len=10)' + l_tmpl[13:]
|
115 |
+
else:
|
116 |
+
l_tmpl = 'character*10' + l_tmpl[13:]
|
117 |
+
charselect = vars[name]['charselector']
|
118 |
+
if charselect.get('*', '') == '(*)':
|
119 |
+
charselect['*'] = '10'
|
120 |
+
|
121 |
+
l1 = l_tmpl.replace('@@@NAME@@@', newname)
|
122 |
+
rl = None
|
123 |
+
|
124 |
+
useisoc = useiso_c_binding(rout)
|
125 |
+
sargs = ', '.join(args)
|
126 |
+
if f90mode:
|
127 |
+
# gh-23598 fix warning
|
128 |
+
# Essentially, this gets called again with modules where the name of the
|
129 |
+
# function is added to the arguments, which is not required, and removed
|
130 |
+
sargs = sargs.replace(f"{name}, ", '')
|
131 |
+
args = [arg for arg in args if arg != name]
|
132 |
+
rout['args'] = args
|
133 |
+
add('subroutine f2pywrap_%s_%s (%s)' %
|
134 |
+
(rout['modulename'], name, sargs))
|
135 |
+
if not signature:
|
136 |
+
add('use %s, only : %s' % (rout['modulename'], fortranname))
|
137 |
+
if useisoc:
|
138 |
+
add('use iso_c_binding')
|
139 |
+
else:
|
140 |
+
add('subroutine f2pywrap%s (%s)' % (name, sargs))
|
141 |
+
if useisoc:
|
142 |
+
add('use iso_c_binding')
|
143 |
+
if not need_interface:
|
144 |
+
add('external %s' % (fortranname))
|
145 |
+
rl = l_tmpl.replace('@@@NAME@@@', '') + ' ' + fortranname
|
146 |
+
|
147 |
+
if need_interface:
|
148 |
+
for line in rout['saved_interface'].split('\n'):
|
149 |
+
if line.lstrip().startswith('use ') and '__user__' not in line:
|
150 |
+
add(line)
|
151 |
+
|
152 |
+
args = args[1:]
|
153 |
+
dumped_args = []
|
154 |
+
for a in args:
|
155 |
+
if isexternal(vars[a]):
|
156 |
+
add('external %s' % (a))
|
157 |
+
dumped_args.append(a)
|
158 |
+
for a in args:
|
159 |
+
if a in dumped_args:
|
160 |
+
continue
|
161 |
+
if isscalar(vars[a]):
|
162 |
+
add(var2fixfortran(vars, a, f90mode=f90mode))
|
163 |
+
dumped_args.append(a)
|
164 |
+
for a in args:
|
165 |
+
if a in dumped_args:
|
166 |
+
continue
|
167 |
+
if isintent_in(vars[a]):
|
168 |
+
add(var2fixfortran(vars, a, f90mode=f90mode))
|
169 |
+
dumped_args.append(a)
|
170 |
+
for a in args:
|
171 |
+
if a in dumped_args:
|
172 |
+
continue
|
173 |
+
add(var2fixfortran(vars, a, f90mode=f90mode))
|
174 |
+
|
175 |
+
add(l1)
|
176 |
+
if rl is not None:
|
177 |
+
add(rl)
|
178 |
+
|
179 |
+
if need_interface:
|
180 |
+
if f90mode:
|
181 |
+
# f90 module already defines needed interface
|
182 |
+
pass
|
183 |
+
else:
|
184 |
+
add('interface')
|
185 |
+
add(rout['saved_interface'].lstrip())
|
186 |
+
add('end interface')
|
187 |
+
|
188 |
+
sargs = ', '.join([a for a in args if a not in extra_args])
|
189 |
+
|
190 |
+
if not signature:
|
191 |
+
if islogicalfunction(rout):
|
192 |
+
add('%s = .not.(.not.%s(%s))' % (newname, fortranname, sargs))
|
193 |
+
else:
|
194 |
+
add('%s = %s(%s)' % (newname, fortranname, sargs))
|
195 |
+
if f90mode:
|
196 |
+
add('end subroutine f2pywrap_%s_%s' % (rout['modulename'], name))
|
197 |
+
else:
|
198 |
+
add('end')
|
199 |
+
return ret[0]
|
200 |
+
|
201 |
+
|
202 |
+
def createsubrwrapper(rout, signature=0):
|
203 |
+
assert issubroutine(rout)
|
204 |
+
|
205 |
+
extra_args = []
|
206 |
+
vars = rout['vars']
|
207 |
+
for a in rout['args']:
|
208 |
+
v = rout['vars'][a]
|
209 |
+
for i, d in enumerate(v.get('dimension', [])):
|
210 |
+
if d == ':':
|
211 |
+
dn = 'f2py_%s_d%s' % (a, i)
|
212 |
+
dv = dict(typespec='integer', intent=['hide'])
|
213 |
+
dv['='] = 'shape(%s, %s)' % (a, i)
|
214 |
+
extra_args.append(dn)
|
215 |
+
vars[dn] = dv
|
216 |
+
v['dimension'][i] = dn
|
217 |
+
rout['args'].extend(extra_args)
|
218 |
+
need_interface = bool(extra_args)
|
219 |
+
|
220 |
+
ret = ['']
|
221 |
+
|
222 |
+
def add(line, ret=ret):
|
223 |
+
ret[0] = '%s\n %s' % (ret[0], line)
|
224 |
+
name = rout['name']
|
225 |
+
fortranname = getfortranname(rout)
|
226 |
+
f90mode = ismoduleroutine(rout)
|
227 |
+
|
228 |
+
args = rout['args']
|
229 |
+
|
230 |
+
useisoc = useiso_c_binding(rout)
|
231 |
+
sargs = ', '.join(args)
|
232 |
+
if f90mode:
|
233 |
+
add('subroutine f2pywrap_%s_%s (%s)' %
|
234 |
+
(rout['modulename'], name, sargs))
|
235 |
+
if useisoc:
|
236 |
+
add('use iso_c_binding')
|
237 |
+
if not signature:
|
238 |
+
add('use %s, only : %s' % (rout['modulename'], fortranname))
|
239 |
+
else:
|
240 |
+
add('subroutine f2pywrap%s (%s)' % (name, sargs))
|
241 |
+
if useisoc:
|
242 |
+
add('use iso_c_binding')
|
243 |
+
if not need_interface:
|
244 |
+
add('external %s' % (fortranname))
|
245 |
+
|
246 |
+
if need_interface:
|
247 |
+
for line in rout['saved_interface'].split('\n'):
|
248 |
+
if line.lstrip().startswith('use ') and '__user__' not in line:
|
249 |
+
add(line)
|
250 |
+
|
251 |
+
dumped_args = []
|
252 |
+
for a in args:
|
253 |
+
if isexternal(vars[a]):
|
254 |
+
add('external %s' % (a))
|
255 |
+
dumped_args.append(a)
|
256 |
+
for a in args:
|
257 |
+
if a in dumped_args:
|
258 |
+
continue
|
259 |
+
if isscalar(vars[a]):
|
260 |
+
add(var2fixfortran(vars, a, f90mode=f90mode))
|
261 |
+
dumped_args.append(a)
|
262 |
+
for a in args:
|
263 |
+
if a in dumped_args:
|
264 |
+
continue
|
265 |
+
add(var2fixfortran(vars, a, f90mode=f90mode))
|
266 |
+
|
267 |
+
if need_interface:
|
268 |
+
if f90mode:
|
269 |
+
# f90 module already defines needed interface
|
270 |
+
pass
|
271 |
+
else:
|
272 |
+
add('interface')
|
273 |
+
for line in rout['saved_interface'].split('\n'):
|
274 |
+
if line.lstrip().startswith('use ') and '__user__' in line:
|
275 |
+
continue
|
276 |
+
add(line)
|
277 |
+
add('end interface')
|
278 |
+
|
279 |
+
sargs = ', '.join([a for a in args if a not in extra_args])
|
280 |
+
|
281 |
+
if not signature:
|
282 |
+
add('call %s(%s)' % (fortranname, sargs))
|
283 |
+
if f90mode:
|
284 |
+
add('end subroutine f2pywrap_%s_%s' % (rout['modulename'], name))
|
285 |
+
else:
|
286 |
+
add('end')
|
287 |
+
return ret[0]
|
288 |
+
|
289 |
+
|
290 |
+
def assubr(rout):
|
291 |
+
if isfunction_wrap(rout):
|
292 |
+
fortranname = getfortranname(rout)
|
293 |
+
name = rout['name']
|
294 |
+
outmess('\t\tCreating wrapper for Fortran function "%s"("%s")...\n' % (
|
295 |
+
name, fortranname))
|
296 |
+
rout = copy.copy(rout)
|
297 |
+
fname = name
|
298 |
+
rname = fname
|
299 |
+
if 'result' in rout:
|
300 |
+
rname = rout['result']
|
301 |
+
rout['vars'][fname] = rout['vars'][rname]
|
302 |
+
fvar = rout['vars'][fname]
|
303 |
+
if not isintent_out(fvar):
|
304 |
+
if 'intent' not in fvar:
|
305 |
+
fvar['intent'] = []
|
306 |
+
fvar['intent'].append('out')
|
307 |
+
flag = 1
|
308 |
+
for i in fvar['intent']:
|
309 |
+
if i.startswith('out='):
|
310 |
+
flag = 0
|
311 |
+
break
|
312 |
+
if flag:
|
313 |
+
fvar['intent'].append('out=%s' % (rname))
|
314 |
+
rout['args'][:] = [fname] + rout['args']
|
315 |
+
return rout, createfuncwrapper(rout)
|
316 |
+
if issubroutine_wrap(rout):
|
317 |
+
fortranname = getfortranname(rout)
|
318 |
+
name = rout['name']
|
319 |
+
outmess('\t\tCreating wrapper for Fortran subroutine "%s"("%s")...\n'
|
320 |
+
% (name, fortranname))
|
321 |
+
rout = copy.copy(rout)
|
322 |
+
return rout, createsubrwrapper(rout)
|
323 |
+
return rout, ''
|
venv/lib/python3.10/site-packages/numpy/f2py/rules.py
ADDED
@@ -0,0 +1,1568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
|
4 |
+
Rules for building C/API module with f2py2e.
|
5 |
+
|
6 |
+
Here is a skeleton of a new wrapper function (13Dec2001):
|
7 |
+
|
8 |
+
wrapper_function(args)
|
9 |
+
declarations
|
10 |
+
get_python_arguments, say, `a' and `b'
|
11 |
+
|
12 |
+
get_a_from_python
|
13 |
+
if (successful) {
|
14 |
+
|
15 |
+
get_b_from_python
|
16 |
+
if (successful) {
|
17 |
+
|
18 |
+
callfortran
|
19 |
+
if (successful) {
|
20 |
+
|
21 |
+
put_a_to_python
|
22 |
+
if (successful) {
|
23 |
+
|
24 |
+
put_b_to_python
|
25 |
+
if (successful) {
|
26 |
+
|
27 |
+
buildvalue = ...
|
28 |
+
|
29 |
+
}
|
30 |
+
|
31 |
+
}
|
32 |
+
|
33 |
+
}
|
34 |
+
|
35 |
+
}
|
36 |
+
cleanup_b
|
37 |
+
|
38 |
+
}
|
39 |
+
cleanup_a
|
40 |
+
|
41 |
+
return buildvalue
|
42 |
+
|
43 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
44 |
+
Copyright 2011 -- present NumPy Developers.
|
45 |
+
Permission to use, modify, and distribute this software is given under the
|
46 |
+
terms of the NumPy License.
|
47 |
+
|
48 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
49 |
+
"""
|
50 |
+
import os, sys
|
51 |
+
import time
|
52 |
+
import copy
|
53 |
+
from pathlib import Path
|
54 |
+
|
55 |
+
# __version__.version is now the same as the NumPy version
|
56 |
+
from . import __version__
|
57 |
+
|
58 |
+
from .auxfuncs import (
|
59 |
+
applyrules, debugcapi, dictappend, errmess, gentitle, getargs2,
|
60 |
+
hascallstatement, hasexternals, hasinitvalue, hasnote,
|
61 |
+
hasresultnote, isarray, isarrayofstrings, ischaracter,
|
62 |
+
ischaracterarray, ischaracter_or_characterarray, iscomplex,
|
63 |
+
iscomplexarray, iscomplexfunction, iscomplexfunction_warn,
|
64 |
+
isdummyroutine, isexternal, isfunction, isfunction_wrap, isint1,
|
65 |
+
isint1array, isintent_aux, isintent_c, isintent_callback,
|
66 |
+
isintent_copy, isintent_hide, isintent_inout, isintent_nothide,
|
67 |
+
isintent_out, isintent_overwrite, islogical, islong_complex,
|
68 |
+
islong_double, islong_doublefunction, islong_long,
|
69 |
+
islong_longfunction, ismoduleroutine, isoptional, isrequired,
|
70 |
+
isscalar, issigned_long_longarray, isstring, isstringarray,
|
71 |
+
isstringfunction, issubroutine, isattr_value,
|
72 |
+
issubroutine_wrap, isthreadsafe, isunsigned, isunsigned_char,
|
73 |
+
isunsigned_chararray, isunsigned_long_long,
|
74 |
+
isunsigned_long_longarray, isunsigned_short, isunsigned_shortarray,
|
75 |
+
l_and, l_not, l_or, outmess, replace, stripcomma, requiresf90wrapper
|
76 |
+
)
|
77 |
+
|
78 |
+
from . import capi_maps
|
79 |
+
from . import cfuncs
|
80 |
+
from . import common_rules
|
81 |
+
from . import use_rules
|
82 |
+
from . import f90mod_rules
|
83 |
+
from . import func2subr
|
84 |
+
|
85 |
+
f2py_version = __version__.version
|
86 |
+
numpy_version = __version__.version
|
87 |
+
|
88 |
+
options = {}
|
89 |
+
sepdict = {}
|
90 |
+
# for k in ['need_cfuncs']: sepdict[k]=','
|
91 |
+
for k in ['decl',
|
92 |
+
'frompyobj',
|
93 |
+
'cleanupfrompyobj',
|
94 |
+
'topyarr', 'method',
|
95 |
+
'pyobjfrom', 'closepyobjfrom',
|
96 |
+
'freemem',
|
97 |
+
'userincludes',
|
98 |
+
'includes0', 'includes', 'typedefs', 'typedefs_generated',
|
99 |
+
'cppmacros', 'cfuncs', 'callbacks',
|
100 |
+
'latexdoc',
|
101 |
+
'restdoc',
|
102 |
+
'routine_defs', 'externroutines',
|
103 |
+
'initf2pywraphooks',
|
104 |
+
'commonhooks', 'initcommonhooks',
|
105 |
+
'f90modhooks', 'initf90modhooks']:
|
106 |
+
sepdict[k] = '\n'
|
107 |
+
|
108 |
+
#################### Rules for C/API module #################
|
109 |
+
|
110 |
+
generationtime = int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))
|
111 |
+
module_rules = {
|
112 |
+
'modulebody': """\
|
113 |
+
/* File: #modulename#module.c
|
114 |
+
* This file is auto-generated with f2py (version:#f2py_version#).
|
115 |
+
* f2py is a Fortran to Python Interface Generator (FPIG), Second Edition,
|
116 |
+
* written by Pearu Peterson <[email protected]>.
|
117 |
+
* Generation date: """ + time.asctime(time.gmtime(generationtime)) + """
|
118 |
+
* Do not edit this file directly unless you know what you are doing!!!
|
119 |
+
*/
|
120 |
+
|
121 |
+
#ifdef __cplusplus
|
122 |
+
extern \"C\" {
|
123 |
+
#endif
|
124 |
+
|
125 |
+
#ifndef PY_SSIZE_T_CLEAN
|
126 |
+
#define PY_SSIZE_T_CLEAN
|
127 |
+
#endif /* PY_SSIZE_T_CLEAN */
|
128 |
+
|
129 |
+
/* Unconditionally included */
|
130 |
+
#include <Python.h>
|
131 |
+
#include <numpy/npy_os.h>
|
132 |
+
|
133 |
+
""" + gentitle("See f2py2e/cfuncs.py: includes") + """
|
134 |
+
#includes#
|
135 |
+
#includes0#
|
136 |
+
|
137 |
+
""" + gentitle("See f2py2e/rules.py: mod_rules['modulebody']") + """
|
138 |
+
static PyObject *#modulename#_error;
|
139 |
+
static PyObject *#modulename#_module;
|
140 |
+
|
141 |
+
""" + gentitle("See f2py2e/cfuncs.py: typedefs") + """
|
142 |
+
#typedefs#
|
143 |
+
|
144 |
+
""" + gentitle("See f2py2e/cfuncs.py: typedefs_generated") + """
|
145 |
+
#typedefs_generated#
|
146 |
+
|
147 |
+
""" + gentitle("See f2py2e/cfuncs.py: cppmacros") + """
|
148 |
+
#cppmacros#
|
149 |
+
|
150 |
+
""" + gentitle("See f2py2e/cfuncs.py: cfuncs") + """
|
151 |
+
#cfuncs#
|
152 |
+
|
153 |
+
""" + gentitle("See f2py2e/cfuncs.py: userincludes") + """
|
154 |
+
#userincludes#
|
155 |
+
|
156 |
+
""" + gentitle("See f2py2e/capi_rules.py: usercode") + """
|
157 |
+
#usercode#
|
158 |
+
|
159 |
+
/* See f2py2e/rules.py */
|
160 |
+
#externroutines#
|
161 |
+
|
162 |
+
""" + gentitle("See f2py2e/capi_rules.py: usercode1") + """
|
163 |
+
#usercode1#
|
164 |
+
|
165 |
+
""" + gentitle("See f2py2e/cb_rules.py: buildcallback") + """
|
166 |
+
#callbacks#
|
167 |
+
|
168 |
+
""" + gentitle("See f2py2e/rules.py: buildapi") + """
|
169 |
+
#body#
|
170 |
+
|
171 |
+
""" + gentitle("See f2py2e/f90mod_rules.py: buildhooks") + """
|
172 |
+
#f90modhooks#
|
173 |
+
|
174 |
+
""" + gentitle("See f2py2e/rules.py: module_rules['modulebody']") + """
|
175 |
+
|
176 |
+
""" + gentitle("See f2py2e/common_rules.py: buildhooks") + """
|
177 |
+
#commonhooks#
|
178 |
+
|
179 |
+
""" + gentitle("See f2py2e/rules.py") + """
|
180 |
+
|
181 |
+
static FortranDataDef f2py_routine_defs[] = {
|
182 |
+
#routine_defs#
|
183 |
+
{NULL}
|
184 |
+
};
|
185 |
+
|
186 |
+
static PyMethodDef f2py_module_methods[] = {
|
187 |
+
#pymethoddef#
|
188 |
+
{NULL,NULL}
|
189 |
+
};
|
190 |
+
|
191 |
+
static struct PyModuleDef moduledef = {
|
192 |
+
PyModuleDef_HEAD_INIT,
|
193 |
+
"#modulename#",
|
194 |
+
NULL,
|
195 |
+
-1,
|
196 |
+
f2py_module_methods,
|
197 |
+
NULL,
|
198 |
+
NULL,
|
199 |
+
NULL,
|
200 |
+
NULL
|
201 |
+
};
|
202 |
+
|
203 |
+
PyMODINIT_FUNC PyInit_#modulename#(void) {
|
204 |
+
int i;
|
205 |
+
PyObject *m,*d, *s, *tmp;
|
206 |
+
m = #modulename#_module = PyModule_Create(&moduledef);
|
207 |
+
Py_SET_TYPE(&PyFortran_Type, &PyType_Type);
|
208 |
+
import_array();
|
209 |
+
if (PyErr_Occurred())
|
210 |
+
{PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return m;}
|
211 |
+
d = PyModule_GetDict(m);
|
212 |
+
s = PyUnicode_FromString(\"#f2py_version#\");
|
213 |
+
PyDict_SetItemString(d, \"__version__\", s);
|
214 |
+
Py_DECREF(s);
|
215 |
+
s = PyUnicode_FromString(
|
216 |
+
\"This module '#modulename#' is auto-generated with f2py (version:#f2py_version#).\\nFunctions:\\n\"\n#docs#\".\");
|
217 |
+
PyDict_SetItemString(d, \"__doc__\", s);
|
218 |
+
Py_DECREF(s);
|
219 |
+
s = PyUnicode_FromString(\"""" + numpy_version + """\");
|
220 |
+
PyDict_SetItemString(d, \"__f2py_numpy_version__\", s);
|
221 |
+
Py_DECREF(s);
|
222 |
+
#modulename#_error = PyErr_NewException (\"#modulename#.error\", NULL, NULL);
|
223 |
+
/*
|
224 |
+
* Store the error object inside the dict, so that it could get deallocated.
|
225 |
+
* (in practice, this is a module, so it likely will not and cannot.)
|
226 |
+
*/
|
227 |
+
PyDict_SetItemString(d, \"_#modulename#_error\", #modulename#_error);
|
228 |
+
Py_DECREF(#modulename#_error);
|
229 |
+
for(i=0;f2py_routine_defs[i].name!=NULL;i++) {
|
230 |
+
tmp = PyFortranObject_NewAsAttr(&f2py_routine_defs[i]);
|
231 |
+
PyDict_SetItemString(d, f2py_routine_defs[i].name, tmp);
|
232 |
+
Py_DECREF(tmp);
|
233 |
+
}
|
234 |
+
#initf2pywraphooks#
|
235 |
+
#initf90modhooks#
|
236 |
+
#initcommonhooks#
|
237 |
+
#interface_usercode#
|
238 |
+
|
239 |
+
#ifdef F2PY_REPORT_ATEXIT
|
240 |
+
if (! PyErr_Occurred())
|
241 |
+
on_exit(f2py_report_on_exit,(void*)\"#modulename#\");
|
242 |
+
#endif
|
243 |
+
return m;
|
244 |
+
}
|
245 |
+
#ifdef __cplusplus
|
246 |
+
}
|
247 |
+
#endif
|
248 |
+
""",
|
249 |
+
'separatorsfor': {'latexdoc': '\n\n',
|
250 |
+
'restdoc': '\n\n'},
|
251 |
+
'latexdoc': ['\\section{Module \\texttt{#texmodulename#}}\n',
|
252 |
+
'#modnote#\n',
|
253 |
+
'#latexdoc#'],
|
254 |
+
'restdoc': ['Module #modulename#\n' + '=' * 80,
|
255 |
+
'\n#restdoc#']
|
256 |
+
}
|
257 |
+
|
258 |
+
defmod_rules = [
|
259 |
+
{'body': '/*eof body*/',
|
260 |
+
'method': '/*eof method*/',
|
261 |
+
'externroutines': '/*eof externroutines*/',
|
262 |
+
'routine_defs': '/*eof routine_defs*/',
|
263 |
+
'initf90modhooks': '/*eof initf90modhooks*/',
|
264 |
+
'initf2pywraphooks': '/*eof initf2pywraphooks*/',
|
265 |
+
'initcommonhooks': '/*eof initcommonhooks*/',
|
266 |
+
'latexdoc': '',
|
267 |
+
'restdoc': '',
|
268 |
+
'modnote': {hasnote: '#note#', l_not(hasnote): ''},
|
269 |
+
}
|
270 |
+
]
|
271 |
+
|
272 |
+
routine_rules = {
|
273 |
+
'separatorsfor': sepdict,
|
274 |
+
'body': """
|
275 |
+
#begintitle#
|
276 |
+
static char doc_#apiname#[] = \"\\\n#docreturn##name#(#docsignatureshort#)\\n\\nWrapper for ``#name#``.\\\n\\n#docstrsigns#\";
|
277 |
+
/* #declfortranroutine# */
|
278 |
+
static PyObject *#apiname#(const PyObject *capi_self,
|
279 |
+
PyObject *capi_args,
|
280 |
+
PyObject *capi_keywds,
|
281 |
+
#functype# (*f2py_func)(#callprotoargument#)) {
|
282 |
+
PyObject * volatile capi_buildvalue = NULL;
|
283 |
+
volatile int f2py_success = 1;
|
284 |
+
#decl#
|
285 |
+
static char *capi_kwlist[] = {#kwlist##kwlistopt##kwlistxa#NULL};
|
286 |
+
#usercode#
|
287 |
+
#routdebugenter#
|
288 |
+
#ifdef F2PY_REPORT_ATEXIT
|
289 |
+
f2py_start_clock();
|
290 |
+
#endif
|
291 |
+
if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\\
|
292 |
+
\"#argformat#|#keyformat##xaformat#:#pyname#\",\\
|
293 |
+
capi_kwlist#args_capi##keys_capi##keys_xa#))\n return NULL;
|
294 |
+
#frompyobj#
|
295 |
+
/*end of frompyobj*/
|
296 |
+
#ifdef F2PY_REPORT_ATEXIT
|
297 |
+
f2py_start_call_clock();
|
298 |
+
#endif
|
299 |
+
#callfortranroutine#
|
300 |
+
if (PyErr_Occurred())
|
301 |
+
f2py_success = 0;
|
302 |
+
#ifdef F2PY_REPORT_ATEXIT
|
303 |
+
f2py_stop_call_clock();
|
304 |
+
#endif
|
305 |
+
/*end of callfortranroutine*/
|
306 |
+
if (f2py_success) {
|
307 |
+
#pyobjfrom#
|
308 |
+
/*end of pyobjfrom*/
|
309 |
+
CFUNCSMESS(\"Building return value.\\n\");
|
310 |
+
capi_buildvalue = Py_BuildValue(\"#returnformat#\"#return#);
|
311 |
+
/*closepyobjfrom*/
|
312 |
+
#closepyobjfrom#
|
313 |
+
} /*if (f2py_success) after callfortranroutine*/
|
314 |
+
/*cleanupfrompyobj*/
|
315 |
+
#cleanupfrompyobj#
|
316 |
+
if (capi_buildvalue == NULL) {
|
317 |
+
#routdebugfailure#
|
318 |
+
} else {
|
319 |
+
#routdebugleave#
|
320 |
+
}
|
321 |
+
CFUNCSMESS(\"Freeing memory.\\n\");
|
322 |
+
#freemem#
|
323 |
+
#ifdef F2PY_REPORT_ATEXIT
|
324 |
+
f2py_stop_clock();
|
325 |
+
#endif
|
326 |
+
return capi_buildvalue;
|
327 |
+
}
|
328 |
+
#endtitle#
|
329 |
+
""",
|
330 |
+
'routine_defs': '#routine_def#',
|
331 |
+
'initf2pywraphooks': '#initf2pywraphook#',
|
332 |
+
'externroutines': '#declfortranroutine#',
|
333 |
+
'doc': '#docreturn##name#(#docsignature#)',
|
334 |
+
'docshort': '#docreturn##name#(#docsignatureshort#)',
|
335 |
+
'docs': '" #docreturn##name#(#docsignature#)\\n"\n',
|
336 |
+
'need': ['arrayobject.h', 'CFUNCSMESS', 'MINMAX'],
|
337 |
+
'cppmacros': {debugcapi: '#define DEBUGCFUNCS'},
|
338 |
+
'latexdoc': ['\\subsection{Wrapper function \\texttt{#texname#}}\n',
|
339 |
+
"""
|
340 |
+
\\noindent{{}\\verb@#docreturn##name#@{}}\\texttt{(#latexdocsignatureshort#)}
|
341 |
+
#routnote#
|
342 |
+
|
343 |
+
#latexdocstrsigns#
|
344 |
+
"""],
|
345 |
+
'restdoc': ['Wrapped function ``#name#``\n' + '-' * 80,
|
346 |
+
|
347 |
+
]
|
348 |
+
}
|
349 |
+
|
350 |
+
################## Rules for C/API function ##############
|
351 |
+
|
352 |
+
rout_rules = [
|
353 |
+
{ # Init
|
354 |
+
'separatorsfor': {'callfortranroutine': '\n', 'routdebugenter': '\n', 'decl': '\n',
|
355 |
+
'routdebugleave': '\n', 'routdebugfailure': '\n',
|
356 |
+
'setjmpbuf': ' || ',
|
357 |
+
'docstrreq': '\n', 'docstropt': '\n', 'docstrout': '\n',
|
358 |
+
'docstrcbs': '\n', 'docstrsigns': '\\n"\n"',
|
359 |
+
'latexdocstrsigns': '\n',
|
360 |
+
'latexdocstrreq': '\n', 'latexdocstropt': '\n',
|
361 |
+
'latexdocstrout': '\n', 'latexdocstrcbs': '\n',
|
362 |
+
},
|
363 |
+
'kwlist': '', 'kwlistopt': '', 'callfortran': '', 'callfortranappend': '',
|
364 |
+
'docsign': '', 'docsignopt': '', 'decl': '/*decl*/',
|
365 |
+
'freemem': '/*freemem*/',
|
366 |
+
'docsignshort': '', 'docsignoptshort': '',
|
367 |
+
'docstrsigns': '', 'latexdocstrsigns': '',
|
368 |
+
'docstrreq': '\\nParameters\\n----------',
|
369 |
+
'docstropt': '\\nOther Parameters\\n----------------',
|
370 |
+
'docstrout': '\\nReturns\\n-------',
|
371 |
+
'docstrcbs': '\\nNotes\\n-----\\nCall-back functions::\\n',
|
372 |
+
'latexdocstrreq': '\\noindent Required arguments:',
|
373 |
+
'latexdocstropt': '\\noindent Optional arguments:',
|
374 |
+
'latexdocstrout': '\\noindent Return objects:',
|
375 |
+
'latexdocstrcbs': '\\noindent Call-back functions:',
|
376 |
+
'args_capi': '', 'keys_capi': '', 'functype': '',
|
377 |
+
'frompyobj': '/*frompyobj*/',
|
378 |
+
# this list will be reversed
|
379 |
+
'cleanupfrompyobj': ['/*end of cleanupfrompyobj*/'],
|
380 |
+
'pyobjfrom': '/*pyobjfrom*/',
|
381 |
+
# this list will be reversed
|
382 |
+
'closepyobjfrom': ['/*end of closepyobjfrom*/'],
|
383 |
+
'topyarr': '/*topyarr*/', 'routdebugleave': '/*routdebugleave*/',
|
384 |
+
'routdebugenter': '/*routdebugenter*/',
|
385 |
+
'routdebugfailure': '/*routdebugfailure*/',
|
386 |
+
'callfortranroutine': '/*callfortranroutine*/',
|
387 |
+
'argformat': '', 'keyformat': '', 'need_cfuncs': '',
|
388 |
+
'docreturn': '', 'return': '', 'returnformat': '', 'rformat': '',
|
389 |
+
'kwlistxa': '', 'keys_xa': '', 'xaformat': '', 'docsignxa': '', 'docsignxashort': '',
|
390 |
+
'initf2pywraphook': '',
|
391 |
+
'routnote': {hasnote: '--- #note#', l_not(hasnote): ''},
|
392 |
+
}, {
|
393 |
+
'apiname': 'f2py_rout_#modulename#_#name#',
|
394 |
+
'pyname': '#modulename#.#name#',
|
395 |
+
'decl': '',
|
396 |
+
'_check': l_not(ismoduleroutine)
|
397 |
+
}, {
|
398 |
+
'apiname': 'f2py_rout_#modulename#_#f90modulename#_#name#',
|
399 |
+
'pyname': '#modulename#.#f90modulename#.#name#',
|
400 |
+
'decl': '',
|
401 |
+
'_check': ismoduleroutine
|
402 |
+
}, { # Subroutine
|
403 |
+
'functype': 'void',
|
404 |
+
'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',
|
405 |
+
l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern void #fortranname#(#callprotoargument#);',
|
406 |
+
ismoduleroutine: '',
|
407 |
+
isdummyroutine: ''
|
408 |
+
},
|
409 |
+
'routine_def': {
|
410 |
+
l_not(l_or(ismoduleroutine, isintent_c, isdummyroutine)):
|
411 |
+
' {\"#name#\",-1,{{-1}},0,0,(char *)'
|
412 |
+
' #F_FUNC#(#fortranname#,#FORTRANNAME#),'
|
413 |
+
' (f2py_init_func)#apiname#,doc_#apiname#},',
|
414 |
+
l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)):
|
415 |
+
' {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,'
|
416 |
+
' (f2py_init_func)#apiname#,doc_#apiname#},',
|
417 |
+
l_and(l_not(ismoduleroutine), isdummyroutine):
|
418 |
+
' {\"#name#\",-1,{{-1}},0,0,NULL,'
|
419 |
+
' (f2py_init_func)#apiname#,doc_#apiname#},',
|
420 |
+
},
|
421 |
+
'need': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'F_FUNC'},
|
422 |
+
'callfortranroutine': [
|
423 |
+
{debugcapi: [
|
424 |
+
""" fprintf(stderr,\"debug-capi:Fortran subroutine `#fortranname#(#callfortran#)\'\\n\");"""]},
|
425 |
+
{hasexternals: """\
|
426 |
+
if (#setjmpbuf#) {
|
427 |
+
f2py_success = 0;
|
428 |
+
} else {"""},
|
429 |
+
{isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},
|
430 |
+
{hascallstatement: ''' #callstatement#;
|
431 |
+
/*(*f2py_func)(#callfortran#);*/'''},
|
432 |
+
{l_not(l_or(hascallstatement, isdummyroutine))
|
433 |
+
: ' (*f2py_func)(#callfortran#);'},
|
434 |
+
{isthreadsafe: ' Py_END_ALLOW_THREADS'},
|
435 |
+
{hasexternals: """ }"""}
|
436 |
+
],
|
437 |
+
'_check': l_and(issubroutine, l_not(issubroutine_wrap)),
|
438 |
+
}, { # Wrapped function
|
439 |
+
'functype': 'void',
|
440 |
+
'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);',
|
441 |
+
isdummyroutine: '',
|
442 |
+
},
|
443 |
+
|
444 |
+
'routine_def': {
|
445 |
+
l_not(l_or(ismoduleroutine, isdummyroutine)):
|
446 |
+
' {\"#name#\",-1,{{-1}},0,0,(char *)'
|
447 |
+
' #F_WRAPPEDFUNC#(#name_lower#,#NAME#),'
|
448 |
+
' (f2py_init_func)#apiname#,doc_#apiname#},',
|
449 |
+
isdummyroutine:
|
450 |
+
' {\"#name#\",-1,{{-1}},0,0,NULL,'
|
451 |
+
' (f2py_init_func)#apiname#,doc_#apiname#},',
|
452 |
+
},
|
453 |
+
'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): '''
|
454 |
+
{
|
455 |
+
extern #ctype# #F_FUNC#(#name_lower#,#NAME#)(void);
|
456 |
+
PyObject* o = PyDict_GetItemString(d,"#name#");
|
457 |
+
tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL);
|
458 |
+
PyObject_SetAttrString(o,"_cpointer", tmp);
|
459 |
+
Py_DECREF(tmp);
|
460 |
+
s = PyUnicode_FromString("#name#");
|
461 |
+
PyObject_SetAttrString(o,"__name__", s);
|
462 |
+
Py_DECREF(s);
|
463 |
+
}
|
464 |
+
'''},
|
465 |
+
'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']},
|
466 |
+
'callfortranroutine': [
|
467 |
+
{debugcapi: [
|
468 |
+
""" fprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]},
|
469 |
+
{hasexternals: """\
|
470 |
+
if (#setjmpbuf#) {
|
471 |
+
f2py_success = 0;
|
472 |
+
} else {"""},
|
473 |
+
{isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},
|
474 |
+
{l_not(l_or(hascallstatement, isdummyroutine))
|
475 |
+
: ' (*f2py_func)(#callfortran#);'},
|
476 |
+
{hascallstatement:
|
477 |
+
' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'},
|
478 |
+
{isthreadsafe: ' Py_END_ALLOW_THREADS'},
|
479 |
+
{hasexternals: ' }'}
|
480 |
+
],
|
481 |
+
'_check': isfunction_wrap,
|
482 |
+
}, { # Wrapped subroutine
|
483 |
+
'functype': 'void',
|
484 |
+
'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);',
|
485 |
+
isdummyroutine: '',
|
486 |
+
},
|
487 |
+
|
488 |
+
'routine_def': {
|
489 |
+
l_not(l_or(ismoduleroutine, isdummyroutine)):
|
490 |
+
' {\"#name#\",-1,{{-1}},0,0,(char *)'
|
491 |
+
' #F_WRAPPEDFUNC#(#name_lower#,#NAME#),'
|
492 |
+
' (f2py_init_func)#apiname#,doc_#apiname#},',
|
493 |
+
isdummyroutine:
|
494 |
+
' {\"#name#\",-1,{{-1}},0,0,NULL,'
|
495 |
+
' (f2py_init_func)#apiname#,doc_#apiname#},',
|
496 |
+
},
|
497 |
+
'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): '''
|
498 |
+
{
|
499 |
+
extern void #F_FUNC#(#name_lower#,#NAME#)(void);
|
500 |
+
PyObject* o = PyDict_GetItemString(d,"#name#");
|
501 |
+
tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL);
|
502 |
+
PyObject_SetAttrString(o,"_cpointer", tmp);
|
503 |
+
Py_DECREF(tmp);
|
504 |
+
s = PyUnicode_FromString("#name#");
|
505 |
+
PyObject_SetAttrString(o,"__name__", s);
|
506 |
+
Py_DECREF(s);
|
507 |
+
}
|
508 |
+
'''},
|
509 |
+
'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']},
|
510 |
+
'callfortranroutine': [
|
511 |
+
{debugcapi: [
|
512 |
+
""" fprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]},
|
513 |
+
{hasexternals: """\
|
514 |
+
if (#setjmpbuf#) {
|
515 |
+
f2py_success = 0;
|
516 |
+
} else {"""},
|
517 |
+
{isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},
|
518 |
+
{l_not(l_or(hascallstatement, isdummyroutine))
|
519 |
+
: ' (*f2py_func)(#callfortran#);'},
|
520 |
+
{hascallstatement:
|
521 |
+
' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'},
|
522 |
+
{isthreadsafe: ' Py_END_ALLOW_THREADS'},
|
523 |
+
{hasexternals: ' }'}
|
524 |
+
],
|
525 |
+
'_check': issubroutine_wrap,
|
526 |
+
}, { # Function
|
527 |
+
'functype': '#ctype#',
|
528 |
+
'docreturn': {l_not(isintent_hide): '#rname#,'},
|
529 |
+
'docstrout': '#pydocsignout#',
|
530 |
+
'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}',
|
531 |
+
{hasresultnote: '--- #resultnote#'}],
|
532 |
+
'callfortranroutine': [{l_and(debugcapi, isstringfunction): """\
|
533 |
+
#ifdef USESCOMPAQFORTRAN
|
534 |
+
fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callcompaqfortran#)\\n\");
|
535 |
+
#else
|
536 |
+
fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\");
|
537 |
+
#endif
|
538 |
+
"""},
|
539 |
+
{l_and(debugcapi, l_not(isstringfunction)): """\
|
540 |
+
fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\");
|
541 |
+
"""}
|
542 |
+
],
|
543 |
+
'_check': l_and(isfunction, l_not(isfunction_wrap))
|
544 |
+
}, { # Scalar function
|
545 |
+
'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern #ctype# #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',
|
546 |
+
l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern #ctype# #fortranname#(#callprotoargument#);',
|
547 |
+
isdummyroutine: ''
|
548 |
+
},
|
549 |
+
'routine_def': {
|
550 |
+
l_and(l_not(l_or(ismoduleroutine, isintent_c)),
|
551 |
+
l_not(isdummyroutine)):
|
552 |
+
(' {\"#name#\",-1,{{-1}},0,0,(char *)'
|
553 |
+
' #F_FUNC#(#fortranname#,#FORTRANNAME#),'
|
554 |
+
' (f2py_init_func)#apiname#,doc_#apiname#},'),
|
555 |
+
l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)):
|
556 |
+
(' {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,'
|
557 |
+
' (f2py_init_func)#apiname#,doc_#apiname#},'),
|
558 |
+
isdummyroutine:
|
559 |
+
' {\"#name#\",-1,{{-1}},0,0,NULL,'
|
560 |
+
'(f2py_init_func)#apiname#,doc_#apiname#},',
|
561 |
+
},
|
562 |
+
'decl': [{iscomplexfunction_warn: ' #ctype# #name#_return_value={0,0};',
|
563 |
+
l_not(iscomplexfunction): ' #ctype# #name#_return_value=0;'},
|
564 |
+
{iscomplexfunction:
|
565 |
+
' PyObject *#name#_return_value_capi = Py_None;'}
|
566 |
+
],
|
567 |
+
'callfortranroutine': [
|
568 |
+
{hasexternals: """\
|
569 |
+
if (#setjmpbuf#) {
|
570 |
+
f2py_success = 0;
|
571 |
+
} else {"""},
|
572 |
+
{isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},
|
573 |
+
{hascallstatement: ''' #callstatement#;
|
574 |
+
/* #name#_return_value = (*f2py_func)(#callfortran#);*/
|
575 |
+
'''},
|
576 |
+
{l_not(l_or(hascallstatement, isdummyroutine))
|
577 |
+
: ' #name#_return_value = (*f2py_func)(#callfortran#);'},
|
578 |
+
{isthreadsafe: ' Py_END_ALLOW_THREADS'},
|
579 |
+
{hasexternals: ' }'},
|
580 |
+
{l_and(debugcapi, iscomplexfunction)
|
581 |
+
: ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value.r,#name#_return_value.i);'},
|
582 |
+
{l_and(debugcapi, l_not(iscomplexfunction)): ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value);'}],
|
583 |
+
'pyobjfrom': {iscomplexfunction: ' #name#_return_value_capi = pyobj_from_#ctype#1(#name#_return_value);'},
|
584 |
+
'need': [{l_not(isdummyroutine): 'F_FUNC'},
|
585 |
+
{iscomplexfunction: 'pyobj_from_#ctype#1'},
|
586 |
+
{islong_longfunction: 'long_long'},
|
587 |
+
{islong_doublefunction: 'long_double'}],
|
588 |
+
'returnformat': {l_not(isintent_hide): '#rformat#'},
|
589 |
+
'return': {iscomplexfunction: ',#name#_return_value_capi',
|
590 |
+
l_not(l_or(iscomplexfunction, isintent_hide)): ',#name#_return_value'},
|
591 |
+
'_check': l_and(isfunction, l_not(isstringfunction), l_not(isfunction_wrap))
|
592 |
+
}, { # String function # in use for --no-wrap
|
593 |
+
'declfortranroutine': 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',
|
594 |
+
'routine_def': {l_not(l_or(ismoduleroutine, isintent_c)):
|
595 |
+
' {\"#name#\",-1,{{-1}},0,0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},',
|
596 |
+
l_and(l_not(ismoduleroutine), isintent_c):
|
597 |
+
' {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},'
|
598 |
+
},
|
599 |
+
'decl': [' #ctype# #name#_return_value = NULL;',
|
600 |
+
' int #name#_return_value_len = 0;'],
|
601 |
+
'callfortran':'#name#_return_value,#name#_return_value_len,',
|
602 |
+
'callfortranroutine':[' #name#_return_value_len = #rlength#;',
|
603 |
+
' if ((#name#_return_value = (string)malloc('
|
604 |
+
+ '#name#_return_value_len+1) == NULL) {',
|
605 |
+
' PyErr_SetString(PyExc_MemoryError, \"out of memory\");',
|
606 |
+
' f2py_success = 0;',
|
607 |
+
' } else {',
|
608 |
+
" (#name#_return_value)[#name#_return_value_len] = '\\0';",
|
609 |
+
' }',
|
610 |
+
' if (f2py_success) {',
|
611 |
+
{hasexternals: """\
|
612 |
+
if (#setjmpbuf#) {
|
613 |
+
f2py_success = 0;
|
614 |
+
} else {"""},
|
615 |
+
{isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},
|
616 |
+
"""\
|
617 |
+
#ifdef USESCOMPAQFORTRAN
|
618 |
+
(*f2py_func)(#callcompaqfortran#);
|
619 |
+
#else
|
620 |
+
(*f2py_func)(#callfortran#);
|
621 |
+
#endif
|
622 |
+
""",
|
623 |
+
{isthreadsafe: ' Py_END_ALLOW_THREADS'},
|
624 |
+
{hasexternals: ' }'},
|
625 |
+
{debugcapi:
|
626 |
+
' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value_len,#name#_return_value);'},
|
627 |
+
' } /* if (f2py_success) after (string)malloc */',
|
628 |
+
],
|
629 |
+
'returnformat': '#rformat#',
|
630 |
+
'return': ',#name#_return_value',
|
631 |
+
'freemem': ' STRINGFREE(#name#_return_value);',
|
632 |
+
'need': ['F_FUNC', '#ctype#', 'STRINGFREE'],
|
633 |
+
'_check':l_and(isstringfunction, l_not(isfunction_wrap)) # ???obsolete
|
634 |
+
},
|
635 |
+
{ # Debugging
|
636 |
+
'routdebugenter': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#(#docsignature#)\\n");',
|
637 |
+
'routdebugleave': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: successful.\\n");',
|
638 |
+
'routdebugfailure': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: failure.\\n");',
|
639 |
+
'_check': debugcapi
|
640 |
+
}
|
641 |
+
]
|
642 |
+
|
643 |
+
################ Rules for arguments ##################
|
644 |
+
|
645 |
+
typedef_need_dict = {islong_long: 'long_long',
|
646 |
+
islong_double: 'long_double',
|
647 |
+
islong_complex: 'complex_long_double',
|
648 |
+
isunsigned_char: 'unsigned_char',
|
649 |
+
isunsigned_short: 'unsigned_short',
|
650 |
+
isunsigned: 'unsigned',
|
651 |
+
isunsigned_long_long: 'unsigned_long_long',
|
652 |
+
isunsigned_chararray: 'unsigned_char',
|
653 |
+
isunsigned_shortarray: 'unsigned_short',
|
654 |
+
isunsigned_long_longarray: 'unsigned_long_long',
|
655 |
+
issigned_long_longarray: 'long_long',
|
656 |
+
isint1: 'signed_char',
|
657 |
+
ischaracter_or_characterarray: 'character',
|
658 |
+
}
|
659 |
+
|
660 |
+
aux_rules = [
|
661 |
+
{
|
662 |
+
'separatorsfor': sepdict
|
663 |
+
},
|
664 |
+
{ # Common
|
665 |
+
'frompyobj': [' /* Processing auxiliary variable #varname# */',
|
666 |
+
{debugcapi: ' fprintf(stderr,"#vardebuginfo#\\n");'}, ],
|
667 |
+
'cleanupfrompyobj': ' /* End of cleaning variable #varname# */',
|
668 |
+
'need': typedef_need_dict,
|
669 |
+
},
|
670 |
+
# Scalars (not complex)
|
671 |
+
{ # Common
|
672 |
+
'decl': ' #ctype# #varname# = 0;',
|
673 |
+
'need': {hasinitvalue: 'math.h'},
|
674 |
+
'frompyobj': {hasinitvalue: ' #varname# = #init#;'},
|
675 |
+
'_check': l_and(isscalar, l_not(iscomplex)),
|
676 |
+
},
|
677 |
+
{
|
678 |
+
'return': ',#varname#',
|
679 |
+
'docstrout': '#pydocsignout#',
|
680 |
+
'docreturn': '#outvarname#,',
|
681 |
+
'returnformat': '#varrformat#',
|
682 |
+
'_check': l_and(isscalar, l_not(iscomplex), isintent_out),
|
683 |
+
},
|
684 |
+
# Complex scalars
|
685 |
+
{ # Common
|
686 |
+
'decl': ' #ctype# #varname#;',
|
687 |
+
'frompyobj': {hasinitvalue: ' #varname#.r = #init.r#, #varname#.i = #init.i#;'},
|
688 |
+
'_check': iscomplex
|
689 |
+
},
|
690 |
+
# String
|
691 |
+
{ # Common
|
692 |
+
'decl': [' #ctype# #varname# = NULL;',
|
693 |
+
' int slen(#varname#);',
|
694 |
+
],
|
695 |
+
'need':['len..'],
|
696 |
+
'_check':isstring
|
697 |
+
},
|
698 |
+
# Array
|
699 |
+
{ # Common
|
700 |
+
'decl': [' #ctype# *#varname# = NULL;',
|
701 |
+
' npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};',
|
702 |
+
' const int #varname#_Rank = #rank#;',
|
703 |
+
],
|
704 |
+
'need':['len..', {hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}],
|
705 |
+
'_check': isarray
|
706 |
+
},
|
707 |
+
# Scalararray
|
708 |
+
{ # Common
|
709 |
+
'_check': l_and(isarray, l_not(iscomplexarray))
|
710 |
+
}, { # Not hidden
|
711 |
+
'_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide)
|
712 |
+
},
|
713 |
+
# Integer*1 array
|
714 |
+
{'need': '#ctype#',
|
715 |
+
'_check': isint1array,
|
716 |
+
'_depend': ''
|
717 |
+
},
|
718 |
+
# Integer*-1 array
|
719 |
+
{'need': '#ctype#',
|
720 |
+
'_check': l_or(isunsigned_chararray, isunsigned_char),
|
721 |
+
'_depend': ''
|
722 |
+
},
|
723 |
+
# Integer*-2 array
|
724 |
+
{'need': '#ctype#',
|
725 |
+
'_check': isunsigned_shortarray,
|
726 |
+
'_depend': ''
|
727 |
+
},
|
728 |
+
# Integer*-8 array
|
729 |
+
{'need': '#ctype#',
|
730 |
+
'_check': isunsigned_long_longarray,
|
731 |
+
'_depend': ''
|
732 |
+
},
|
733 |
+
# Complexarray
|
734 |
+
{'need': '#ctype#',
|
735 |
+
'_check': iscomplexarray,
|
736 |
+
'_depend': ''
|
737 |
+
},
|
738 |
+
# Stringarray
|
739 |
+
{
|
740 |
+
'callfortranappend': {isarrayofstrings: 'flen(#varname#),'},
|
741 |
+
'need': 'string',
|
742 |
+
'_check': isstringarray
|
743 |
+
}
|
744 |
+
]
|
745 |
+
|
746 |
+
arg_rules = [
|
747 |
+
{
|
748 |
+
'separatorsfor': sepdict
|
749 |
+
},
|
750 |
+
{ # Common
|
751 |
+
'frompyobj': [' /* Processing variable #varname# */',
|
752 |
+
{debugcapi: ' fprintf(stderr,"#vardebuginfo#\\n");'}, ],
|
753 |
+
'cleanupfrompyobj': ' /* End of cleaning variable #varname# */',
|
754 |
+
'_depend': '',
|
755 |
+
'need': typedef_need_dict,
|
756 |
+
},
|
757 |
+
# Doc signatures
|
758 |
+
{
|
759 |
+
'docstropt': {l_and(isoptional, isintent_nothide): '#pydocsign#'},
|
760 |
+
'docstrreq': {l_and(isrequired, isintent_nothide): '#pydocsign#'},
|
761 |
+
'docstrout': {isintent_out: '#pydocsignout#'},
|
762 |
+
'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}',
|
763 |
+
{hasnote: '--- #note#'}]},
|
764 |
+
'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}',
|
765 |
+
{hasnote: '--- #note#'}]},
|
766 |
+
'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}',
|
767 |
+
{l_and(hasnote, isintent_hide): '--- #note#',
|
768 |
+
l_and(hasnote, isintent_nothide): '--- See above.'}]},
|
769 |
+
'depend': ''
|
770 |
+
},
|
771 |
+
# Required/Optional arguments
|
772 |
+
{
|
773 |
+
'kwlist': '"#varname#",',
|
774 |
+
'docsign': '#varname#,',
|
775 |
+
'_check': l_and(isintent_nothide, l_not(isoptional))
|
776 |
+
},
|
777 |
+
{
|
778 |
+
'kwlistopt': '"#varname#",',
|
779 |
+
'docsignopt': '#varname#=#showinit#,',
|
780 |
+
'docsignoptshort': '#varname#,',
|
781 |
+
'_check': l_and(isintent_nothide, isoptional)
|
782 |
+
},
|
783 |
+
# Docstring/BuildValue
|
784 |
+
{
|
785 |
+
'docreturn': '#outvarname#,',
|
786 |
+
'returnformat': '#varrformat#',
|
787 |
+
'_check': isintent_out
|
788 |
+
},
|
789 |
+
# Externals (call-back functions)
|
790 |
+
{ # Common
|
791 |
+
'docsignxa': {isintent_nothide: '#varname#_extra_args=(),'},
|
792 |
+
'docsignxashort': {isintent_nothide: '#varname#_extra_args,'},
|
793 |
+
'docstropt': {isintent_nothide: '#varname#_extra_args : input tuple, optional\\n Default: ()'},
|
794 |
+
'docstrcbs': '#cbdocstr#',
|
795 |
+
'latexdocstrcbs': '\\item[] #cblatexdocstr#',
|
796 |
+
'latexdocstropt': {isintent_nothide: '\\item[]{{}\\verb@#varname#_extra_args := () input tuple@{}} --- Extra arguments for call-back function {{}\\verb@#varname#@{}}.'},
|
797 |
+
'decl': [' #cbname#_t #varname#_cb = { Py_None, NULL, 0 };',
|
798 |
+
' #cbname#_t *#varname#_cb_ptr = &#varname#_cb;',
|
799 |
+
' PyTupleObject *#varname#_xa_capi = NULL;',
|
800 |
+
{l_not(isintent_callback):
|
801 |
+
' #cbname#_typedef #varname#_cptr;'}
|
802 |
+
],
|
803 |
+
'kwlistxa': {isintent_nothide: '"#varname#_extra_args",'},
|
804 |
+
'argformat': {isrequired: 'O'},
|
805 |
+
'keyformat': {isoptional: 'O'},
|
806 |
+
'xaformat': {isintent_nothide: 'O!'},
|
807 |
+
'args_capi': {isrequired: ',&#varname#_cb.capi'},
|
808 |
+
'keys_capi': {isoptional: ',&#varname#_cb.capi'},
|
809 |
+
'keys_xa': ',&PyTuple_Type,&#varname#_xa_capi',
|
810 |
+
'setjmpbuf': '(setjmp(#varname#_cb.jmpbuf))',
|
811 |
+
'callfortran': {l_not(isintent_callback): '#varname#_cptr,'},
|
812 |
+
'need': ['#cbname#', 'setjmp.h'],
|
813 |
+
'_check':isexternal
|
814 |
+
},
|
815 |
+
{
|
816 |
+
'frompyobj': [{l_not(isintent_callback): """\
|
817 |
+
if(F2PyCapsule_Check(#varname#_cb.capi)) {
|
818 |
+
#varname#_cptr = F2PyCapsule_AsVoidPtr(#varname#_cb.capi);
|
819 |
+
} else {
|
820 |
+
#varname#_cptr = #cbname#;
|
821 |
+
}
|
822 |
+
"""}, {isintent_callback: """\
|
823 |
+
if (#varname#_cb.capi==Py_None) {
|
824 |
+
#varname#_cb.capi = PyObject_GetAttrString(#modulename#_module,\"#varname#\");
|
825 |
+
if (#varname#_cb.capi) {
|
826 |
+
if (#varname#_xa_capi==NULL) {
|
827 |
+
if (PyObject_HasAttrString(#modulename#_module,\"#varname#_extra_args\")) {
|
828 |
+
PyObject* capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#varname#_extra_args\");
|
829 |
+
if (capi_tmp) {
|
830 |
+
#varname#_xa_capi = (PyTupleObject *)PySequence_Tuple(capi_tmp);
|
831 |
+
Py_DECREF(capi_tmp);
|
832 |
+
}
|
833 |
+
else {
|
834 |
+
#varname#_xa_capi = (PyTupleObject *)Py_BuildValue(\"()\");
|
835 |
+
}
|
836 |
+
if (#varname#_xa_capi==NULL) {
|
837 |
+
PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#varname#_extra_args to tuple.\\n\");
|
838 |
+
return NULL;
|
839 |
+
}
|
840 |
+
}
|
841 |
+
}
|
842 |
+
}
|
843 |
+
if (#varname#_cb.capi==NULL) {
|
844 |
+
PyErr_SetString(#modulename#_error,\"Callback #varname# not defined (as an argument or module #modulename# attribute).\\n\");
|
845 |
+
return NULL;
|
846 |
+
}
|
847 |
+
}
|
848 |
+
"""},
|
849 |
+
"""\
|
850 |
+
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#.\")) {
|
851 |
+
""",
|
852 |
+
{debugcapi: ["""\
|
853 |
+
fprintf(stderr,\"debug-capi:Assuming %d arguments; at most #maxnofargs#(-#nofoptargs#) is expected.\\n\",#varname#_cb.nofargs);
|
854 |
+
CFUNCSMESSPY(\"for #varname#=\",#varname#_cb.capi);""",
|
855 |
+
{l_not(isintent_callback): """ fprintf(stderr,\"#vardebugshowvalue# (call-back in C).\\n\",#cbname#);"""}]},
|
856 |
+
"""\
|
857 |
+
CFUNCSMESS(\"Saving callback variables for `#varname#`.\\n\");
|
858 |
+
#varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);""",
|
859 |
+
],
|
860 |
+
'cleanupfrompyobj':
|
861 |
+
"""\
|
862 |
+
CFUNCSMESS(\"Restoring callback variables for `#varname#`.\\n\");
|
863 |
+
#varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);
|
864 |
+
Py_DECREF(#varname#_cb.args_capi);
|
865 |
+
}""",
|
866 |
+
'need': ['SWAP', 'create_cb_arglist'],
|
867 |
+
'_check':isexternal,
|
868 |
+
'_depend':''
|
869 |
+
},
|
870 |
+
# Scalars (not complex)
|
871 |
+
{ # Common
|
872 |
+
'decl': ' #ctype# #varname# = 0;',
|
873 |
+
'pyobjfrom': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'},
|
874 |
+
'callfortran': {l_or(isintent_c, isattr_value): '#varname#,', l_not(l_or(isintent_c, isattr_value)): '&#varname#,'},
|
875 |
+
'return': {isintent_out: ',#varname#'},
|
876 |
+
'_check': l_and(isscalar, l_not(iscomplex))
|
877 |
+
}, {
|
878 |
+
'need': {hasinitvalue: 'math.h'},
|
879 |
+
'_check': l_and(isscalar, l_not(iscomplex)),
|
880 |
+
}, { # Not hidden
|
881 |
+
'decl': ' PyObject *#varname#_capi = Py_None;',
|
882 |
+
'argformat': {isrequired: 'O'},
|
883 |
+
'keyformat': {isoptional: 'O'},
|
884 |
+
'args_capi': {isrequired: ',&#varname#_capi'},
|
885 |
+
'keys_capi': {isoptional: ',&#varname#_capi'},
|
886 |
+
'pyobjfrom': {isintent_inout: """\
|
887 |
+
f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#);
|
888 |
+
if (f2py_success) {"""},
|
889 |
+
'closepyobjfrom': {isintent_inout: " } /*if (f2py_success) of #varname# pyobjfrom*/"},
|
890 |
+
'need': {isintent_inout: 'try_pyarr_from_#ctype#'},
|
891 |
+
'_check': l_and(isscalar, l_not(iscomplex), l_not(isstring),
|
892 |
+
isintent_nothide)
|
893 |
+
}, {
|
894 |
+
'frompyobj': [
|
895 |
+
# hasinitvalue...
|
896 |
+
# if pyobj is None:
|
897 |
+
# varname = init
|
898 |
+
# else
|
899 |
+
# from_pyobj(varname)
|
900 |
+
#
|
901 |
+
# isoptional and noinitvalue...
|
902 |
+
# if pyobj is not None:
|
903 |
+
# from_pyobj(varname)
|
904 |
+
# else:
|
905 |
+
# varname is uninitialized
|
906 |
+
#
|
907 |
+
# ...
|
908 |
+
# from_pyobj(varname)
|
909 |
+
#
|
910 |
+
{hasinitvalue: ' if (#varname#_capi == Py_None) #varname# = #init#; else',
|
911 |
+
'_depend': ''},
|
912 |
+
{l_and(isoptional, l_not(hasinitvalue)): ' if (#varname#_capi != Py_None)',
|
913 |
+
'_depend': ''},
|
914 |
+
{l_not(islogical): '''\
|
915 |
+
f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");
|
916 |
+
if (f2py_success) {'''},
|
917 |
+
{islogical: '''\
|
918 |
+
#varname# = (#ctype#)PyObject_IsTrue(#varname#_capi);
|
919 |
+
f2py_success = 1;
|
920 |
+
if (f2py_success) {'''},
|
921 |
+
],
|
922 |
+
'cleanupfrompyobj': ' } /*if (f2py_success) of #varname#*/',
|
923 |
+
'need': {l_not(islogical): '#ctype#_from_pyobj'},
|
924 |
+
'_check': l_and(isscalar, l_not(iscomplex), isintent_nothide),
|
925 |
+
'_depend': ''
|
926 |
+
}, { # Hidden
|
927 |
+
'frompyobj': {hasinitvalue: ' #varname# = #init#;'},
|
928 |
+
'need': typedef_need_dict,
|
929 |
+
'_check': l_and(isscalar, l_not(iscomplex), isintent_hide),
|
930 |
+
'_depend': ''
|
931 |
+
}, { # Common
|
932 |
+
'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'},
|
933 |
+
'_check': l_and(isscalar, l_not(iscomplex)),
|
934 |
+
'_depend': ''
|
935 |
+
},
|
936 |
+
# Complex scalars
|
937 |
+
{ # Common
|
938 |
+
'decl': ' #ctype# #varname#;',
|
939 |
+
'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'},
|
940 |
+
'pyobjfrom': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'},
|
941 |
+
'return': {isintent_out: ',#varname#_capi'},
|
942 |
+
'_check': iscomplex
|
943 |
+
}, { # Not hidden
|
944 |
+
'decl': ' PyObject *#varname#_capi = Py_None;',
|
945 |
+
'argformat': {isrequired: 'O'},
|
946 |
+
'keyformat': {isoptional: 'O'},
|
947 |
+
'args_capi': {isrequired: ',&#varname#_capi'},
|
948 |
+
'keys_capi': {isoptional: ',&#varname#_capi'},
|
949 |
+
'need': {isintent_inout: 'try_pyarr_from_#ctype#'},
|
950 |
+
'pyobjfrom': {isintent_inout: """\
|
951 |
+
f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#);
|
952 |
+
if (f2py_success) {"""},
|
953 |
+
'closepyobjfrom': {isintent_inout: " } /*if (f2py_success) of #varname# pyobjfrom*/"},
|
954 |
+
'_check': l_and(iscomplex, isintent_nothide)
|
955 |
+
}, {
|
956 |
+
'frompyobj': [{hasinitvalue: ' if (#varname#_capi==Py_None) {#varname#.r = #init.r#, #varname#.i = #init.i#;} else'},
|
957 |
+
{l_and(isoptional, l_not(hasinitvalue))
|
958 |
+
: ' if (#varname#_capi != Py_None)'},
|
959 |
+
' f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");'
|
960 |
+
'\n if (f2py_success) {'],
|
961 |
+
'cleanupfrompyobj': ' } /*if (f2py_success) of #varname# frompyobj*/',
|
962 |
+
'need': ['#ctype#_from_pyobj'],
|
963 |
+
'_check': l_and(iscomplex, isintent_nothide),
|
964 |
+
'_depend': ''
|
965 |
+
}, { # Hidden
|
966 |
+
'decl': {isintent_out: ' PyObject *#varname#_capi = Py_None;'},
|
967 |
+
'_check': l_and(iscomplex, isintent_hide)
|
968 |
+
}, {
|
969 |
+
'frompyobj': {hasinitvalue: ' #varname#.r = #init.r#, #varname#.i = #init.i#;'},
|
970 |
+
'_check': l_and(iscomplex, isintent_hide),
|
971 |
+
'_depend': ''
|
972 |
+
}, { # Common
|
973 |
+
'pyobjfrom': {isintent_out: ' #varname#_capi = pyobj_from_#ctype#1(#varname#);'},
|
974 |
+
'need': ['pyobj_from_#ctype#1'],
|
975 |
+
'_check': iscomplex
|
976 |
+
}, {
|
977 |
+
'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'},
|
978 |
+
'_check': iscomplex,
|
979 |
+
'_depend': ''
|
980 |
+
},
|
981 |
+
# String
|
982 |
+
{ # Common
|
983 |
+
'decl': [' #ctype# #varname# = NULL;',
|
984 |
+
' int slen(#varname#);',
|
985 |
+
' PyObject *#varname#_capi = Py_None;'],
|
986 |
+
'callfortran':'#varname#,',
|
987 |
+
'callfortranappend':'slen(#varname#),',
|
988 |
+
'pyobjfrom':[
|
989 |
+
{debugcapi:
|
990 |
+
' fprintf(stderr,'
|
991 |
+
'"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'},
|
992 |
+
# The trailing null value for Fortran is blank.
|
993 |
+
{l_and(isintent_out, l_not(isintent_c)):
|
994 |
+
" STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"},
|
995 |
+
],
|
996 |
+
'return': {isintent_out: ',#varname#'},
|
997 |
+
'need': ['len..',
|
998 |
+
{l_and(isintent_out, l_not(isintent_c)): 'STRINGPADN'}],
|
999 |
+
'_check': isstring
|
1000 |
+
}, { # Common
|
1001 |
+
'frompyobj': [
|
1002 |
+
"""\
|
1003 |
+
slen(#varname#) = #elsize#;
|
1004 |
+
f2py_success = #ctype#_from_pyobj(&#varname#,&slen(#varname#),#init#,"""
|
1005 |
+
"""#varname#_capi,\"#ctype#_from_pyobj failed in converting #nth#"""
|
1006 |
+
"""`#varname#\' of #pyname# to C #ctype#\");
|
1007 |
+
if (f2py_success) {""",
|
1008 |
+
# The trailing null value for Fortran is blank.
|
1009 |
+
{l_not(isintent_c):
|
1010 |
+
" STRINGPADN(#varname#, slen(#varname#), '\\0', ' ');"},
|
1011 |
+
],
|
1012 |
+
'cleanupfrompyobj': """\
|
1013 |
+
STRINGFREE(#varname#);
|
1014 |
+
} /*if (f2py_success) of #varname#*/""",
|
1015 |
+
'need': ['#ctype#_from_pyobj', 'len..', 'STRINGFREE',
|
1016 |
+
{l_not(isintent_c): 'STRINGPADN'}],
|
1017 |
+
'_check':isstring,
|
1018 |
+
'_depend':''
|
1019 |
+
}, { # Not hidden
|
1020 |
+
'argformat': {isrequired: 'O'},
|
1021 |
+
'keyformat': {isoptional: 'O'},
|
1022 |
+
'args_capi': {isrequired: ',&#varname#_capi'},
|
1023 |
+
'keys_capi': {isoptional: ',&#varname#_capi'},
|
1024 |
+
'pyobjfrom': [
|
1025 |
+
{l_and(isintent_inout, l_not(isintent_c)):
|
1026 |
+
" STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"},
|
1027 |
+
{isintent_inout: '''\
|
1028 |
+
f2py_success = try_pyarr_from_#ctype#(#varname#_capi, #varname#,
|
1029 |
+
slen(#varname#));
|
1030 |
+
if (f2py_success) {'''}],
|
1031 |
+
'closepyobjfrom': {isintent_inout: ' } /*if (f2py_success) of #varname# pyobjfrom*/'},
|
1032 |
+
'need': {isintent_inout: 'try_pyarr_from_#ctype#',
|
1033 |
+
l_and(isintent_inout, l_not(isintent_c)): 'STRINGPADN'},
|
1034 |
+
'_check': l_and(isstring, isintent_nothide)
|
1035 |
+
}, { # Hidden
|
1036 |
+
'_check': l_and(isstring, isintent_hide)
|
1037 |
+
}, {
|
1038 |
+
'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'},
|
1039 |
+
'_check': isstring,
|
1040 |
+
'_depend': ''
|
1041 |
+
},
|
1042 |
+
# Array
|
1043 |
+
{ # Common
|
1044 |
+
'decl': [' #ctype# *#varname# = NULL;',
|
1045 |
+
' npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};',
|
1046 |
+
' const int #varname#_Rank = #rank#;',
|
1047 |
+
' PyArrayObject *capi_#varname#_as_array = NULL;',
|
1048 |
+
' int capi_#varname#_intent = 0;',
|
1049 |
+
{isstringarray: ' int slen(#varname#) = 0;'},
|
1050 |
+
],
|
1051 |
+
'callfortran':'#varname#,',
|
1052 |
+
'callfortranappend': {isstringarray: 'slen(#varname#),'},
|
1053 |
+
'return': {isintent_out: ',capi_#varname#_as_array'},
|
1054 |
+
'need': 'len..',
|
1055 |
+
'_check': isarray
|
1056 |
+
}, { # intent(overwrite) array
|
1057 |
+
'decl': ' int capi_overwrite_#varname# = 1;',
|
1058 |
+
'kwlistxa': '"overwrite_#varname#",',
|
1059 |
+
'xaformat': 'i',
|
1060 |
+
'keys_xa': ',&capi_overwrite_#varname#',
|
1061 |
+
'docsignxa': 'overwrite_#varname#=1,',
|
1062 |
+
'docsignxashort': 'overwrite_#varname#,',
|
1063 |
+
'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 1',
|
1064 |
+
'_check': l_and(isarray, isintent_overwrite),
|
1065 |
+
}, {
|
1066 |
+
'frompyobj': ' capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);',
|
1067 |
+
'_check': l_and(isarray, isintent_overwrite),
|
1068 |
+
'_depend': '',
|
1069 |
+
},
|
1070 |
+
{ # intent(copy) array
|
1071 |
+
'decl': ' int capi_overwrite_#varname# = 0;',
|
1072 |
+
'kwlistxa': '"overwrite_#varname#",',
|
1073 |
+
'xaformat': 'i',
|
1074 |
+
'keys_xa': ',&capi_overwrite_#varname#',
|
1075 |
+
'docsignxa': 'overwrite_#varname#=0,',
|
1076 |
+
'docsignxashort': 'overwrite_#varname#,',
|
1077 |
+
'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 0',
|
1078 |
+
'_check': l_and(isarray, isintent_copy),
|
1079 |
+
}, {
|
1080 |
+
'frompyobj': ' capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);',
|
1081 |
+
'_check': l_and(isarray, isintent_copy),
|
1082 |
+
'_depend': '',
|
1083 |
+
}, {
|
1084 |
+
'need': [{hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}],
|
1085 |
+
'_check': isarray,
|
1086 |
+
'_depend': ''
|
1087 |
+
}, { # Not hidden
|
1088 |
+
'decl': ' PyObject *#varname#_capi = Py_None;',
|
1089 |
+
'argformat': {isrequired: 'O'},
|
1090 |
+
'keyformat': {isoptional: 'O'},
|
1091 |
+
'args_capi': {isrequired: ',&#varname#_capi'},
|
1092 |
+
'keys_capi': {isoptional: ',&#varname#_capi'},
|
1093 |
+
'_check': l_and(isarray, isintent_nothide)
|
1094 |
+
}, {
|
1095 |
+
'frompyobj': [
|
1096 |
+
' #setdims#;',
|
1097 |
+
' capi_#varname#_intent |= #intent#;',
|
1098 |
+
(' const char * capi_errmess = "#modulename#.#pyname#:'
|
1099 |
+
' failed to create array from the #nth# `#varname#`";'),
|
1100 |
+
{isintent_hide:
|
1101 |
+
' capi_#varname#_as_array = ndarray_from_pyobj('
|
1102 |
+
' #atype#,#elsize#,#varname#_Dims,#varname#_Rank,'
|
1103 |
+
' capi_#varname#_intent,Py_None,capi_errmess);'},
|
1104 |
+
{isintent_nothide:
|
1105 |
+
' capi_#varname#_as_array = ndarray_from_pyobj('
|
1106 |
+
' #atype#,#elsize#,#varname#_Dims,#varname#_Rank,'
|
1107 |
+
' capi_#varname#_intent,#varname#_capi,capi_errmess);'},
|
1108 |
+
"""\
|
1109 |
+
if (capi_#varname#_as_array == NULL) {
|
1110 |
+
PyObject* capi_err = PyErr_Occurred();
|
1111 |
+
if (capi_err == NULL) {
|
1112 |
+
capi_err = #modulename#_error;
|
1113 |
+
PyErr_SetString(capi_err, capi_errmess);
|
1114 |
+
}
|
1115 |
+
} else {
|
1116 |
+
#varname# = (#ctype# *)(PyArray_DATA(capi_#varname#_as_array));
|
1117 |
+
""",
|
1118 |
+
{isstringarray:
|
1119 |
+
' slen(#varname#) = f2py_itemsize(#varname#);'},
|
1120 |
+
{hasinitvalue: [
|
1121 |
+
{isintent_nothide:
|
1122 |
+
' if (#varname#_capi == Py_None) {'},
|
1123 |
+
{isintent_hide: ' {'},
|
1124 |
+
{iscomplexarray: ' #ctype# capi_c;'},
|
1125 |
+
"""\
|
1126 |
+
int *_i,capi_i=0;
|
1127 |
+
CFUNCSMESS(\"#name#: Initializing #varname#=#init#\\n\");
|
1128 |
+
if (initforcomb(PyArray_DIMS(capi_#varname#_as_array),
|
1129 |
+
PyArray_NDIM(capi_#varname#_as_array),1)) {
|
1130 |
+
while ((_i = nextforcomb()))
|
1131 |
+
#varname#[capi_i++] = #init#; /* fortran way */
|
1132 |
+
} else {
|
1133 |
+
PyObject *exc, *val, *tb;
|
1134 |
+
PyErr_Fetch(&exc, &val, &tb);
|
1135 |
+
PyErr_SetString(exc ? exc : #modulename#_error,
|
1136 |
+
\"Initialization of #nth# #varname# failed (initforcomb).\");
|
1137 |
+
npy_PyErr_ChainExceptionsCause(exc, val, tb);
|
1138 |
+
f2py_success = 0;
|
1139 |
+
}
|
1140 |
+
}
|
1141 |
+
if (f2py_success) {"""]},
|
1142 |
+
],
|
1143 |
+
'cleanupfrompyobj': [ # note that this list will be reversed
|
1144 |
+
' } '
|
1145 |
+
'/* if (capi_#varname#_as_array == NULL) ... else of #varname# */',
|
1146 |
+
{l_not(l_or(isintent_out, isintent_hide)): """\
|
1147 |
+
if((PyObject *)capi_#varname#_as_array!=#varname#_capi) {
|
1148 |
+
Py_XDECREF(capi_#varname#_as_array); }"""},
|
1149 |
+
{l_and(isintent_hide, l_not(isintent_out))
|
1150 |
+
: """ Py_XDECREF(capi_#varname#_as_array);"""},
|
1151 |
+
{hasinitvalue: ' } /*if (f2py_success) of #varname# init*/'},
|
1152 |
+
],
|
1153 |
+
'_check': isarray,
|
1154 |
+
'_depend': ''
|
1155 |
+
},
|
1156 |
+
# Scalararray
|
1157 |
+
{ # Common
|
1158 |
+
'_check': l_and(isarray, l_not(iscomplexarray))
|
1159 |
+
}, { # Not hidden
|
1160 |
+
'_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide)
|
1161 |
+
},
|
1162 |
+
# Integer*1 array
|
1163 |
+
{'need': '#ctype#',
|
1164 |
+
'_check': isint1array,
|
1165 |
+
'_depend': ''
|
1166 |
+
},
|
1167 |
+
# Integer*-1 array
|
1168 |
+
{'need': '#ctype#',
|
1169 |
+
'_check': isunsigned_chararray,
|
1170 |
+
'_depend': ''
|
1171 |
+
},
|
1172 |
+
# Integer*-2 array
|
1173 |
+
{'need': '#ctype#',
|
1174 |
+
'_check': isunsigned_shortarray,
|
1175 |
+
'_depend': ''
|
1176 |
+
},
|
1177 |
+
# Integer*-8 array
|
1178 |
+
{'need': '#ctype#',
|
1179 |
+
'_check': isunsigned_long_longarray,
|
1180 |
+
'_depend': ''
|
1181 |
+
},
|
1182 |
+
# Complexarray
|
1183 |
+
{'need': '#ctype#',
|
1184 |
+
'_check': iscomplexarray,
|
1185 |
+
'_depend': ''
|
1186 |
+
},
|
1187 |
+
# Character
|
1188 |
+
{
|
1189 |
+
'need': 'string',
|
1190 |
+
'_check': ischaracter,
|
1191 |
+
},
|
1192 |
+
# Character array
|
1193 |
+
{
|
1194 |
+
'need': 'string',
|
1195 |
+
'_check': ischaracterarray,
|
1196 |
+
},
|
1197 |
+
# Stringarray
|
1198 |
+
{
|
1199 |
+
'callfortranappend': {isarrayofstrings: 'flen(#varname#),'},
|
1200 |
+
'need': 'string',
|
1201 |
+
'_check': isstringarray
|
1202 |
+
}
|
1203 |
+
]
|
1204 |
+
|
1205 |
+
################# Rules for checking ###############
|
1206 |
+
|
1207 |
+
check_rules = [
|
1208 |
+
{
|
1209 |
+
'frompyobj': {debugcapi: ' fprintf(stderr,\"debug-capi:Checking `#check#\'\\n\");'},
|
1210 |
+
'need': 'len..'
|
1211 |
+
}, {
|
1212 |
+
'frompyobj': ' CHECKSCALAR(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {',
|
1213 |
+
'cleanupfrompyobj': ' } /*CHECKSCALAR(#check#)*/',
|
1214 |
+
'need': 'CHECKSCALAR',
|
1215 |
+
'_check': l_and(isscalar, l_not(iscomplex)),
|
1216 |
+
'_break': ''
|
1217 |
+
}, {
|
1218 |
+
'frompyobj': ' CHECKSTRING(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {',
|
1219 |
+
'cleanupfrompyobj': ' } /*CHECKSTRING(#check#)*/',
|
1220 |
+
'need': 'CHECKSTRING',
|
1221 |
+
'_check': isstring,
|
1222 |
+
'_break': ''
|
1223 |
+
}, {
|
1224 |
+
'need': 'CHECKARRAY',
|
1225 |
+
'frompyobj': ' CHECKARRAY(#check#,\"#check#\",\"#nth# #varname#\") {',
|
1226 |
+
'cleanupfrompyobj': ' } /*CHECKARRAY(#check#)*/',
|
1227 |
+
'_check': isarray,
|
1228 |
+
'_break': ''
|
1229 |
+
}, {
|
1230 |
+
'need': 'CHECKGENERIC',
|
1231 |
+
'frompyobj': ' CHECKGENERIC(#check#,\"#check#\",\"#nth# #varname#\") {',
|
1232 |
+
'cleanupfrompyobj': ' } /*CHECKGENERIC(#check#)*/',
|
1233 |
+
}
|
1234 |
+
]
|
1235 |
+
|
1236 |
+
########## Applying the rules. No need to modify what follows #############
|
1237 |
+
|
1238 |
+
#################### Build C/API module #######################
|
1239 |
+
|
1240 |
+
|
1241 |
+
def buildmodule(m, um):
|
1242 |
+
"""
|
1243 |
+
Return
|
1244 |
+
"""
|
1245 |
+
outmess(' Building module "%s"...\n' % (m['name']))
|
1246 |
+
ret = {}
|
1247 |
+
mod_rules = defmod_rules[:]
|
1248 |
+
vrd = capi_maps.modsign2map(m)
|
1249 |
+
rd = dictappend({'f2py_version': f2py_version}, vrd)
|
1250 |
+
funcwrappers = []
|
1251 |
+
funcwrappers2 = [] # F90 codes
|
1252 |
+
for n in m['interfaced']:
|
1253 |
+
nb = None
|
1254 |
+
for bi in m['body']:
|
1255 |
+
if bi['block'] not in ['interface', 'abstract interface']:
|
1256 |
+
errmess('buildmodule: Expected interface block. Skipping.\n')
|
1257 |
+
continue
|
1258 |
+
for b in bi['body']:
|
1259 |
+
if b['name'] == n:
|
1260 |
+
nb = b
|
1261 |
+
break
|
1262 |
+
|
1263 |
+
if not nb:
|
1264 |
+
print(
|
1265 |
+
'buildmodule: Could not find the body of interfaced routine "%s". Skipping.\n' % (n), file=sys.stderr)
|
1266 |
+
continue
|
1267 |
+
nb_list = [nb]
|
1268 |
+
if 'entry' in nb:
|
1269 |
+
for k, a in nb['entry'].items():
|
1270 |
+
nb1 = copy.deepcopy(nb)
|
1271 |
+
del nb1['entry']
|
1272 |
+
nb1['name'] = k
|
1273 |
+
nb1['args'] = a
|
1274 |
+
nb_list.append(nb1)
|
1275 |
+
for nb in nb_list:
|
1276 |
+
# requiresf90wrapper must be called before buildapi as it
|
1277 |
+
# rewrites assumed shape arrays as automatic arrays.
|
1278 |
+
isf90 = requiresf90wrapper(nb)
|
1279 |
+
# options is in scope here
|
1280 |
+
if options['emptygen']:
|
1281 |
+
b_path = options['buildpath']
|
1282 |
+
m_name = vrd['modulename']
|
1283 |
+
outmess(' Generating possibly empty wrappers"\n')
|
1284 |
+
Path(f"{b_path}/{vrd['coutput']}").touch()
|
1285 |
+
if isf90:
|
1286 |
+
# f77 + f90 wrappers
|
1287 |
+
outmess(f' Maybe empty "{m_name}-f2pywrappers2.f90"\n')
|
1288 |
+
Path(f'{b_path}/{m_name}-f2pywrappers2.f90').touch()
|
1289 |
+
outmess(f' Maybe empty "{m_name}-f2pywrappers.f"\n')
|
1290 |
+
Path(f'{b_path}/{m_name}-f2pywrappers.f').touch()
|
1291 |
+
else:
|
1292 |
+
# only f77 wrappers
|
1293 |
+
outmess(f' Maybe empty "{m_name}-f2pywrappers.f"\n')
|
1294 |
+
Path(f'{b_path}/{m_name}-f2pywrappers.f').touch()
|
1295 |
+
api, wrap = buildapi(nb)
|
1296 |
+
if wrap:
|
1297 |
+
if isf90:
|
1298 |
+
funcwrappers2.append(wrap)
|
1299 |
+
else:
|
1300 |
+
funcwrappers.append(wrap)
|
1301 |
+
ar = applyrules(api, vrd)
|
1302 |
+
rd = dictappend(rd, ar)
|
1303 |
+
|
1304 |
+
# Construct COMMON block support
|
1305 |
+
cr, wrap = common_rules.buildhooks(m)
|
1306 |
+
if wrap:
|
1307 |
+
funcwrappers.append(wrap)
|
1308 |
+
ar = applyrules(cr, vrd)
|
1309 |
+
rd = dictappend(rd, ar)
|
1310 |
+
|
1311 |
+
# Construct F90 module support
|
1312 |
+
mr, wrap = f90mod_rules.buildhooks(m)
|
1313 |
+
if wrap:
|
1314 |
+
funcwrappers2.append(wrap)
|
1315 |
+
ar = applyrules(mr, vrd)
|
1316 |
+
rd = dictappend(rd, ar)
|
1317 |
+
|
1318 |
+
for u in um:
|
1319 |
+
ar = use_rules.buildusevars(u, m['use'][u['name']])
|
1320 |
+
rd = dictappend(rd, ar)
|
1321 |
+
|
1322 |
+
needs = cfuncs.get_needs()
|
1323 |
+
# Add mapped definitions
|
1324 |
+
needs['typedefs'] += [cvar for cvar in capi_maps.f2cmap_mapped #
|
1325 |
+
if cvar in typedef_need_dict.values()]
|
1326 |
+
code = {}
|
1327 |
+
for n in needs.keys():
|
1328 |
+
code[n] = []
|
1329 |
+
for k in needs[n]:
|
1330 |
+
c = ''
|
1331 |
+
if k in cfuncs.includes0:
|
1332 |
+
c = cfuncs.includes0[k]
|
1333 |
+
elif k in cfuncs.includes:
|
1334 |
+
c = cfuncs.includes[k]
|
1335 |
+
elif k in cfuncs.userincludes:
|
1336 |
+
c = cfuncs.userincludes[k]
|
1337 |
+
elif k in cfuncs.typedefs:
|
1338 |
+
c = cfuncs.typedefs[k]
|
1339 |
+
elif k in cfuncs.typedefs_generated:
|
1340 |
+
c = cfuncs.typedefs_generated[k]
|
1341 |
+
elif k in cfuncs.cppmacros:
|
1342 |
+
c = cfuncs.cppmacros[k]
|
1343 |
+
elif k in cfuncs.cfuncs:
|
1344 |
+
c = cfuncs.cfuncs[k]
|
1345 |
+
elif k in cfuncs.callbacks:
|
1346 |
+
c = cfuncs.callbacks[k]
|
1347 |
+
elif k in cfuncs.f90modhooks:
|
1348 |
+
c = cfuncs.f90modhooks[k]
|
1349 |
+
elif k in cfuncs.commonhooks:
|
1350 |
+
c = cfuncs.commonhooks[k]
|
1351 |
+
else:
|
1352 |
+
errmess('buildmodule: unknown need %s.\n' % (repr(k)))
|
1353 |
+
continue
|
1354 |
+
code[n].append(c)
|
1355 |
+
mod_rules.append(code)
|
1356 |
+
for r in mod_rules:
|
1357 |
+
if ('_check' in r and r['_check'](m)) or ('_check' not in r):
|
1358 |
+
ar = applyrules(r, vrd, m)
|
1359 |
+
rd = dictappend(rd, ar)
|
1360 |
+
ar = applyrules(module_rules, rd)
|
1361 |
+
|
1362 |
+
fn = os.path.join(options['buildpath'], vrd['coutput'])
|
1363 |
+
ret['csrc'] = fn
|
1364 |
+
with open(fn, 'w') as f:
|
1365 |
+
f.write(ar['modulebody'].replace('\t', 2 * ' '))
|
1366 |
+
outmess(' Wrote C/API module "%s" to file "%s"\n' % (m['name'], fn))
|
1367 |
+
|
1368 |
+
if options['dorestdoc']:
|
1369 |
+
fn = os.path.join(
|
1370 |
+
options['buildpath'], vrd['modulename'] + 'module.rest')
|
1371 |
+
with open(fn, 'w') as f:
|
1372 |
+
f.write('.. -*- rest -*-\n')
|
1373 |
+
f.write('\n'.join(ar['restdoc']))
|
1374 |
+
outmess(' ReST Documentation is saved to file "%s/%smodule.rest"\n' %
|
1375 |
+
(options['buildpath'], vrd['modulename']))
|
1376 |
+
if options['dolatexdoc']:
|
1377 |
+
fn = os.path.join(
|
1378 |
+
options['buildpath'], vrd['modulename'] + 'module.tex')
|
1379 |
+
ret['ltx'] = fn
|
1380 |
+
with open(fn, 'w') as f:
|
1381 |
+
f.write(
|
1382 |
+
'%% This file is auto-generated with f2py (version:%s)\n' % (f2py_version))
|
1383 |
+
if 'shortlatex' not in options:
|
1384 |
+
f.write(
|
1385 |
+
'\\documentclass{article}\n\\usepackage{a4wide}\n\\begin{document}\n\\tableofcontents\n\n')
|
1386 |
+
f.write('\n'.join(ar['latexdoc']))
|
1387 |
+
if 'shortlatex' not in options:
|
1388 |
+
f.write('\\end{document}')
|
1389 |
+
outmess(' Documentation is saved to file "%s/%smodule.tex"\n' %
|
1390 |
+
(options['buildpath'], vrd['modulename']))
|
1391 |
+
if funcwrappers:
|
1392 |
+
wn = os.path.join(options['buildpath'], vrd['f2py_wrapper_output'])
|
1393 |
+
ret['fsrc'] = wn
|
1394 |
+
with open(wn, 'w') as f:
|
1395 |
+
f.write('C -*- fortran -*-\n')
|
1396 |
+
f.write(
|
1397 |
+
'C This file is autogenerated with f2py (version:%s)\n' % (f2py_version))
|
1398 |
+
f.write(
|
1399 |
+
'C It contains Fortran 77 wrappers to fortran functions.\n')
|
1400 |
+
lines = []
|
1401 |
+
for l in ('\n\n'.join(funcwrappers) + '\n').split('\n'):
|
1402 |
+
if 0 <= l.find('!') < 66:
|
1403 |
+
# don't split comment lines
|
1404 |
+
lines.append(l + '\n')
|
1405 |
+
elif l and l[0] == ' ':
|
1406 |
+
while len(l) >= 66:
|
1407 |
+
lines.append(l[:66] + '\n &')
|
1408 |
+
l = l[66:]
|
1409 |
+
lines.append(l + '\n')
|
1410 |
+
else:
|
1411 |
+
lines.append(l + '\n')
|
1412 |
+
lines = ''.join(lines).replace('\n &\n', '\n')
|
1413 |
+
f.write(lines)
|
1414 |
+
outmess(' Fortran 77 wrappers are saved to "%s"\n' % (wn))
|
1415 |
+
if funcwrappers2:
|
1416 |
+
wn = os.path.join(
|
1417 |
+
options['buildpath'], '%s-f2pywrappers2.f90' % (vrd['modulename']))
|
1418 |
+
ret['fsrc'] = wn
|
1419 |
+
with open(wn, 'w') as f:
|
1420 |
+
f.write('! -*- f90 -*-\n')
|
1421 |
+
f.write(
|
1422 |
+
'! This file is autogenerated with f2py (version:%s)\n' % (f2py_version))
|
1423 |
+
f.write(
|
1424 |
+
'! It contains Fortran 90 wrappers to fortran functions.\n')
|
1425 |
+
lines = []
|
1426 |
+
for l in ('\n\n'.join(funcwrappers2) + '\n').split('\n'):
|
1427 |
+
if 0 <= l.find('!') < 72:
|
1428 |
+
# don't split comment lines
|
1429 |
+
lines.append(l + '\n')
|
1430 |
+
elif len(l) > 72 and l[0] == ' ':
|
1431 |
+
lines.append(l[:72] + '&\n &')
|
1432 |
+
l = l[72:]
|
1433 |
+
while len(l) > 66:
|
1434 |
+
lines.append(l[:66] + '&\n &')
|
1435 |
+
l = l[66:]
|
1436 |
+
lines.append(l + '\n')
|
1437 |
+
else:
|
1438 |
+
lines.append(l + '\n')
|
1439 |
+
lines = ''.join(lines).replace('\n &\n', '\n')
|
1440 |
+
f.write(lines)
|
1441 |
+
outmess(' Fortran 90 wrappers are saved to "%s"\n' % (wn))
|
1442 |
+
return ret
|
1443 |
+
|
1444 |
+
################## Build C/API function #############
|
1445 |
+
|
1446 |
+
stnd = {1: 'st', 2: 'nd', 3: 'rd', 4: 'th', 5: 'th',
|
1447 |
+
6: 'th', 7: 'th', 8: 'th', 9: 'th', 0: 'th'}
|
1448 |
+
|
1449 |
+
|
1450 |
+
def buildapi(rout):
|
1451 |
+
rout, wrap = func2subr.assubr(rout)
|
1452 |
+
args, depargs = getargs2(rout)
|
1453 |
+
capi_maps.depargs = depargs
|
1454 |
+
var = rout['vars']
|
1455 |
+
|
1456 |
+
if ismoduleroutine(rout):
|
1457 |
+
outmess(' Constructing wrapper function "%s.%s"...\n' %
|
1458 |
+
(rout['modulename'], rout['name']))
|
1459 |
+
else:
|
1460 |
+
outmess(' Constructing wrapper function "%s"...\n' % (rout['name']))
|
1461 |
+
# Routine
|
1462 |
+
vrd = capi_maps.routsign2map(rout)
|
1463 |
+
rd = dictappend({}, vrd)
|
1464 |
+
for r in rout_rules:
|
1465 |
+
if ('_check' in r and r['_check'](rout)) or ('_check' not in r):
|
1466 |
+
ar = applyrules(r, vrd, rout)
|
1467 |
+
rd = dictappend(rd, ar)
|
1468 |
+
|
1469 |
+
# Args
|
1470 |
+
nth, nthk = 0, 0
|
1471 |
+
savevrd = {}
|
1472 |
+
for a in args:
|
1473 |
+
vrd = capi_maps.sign2map(a, var[a])
|
1474 |
+
if isintent_aux(var[a]):
|
1475 |
+
_rules = aux_rules
|
1476 |
+
else:
|
1477 |
+
_rules = arg_rules
|
1478 |
+
if not isintent_hide(var[a]):
|
1479 |
+
if not isoptional(var[a]):
|
1480 |
+
nth = nth + 1
|
1481 |
+
vrd['nth'] = repr(nth) + stnd[nth % 10] + ' argument'
|
1482 |
+
else:
|
1483 |
+
nthk = nthk + 1
|
1484 |
+
vrd['nth'] = repr(nthk) + stnd[nthk % 10] + ' keyword'
|
1485 |
+
else:
|
1486 |
+
vrd['nth'] = 'hidden'
|
1487 |
+
savevrd[a] = vrd
|
1488 |
+
for r in _rules:
|
1489 |
+
if '_depend' in r:
|
1490 |
+
continue
|
1491 |
+
if ('_check' in r and r['_check'](var[a])) or ('_check' not in r):
|
1492 |
+
ar = applyrules(r, vrd, var[a])
|
1493 |
+
rd = dictappend(rd, ar)
|
1494 |
+
if '_break' in r:
|
1495 |
+
break
|
1496 |
+
for a in depargs:
|
1497 |
+
if isintent_aux(var[a]):
|
1498 |
+
_rules = aux_rules
|
1499 |
+
else:
|
1500 |
+
_rules = arg_rules
|
1501 |
+
vrd = savevrd[a]
|
1502 |
+
for r in _rules:
|
1503 |
+
if '_depend' not in r:
|
1504 |
+
continue
|
1505 |
+
if ('_check' in r and r['_check'](var[a])) or ('_check' not in r):
|
1506 |
+
ar = applyrules(r, vrd, var[a])
|
1507 |
+
rd = dictappend(rd, ar)
|
1508 |
+
if '_break' in r:
|
1509 |
+
break
|
1510 |
+
if 'check' in var[a]:
|
1511 |
+
for c in var[a]['check']:
|
1512 |
+
vrd['check'] = c
|
1513 |
+
ar = applyrules(check_rules, vrd, var[a])
|
1514 |
+
rd = dictappend(rd, ar)
|
1515 |
+
if isinstance(rd['cleanupfrompyobj'], list):
|
1516 |
+
rd['cleanupfrompyobj'].reverse()
|
1517 |
+
if isinstance(rd['closepyobjfrom'], list):
|
1518 |
+
rd['closepyobjfrom'].reverse()
|
1519 |
+
rd['docsignature'] = stripcomma(replace('#docsign##docsignopt##docsignxa#',
|
1520 |
+
{'docsign': rd['docsign'],
|
1521 |
+
'docsignopt': rd['docsignopt'],
|
1522 |
+
'docsignxa': rd['docsignxa']}))
|
1523 |
+
optargs = stripcomma(replace('#docsignopt##docsignxa#',
|
1524 |
+
{'docsignxa': rd['docsignxashort'],
|
1525 |
+
'docsignopt': rd['docsignoptshort']}
|
1526 |
+
))
|
1527 |
+
if optargs == '':
|
1528 |
+
rd['docsignatureshort'] = stripcomma(
|
1529 |
+
replace('#docsign#', {'docsign': rd['docsign']}))
|
1530 |
+
else:
|
1531 |
+
rd['docsignatureshort'] = replace('#docsign#[#docsignopt#]',
|
1532 |
+
{'docsign': rd['docsign'],
|
1533 |
+
'docsignopt': optargs,
|
1534 |
+
})
|
1535 |
+
rd['latexdocsignatureshort'] = rd['docsignatureshort'].replace('_', '\\_')
|
1536 |
+
rd['latexdocsignatureshort'] = rd[
|
1537 |
+
'latexdocsignatureshort'].replace(',', ', ')
|
1538 |
+
cfs = stripcomma(replace('#callfortran##callfortranappend#', {
|
1539 |
+
'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']}))
|
1540 |
+
if len(rd['callfortranappend']) > 1:
|
1541 |
+
rd['callcompaqfortran'] = stripcomma(replace('#callfortran# 0,#callfortranappend#', {
|
1542 |
+
'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']}))
|
1543 |
+
else:
|
1544 |
+
rd['callcompaqfortran'] = cfs
|
1545 |
+
rd['callfortran'] = cfs
|
1546 |
+
if isinstance(rd['docreturn'], list):
|
1547 |
+
rd['docreturn'] = stripcomma(
|
1548 |
+
replace('#docreturn#', {'docreturn': rd['docreturn']})) + ' = '
|
1549 |
+
rd['docstrsigns'] = []
|
1550 |
+
rd['latexdocstrsigns'] = []
|
1551 |
+
for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']:
|
1552 |
+
if k in rd and isinstance(rd[k], list):
|
1553 |
+
rd['docstrsigns'] = rd['docstrsigns'] + rd[k]
|
1554 |
+
k = 'latex' + k
|
1555 |
+
if k in rd and isinstance(rd[k], list):
|
1556 |
+
rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] +\
|
1557 |
+
['\\begin{description}'] + rd[k][1:] +\
|
1558 |
+
['\\end{description}']
|
1559 |
+
|
1560 |
+
ar = applyrules(routine_rules, rd)
|
1561 |
+
if ismoduleroutine(rout):
|
1562 |
+
outmess(' %s\n' % (ar['docshort']))
|
1563 |
+
else:
|
1564 |
+
outmess(' %s\n' % (ar['docshort']))
|
1565 |
+
return ar, wrap
|
1566 |
+
|
1567 |
+
|
1568 |
+
#################### EOF rules.py #######################
|
venv/lib/python3.10/site-packages/numpy/f2py/setup.cfg
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
[bdist_rpm]
|
2 |
+
doc_files = docs/
|
3 |
+
tests/
|
venv/lib/python3.10/site-packages/numpy/f2py/setup.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
setup.py for installing F2PY
|
4 |
+
|
5 |
+
Usage:
|
6 |
+
pip install .
|
7 |
+
|
8 |
+
Copyright 2001-2005 Pearu Peterson all rights reserved,
|
9 |
+
Pearu Peterson <[email protected]>
|
10 |
+
Permission to use, modify, and distribute this software is given under the
|
11 |
+
terms of the NumPy License.
|
12 |
+
|
13 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
14 |
+
$Revision: 1.32 $
|
15 |
+
$Date: 2005/01/30 17:22:14 $
|
16 |
+
Pearu Peterson
|
17 |
+
|
18 |
+
"""
|
19 |
+
from numpy.distutils.core import setup
|
20 |
+
from numpy.distutils.misc_util import Configuration
|
21 |
+
|
22 |
+
|
23 |
+
from __version__ import version
|
24 |
+
|
25 |
+
|
26 |
+
def configuration(parent_package='', top_path=None):
|
27 |
+
config = Configuration('f2py', parent_package, top_path)
|
28 |
+
config.add_subpackage('tests')
|
29 |
+
config.add_subpackage('_backends')
|
30 |
+
config.add_data_dir('tests/src')
|
31 |
+
config.add_data_files(
|
32 |
+
'src/fortranobject.c',
|
33 |
+
'src/fortranobject.h',
|
34 |
+
'_backends/meson.build.template',
|
35 |
+
)
|
36 |
+
config.add_data_files('*.pyi')
|
37 |
+
return config
|
38 |
+
|
39 |
+
|
40 |
+
if __name__ == "__main__":
|
41 |
+
|
42 |
+
config = configuration(top_path='')
|
43 |
+
config = config.todict()
|
44 |
+
|
45 |
+
config['classifiers'] = [
|
46 |
+
'Development Status :: 5 - Production/Stable',
|
47 |
+
'Intended Audience :: Developers',
|
48 |
+
'Intended Audience :: Science/Research',
|
49 |
+
'License :: OSI Approved :: NumPy License',
|
50 |
+
'Natural Language :: English',
|
51 |
+
'Operating System :: OS Independent',
|
52 |
+
'Programming Language :: C',
|
53 |
+
'Programming Language :: Fortran',
|
54 |
+
'Programming Language :: Python',
|
55 |
+
'Topic :: Scientific/Engineering',
|
56 |
+
'Topic :: Software Development :: Code Generators',
|
57 |
+
]
|
58 |
+
setup(version=version,
|
59 |
+
description="F2PY - Fortran to Python Interface Generator",
|
60 |
+
author="Pearu Peterson",
|
61 |
+
author_email="[email protected]",
|
62 |
+
maintainer="Pearu Peterson",
|
63 |
+
maintainer_email="[email protected]",
|
64 |
+
license="BSD",
|
65 |
+
platforms="Unix, Windows (mingw|cygwin), Mac OSX",
|
66 |
+
long_description="""\
|
67 |
+
The Fortran to Python Interface Generator, or F2PY for short, is a
|
68 |
+
command line tool (f2py) for generating Python C/API modules for
|
69 |
+
wrapping Fortran 77/90/95 subroutines, accessing common blocks from
|
70 |
+
Python, and calling Python functions from Fortran (call-backs).
|
71 |
+
Interfacing subroutines/data from F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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#define FORTRANOBJECT_C
|
2 |
+
#include "fortranobject.h"
|
3 |
+
|
4 |
+
#ifdef __cplusplus
|
5 |
+
extern "C" {
|
6 |
+
#endif
|
7 |
+
|
8 |
+
#include <stdarg.h>
|
9 |
+
#include <stdlib.h>
|
10 |
+
#include <string.h>
|
11 |
+
|
12 |
+
/*
|
13 |
+
This file implements: FortranObject, array_from_pyobj, copy_ND_array
|
14 |
+
|
15 |
+
Author: Pearu Peterson <[email protected]>
|
16 |
+
$Revision: 1.52 $
|
17 |
+
$Date: 2005/07/11 07:44:20 $
|
18 |
+
*/
|
19 |
+
|
20 |
+
int
|
21 |
+
F2PyDict_SetItemString(PyObject *dict, char *name, PyObject *obj)
|
22 |
+
{
|
23 |
+
if (obj == NULL) {
|
24 |
+
fprintf(stderr, "Error loading %s\n", name);
|
25 |
+
if (PyErr_Occurred()) {
|
26 |
+
PyErr_Print();
|
27 |
+
PyErr_Clear();
|
28 |
+
}
|
29 |
+
return -1;
|
30 |
+
}
|
31 |
+
return PyDict_SetItemString(dict, name, obj);
|
32 |
+
}
|
33 |
+
|
34 |
+
/*
|
35 |
+
* Python-only fallback for thread-local callback pointers
|
36 |
+
*/
|
37 |
+
void *
|
38 |
+
F2PySwapThreadLocalCallbackPtr(char *key, void *ptr)
|
39 |
+
{
|
40 |
+
PyObject *local_dict, *value;
|
41 |
+
void *prev;
|
42 |
+
|
43 |
+
local_dict = PyThreadState_GetDict();
|
44 |
+
if (local_dict == NULL) {
|
45 |
+
Py_FatalError(
|
46 |
+
"F2PySwapThreadLocalCallbackPtr: PyThreadState_GetDict "
|
47 |
+
"failed");
|
48 |
+
}
|
49 |
+
|
50 |
+
value = PyDict_GetItemString(local_dict, key);
|
51 |
+
if (value != NULL) {
|
52 |
+
prev = PyLong_AsVoidPtr(value);
|
53 |
+
if (PyErr_Occurred()) {
|
54 |
+
Py_FatalError(
|
55 |
+
"F2PySwapThreadLocalCallbackPtr: PyLong_AsVoidPtr failed");
|
56 |
+
}
|
57 |
+
}
|
58 |
+
else {
|
59 |
+
prev = NULL;
|
60 |
+
}
|
61 |
+
|
62 |
+
value = PyLong_FromVoidPtr((void *)ptr);
|
63 |
+
if (value == NULL) {
|
64 |
+
Py_FatalError(
|
65 |
+
"F2PySwapThreadLocalCallbackPtr: PyLong_FromVoidPtr failed");
|
66 |
+
}
|
67 |
+
|
68 |
+
if (PyDict_SetItemString(local_dict, key, value) != 0) {
|
69 |
+
Py_FatalError(
|
70 |
+
"F2PySwapThreadLocalCallbackPtr: PyDict_SetItemString failed");
|
71 |
+
}
|
72 |
+
|
73 |
+
Py_DECREF(value);
|
74 |
+
|
75 |
+
return prev;
|
76 |
+
}
|
77 |
+
|
78 |
+
void *
|
79 |
+
F2PyGetThreadLocalCallbackPtr(char *key)
|
80 |
+
{
|
81 |
+
PyObject *local_dict, *value;
|
82 |
+
void *prev;
|
83 |
+
|
84 |
+
local_dict = PyThreadState_GetDict();
|
85 |
+
if (local_dict == NULL) {
|
86 |
+
Py_FatalError(
|
87 |
+
"F2PyGetThreadLocalCallbackPtr: PyThreadState_GetDict failed");
|
88 |
+
}
|
89 |
+
|
90 |
+
value = PyDict_GetItemString(local_dict, key);
|
91 |
+
if (value != NULL) {
|
92 |
+
prev = PyLong_AsVoidPtr(value);
|
93 |
+
if (PyErr_Occurred()) {
|
94 |
+
Py_FatalError(
|
95 |
+
"F2PyGetThreadLocalCallbackPtr: PyLong_AsVoidPtr failed");
|
96 |
+
}
|
97 |
+
}
|
98 |
+
else {
|
99 |
+
prev = NULL;
|
100 |
+
}
|
101 |
+
|
102 |
+
return prev;
|
103 |
+
}
|
104 |
+
|
105 |
+
static PyArray_Descr *
|
106 |
+
get_descr_from_type_and_elsize(const int type_num, const int elsize) {
|
107 |
+
PyArray_Descr * descr = PyArray_DescrFromType(type_num);
|
108 |
+
if (type_num == NPY_STRING) {
|
109 |
+
// PyArray_DescrFromType returns descr with elsize = 0.
|
110 |
+
PyArray_DESCR_REPLACE(descr);
|
111 |
+
if (descr == NULL) {
|
112 |
+
return NULL;
|
113 |
+
}
|
114 |
+
descr->elsize = elsize;
|
115 |
+
}
|
116 |
+
return descr;
|
117 |
+
}
|
118 |
+
|
119 |
+
/************************* FortranObject *******************************/
|
120 |
+
|
121 |
+
typedef PyObject *(*fortranfunc)(PyObject *, PyObject *, PyObject *, void *);
|
122 |
+
|
123 |
+
PyObject *
|
124 |
+
PyFortranObject_New(FortranDataDef *defs, f2py_void_func init)
|
125 |
+
{
|
126 |
+
int i;
|
127 |
+
PyFortranObject *fp = NULL;
|
128 |
+
PyObject *v = NULL;
|
129 |
+
if (init != NULL) { /* Initialize F90 module objects */
|
130 |
+
(*(init))();
|
131 |
+
}
|
132 |
+
fp = PyObject_New(PyFortranObject, &PyFortran_Type);
|
133 |
+
if (fp == NULL) {
|
134 |
+
return NULL;
|
135 |
+
}
|
136 |
+
if ((fp->dict = PyDict_New()) == NULL) {
|
137 |
+
Py_DECREF(fp);
|
138 |
+
return NULL;
|
139 |
+
}
|
140 |
+
fp->len = 0;
|
141 |
+
while (defs[fp->len].name != NULL) {
|
142 |
+
fp->len++;
|
143 |
+
}
|
144 |
+
if (fp->len == 0) {
|
145 |
+
goto fail;
|
146 |
+
}
|
147 |
+
fp->defs = defs;
|
148 |
+
for (i = 0; i < fp->len; i++) {
|
149 |
+
if (fp->defs[i].rank == -1) { /* Is Fortran routine */
|
150 |
+
v = PyFortranObject_NewAsAttr(&(fp->defs[i]));
|
151 |
+
if (v == NULL) {
|
152 |
+
goto fail;
|
153 |
+
}
|
154 |
+
PyDict_SetItemString(fp->dict, fp->defs[i].name, v);
|
155 |
+
Py_XDECREF(v);
|
156 |
+
}
|
157 |
+
else if ((fp->defs[i].data) !=
|
158 |
+
NULL) { /* Is Fortran variable or array (not allocatable) */
|
159 |
+
PyArray_Descr *
|
160 |
+
descr = get_descr_from_type_and_elsize(fp->defs[i].type,
|
161 |
+
fp->defs[i].elsize);
|
162 |
+
if (descr == NULL) {
|
163 |
+
goto fail;
|
164 |
+
}
|
165 |
+
v = PyArray_NewFromDescr(&PyArray_Type, descr, fp->defs[i].rank,
|
166 |
+
fp->defs[i].dims.d, NULL, fp->defs[i].data,
|
167 |
+
NPY_ARRAY_FARRAY, NULL);
|
168 |
+
if (v == NULL) {
|
169 |
+
Py_DECREF(descr);
|
170 |
+
goto fail;
|
171 |
+
}
|
172 |
+
PyDict_SetItemString(fp->dict, fp->defs[i].name, v);
|
173 |
+
Py_XDECREF(v);
|
174 |
+
}
|
175 |
+
}
|
176 |
+
return (PyObject *)fp;
|
177 |
+
fail:
|
178 |
+
Py_XDECREF(fp);
|
179 |
+
return NULL;
|
180 |
+
}
|
181 |
+
|
182 |
+
PyObject *
|
183 |
+
PyFortranObject_NewAsAttr(FortranDataDef *defs)
|
184 |
+
{ /* used for calling F90 module routines */
|
185 |
+
PyFortranObject *fp = NULL;
|
186 |
+
fp = PyObject_New(PyFortranObject, &PyFortran_Type);
|
187 |
+
if (fp == NULL)
|
188 |
+
return NULL;
|
189 |
+
if ((fp->dict = PyDict_New()) == NULL) {
|
190 |
+
PyObject_Del(fp);
|
191 |
+
return NULL;
|
192 |
+
}
|
193 |
+
fp->len = 1;
|
194 |
+
fp->defs = defs;
|
195 |
+
if (defs->rank == -1) {
|
196 |
+
PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("function %s", defs->name));
|
197 |
+
} else if (defs->rank == 0) {
|
198 |
+
PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("scalar %s", defs->name));
|
199 |
+
} else {
|
200 |
+
PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("array %s", defs->name));
|
201 |
+
}
|
202 |
+
return (PyObject *)fp;
|
203 |
+
}
|
204 |
+
|
205 |
+
/* Fortran methods */
|
206 |
+
|
207 |
+
static void
|
208 |
+
fortran_dealloc(PyFortranObject *fp)
|
209 |
+
{
|
210 |
+
Py_XDECREF(fp->dict);
|
211 |
+
PyObject_Del(fp);
|
212 |
+
}
|
213 |
+
|
214 |
+
/* Returns number of bytes consumed from buf, or -1 on error. */
|
215 |
+
static Py_ssize_t
|
216 |
+
format_def(char *buf, Py_ssize_t size, FortranDataDef def)
|
217 |
+
{
|
218 |
+
char *p = buf;
|
219 |
+
int i;
|
220 |
+
npy_intp n;
|
221 |
+
|
222 |
+
n = PyOS_snprintf(p, size, "array(%" NPY_INTP_FMT, def.dims.d[0]);
|
223 |
+
if (n < 0 || n >= size) {
|
224 |
+
return -1;
|
225 |
+
}
|
226 |
+
p += n;
|
227 |
+
size -= n;
|
228 |
+
|
229 |
+
for (i = 1; i < def.rank; i++) {
|
230 |
+
n = PyOS_snprintf(p, size, ",%" NPY_INTP_FMT, def.dims.d[i]);
|
231 |
+
if (n < 0 || n >= size) {
|
232 |
+
return -1;
|
233 |
+
}
|
234 |
+
p += n;
|
235 |
+
size -= n;
|
236 |
+
}
|
237 |
+
|
238 |
+
if (size <= 0) {
|
239 |
+
return -1;
|
240 |
+
}
|
241 |
+
|
242 |
+
*p++ = ')';
|
243 |
+
size--;
|
244 |
+
|
245 |
+
if (def.data == NULL) {
|
246 |
+
static const char notalloc[] = ", not allocated";
|
247 |
+
if ((size_t)size < sizeof(notalloc)) {
|
248 |
+
return -1;
|
249 |
+
}
|
250 |
+
memcpy(p, notalloc, sizeof(notalloc));
|
251 |
+
p += sizeof(notalloc);
|
252 |
+
size -= sizeof(notalloc);
|
253 |
+
}
|
254 |
+
|
255 |
+
return p - buf;
|
256 |
+
}
|
257 |
+
|
258 |
+
static PyObject *
|
259 |
+
fortran_doc(FortranDataDef def)
|
260 |
+
{
|
261 |
+
char *buf, *p;
|
262 |
+
PyObject *s = NULL;
|
263 |
+
Py_ssize_t n, origsize, size = 100;
|
264 |
+
|
265 |
+
if (def.doc != NULL) {
|
266 |
+
size += strlen(def.doc);
|
267 |
+
}
|
268 |
+
origsize = size;
|
269 |
+
buf = p = (char *)PyMem_Malloc(size);
|
270 |
+
if (buf == NULL) {
|
271 |
+
return PyErr_NoMemory();
|
272 |
+
}
|
273 |
+
|
274 |
+
if (def.rank == -1) {
|
275 |
+
if (def.doc) {
|
276 |
+
n = strlen(def.doc);
|
277 |
+
if (n > size) {
|
278 |
+
goto fail;
|
279 |
+
}
|
280 |
+
memcpy(p, def.doc, n);
|
281 |
+
p += n;
|
282 |
+
size -= n;
|
283 |
+
}
|
284 |
+
else {
|
285 |
+
n = PyOS_snprintf(p, size, "%s - no docs available", def.name);
|
286 |
+
if (n < 0 || n >= size) {
|
287 |
+
goto fail;
|
288 |
+
}
|
289 |
+
p += n;
|
290 |
+
size -= n;
|
291 |
+
}
|
292 |
+
}
|
293 |
+
else {
|
294 |
+
PyArray_Descr *d = PyArray_DescrFromType(def.type);
|
295 |
+
n = PyOS_snprintf(p, size, "%s : '%c'-", def.name, d->type);
|
296 |
+
Py_DECREF(d);
|
297 |
+
if (n < 0 || n >= size) {
|
298 |
+
goto fail;
|
299 |
+
}
|
300 |
+
p += n;
|
301 |
+
size -= n;
|
302 |
+
|
303 |
+
if (def.data == NULL) {
|
304 |
+
n = format_def(p, size, def);
|
305 |
+
if (n < 0) {
|
306 |
+
goto fail;
|
307 |
+
}
|
308 |
+
p += n;
|
309 |
+
size -= n;
|
310 |
+
}
|
311 |
+
else if (def.rank > 0) {
|
312 |
+
n = format_def(p, size, def);
|
313 |
+
if (n < 0) {
|
314 |
+
goto fail;
|
315 |
+
}
|
316 |
+
p += n;
|
317 |
+
size -= n;
|
318 |
+
}
|
319 |
+
else {
|
320 |
+
n = strlen("scalar");
|
321 |
+
if (size < n) {
|
322 |
+
goto fail;
|
323 |
+
}
|
324 |
+
memcpy(p, "scalar", n);
|
325 |
+
p += n;
|
326 |
+
size -= n;
|
327 |
+
}
|
328 |
+
}
|
329 |
+
if (size <= 1) {
|
330 |
+
goto fail;
|
331 |
+
}
|
332 |
+
*p++ = '\n';
|
333 |
+
size--;
|
334 |
+
|
335 |
+
/* p now points one beyond the last character of the string in buf */
|
336 |
+
s = PyUnicode_FromStringAndSize(buf, p - buf);
|
337 |
+
|
338 |
+
PyMem_Free(buf);
|
339 |
+
return s;
|
340 |
+
|
341 |
+
fail:
|
342 |
+
fprintf(stderr,
|
343 |
+
"fortranobject.c: fortran_doc: len(p)=%zd>%zd=size:"
|
344 |
+
" too long docstring required, increase size\n",
|
345 |
+
p - buf, origsize);
|
346 |
+
PyMem_Free(buf);
|
347 |
+
return NULL;
|
348 |
+
}
|
349 |
+
|
350 |
+
static FortranDataDef *save_def; /* save pointer of an allocatable array */
|
351 |
+
static void
|
352 |
+
set_data(char *d, npy_intp *f)
|
353 |
+
{ /* callback from Fortran */
|
354 |
+
if (*f) /* In fortran f=allocated(d) */
|
355 |
+
save_def->data = d;
|
356 |
+
else
|
357 |
+
save_def->data = NULL;
|
358 |
+
/* printf("set_data: d=%p,f=%d\n",d,*f); */
|
359 |
+
}
|
360 |
+
|
361 |
+
static PyObject *
|
362 |
+
fortran_getattr(PyFortranObject *fp, char *name)
|
363 |
+
{
|
364 |
+
int i, j, k, flag;
|
365 |
+
if (fp->dict != NULL) {
|
366 |
+
PyObject *v = _PyDict_GetItemStringWithError(fp->dict, name);
|
367 |
+
if (v == NULL && PyErr_Occurred()) {
|
368 |
+
return NULL;
|
369 |
+
}
|
370 |
+
else if (v != NULL) {
|
371 |
+
Py_INCREF(v);
|
372 |
+
return v;
|
373 |
+
}
|
374 |
+
}
|
375 |
+
for (i = 0, j = 1; i < fp->len && (j = strcmp(name, fp->defs[i].name));
|
376 |
+
i++)
|
377 |
+
;
|
378 |
+
if (j == 0)
|
379 |
+
if (fp->defs[i].rank != -1) { /* F90 allocatable array */
|
380 |
+
if (fp->defs[i].func == NULL)
|
381 |
+
return NULL;
|
382 |
+
for (k = 0; k < fp->defs[i].rank; ++k) fp->defs[i].dims.d[k] = -1;
|
383 |
+
save_def = &fp->defs[i];
|
384 |
+
(*(fp->defs[i].func))(&fp->defs[i].rank, fp->defs[i].dims.d,
|
385 |
+
set_data, &flag);
|
386 |
+
if (flag == 2)
|
387 |
+
k = fp->defs[i].rank + 1;
|
388 |
+
else
|
389 |
+
k = fp->defs[i].rank;
|
390 |
+
if (fp->defs[i].data != NULL) { /* array is allocated */
|
391 |
+
PyObject *v = PyArray_New(
|
392 |
+
&PyArray_Type, k, fp->defs[i].dims.d, fp->defs[i].type,
|
393 |
+
NULL, fp->defs[i].data, 0, NPY_ARRAY_FARRAY, NULL);
|
394 |
+
if (v == NULL)
|
395 |
+
return NULL;
|
396 |
+
/* Py_INCREF(v); */
|
397 |
+
return v;
|
398 |
+
}
|
399 |
+
else { /* array is not allocated */
|
400 |
+
Py_RETURN_NONE;
|
401 |
+
}
|
402 |
+
}
|
403 |
+
if (strcmp(name, "__dict__") == 0) {
|
404 |
+
Py_INCREF(fp->dict);
|
405 |
+
return fp->dict;
|
406 |
+
}
|
407 |
+
if (strcmp(name, "__doc__") == 0) {
|
408 |
+
PyObject *s = PyUnicode_FromString(""), *s2, *s3;
|
409 |
+
for (i = 0; i < fp->len; i++) {
|
410 |
+
s2 = fortran_doc(fp->defs[i]);
|
411 |
+
s3 = PyUnicode_Concat(s, s2);
|
412 |
+
Py_DECREF(s2);
|
413 |
+
Py_DECREF(s);
|
414 |
+
s = s3;
|
415 |
+
}
|
416 |
+
if (PyDict_SetItemString(fp->dict, name, s))
|
417 |
+
return NULL;
|
418 |
+
return s;
|
419 |
+
}
|
420 |
+
if ((strcmp(name, "_cpointer") == 0) && (fp->len == 1)) {
|
421 |
+
PyObject *cobj =
|
422 |
+
F2PyCapsule_FromVoidPtr((void *)(fp->defs[0].data), NULL);
|
423 |
+
if (PyDict_SetItemString(fp->dict, name, cobj))
|
424 |
+
return NULL;
|
425 |
+
return cobj;
|
426 |
+
}
|
427 |
+
PyObject *str, *ret;
|
428 |
+
str = PyUnicode_FromString(name);
|
429 |
+
ret = PyObject_GenericGetAttr((PyObject *)fp, str);
|
430 |
+
Py_DECREF(str);
|
431 |
+
return ret;
|
432 |
+
}
|
433 |
+
|
434 |
+
static int
|
435 |
+
fortran_setattr(PyFortranObject *fp, char *name, PyObject *v)
|
436 |
+
{
|
437 |
+
int i, j, flag;
|
438 |
+
PyArrayObject *arr = NULL;
|
439 |
+
for (i = 0, j = 1; i < fp->len && (j = strcmp(name, fp->defs[i].name));
|
440 |
+
i++)
|
441 |
+
;
|
442 |
+
if (j == 0) {
|
443 |
+
if (fp->defs[i].rank == -1) {
|
444 |
+
PyErr_SetString(PyExc_AttributeError,
|
445 |
+
"over-writing fortran routine");
|
446 |
+
return -1;
|
447 |
+
}
|
448 |
+
if (fp->defs[i].func != NULL) { /* is allocatable array */
|
449 |
+
npy_intp dims[F2PY_MAX_DIMS];
|
450 |
+
int k;
|
451 |
+
save_def = &fp->defs[i];
|
452 |
+
if (v != Py_None) { /* set new value (reallocate if needed --
|
453 |
+
see f2py generated code for more
|
454 |
+
details ) */
|
455 |
+
for (k = 0; k < fp->defs[i].rank; k++) dims[k] = -1;
|
456 |
+
if ((arr = array_from_pyobj(fp->defs[i].type, dims,
|
457 |
+
fp->defs[i].rank, F2PY_INTENT_IN,
|
458 |
+
v)) == NULL)
|
459 |
+
return -1;
|
460 |
+
(*(fp->defs[i].func))(&fp->defs[i].rank, PyArray_DIMS(arr),
|
461 |
+
set_data, &flag);
|
462 |
+
}
|
463 |
+
else { /* deallocate */
|
464 |
+
for (k = 0; k < fp->defs[i].rank; k++) dims[k] = 0;
|
465 |
+
(*(fp->defs[i].func))(&fp->defs[i].rank, dims, set_data,
|
466 |
+
&flag);
|
467 |
+
for (k = 0; k < fp->defs[i].rank; k++) dims[k] = -1;
|
468 |
+
}
|
469 |
+
memcpy(fp->defs[i].dims.d, dims,
|
470 |
+
fp->defs[i].rank * sizeof(npy_intp));
|
471 |
+
}
|
472 |
+
else { /* not allocatable array */
|
473 |
+
if ((arr = array_from_pyobj(fp->defs[i].type, fp->defs[i].dims.d,
|
474 |
+
fp->defs[i].rank, F2PY_INTENT_IN,
|
475 |
+
v)) == NULL)
|
476 |
+
return -1;
|
477 |
+
}
|
478 |
+
if (fp->defs[i].data !=
|
479 |
+
NULL) { /* copy Python object to Fortran array */
|
480 |
+
npy_intp s = PyArray_MultiplyList(fp->defs[i].dims.d,
|
481 |
+
PyArray_NDIM(arr));
|
482 |
+
if (s == -1)
|
483 |
+
s = PyArray_MultiplyList(PyArray_DIMS(arr), PyArray_NDIM(arr));
|
484 |
+
if (s < 0 || (memcpy(fp->defs[i].data, PyArray_DATA(arr),
|
485 |
+
s * PyArray_ITEMSIZE(arr))) == NULL) {
|
486 |
+
if ((PyObject *)arr != v) {
|
487 |
+
Py_DECREF(arr);
|
488 |
+
}
|
489 |
+
return -1;
|
490 |
+
}
|
491 |
+
if ((PyObject *)arr != v) {
|
492 |
+
Py_DECREF(arr);
|
493 |
+
}
|
494 |
+
}
|
495 |
+
else
|
496 |
+
return (fp->defs[i].func == NULL ? -1 : 0);
|
497 |
+
return 0; /* successful */
|
498 |
+
}
|
499 |
+
if (fp->dict == NULL) {
|
500 |
+
fp->dict = PyDict_New();
|
501 |
+
if (fp->dict == NULL)
|
502 |
+
return -1;
|
503 |
+
}
|
504 |
+
if (v == NULL) {
|
505 |
+
int rv = PyDict_DelItemString(fp->dict, name);
|
506 |
+
if (rv < 0)
|
507 |
+
PyErr_SetString(PyExc_AttributeError,
|
508 |
+
"delete non-existing fortran attribute");
|
509 |
+
return rv;
|
510 |
+
}
|
511 |
+
else
|
512 |
+
return PyDict_SetItemString(fp->dict, name, v);
|
513 |
+
}
|
514 |
+
|
515 |
+
static PyObject *
|
516 |
+
fortran_call(PyFortranObject *fp, PyObject *arg, PyObject *kw)
|
517 |
+
{
|
518 |
+
int i = 0;
|
519 |
+
/* printf("fortran call
|
520 |
+
name=%s,func=%p,data=%p,%p\n",fp->defs[i].name,
|
521 |
+
fp->defs[i].func,fp->defs[i].data,&fp->defs[i].data); */
|
522 |
+
if (fp->defs[i].rank == -1) { /* is Fortran routine */
|
523 |
+
if (fp->defs[i].func == NULL) {
|
524 |
+
PyErr_Format(PyExc_RuntimeError, "no function to call");
|
525 |
+
return NULL;
|
526 |
+
}
|
527 |
+
else if (fp->defs[i].data == NULL)
|
528 |
+
/* dummy routine */
|
529 |
+
return (*((fortranfunc)(fp->defs[i].func)))((PyObject *)fp, arg,
|
530 |
+
kw, NULL);
|
531 |
+
else
|
532 |
+
return (*((fortranfunc)(fp->defs[i].func)))(
|
533 |
+
(PyObject *)fp, arg, kw, (void *)fp->defs[i].data);
|
534 |
+
}
|
535 |
+
PyErr_Format(PyExc_TypeError, "this fortran object is not callable");
|
536 |
+
return NULL;
|
537 |
+
}
|
538 |
+
|
539 |
+
static PyObject *
|
540 |
+
fortran_repr(PyFortranObject *fp)
|
541 |
+
{
|
542 |
+
PyObject *name = NULL, *repr = NULL;
|
543 |
+
name = PyObject_GetAttrString((PyObject *)fp, "__name__");
|
544 |
+
PyErr_Clear();
|
545 |
+
if (name != NULL && PyUnicode_Check(name)) {
|
546 |
+
repr = PyUnicode_FromFormat("<fortran %U>", name);
|
547 |
+
}
|
548 |
+
else {
|
549 |
+
repr = PyUnicode_FromString("<fortran object>");
|
550 |
+
}
|
551 |
+
Py_XDECREF(name);
|
552 |
+
return repr;
|
553 |
+
}
|
554 |
+
|
555 |
+
PyTypeObject PyFortran_Type = {
|
556 |
+
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fortran",
|
557 |
+
.tp_basicsize = sizeof(PyFortranObject),
|
558 |
+
.tp_dealloc = (destructor)fortran_dealloc,
|
559 |
+
.tp_getattr = (getattrfunc)fortran_getattr,
|
560 |
+
.tp_setattr = (setattrfunc)fortran_setattr,
|
561 |
+
.tp_repr = (reprfunc)fortran_repr,
|
562 |
+
.tp_call = (ternaryfunc)fortran_call,
|
563 |
+
};
|
564 |
+
|
565 |
+
/************************* f2py_report_atexit *******************************/
|
566 |
+
|
567 |
+
#ifdef F2PY_REPORT_ATEXIT
|
568 |
+
static int passed_time = 0;
|
569 |
+
static int passed_counter = 0;
|
570 |
+
static int passed_call_time = 0;
|
571 |
+
static struct timeb start_time;
|
572 |
+
static struct timeb stop_time;
|
573 |
+
static struct timeb start_call_time;
|
574 |
+
static struct timeb stop_call_time;
|
575 |
+
static int cb_passed_time = 0;
|
576 |
+
static int cb_passed_counter = 0;
|
577 |
+
static int cb_passed_call_time = 0;
|
578 |
+
static struct timeb cb_start_time;
|
579 |
+
static struct timeb cb_stop_time;
|
580 |
+
static struct timeb cb_start_call_time;
|
581 |
+
static struct timeb cb_stop_call_time;
|
582 |
+
|
583 |
+
extern void
|
584 |
+
f2py_start_clock(void)
|
585 |
+
{
|
586 |
+
ftime(&start_time);
|
587 |
+
}
|
588 |
+
extern void
|
589 |
+
f2py_start_call_clock(void)
|
590 |
+
{
|
591 |
+
f2py_stop_clock();
|
592 |
+
ftime(&start_call_time);
|
593 |
+
}
|
594 |
+
extern void
|
595 |
+
f2py_stop_clock(void)
|
596 |
+
{
|
597 |
+
ftime(&stop_time);
|
598 |
+
passed_time += 1000 * (stop_time.time - start_time.time);
|
599 |
+
passed_time += stop_time.millitm - start_time.millitm;
|
600 |
+
}
|
601 |
+
extern void
|
602 |
+
f2py_stop_call_clock(void)
|
603 |
+
{
|
604 |
+
ftime(&stop_call_time);
|
605 |
+
passed_call_time += 1000 * (stop_call_time.time - start_call_time.time);
|
606 |
+
passed_call_time += stop_call_time.millitm - start_call_time.millitm;
|
607 |
+
passed_counter += 1;
|
608 |
+
f2py_start_clock();
|
609 |
+
}
|
610 |
+
|
611 |
+
extern void
|
612 |
+
f2py_cb_start_clock(void)
|
613 |
+
{
|
614 |
+
ftime(&cb_start_time);
|
615 |
+
}
|
616 |
+
extern void
|
617 |
+
f2py_cb_start_call_clock(void)
|
618 |
+
{
|
619 |
+
f2py_cb_stop_clock();
|
620 |
+
ftime(&cb_start_call_time);
|
621 |
+
}
|
622 |
+
extern void
|
623 |
+
f2py_cb_stop_clock(void)
|
624 |
+
{
|
625 |
+
ftime(&cb_stop_time);
|
626 |
+
cb_passed_time += 1000 * (cb_stop_time.time - cb_start_time.time);
|
627 |
+
cb_passed_time += cb_stop_time.millitm - cb_start_time.millitm;
|
628 |
+
}
|
629 |
+
extern void
|
630 |
+
f2py_cb_stop_call_clock(void)
|
631 |
+
{
|
632 |
+
ftime(&cb_stop_call_time);
|
633 |
+
cb_passed_call_time +=
|
634 |
+
1000 * (cb_stop_call_time.time - cb_start_call_time.time);
|
635 |
+
cb_passed_call_time +=
|
636 |
+
cb_stop_call_time.millitm - cb_start_call_time.millitm;
|
637 |
+
cb_passed_counter += 1;
|
638 |
+
f2py_cb_start_clock();
|
639 |
+
}
|
640 |
+
|
641 |
+
static int f2py_report_on_exit_been_here = 0;
|
642 |
+
extern void
|
643 |
+
f2py_report_on_exit(int exit_flag, void *name)
|
644 |
+
{
|
645 |
+
if (f2py_report_on_exit_been_here) {
|
646 |
+
fprintf(stderr, " %s\n", (char *)name);
|
647 |
+
return;
|
648 |
+
}
|
649 |
+
f2py_report_on_exit_been_here = 1;
|
650 |
+
fprintf(stderr, " /-----------------------\\\n");
|
651 |
+
fprintf(stderr, " < F2PY performance report >\n");
|
652 |
+
fprintf(stderr, " \\-----------------------/\n");
|
653 |
+
fprintf(stderr, "Overall time spent in ...\n");
|
654 |
+
fprintf(stderr, "(a) wrapped (Fortran/C) functions : %8d msec\n",
|
655 |
+
passed_call_time);
|
656 |
+
fprintf(stderr, "(b) f2py interface, %6d calls : %8d msec\n",
|
657 |
+
passed_counter, passed_time);
|
658 |
+
fprintf(stderr, "(c) call-back (Python) functions : %8d msec\n",
|
659 |
+
cb_passed_call_time);
|
660 |
+
fprintf(stderr, "(d) f2py call-back interface, %6d calls : %8d msec\n",
|
661 |
+
cb_passed_counter, cb_passed_time);
|
662 |
+
|
663 |
+
fprintf(stderr,
|
664 |
+
"(e) wrapped (Fortran/C) functions (actual) : %8d msec\n\n",
|
665 |
+
passed_call_time - cb_passed_call_time - cb_passed_time);
|
666 |
+
fprintf(stderr,
|
667 |
+
"Use -DF2PY_REPORT_ATEXIT_DISABLE to disable this message.\n");
|
668 |
+
fprintf(stderr, "Exit status: %d\n", exit_flag);
|
669 |
+
fprintf(stderr, "Modules : %s\n", (char *)name);
|
670 |
+
}
|
671 |
+
#endif
|
672 |
+
|
673 |
+
/********************** report on array copy ****************************/
|
674 |
+
|
675 |
+
#ifdef F2PY_REPORT_ON_ARRAY_COPY
|
676 |
+
static void
|
677 |
+
f2py_report_on_array_copy(PyArrayObject *arr)
|
678 |
+
{
|
679 |
+
const npy_intp arr_size = PyArray_Size((PyObject *)arr);
|
680 |
+
if (arr_size > F2PY_REPORT_ON_ARRAY_COPY) {
|
681 |
+
fprintf(stderr,
|
682 |
+
"copied an array: size=%ld, elsize=%" NPY_INTP_FMT "\n",
|
683 |
+
arr_size, (npy_intp)PyArray_ITEMSIZE(arr));
|
684 |
+
}
|
685 |
+
}
|
686 |
+
static void
|
687 |
+
f2py_report_on_array_copy_fromany(void)
|
688 |
+
{
|
689 |
+
fprintf(stderr, "created an array from object\n");
|
690 |
+
}
|
691 |
+
|
692 |
+
#define F2PY_REPORT_ON_ARRAY_COPY_FROMARR \
|
693 |
+
f2py_report_on_array_copy((PyArrayObject *)arr)
|
694 |
+
#define F2PY_REPORT_ON_ARRAY_COPY_FROMANY f2py_report_on_array_copy_fromany()
|
695 |
+
#else
|
696 |
+
#define F2PY_REPORT_ON_ARRAY_COPY_FROMARR
|
697 |
+
#define F2PY_REPORT_ON_ARRAY_COPY_FROMANY
|
698 |
+
#endif
|
699 |
+
|
700 |
+
/************************* array_from_obj *******************************/
|
701 |
+
|
702 |
+
/*
|
703 |
+
* File: array_from_pyobj.c
|
704 |
+
*
|
705 |
+
* Description:
|
706 |
+
* ------------
|
707 |
+
* Provides array_from_pyobj function that returns a contiguous array
|
708 |
+
* object with the given dimensions and required storage order, either
|
709 |
+
* in row-major (C) or column-major (Fortran) order. The function
|
710 |
+
* array_from_pyobj is very flexible about its Python object argument
|
711 |
+
* that can be any number, list, tuple, or array.
|
712 |
+
*
|
713 |
+
* array_from_pyobj is used in f2py generated Python extension
|
714 |
+
* modules.
|
715 |
+
*
|
716 |
+
* Author: Pearu Peterson <[email protected]>
|
717 |
+
* Created: 13-16 January 2002
|
718 |
+
* $Id: fortranobject.c,v 1.52 2005/07/11 07:44:20 pearu Exp $
|
719 |
+
*/
|
720 |
+
|
721 |
+
static int check_and_fix_dimensions(const PyArrayObject* arr,
|
722 |
+
const int rank,
|
723 |
+
npy_intp *dims,
|
724 |
+
const char *errmess);
|
725 |
+
|
726 |
+
static int
|
727 |
+
find_first_negative_dimension(const int rank, const npy_intp *dims)
|
728 |
+
{
|
729 |
+
int i;
|
730 |
+
for (i = 0; i < rank; ++i) {
|
731 |
+
if (dims[i] < 0) {
|
732 |
+
return i;
|
733 |
+
}
|
734 |
+
}
|
735 |
+
return -1;
|
736 |
+
}
|
737 |
+
|
738 |
+
#ifdef DEBUG_COPY_ND_ARRAY
|
739 |
+
void
|
740 |
+
dump_dims(int rank, npy_intp const *dims)
|
741 |
+
{
|
742 |
+
int i;
|
743 |
+
printf("[");
|
744 |
+
for (i = 0; i < rank; ++i) {
|
745 |
+
printf("%3" NPY_INTP_FMT, dims[i]);
|
746 |
+
}
|
747 |
+
printf("]\n");
|
748 |
+
}
|
749 |
+
void
|
750 |
+
dump_attrs(const PyArrayObject *obj)
|
751 |
+
{
|
752 |
+
const PyArrayObject_fields *arr = (const PyArrayObject_fields *)obj;
|
753 |
+
int rank = PyArray_NDIM(arr);
|
754 |
+
npy_intp size = PyArray_Size((PyObject *)arr);
|
755 |
+
printf("\trank = %d, flags = %d, size = %" NPY_INTP_FMT "\n", rank,
|
756 |
+
arr->flags, size);
|
757 |
+
printf("\tstrides = ");
|
758 |
+
dump_dims(rank, arr->strides);
|
759 |
+
printf("\tdimensions = ");
|
760 |
+
dump_dims(rank, arr->dimensions);
|
761 |
+
}
|
762 |
+
#endif
|
763 |
+
|
764 |
+
#define SWAPTYPE(a, b, t) \
|
765 |
+
{ \
|
766 |
+
t c; \
|
767 |
+
c = (a); \
|
768 |
+
(a) = (b); \
|
769 |
+
(b) = c; \
|
770 |
+
}
|
771 |
+
|
772 |
+
static int
|
773 |
+
swap_arrays(PyArrayObject *obj1, PyArrayObject *obj2)
|
774 |
+
{
|
775 |
+
PyArrayObject_fields *arr1 = (PyArrayObject_fields *)obj1,
|
776 |
+
*arr2 = (PyArrayObject_fields *)obj2;
|
777 |
+
SWAPTYPE(arr1->data, arr2->data, char *);
|
778 |
+
SWAPTYPE(arr1->nd, arr2->nd, int);
|
779 |
+
SWAPTYPE(arr1->dimensions, arr2->dimensions, npy_intp *);
|
780 |
+
SWAPTYPE(arr1->strides, arr2->strides, npy_intp *);
|
781 |
+
SWAPTYPE(arr1->base, arr2->base, PyObject *);
|
782 |
+
SWAPTYPE(arr1->descr, arr2->descr, PyArray_Descr *);
|
783 |
+
SWAPTYPE(arr1->flags, arr2->flags, int);
|
784 |
+
/* SWAPTYPE(arr1->weakreflist,arr2->weakreflist,PyObject*); */
|
785 |
+
return 0;
|
786 |
+
}
|
787 |
+
|
788 |
+
#define ARRAY_ISCOMPATIBLE(arr,type_num) \
|
789 |
+
((PyArray_ISINTEGER(arr) && PyTypeNum_ISINTEGER(type_num)) || \
|
790 |
+
(PyArray_ISFLOAT(arr) && PyTypeNum_ISFLOAT(type_num)) || \
|
791 |
+
(PyArray_ISCOMPLEX(arr) && PyTypeNum_ISCOMPLEX(type_num)) || \
|
792 |
+
(PyArray_ISBOOL(arr) && PyTypeNum_ISBOOL(type_num)) || \
|
793 |
+
(PyArray_ISSTRING(arr) && PyTypeNum_ISSTRING(type_num)))
|
794 |
+
|
795 |
+
static int
|
796 |
+
get_elsize(PyObject *obj) {
|
797 |
+
/*
|
798 |
+
get_elsize determines array itemsize from a Python object. Returns
|
799 |
+
elsize if successful, -1 otherwise.
|
800 |
+
|
801 |
+
Supported types of the input are: numpy.ndarray, bytes, str, tuple,
|
802 |
+
list.
|
803 |
+
*/
|
804 |
+
|
805 |
+
if (PyArray_Check(obj)) {
|
806 |
+
return PyArray_DESCR((PyArrayObject *)obj)->elsize;
|
807 |
+
} else if (PyBytes_Check(obj)) {
|
808 |
+
return PyBytes_GET_SIZE(obj);
|
809 |
+
} else if (PyUnicode_Check(obj)) {
|
810 |
+
return PyUnicode_GET_LENGTH(obj);
|
811 |
+
} else if (PySequence_Check(obj)) {
|
812 |
+
PyObject* fast = PySequence_Fast(obj, "f2py:fortranobject.c:get_elsize");
|
813 |
+
if (fast != NULL) {
|
814 |
+
Py_ssize_t i, n = PySequence_Fast_GET_SIZE(fast);
|
815 |
+
int sz, elsize = 0;
|
816 |
+
for (i=0; i<n; i++) {
|
817 |
+
sz = get_elsize(PySequence_Fast_GET_ITEM(fast, i) /* borrowed */);
|
818 |
+
if (sz > elsize) {
|
819 |
+
elsize = sz;
|
820 |
+
}
|
821 |
+
}
|
822 |
+
Py_DECREF(fast);
|
823 |
+
return elsize;
|
824 |
+
}
|
825 |
+
}
|
826 |
+
return -1;
|
827 |
+
}
|
828 |
+
|
829 |
+
extern PyArrayObject *
|
830 |
+
ndarray_from_pyobj(const int type_num,
|
831 |
+
const int elsize_,
|
832 |
+
npy_intp *dims,
|
833 |
+
const int rank,
|
834 |
+
const int intent,
|
835 |
+
PyObject *obj,
|
836 |
+
const char *errmess) {
|
837 |
+
/*
|
838 |
+
* Return an array with given element type and shape from a Python
|
839 |
+
* object while taking into account the usage intent of the array.
|
840 |
+
*
|
841 |
+
* - element type is defined by type_num and elsize
|
842 |
+
* - shape is defined by dims and rank
|
843 |
+
*
|
844 |
+
* ndarray_from_pyobj is used to convert Python object arguments
|
845 |
+
* to numpy ndarrays with given type and shape that data is passed
|
846 |
+
* to interfaced Fortran or C functions.
|
847 |
+
*
|
848 |
+
* errmess (if not NULL), contains a prefix of an error message
|
849 |
+
* for an exception to be triggered within this function.
|
850 |
+
*
|
851 |
+
* Negative elsize value means that elsize is to be determined
|
852 |
+
* from the Python object in runtime.
|
853 |
+
*
|
854 |
+
* Note on strings
|
855 |
+
* ---------------
|
856 |
+
*
|
857 |
+
* String type (type_num == NPY_STRING) does not have fixed
|
858 |
+
* element size and, by default, the type object sets it to
|
859 |
+
* 0. Therefore, for string types, one has to use elsize
|
860 |
+
* argument. For other types, elsize value is ignored.
|
861 |
+
*
|
862 |
+
* NumPy defines the type of a fixed-width string as
|
863 |
+
* dtype('S<width>'). In addition, there is also dtype('c'), that
|
864 |
+
* appears as dtype('S1') (these have the same type_num value),
|
865 |
+
* but is actually different (.char attribute is either 'S' or
|
866 |
+
* 'c', respecitely).
|
867 |
+
*
|
868 |
+
* In Fortran, character arrays and strings are different
|
869 |
+
* concepts. The relation between Fortran types, NumPy dtypes,
|
870 |
+
* and type_num-elsize pairs, is defined as follows:
|
871 |
+
*
|
872 |
+
* character*5 foo | dtype('S5') | elsize=5, shape=()
|
873 |
+
* character(5) foo | dtype('S1') | elsize=1, shape=(5)
|
874 |
+
* character*5 foo(n) | dtype('S5') | elsize=5, shape=(n,)
|
875 |
+
* character(5) foo(n) | dtype('S1') | elsize=1, shape=(5, n)
|
876 |
+
* character*(*) foo | dtype('S') | elsize=-1, shape=()
|
877 |
+
*
|
878 |
+
* Note about reference counting
|
879 |
+
* -----------------------------
|
880 |
+
*
|
881 |
+
* If the caller returns the array to Python, it must be done with
|
882 |
+
* Py_BuildValue("N",arr). Otherwise, if obj!=arr then the caller
|
883 |
+
* must call Py_DECREF(arr).
|
884 |
+
*
|
885 |
+
* Note on intent(cache,out,..)
|
886 |
+
* ----------------------------
|
887 |
+
* Don't expect correct data when returning intent(cache) array.
|
888 |
+
*
|
889 |
+
*/
|
890 |
+
char mess[F2PY_MESSAGE_BUFFER_SIZE];
|
891 |
+
PyArrayObject *arr = NULL;
|
892 |
+
int elsize = (elsize_ < 0 ? get_elsize(obj) : elsize_);
|
893 |
+
if (elsize < 0) {
|
894 |
+
if (errmess != NULL) {
|
895 |
+
strcpy(mess, errmess);
|
896 |
+
}
|
897 |
+
sprintf(mess + strlen(mess),
|
898 |
+
" -- failed to determine element size from %s",
|
899 |
+
Py_TYPE(obj)->tp_name);
|
900 |
+
PyErr_SetString(PyExc_SystemError, mess);
|
901 |
+
return NULL;
|
902 |
+
}
|
903 |
+
PyArray_Descr * descr = get_descr_from_type_and_elsize(type_num, elsize); // new reference
|
904 |
+
if (descr == NULL) {
|
905 |
+
return NULL;
|
906 |
+
}
|
907 |
+
elsize = descr->elsize;
|
908 |
+
if ((intent & F2PY_INTENT_HIDE)
|
909 |
+
|| ((intent & F2PY_INTENT_CACHE) && (obj == Py_None))
|
910 |
+
|| ((intent & F2PY_OPTIONAL) && (obj == Py_None))
|
911 |
+
) {
|
912 |
+
/* intent(cache), optional, intent(hide) */
|
913 |
+
int ineg = find_first_negative_dimension(rank, dims);
|
914 |
+
if (ineg >= 0) {
|
915 |
+
int i;
|
916 |
+
strcpy(mess, "failed to create intent(cache|hide)|optional array"
|
917 |
+
"-- must have defined dimensions but got (");
|
918 |
+
for(i = 0; i < rank; ++i)
|
919 |
+
sprintf(mess + strlen(mess), "%" NPY_INTP_FMT ",", dims[i]);
|
920 |
+
strcat(mess, ")");
|
921 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
922 |
+
Py_DECREF(descr);
|
923 |
+
return NULL;
|
924 |
+
}
|
925 |
+
arr = (PyArrayObject *) \
|
926 |
+
PyArray_NewFromDescr(&PyArray_Type, descr, rank, dims,
|
927 |
+
NULL, NULL, !(intent & F2PY_INTENT_C), NULL);
|
928 |
+
if (arr == NULL) {
|
929 |
+
Py_DECREF(descr);
|
930 |
+
return NULL;
|
931 |
+
}
|
932 |
+
if (PyArray_ITEMSIZE(arr) != elsize) {
|
933 |
+
strcpy(mess, "failed to create intent(cache|hide)|optional array");
|
934 |
+
sprintf(mess+strlen(mess)," -- expected elsize=%d got %" NPY_INTP_FMT, elsize, (npy_intp)PyArray_ITEMSIZE(arr));
|
935 |
+
PyErr_SetString(PyExc_ValueError,mess);
|
936 |
+
Py_DECREF(arr);
|
937 |
+
return NULL;
|
938 |
+
}
|
939 |
+
if (!(intent & F2PY_INTENT_CACHE)) {
|
940 |
+
PyArray_FILLWBYTE(arr, 0);
|
941 |
+
}
|
942 |
+
return arr;
|
943 |
+
}
|
944 |
+
|
945 |
+
if (PyArray_Check(obj)) {
|
946 |
+
arr = (PyArrayObject *)obj;
|
947 |
+
if (intent & F2PY_INTENT_CACHE) {
|
948 |
+
/* intent(cache) */
|
949 |
+
if (PyArray_ISONESEGMENT(arr)
|
950 |
+
&& PyArray_ITEMSIZE(arr) >= elsize) {
|
951 |
+
if (check_and_fix_dimensions(arr, rank, dims, errmess)) {
|
952 |
+
Py_DECREF(descr);
|
953 |
+
return NULL;
|
954 |
+
}
|
955 |
+
if (intent & F2PY_INTENT_OUT)
|
956 |
+
Py_INCREF(arr);
|
957 |
+
Py_DECREF(descr);
|
958 |
+
return arr;
|
959 |
+
}
|
960 |
+
strcpy(mess, "failed to initialize intent(cache) array");
|
961 |
+
if (!PyArray_ISONESEGMENT(arr))
|
962 |
+
strcat(mess, " -- input must be in one segment");
|
963 |
+
if (PyArray_ITEMSIZE(arr) < elsize)
|
964 |
+
sprintf(mess + strlen(mess),
|
965 |
+
" -- expected at least elsize=%d but got "
|
966 |
+
"%" NPY_INTP_FMT,
|
967 |
+
elsize, (npy_intp)PyArray_ITEMSIZE(arr));
|
968 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
969 |
+
Py_DECREF(descr);
|
970 |
+
return NULL;
|
971 |
+
}
|
972 |
+
|
973 |
+
/* here we have always intent(in) or intent(inout) or intent(inplace)
|
974 |
+
*/
|
975 |
+
|
976 |
+
if (check_and_fix_dimensions(arr, rank, dims, errmess)) {
|
977 |
+
Py_DECREF(descr);
|
978 |
+
return NULL;
|
979 |
+
}
|
980 |
+
/*
|
981 |
+
printf("intent alignment=%d\n", F2PY_GET_ALIGNMENT(intent));
|
982 |
+
printf("alignment check=%d\n", F2PY_CHECK_ALIGNMENT(arr, intent));
|
983 |
+
int i;
|
984 |
+
for (i=1;i<=16;i++)
|
985 |
+
printf("i=%d isaligned=%d\n", i, ARRAY_ISALIGNED(arr, i));
|
986 |
+
*/
|
987 |
+
if ((! (intent & F2PY_INTENT_COPY)) &&
|
988 |
+
PyArray_ITEMSIZE(arr) == elsize &&
|
989 |
+
ARRAY_ISCOMPATIBLE(arr,type_num) &&
|
990 |
+
F2PY_CHECK_ALIGNMENT(arr, intent)) {
|
991 |
+
if ((intent & F2PY_INTENT_INOUT || intent & F2PY_INTENT_INPLACE)
|
992 |
+
? ((intent & F2PY_INTENT_C) ? PyArray_ISCARRAY(arr) : PyArray_ISFARRAY(arr))
|
993 |
+
: ((intent & F2PY_INTENT_C) ? PyArray_ISCARRAY_RO(arr) : PyArray_ISFARRAY_RO(arr))) {
|
994 |
+
if ((intent & F2PY_INTENT_OUT)) {
|
995 |
+
Py_INCREF(arr);
|
996 |
+
}
|
997 |
+
/* Returning input array */
|
998 |
+
Py_DECREF(descr);
|
999 |
+
return arr;
|
1000 |
+
}
|
1001 |
+
}
|
1002 |
+
if (intent & F2PY_INTENT_INOUT) {
|
1003 |
+
strcpy(mess, "failed to initialize intent(inout) array");
|
1004 |
+
/* Must use PyArray_IS*ARRAY because intent(inout) requires
|
1005 |
+
* writable input */
|
1006 |
+
if ((intent & F2PY_INTENT_C) && !PyArray_ISCARRAY(arr))
|
1007 |
+
strcat(mess, " -- input not contiguous");
|
1008 |
+
if (!(intent & F2PY_INTENT_C) && !PyArray_ISFARRAY(arr))
|
1009 |
+
strcat(mess, " -- input not fortran contiguous");
|
1010 |
+
if (PyArray_ITEMSIZE(arr) != elsize)
|
1011 |
+
sprintf(mess + strlen(mess),
|
1012 |
+
" -- expected elsize=%d but got %" NPY_INTP_FMT,
|
1013 |
+
elsize,
|
1014 |
+
(npy_intp)PyArray_ITEMSIZE(arr)
|
1015 |
+
);
|
1016 |
+
if (!(ARRAY_ISCOMPATIBLE(arr, type_num))) {
|
1017 |
+
sprintf(mess + strlen(mess),
|
1018 |
+
" -- input '%c' not compatible to '%c'",
|
1019 |
+
PyArray_DESCR(arr)->type, descr->type);
|
1020 |
+
}
|
1021 |
+
if (!(F2PY_CHECK_ALIGNMENT(arr, intent)))
|
1022 |
+
sprintf(mess + strlen(mess), " -- input not %d-aligned",
|
1023 |
+
F2PY_GET_ALIGNMENT(intent));
|
1024 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
1025 |
+
Py_DECREF(descr);
|
1026 |
+
return NULL;
|
1027 |
+
}
|
1028 |
+
|
1029 |
+
/* here we have always intent(in) or intent(inplace) */
|
1030 |
+
|
1031 |
+
{
|
1032 |
+
PyArrayObject * retarr = (PyArrayObject *) \
|
1033 |
+
PyArray_NewFromDescr(&PyArray_Type, descr, PyArray_NDIM(arr), PyArray_DIMS(arr),
|
1034 |
+
NULL, NULL, !(intent & F2PY_INTENT_C), NULL);
|
1035 |
+
if (retarr==NULL) {
|
1036 |
+
Py_DECREF(descr);
|
1037 |
+
return NULL;
|
1038 |
+
}
|
1039 |
+
F2PY_REPORT_ON_ARRAY_COPY_FROMARR;
|
1040 |
+
if (PyArray_CopyInto(retarr, arr)) {
|
1041 |
+
Py_DECREF(retarr);
|
1042 |
+
return NULL;
|
1043 |
+
}
|
1044 |
+
if (intent & F2PY_INTENT_INPLACE) {
|
1045 |
+
if (swap_arrays(arr,retarr)) {
|
1046 |
+
Py_DECREF(retarr);
|
1047 |
+
return NULL; /* XXX: set exception */
|
1048 |
+
}
|
1049 |
+
Py_XDECREF(retarr);
|
1050 |
+
if (intent & F2PY_INTENT_OUT)
|
1051 |
+
Py_INCREF(arr);
|
1052 |
+
} else {
|
1053 |
+
arr = retarr;
|
1054 |
+
}
|
1055 |
+
}
|
1056 |
+
return arr;
|
1057 |
+
}
|
1058 |
+
|
1059 |
+
if ((intent & F2PY_INTENT_INOUT) || (intent & F2PY_INTENT_INPLACE) ||
|
1060 |
+
(intent & F2PY_INTENT_CACHE)) {
|
1061 |
+
PyErr_Format(PyExc_TypeError,
|
1062 |
+
"failed to initialize intent(inout|inplace|cache) "
|
1063 |
+
"array, input '%s' object is not an array",
|
1064 |
+
Py_TYPE(obj)->tp_name);
|
1065 |
+
Py_DECREF(descr);
|
1066 |
+
return NULL;
|
1067 |
+
}
|
1068 |
+
|
1069 |
+
{
|
1070 |
+
F2PY_REPORT_ON_ARRAY_COPY_FROMANY;
|
1071 |
+
arr = (PyArrayObject *)PyArray_FromAny(
|
1072 |
+
obj, descr, 0, 0,
|
1073 |
+
((intent & F2PY_INTENT_C) ? NPY_ARRAY_CARRAY
|
1074 |
+
: NPY_ARRAY_FARRAY) |
|
1075 |
+
NPY_ARRAY_FORCECAST,
|
1076 |
+
NULL);
|
1077 |
+
// Warning: in the case of NPY_STRING, PyArray_FromAny may
|
1078 |
+
// reset descr->elsize, e.g. dtype('S0') becomes dtype('S1').
|
1079 |
+
if (arr == NULL) {
|
1080 |
+
Py_DECREF(descr);
|
1081 |
+
return NULL;
|
1082 |
+
}
|
1083 |
+
if (type_num != NPY_STRING && PyArray_ITEMSIZE(arr) != elsize) {
|
1084 |
+
// This is internal sanity tests: elsize has been set to
|
1085 |
+
// descr->elsize in the beginning of this function.
|
1086 |
+
strcpy(mess, "failed to initialize intent(in) array");
|
1087 |
+
sprintf(mess + strlen(mess),
|
1088 |
+
" -- expected elsize=%d got %" NPY_INTP_FMT, elsize,
|
1089 |
+
(npy_intp)PyArray_ITEMSIZE(arr));
|
1090 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
1091 |
+
Py_DECREF(arr);
|
1092 |
+
return NULL;
|
1093 |
+
}
|
1094 |
+
if (check_and_fix_dimensions(arr, rank, dims, errmess)) {
|
1095 |
+
Py_DECREF(arr);
|
1096 |
+
return NULL;
|
1097 |
+
}
|
1098 |
+
return arr;
|
1099 |
+
}
|
1100 |
+
}
|
1101 |
+
|
1102 |
+
extern PyArrayObject *
|
1103 |
+
array_from_pyobj(const int type_num,
|
1104 |
+
npy_intp *dims,
|
1105 |
+
const int rank,
|
1106 |
+
const int intent,
|
1107 |
+
PyObject *obj) {
|
1108 |
+
/*
|
1109 |
+
Same as ndarray_from_pyobj but with elsize determined from type,
|
1110 |
+
if possible. Provided for backward compatibility.
|
1111 |
+
*/
|
1112 |
+
PyArray_Descr* descr = PyArray_DescrFromType(type_num);
|
1113 |
+
int elsize = descr->elsize;
|
1114 |
+
Py_DECREF(descr);
|
1115 |
+
return ndarray_from_pyobj(type_num, elsize, dims, rank, intent, obj, NULL);
|
1116 |
+
}
|
1117 |
+
|
1118 |
+
/*****************************************/
|
1119 |
+
/* Helper functions for array_from_pyobj */
|
1120 |
+
/*****************************************/
|
1121 |
+
|
1122 |
+
static int
|
1123 |
+
check_and_fix_dimensions(const PyArrayObject* arr, const int rank,
|
1124 |
+
npy_intp *dims, const char *errmess)
|
1125 |
+
{
|
1126 |
+
/*
|
1127 |
+
* This function fills in blanks (that are -1's) in dims list using
|
1128 |
+
* the dimensions from arr. It also checks that non-blank dims will
|
1129 |
+
* match with the corresponding values in arr dimensions.
|
1130 |
+
*
|
1131 |
+
* Returns 0 if the function is successful.
|
1132 |
+
*
|
1133 |
+
* If an error condition is detected, an exception is set and 1 is
|
1134 |
+
* returned.
|
1135 |
+
*/
|
1136 |
+
char mess[F2PY_MESSAGE_BUFFER_SIZE];
|
1137 |
+
const npy_intp arr_size =
|
1138 |
+
(PyArray_NDIM(arr)) ? PyArray_Size((PyObject *)arr) : 1;
|
1139 |
+
#ifdef DEBUG_COPY_ND_ARRAY
|
1140 |
+
dump_attrs(arr);
|
1141 |
+
printf("check_and_fix_dimensions:init: dims=");
|
1142 |
+
dump_dims(rank, dims);
|
1143 |
+
#endif
|
1144 |
+
if (rank > PyArray_NDIM(arr)) { /* [1,2] -> [[1],[2]]; 1 -> [[1]] */
|
1145 |
+
npy_intp new_size = 1;
|
1146 |
+
int free_axe = -1;
|
1147 |
+
int i;
|
1148 |
+
npy_intp d;
|
1149 |
+
/* Fill dims where -1 or 0; check dimensions; calc new_size; */
|
1150 |
+
for (i = 0; i < PyArray_NDIM(arr); ++i) {
|
1151 |
+
d = PyArray_DIM(arr, i);
|
1152 |
+
if (dims[i] >= 0) {
|
1153 |
+
if (d > 1 && dims[i] != d) {
|
1154 |
+
PyErr_Format(
|
1155 |
+
PyExc_ValueError,
|
1156 |
+
"%d-th dimension must be fixed to %" NPY_INTP_FMT
|
1157 |
+
" but got %" NPY_INTP_FMT "\n",
|
1158 |
+
i, dims[i], d);
|
1159 |
+
return 1;
|
1160 |
+
}
|
1161 |
+
if (!dims[i])
|
1162 |
+
dims[i] = 1;
|
1163 |
+
}
|
1164 |
+
else {
|
1165 |
+
dims[i] = d ? d : 1;
|
1166 |
+
}
|
1167 |
+
new_size *= dims[i];
|
1168 |
+
}
|
1169 |
+
for (i = PyArray_NDIM(arr); i < rank; ++i)
|
1170 |
+
if (dims[i] > 1) {
|
1171 |
+
PyErr_Format(PyExc_ValueError,
|
1172 |
+
"%d-th dimension must be %" NPY_INTP_FMT
|
1173 |
+
" but got 0 (not defined).\n",
|
1174 |
+
i, dims[i]);
|
1175 |
+
return 1;
|
1176 |
+
}
|
1177 |
+
else if (free_axe < 0)
|
1178 |
+
free_axe = i;
|
1179 |
+
else
|
1180 |
+
dims[i] = 1;
|
1181 |
+
if (free_axe >= 0) {
|
1182 |
+
dims[free_axe] = arr_size / new_size;
|
1183 |
+
new_size *= dims[free_axe];
|
1184 |
+
}
|
1185 |
+
if (new_size != arr_size) {
|
1186 |
+
PyErr_Format(PyExc_ValueError,
|
1187 |
+
"unexpected array size: new_size=%" NPY_INTP_FMT
|
1188 |
+
", got array with arr_size=%" NPY_INTP_FMT
|
1189 |
+
" (maybe too many free indices)\n",
|
1190 |
+
new_size, arr_size);
|
1191 |
+
return 1;
|
1192 |
+
}
|
1193 |
+
}
|
1194 |
+
else if (rank == PyArray_NDIM(arr)) {
|
1195 |
+
npy_intp new_size = 1;
|
1196 |
+
int i;
|
1197 |
+
npy_intp d;
|
1198 |
+
for (i = 0; i < rank; ++i) {
|
1199 |
+
d = PyArray_DIM(arr, i);
|
1200 |
+
if (dims[i] >= 0) {
|
1201 |
+
if (d > 1 && d != dims[i]) {
|
1202 |
+
if (errmess != NULL) {
|
1203 |
+
strcpy(mess, errmess);
|
1204 |
+
}
|
1205 |
+
sprintf(mess + strlen(mess),
|
1206 |
+
" -- %d-th dimension must be fixed to %"
|
1207 |
+
NPY_INTP_FMT " but got %" NPY_INTP_FMT,
|
1208 |
+
i, dims[i], d);
|
1209 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
1210 |
+
return 1;
|
1211 |
+
}
|
1212 |
+
if (!dims[i])
|
1213 |
+
dims[i] = 1;
|
1214 |
+
}
|
1215 |
+
else
|
1216 |
+
dims[i] = d;
|
1217 |
+
new_size *= dims[i];
|
1218 |
+
}
|
1219 |
+
if (new_size != arr_size) {
|
1220 |
+
PyErr_Format(PyExc_ValueError,
|
1221 |
+
"unexpected array size: new_size=%" NPY_INTP_FMT
|
1222 |
+
", got array with arr_size=%" NPY_INTP_FMT "\n",
|
1223 |
+
new_size, arr_size);
|
1224 |
+
return 1;
|
1225 |
+
}
|
1226 |
+
}
|
1227 |
+
else { /* [[1,2]] -> [[1],[2]] */
|
1228 |
+
int i, j;
|
1229 |
+
npy_intp d;
|
1230 |
+
int effrank;
|
1231 |
+
npy_intp size;
|
1232 |
+
for (i = 0, effrank = 0; i < PyArray_NDIM(arr); ++i)
|
1233 |
+
if (PyArray_DIM(arr, i) > 1)
|
1234 |
+
++effrank;
|
1235 |
+
if (dims[rank - 1] >= 0)
|
1236 |
+
if (effrank > rank) {
|
1237 |
+
PyErr_Format(PyExc_ValueError,
|
1238 |
+
"too many axes: %d (effrank=%d), "
|
1239 |
+
"expected rank=%d\n",
|
1240 |
+
PyArray_NDIM(arr), effrank, rank);
|
1241 |
+
return 1;
|
1242 |
+
}
|
1243 |
+
|
1244 |
+
for (i = 0, j = 0; i < rank; ++i) {
|
1245 |
+
while (j < PyArray_NDIM(arr) && PyArray_DIM(arr, j) < 2) ++j;
|
1246 |
+
if (j >= PyArray_NDIM(arr))
|
1247 |
+
d = 1;
|
1248 |
+
else
|
1249 |
+
d = PyArray_DIM(arr, j++);
|
1250 |
+
if (dims[i] >= 0) {
|
1251 |
+
if (d > 1 && d != dims[i]) {
|
1252 |
+
if (errmess != NULL) {
|
1253 |
+
strcpy(mess, errmess);
|
1254 |
+
}
|
1255 |
+
sprintf(mess + strlen(mess),
|
1256 |
+
" -- %d-th dimension must be fixed to %"
|
1257 |
+
NPY_INTP_FMT " but got %" NPY_INTP_FMT
|
1258 |
+
" (real index=%d)\n",
|
1259 |
+
i, dims[i], d, j-1);
|
1260 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
1261 |
+
return 1;
|
1262 |
+
}
|
1263 |
+
if (!dims[i])
|
1264 |
+
dims[i] = 1;
|
1265 |
+
}
|
1266 |
+
else
|
1267 |
+
dims[i] = d;
|
1268 |
+
}
|
1269 |
+
|
1270 |
+
for (i = rank; i < PyArray_NDIM(arr);
|
1271 |
+
++i) { /* [[1,2],[3,4]] -> [1,2,3,4] */
|
1272 |
+
while (j < PyArray_NDIM(arr) && PyArray_DIM(arr, j) < 2) ++j;
|
1273 |
+
if (j >= PyArray_NDIM(arr))
|
1274 |
+
d = 1;
|
1275 |
+
else
|
1276 |
+
d = PyArray_DIM(arr, j++);
|
1277 |
+
dims[rank - 1] *= d;
|
1278 |
+
}
|
1279 |
+
for (i = 0, size = 1; i < rank; ++i) size *= dims[i];
|
1280 |
+
if (size != arr_size) {
|
1281 |
+
char msg[200];
|
1282 |
+
int len;
|
1283 |
+
snprintf(msg, sizeof(msg),
|
1284 |
+
"unexpected array size: size=%" NPY_INTP_FMT
|
1285 |
+
", arr_size=%" NPY_INTP_FMT
|
1286 |
+
", rank=%d, effrank=%d, arr.nd=%d, dims=[",
|
1287 |
+
size, arr_size, rank, effrank, PyArray_NDIM(arr));
|
1288 |
+
for (i = 0; i < rank; ++i) {
|
1289 |
+
len = strlen(msg);
|
1290 |
+
snprintf(msg + len, sizeof(msg) - len, " %" NPY_INTP_FMT,
|
1291 |
+
dims[i]);
|
1292 |
+
}
|
1293 |
+
len = strlen(msg);
|
1294 |
+
snprintf(msg + len, sizeof(msg) - len, " ], arr.dims=[");
|
1295 |
+
for (i = 0; i < PyArray_NDIM(arr); ++i) {
|
1296 |
+
len = strlen(msg);
|
1297 |
+
snprintf(msg + len, sizeof(msg) - len, " %" NPY_INTP_FMT,
|
1298 |
+
PyArray_DIM(arr, i));
|
1299 |
+
}
|
1300 |
+
len = strlen(msg);
|
1301 |
+
snprintf(msg + len, sizeof(msg) - len, " ]\n");
|
1302 |
+
PyErr_SetString(PyExc_ValueError, msg);
|
1303 |
+
return 1;
|
1304 |
+
}
|
1305 |
+
}
|
1306 |
+
#ifdef DEBUG_COPY_ND_ARRAY
|
1307 |
+
printf("check_and_fix_dimensions:end: dims=");
|
1308 |
+
dump_dims(rank, dims);
|
1309 |
+
#endif
|
1310 |
+
return 0;
|
1311 |
+
}
|
1312 |
+
|
1313 |
+
/* End of file: array_from_pyobj.c */
|
1314 |
+
|
1315 |
+
/************************* copy_ND_array *******************************/
|
1316 |
+
|
1317 |
+
extern int
|
1318 |
+
copy_ND_array(const PyArrayObject *arr, PyArrayObject *out)
|
1319 |
+
{
|
1320 |
+
F2PY_REPORT_ON_ARRAY_COPY_FROMARR;
|
1321 |
+
return PyArray_CopyInto(out, (PyArrayObject *)arr);
|
1322 |
+
}
|
1323 |
+
|
1324 |
+
/********************* Various utility functions ***********************/
|
1325 |
+
|
1326 |
+
extern int
|
1327 |
+
f2py_describe(PyObject *obj, char *buf) {
|
1328 |
+
/*
|
1329 |
+
Write the description of a Python object to buf. The caller must
|
1330 |
+
provide buffer with size sufficient to write the description.
|
1331 |
+
|
1332 |
+
Return 1 on success.
|
1333 |
+
*/
|
1334 |
+
char localbuf[F2PY_MESSAGE_BUFFER_SIZE];
|
1335 |
+
if (PyBytes_Check(obj)) {
|
1336 |
+
sprintf(localbuf, "%d-%s", (npy_int)PyBytes_GET_SIZE(obj), Py_TYPE(obj)->tp_name);
|
1337 |
+
} else if (PyUnicode_Check(obj)) {
|
1338 |
+
sprintf(localbuf, "%d-%s", (npy_int)PyUnicode_GET_LENGTH(obj), Py_TYPE(obj)->tp_name);
|
1339 |
+
} else if (PyArray_CheckScalar(obj)) {
|
1340 |
+
PyArrayObject* arr = (PyArrayObject*)obj;
|
1341 |
+
sprintf(localbuf, "%c%" NPY_INTP_FMT "-%s-scalar", PyArray_DESCR(arr)->kind, PyArray_ITEMSIZE(arr), Py_TYPE(obj)->tp_name);
|
1342 |
+
} else if (PyArray_Check(obj)) {
|
1343 |
+
int i;
|
1344 |
+
PyArrayObject* arr = (PyArrayObject*)obj;
|
1345 |
+
strcpy(localbuf, "(");
|
1346 |
+
for (i=0; i<PyArray_NDIM(arr); i++) {
|
1347 |
+
if (i) {
|
1348 |
+
strcat(localbuf, " ");
|
1349 |
+
}
|
1350 |
+
sprintf(localbuf + strlen(localbuf), "%" NPY_INTP_FMT ",", PyArray_DIM(arr, i));
|
1351 |
+
}
|
1352 |
+
sprintf(localbuf + strlen(localbuf), ")-%c%" NPY_INTP_FMT "-%s", PyArray_DESCR(arr)->kind, PyArray_ITEMSIZE(arr), Py_TYPE(obj)->tp_name);
|
1353 |
+
} else if (PySequence_Check(obj)) {
|
1354 |
+
sprintf(localbuf, "%d-%s", (npy_int)PySequence_Length(obj), Py_TYPE(obj)->tp_name);
|
1355 |
+
} else {
|
1356 |
+
sprintf(localbuf, "%s instance", Py_TYPE(obj)->tp_name);
|
1357 |
+
}
|
1358 |
+
// TODO: detect the size of buf and make sure that size(buf) >= size(localbuf).
|
1359 |
+
strcpy(buf, localbuf);
|
1360 |
+
return 1;
|
1361 |
+
}
|
1362 |
+
|
1363 |
+
extern npy_intp
|
1364 |
+
f2py_size_impl(PyArrayObject* var, ...)
|
1365 |
+
{
|
1366 |
+
npy_intp sz = 0;
|
1367 |
+
npy_intp dim;
|
1368 |
+
npy_intp rank;
|
1369 |
+
va_list argp;
|
1370 |
+
va_start(argp, var);
|
1371 |
+
dim = va_arg(argp, npy_int);
|
1372 |
+
if (dim==-1)
|
1373 |
+
{
|
1374 |
+
sz = PyArray_SIZE(var);
|
1375 |
+
}
|
1376 |
+
else
|
1377 |
+
{
|
1378 |
+
rank = PyArray_NDIM(var);
|
1379 |
+
if (dim>=1 && dim<=rank)
|
1380 |
+
sz = PyArray_DIM(var, dim-1);
|
1381 |
+
else
|
1382 |
+
fprintf(stderr, "f2py_size: 2nd argument value=%" NPY_INTP_FMT
|
1383 |
+
" fails to satisfy 1<=value<=%" NPY_INTP_FMT
|
1384 |
+
". Result will be 0.\n", dim, rank);
|
1385 |
+
}
|
1386 |
+
va_end(argp);
|
1387 |
+
return sz;
|
1388 |
+
}
|
1389 |
+
|
1390 |
+
/*********************************************/
|
1391 |
+
/* Compatibility functions for Python >= 3.0 */
|
1392 |
+
/*********************************************/
|
1393 |
+
|
1394 |
+
PyObject *
|
1395 |
+
F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *))
|
1396 |
+
{
|
1397 |
+
PyObject *ret = PyCapsule_New(ptr, NULL, dtor);
|
1398 |
+
if (ret == NULL) {
|
1399 |
+
PyErr_Clear();
|
1400 |
+
}
|
1401 |
+
return ret;
|
1402 |
+
}
|
1403 |
+
|
1404 |
+
void *
|
1405 |
+
F2PyCapsule_AsVoidPtr(PyObject *obj)
|
1406 |
+
{
|
1407 |
+
void *ret = PyCapsule_GetPointer(obj, NULL);
|
1408 |
+
if (ret == NULL) {
|
1409 |
+
PyErr_Clear();
|
1410 |
+
}
|
1411 |
+
return ret;
|
1412 |
+
}
|
1413 |
+
|
1414 |
+
int
|
1415 |
+
F2PyCapsule_Check(PyObject *ptr)
|
1416 |
+
{
|
1417 |
+
return PyCapsule_CheckExact(ptr);
|
1418 |
+
}
|
1419 |
+
|
1420 |
+
#ifdef __cplusplus
|
1421 |
+
}
|
1422 |
+
#endif
|
1423 |
+
/************************* EOF fortranobject.c *******************************/
|
venv/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.h
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef Py_FORTRANOBJECT_H
|
2 |
+
#define Py_FORTRANOBJECT_H
|
3 |
+
#ifdef __cplusplus
|
4 |
+
extern "C" {
|
5 |
+
#endif
|
6 |
+
|
7 |
+
#include <Python.h>
|
8 |
+
|
9 |
+
#ifndef NPY_NO_DEPRECATED_API
|
10 |
+
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
|
11 |
+
#endif
|
12 |
+
#ifdef FORTRANOBJECT_C
|
13 |
+
#define NO_IMPORT_ARRAY
|
14 |
+
#endif
|
15 |
+
#define PY_ARRAY_UNIQUE_SYMBOL _npy_f2py_ARRAY_API
|
16 |
+
#include "numpy/arrayobject.h"
|
17 |
+
#include "numpy/npy_3kcompat.h"
|
18 |
+
|
19 |
+
#ifdef F2PY_REPORT_ATEXIT
|
20 |
+
#include <sys/timeb.h>
|
21 |
+
// clang-format off
|
22 |
+
extern void f2py_start_clock(void);
|
23 |
+
extern void f2py_stop_clock(void);
|
24 |
+
extern void f2py_start_call_clock(void);
|
25 |
+
extern void f2py_stop_call_clock(void);
|
26 |
+
extern void f2py_cb_start_clock(void);
|
27 |
+
extern void f2py_cb_stop_clock(void);
|
28 |
+
extern void f2py_cb_start_call_clock(void);
|
29 |
+
extern void f2py_cb_stop_call_clock(void);
|
30 |
+
extern void f2py_report_on_exit(int, void *);
|
31 |
+
// clang-format on
|
32 |
+
#endif
|
33 |
+
|
34 |
+
#ifdef DMALLOC
|
35 |
+
#include "dmalloc.h"
|
36 |
+
#endif
|
37 |
+
|
38 |
+
/* Fortran object interface */
|
39 |
+
|
40 |
+
/*
|
41 |
+
123456789-123456789-123456789-123456789-123456789-123456789-123456789-12
|
42 |
+
|
43 |
+
PyFortranObject represents various Fortran objects:
|
44 |
+
Fortran (module) routines, COMMON blocks, module data.
|
45 |
+
|
46 |
+
Author: Pearu Peterson <[email protected]>
|
47 |
+
*/
|
48 |
+
|
49 |
+
#define F2PY_MAX_DIMS 40
|
50 |
+
#define F2PY_MESSAGE_BUFFER_SIZE 300 // Increase on "stack smashing detected"
|
51 |
+
|
52 |
+
typedef void (*f2py_set_data_func)(char *, npy_intp *);
|
53 |
+
typedef void (*f2py_void_func)(void);
|
54 |
+
typedef void (*f2py_init_func)(int *, npy_intp *, f2py_set_data_func, int *);
|
55 |
+
|
56 |
+
/*typedef void* (*f2py_c_func)(void*,...);*/
|
57 |
+
|
58 |
+
typedef void *(*f2pycfunc)(void);
|
59 |
+
|
60 |
+
typedef struct {
|
61 |
+
char *name; /* attribute (array||routine) name */
|
62 |
+
int rank; /* array rank, 0 for scalar, max is F2PY_MAX_DIMS,
|
63 |
+
|| rank=-1 for Fortran routine */
|
64 |
+
struct {
|
65 |
+
npy_intp d[F2PY_MAX_DIMS];
|
66 |
+
} dims; /* dimensions of the array, || not used */
|
67 |
+
int type; /* PyArray_<type> || not used */
|
68 |
+
int elsize; /* Element size || not used */
|
69 |
+
char *data; /* pointer to array || Fortran routine */
|
70 |
+
f2py_init_func func; /* initialization function for
|
71 |
+
allocatable arrays:
|
72 |
+
func(&rank,dims,set_ptr_func,name,len(name))
|
73 |
+
|| C/API wrapper for Fortran routine */
|
74 |
+
char *doc; /* documentation string; only recommended
|
75 |
+
for routines. */
|
76 |
+
} FortranDataDef;
|
77 |
+
|
78 |
+
typedef struct {
|
79 |
+
PyObject_HEAD
|
80 |
+
int len; /* Number of attributes */
|
81 |
+
FortranDataDef *defs; /* An array of FortranDataDef's */
|
82 |
+
PyObject *dict; /* Fortran object attribute dictionary */
|
83 |
+
} PyFortranObject;
|
84 |
+
|
85 |
+
#define PyFortran_Check(op) (Py_TYPE(op) == &PyFortran_Type)
|
86 |
+
#define PyFortran_Check1(op) (0 == strcmp(Py_TYPE(op)->tp_name, "fortran"))
|
87 |
+
|
88 |
+
extern PyTypeObject PyFortran_Type;
|
89 |
+
extern int
|
90 |
+
F2PyDict_SetItemString(PyObject *dict, char *name, PyObject *obj);
|
91 |
+
extern PyObject *
|
92 |
+
PyFortranObject_New(FortranDataDef *defs, f2py_void_func init);
|
93 |
+
extern PyObject *
|
94 |
+
PyFortranObject_NewAsAttr(FortranDataDef *defs);
|
95 |
+
|
96 |
+
PyObject *
|
97 |
+
F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *));
|
98 |
+
void *
|
99 |
+
F2PyCapsule_AsVoidPtr(PyObject *obj);
|
100 |
+
int
|
101 |
+
F2PyCapsule_Check(PyObject *ptr);
|
102 |
+
|
103 |
+
extern void *
|
104 |
+
F2PySwapThreadLocalCallbackPtr(char *key, void *ptr);
|
105 |
+
extern void *
|
106 |
+
F2PyGetThreadLocalCallbackPtr(char *key);
|
107 |
+
|
108 |
+
#define ISCONTIGUOUS(m) (PyArray_FLAGS(m) & NPY_ARRAY_C_CONTIGUOUS)
|
109 |
+
#define F2PY_INTENT_IN 1
|
110 |
+
#define F2PY_INTENT_INOUT 2
|
111 |
+
#define F2PY_INTENT_OUT 4
|
112 |
+
#define F2PY_INTENT_HIDE 8
|
113 |
+
#define F2PY_INTENT_CACHE 16
|
114 |
+
#define F2PY_INTENT_COPY 32
|
115 |
+
#define F2PY_INTENT_C 64
|
116 |
+
#define F2PY_OPTIONAL 128
|
117 |
+
#define F2PY_INTENT_INPLACE 256
|
118 |
+
#define F2PY_INTENT_ALIGNED4 512
|
119 |
+
#define F2PY_INTENT_ALIGNED8 1024
|
120 |
+
#define F2PY_INTENT_ALIGNED16 2048
|
121 |
+
|
122 |
+
#define ARRAY_ISALIGNED(ARR, SIZE) ((size_t)(PyArray_DATA(ARR)) % (SIZE) == 0)
|
123 |
+
#define F2PY_ALIGN4(intent) (intent & F2PY_INTENT_ALIGNED4)
|
124 |
+
#define F2PY_ALIGN8(intent) (intent & F2PY_INTENT_ALIGNED8)
|
125 |
+
#define F2PY_ALIGN16(intent) (intent & F2PY_INTENT_ALIGNED16)
|
126 |
+
|
127 |
+
#define F2PY_GET_ALIGNMENT(intent) \
|
128 |
+
(F2PY_ALIGN4(intent) \
|
129 |
+
? 4 \
|
130 |
+
: (F2PY_ALIGN8(intent) ? 8 : (F2PY_ALIGN16(intent) ? 16 : 1)))
|
131 |
+
#define F2PY_CHECK_ALIGNMENT(arr, intent) \
|
132 |
+
ARRAY_ISALIGNED(arr, F2PY_GET_ALIGNMENT(intent))
|
133 |
+
#define F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr) ((PyArray_DESCR(arr)->type_num == NPY_STRING && PyArray_DESCR(arr)->elsize >= 1) \
|
134 |
+
|| PyArray_DESCR(arr)->type_num == NPY_UINT8)
|
135 |
+
#define F2PY_IS_UNICODE_ARRAY(arr) (PyArray_DESCR(arr)->type_num == NPY_UNICODE)
|
136 |
+
|
137 |
+
extern PyArrayObject *
|
138 |
+
ndarray_from_pyobj(const int type_num, const int elsize_, npy_intp *dims,
|
139 |
+
const int rank, const int intent, PyObject *obj,
|
140 |
+
const char *errmess);
|
141 |
+
|
142 |
+
extern PyArrayObject *
|
143 |
+
array_from_pyobj(const int type_num, npy_intp *dims, const int rank,
|
144 |
+
const int intent, PyObject *obj);
|
145 |
+
extern int
|
146 |
+
copy_ND_array(const PyArrayObject *in, PyArrayObject *out);
|
147 |
+
|
148 |
+
#ifdef DEBUG_COPY_ND_ARRAY
|
149 |
+
extern void
|
150 |
+
dump_attrs(const PyArrayObject *arr);
|
151 |
+
#endif
|
152 |
+
|
153 |
+
extern int f2py_describe(PyObject *obj, char *buf);
|
154 |
+
|
155 |
+
/* Utility CPP macros and functions that can be used in signature file
|
156 |
+
expressions. See signature-file.rst for documentation.
|
157 |
+
*/
|
158 |
+
|
159 |
+
#define f2py_itemsize(var) (PyArray_DESCR((capi_ ## var ## _as_array))->elsize)
|
160 |
+
#define f2py_size(var, ...) f2py_size_impl((PyArrayObject *)(capi_ ## var ## _as_array), ## __VA_ARGS__, -1)
|
161 |
+
#define f2py_rank(var) var ## _Rank
|
162 |
+
#define f2py_shape(var,dim) var ## _Dims[dim]
|
163 |
+
#define f2py_len(var) f2py_shape(var,0)
|
164 |
+
#define f2py_fshape(var,dim) f2py_shape(var,rank(var)-dim-1)
|
165 |
+
#define f2py_flen(var) f2py_fshape(var,0)
|
166 |
+
#define f2py_slen(var) capi_ ## var ## _len
|
167 |
+
|
168 |
+
extern npy_intp f2py_size_impl(PyArrayObject* var, ...);
|
169 |
+
|
170 |
+
#ifdef __cplusplus
|
171 |
+
}
|
172 |
+
#endif
|
173 |
+
#endif /* !Py_FORTRANOBJECT_H */
|
venv/lib/python3.10/site-packages/numpy/f2py/symbolic.py
ADDED
@@ -0,0 +1,1517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Fortran/C symbolic expressions
|
2 |
+
|
3 |
+
References:
|
4 |
+
- J3/21-007: Draft Fortran 202x. https://j3-fortran.org/doc/year/21/21-007.pdf
|
5 |
+
|
6 |
+
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
|
7 |
+
Copyright 2011 -- present NumPy Developers.
|
8 |
+
Permission to use, modify, and distribute this software is given under the
|
9 |
+
terms of the NumPy License.
|
10 |
+
|
11 |
+
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
12 |
+
"""
|
13 |
+
|
14 |
+
# To analyze Fortran expressions to solve dimensions specifications,
|
15 |
+
# for instances, we implement a minimal symbolic engine for parsing
|
16 |
+
# expressions into a tree of expression instances. As a first
|
17 |
+
# instance, we care only about arithmetic expressions involving
|
18 |
+
# integers and operations like addition (+), subtraction (-),
|
19 |
+
# multiplication (*), division (Fortran / is Python //, Fortran // is
|
20 |
+
# concatenate), and exponentiation (**). In addition, .pyf files may
|
21 |
+
# contain C expressions that support here is implemented as well.
|
22 |
+
#
|
23 |
+
# TODO: support logical constants (Op.BOOLEAN)
|
24 |
+
# TODO: support logical operators (.AND., ...)
|
25 |
+
# TODO: support defined operators (.MYOP., ...)
|
26 |
+
#
|
27 |
+
__all__ = ['Expr']
|
28 |
+
|
29 |
+
|
30 |
+
import re
|
31 |
+
import warnings
|
32 |
+
from enum import Enum
|
33 |
+
from math import gcd
|
34 |
+
|
35 |
+
|
36 |
+
class Language(Enum):
|
37 |
+
"""
|
38 |
+
Used as Expr.tostring language argument.
|
39 |
+
"""
|
40 |
+
Python = 0
|
41 |
+
Fortran = 1
|
42 |
+
C = 2
|
43 |
+
|
44 |
+
|
45 |
+
class Op(Enum):
|
46 |
+
"""
|
47 |
+
Used as Expr op attribute.
|
48 |
+
"""
|
49 |
+
INTEGER = 10
|
50 |
+
REAL = 12
|
51 |
+
COMPLEX = 15
|
52 |
+
STRING = 20
|
53 |
+
ARRAY = 30
|
54 |
+
SYMBOL = 40
|
55 |
+
TERNARY = 100
|
56 |
+
APPLY = 200
|
57 |
+
INDEXING = 210
|
58 |
+
CONCAT = 220
|
59 |
+
RELATIONAL = 300
|
60 |
+
TERMS = 1000
|
61 |
+
FACTORS = 2000
|
62 |
+
REF = 3000
|
63 |
+
DEREF = 3001
|
64 |
+
|
65 |
+
|
66 |
+
class RelOp(Enum):
|
67 |
+
"""
|
68 |
+
Used in Op.RELATIONAL expression to specify the function part.
|
69 |
+
"""
|
70 |
+
EQ = 1
|
71 |
+
NE = 2
|
72 |
+
LT = 3
|
73 |
+
LE = 4
|
74 |
+
GT = 5
|
75 |
+
GE = 6
|
76 |
+
|
77 |
+
@classmethod
|
78 |
+
def fromstring(cls, s, language=Language.C):
|
79 |
+
if language is Language.Fortran:
|
80 |
+
return {'.eq.': RelOp.EQ, '.ne.': RelOp.NE,
|
81 |
+
'.lt.': RelOp.LT, '.le.': RelOp.LE,
|
82 |
+
'.gt.': RelOp.GT, '.ge.': RelOp.GE}[s.lower()]
|
83 |
+
return {'==': RelOp.EQ, '!=': RelOp.NE, '<': RelOp.LT,
|
84 |
+
'<=': RelOp.LE, '>': RelOp.GT, '>=': RelOp.GE}[s]
|
85 |
+
|
86 |
+
def tostring(self, language=Language.C):
|
87 |
+
if language is Language.Fortran:
|
88 |
+
return {RelOp.EQ: '.eq.', RelOp.NE: '.ne.',
|
89 |
+
RelOp.LT: '.lt.', RelOp.LE: '.le.',
|
90 |
+
RelOp.GT: '.gt.', RelOp.GE: '.ge.'}[self]
|
91 |
+
return {RelOp.EQ: '==', RelOp.NE: '!=',
|
92 |
+
RelOp.LT: '<', RelOp.LE: '<=',
|
93 |
+
RelOp.GT: '>', RelOp.GE: '>='}[self]
|
94 |
+
|
95 |
+
|
96 |
+
class ArithOp(Enum):
|
97 |
+
"""
|
98 |
+
Used in Op.APPLY expression to specify the function part.
|
99 |
+
"""
|
100 |
+
POS = 1
|
101 |
+
NEG = 2
|
102 |
+
ADD = 3
|
103 |
+
SUB = 4
|
104 |
+
MUL = 5
|
105 |
+
DIV = 6
|
106 |
+
POW = 7
|
107 |
+
|
108 |
+
|
109 |
+
class OpError(Exception):
|
110 |
+
pass
|
111 |
+
|
112 |
+
|
113 |
+
class Precedence(Enum):
|
114 |
+
"""
|
115 |
+
Used as Expr.tostring precedence argument.
|
116 |
+
"""
|
117 |
+
ATOM = 0
|
118 |
+
POWER = 1
|
119 |
+
UNARY = 2
|
120 |
+
PRODUCT = 3
|
121 |
+
SUM = 4
|
122 |
+
LT = 6
|
123 |
+
EQ = 7
|
124 |
+
LAND = 11
|
125 |
+
LOR = 12
|
126 |
+
TERNARY = 13
|
127 |
+
ASSIGN = 14
|
128 |
+
TUPLE = 15
|
129 |
+
NONE = 100
|
130 |
+
|
131 |
+
|
132 |
+
integer_types = (int,)
|
133 |
+
number_types = (int, float)
|
134 |
+
|
135 |
+
|
136 |
+
def _pairs_add(d, k, v):
|
137 |
+
# Internal utility method for updating terms and factors data.
|
138 |
+
c = d.get(k)
|
139 |
+
if c is None:
|
140 |
+
d[k] = v
|
141 |
+
else:
|
142 |
+
c = c + v
|
143 |
+
if c:
|
144 |
+
d[k] = c
|
145 |
+
else:
|
146 |
+
del d[k]
|
147 |
+
|
148 |
+
|
149 |
+
class ExprWarning(UserWarning):
|
150 |
+
pass
|
151 |
+
|
152 |
+
|
153 |
+
def ewarn(message):
|
154 |
+
warnings.warn(message, ExprWarning, stacklevel=2)
|
155 |
+
|
156 |
+
|
157 |
+
class Expr:
|
158 |
+
"""Represents a Fortran expression as a op-data pair.
|
159 |
+
|
160 |
+
Expr instances are hashable and sortable.
|
161 |
+
"""
|
162 |
+
|
163 |
+
@staticmethod
|
164 |
+
def parse(s, language=Language.C):
|
165 |
+
"""Parse a Fortran expression to a Expr.
|
166 |
+
"""
|
167 |
+
return fromstring(s, language=language)
|
168 |
+
|
169 |
+
def __init__(self, op, data):
|
170 |
+
assert isinstance(op, Op)
|
171 |
+
|
172 |
+
# sanity checks
|
173 |
+
if op is Op.INTEGER:
|
174 |
+
# data is a 2-tuple of numeric object and a kind value
|
175 |
+
# (default is 4)
|
176 |
+
assert isinstance(data, tuple) and len(data) == 2
|
177 |
+
assert isinstance(data[0], int)
|
178 |
+
assert isinstance(data[1], (int, str)), data
|
179 |
+
elif op is Op.REAL:
|
180 |
+
# data is a 2-tuple of numeric object and a kind value
|
181 |
+
# (default is 4)
|
182 |
+
assert isinstance(data, tuple) and len(data) == 2
|
183 |
+
assert isinstance(data[0], float)
|
184 |
+
assert isinstance(data[1], (int, str)), data
|
185 |
+
elif op is Op.COMPLEX:
|
186 |
+
# data is a 2-tuple of constant expressions
|
187 |
+
assert isinstance(data, tuple) and len(data) == 2
|
188 |
+
elif op is Op.STRING:
|
189 |
+
# data is a 2-tuple of quoted string and a kind value
|
190 |
+
# (default is 1)
|
191 |
+
assert isinstance(data, tuple) and len(data) == 2
|
192 |
+
assert (isinstance(data[0], str)
|
193 |
+
and data[0][::len(data[0])-1] in ('""', "''", '@@'))
|
194 |
+
assert isinstance(data[1], (int, str)), data
|
195 |
+
elif op is Op.SYMBOL:
|
196 |
+
# data is any hashable object
|
197 |
+
assert hash(data) is not None
|
198 |
+
elif op in (Op.ARRAY, Op.CONCAT):
|
199 |
+
# data is a tuple of expressions
|
200 |
+
assert isinstance(data, tuple)
|
201 |
+
assert all(isinstance(item, Expr) for item in data), data
|
202 |
+
elif op in (Op.TERMS, Op.FACTORS):
|
203 |
+
# data is {<term|base>:<coeff|exponent>} where dict values
|
204 |
+
# are nonzero Python integers
|
205 |
+
assert isinstance(data, dict)
|
206 |
+
elif op is Op.APPLY:
|
207 |
+
# data is (<function>, <operands>, <kwoperands>) where
|
208 |
+
# operands are Expr instances
|
209 |
+
assert isinstance(data, tuple) and len(data) == 3
|
210 |
+
# function is any hashable object
|
211 |
+
assert hash(data[0]) is not None
|
212 |
+
assert isinstance(data[1], tuple)
|
213 |
+
assert isinstance(data[2], dict)
|
214 |
+
elif op is Op.INDEXING:
|
215 |
+
# data is (<object>, <indices>)
|
216 |
+
assert isinstance(data, tuple) and len(data) == 2
|
217 |
+
# function is any hashable object
|
218 |
+
assert hash(data[0]) is not None
|
219 |
+
elif op is Op.TERNARY:
|
220 |
+
# data is (<cond>, <expr1>, <expr2>)
|
221 |
+
assert isinstance(data, tuple) and len(data) == 3
|
222 |
+
elif op in (Op.REF, Op.DEREF):
|
223 |
+
# data is Expr instance
|
224 |
+
assert isinstance(data, Expr)
|
225 |
+
elif op is Op.RELATIONAL:
|
226 |
+
# data is (<relop>, <left>, <right>)
|
227 |
+
assert isinstance(data, tuple) and len(data) == 3
|
228 |
+
else:
|
229 |
+
raise NotImplementedError(
|
230 |
+
f'unknown op or missing sanity check: {op}')
|
231 |
+
|
232 |
+
self.op = op
|
233 |
+
self.data = data
|
234 |
+
|
235 |
+
def __eq__(self, other):
|
236 |
+
return (isinstance(other, Expr)
|
237 |
+
and self.op is other.op
|
238 |
+
and self.data == other.data)
|
239 |
+
|
240 |
+
def __hash__(self):
|
241 |
+
if self.op in (Op.TERMS, Op.FACTORS):
|
242 |
+
data = tuple(sorted(self.data.items()))
|
243 |
+
elif self.op is Op.APPLY:
|
244 |
+
data = self.data[:2] + tuple(sorted(self.data[2].items()))
|
245 |
+
else:
|
246 |
+
data = self.data
|
247 |
+
return hash((self.op, data))
|
248 |
+
|
249 |
+
def __lt__(self, other):
|
250 |
+
if isinstance(other, Expr):
|
251 |
+
if self.op is not other.op:
|
252 |
+
return self.op.value < other.op.value
|
253 |
+
if self.op in (Op.TERMS, Op.FACTORS):
|
254 |
+
return (tuple(sorted(self.data.items()))
|
255 |
+
< tuple(sorted(other.data.items())))
|
256 |
+
if self.op is Op.APPLY:
|
257 |
+
if self.data[:2] != other.data[:2]:
|
258 |
+
return self.data[:2] < other.data[:2]
|
259 |
+
return tuple(sorted(self.data[2].items())) < tuple(
|
260 |
+
sorted(other.data[2].items()))
|
261 |
+
return self.data < other.data
|
262 |
+
return NotImplemented
|
263 |
+
|
264 |
+
def __le__(self, other): return self == other or self < other
|
265 |
+
|
266 |
+
def __gt__(self, other): return not (self <= other)
|
267 |
+
|
268 |
+
def __ge__(self, other): return not (self < other)
|
269 |
+
|
270 |
+
def __repr__(self):
|
271 |
+
return f'{type(self).__name__}({self.op}, {self.data!r})'
|
272 |
+
|
273 |
+
def __str__(self):
|
274 |
+
return self.tostring()
|
275 |
+
|
276 |
+
def tostring(self, parent_precedence=Precedence.NONE,
|
277 |
+
language=Language.Fortran):
|
278 |
+
"""Return a string representation of Expr.
|
279 |
+
"""
|
280 |
+
if self.op in (Op.INTEGER, Op.REAL):
|
281 |
+
precedence = (Precedence.SUM if self.data[0] < 0
|
282 |
+
else Precedence.ATOM)
|
283 |
+
r = str(self.data[0]) + (f'_{self.data[1]}'
|
284 |
+
if self.data[1] != 4 else '')
|
285 |
+
elif self.op is Op.COMPLEX:
|
286 |
+
r = ', '.join(item.tostring(Precedence.TUPLE, language=language)
|
287 |
+
for item in self.data)
|
288 |
+
r = '(' + r + ')'
|
289 |
+
precedence = Precedence.ATOM
|
290 |
+
elif self.op is Op.SYMBOL:
|
291 |
+
precedence = Precedence.ATOM
|
292 |
+
r = str(self.data)
|
293 |
+
elif self.op is Op.STRING:
|
294 |
+
r = self.data[0]
|
295 |
+
if self.data[1] != 1:
|
296 |
+
r = self.data[1] + '_' + r
|
297 |
+
precedence = Precedence.ATOM
|
298 |
+
elif self.op is Op.ARRAY:
|
299 |
+
r = ', '.join(item.tostring(Precedence.TUPLE, language=language)
|
300 |
+
for item in self.data)
|
301 |
+
r = '[' + r + ']'
|
302 |
+
precedence = Precedence.ATOM
|
303 |
+
elif self.op is Op.TERMS:
|
304 |
+
terms = []
|
305 |
+
for term, coeff in sorted(self.data.items()):
|
306 |
+
if coeff < 0:
|
307 |
+
op = ' - '
|
308 |
+
coeff = -coeff
|
309 |
+
else:
|
310 |
+
op = ' + '
|
311 |
+
if coeff == 1:
|
312 |
+
term = term.tostring(Precedence.SUM, language=language)
|
313 |
+
else:
|
314 |
+
if term == as_number(1):
|
315 |
+
term = str(coeff)
|
316 |
+
else:
|
317 |
+
term = f'{coeff} * ' + term.tostring(
|
318 |
+
Precedence.PRODUCT, language=language)
|
319 |
+
if terms:
|
320 |
+
terms.append(op)
|
321 |
+
elif op == ' - ':
|
322 |
+
terms.append('-')
|
323 |
+
terms.append(term)
|
324 |
+
r = ''.join(terms) or '0'
|
325 |
+
precedence = Precedence.SUM if terms else Precedence.ATOM
|
326 |
+
elif self.op is Op.FACTORS:
|
327 |
+
factors = []
|
328 |
+
tail = []
|
329 |
+
for base, exp in sorted(self.data.items()):
|
330 |
+
op = ' * '
|
331 |
+
if exp == 1:
|
332 |
+
factor = base.tostring(Precedence.PRODUCT,
|
333 |
+
language=language)
|
334 |
+
elif language is Language.C:
|
335 |
+
if exp in range(2, 10):
|
336 |
+
factor = base.tostring(Precedence.PRODUCT,
|
337 |
+
language=language)
|
338 |
+
factor = ' * '.join([factor] * exp)
|
339 |
+
elif exp in range(-10, 0):
|
340 |
+
factor = base.tostring(Precedence.PRODUCT,
|
341 |
+
language=language)
|
342 |
+
tail += [factor] * -exp
|
343 |
+
continue
|
344 |
+
else:
|
345 |
+
factor = base.tostring(Precedence.TUPLE,
|
346 |
+
language=language)
|
347 |
+
factor = f'pow({factor}, {exp})'
|
348 |
+
else:
|
349 |
+
factor = base.tostring(Precedence.POWER,
|
350 |
+
language=language) + f' ** {exp}'
|
351 |
+
if factors:
|
352 |
+
factors.append(op)
|
353 |
+
factors.append(factor)
|
354 |
+
if tail:
|
355 |
+
if not factors:
|
356 |
+
factors += ['1']
|
357 |
+
factors += ['/', '(', ' * '.join(tail), ')']
|
358 |
+
r = ''.join(factors) or '1'
|
359 |
+
precedence = Precedence.PRODUCT if factors else Precedence.ATOM
|
360 |
+
elif self.op is Op.APPLY:
|
361 |
+
name, args, kwargs = self.data
|
362 |
+
if name is ArithOp.DIV and language is Language.C:
|
363 |
+
numer, denom = [arg.tostring(Precedence.PRODUCT,
|
364 |
+
language=language)
|
365 |
+
for arg in args]
|
366 |
+
r = f'{numer} / {denom}'
|
367 |
+
precedence = Precedence.PRODUCT
|
368 |
+
else:
|
369 |
+
args = [arg.tostring(Precedence.TUPLE, language=language)
|
370 |
+
for arg in args]
|
371 |
+
args += [k + '=' + v.tostring(Precedence.NONE)
|
372 |
+
for k, v in kwargs.items()]
|
373 |
+
r = f'{name}({", ".join(args)})'
|
374 |
+
precedence = Precedence.ATOM
|
375 |
+
elif self.op is Op.INDEXING:
|
376 |
+
name = self.data[0]
|
377 |
+
args = [arg.tostring(Precedence.TUPLE, language=language)
|
378 |
+
for arg in self.data[1:]]
|
379 |
+
r = f'{name}[{", ".join(args)}]'
|
380 |
+
precedence = Precedence.ATOM
|
381 |
+
elif self.op is Op.CONCAT:
|
382 |
+
args = [arg.tostring(Precedence.PRODUCT, language=language)
|
383 |
+
for arg in self.data]
|
384 |
+
r = " // ".join(args)
|
385 |
+
precedence = Precedence.PRODUCT
|
386 |
+
elif self.op is Op.TERNARY:
|
387 |
+
cond, expr1, expr2 = [a.tostring(Precedence.TUPLE,
|
388 |
+
language=language)
|
389 |
+
for a in self.data]
|
390 |
+
if language is Language.C:
|
391 |
+
r = f'({cond}?{expr1}:{expr2})'
|
392 |
+
elif language is Language.Python:
|
393 |
+
r = f'({expr1} if {cond} else {expr2})'
|
394 |
+
elif language is Language.Fortran:
|
395 |
+
r = f'merge({expr1}, {expr2}, {cond})'
|
396 |
+
else:
|
397 |
+
raise NotImplementedError(
|
398 |
+
f'tostring for {self.op} and {language}')
|
399 |
+
precedence = Precedence.ATOM
|
400 |
+
elif self.op is Op.REF:
|
401 |
+
r = '&' + self.data.tostring(Precedence.UNARY, language=language)
|
402 |
+
precedence = Precedence.UNARY
|
403 |
+
elif self.op is Op.DEREF:
|
404 |
+
r = '*' + self.data.tostring(Precedence.UNARY, language=language)
|
405 |
+
precedence = Precedence.UNARY
|
406 |
+
elif self.op is Op.RELATIONAL:
|
407 |
+
rop, left, right = self.data
|
408 |
+
precedence = (Precedence.EQ if rop in (RelOp.EQ, RelOp.NE)
|
409 |
+
else Precedence.LT)
|
410 |
+
left = left.tostring(precedence, language=language)
|
411 |
+
right = right.tostring(precedence, language=language)
|
412 |
+
rop = rop.tostring(language=language)
|
413 |
+
r = f'{left} {rop} {right}'
|
414 |
+
else:
|
415 |
+
raise NotImplementedError(f'tostring for op {self.op}')
|
416 |
+
if parent_precedence.value < precedence.value:
|
417 |
+
# If parent precedence is higher than operand precedence,
|
418 |
+
# operand will be enclosed in parenthesis.
|
419 |
+
return '(' + r + ')'
|
420 |
+
return r
|
421 |
+
|
422 |
+
def __pos__(self):
|
423 |
+
return self
|
424 |
+
|
425 |
+
def __neg__(self):
|
426 |
+
return self * -1
|
427 |
+
|
428 |
+
def __add__(self, other):
|
429 |
+
other = as_expr(other)
|
430 |
+
if isinstance(other, Expr):
|
431 |
+
if self.op is other.op:
|
432 |
+
if self.op in (Op.INTEGER, Op.REAL):
|
433 |
+
return as_number(
|
434 |
+
self.data[0] + other.data[0],
|
435 |
+
max(self.data[1], other.data[1]))
|
436 |
+
if self.op is Op.COMPLEX:
|
437 |
+
r1, i1 = self.data
|
438 |
+
r2, i2 = other.data
|
439 |
+
return as_complex(r1 + r2, i1 + i2)
|
440 |
+
if self.op is Op.TERMS:
|
441 |
+
r = Expr(self.op, dict(self.data))
|
442 |
+
for k, v in other.data.items():
|
443 |
+
_pairs_add(r.data, k, v)
|
444 |
+
return normalize(r)
|
445 |
+
if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL):
|
446 |
+
return self + as_complex(other)
|
447 |
+
elif self.op in (Op.INTEGER, Op.REAL) and other.op is Op.COMPLEX:
|
448 |
+
return as_complex(self) + other
|
449 |
+
elif self.op is Op.REAL and other.op is Op.INTEGER:
|
450 |
+
return self + as_real(other, kind=self.data[1])
|
451 |
+
elif self.op is Op.INTEGER and other.op is Op.REAL:
|
452 |
+
return as_real(self, kind=other.data[1]) + other
|
453 |
+
return as_terms(self) + as_terms(other)
|
454 |
+
return NotImplemented
|
455 |
+
|
456 |
+
def __radd__(self, other):
|
457 |
+
if isinstance(other, number_types):
|
458 |
+
return as_number(other) + self
|
459 |
+
return NotImplemented
|
460 |
+
|
461 |
+
def __sub__(self, other):
|
462 |
+
return self + (-other)
|
463 |
+
|
464 |
+
def __rsub__(self, other):
|
465 |
+
if isinstance(other, number_types):
|
466 |
+
return as_number(other) - self
|
467 |
+
return NotImplemented
|
468 |
+
|
469 |
+
def __mul__(self, other):
|
470 |
+
other = as_expr(other)
|
471 |
+
if isinstance(other, Expr):
|
472 |
+
if self.op is other.op:
|
473 |
+
if self.op in (Op.INTEGER, Op.REAL):
|
474 |
+
return as_number(self.data[0] * other.data[0],
|
475 |
+
max(self.data[1], other.data[1]))
|
476 |
+
elif self.op is Op.COMPLEX:
|
477 |
+
r1, i1 = self.data
|
478 |
+
r2, i2 = other.data
|
479 |
+
return as_complex(r1 * r2 - i1 * i2, r1 * i2 + r2 * i1)
|
480 |
+
|
481 |
+
if self.op is Op.FACTORS:
|
482 |
+
r = Expr(self.op, dict(self.data))
|
483 |
+
for k, v in other.data.items():
|
484 |
+
_pairs_add(r.data, k, v)
|
485 |
+
return normalize(r)
|
486 |
+
elif self.op is Op.TERMS:
|
487 |
+
r = Expr(self.op, {})
|
488 |
+
for t1, c1 in self.data.items():
|
489 |
+
for t2, c2 in other.data.items():
|
490 |
+
_pairs_add(r.data, t1 * t2, c1 * c2)
|
491 |
+
return normalize(r)
|
492 |
+
|
493 |
+
if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL):
|
494 |
+
return self * as_complex(other)
|
495 |
+
elif other.op is Op.COMPLEX and self.op in (Op.INTEGER, Op.REAL):
|
496 |
+
return as_complex(self) * other
|
497 |
+
elif self.op is Op.REAL and other.op is Op.INTEGER:
|
498 |
+
return self * as_real(other, kind=self.data[1])
|
499 |
+
elif self.op is Op.INTEGER and other.op is Op.REAL:
|
500 |
+
return as_real(self, kind=other.data[1]) * other
|
501 |
+
|
502 |
+
if self.op is Op.TERMS:
|
503 |
+
return self * as_terms(other)
|
504 |
+
elif other.op is Op.TERMS:
|
505 |
+
return as_terms(self) * other
|
506 |
+
|
507 |
+
return as_factors(self) * as_factors(other)
|
508 |
+
return NotImplemented
|
509 |
+
|
510 |
+
def __rmul__(self, other):
|
511 |
+
if isinstance(other, number_types):
|
512 |
+
return as_number(other) * self
|
513 |
+
return NotImplemented
|
514 |
+
|
515 |
+
def __pow__(self, other):
|
516 |
+
other = as_expr(other)
|
517 |
+
if isinstance(other, Expr):
|
518 |
+
if other.op is Op.INTEGER:
|
519 |
+
exponent = other.data[0]
|
520 |
+
# TODO: other kind not used
|
521 |
+
if exponent == 0:
|
522 |
+
return as_number(1)
|
523 |
+
if exponent == 1:
|
524 |
+
return self
|
525 |
+
if exponent > 0:
|
526 |
+
if self.op is Op.FACTORS:
|
527 |
+
r = Expr(self.op, {})
|
528 |
+
for k, v in self.data.items():
|
529 |
+
r.data[k] = v * exponent
|
530 |
+
return normalize(r)
|
531 |
+
return self * (self ** (exponent - 1))
|
532 |
+
elif exponent != -1:
|
533 |
+
return (self ** (-exponent)) ** -1
|
534 |
+
return Expr(Op.FACTORS, {self: exponent})
|
535 |
+
return as_apply(ArithOp.POW, self, other)
|
536 |
+
return NotImplemented
|
537 |
+
|
538 |
+
def __truediv__(self, other):
|
539 |
+
other = as_expr(other)
|
540 |
+
if isinstance(other, Expr):
|
541 |
+
# Fortran / is different from Python /:
|
542 |
+
# - `/` is a truncate operation for integer operands
|
543 |
+
return normalize(as_apply(ArithOp.DIV, self, other))
|
544 |
+
return NotImplemented
|
545 |
+
|
546 |
+
def __rtruediv__(self, other):
|
547 |
+
other = as_expr(other)
|
548 |
+
if isinstance(other, Expr):
|
549 |
+
return other / self
|
550 |
+
return NotImplemented
|
551 |
+
|
552 |
+
def __floordiv__(self, other):
|
553 |
+
other = as_expr(other)
|
554 |
+
if isinstance(other, Expr):
|
555 |
+
# Fortran // is different from Python //:
|
556 |
+
# - `//` is a concatenate operation for string operands
|
557 |
+
return normalize(Expr(Op.CONCAT, (self, other)))
|
558 |
+
return NotImplemented
|
559 |
+
|
560 |
+
def __rfloordiv__(self, other):
|
561 |
+
other = as_expr(other)
|
562 |
+
if isinstance(other, Expr):
|
563 |
+
return other // self
|
564 |
+
return NotImplemented
|
565 |
+
|
566 |
+
def __call__(self, *args, **kwargs):
|
567 |
+
# In Fortran, parenthesis () are use for both function call as
|
568 |
+
# well as indexing operations.
|
569 |
+
#
|
570 |
+
# TODO: implement a method for deciding when __call__ should
|
571 |
+
# return an INDEXING expression.
|
572 |
+
return as_apply(self, *map(as_expr, args),
|
573 |
+
**dict((k, as_expr(v)) for k, v in kwargs.items()))
|
574 |
+
|
575 |
+
def __getitem__(self, index):
|
576 |
+
# Provided to support C indexing operations that .pyf files
|
577 |
+
# may contain.
|
578 |
+
index = as_expr(index)
|
579 |
+
if not isinstance(index, tuple):
|
580 |
+
index = index,
|
581 |
+
if len(index) > 1:
|
582 |
+
ewarn(f'C-index should be a single expression but got `{index}`')
|
583 |
+
return Expr(Op.INDEXING, (self,) + index)
|
584 |
+
|
585 |
+
def substitute(self, symbols_map):
|
586 |
+
"""Recursively substitute symbols with values in symbols map.
|
587 |
+
|
588 |
+
Symbols map is a dictionary of symbol-expression pairs.
|
589 |
+
"""
|
590 |
+
if self.op is Op.SYMBOL:
|
591 |
+
value = symbols_map.get(self)
|
592 |
+
if value is None:
|
593 |
+
return self
|
594 |
+
m = re.match(r'\A(@__f2py_PARENTHESIS_(\w+)_\d+@)\Z', self.data)
|
595 |
+
if m:
|
596 |
+
# complement to fromstring method
|
597 |
+
items, paren = m.groups()
|
598 |
+
if paren in ['ROUNDDIV', 'SQUARE']:
|
599 |
+
return as_array(value)
|
600 |
+
assert paren == 'ROUND', (paren, value)
|
601 |
+
return value
|
602 |
+
if self.op in (Op.INTEGER, Op.REAL, Op.STRING):
|
603 |
+
return self
|
604 |
+
if self.op in (Op.ARRAY, Op.COMPLEX):
|
605 |
+
return Expr(self.op, tuple(item.substitute(symbols_map)
|
606 |
+
for item in self.data))
|
607 |
+
if self.op is Op.CONCAT:
|
608 |
+
return normalize(Expr(self.op, tuple(item.substitute(symbols_map)
|
609 |
+
for item in self.data)))
|
610 |
+
if self.op is Op.TERMS:
|
611 |
+
r = None
|
612 |
+
for term, coeff in self.data.items():
|
613 |
+
if r is None:
|
614 |
+
r = term.substitute(symbols_map) * coeff
|
615 |
+
else:
|
616 |
+
r += term.substitute(symbols_map) * coeff
|
617 |
+
if r is None:
|
618 |
+
ewarn('substitute: empty TERMS expression interpreted as'
|
619 |
+
' int-literal 0')
|
620 |
+
return as_number(0)
|
621 |
+
return r
|
622 |
+
if self.op is Op.FACTORS:
|
623 |
+
r = None
|
624 |
+
for base, exponent in self.data.items():
|
625 |
+
if r is None:
|
626 |
+
r = base.substitute(symbols_map) ** exponent
|
627 |
+
else:
|
628 |
+
r *= base.substitute(symbols_map) ** exponent
|
629 |
+
if r is None:
|
630 |
+
ewarn('substitute: empty FACTORS expression interpreted'
|
631 |
+
' as int-literal 1')
|
632 |
+
return as_number(1)
|
633 |
+
return r
|
634 |
+
if self.op is Op.APPLY:
|
635 |
+
target, args, kwargs = self.data
|
636 |
+
if isinstance(target, Expr):
|
637 |
+
target = target.substitute(symbols_map)
|
638 |
+
args = tuple(a.substitute(symbols_map) for a in args)
|
639 |
+
kwargs = dict((k, v.substitute(symbols_map))
|
640 |
+
for k, v in kwargs.items())
|
641 |
+
return normalize(Expr(self.op, (target, args, kwargs)))
|
642 |
+
if self.op is Op.INDEXING:
|
643 |
+
func = self.data[0]
|
644 |
+
if isinstance(func, Expr):
|
645 |
+
func = func.substitute(symbols_map)
|
646 |
+
args = tuple(a.substitute(symbols_map) for a in self.data[1:])
|
647 |
+
return normalize(Expr(self.op, (func,) + args))
|
648 |
+
if self.op is Op.TERNARY:
|
649 |
+
operands = tuple(a.substitute(symbols_map) for a in self.data)
|
650 |
+
return normalize(Expr(self.op, operands))
|
651 |
+
if self.op in (Op.REF, Op.DEREF):
|
652 |
+
return normalize(Expr(self.op, self.data.substitute(symbols_map)))
|
653 |
+
if self.op is Op.RELATIONAL:
|
654 |
+
rop, left, right = self.data
|
655 |
+
left = left.substitute(symbols_map)
|
656 |
+
right = right.substitute(symbols_map)
|
657 |
+
return normalize(Expr(self.op, (rop, left, right)))
|
658 |
+
raise NotImplementedError(f'substitute method for {self.op}: {self!r}')
|
659 |
+
|
660 |
+
def traverse(self, visit, *args, **kwargs):
|
661 |
+
"""Traverse expression tree with visit function.
|
662 |
+
|
663 |
+
The visit function is applied to an expression with given args
|
664 |
+
and kwargs.
|
665 |
+
|
666 |
+
Traverse call returns an expression returned by visit when not
|
667 |
+
None, otherwise return a new normalized expression with
|
668 |
+
traverse-visit sub-expressions.
|
669 |
+
"""
|
670 |
+
result = visit(self, *args, **kwargs)
|
671 |
+
if result is not None:
|
672 |
+
return result
|
673 |
+
|
674 |
+
if self.op in (Op.INTEGER, Op.REAL, Op.STRING, Op.SYMBOL):
|
675 |
+
return self
|
676 |
+
elif self.op in (Op.COMPLEX, Op.ARRAY, Op.CONCAT, Op.TERNARY):
|
677 |
+
return normalize(Expr(self.op, tuple(
|
678 |
+
item.traverse(visit, *args, **kwargs)
|
679 |
+
for item in self.data)))
|
680 |
+
elif self.op in (Op.TERMS, Op.FACTORS):
|
681 |
+
data = {}
|
682 |
+
for k, v in self.data.items():
|
683 |
+
k = k.traverse(visit, *args, **kwargs)
|
684 |
+
v = (v.traverse(visit, *args, **kwargs)
|
685 |
+
if isinstance(v, Expr) else v)
|
686 |
+
if k in data:
|
687 |
+
v = data[k] + v
|
688 |
+
data[k] = v
|
689 |
+
return normalize(Expr(self.op, data))
|
690 |
+
elif self.op is Op.APPLY:
|
691 |
+
obj = self.data[0]
|
692 |
+
func = (obj.traverse(visit, *args, **kwargs)
|
693 |
+
if isinstance(obj, Expr) else obj)
|
694 |
+
operands = tuple(operand.traverse(visit, *args, **kwargs)
|
695 |
+
for operand in self.data[1])
|
696 |
+
kwoperands = dict((k, v.traverse(visit, *args, **kwargs))
|
697 |
+
for k, v in self.data[2].items())
|
698 |
+
return normalize(Expr(self.op, (func, operands, kwoperands)))
|
699 |
+
elif self.op is Op.INDEXING:
|
700 |
+
obj = self.data[0]
|
701 |
+
obj = (obj.traverse(visit, *args, **kwargs)
|
702 |
+
if isinstance(obj, Expr) else obj)
|
703 |
+
indices = tuple(index.traverse(visit, *args, **kwargs)
|
704 |
+
for index in self.data[1:])
|
705 |
+
return normalize(Expr(self.op, (obj,) + indices))
|
706 |
+
elif self.op in (Op.REF, Op.DEREF):
|
707 |
+
return normalize(Expr(self.op,
|
708 |
+
self.data.traverse(visit, *args, **kwargs)))
|
709 |
+
elif self.op is Op.RELATIONAL:
|
710 |
+
rop, left, right = self.data
|
711 |
+
left = left.traverse(visit, *args, **kwargs)
|
712 |
+
right = right.traverse(visit, *args, **kwargs)
|
713 |
+
return normalize(Expr(self.op, (rop, left, right)))
|
714 |
+
raise NotImplementedError(f'traverse method for {self.op}')
|
715 |
+
|
716 |
+
def contains(self, other):
|
717 |
+
"""Check if self contains other.
|
718 |
+
"""
|
719 |
+
found = []
|
720 |
+
|
721 |
+
def visit(expr, found=found):
|
722 |
+
if found:
|
723 |
+
return expr
|
724 |
+
elif expr == other:
|
725 |
+
found.append(1)
|
726 |
+
return expr
|
727 |
+
|
728 |
+
self.traverse(visit)
|
729 |
+
|
730 |
+
return len(found) != 0
|
731 |
+
|
732 |
+
def symbols(self):
|
733 |
+
"""Return a set of symbols contained in self.
|
734 |
+
"""
|
735 |
+
found = set()
|
736 |
+
|
737 |
+
def visit(expr, found=found):
|
738 |
+
if expr.op is Op.SYMBOL:
|
739 |
+
found.add(expr)
|
740 |
+
|
741 |
+
self.traverse(visit)
|
742 |
+
|
743 |
+
return found
|
744 |
+
|
745 |
+
def polynomial_atoms(self):
|
746 |
+
"""Return a set of expressions used as atoms in polynomial self.
|
747 |
+
"""
|
748 |
+
found = set()
|
749 |
+
|
750 |
+
def visit(expr, found=found):
|
751 |
+
if expr.op is Op.FACTORS:
|
752 |
+
for b in expr.data:
|
753 |
+
b.traverse(visit)
|
754 |
+
return expr
|
755 |
+
if expr.op in (Op.TERMS, Op.COMPLEX):
|
756 |
+
return
|
757 |
+
if expr.op is Op.APPLY and isinstance(expr.data[0], ArithOp):
|
758 |
+
if expr.data[0] is ArithOp.POW:
|
759 |
+
expr.data[1][0].traverse(visit)
|
760 |
+
return expr
|
761 |
+
return
|
762 |
+
if expr.op in (Op.INTEGER, Op.REAL):
|
763 |
+
return expr
|
764 |
+
|
765 |
+
found.add(expr)
|
766 |
+
|
767 |
+
if expr.op in (Op.INDEXING, Op.APPLY):
|
768 |
+
return expr
|
769 |
+
|
770 |
+
self.traverse(visit)
|
771 |
+
|
772 |
+
return found
|
773 |
+
|
774 |
+
def linear_solve(self, symbol):
|
775 |
+
"""Return a, b such that a * symbol + b == self.
|
776 |
+
|
777 |
+
If self is not linear with respect to symbol, raise RuntimeError.
|
778 |
+
"""
|
779 |
+
b = self.substitute({symbol: as_number(0)})
|
780 |
+
ax = self - b
|
781 |
+
a = ax.substitute({symbol: as_number(1)})
|
782 |
+
|
783 |
+
zero, _ = as_numer_denom(a * symbol - ax)
|
784 |
+
|
785 |
+
if zero != as_number(0):
|
786 |
+
raise RuntimeError(f'not a {symbol}-linear equation:'
|
787 |
+
f' {a} * {symbol} + {b} == {self}')
|
788 |
+
return a, b
|
789 |
+
|
790 |
+
|
791 |
+
def normalize(obj):
|
792 |
+
"""Normalize Expr and apply basic evaluation methods.
|
793 |
+
"""
|
794 |
+
if not isinstance(obj, Expr):
|
795 |
+
return obj
|
796 |
+
|
797 |
+
if obj.op is Op.TERMS:
|
798 |
+
d = {}
|
799 |
+
for t, c in obj.data.items():
|
800 |
+
if c == 0:
|
801 |
+
continue
|
802 |
+
if t.op is Op.COMPLEX and c != 1:
|
803 |
+
t = t * c
|
804 |
+
c = 1
|
805 |
+
if t.op is Op.TERMS:
|
806 |
+
for t1, c1 in t.data.items():
|
807 |
+
_pairs_add(d, t1, c1 * c)
|
808 |
+
else:
|
809 |
+
_pairs_add(d, t, c)
|
810 |
+
if len(d) == 0:
|
811 |
+
# TODO: determine correct kind
|
812 |
+
return as_number(0)
|
813 |
+
elif len(d) == 1:
|
814 |
+
(t, c), = d.items()
|
815 |
+
if c == 1:
|
816 |
+
return t
|
817 |
+
return Expr(Op.TERMS, d)
|
818 |
+
|
819 |
+
if obj.op is Op.FACTORS:
|
820 |
+
coeff = 1
|
821 |
+
d = {}
|
822 |
+
for b, e in obj.data.items():
|
823 |
+
if e == 0:
|
824 |
+
continue
|
825 |
+
if b.op is Op.TERMS and isinstance(e, integer_types) and e > 1:
|
826 |
+
# expand integer powers of sums
|
827 |
+
b = b * (b ** (e - 1))
|
828 |
+
e = 1
|
829 |
+
|
830 |
+
if b.op in (Op.INTEGER, Op.REAL):
|
831 |
+
if e == 1:
|
832 |
+
coeff *= b.data[0]
|
833 |
+
elif e > 0:
|
834 |
+
coeff *= b.data[0] ** e
|
835 |
+
else:
|
836 |
+
_pairs_add(d, b, e)
|
837 |
+
elif b.op is Op.FACTORS:
|
838 |
+
if e > 0 and isinstance(e, integer_types):
|
839 |
+
for b1, e1 in b.data.items():
|
840 |
+
_pairs_add(d, b1, e1 * e)
|
841 |
+
else:
|
842 |
+
_pairs_add(d, b, e)
|
843 |
+
else:
|
844 |
+
_pairs_add(d, b, e)
|
845 |
+
if len(d) == 0 or coeff == 0:
|
846 |
+
# TODO: determine correct kind
|
847 |
+
assert isinstance(coeff, number_types)
|
848 |
+
return as_number(coeff)
|
849 |
+
elif len(d) == 1:
|
850 |
+
(b, e), = d.items()
|
851 |
+
if e == 1:
|
852 |
+
t = b
|
853 |
+
else:
|
854 |
+
t = Expr(Op.FACTORS, d)
|
855 |
+
if coeff == 1:
|
856 |
+
return t
|
857 |
+
return Expr(Op.TERMS, {t: coeff})
|
858 |
+
elif coeff == 1:
|
859 |
+
return Expr(Op.FACTORS, d)
|
860 |
+
else:
|
861 |
+
return Expr(Op.TERMS, {Expr(Op.FACTORS, d): coeff})
|
862 |
+
|
863 |
+
if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV:
|
864 |
+
dividend, divisor = obj.data[1]
|
865 |
+
t1, c1 = as_term_coeff(dividend)
|
866 |
+
t2, c2 = as_term_coeff(divisor)
|
867 |
+
if isinstance(c1, integer_types) and isinstance(c2, integer_types):
|
868 |
+
g = gcd(c1, c2)
|
869 |
+
c1, c2 = c1//g, c2//g
|
870 |
+
else:
|
871 |
+
c1, c2 = c1/c2, 1
|
872 |
+
|
873 |
+
if t1.op is Op.APPLY and t1.data[0] is ArithOp.DIV:
|
874 |
+
numer = t1.data[1][0] * c1
|
875 |
+
denom = t1.data[1][1] * t2 * c2
|
876 |
+
return as_apply(ArithOp.DIV, numer, denom)
|
877 |
+
|
878 |
+
if t2.op is Op.APPLY and t2.data[0] is ArithOp.DIV:
|
879 |
+
numer = t2.data[1][1] * t1 * c1
|
880 |
+
denom = t2.data[1][0] * c2
|
881 |
+
return as_apply(ArithOp.DIV, numer, denom)
|
882 |
+
|
883 |
+
d = dict(as_factors(t1).data)
|
884 |
+
for b, e in as_factors(t2).data.items():
|
885 |
+
_pairs_add(d, b, -e)
|
886 |
+
numer, denom = {}, {}
|
887 |
+
for b, e in d.items():
|
888 |
+
if e > 0:
|
889 |
+
numer[b] = e
|
890 |
+
else:
|
891 |
+
denom[b] = -e
|
892 |
+
numer = normalize(Expr(Op.FACTORS, numer)) * c1
|
893 |
+
denom = normalize(Expr(Op.FACTORS, denom)) * c2
|
894 |
+
|
895 |
+
if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] == 1:
|
896 |
+
# TODO: denom kind not used
|
897 |
+
return numer
|
898 |
+
return as_apply(ArithOp.DIV, numer, denom)
|
899 |
+
|
900 |
+
if obj.op is Op.CONCAT:
|
901 |
+
lst = [obj.data[0]]
|
902 |
+
for s in obj.data[1:]:
|
903 |
+
last = lst[-1]
|
904 |
+
if (
|
905 |
+
last.op is Op.STRING
|
906 |
+
and s.op is Op.STRING
|
907 |
+
and last.data[0][0] in '"\''
|
908 |
+
and s.data[0][0] == last.data[0][-1]
|
909 |
+
):
|
910 |
+
new_last = as_string(last.data[0][:-1] + s.data[0][1:],
|
911 |
+
max(last.data[1], s.data[1]))
|
912 |
+
lst[-1] = new_last
|
913 |
+
else:
|
914 |
+
lst.append(s)
|
915 |
+
if len(lst) == 1:
|
916 |
+
return lst[0]
|
917 |
+
return Expr(Op.CONCAT, tuple(lst))
|
918 |
+
|
919 |
+
if obj.op is Op.TERNARY:
|
920 |
+
cond, expr1, expr2 = map(normalize, obj.data)
|
921 |
+
if cond.op is Op.INTEGER:
|
922 |
+
return expr1 if cond.data[0] else expr2
|
923 |
+
return Expr(Op.TERNARY, (cond, expr1, expr2))
|
924 |
+
|
925 |
+
return obj
|
926 |
+
|
927 |
+
|
928 |
+
def as_expr(obj):
|
929 |
+
"""Convert non-Expr objects to Expr objects.
|
930 |
+
"""
|
931 |
+
if isinstance(obj, complex):
|
932 |
+
return as_complex(obj.real, obj.imag)
|
933 |
+
if isinstance(obj, number_types):
|
934 |
+
return as_number(obj)
|
935 |
+
if isinstance(obj, str):
|
936 |
+
# STRING expression holds string with boundary quotes, hence
|
937 |
+
# applying repr:
|
938 |
+
return as_string(repr(obj))
|
939 |
+
if isinstance(obj, tuple):
|
940 |
+
return tuple(map(as_expr, obj))
|
941 |
+
return obj
|
942 |
+
|
943 |
+
|
944 |
+
def as_symbol(obj):
|
945 |
+
"""Return object as SYMBOL expression (variable or unparsed expression).
|
946 |
+
"""
|
947 |
+
return Expr(Op.SYMBOL, obj)
|
948 |
+
|
949 |
+
|
950 |
+
def as_number(obj, kind=4):
|
951 |
+
"""Return object as INTEGER or REAL constant.
|
952 |
+
"""
|
953 |
+
if isinstance(obj, int):
|
954 |
+
return Expr(Op.INTEGER, (obj, kind))
|
955 |
+
if isinstance(obj, float):
|
956 |
+
return Expr(Op.REAL, (obj, kind))
|
957 |
+
if isinstance(obj, Expr):
|
958 |
+
if obj.op in (Op.INTEGER, Op.REAL):
|
959 |
+
return obj
|
960 |
+
raise OpError(f'cannot convert {obj} to INTEGER or REAL constant')
|
961 |
+
|
962 |
+
|
963 |
+
def as_integer(obj, kind=4):
|
964 |
+
"""Return object as INTEGER constant.
|
965 |
+
"""
|
966 |
+
if isinstance(obj, int):
|
967 |
+
return Expr(Op.INTEGER, (obj, kind))
|
968 |
+
if isinstance(obj, Expr):
|
969 |
+
if obj.op is Op.INTEGER:
|
970 |
+
return obj
|
971 |
+
raise OpError(f'cannot convert {obj} to INTEGER constant')
|
972 |
+
|
973 |
+
|
974 |
+
def as_real(obj, kind=4):
|
975 |
+
"""Return object as REAL constant.
|
976 |
+
"""
|
977 |
+
if isinstance(obj, int):
|
978 |
+
return Expr(Op.REAL, (float(obj), kind))
|
979 |
+
if isinstance(obj, float):
|
980 |
+
return Expr(Op.REAL, (obj, kind))
|
981 |
+
if isinstance(obj, Expr):
|
982 |
+
if obj.op is Op.REAL:
|
983 |
+
return obj
|
984 |
+
elif obj.op is Op.INTEGER:
|
985 |
+
return Expr(Op.REAL, (float(obj.data[0]), kind))
|
986 |
+
raise OpError(f'cannot convert {obj} to REAL constant')
|
987 |
+
|
988 |
+
|
989 |
+
def as_string(obj, kind=1):
|
990 |
+
"""Return object as STRING expression (string literal constant).
|
991 |
+
"""
|
992 |
+
return Expr(Op.STRING, (obj, kind))
|
993 |
+
|
994 |
+
|
995 |
+
def as_array(obj):
|
996 |
+
"""Return object as ARRAY expression (array constant).
|
997 |
+
"""
|
998 |
+
if isinstance(obj, Expr):
|
999 |
+
obj = obj,
|
1000 |
+
return Expr(Op.ARRAY, obj)
|
1001 |
+
|
1002 |
+
|
1003 |
+
def as_complex(real, imag=0):
|
1004 |
+
"""Return object as COMPLEX expression (complex literal constant).
|
1005 |
+
"""
|
1006 |
+
return Expr(Op.COMPLEX, (as_expr(real), as_expr(imag)))
|
1007 |
+
|
1008 |
+
|
1009 |
+
def as_apply(func, *args, **kwargs):
|
1010 |
+
"""Return object as APPLY expression (function call, constructor, etc.)
|
1011 |
+
"""
|
1012 |
+
return Expr(Op.APPLY,
|
1013 |
+
(func, tuple(map(as_expr, args)),
|
1014 |
+
dict((k, as_expr(v)) for k, v in kwargs.items())))
|
1015 |
+
|
1016 |
+
|
1017 |
+
def as_ternary(cond, expr1, expr2):
|
1018 |
+
"""Return object as TERNARY expression (cond?expr1:expr2).
|
1019 |
+
"""
|
1020 |
+
return Expr(Op.TERNARY, (cond, expr1, expr2))
|
1021 |
+
|
1022 |
+
|
1023 |
+
def as_ref(expr):
|
1024 |
+
"""Return object as referencing expression.
|
1025 |
+
"""
|
1026 |
+
return Expr(Op.REF, expr)
|
1027 |
+
|
1028 |
+
|
1029 |
+
def as_deref(expr):
|
1030 |
+
"""Return object as dereferencing expression.
|
1031 |
+
"""
|
1032 |
+
return Expr(Op.DEREF, expr)
|
1033 |
+
|
1034 |
+
|
1035 |
+
def as_eq(left, right):
|
1036 |
+
return Expr(Op.RELATIONAL, (RelOp.EQ, left, right))
|
1037 |
+
|
1038 |
+
|
1039 |
+
def as_ne(left, right):
|
1040 |
+
return Expr(Op.RELATIONAL, (RelOp.NE, left, right))
|
1041 |
+
|
1042 |
+
|
1043 |
+
def as_lt(left, right):
|
1044 |
+
return Expr(Op.RELATIONAL, (RelOp.LT, left, right))
|
1045 |
+
|
1046 |
+
|
1047 |
+
def as_le(left, right):
|
1048 |
+
return Expr(Op.RELATIONAL, (RelOp.LE, left, right))
|
1049 |
+
|
1050 |
+
|
1051 |
+
def as_gt(left, right):
|
1052 |
+
return Expr(Op.RELATIONAL, (RelOp.GT, left, right))
|
1053 |
+
|
1054 |
+
|
1055 |
+
def as_ge(left, right):
|
1056 |
+
return Expr(Op.RELATIONAL, (RelOp.GE, left, right))
|
1057 |
+
|
1058 |
+
|
1059 |
+
def as_terms(obj):
|
1060 |
+
"""Return expression as TERMS expression.
|
1061 |
+
"""
|
1062 |
+
if isinstance(obj, Expr):
|
1063 |
+
obj = normalize(obj)
|
1064 |
+
if obj.op is Op.TERMS:
|
1065 |
+
return obj
|
1066 |
+
if obj.op is Op.INTEGER:
|
1067 |
+
return Expr(Op.TERMS, {as_integer(1, obj.data[1]): obj.data[0]})
|
1068 |
+
if obj.op is Op.REAL:
|
1069 |
+
return Expr(Op.TERMS, {as_real(1, obj.data[1]): obj.data[0]})
|
1070 |
+
return Expr(Op.TERMS, {obj: 1})
|
1071 |
+
raise OpError(f'cannot convert {type(obj)} to terms Expr')
|
1072 |
+
|
1073 |
+
|
1074 |
+
def as_factors(obj):
|
1075 |
+
"""Return expression as FACTORS expression.
|
1076 |
+
"""
|
1077 |
+
if isinstance(obj, Expr):
|
1078 |
+
obj = normalize(obj)
|
1079 |
+
if obj.op is Op.FACTORS:
|
1080 |
+
return obj
|
1081 |
+
if obj.op is Op.TERMS:
|
1082 |
+
if len(obj.data) == 1:
|
1083 |
+
(term, coeff), = obj.data.items()
|
1084 |
+
if coeff == 1:
|
1085 |
+
return Expr(Op.FACTORS, {term: 1})
|
1086 |
+
return Expr(Op.FACTORS, {term: 1, Expr.number(coeff): 1})
|
1087 |
+
if ((obj.op is Op.APPLY
|
1088 |
+
and obj.data[0] is ArithOp.DIV
|
1089 |
+
and not obj.data[2])):
|
1090 |
+
return Expr(Op.FACTORS, {obj.data[1][0]: 1, obj.data[1][1]: -1})
|
1091 |
+
return Expr(Op.FACTORS, {obj: 1})
|
1092 |
+
raise OpError(f'cannot convert {type(obj)} to terms Expr')
|
1093 |
+
|
1094 |
+
|
1095 |
+
def as_term_coeff(obj):
|
1096 |
+
"""Return expression as term-coefficient pair.
|
1097 |
+
"""
|
1098 |
+
if isinstance(obj, Expr):
|
1099 |
+
obj = normalize(obj)
|
1100 |
+
if obj.op is Op.INTEGER:
|
1101 |
+
return as_integer(1, obj.data[1]), obj.data[0]
|
1102 |
+
if obj.op is Op.REAL:
|
1103 |
+
return as_real(1, obj.data[1]), obj.data[0]
|
1104 |
+
if obj.op is Op.TERMS:
|
1105 |
+
if len(obj.data) == 1:
|
1106 |
+
(term, coeff), = obj.data.items()
|
1107 |
+
return term, coeff
|
1108 |
+
# TODO: find common divisor of coefficients
|
1109 |
+
if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV:
|
1110 |
+
t, c = as_term_coeff(obj.data[1][0])
|
1111 |
+
return as_apply(ArithOp.DIV, t, obj.data[1][1]), c
|
1112 |
+
return obj, 1
|
1113 |
+
raise OpError(f'cannot convert {type(obj)} to term and coeff')
|
1114 |
+
|
1115 |
+
|
1116 |
+
def as_numer_denom(obj):
|
1117 |
+
"""Return expression as numer-denom pair.
|
1118 |
+
"""
|
1119 |
+
if isinstance(obj, Expr):
|
1120 |
+
obj = normalize(obj)
|
1121 |
+
if obj.op in (Op.INTEGER, Op.REAL, Op.COMPLEX, Op.SYMBOL,
|
1122 |
+
Op.INDEXING, Op.TERNARY):
|
1123 |
+
return obj, as_number(1)
|
1124 |
+
elif obj.op is Op.APPLY:
|
1125 |
+
if obj.data[0] is ArithOp.DIV and not obj.data[2]:
|
1126 |
+
numers, denoms = map(as_numer_denom, obj.data[1])
|
1127 |
+
return numers[0] * denoms[1], numers[1] * denoms[0]
|
1128 |
+
return obj, as_number(1)
|
1129 |
+
elif obj.op is Op.TERMS:
|
1130 |
+
numers, denoms = [], []
|
1131 |
+
for term, coeff in obj.data.items():
|
1132 |
+
n, d = as_numer_denom(term)
|
1133 |
+
n = n * coeff
|
1134 |
+
numers.append(n)
|
1135 |
+
denoms.append(d)
|
1136 |
+
numer, denom = as_number(0), as_number(1)
|
1137 |
+
for i in range(len(numers)):
|
1138 |
+
n = numers[i]
|
1139 |
+
for j in range(len(numers)):
|
1140 |
+
if i != j:
|
1141 |
+
n *= denoms[j]
|
1142 |
+
numer += n
|
1143 |
+
denom *= denoms[i]
|
1144 |
+
if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] < 0:
|
1145 |
+
numer, denom = -numer, -denom
|
1146 |
+
return numer, denom
|
1147 |
+
elif obj.op is Op.FACTORS:
|
1148 |
+
numer, denom = as_number(1), as_number(1)
|
1149 |
+
for b, e in obj.data.items():
|
1150 |
+
bnumer, bdenom = as_numer_denom(b)
|
1151 |
+
if e > 0:
|
1152 |
+
numer *= bnumer ** e
|
1153 |
+
denom *= bdenom ** e
|
1154 |
+
elif e < 0:
|
1155 |
+
numer *= bdenom ** (-e)
|
1156 |
+
denom *= bnumer ** (-e)
|
1157 |
+
return numer, denom
|
1158 |
+
raise OpError(f'cannot convert {type(obj)} to numer and denom')
|
1159 |
+
|
1160 |
+
|
1161 |
+
def _counter():
|
1162 |
+
# Used internally to generate unique dummy symbols
|
1163 |
+
counter = 0
|
1164 |
+
while True:
|
1165 |
+
counter += 1
|
1166 |
+
yield counter
|
1167 |
+
|
1168 |
+
|
1169 |
+
COUNTER = _counter()
|
1170 |
+
|
1171 |
+
|
1172 |
+
def eliminate_quotes(s):
|
1173 |
+
"""Replace quoted substrings of input string.
|
1174 |
+
|
1175 |
+
Return a new string and a mapping of replacements.
|
1176 |
+
"""
|
1177 |
+
d = {}
|
1178 |
+
|
1179 |
+
def repl(m):
|
1180 |
+
kind, value = m.groups()[:2]
|
1181 |
+
if kind:
|
1182 |
+
# remove trailing underscore
|
1183 |
+
kind = kind[:-1]
|
1184 |
+
p = {"'": "SINGLE", '"': "DOUBLE"}[value[0]]
|
1185 |
+
k = f'{kind}@__f2py_QUOTES_{p}_{COUNTER.__next__()}@'
|
1186 |
+
d[k] = value
|
1187 |
+
return k
|
1188 |
+
|
1189 |
+
new_s = re.sub(r'({kind}_|)({single_quoted}|{double_quoted})'.format(
|
1190 |
+
kind=r'\w[\w\d_]*',
|
1191 |
+
single_quoted=r"('([^'\\]|(\\.))*')",
|
1192 |
+
double_quoted=r'("([^"\\]|(\\.))*")'),
|
1193 |
+
repl, s)
|
1194 |
+
|
1195 |
+
assert '"' not in new_s
|
1196 |
+
assert "'" not in new_s
|
1197 |
+
|
1198 |
+
return new_s, d
|
1199 |
+
|
1200 |
+
|
1201 |
+
def insert_quotes(s, d):
|
1202 |
+
"""Inverse of eliminate_quotes.
|
1203 |
+
"""
|
1204 |
+
for k, v in d.items():
|
1205 |
+
kind = k[:k.find('@')]
|
1206 |
+
if kind:
|
1207 |
+
kind += '_'
|
1208 |
+
s = s.replace(k, kind + v)
|
1209 |
+
return s
|
1210 |
+
|
1211 |
+
|
1212 |
+
def replace_parenthesis(s):
|
1213 |
+
"""Replace substrings of input that are enclosed in parenthesis.
|
1214 |
+
|
1215 |
+
Return a new string and a mapping of replacements.
|
1216 |
+
"""
|
1217 |
+
# Find a parenthesis pair that appears first.
|
1218 |
+
|
1219 |
+
# Fortran deliminator are `(`, `)`, `[`, `]`, `(/', '/)`, `/`.
|
1220 |
+
# We don't handle `/` deliminator because it is not a part of an
|
1221 |
+
# expression.
|
1222 |
+
left, right = None, None
|
1223 |
+
mn_i = len(s)
|
1224 |
+
for left_, right_ in (('(/', '/)'),
|
1225 |
+
'()',
|
1226 |
+
'{}', # to support C literal structs
|
1227 |
+
'[]'):
|
1228 |
+
i = s.find(left_)
|
1229 |
+
if i == -1:
|
1230 |
+
continue
|
1231 |
+
if i < mn_i:
|
1232 |
+
mn_i = i
|
1233 |
+
left, right = left_, right_
|
1234 |
+
|
1235 |
+
if left is None:
|
1236 |
+
return s, {}
|
1237 |
+
|
1238 |
+
i = mn_i
|
1239 |
+
j = s.find(right, i)
|
1240 |
+
|
1241 |
+
while s.count(left, i + 1, j) != s.count(right, i + 1, j):
|
1242 |
+
j = s.find(right, j + 1)
|
1243 |
+
if j == -1:
|
1244 |
+
raise ValueError(f'Mismatch of {left+right} parenthesis in {s!r}')
|
1245 |
+
|
1246 |
+
p = {'(': 'ROUND', '[': 'SQUARE', '{': 'CURLY', '(/': 'ROUNDDIV'}[left]
|
1247 |
+
|
1248 |
+
k = f'@__f2py_PARENTHESIS_{p}_{COUNTER.__next__()}@'
|
1249 |
+
v = s[i+len(left):j]
|
1250 |
+
r, d = replace_parenthesis(s[j+len(right):])
|
1251 |
+
d[k] = v
|
1252 |
+
return s[:i] + k + r, d
|
1253 |
+
|
1254 |
+
|
1255 |
+
def _get_parenthesis_kind(s):
|
1256 |
+
assert s.startswith('@__f2py_PARENTHESIS_'), s
|
1257 |
+
return s.split('_')[4]
|
1258 |
+
|
1259 |
+
|
1260 |
+
def unreplace_parenthesis(s, d):
|
1261 |
+
"""Inverse of replace_parenthesis.
|
1262 |
+
"""
|
1263 |
+
for k, v in d.items():
|
1264 |
+
p = _get_parenthesis_kind(k)
|
1265 |
+
left = dict(ROUND='(', SQUARE='[', CURLY='{', ROUNDDIV='(/')[p]
|
1266 |
+
right = dict(ROUND=')', SQUARE=']', CURLY='}', ROUNDDIV='/)')[p]
|
1267 |
+
s = s.replace(k, left + v + right)
|
1268 |
+
return s
|
1269 |
+
|
1270 |
+
|
1271 |
+
def fromstring(s, language=Language.C):
|
1272 |
+
"""Create an expression from a string.
|
1273 |
+
|
1274 |
+
This is a "lazy" parser, that is, only arithmetic operations are
|
1275 |
+
resolved, non-arithmetic operations are treated as symbols.
|
1276 |
+
"""
|
1277 |
+
r = _FromStringWorker(language=language).parse(s)
|
1278 |
+
if isinstance(r, Expr):
|
1279 |
+
return r
|
1280 |
+
raise ValueError(f'failed to parse `{s}` to Expr instance: got `{r}`')
|
1281 |
+
|
1282 |
+
|
1283 |
+
class _Pair:
|
1284 |
+
# Internal class to represent a pair of expressions
|
1285 |
+
|
1286 |
+
def __init__(self, left, right):
|
1287 |
+
self.left = left
|
1288 |
+
self.right = right
|
1289 |
+
|
1290 |
+
def substitute(self, symbols_map):
|
1291 |
+
left, right = self.left, self.right
|
1292 |
+
if isinstance(left, Expr):
|
1293 |
+
left = left.substitute(symbols_map)
|
1294 |
+
if isinstance(right, Expr):
|
1295 |
+
right = right.substitute(symbols_map)
|
1296 |
+
return _Pair(left, right)
|
1297 |
+
|
1298 |
+
def __repr__(self):
|
1299 |
+
return f'{type(self).__name__}({self.left}, {self.right})'
|
1300 |
+
|
1301 |
+
|
1302 |
+
class _FromStringWorker:
|
1303 |
+
|
1304 |
+
def __init__(self, language=Language.C):
|
1305 |
+
self.original = None
|
1306 |
+
self.quotes_map = None
|
1307 |
+
self.language = language
|
1308 |
+
|
1309 |
+
def finalize_string(self, s):
|
1310 |
+
return insert_quotes(s, self.quotes_map)
|
1311 |
+
|
1312 |
+
def parse(self, inp):
|
1313 |
+
self.original = inp
|
1314 |
+
unquoted, self.quotes_map = eliminate_quotes(inp)
|
1315 |
+
return self.process(unquoted)
|
1316 |
+
|
1317 |
+
def process(self, s, context='expr'):
|
1318 |
+
"""Parse string within the given context.
|
1319 |
+
|
1320 |
+
The context may define the result in case of ambiguous
|
1321 |
+
expressions. For instance, consider expressions `f(x, y)` and
|
1322 |
+
`(x, y) + (a, b)` where `f` is a function and pair `(x, y)`
|
1323 |
+
denotes complex number. Specifying context as "args" or
|
1324 |
+
"expr", the subexpression `(x, y)` will be parse to an
|
1325 |
+
argument list or to a complex number, respectively.
|
1326 |
+
"""
|
1327 |
+
if isinstance(s, (list, tuple)):
|
1328 |
+
return type(s)(self.process(s_, context) for s_ in s)
|
1329 |
+
|
1330 |
+
assert isinstance(s, str), (type(s), s)
|
1331 |
+
|
1332 |
+
# replace subexpressions in parenthesis with f2py @-names
|
1333 |
+
r, raw_symbols_map = replace_parenthesis(s)
|
1334 |
+
r = r.strip()
|
1335 |
+
|
1336 |
+
def restore(r):
|
1337 |
+
# restores subexpressions marked with f2py @-names
|
1338 |
+
if isinstance(r, (list, tuple)):
|
1339 |
+
return type(r)(map(restore, r))
|
1340 |
+
return unreplace_parenthesis(r, raw_symbols_map)
|
1341 |
+
|
1342 |
+
# comma-separated tuple
|
1343 |
+
if ',' in r:
|
1344 |
+
operands = restore(r.split(','))
|
1345 |
+
if context == 'args':
|
1346 |
+
return tuple(self.process(operands))
|
1347 |
+
if context == 'expr':
|
1348 |
+
if len(operands) == 2:
|
1349 |
+
# complex number literal
|
1350 |
+
return as_complex(*self.process(operands))
|
1351 |
+
raise NotImplementedError(
|
1352 |
+
f'parsing comma-separated list (context={context}): {r}')
|
1353 |
+
|
1354 |
+
# ternary operation
|
1355 |
+
m = re.match(r'\A([^?]+)[?]([^:]+)[:](.+)\Z', r)
|
1356 |
+
if m:
|
1357 |
+
assert context == 'expr', context
|
1358 |
+
oper, expr1, expr2 = restore(m.groups())
|
1359 |
+
oper = self.process(oper)
|
1360 |
+
expr1 = self.process(expr1)
|
1361 |
+
expr2 = self.process(expr2)
|
1362 |
+
return as_ternary(oper, expr1, expr2)
|
1363 |
+
|
1364 |
+
# relational expression
|
1365 |
+
if self.language is Language.Fortran:
|
1366 |
+
m = re.match(
|
1367 |
+
r'\A(.+)\s*[.](eq|ne|lt|le|gt|ge)[.]\s*(.+)\Z', r, re.I)
|
1368 |
+
else:
|
1369 |
+
m = re.match(
|
1370 |
+
r'\A(.+)\s*([=][=]|[!][=]|[<][=]|[<]|[>][=]|[>])\s*(.+)\Z', r)
|
1371 |
+
if m:
|
1372 |
+
left, rop, right = m.groups()
|
1373 |
+
if self.language is Language.Fortran:
|
1374 |
+
rop = '.' + rop + '.'
|
1375 |
+
left, right = self.process(restore((left, right)))
|
1376 |
+
rop = RelOp.fromstring(rop, language=self.language)
|
1377 |
+
return Expr(Op.RELATIONAL, (rop, left, right))
|
1378 |
+
|
1379 |
+
# keyword argument
|
1380 |
+
m = re.match(r'\A(\w[\w\d_]*)\s*[=](.*)\Z', r)
|
1381 |
+
if m:
|
1382 |
+
keyname, value = m.groups()
|
1383 |
+
value = restore(value)
|
1384 |
+
return _Pair(keyname, self.process(value))
|
1385 |
+
|
1386 |
+
# addition/subtraction operations
|
1387 |
+
operands = re.split(r'((?<!\d[edED])[+-])', r)
|
1388 |
+
if len(operands) > 1:
|
1389 |
+
result = self.process(restore(operands[0] or '0'))
|
1390 |
+
for op, operand in zip(operands[1::2], operands[2::2]):
|
1391 |
+
operand = self.process(restore(operand))
|
1392 |
+
op = op.strip()
|
1393 |
+
if op == '+':
|
1394 |
+
result += operand
|
1395 |
+
else:
|
1396 |
+
assert op == '-'
|
1397 |
+
result -= operand
|
1398 |
+
return result
|
1399 |
+
|
1400 |
+
# string concatenate operation
|
1401 |
+
if self.language is Language.Fortran and '//' in r:
|
1402 |
+
operands = restore(r.split('//'))
|
1403 |
+
return Expr(Op.CONCAT,
|
1404 |
+
tuple(self.process(operands)))
|
1405 |
+
|
1406 |
+
# multiplication/division operations
|
1407 |
+
operands = re.split(r'(?<=[@\w\d_])\s*([*]|/)',
|
1408 |
+
(r if self.language is Language.C
|
1409 |
+
else r.replace('**', '@__f2py_DOUBLE_STAR@')))
|
1410 |
+
if len(operands) > 1:
|
1411 |
+
operands = restore(operands)
|
1412 |
+
if self.language is not Language.C:
|
1413 |
+
operands = [operand.replace('@__f2py_DOUBLE_STAR@', '**')
|
1414 |
+
for operand in operands]
|
1415 |
+
# Expression is an arithmetic product
|
1416 |
+
result = self.process(operands[0])
|
1417 |
+
for op, operand in zip(operands[1::2], operands[2::2]):
|
1418 |
+
operand = self.process(operand)
|
1419 |
+
op = op.strip()
|
1420 |
+
if op == '*':
|
1421 |
+
result *= operand
|
1422 |
+
else:
|
1423 |
+
assert op == '/'
|
1424 |
+
result /= operand
|
1425 |
+
return result
|
1426 |
+
|
1427 |
+
# referencing/dereferencing
|
1428 |
+
if r.startswith('*') or r.startswith('&'):
|
1429 |
+
op = {'*': Op.DEREF, '&': Op.REF}[r[0]]
|
1430 |
+
operand = self.process(restore(r[1:]))
|
1431 |
+
return Expr(op, operand)
|
1432 |
+
|
1433 |
+
# exponentiation operations
|
1434 |
+
if self.language is not Language.C and '**' in r:
|
1435 |
+
operands = list(reversed(restore(r.split('**'))))
|
1436 |
+
result = self.process(operands[0])
|
1437 |
+
for operand in operands[1:]:
|
1438 |
+
operand = self.process(operand)
|
1439 |
+
result = operand ** result
|
1440 |
+
return result
|
1441 |
+
|
1442 |
+
# int-literal-constant
|
1443 |
+
m = re.match(r'\A({digit_string})({kind}|)\Z'.format(
|
1444 |
+
digit_string=r'\d+',
|
1445 |
+
kind=r'_(\d+|\w[\w\d_]*)'), r)
|
1446 |
+
if m:
|
1447 |
+
value, _, kind = m.groups()
|
1448 |
+
if kind and kind.isdigit():
|
1449 |
+
kind = int(kind)
|
1450 |
+
return as_integer(int(value), kind or 4)
|
1451 |
+
|
1452 |
+
# real-literal-constant
|
1453 |
+
m = re.match(r'\A({significant}({exponent}|)|\d+{exponent})({kind}|)\Z'
|
1454 |
+
.format(
|
1455 |
+
significant=r'[.]\d+|\d+[.]\d*',
|
1456 |
+
exponent=r'[edED][+-]?\d+',
|
1457 |
+
kind=r'_(\d+|\w[\w\d_]*)'), r)
|
1458 |
+
if m:
|
1459 |
+
value, _, _, kind = m.groups()
|
1460 |
+
if kind and kind.isdigit():
|
1461 |
+
kind = int(kind)
|
1462 |
+
value = value.lower()
|
1463 |
+
if 'd' in value:
|
1464 |
+
return as_real(float(value.replace('d', 'e')), kind or 8)
|
1465 |
+
return as_real(float(value), kind or 4)
|
1466 |
+
|
1467 |
+
# string-literal-constant with kind parameter specification
|
1468 |
+
if r in self.quotes_map:
|
1469 |
+
kind = r[:r.find('@')]
|
1470 |
+
return as_string(self.quotes_map[r], kind or 1)
|
1471 |
+
|
1472 |
+
# array constructor or literal complex constant or
|
1473 |
+
# parenthesized expression
|
1474 |
+
if r in raw_symbols_map:
|
1475 |
+
paren = _get_parenthesis_kind(r)
|
1476 |
+
items = self.process(restore(raw_symbols_map[r]),
|
1477 |
+
'expr' if paren == 'ROUND' else 'args')
|
1478 |
+
if paren == 'ROUND':
|
1479 |
+
if isinstance(items, Expr):
|
1480 |
+
return items
|
1481 |
+
if paren in ['ROUNDDIV', 'SQUARE']:
|
1482 |
+
# Expression is a array constructor
|
1483 |
+
if isinstance(items, Expr):
|
1484 |
+
items = (items,)
|
1485 |
+
return as_array(items)
|
1486 |
+
|
1487 |
+
# function call/indexing
|
1488 |
+
m = re.match(r'\A(.+)\s*(@__f2py_PARENTHESIS_(ROUND|SQUARE)_\d+@)\Z',
|
1489 |
+
r)
|
1490 |
+
if m:
|
1491 |
+
target, args, paren = m.groups()
|
1492 |
+
target = self.process(restore(target))
|
1493 |
+
args = self.process(restore(args)[1:-1], 'args')
|
1494 |
+
if not isinstance(args, tuple):
|
1495 |
+
args = args,
|
1496 |
+
if paren == 'ROUND':
|
1497 |
+
kwargs = dict((a.left, a.right) for a in args
|
1498 |
+
if isinstance(a, _Pair))
|
1499 |
+
args = tuple(a for a in args if not isinstance(a, _Pair))
|
1500 |
+
# Warning: this could also be Fortran indexing operation..
|
1501 |
+
return as_apply(target, *args, **kwargs)
|
1502 |
+
else:
|
1503 |
+
# Expression is a C/Python indexing operation
|
1504 |
+
# (e.g. used in .pyf files)
|
1505 |
+
assert paren == 'SQUARE'
|
1506 |
+
return target[args]
|
1507 |
+
|
1508 |
+
# Fortran standard conforming identifier
|
1509 |
+
m = re.match(r'\A\w[\w\d_]*\Z', r)
|
1510 |
+
if m:
|
1511 |
+
return as_symbol(r)
|
1512 |
+
|
1513 |
+
# fall-back to symbol
|
1514 |
+
r = self.finalize_string(restore(r))
|
1515 |
+
ewarn(
|
1516 |
+
f'fromstring: treating {r!r} as symbol (original={self.original})')
|
1517 |
+
return as_symbol(r)
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/src/parameter/constant_both.f90
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
! Check that parameters are correct intercepted.
|
2 |
+
! Constants with comma separations are commonly
|
3 |
+
! used, for instance Pi = 3._dp
|
4 |
+
subroutine foo(x)
|
5 |
+
implicit none
|
6 |
+
integer, parameter :: sp = selected_real_kind(6)
|
7 |
+
integer, parameter :: dp = selected_real_kind(15)
|
8 |
+
integer, parameter :: ii = selected_int_kind(9)
|
9 |
+
integer, parameter :: il = selected_int_kind(18)
|
10 |
+
real(dp), intent(inout) :: x
|
11 |
+
dimension x(3)
|
12 |
+
real(sp), parameter :: three_s = 3._sp
|
13 |
+
real(dp), parameter :: three_d = 3._dp
|
14 |
+
integer(ii), parameter :: three_i = 3_ii
|
15 |
+
integer(il), parameter :: three_l = 3_il
|
16 |
+
x(1) = x(1) + x(2) * three_s * three_i + x(3) * three_d * three_l
|
17 |
+
x(2) = x(2) * three_s
|
18 |
+
x(3) = x(3) * three_l
|
19 |
+
return
|
20 |
+
end subroutine
|
21 |
+
|
22 |
+
|
23 |
+
subroutine foo_no(x)
|
24 |
+
implicit none
|
25 |
+
integer, parameter :: sp = selected_real_kind(6)
|
26 |
+
integer, parameter :: dp = selected_real_kind(15)
|
27 |
+
integer, parameter :: ii = selected_int_kind(9)
|
28 |
+
integer, parameter :: il = selected_int_kind(18)
|
29 |
+
real(dp), intent(inout) :: x
|
30 |
+
dimension x(3)
|
31 |
+
real(sp), parameter :: three_s = 3.
|
32 |
+
real(dp), parameter :: three_d = 3.
|
33 |
+
integer(ii), parameter :: three_i = 3
|
34 |
+
integer(il), parameter :: three_l = 3
|
35 |
+
x(1) = x(1) + x(2) * three_s * three_i + x(3) * three_d * three_l
|
36 |
+
x(2) = x(2) * three_s
|
37 |
+
x(3) = x(3) * three_l
|
38 |
+
return
|
39 |
+
end subroutine
|
40 |
+
|
41 |
+
subroutine foo_sum(x)
|
42 |
+
implicit none
|
43 |
+
integer, parameter :: sp = selected_real_kind(6)
|
44 |
+
integer, parameter :: dp = selected_real_kind(15)
|
45 |
+
integer, parameter :: ii = selected_int_kind(9)
|
46 |
+
integer, parameter :: il = selected_int_kind(18)
|
47 |
+
real(dp), intent(inout) :: x
|
48 |
+
dimension x(3)
|
49 |
+
real(sp), parameter :: three_s = 2._sp + 1._sp
|
50 |
+
real(dp), parameter :: three_d = 1._dp + 2._dp
|
51 |
+
integer(ii), parameter :: three_i = 2_ii + 1_ii
|
52 |
+
integer(il), parameter :: three_l = 1_il + 2_il
|
53 |
+
x(1) = x(1) + x(2) * three_s * three_i + x(3) * three_d * three_l
|
54 |
+
x(2) = x(2) * three_s
|
55 |
+
x(3) = x(3) * three_l
|
56 |
+
return
|
57 |
+
end subroutine
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/src/parameter/constant_compound.f90
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
! Check that parameters are correct intercepted.
|
2 |
+
! Constants with comma separations are commonly
|
3 |
+
! used, for instance Pi = 3._dp
|
4 |
+
subroutine foo_compound_int(x)
|
5 |
+
implicit none
|
6 |
+
integer, parameter :: ii = selected_int_kind(9)
|
7 |
+
integer(ii), intent(inout) :: x
|
8 |
+
dimension x(3)
|
9 |
+
integer(ii), parameter :: three = 3_ii
|
10 |
+
integer(ii), parameter :: two = 2_ii
|
11 |
+
integer(ii), parameter :: six = three * 1_ii * two
|
12 |
+
|
13 |
+
x(1) = x(1) + x(2) + x(3) * six
|
14 |
+
return
|
15 |
+
end subroutine
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/src/parameter/constant_integer.f90
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
! Check that parameters are correct intercepted.
|
2 |
+
! Constants with comma separations are commonly
|
3 |
+
! used, for instance Pi = 3._dp
|
4 |
+
subroutine foo_int(x)
|
5 |
+
implicit none
|
6 |
+
integer, parameter :: ii = selected_int_kind(9)
|
7 |
+
integer(ii), intent(inout) :: x
|
8 |
+
dimension x(3)
|
9 |
+
integer(ii), parameter :: three = 3_ii
|
10 |
+
x(1) = x(1) + x(2) + x(3) * three
|
11 |
+
return
|
12 |
+
end subroutine
|
13 |
+
|
14 |
+
subroutine foo_long(x)
|
15 |
+
implicit none
|
16 |
+
integer, parameter :: ii = selected_int_kind(18)
|
17 |
+
integer(ii), intent(inout) :: x
|
18 |
+
dimension x(3)
|
19 |
+
integer(ii), parameter :: three = 3_ii
|
20 |
+
x(1) = x(1) + x(2) + x(3) * three
|
21 |
+
return
|
22 |
+
end subroutine
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/src/parameter/constant_non_compound.f90
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
! Check that parameters are correct intercepted.
|
2 |
+
! Specifically that types of constants without
|
3 |
+
! compound kind specs are correctly inferred
|
4 |
+
! adapted Gibbs iteration code from pymc
|
5 |
+
! for this test case
|
6 |
+
subroutine foo_non_compound_int(x)
|
7 |
+
implicit none
|
8 |
+
integer, parameter :: ii = selected_int_kind(9)
|
9 |
+
|
10 |
+
integer(ii) maxiterates
|
11 |
+
parameter (maxiterates=2)
|
12 |
+
|
13 |
+
integer(ii) maxseries
|
14 |
+
parameter (maxseries=2)
|
15 |
+
|
16 |
+
integer(ii) wasize
|
17 |
+
parameter (wasize=maxiterates*maxseries)
|
18 |
+
integer(ii), intent(inout) :: x
|
19 |
+
dimension x(wasize)
|
20 |
+
|
21 |
+
x(1) = x(1) + x(2) + x(3) + x(4) * wasize
|
22 |
+
return
|
23 |
+
end subroutine
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/src/parameter/constant_real.f90
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
! Check that parameters are correct intercepted.
|
2 |
+
! Constants with comma separations are commonly
|
3 |
+
! used, for instance Pi = 3._dp
|
4 |
+
subroutine foo_single(x)
|
5 |
+
implicit none
|
6 |
+
integer, parameter :: rp = selected_real_kind(6)
|
7 |
+
real(rp), intent(inout) :: x
|
8 |
+
dimension x(3)
|
9 |
+
real(rp), parameter :: three = 3._rp
|
10 |
+
x(1) = x(1) + x(2) + x(3) * three
|
11 |
+
return
|
12 |
+
end subroutine
|
13 |
+
|
14 |
+
subroutine foo_double(x)
|
15 |
+
implicit none
|
16 |
+
integer, parameter :: rp = selected_real_kind(15)
|
17 |
+
real(rp), intent(inout) :: x
|
18 |
+
dimension x(3)
|
19 |
+
real(rp), parameter :: three = 3._rp
|
20 |
+
x(1) = x(1) + x(2) + x(3) * three
|
21 |
+
return
|
22 |
+
end subroutine
|
23 |
+
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/test_abstract_interface.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pathlib import Path
|
2 |
+
import pytest
|
3 |
+
import textwrap
|
4 |
+
from . import util
|
5 |
+
from numpy.f2py import crackfortran
|
6 |
+
from numpy.testing import IS_WASM
|
7 |
+
|
8 |
+
|
9 |
+
@pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
|
10 |
+
class TestAbstractInterface(util.F2PyTest):
|
11 |
+
sources = [util.getpath("tests", "src", "abstract_interface", "foo.f90")]
|
12 |
+
|
13 |
+
skip = ["add1", "add2"]
|
14 |
+
|
15 |
+
def test_abstract_interface(self):
|
16 |
+
assert self.module.ops_module.foo(3, 5) == (8, 13)
|
17 |
+
|
18 |
+
def test_parse_abstract_interface(self):
|
19 |
+
# Test gh18403
|
20 |
+
fpath = util.getpath("tests", "src", "abstract_interface",
|
21 |
+
"gh18403_mod.f90")
|
22 |
+
mod = crackfortran.crackfortran([str(fpath)])
|
23 |
+
assert len(mod) == 1
|
24 |
+
assert len(mod[0]["body"]) == 1
|
25 |
+
assert mod[0]["body"][0]["block"] == "abstract interface"
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/test_array_from_pyobj.py
ADDED
@@ -0,0 +1,686 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import copy
|
4 |
+
import platform
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from numpy.testing import assert_, assert_equal
|
10 |
+
from numpy.core.multiarray import typeinfo as _typeinfo
|
11 |
+
from . import util
|
12 |
+
|
13 |
+
wrap = None
|
14 |
+
|
15 |
+
# Extend core typeinfo with CHARACTER to test dtype('c')
|
16 |
+
_ti = _typeinfo['STRING']
|
17 |
+
typeinfo = dict(
|
18 |
+
CHARACTER=type(_ti)(('c', _ti.num, 8, _ti.alignment, _ti.type)),
|
19 |
+
**_typeinfo)
|
20 |
+
|
21 |
+
|
22 |
+
def setup_module():
|
23 |
+
"""
|
24 |
+
Build the required testing extension module
|
25 |
+
|
26 |
+
"""
|
27 |
+
global wrap
|
28 |
+
|
29 |
+
# Check compiler availability first
|
30 |
+
if not util.has_c_compiler():
|
31 |
+
pytest.skip("No C compiler available")
|
32 |
+
|
33 |
+
if wrap is None:
|
34 |
+
config_code = """
|
35 |
+
config.add_extension('test_array_from_pyobj_ext',
|
36 |
+
sources=['wrapmodule.c', 'fortranobject.c'],
|
37 |
+
define_macros=[])
|
38 |
+
"""
|
39 |
+
d = os.path.dirname(__file__)
|
40 |
+
src = [
|
41 |
+
util.getpath("tests", "src", "array_from_pyobj", "wrapmodule.c"),
|
42 |
+
util.getpath("src", "fortranobject.c"),
|
43 |
+
util.getpath("src", "fortranobject.h"),
|
44 |
+
]
|
45 |
+
wrap = util.build_module_distutils(src, config_code,
|
46 |
+
"test_array_from_pyobj_ext")
|
47 |
+
|
48 |
+
|
49 |
+
def flags_info(arr):
|
50 |
+
flags = wrap.array_attrs(arr)[6]
|
51 |
+
return flags2names(flags)
|
52 |
+
|
53 |
+
|
54 |
+
def flags2names(flags):
|
55 |
+
info = []
|
56 |
+
for flagname in [
|
57 |
+
"CONTIGUOUS",
|
58 |
+
"FORTRAN",
|
59 |
+
"OWNDATA",
|
60 |
+
"ENSURECOPY",
|
61 |
+
"ENSUREARRAY",
|
62 |
+
"ALIGNED",
|
63 |
+
"NOTSWAPPED",
|
64 |
+
"WRITEABLE",
|
65 |
+
"WRITEBACKIFCOPY",
|
66 |
+
"UPDATEIFCOPY",
|
67 |
+
"BEHAVED",
|
68 |
+
"BEHAVED_RO",
|
69 |
+
"CARRAY",
|
70 |
+
"FARRAY",
|
71 |
+
]:
|
72 |
+
if abs(flags) & getattr(wrap, flagname, 0):
|
73 |
+
info.append(flagname)
|
74 |
+
return info
|
75 |
+
|
76 |
+
|
77 |
+
class Intent:
|
78 |
+
def __init__(self, intent_list=[]):
|
79 |
+
self.intent_list = intent_list[:]
|
80 |
+
flags = 0
|
81 |
+
for i in intent_list:
|
82 |
+
if i == "optional":
|
83 |
+
flags |= wrap.F2PY_OPTIONAL
|
84 |
+
else:
|
85 |
+
flags |= getattr(wrap, "F2PY_INTENT_" + i.upper())
|
86 |
+
self.flags = flags
|
87 |
+
|
88 |
+
def __getattr__(self, name):
|
89 |
+
name = name.lower()
|
90 |
+
if name == "in_":
|
91 |
+
name = "in"
|
92 |
+
return self.__class__(self.intent_list + [name])
|
93 |
+
|
94 |
+
def __str__(self):
|
95 |
+
return "intent(%s)" % (",".join(self.intent_list))
|
96 |
+
|
97 |
+
def __repr__(self):
|
98 |
+
return "Intent(%r)" % (self.intent_list)
|
99 |
+
|
100 |
+
def is_intent(self, *names):
|
101 |
+
for name in names:
|
102 |
+
if name not in self.intent_list:
|
103 |
+
return False
|
104 |
+
return True
|
105 |
+
|
106 |
+
def is_intent_exact(self, *names):
|
107 |
+
return len(self.intent_list) == len(names) and self.is_intent(*names)
|
108 |
+
|
109 |
+
|
110 |
+
intent = Intent()
|
111 |
+
|
112 |
+
_type_names = [
|
113 |
+
"BOOL",
|
114 |
+
"BYTE",
|
115 |
+
"UBYTE",
|
116 |
+
"SHORT",
|
117 |
+
"USHORT",
|
118 |
+
"INT",
|
119 |
+
"UINT",
|
120 |
+
"LONG",
|
121 |
+
"ULONG",
|
122 |
+
"LONGLONG",
|
123 |
+
"ULONGLONG",
|
124 |
+
"FLOAT",
|
125 |
+
"DOUBLE",
|
126 |
+
"CFLOAT",
|
127 |
+
"STRING1",
|
128 |
+
"STRING5",
|
129 |
+
"CHARACTER",
|
130 |
+
]
|
131 |
+
|
132 |
+
_cast_dict = {"BOOL": ["BOOL"]}
|
133 |
+
_cast_dict["BYTE"] = _cast_dict["BOOL"] + ["BYTE"]
|
134 |
+
_cast_dict["UBYTE"] = _cast_dict["BOOL"] + ["UBYTE"]
|
135 |
+
_cast_dict["BYTE"] = ["BYTE"]
|
136 |
+
_cast_dict["UBYTE"] = ["UBYTE"]
|
137 |
+
_cast_dict["SHORT"] = _cast_dict["BYTE"] + ["UBYTE", "SHORT"]
|
138 |
+
_cast_dict["USHORT"] = _cast_dict["UBYTE"] + ["BYTE", "USHORT"]
|
139 |
+
_cast_dict["INT"] = _cast_dict["SHORT"] + ["USHORT", "INT"]
|
140 |
+
_cast_dict["UINT"] = _cast_dict["USHORT"] + ["SHORT", "UINT"]
|
141 |
+
|
142 |
+
_cast_dict["LONG"] = _cast_dict["INT"] + ["LONG"]
|
143 |
+
_cast_dict["ULONG"] = _cast_dict["UINT"] + ["ULONG"]
|
144 |
+
|
145 |
+
_cast_dict["LONGLONG"] = _cast_dict["LONG"] + ["LONGLONG"]
|
146 |
+
_cast_dict["ULONGLONG"] = _cast_dict["ULONG"] + ["ULONGLONG"]
|
147 |
+
|
148 |
+
_cast_dict["FLOAT"] = _cast_dict["SHORT"] + ["USHORT", "FLOAT"]
|
149 |
+
_cast_dict["DOUBLE"] = _cast_dict["INT"] + ["UINT", "FLOAT", "DOUBLE"]
|
150 |
+
|
151 |
+
_cast_dict["CFLOAT"] = _cast_dict["FLOAT"] + ["CFLOAT"]
|
152 |
+
|
153 |
+
_cast_dict['STRING1'] = ['STRING1']
|
154 |
+
_cast_dict['STRING5'] = ['STRING5']
|
155 |
+
_cast_dict['CHARACTER'] = ['CHARACTER']
|
156 |
+
|
157 |
+
# 32 bit system malloc typically does not provide the alignment required by
|
158 |
+
# 16 byte long double types this means the inout intent cannot be satisfied
|
159 |
+
# and several tests fail as the alignment flag can be randomly true or fals
|
160 |
+
# when numpy gains an aligned allocator the tests could be enabled again
|
161 |
+
#
|
162 |
+
# Furthermore, on macOS ARM64, LONGDOUBLE is an alias for DOUBLE.
|
163 |
+
if ((np.intp().dtype.itemsize != 4 or np.clongdouble().dtype.alignment <= 8)
|
164 |
+
and sys.platform != "win32"
|
165 |
+
and (platform.system(), platform.processor()) != ("Darwin", "arm")):
|
166 |
+
_type_names.extend(["LONGDOUBLE", "CDOUBLE", "CLONGDOUBLE"])
|
167 |
+
_cast_dict["LONGDOUBLE"] = _cast_dict["LONG"] + [
|
168 |
+
"ULONG",
|
169 |
+
"FLOAT",
|
170 |
+
"DOUBLE",
|
171 |
+
"LONGDOUBLE",
|
172 |
+
]
|
173 |
+
_cast_dict["CLONGDOUBLE"] = _cast_dict["LONGDOUBLE"] + [
|
174 |
+
"CFLOAT",
|
175 |
+
"CDOUBLE",
|
176 |
+
"CLONGDOUBLE",
|
177 |
+
]
|
178 |
+
_cast_dict["CDOUBLE"] = _cast_dict["DOUBLE"] + ["CFLOAT", "CDOUBLE"]
|
179 |
+
|
180 |
+
|
181 |
+
class Type:
|
182 |
+
_type_cache = {}
|
183 |
+
|
184 |
+
def __new__(cls, name):
|
185 |
+
if isinstance(name, np.dtype):
|
186 |
+
dtype0 = name
|
187 |
+
name = None
|
188 |
+
for n, i in typeinfo.items():
|
189 |
+
if not isinstance(i, type) and dtype0.type is i.type:
|
190 |
+
name = n
|
191 |
+
break
|
192 |
+
obj = cls._type_cache.get(name.upper(), None)
|
193 |
+
if obj is not None:
|
194 |
+
return obj
|
195 |
+
obj = object.__new__(cls)
|
196 |
+
obj._init(name)
|
197 |
+
cls._type_cache[name.upper()] = obj
|
198 |
+
return obj
|
199 |
+
|
200 |
+
def _init(self, name):
|
201 |
+
self.NAME = name.upper()
|
202 |
+
|
203 |
+
if self.NAME == 'CHARACTER':
|
204 |
+
info = typeinfo[self.NAME]
|
205 |
+
self.type_num = getattr(wrap, 'NPY_STRING')
|
206 |
+
self.elsize = 1
|
207 |
+
self.dtype = np.dtype('c')
|
208 |
+
elif self.NAME.startswith('STRING'):
|
209 |
+
info = typeinfo[self.NAME[:6]]
|
210 |
+
self.type_num = getattr(wrap, 'NPY_STRING')
|
211 |
+
self.elsize = int(self.NAME[6:] or 0)
|
212 |
+
self.dtype = np.dtype(f'S{self.elsize}')
|
213 |
+
else:
|
214 |
+
info = typeinfo[self.NAME]
|
215 |
+
self.type_num = getattr(wrap, 'NPY_' + self.NAME)
|
216 |
+
self.elsize = info.bits // 8
|
217 |
+
self.dtype = np.dtype(info.type)
|
218 |
+
|
219 |
+
assert self.type_num == info.num
|
220 |
+
self.type = info.type
|
221 |
+
self.dtypechar = info.char
|
222 |
+
|
223 |
+
def __repr__(self):
|
224 |
+
return (f"Type({self.NAME})|type_num={self.type_num},"
|
225 |
+
f" dtype={self.dtype},"
|
226 |
+
f" type={self.type}, elsize={self.elsize},"
|
227 |
+
f" dtypechar={self.dtypechar}")
|
228 |
+
|
229 |
+
def cast_types(self):
|
230 |
+
return [self.__class__(_m) for _m in _cast_dict[self.NAME]]
|
231 |
+
|
232 |
+
def all_types(self):
|
233 |
+
return [self.__class__(_m) for _m in _type_names]
|
234 |
+
|
235 |
+
def smaller_types(self):
|
236 |
+
bits = typeinfo[self.NAME].alignment
|
237 |
+
types = []
|
238 |
+
for name in _type_names:
|
239 |
+
if typeinfo[name].alignment < bits:
|
240 |
+
types.append(Type(name))
|
241 |
+
return types
|
242 |
+
|
243 |
+
def equal_types(self):
|
244 |
+
bits = typeinfo[self.NAME].alignment
|
245 |
+
types = []
|
246 |
+
for name in _type_names:
|
247 |
+
if name == self.NAME:
|
248 |
+
continue
|
249 |
+
if typeinfo[name].alignment == bits:
|
250 |
+
types.append(Type(name))
|
251 |
+
return types
|
252 |
+
|
253 |
+
def larger_types(self):
|
254 |
+
bits = typeinfo[self.NAME].alignment
|
255 |
+
types = []
|
256 |
+
for name in _type_names:
|
257 |
+
if typeinfo[name].alignment > bits:
|
258 |
+
types.append(Type(name))
|
259 |
+
return types
|
260 |
+
|
261 |
+
|
262 |
+
class Array:
|
263 |
+
|
264 |
+
def __repr__(self):
|
265 |
+
return (f'Array({self.type}, {self.dims}, {self.intent},'
|
266 |
+
f' {self.obj})|arr={self.arr}')
|
267 |
+
|
268 |
+
def __init__(self, typ, dims, intent, obj):
|
269 |
+
self.type = typ
|
270 |
+
self.dims = dims
|
271 |
+
self.intent = intent
|
272 |
+
self.obj_copy = copy.deepcopy(obj)
|
273 |
+
self.obj = obj
|
274 |
+
|
275 |
+
# arr.dtypechar may be different from typ.dtypechar
|
276 |
+
self.arr = wrap.call(typ.type_num,
|
277 |
+
typ.elsize,
|
278 |
+
dims, intent.flags, obj)
|
279 |
+
|
280 |
+
assert isinstance(self.arr, np.ndarray)
|
281 |
+
|
282 |
+
self.arr_attr = wrap.array_attrs(self.arr)
|
283 |
+
|
284 |
+
if len(dims) > 1:
|
285 |
+
if self.intent.is_intent("c"):
|
286 |
+
assert (intent.flags & wrap.F2PY_INTENT_C)
|
287 |
+
assert not self.arr.flags["FORTRAN"]
|
288 |
+
assert self.arr.flags["CONTIGUOUS"]
|
289 |
+
assert (not self.arr_attr[6] & wrap.FORTRAN)
|
290 |
+
else:
|
291 |
+
assert (not intent.flags & wrap.F2PY_INTENT_C)
|
292 |
+
assert self.arr.flags["FORTRAN"]
|
293 |
+
assert not self.arr.flags["CONTIGUOUS"]
|
294 |
+
assert (self.arr_attr[6] & wrap.FORTRAN)
|
295 |
+
|
296 |
+
if obj is None:
|
297 |
+
self.pyarr = None
|
298 |
+
self.pyarr_attr = None
|
299 |
+
return
|
300 |
+
|
301 |
+
if intent.is_intent("cache"):
|
302 |
+
assert isinstance(obj, np.ndarray), repr(type(obj))
|
303 |
+
self.pyarr = np.array(obj).reshape(*dims).copy()
|
304 |
+
else:
|
305 |
+
self.pyarr = np.array(
|
306 |
+
np.array(obj, dtype=typ.dtypechar).reshape(*dims),
|
307 |
+
order=self.intent.is_intent("c") and "C" or "F",
|
308 |
+
)
|
309 |
+
assert self.pyarr.dtype == typ
|
310 |
+
self.pyarr.setflags(write=self.arr.flags["WRITEABLE"])
|
311 |
+
assert self.pyarr.flags["OWNDATA"], (obj, intent)
|
312 |
+
self.pyarr_attr = wrap.array_attrs(self.pyarr)
|
313 |
+
|
314 |
+
if len(dims) > 1:
|
315 |
+
if self.intent.is_intent("c"):
|
316 |
+
assert not self.pyarr.flags["FORTRAN"]
|
317 |
+
assert self.pyarr.flags["CONTIGUOUS"]
|
318 |
+
assert (not self.pyarr_attr[6] & wrap.FORTRAN)
|
319 |
+
else:
|
320 |
+
assert self.pyarr.flags["FORTRAN"]
|
321 |
+
assert not self.pyarr.flags["CONTIGUOUS"]
|
322 |
+
assert (self.pyarr_attr[6] & wrap.FORTRAN)
|
323 |
+
|
324 |
+
assert self.arr_attr[1] == self.pyarr_attr[1] # nd
|
325 |
+
assert self.arr_attr[2] == self.pyarr_attr[2] # dimensions
|
326 |
+
if self.arr_attr[1] <= 1:
|
327 |
+
assert self.arr_attr[3] == self.pyarr_attr[3], repr((
|
328 |
+
self.arr_attr[3],
|
329 |
+
self.pyarr_attr[3],
|
330 |
+
self.arr.tobytes(),
|
331 |
+
self.pyarr.tobytes(),
|
332 |
+
)) # strides
|
333 |
+
assert self.arr_attr[5][-2:] == self.pyarr_attr[5][-2:], repr((
|
334 |
+
self.arr_attr[5], self.pyarr_attr[5]
|
335 |
+
)) # descr
|
336 |
+
assert self.arr_attr[6] == self.pyarr_attr[6], repr((
|
337 |
+
self.arr_attr[6],
|
338 |
+
self.pyarr_attr[6],
|
339 |
+
flags2names(0 * self.arr_attr[6] - self.pyarr_attr[6]),
|
340 |
+
flags2names(self.arr_attr[6]),
|
341 |
+
intent,
|
342 |
+
)) # flags
|
343 |
+
|
344 |
+
if intent.is_intent("cache"):
|
345 |
+
assert self.arr_attr[5][3] >= self.type.elsize
|
346 |
+
else:
|
347 |
+
assert self.arr_attr[5][3] == self.type.elsize
|
348 |
+
assert (self.arr_equal(self.pyarr, self.arr))
|
349 |
+
|
350 |
+
if isinstance(self.obj, np.ndarray):
|
351 |
+
if typ.elsize == Type(obj.dtype).elsize:
|
352 |
+
if not intent.is_intent("copy") and self.arr_attr[1] <= 1:
|
353 |
+
assert self.has_shared_memory()
|
354 |
+
|
355 |
+
def arr_equal(self, arr1, arr2):
|
356 |
+
if arr1.shape != arr2.shape:
|
357 |
+
return False
|
358 |
+
return (arr1 == arr2).all()
|
359 |
+
|
360 |
+
def __str__(self):
|
361 |
+
return str(self.arr)
|
362 |
+
|
363 |
+
def has_shared_memory(self):
|
364 |
+
"""Check that created array shares data with input array."""
|
365 |
+
if self.obj is self.arr:
|
366 |
+
return True
|
367 |
+
if not isinstance(self.obj, np.ndarray):
|
368 |
+
return False
|
369 |
+
obj_attr = wrap.array_attrs(self.obj)
|
370 |
+
return obj_attr[0] == self.arr_attr[0]
|
371 |
+
|
372 |
+
|
373 |
+
class TestIntent:
|
374 |
+
def test_in_out(self):
|
375 |
+
assert str(intent.in_.out) == "intent(in,out)"
|
376 |
+
assert intent.in_.c.is_intent("c")
|
377 |
+
assert not intent.in_.c.is_intent_exact("c")
|
378 |
+
assert intent.in_.c.is_intent_exact("c", "in")
|
379 |
+
assert intent.in_.c.is_intent_exact("in", "c")
|
380 |
+
assert not intent.in_.is_intent("c")
|
381 |
+
|
382 |
+
|
383 |
+
class TestSharedMemory:
|
384 |
+
|
385 |
+
@pytest.fixture(autouse=True, scope="class", params=_type_names)
|
386 |
+
def setup_type(self, request):
|
387 |
+
request.cls.type = Type(request.param)
|
388 |
+
request.cls.array = lambda self, dims, intent, obj: Array(
|
389 |
+
Type(request.param), dims, intent, obj)
|
390 |
+
|
391 |
+
@property
|
392 |
+
def num2seq(self):
|
393 |
+
if self.type.NAME.startswith('STRING'):
|
394 |
+
elsize = self.type.elsize
|
395 |
+
return ['1' * elsize, '2' * elsize]
|
396 |
+
return [1, 2]
|
397 |
+
|
398 |
+
@property
|
399 |
+
def num23seq(self):
|
400 |
+
if self.type.NAME.startswith('STRING'):
|
401 |
+
elsize = self.type.elsize
|
402 |
+
return [['1' * elsize, '2' * elsize, '3' * elsize],
|
403 |
+
['4' * elsize, '5' * elsize, '6' * elsize]]
|
404 |
+
return [[1, 2, 3], [4, 5, 6]]
|
405 |
+
|
406 |
+
def test_in_from_2seq(self):
|
407 |
+
a = self.array([2], intent.in_, self.num2seq)
|
408 |
+
assert not a.has_shared_memory()
|
409 |
+
|
410 |
+
def test_in_from_2casttype(self):
|
411 |
+
for t in self.type.cast_types():
|
412 |
+
obj = np.array(self.num2seq, dtype=t.dtype)
|
413 |
+
a = self.array([len(self.num2seq)], intent.in_, obj)
|
414 |
+
if t.elsize == self.type.elsize:
|
415 |
+
assert a.has_shared_memory(), repr((self.type.dtype, t.dtype))
|
416 |
+
else:
|
417 |
+
assert not a.has_shared_memory()
|
418 |
+
|
419 |
+
@pytest.mark.parametrize("write", ["w", "ro"])
|
420 |
+
@pytest.mark.parametrize("order", ["C", "F"])
|
421 |
+
@pytest.mark.parametrize("inp", ["2seq", "23seq"])
|
422 |
+
def test_in_nocopy(self, write, order, inp):
|
423 |
+
"""Test if intent(in) array can be passed without copies"""
|
424 |
+
seq = getattr(self, "num" + inp)
|
425 |
+
obj = np.array(seq, dtype=self.type.dtype, order=order)
|
426 |
+
obj.setflags(write=(write == 'w'))
|
427 |
+
a = self.array(obj.shape,
|
428 |
+
((order == 'C' and intent.in_.c) or intent.in_), obj)
|
429 |
+
assert a.has_shared_memory()
|
430 |
+
|
431 |
+
def test_inout_2seq(self):
|
432 |
+
obj = np.array(self.num2seq, dtype=self.type.dtype)
|
433 |
+
a = self.array([len(self.num2seq)], intent.inout, obj)
|
434 |
+
assert a.has_shared_memory()
|
435 |
+
|
436 |
+
try:
|
437 |
+
a = self.array([2], intent.in_.inout, self.num2seq)
|
438 |
+
except TypeError as msg:
|
439 |
+
if not str(msg).startswith(
|
440 |
+
"failed to initialize intent(inout|inplace|cache) array"):
|
441 |
+
raise
|
442 |
+
else:
|
443 |
+
raise SystemError("intent(inout) should have failed on sequence")
|
444 |
+
|
445 |
+
def test_f_inout_23seq(self):
|
446 |
+
obj = np.array(self.num23seq, dtype=self.type.dtype, order="F")
|
447 |
+
shape = (len(self.num23seq), len(self.num23seq[0]))
|
448 |
+
a = self.array(shape, intent.in_.inout, obj)
|
449 |
+
assert a.has_shared_memory()
|
450 |
+
|
451 |
+
obj = np.array(self.num23seq, dtype=self.type.dtype, order="C")
|
452 |
+
shape = (len(self.num23seq), len(self.num23seq[0]))
|
453 |
+
try:
|
454 |
+
a = self.array(shape, intent.in_.inout, obj)
|
455 |
+
except ValueError as msg:
|
456 |
+
if not str(msg).startswith(
|
457 |
+
"failed to initialize intent(inout) array"):
|
458 |
+
raise
|
459 |
+
else:
|
460 |
+
raise SystemError(
|
461 |
+
"intent(inout) should have failed on improper array")
|
462 |
+
|
463 |
+
def test_c_inout_23seq(self):
|
464 |
+
obj = np.array(self.num23seq, dtype=self.type.dtype)
|
465 |
+
shape = (len(self.num23seq), len(self.num23seq[0]))
|
466 |
+
a = self.array(shape, intent.in_.c.inout, obj)
|
467 |
+
assert a.has_shared_memory()
|
468 |
+
|
469 |
+
def test_in_copy_from_2casttype(self):
|
470 |
+
for t in self.type.cast_types():
|
471 |
+
obj = np.array(self.num2seq, dtype=t.dtype)
|
472 |
+
a = self.array([len(self.num2seq)], intent.in_.copy, obj)
|
473 |
+
assert not a.has_shared_memory()
|
474 |
+
|
475 |
+
def test_c_in_from_23seq(self):
|
476 |
+
a = self.array(
|
477 |
+
[len(self.num23seq), len(self.num23seq[0])], intent.in_,
|
478 |
+
self.num23seq)
|
479 |
+
assert not a.has_shared_memory()
|
480 |
+
|
481 |
+
def test_in_from_23casttype(self):
|
482 |
+
for t in self.type.cast_types():
|
483 |
+
obj = np.array(self.num23seq, dtype=t.dtype)
|
484 |
+
a = self.array(
|
485 |
+
[len(self.num23seq), len(self.num23seq[0])], intent.in_, obj)
|
486 |
+
assert not a.has_shared_memory()
|
487 |
+
|
488 |
+
def test_f_in_from_23casttype(self):
|
489 |
+
for t in self.type.cast_types():
|
490 |
+
obj = np.array(self.num23seq, dtype=t.dtype, order="F")
|
491 |
+
a = self.array(
|
492 |
+
[len(self.num23seq), len(self.num23seq[0])], intent.in_, obj)
|
493 |
+
if t.elsize == self.type.elsize:
|
494 |
+
assert a.has_shared_memory()
|
495 |
+
else:
|
496 |
+
assert not a.has_shared_memory()
|
497 |
+
|
498 |
+
def test_c_in_from_23casttype(self):
|
499 |
+
for t in self.type.cast_types():
|
500 |
+
obj = np.array(self.num23seq, dtype=t.dtype)
|
501 |
+
a = self.array(
|
502 |
+
[len(self.num23seq), len(self.num23seq[0])], intent.in_.c, obj)
|
503 |
+
if t.elsize == self.type.elsize:
|
504 |
+
assert a.has_shared_memory()
|
505 |
+
else:
|
506 |
+
assert not a.has_shared_memory()
|
507 |
+
|
508 |
+
def test_f_copy_in_from_23casttype(self):
|
509 |
+
for t in self.type.cast_types():
|
510 |
+
obj = np.array(self.num23seq, dtype=t.dtype, order="F")
|
511 |
+
a = self.array(
|
512 |
+
[len(self.num23seq), len(self.num23seq[0])], intent.in_.copy,
|
513 |
+
obj)
|
514 |
+
assert not a.has_shared_memory()
|
515 |
+
|
516 |
+
def test_c_copy_in_from_23casttype(self):
|
517 |
+
for t in self.type.cast_types():
|
518 |
+
obj = np.array(self.num23seq, dtype=t.dtype)
|
519 |
+
a = self.array(
|
520 |
+
[len(self.num23seq), len(self.num23seq[0])], intent.in_.c.copy,
|
521 |
+
obj)
|
522 |
+
assert not a.has_shared_memory()
|
523 |
+
|
524 |
+
def test_in_cache_from_2casttype(self):
|
525 |
+
for t in self.type.all_types():
|
526 |
+
if t.elsize != self.type.elsize:
|
527 |
+
continue
|
528 |
+
obj = np.array(self.num2seq, dtype=t.dtype)
|
529 |
+
shape = (len(self.num2seq), )
|
530 |
+
a = self.array(shape, intent.in_.c.cache, obj)
|
531 |
+
assert a.has_shared_memory()
|
532 |
+
|
533 |
+
a = self.array(shape, intent.in_.cache, obj)
|
534 |
+
assert a.has_shared_memory()
|
535 |
+
|
536 |
+
obj = np.array(self.num2seq, dtype=t.dtype, order="F")
|
537 |
+
a = self.array(shape, intent.in_.c.cache, obj)
|
538 |
+
assert a.has_shared_memory()
|
539 |
+
|
540 |
+
a = self.array(shape, intent.in_.cache, obj)
|
541 |
+
assert a.has_shared_memory(), repr(t.dtype)
|
542 |
+
|
543 |
+
try:
|
544 |
+
a = self.array(shape, intent.in_.cache, obj[::-1])
|
545 |
+
except ValueError as msg:
|
546 |
+
if not str(msg).startswith(
|
547 |
+
"failed to initialize intent(cache) array"):
|
548 |
+
raise
|
549 |
+
else:
|
550 |
+
raise SystemError(
|
551 |
+
"intent(cache) should have failed on multisegmented array")
|
552 |
+
|
553 |
+
def test_in_cache_from_2casttype_failure(self):
|
554 |
+
for t in self.type.all_types():
|
555 |
+
if t.NAME == 'STRING':
|
556 |
+
# string elsize is 0, so skipping the test
|
557 |
+
continue
|
558 |
+
if t.elsize >= self.type.elsize:
|
559 |
+
continue
|
560 |
+
obj = np.array(self.num2seq, dtype=t.dtype)
|
561 |
+
shape = (len(self.num2seq), )
|
562 |
+
try:
|
563 |
+
self.array(shape, intent.in_.cache, obj) # Should succeed
|
564 |
+
except ValueError as msg:
|
565 |
+
if not str(msg).startswith(
|
566 |
+
"failed to initialize intent(cache) array"):
|
567 |
+
raise
|
568 |
+
else:
|
569 |
+
raise SystemError(
|
570 |
+
"intent(cache) should have failed on smaller array")
|
571 |
+
|
572 |
+
def test_cache_hidden(self):
|
573 |
+
shape = (2, )
|
574 |
+
a = self.array(shape, intent.cache.hide, None)
|
575 |
+
assert a.arr.shape == shape
|
576 |
+
|
577 |
+
shape = (2, 3)
|
578 |
+
a = self.array(shape, intent.cache.hide, None)
|
579 |
+
assert a.arr.shape == shape
|
580 |
+
|
581 |
+
shape = (-1, 3)
|
582 |
+
try:
|
583 |
+
a = self.array(shape, intent.cache.hide, None)
|
584 |
+
except ValueError as msg:
|
585 |
+
if not str(msg).startswith(
|
586 |
+
"failed to create intent(cache|hide)|optional array"):
|
587 |
+
raise
|
588 |
+
else:
|
589 |
+
raise SystemError(
|
590 |
+
"intent(cache) should have failed on undefined dimensions")
|
591 |
+
|
592 |
+
def test_hidden(self):
|
593 |
+
shape = (2, )
|
594 |
+
a = self.array(shape, intent.hide, None)
|
595 |
+
assert a.arr.shape == shape
|
596 |
+
assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
|
597 |
+
|
598 |
+
shape = (2, 3)
|
599 |
+
a = self.array(shape, intent.hide, None)
|
600 |
+
assert a.arr.shape == shape
|
601 |
+
assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
|
602 |
+
assert a.arr.flags["FORTRAN"] and not a.arr.flags["CONTIGUOUS"]
|
603 |
+
|
604 |
+
shape = (2, 3)
|
605 |
+
a = self.array(shape, intent.c.hide, None)
|
606 |
+
assert a.arr.shape == shape
|
607 |
+
assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
|
608 |
+
assert not a.arr.flags["FORTRAN"] and a.arr.flags["CONTIGUOUS"]
|
609 |
+
|
610 |
+
shape = (-1, 3)
|
611 |
+
try:
|
612 |
+
a = self.array(shape, intent.hide, None)
|
613 |
+
except ValueError as msg:
|
614 |
+
if not str(msg).startswith(
|
615 |
+
"failed to create intent(cache|hide)|optional array"):
|
616 |
+
raise
|
617 |
+
else:
|
618 |
+
raise SystemError(
|
619 |
+
"intent(hide) should have failed on undefined dimensions")
|
620 |
+
|
621 |
+
def test_optional_none(self):
|
622 |
+
shape = (2, )
|
623 |
+
a = self.array(shape, intent.optional, None)
|
624 |
+
assert a.arr.shape == shape
|
625 |
+
assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
|
626 |
+
|
627 |
+
shape = (2, 3)
|
628 |
+
a = self.array(shape, intent.optional, None)
|
629 |
+
assert a.arr.shape == shape
|
630 |
+
assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
|
631 |
+
assert a.arr.flags["FORTRAN"] and not a.arr.flags["CONTIGUOUS"]
|
632 |
+
|
633 |
+
shape = (2, 3)
|
634 |
+
a = self.array(shape, intent.c.optional, None)
|
635 |
+
assert a.arr.shape == shape
|
636 |
+
assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
|
637 |
+
assert not a.arr.flags["FORTRAN"] and a.arr.flags["CONTIGUOUS"]
|
638 |
+
|
639 |
+
def test_optional_from_2seq(self):
|
640 |
+
obj = self.num2seq
|
641 |
+
shape = (len(obj), )
|
642 |
+
a = self.array(shape, intent.optional, obj)
|
643 |
+
assert a.arr.shape == shape
|
644 |
+
assert not a.has_shared_memory()
|
645 |
+
|
646 |
+
def test_optional_from_23seq(self):
|
647 |
+
obj = self.num23seq
|
648 |
+
shape = (len(obj), len(obj[0]))
|
649 |
+
a = self.array(shape, intent.optional, obj)
|
650 |
+
assert a.arr.shape == shape
|
651 |
+
assert not a.has_shared_memory()
|
652 |
+
|
653 |
+
a = self.array(shape, intent.optional.c, obj)
|
654 |
+
assert a.arr.shape == shape
|
655 |
+
assert not a.has_shared_memory()
|
656 |
+
|
657 |
+
def test_inplace(self):
|
658 |
+
obj = np.array(self.num23seq, dtype=self.type.dtype)
|
659 |
+
assert not obj.flags["FORTRAN"] and obj.flags["CONTIGUOUS"]
|
660 |
+
shape = obj.shape
|
661 |
+
a = self.array(shape, intent.inplace, obj)
|
662 |
+
assert obj[1][2] == a.arr[1][2], repr((obj, a.arr))
|
663 |
+
a.arr[1][2] = 54
|
664 |
+
assert obj[1][2] == a.arr[1][2] == np.array(54, dtype=self.type.dtype)
|
665 |
+
assert a.arr is obj
|
666 |
+
assert obj.flags["FORTRAN"] # obj attributes are changed inplace!
|
667 |
+
assert not obj.flags["CONTIGUOUS"]
|
668 |
+
|
669 |
+
def test_inplace_from_casttype(self):
|
670 |
+
for t in self.type.cast_types():
|
671 |
+
if t is self.type:
|
672 |
+
continue
|
673 |
+
obj = np.array(self.num23seq, dtype=t.dtype)
|
674 |
+
assert obj.dtype.type == t.type
|
675 |
+
assert obj.dtype.type is not self.type.type
|
676 |
+
assert not obj.flags["FORTRAN"] and obj.flags["CONTIGUOUS"]
|
677 |
+
shape = obj.shape
|
678 |
+
a = self.array(shape, intent.inplace, obj)
|
679 |
+
assert obj[1][2] == a.arr[1][2], repr((obj, a.arr))
|
680 |
+
a.arr[1][2] = 54
|
681 |
+
assert obj[1][2] == a.arr[1][2] == np.array(54,
|
682 |
+
dtype=self.type.dtype)
|
683 |
+
assert a.arr is obj
|
684 |
+
assert obj.flags["FORTRAN"] # obj attributes changed inplace!
|
685 |
+
assert not obj.flags["CONTIGUOUS"]
|
686 |
+
assert obj.dtype.type is self.type.type # obj changed inplace!
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/test_assumed_shape.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import pytest
|
3 |
+
import tempfile
|
4 |
+
|
5 |
+
from . import util
|
6 |
+
|
7 |
+
|
8 |
+
class TestAssumedShapeSumExample(util.F2PyTest):
|
9 |
+
sources = [
|
10 |
+
util.getpath("tests", "src", "assumed_shape", "foo_free.f90"),
|
11 |
+
util.getpath("tests", "src", "assumed_shape", "foo_use.f90"),
|
12 |
+
util.getpath("tests", "src", "assumed_shape", "precision.f90"),
|
13 |
+
util.getpath("tests", "src", "assumed_shape", "foo_mod.f90"),
|
14 |
+
util.getpath("tests", "src", "assumed_shape", ".f2py_f2cmap"),
|
15 |
+
]
|
16 |
+
|
17 |
+
@pytest.mark.slow
|
18 |
+
def test_all(self):
|
19 |
+
r = self.module.fsum([1, 2])
|
20 |
+
assert r == 3
|
21 |
+
r = self.module.sum([1, 2])
|
22 |
+
assert r == 3
|
23 |
+
r = self.module.sum_with_use([1, 2])
|
24 |
+
assert r == 3
|
25 |
+
|
26 |
+
r = self.module.mod.sum([1, 2])
|
27 |
+
assert r == 3
|
28 |
+
r = self.module.mod.fsum([1, 2])
|
29 |
+
assert r == 3
|
30 |
+
|
31 |
+
|
32 |
+
class TestF2cmapOption(TestAssumedShapeSumExample):
|
33 |
+
def setup_method(self):
|
34 |
+
# Use a custom file name for .f2py_f2cmap
|
35 |
+
self.sources = list(self.sources)
|
36 |
+
f2cmap_src = self.sources.pop(-1)
|
37 |
+
|
38 |
+
self.f2cmap_file = tempfile.NamedTemporaryFile(delete=False)
|
39 |
+
with open(f2cmap_src, "rb") as f:
|
40 |
+
self.f2cmap_file.write(f.read())
|
41 |
+
self.f2cmap_file.close()
|
42 |
+
|
43 |
+
self.sources.append(self.f2cmap_file.name)
|
44 |
+
self.options = ["--f2cmap", self.f2cmap_file.name]
|
45 |
+
|
46 |
+
super().setup_method()
|
47 |
+
|
48 |
+
def teardown_method(self):
|
49 |
+
os.unlink(self.f2cmap_file.name)
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/test_block_docstring.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import pytest
|
3 |
+
from . import util
|
4 |
+
|
5 |
+
from numpy.testing import IS_PYPY
|
6 |
+
|
7 |
+
|
8 |
+
class TestBlockDocString(util.F2PyTest):
|
9 |
+
sources = [util.getpath("tests", "src", "block_docstring", "foo.f")]
|
10 |
+
|
11 |
+
@pytest.mark.skipif(sys.platform == "win32",
|
12 |
+
reason="Fails with MinGW64 Gfortran (Issue #9673)")
|
13 |
+
@pytest.mark.xfail(IS_PYPY,
|
14 |
+
reason="PyPy cannot modify tp_doc after PyType_Ready")
|
15 |
+
def test_block_docstring(self):
|
16 |
+
expected = "bar : 'i'-array(2,3)\n"
|
17 |
+
assert self.module.block.__doc__ == expected
|
venv/lib/python3.10/site-packages/numpy/f2py/tests/test_callback.py
ADDED
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import textwrap
|
3 |
+
import sys
|
4 |
+
import pytest
|
5 |
+
import threading
|
6 |
+
import traceback
|
7 |
+
import time
|
8 |
+
|
9 |
+
import numpy as np
|
10 |
+
from numpy.testing import IS_PYPY
|
11 |
+
from . import util
|
12 |
+
|
13 |
+
|
14 |
+
class TestF77Callback(util.F2PyTest):
|
15 |
+
sources = [util.getpath("tests", "src", "callback", "foo.f")]
|
16 |
+
|
17 |
+
@pytest.mark.parametrize("name", "t,t2".split(","))
|
18 |
+
def test_all(self, name):
|
19 |
+
self.check_function(name)
|
20 |
+
|
21 |
+
@pytest.mark.xfail(IS_PYPY,
|
22 |
+
reason="PyPy cannot modify tp_doc after PyType_Ready")
|
23 |
+
def test_docstring(self):
|
24 |
+
expected = textwrap.dedent("""\
|
25 |
+
a = t(fun,[fun_extra_args])
|
26 |
+
|
27 |
+
Wrapper for ``t``.
|
28 |
+
|
29 |
+
Parameters
|
30 |
+
----------
|
31 |
+
fun : call-back function
|
32 |
+
|
33 |
+
Other Parameters
|
34 |
+
----------------
|
35 |
+
fun_extra_args : input tuple, optional
|
36 |
+
Default: ()
|
37 |
+
|
38 |
+
Returns
|
39 |
+
-------
|
40 |
+
a : int
|
41 |
+
|
42 |
+
Notes
|
43 |
+
-----
|
44 |
+
Call-back functions::
|
45 |
+
|
46 |
+
def fun(): return a
|
47 |
+
Return objects:
|
48 |
+
a : int
|
49 |
+
""")
|
50 |
+
assert self.module.t.__doc__ == expected
|
51 |
+
|
52 |
+
def check_function(self, name):
|
53 |
+
t = getattr(self.module, name)
|
54 |
+
r = t(lambda: 4)
|
55 |
+
assert r == 4
|
56 |
+
r = t(lambda a: 5, fun_extra_args=(6, ))
|
57 |
+
assert r == 5
|
58 |
+
r = t(lambda a: a, fun_extra_args=(6, ))
|
59 |
+
assert r == 6
|
60 |
+
r = t(lambda a: 5 + a, fun_extra_args=(7, ))
|
61 |
+
assert r == 12
|
62 |
+
r = t(lambda a: math.degrees(a), fun_extra_args=(math.pi, ))
|
63 |
+
assert r == 180
|
64 |
+
r = t(math.degrees, fun_extra_args=(math.pi, ))
|
65 |
+
assert r == 180
|
66 |
+
|
67 |
+
r = t(self.module.func, fun_extra_args=(6, ))
|
68 |
+
assert r == 17
|
69 |
+
r = t(self.module.func0)
|
70 |
+
assert r == 11
|
71 |
+
r = t(self.module.func0._cpointer)
|
72 |
+
assert r == 11
|
73 |
+
|
74 |
+
class A:
|
75 |
+
def __call__(self):
|
76 |
+
return 7
|
77 |
+
|
78 |
+
def mth(self):
|
79 |
+
return 9
|
80 |
+
|
81 |
+
a = A()
|
82 |
+
r = t(a)
|
83 |
+
assert r == 7
|
84 |
+
r = t(a.mth)
|
85 |
+
assert r == 9
|
86 |
+
|
87 |
+
@pytest.mark.skipif(sys.platform == 'win32',
|
88 |
+
reason='Fails with MinGW64 Gfortran (Issue #9673)')
|
89 |
+
def test_string_callback(self):
|
90 |
+
def callback(code):
|
91 |
+
if code == "r":
|
92 |
+
return 0
|
93 |
+
else:
|
94 |
+
return 1
|
95 |
+
|
96 |
+
f = getattr(self.module, "string_callback")
|
97 |
+
r = f(callback)
|
98 |
+
assert r == 0
|
99 |
+
|
100 |
+
@pytest.mark.skipif(sys.platform == 'win32',
|
101 |
+
reason='Fails with MinGW64 Gfortran (Issue #9673)')
|
102 |
+
def test_string_callback_array(self):
|
103 |
+
# See gh-10027
|
104 |
+
cu1 = np.zeros((1, ), "S8")
|
105 |
+
cu2 = np.zeros((1, 8), "c")
|
106 |
+
cu3 = np.array([""], "S8")
|
107 |
+
|
108 |
+
def callback(cu, lencu):
|
109 |
+
if cu.shape != (lencu,):
|
110 |
+
return 1
|
111 |
+
if cu.dtype != "S8":
|
112 |
+
return 2
|
113 |
+
if not np.all(cu == b""):
|
114 |
+
return 3
|
115 |
+
return 0
|
116 |
+
|
117 |
+
f = getattr(self.module, "string_callback_array")
|
118 |
+
for cu in [cu1, cu2, cu3]:
|
119 |
+
res = f(callback, cu, cu.size)
|
120 |
+
assert res == 0
|
121 |
+
|
122 |
+
def test_threadsafety(self):
|
123 |
+
# Segfaults if the callback handling is not threadsafe
|
124 |
+
|
125 |
+
errors = []
|
126 |
+
|
127 |
+
def cb():
|
128 |
+
# Sleep here to make it more likely for another thread
|
129 |
+
# to call their callback at the same time.
|
130 |
+
time.sleep(1e-3)
|
131 |
+
|
132 |
+
# Check reentrancy
|
133 |
+
r = self.module.t(lambda: 123)
|
134 |
+
assert r == 123
|
135 |
+
|
136 |
+
return 42
|
137 |
+
|
138 |
+
def runner(name):
|
139 |
+
try:
|
140 |
+
for j in range(50):
|
141 |
+
r = self.module.t(cb)
|
142 |
+
assert r == 42
|
143 |
+
self.check_function(name)
|
144 |
+
except Exception:
|
145 |
+
errors.append(traceback.format_exc())
|
146 |
+
|
147 |
+
threads = [
|
148 |
+
threading.Thread(target=runner, args=(arg, ))
|
149 |
+
for arg in ("t", "t2") for n in range(20)
|
150 |
+
]
|
151 |
+
|
152 |
+
for t in threads:
|
153 |
+
t.start()
|
154 |
+
|
155 |
+
for t in threads:
|
156 |
+
t.join()
|
157 |
+
|
158 |
+
errors = "\n\n".join(errors)
|
159 |
+
if errors:
|
160 |
+
raise AssertionError(errors)
|
161 |
+
|
162 |
+
def test_hidden_callback(self):
|
163 |
+
try:
|
164 |
+
self.module.hidden_callback(2)
|
165 |
+
except Exception as msg:
|
166 |
+
assert str(msg).startswith("Callback global_f not defined")
|
167 |
+
|
168 |
+
try:
|
169 |
+
self.module.hidden_callback2(2)
|
170 |
+
except Exception as msg:
|
171 |
+
assert str(msg).startswith("cb: Callback global_f not defined")
|
172 |
+
|
173 |
+
self.module.global_f = lambda x: x + 1
|
174 |
+
r = self.module.hidden_callback(2)
|
175 |
+
assert r == 3
|
176 |
+
|
177 |
+
self.module.global_f = lambda x: x + 2
|
178 |
+
r = self.module.hidden_callback(2)
|
179 |
+
assert r == 4
|
180 |
+
|
181 |
+
del self.module.global_f
|
182 |
+
try:
|
183 |
+
self.module.hidden_callback(2)
|
184 |
+
except Exception as msg:
|
185 |
+
assert str(msg).startswith("Callback global_f not defined")
|
186 |
+
|
187 |
+
self.module.global_f = lambda x=0: x + 3
|
188 |
+
r = self.module.hidden_callback(2)
|
189 |
+
assert r == 5
|
190 |
+
|
191 |
+
# reproducer of gh18341
|
192 |
+
r = self.module.hidden_callback2(2)
|
193 |
+
assert r == 3
|
194 |
+
|
195 |
+
|
196 |
+
class TestF77CallbackPythonTLS(TestF77Callback):
|
197 |
+
"""
|
198 |
+
Callback tests using Python thread-local storage instead of
|
199 |
+
compiler-provided
|
200 |
+
"""
|
201 |
+
|
202 |
+
options = ["-DF2PY_USE_PYTHON_TLS"]
|
203 |
+
|
204 |
+
|
205 |
+
class TestF90Callback(util.F2PyTest):
|
206 |
+
sources = [util.getpath("tests", "src", "callback", "gh17797.f90")]
|
207 |
+
|
208 |
+
def test_gh17797(self):
|
209 |
+
def incr(x):
|
210 |
+
return x + 123
|
211 |
+
|
212 |
+
y = np.array([1, 2, 3], dtype=np.int64)
|
213 |
+
r = self.module.gh17797(incr, y)
|
214 |
+
assert r == 123 + 1 + 2 + 3
|
215 |
+
|
216 |
+
|
217 |
+
class TestGH18335(util.F2PyTest):
|
218 |
+
"""The reproduction of the reported issue requires specific input that
|
219 |
+
extensions may break the issue conditions, so the reproducer is
|
220 |
+
implemented as a separate test class. Do not extend this test with
|
221 |
+
other tests!
|
222 |
+
"""
|
223 |
+
sources = [util.getpath("tests", "src", "callback", "gh18335.f90")]
|
224 |
+
|
225 |
+
def test_gh18335(self):
|
226 |
+
def foo(x):
|
227 |
+
x[0] += 1
|
228 |
+
|
229 |
+
r = self.module.gh18335(foo)
|
230 |
+
assert r == 123 + 1
|
231 |
+
|
232 |
+
|
233 |
+
class TestGH25211(util.F2PyTest):
|
234 |
+
sources = [util.getpath("tests", "src", "callback", "gh25211.f"),
|
235 |
+
util.getpath("tests", "src", "callback", "gh25211.pyf")]
|
236 |
+
module_name = "callback2"
|
237 |
+
|
238 |
+
def test_gh18335(self):
|
239 |
+
def bar(x):
|
240 |
+
return x*x
|
241 |
+
|
242 |
+
res = self.module.foo(bar)
|
243 |
+
assert res == 110
|