applied-ai-018 commited on
Commit
74f22b7
·
verified ·
1 Parent(s): 265fa6d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/numpy/f2py/__init__.py +194 -0
  2. env-llmeval/lib/python3.10/site-packages/numpy/f2py/__init__.pyi +42 -0
  3. env-llmeval/lib/python3.10/site-packages/numpy/f2py/__main__.py +5 -0
  4. env-llmeval/lib/python3.10/site-packages/numpy/f2py/__version__.py +1 -0
  5. env-llmeval/lib/python3.10/site-packages/numpy/f2py/_isocbind.py +62 -0
  6. env-llmeval/lib/python3.10/site-packages/numpy/f2py/_src_pyf.py +239 -0
  7. env-llmeval/lib/python3.10/site-packages/numpy/f2py/auxfuncs.py +988 -0
  8. env-llmeval/lib/python3.10/site-packages/numpy/f2py/capi_maps.py +819 -0
  9. env-llmeval/lib/python3.10/site-packages/numpy/f2py/cb_rules.py +644 -0
  10. env-llmeval/lib/python3.10/site-packages/numpy/f2py/cfuncs.py +1536 -0
  11. env-llmeval/lib/python3.10/site-packages/numpy/f2py/common_rules.py +146 -0
  12. env-llmeval/lib/python3.10/site-packages/numpy/f2py/crackfortran.py +0 -0
  13. env-llmeval/lib/python3.10/site-packages/numpy/f2py/diagnose.py +154 -0
  14. env-llmeval/lib/python3.10/site-packages/numpy/f2py/f2py2e.py +768 -0
  15. env-llmeval/lib/python3.10/site-packages/numpy/f2py/f90mod_rules.py +264 -0
  16. env-llmeval/lib/python3.10/site-packages/numpy/f2py/func2subr.py +323 -0
  17. env-llmeval/lib/python3.10/site-packages/numpy/f2py/rules.py +1568 -0
  18. env-llmeval/lib/python3.10/site-packages/numpy/f2py/setup.cfg +3 -0
  19. env-llmeval/lib/python3.10/site-packages/numpy/f2py/setup.py +74 -0
  20. env-llmeval/lib/python3.10/site-packages/numpy/f2py/symbolic.py +1517 -0
  21. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_array_from_pyobj.py +686 -0
  22. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_assumed_shape.py +49 -0
  23. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_callback.py +243 -0
  24. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_common.py +27 -0
  25. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_crackfortran.py +350 -0
  26. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_data.py +70 -0
  27. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_docs.py +55 -0
  28. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_f2py2e.py +896 -0
  29. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_isoc.py +52 -0
  30. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_kind.py +47 -0
  31. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_mixed.py +33 -0
  32. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_pyf_src.py +44 -0
  33. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_return_character.py +45 -0
  34. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_return_complex.py +65 -0
  35. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_return_integer.py +53 -0
  36. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_return_real.py +107 -0
  37. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_semicolon_split.py +74 -0
  38. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_size.py +45 -0
  39. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_string.py +100 -0
  40. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_symbolic.py +494 -0
  41. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_value_attrspec.py +14 -0
  42. env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/util.py +440 -0
  43. env-llmeval/lib/python3.10/site-packages/numpy/f2py/use_rules.py +106 -0
  44. env-llmeval/lib/python3.10/site-packages/numpy/testing/__init__.py +22 -0
  45. env-llmeval/lib/python3.10/site-packages/numpy/testing/__init__.pyi +50 -0
  46. env-llmeval/lib/python3.10/site-packages/numpy/testing/__pycache__/__init__.cpython-310.pyc +0 -0
  47. env-llmeval/lib/python3.10/site-packages/numpy/testing/__pycache__/overrides.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/numpy/testing/__pycache__/print_coercion_tables.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/numpy/testing/__pycache__/setup.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/numpy/testing/_private/__init__.py +0 -0
env-llmeval/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"})
env-llmeval/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: ...
env-llmeval/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()
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__version__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from numpy.version import version
env-llmeval/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
+ isoc_kindmap[c_type] = fortran_type
env-llmeval/lib/python3.10/site-packages/numpy/f2py/_src_pyf.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ###########################################################
env-llmeval/lib/python3.10/site-packages/numpy/f2py/auxfuncs.py ADDED
@@ -0,0 +1,988 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
env-llmeval/lib/python3.10/site-packages/numpy/f2py/capi_maps.py ADDED
@@ -0,0 +1,819 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ret['arrdocstr'] = getarrdocsign(a, var)
819
+ return ret
env-llmeval/lib/python3.10/site-packages/numpy/f2py/cb_rules.py ADDED
@@ -0,0 +1,644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 #############
env-llmeval/lib/python3.10/site-packages/numpy/f2py/cfuncs.py ADDED
@@ -0,0 +1,1536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
env-llmeval/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]
env-llmeval/lib/python3.10/site-packages/numpy/f2py/crackfortran.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/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()
env-llmeval/lib/python3.10/site-packages/numpy/f2py/f2py2e.py ADDED
@@ -0,0 +1,768 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+
4
+ f2py2e - Fortran to Python C/API generator. 2nd Edition.
5
+ See __usage__ below.
6
+
7
+ Copyright 1999 -- 2011 Pearu Peterson 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:])
env-llmeval/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]
env-llmeval/lib/python3.10/site-packages/numpy/f2py/func2subr.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ Rules for 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, ''
env-llmeval/lib/python3.10/site-packages/numpy/f2py/rules.py ADDED
@@ -0,0 +1,1568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 #######################
env-llmeval/lib/python3.10/site-packages/numpy/f2py/setup.cfg ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [bdist_rpm]
2
+ doc_files = docs/
3
+ tests/
env-llmeval/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 Fortran 90/95 modules is supported.""",
72
+ url="https://numpy.org/doc/stable/f2py/",
73
+ keywords=['Fortran', 'f2py'],
74
+ **config)
env-llmeval/lib/python3.10/site-packages/numpy/f2py/symbolic.py ADDED
@@ -0,0 +1,1517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_array_from_pyobj.py ADDED
@@ -0,0 +1,686 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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!
env-llmeval/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)
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_common.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import pytest
4
+
5
+ import numpy as np
6
+ from . import util
7
+
8
+
9
+ class TestCommonBlock(util.F2PyTest):
10
+ sources = [util.getpath("tests", "src", "common", "block.f")]
11
+
12
+ @pytest.mark.skipif(sys.platform == "win32",
13
+ reason="Fails with MinGW64 Gfortran (Issue #9673)")
14
+ def test_common_block(self):
15
+ self.module.initcb()
16
+ assert self.module.block.long_bn == np.array(1.0, dtype=np.float64)
17
+ assert self.module.block.string_bn == np.array("2", dtype="|S1")
18
+ assert self.module.block.ok == np.array(3, dtype=np.int32)
19
+
20
+
21
+ class TestCommonWithUse(util.F2PyTest):
22
+ sources = [util.getpath("tests", "src", "common", "gh19161.f90")]
23
+
24
+ @pytest.mark.skipif(sys.platform == "win32",
25
+ reason="Fails with MinGW64 Gfortran (Issue #9673)")
26
+ def test_common_gh19161(self):
27
+ assert self.module.data.x == 0
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_crackfortran.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import codecs
3
+ import time
4
+ import unicodedata
5
+ import pytest
6
+ import numpy as np
7
+ from numpy.f2py.crackfortran import markinnerspaces, nameargspattern
8
+ from . import util
9
+ from numpy.f2py import crackfortran
10
+ import textwrap
11
+ import contextlib
12
+ import io
13
+
14
+
15
+ class TestNoSpace(util.F2PyTest):
16
+ # issue gh-15035: add handling for endsubroutine, endfunction with no space
17
+ # between "end" and the block name
18
+ sources = [util.getpath("tests", "src", "crackfortran", "gh15035.f")]
19
+
20
+ def test_module(self):
21
+ k = np.array([1, 2, 3], dtype=np.float64)
22
+ w = np.array([1, 2, 3], dtype=np.float64)
23
+ self.module.subb(k)
24
+ assert np.allclose(k, w + 1)
25
+ self.module.subc([w, k])
26
+ assert np.allclose(k, w + 1)
27
+ assert self.module.t0("23") == b"2"
28
+
29
+
30
+ class TestPublicPrivate:
31
+ def test_defaultPrivate(self):
32
+ fpath = util.getpath("tests", "src", "crackfortran", "privatemod.f90")
33
+ mod = crackfortran.crackfortran([str(fpath)])
34
+ assert len(mod) == 1
35
+ mod = mod[0]
36
+ assert "private" in mod["vars"]["a"]["attrspec"]
37
+ assert "public" not in mod["vars"]["a"]["attrspec"]
38
+ assert "private" in mod["vars"]["b"]["attrspec"]
39
+ assert "public" not in mod["vars"]["b"]["attrspec"]
40
+ assert "private" not in mod["vars"]["seta"]["attrspec"]
41
+ assert "public" in mod["vars"]["seta"]["attrspec"]
42
+
43
+ def test_defaultPublic(self, tmp_path):
44
+ fpath = util.getpath("tests", "src", "crackfortran", "publicmod.f90")
45
+ mod = crackfortran.crackfortran([str(fpath)])
46
+ assert len(mod) == 1
47
+ mod = mod[0]
48
+ assert "private" in mod["vars"]["a"]["attrspec"]
49
+ assert "public" not in mod["vars"]["a"]["attrspec"]
50
+ assert "private" not in mod["vars"]["seta"]["attrspec"]
51
+ assert "public" in mod["vars"]["seta"]["attrspec"]
52
+
53
+ def test_access_type(self, tmp_path):
54
+ fpath = util.getpath("tests", "src", "crackfortran", "accesstype.f90")
55
+ mod = crackfortran.crackfortran([str(fpath)])
56
+ assert len(mod) == 1
57
+ tt = mod[0]['vars']
58
+ assert set(tt['a']['attrspec']) == {'private', 'bind(c)'}
59
+ assert set(tt['b_']['attrspec']) == {'public', 'bind(c)'}
60
+ assert set(tt['c']['attrspec']) == {'public'}
61
+
62
+ def test_nowrap_private_proceedures(self, tmp_path):
63
+ fpath = util.getpath("tests", "src", "crackfortran", "gh23879.f90")
64
+ mod = crackfortran.crackfortran([str(fpath)])
65
+ assert len(mod) == 1
66
+ pyf = crackfortran.crack2fortran(mod)
67
+ assert 'bar' not in pyf
68
+
69
+ class TestModuleProcedure():
70
+ def test_moduleOperators(self, tmp_path):
71
+ fpath = util.getpath("tests", "src", "crackfortran", "operators.f90")
72
+ mod = crackfortran.crackfortran([str(fpath)])
73
+ assert len(mod) == 1
74
+ mod = mod[0]
75
+ assert "body" in mod and len(mod["body"]) == 9
76
+ assert mod["body"][1]["name"] == "operator(.item.)"
77
+ assert "implementedby" in mod["body"][1]
78
+ assert mod["body"][1]["implementedby"] == \
79
+ ["item_int", "item_real"]
80
+ assert mod["body"][2]["name"] == "operator(==)"
81
+ assert "implementedby" in mod["body"][2]
82
+ assert mod["body"][2]["implementedby"] == ["items_are_equal"]
83
+ assert mod["body"][3]["name"] == "assignment(=)"
84
+ assert "implementedby" in mod["body"][3]
85
+ assert mod["body"][3]["implementedby"] == \
86
+ ["get_int", "get_real"]
87
+
88
+ def test_notPublicPrivate(self, tmp_path):
89
+ fpath = util.getpath("tests", "src", "crackfortran", "pubprivmod.f90")
90
+ mod = crackfortran.crackfortran([str(fpath)])
91
+ assert len(mod) == 1
92
+ mod = mod[0]
93
+ assert mod['vars']['a']['attrspec'] == ['private', ]
94
+ assert mod['vars']['b']['attrspec'] == ['public', ]
95
+ assert mod['vars']['seta']['attrspec'] == ['public', ]
96
+
97
+
98
+ class TestExternal(util.F2PyTest):
99
+ # issue gh-17859: add external attribute support
100
+ sources = [util.getpath("tests", "src", "crackfortran", "gh17859.f")]
101
+
102
+ def test_external_as_statement(self):
103
+ def incr(x):
104
+ return x + 123
105
+
106
+ r = self.module.external_as_statement(incr)
107
+ assert r == 123
108
+
109
+ def test_external_as_attribute(self):
110
+ def incr(x):
111
+ return x + 123
112
+
113
+ r = self.module.external_as_attribute(incr)
114
+ assert r == 123
115
+
116
+
117
+ class TestCrackFortran(util.F2PyTest):
118
+ # gh-2848: commented lines between parameters in subroutine parameter lists
119
+ sources = [util.getpath("tests", "src", "crackfortran", "gh2848.f90")]
120
+
121
+ def test_gh2848(self):
122
+ r = self.module.gh2848(1, 2)
123
+ assert r == (1, 2)
124
+
125
+
126
+ class TestMarkinnerspaces:
127
+ # gh-14118: markinnerspaces does not handle multiple quotations
128
+
129
+ def test_do_not_touch_normal_spaces(self):
130
+ test_list = ["a ", " a", "a b c", "'abcdefghij'"]
131
+ for i in test_list:
132
+ assert markinnerspaces(i) == i
133
+
134
+ def test_one_relevant_space(self):
135
+ assert markinnerspaces("a 'b c' \\' \\'") == "a 'b@_@c' \\' \\'"
136
+ assert markinnerspaces(r'a "b c" \" \"') == r'a "b@_@c" \" \"'
137
+
138
+ def test_ignore_inner_quotes(self):
139
+ assert markinnerspaces("a 'b c\" \" d' e") == "a 'b@_@c\"@_@\"@_@d' e"
140
+ assert markinnerspaces("a \"b c' ' d\" e") == "a \"b@_@c'@_@'@_@d\" e"
141
+
142
+ def test_multiple_relevant_spaces(self):
143
+ assert markinnerspaces("a 'b c' 'd e'") == "a 'b@_@c' 'd@_@e'"
144
+ assert markinnerspaces(r'a "b c" "d e"') == r'a "b@_@c" "d@_@e"'
145
+
146
+
147
+ class TestDimSpec(util.F2PyTest):
148
+ """This test suite tests various expressions that are used as dimension
149
+ specifications.
150
+
151
+ There exists two usage cases where analyzing dimensions
152
+ specifications are important.
153
+
154
+ In the first case, the size of output arrays must be defined based
155
+ on the inputs to a Fortran function. Because Fortran supports
156
+ arbitrary bases for indexing, for instance, `arr(lower:upper)`,
157
+ f2py has to evaluate an expression `upper - lower + 1` where
158
+ `lower` and `upper` are arbitrary expressions of input parameters.
159
+ The evaluation is performed in C, so f2py has to translate Fortran
160
+ expressions to valid C expressions (an alternative approach is
161
+ that a developer specifies the corresponding C expressions in a
162
+ .pyf file).
163
+
164
+ In the second case, when user provides an input array with a given
165
+ size but some hidden parameters used in dimensions specifications
166
+ need to be determined based on the input array size. This is a
167
+ harder problem because f2py has to solve the inverse problem: find
168
+ a parameter `p` such that `upper(p) - lower(p) + 1` equals to the
169
+ size of input array. In the case when this equation cannot be
170
+ solved (e.g. because the input array size is wrong), raise an
171
+ error before calling the Fortran function (that otherwise would
172
+ likely crash Python process when the size of input arrays is
173
+ wrong). f2py currently supports this case only when the equation
174
+ is linear with respect to unknown parameter.
175
+
176
+ """
177
+
178
+ suffix = ".f90"
179
+
180
+ code_template = textwrap.dedent("""
181
+ function get_arr_size_{count}(a, n) result (length)
182
+ integer, intent(in) :: n
183
+ integer, dimension({dimspec}), intent(out) :: a
184
+ integer length
185
+ length = size(a)
186
+ end function
187
+
188
+ subroutine get_inv_arr_size_{count}(a, n)
189
+ integer :: n
190
+ ! the value of n is computed in f2py wrapper
191
+ !f2py intent(out) n
192
+ integer, dimension({dimspec}), intent(in) :: a
193
+ end subroutine
194
+ """)
195
+
196
+ linear_dimspecs = [
197
+ "n", "2*n", "2:n", "n/2", "5 - n/2", "3*n:20", "n*(n+1):n*(n+5)",
198
+ "2*n, n"
199
+ ]
200
+ nonlinear_dimspecs = ["2*n:3*n*n+2*n"]
201
+ all_dimspecs = linear_dimspecs + nonlinear_dimspecs
202
+
203
+ code = ""
204
+ for count, dimspec in enumerate(all_dimspecs):
205
+ lst = [(d.split(":")[0] if ":" in d else "1") for d in dimspec.split(',')]
206
+ code += code_template.format(
207
+ count=count,
208
+ dimspec=dimspec,
209
+ first=", ".join(lst),
210
+ )
211
+
212
+ @pytest.mark.parametrize("dimspec", all_dimspecs)
213
+ def test_array_size(self, dimspec):
214
+
215
+ count = self.all_dimspecs.index(dimspec)
216
+ get_arr_size = getattr(self.module, f"get_arr_size_{count}")
217
+
218
+ for n in [1, 2, 3, 4, 5]:
219
+ sz, a = get_arr_size(n)
220
+ assert a.size == sz
221
+
222
+ @pytest.mark.parametrize("dimspec", all_dimspecs)
223
+ def test_inv_array_size(self, dimspec):
224
+
225
+ count = self.all_dimspecs.index(dimspec)
226
+ get_arr_size = getattr(self.module, f"get_arr_size_{count}")
227
+ get_inv_arr_size = getattr(self.module, f"get_inv_arr_size_{count}")
228
+
229
+ for n in [1, 2, 3, 4, 5]:
230
+ sz, a = get_arr_size(n)
231
+ if dimspec in self.nonlinear_dimspecs:
232
+ # one must specify n as input, the call we'll ensure
233
+ # that a and n are compatible:
234
+ n1 = get_inv_arr_size(a, n)
235
+ else:
236
+ # in case of linear dependence, n can be determined
237
+ # from the shape of a:
238
+ n1 = get_inv_arr_size(a)
239
+ # n1 may be different from n (for instance, when `a` size
240
+ # is a function of some `n` fraction) but it must produce
241
+ # the same sized array
242
+ sz1, _ = get_arr_size(n1)
243
+ assert sz == sz1, (n, n1, sz, sz1)
244
+
245
+
246
+ class TestModuleDeclaration:
247
+ def test_dependencies(self, tmp_path):
248
+ fpath = util.getpath("tests", "src", "crackfortran", "foo_deps.f90")
249
+ mod = crackfortran.crackfortran([str(fpath)])
250
+ assert len(mod) == 1
251
+ assert mod[0]["vars"]["abar"]["="] == "bar('abar')"
252
+
253
+
254
+ class TestEval(util.F2PyTest):
255
+ def test_eval_scalar(self):
256
+ eval_scalar = crackfortran._eval_scalar
257
+
258
+ assert eval_scalar('123', {}) == '123'
259
+ assert eval_scalar('12 + 3', {}) == '15'
260
+ assert eval_scalar('a + b', dict(a=1, b=2)) == '3'
261
+ assert eval_scalar('"123"', {}) == "'123'"
262
+
263
+
264
+ class TestFortranReader(util.F2PyTest):
265
+ @pytest.mark.parametrize("encoding",
266
+ ['ascii', 'utf-8', 'utf-16', 'utf-32'])
267
+ def test_input_encoding(self, tmp_path, encoding):
268
+ # gh-635
269
+ f_path = tmp_path / f"input_with_{encoding}_encoding.f90"
270
+ with f_path.open('w', encoding=encoding) as ff:
271
+ ff.write("""
272
+ subroutine foo()
273
+ end subroutine foo
274
+ """)
275
+ mod = crackfortran.crackfortran([str(f_path)])
276
+ assert mod[0]['name'] == 'foo'
277
+
278
+
279
+ class TestUnicodeComment(util.F2PyTest):
280
+ sources = [util.getpath("tests", "src", "crackfortran", "unicode_comment.f90")]
281
+
282
+ @pytest.mark.skipif(
283
+ (importlib.util.find_spec("charset_normalizer") is None),
284
+ reason="test requires charset_normalizer which is not installed",
285
+ )
286
+ def test_encoding_comment(self):
287
+ self.module.foo(3)
288
+
289
+
290
+ class TestNameArgsPatternBacktracking:
291
+ @pytest.mark.parametrize(
292
+ ['adversary'],
293
+ [
294
+ ('@)@bind@(@',),
295
+ ('@)@bind @(@',),
296
+ ('@)@bind foo bar baz@(@',)
297
+ ]
298
+ )
299
+ def test_nameargspattern_backtracking(self, adversary):
300
+ '''address ReDOS vulnerability:
301
+ https://github.com/numpy/numpy/issues/23338'''
302
+ trials_per_batch = 12
303
+ batches_per_regex = 4
304
+ start_reps, end_reps = 15, 25
305
+ for ii in range(start_reps, end_reps):
306
+ repeated_adversary = adversary * ii
307
+ # test times in small batches.
308
+ # this gives us more chances to catch a bad regex
309
+ # while still catching it before too long if it is bad
310
+ for _ in range(batches_per_regex):
311
+ times = []
312
+ for _ in range(trials_per_batch):
313
+ t0 = time.perf_counter()
314
+ mtch = nameargspattern.search(repeated_adversary)
315
+ times.append(time.perf_counter() - t0)
316
+ # our pattern should be much faster than 0.2s per search
317
+ # it's unlikely that a bad regex will pass even on fast CPUs
318
+ assert np.median(times) < 0.2
319
+ assert not mtch
320
+ # if the adversary is capped with @)@, it becomes acceptable
321
+ # according to the old version of the regex.
322
+ # that should still be true.
323
+ good_version_of_adversary = repeated_adversary + '@)@'
324
+ assert nameargspattern.search(good_version_of_adversary)
325
+
326
+
327
+ class TestFunctionReturn(util.F2PyTest):
328
+ sources = [util.getpath("tests", "src", "crackfortran", "gh23598.f90")]
329
+
330
+ def test_function_rettype(self):
331
+ # gh-23598
332
+ assert self.module.intproduct(3, 4) == 12
333
+
334
+
335
+ class TestFortranGroupCounters(util.F2PyTest):
336
+ def test_end_if_comment(self):
337
+ # gh-23533
338
+ fpath = util.getpath("tests", "src", "crackfortran", "gh23533.f")
339
+ try:
340
+ crackfortran.crackfortran([str(fpath)])
341
+ except Exception as exc:
342
+ assert False, f"'crackfortran.crackfortran' raised an exception {exc}"
343
+
344
+
345
+ class TestF77CommonBlockReader():
346
+ def test_gh22648(self, tmp_path):
347
+ fpath = util.getpath("tests", "src", "crackfortran", "gh22648.pyf")
348
+ with contextlib.redirect_stdout(io.StringIO()) as stdout_f2py:
349
+ mod = crackfortran.crackfortran([str(fpath)])
350
+ assert "Mismatch" not in stdout_f2py.getvalue()
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_data.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pytest
3
+ import numpy as np
4
+
5
+ from . import util
6
+ from numpy.f2py.crackfortran import crackfortran
7
+
8
+
9
+ class TestData(util.F2PyTest):
10
+ sources = [util.getpath("tests", "src", "crackfortran", "data_stmts.f90")]
11
+
12
+ # For gh-23276
13
+ def test_data_stmts(self):
14
+ assert self.module.cmplxdat.i == 2
15
+ assert self.module.cmplxdat.j == 3
16
+ assert self.module.cmplxdat.x == 1.5
17
+ assert self.module.cmplxdat.y == 2.0
18
+ assert self.module.cmplxdat.pi == 3.1415926535897932384626433832795028841971693993751058209749445923078164062
19
+ assert self.module.cmplxdat.medium_ref_index == np.array(1.+0.j)
20
+ assert np.all(self.module.cmplxdat.z == np.array([3.5, 7.0]))
21
+ assert np.all(self.module.cmplxdat.my_array == np.array([ 1.+2.j, -3.+4.j]))
22
+ assert np.all(self.module.cmplxdat.my_real_array == np.array([ 1., 2., 3.]))
23
+ assert np.all(self.module.cmplxdat.ref_index_one == np.array([13.0 + 21.0j]))
24
+ assert np.all(self.module.cmplxdat.ref_index_two == np.array([-30.0 + 43.0j]))
25
+
26
+ def test_crackedlines(self):
27
+ mod = crackfortran(self.sources)
28
+ assert mod[0]['vars']['x']['='] == '1.5'
29
+ assert mod[0]['vars']['y']['='] == '2.0'
30
+ assert mod[0]['vars']['pi']['='] == '3.1415926535897932384626433832795028841971693993751058209749445923078164062d0'
31
+ assert mod[0]['vars']['my_real_array']['='] == '(/1.0d0, 2.0d0, 3.0d0/)'
32
+ assert mod[0]['vars']['ref_index_one']['='] == '(13.0d0, 21.0d0)'
33
+ assert mod[0]['vars']['ref_index_two']['='] == '(-30.0d0, 43.0d0)'
34
+ assert mod[0]['vars']['my_array']['='] == '(/(1.0d0, 2.0d0), (-3.0d0, 4.0d0)/)'
35
+ assert mod[0]['vars']['z']['='] == '(/3.5, 7.0/)'
36
+
37
+ class TestDataF77(util.F2PyTest):
38
+ sources = [util.getpath("tests", "src", "crackfortran", "data_common.f")]
39
+
40
+ # For gh-23276
41
+ def test_data_stmts(self):
42
+ assert self.module.mycom.mydata == 0
43
+
44
+ def test_crackedlines(self):
45
+ mod = crackfortran(str(self.sources[0]))
46
+ print(mod[0]['vars'])
47
+ assert mod[0]['vars']['mydata']['='] == '0'
48
+
49
+
50
+ class TestDataMultiplierF77(util.F2PyTest):
51
+ sources = [util.getpath("tests", "src", "crackfortran", "data_multiplier.f")]
52
+
53
+ # For gh-23276
54
+ def test_data_stmts(self):
55
+ assert self.module.mycom.ivar1 == 3
56
+ assert self.module.mycom.ivar2 == 3
57
+ assert self.module.mycom.ivar3 == 2
58
+ assert self.module.mycom.ivar4 == 2
59
+ assert self.module.mycom.evar5 == 0
60
+
61
+
62
+ class TestDataWithCommentsF77(util.F2PyTest):
63
+ sources = [util.getpath("tests", "src", "crackfortran", "data_with_comments.f")]
64
+
65
+ # For gh-23276
66
+ def test_data_stmts(self):
67
+ assert len(self.module.mycom.mytab) == 3
68
+ assert self.module.mycom.mytab[0] == 0
69
+ assert self.module.mycom.mytab[1] == 4
70
+ assert self.module.mycom.mytab[2] == 0
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_docs.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pytest
3
+ import numpy as np
4
+ from numpy.testing import assert_array_equal, assert_equal
5
+ from . import util
6
+
7
+
8
+ def get_docdir():
9
+ # assuming that documentation tests are run from a source
10
+ # directory
11
+ return os.path.abspath(os.path.join(
12
+ os.path.dirname(__file__),
13
+ '..', '..', '..',
14
+ 'doc', 'source', 'f2py', 'code'))
15
+
16
+
17
+ pytestmark = pytest.mark.skipif(
18
+ not os.path.isdir(get_docdir()),
19
+ reason=('Could not find f2py documentation sources'
20
+ f' ({get_docdir()} does not exists)'))
21
+
22
+
23
+ def _path(*a):
24
+ return os.path.join(*((get_docdir(),) + a))
25
+
26
+
27
+ class TestDocAdvanced(util.F2PyTest):
28
+ # options = ['--debug-capi', '--build-dir', '/tmp/build-f2py']
29
+ sources = [_path('asterisk1.f90'), _path('asterisk2.f90'),
30
+ _path('ftype.f')]
31
+
32
+ def test_asterisk1(self):
33
+ foo = getattr(self.module, 'foo1')
34
+ assert_equal(foo(), b'123456789A12')
35
+
36
+ def test_asterisk2(self):
37
+ foo = getattr(self.module, 'foo2')
38
+ assert_equal(foo(2), b'12')
39
+ assert_equal(foo(12), b'123456789A12')
40
+ assert_equal(foo(24), b'123456789A123456789B')
41
+
42
+ def test_ftype(self):
43
+ ftype = self.module
44
+ ftype.foo()
45
+ assert_equal(ftype.data.a, 0)
46
+ ftype.data.a = 3
47
+ ftype.data.x = [1, 2, 3]
48
+ assert_equal(ftype.data.a, 3)
49
+ assert_array_equal(ftype.data.x,
50
+ np.array([1, 2, 3], dtype=np.float32))
51
+ ftype.data.x[1] = 45
52
+ assert_array_equal(ftype.data.x,
53
+ np.array([1, 45, 3], dtype=np.float32))
54
+
55
+ # TODO: implement test methods for other example Fortran codes
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_f2py2e.py ADDED
@@ -0,0 +1,896 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import textwrap, re, sys, subprocess, shlex
2
+ from pathlib import Path
3
+ from collections import namedtuple
4
+ import platform
5
+
6
+ import pytest
7
+
8
+ from . import util
9
+ from numpy.f2py.f2py2e import main as f2pycli
10
+
11
+ #########################
12
+ # CLI utils and classes #
13
+ #########################
14
+
15
+ PPaths = namedtuple("PPaths", "finp, f90inp, pyf, wrap77, wrap90, cmodf")
16
+
17
+
18
+ def get_io_paths(fname_inp, mname="untitled"):
19
+ """Takes in a temporary file for testing and returns the expected output and input paths
20
+
21
+ Here expected output is essentially one of any of the possible generated
22
+ files.
23
+
24
+ ..note::
25
+
26
+ Since this does not actually run f2py, none of these are guaranteed to
27
+ exist, and module names are typically incorrect
28
+
29
+ Parameters
30
+ ----------
31
+ fname_inp : str
32
+ The input filename
33
+ mname : str, optional
34
+ The name of the module, untitled by default
35
+
36
+ Returns
37
+ -------
38
+ genp : NamedTuple PPaths
39
+ The possible paths which are generated, not all of which exist
40
+ """
41
+ bpath = Path(fname_inp)
42
+ return PPaths(
43
+ finp=bpath.with_suffix(".f"),
44
+ f90inp=bpath.with_suffix(".f90"),
45
+ pyf=bpath.with_suffix(".pyf"),
46
+ wrap77=bpath.with_name(f"{mname}-f2pywrappers.f"),
47
+ wrap90=bpath.with_name(f"{mname}-f2pywrappers2.f90"),
48
+ cmodf=bpath.with_name(f"{mname}module.c"),
49
+ )
50
+
51
+
52
+ ##############
53
+ # CLI Fixtures and Tests #
54
+ #############
55
+
56
+
57
+ @pytest.fixture(scope="session")
58
+ def hello_world_f90(tmpdir_factory):
59
+ """Generates a single f90 file for testing"""
60
+ fdat = util.getpath("tests", "src", "cli", "hiworld.f90").read_text()
61
+ fn = tmpdir_factory.getbasetemp() / "hello.f90"
62
+ fn.write_text(fdat, encoding="ascii")
63
+ return fn
64
+
65
+
66
+ @pytest.fixture(scope="session")
67
+ def gh23598_warn(tmpdir_factory):
68
+ """F90 file for testing warnings in gh23598"""
69
+ fdat = util.getpath("tests", "src", "crackfortran", "gh23598Warn.f90").read_text()
70
+ fn = tmpdir_factory.getbasetemp() / "gh23598Warn.f90"
71
+ fn.write_text(fdat, encoding="ascii")
72
+ return fn
73
+
74
+
75
+ @pytest.fixture(scope="session")
76
+ def gh22819_cli(tmpdir_factory):
77
+ """F90 file for testing disallowed CLI arguments in ghff819"""
78
+ fdat = util.getpath("tests", "src", "cli", "gh_22819.pyf").read_text()
79
+ fn = tmpdir_factory.getbasetemp() / "gh_22819.pyf"
80
+ fn.write_text(fdat, encoding="ascii")
81
+ return fn
82
+
83
+
84
+ @pytest.fixture(scope="session")
85
+ def hello_world_f77(tmpdir_factory):
86
+ """Generates a single f77 file for testing"""
87
+ fdat = util.getpath("tests", "src", "cli", "hi77.f").read_text()
88
+ fn = tmpdir_factory.getbasetemp() / "hello.f"
89
+ fn.write_text(fdat, encoding="ascii")
90
+ return fn
91
+
92
+
93
+ @pytest.fixture(scope="session")
94
+ def retreal_f77(tmpdir_factory):
95
+ """Generates a single f77 file for testing"""
96
+ fdat = util.getpath("tests", "src", "return_real", "foo77.f").read_text()
97
+ fn = tmpdir_factory.getbasetemp() / "foo.f"
98
+ fn.write_text(fdat, encoding="ascii")
99
+ return fn
100
+
101
+ @pytest.fixture(scope="session")
102
+ def f2cmap_f90(tmpdir_factory):
103
+ """Generates a single f90 file for testing"""
104
+ fdat = util.getpath("tests", "src", "f2cmap", "isoFortranEnvMap.f90").read_text()
105
+ f2cmap = util.getpath("tests", "src", "f2cmap", ".f2py_f2cmap").read_text()
106
+ fn = tmpdir_factory.getbasetemp() / "f2cmap.f90"
107
+ fmap = tmpdir_factory.getbasetemp() / "mapfile"
108
+ fn.write_text(fdat, encoding="ascii")
109
+ fmap.write_text(f2cmap, encoding="ascii")
110
+ return fn
111
+
112
+
113
+ def test_gh22819_cli(capfd, gh22819_cli, monkeypatch):
114
+ """Check that module names are handled correctly
115
+ gh-22819
116
+ Essentially, the -m name cannot be used to import the module, so the module
117
+ named in the .pyf needs to be used instead
118
+
119
+ CLI :: -m and a .pyf file
120
+ """
121
+ ipath = Path(gh22819_cli)
122
+ monkeypatch.setattr(sys, "argv", f"f2py -m blah {ipath}".split())
123
+ with util.switchdir(ipath.parent):
124
+ f2pycli()
125
+ gen_paths = [item.name for item in ipath.parent.rglob("*") if item.is_file()]
126
+ assert "blahmodule.c" not in gen_paths # shouldn't be generated
127
+ assert "blah-f2pywrappers.f" not in gen_paths
128
+ assert "test_22819-f2pywrappers.f" in gen_paths
129
+ assert "test_22819module.c" in gen_paths
130
+ assert "Ignoring blah"
131
+
132
+
133
+ def test_gh22819_many_pyf(capfd, gh22819_cli, monkeypatch):
134
+ """Only one .pyf file allowed
135
+ gh-22819
136
+ CLI :: .pyf files
137
+ """
138
+ ipath = Path(gh22819_cli)
139
+ monkeypatch.setattr(sys, "argv", f"f2py -m blah {ipath} hello.pyf".split())
140
+ with util.switchdir(ipath.parent):
141
+ with pytest.raises(ValueError, match="Only one .pyf file per call"):
142
+ f2pycli()
143
+
144
+
145
+ def test_gh23598_warn(capfd, gh23598_warn, monkeypatch):
146
+ foutl = get_io_paths(gh23598_warn, mname="test")
147
+ ipath = foutl.f90inp
148
+ monkeypatch.setattr(
149
+ sys, "argv",
150
+ f'f2py {ipath} -m test'.split())
151
+
152
+ with util.switchdir(ipath.parent):
153
+ f2pycli() # Generate files
154
+ wrapper = foutl.wrap90.read_text()
155
+ assert "intproductf2pywrap, intpr" not in wrapper
156
+
157
+
158
+ def test_gen_pyf(capfd, hello_world_f90, monkeypatch):
159
+ """Ensures that a signature file is generated via the CLI
160
+ CLI :: -h
161
+ """
162
+ ipath = Path(hello_world_f90)
163
+ opath = Path(hello_world_f90).stem + ".pyf"
164
+ monkeypatch.setattr(sys, "argv", f'f2py -h {opath} {ipath}'.split())
165
+
166
+ with util.switchdir(ipath.parent):
167
+ f2pycli() # Generate wrappers
168
+ out, _ = capfd.readouterr()
169
+ assert "Saving signatures to file" in out
170
+ assert Path(f'{opath}').exists()
171
+
172
+
173
+ def test_gen_pyf_stdout(capfd, hello_world_f90, monkeypatch):
174
+ """Ensures that a signature file can be dumped to stdout
175
+ CLI :: -h
176
+ """
177
+ ipath = Path(hello_world_f90)
178
+ monkeypatch.setattr(sys, "argv", f'f2py -h stdout {ipath}'.split())
179
+ with util.switchdir(ipath.parent):
180
+ f2pycli()
181
+ out, _ = capfd.readouterr()
182
+ assert "Saving signatures to file" in out
183
+ assert "function hi() ! in " in out
184
+
185
+
186
+ def test_gen_pyf_no_overwrite(capfd, hello_world_f90, monkeypatch):
187
+ """Ensures that the CLI refuses to overwrite signature files
188
+ CLI :: -h without --overwrite-signature
189
+ """
190
+ ipath = Path(hello_world_f90)
191
+ monkeypatch.setattr(sys, "argv", f'f2py -h faker.pyf {ipath}'.split())
192
+
193
+ with util.switchdir(ipath.parent):
194
+ Path("faker.pyf").write_text("Fake news", encoding="ascii")
195
+ with pytest.raises(SystemExit):
196
+ f2pycli() # Refuse to overwrite
197
+ _, err = capfd.readouterr()
198
+ assert "Use --overwrite-signature to overwrite" in err
199
+
200
+
201
+ @pytest.mark.skipif((platform.system() != 'Linux') or (sys.version_info <= (3, 12)),
202
+ reason='Compiler and 3.12 required')
203
+ def test_untitled_cli(capfd, hello_world_f90, monkeypatch):
204
+ """Check that modules are named correctly
205
+
206
+ CLI :: defaults
207
+ """
208
+ ipath = Path(hello_world_f90)
209
+ monkeypatch.setattr(sys, "argv", f"f2py --backend meson -c {ipath}".split())
210
+ with util.switchdir(ipath.parent):
211
+ f2pycli()
212
+ out, _ = capfd.readouterr()
213
+ assert "untitledmodule.c" in out
214
+
215
+
216
+ @pytest.mark.skipif((platform.system() != 'Linux') or (sys.version_info <= (3, 12)), reason='Compiler and 3.12 required')
217
+ def test_no_py312_distutils_fcompiler(capfd, hello_world_f90, monkeypatch):
218
+ """Check that no distutils imports are performed on 3.12
219
+ CLI :: --fcompiler --help-link --backend distutils
220
+ """
221
+ MNAME = "hi"
222
+ foutl = get_io_paths(hello_world_f90, mname=MNAME)
223
+ ipath = foutl.f90inp
224
+ monkeypatch.setattr(
225
+ sys, "argv", f"f2py {ipath} -c --fcompiler=gfortran -m {MNAME}".split()
226
+ )
227
+ with util.switchdir(ipath.parent):
228
+ f2pycli()
229
+ out, _ = capfd.readouterr()
230
+ assert "--fcompiler cannot be used with meson" in out
231
+ monkeypatch.setattr(
232
+ sys, "argv", f"f2py --help-link".split()
233
+ )
234
+ with util.switchdir(ipath.parent):
235
+ f2pycli()
236
+ out, _ = capfd.readouterr()
237
+ assert "Use --dep for meson builds" in out
238
+ MNAME = "hi2" # Needs to be different for a new -c
239
+ monkeypatch.setattr(
240
+ sys, "argv", f"f2py {ipath} -c -m {MNAME} --backend distutils".split()
241
+ )
242
+ with util.switchdir(ipath.parent):
243
+ f2pycli()
244
+ out, _ = capfd.readouterr()
245
+ assert "Cannot use distutils backend with Python>=3.12" in out
246
+
247
+
248
+ @pytest.mark.xfail
249
+ def test_f2py_skip(capfd, retreal_f77, monkeypatch):
250
+ """Tests that functions can be skipped
251
+ CLI :: skip:
252
+ """
253
+ foutl = get_io_paths(retreal_f77, mname="test")
254
+ ipath = foutl.finp
255
+ toskip = "t0 t4 t8 sd s8 s4"
256
+ remaining = "td s0"
257
+ monkeypatch.setattr(
258
+ sys, "argv",
259
+ f'f2py {ipath} -m test skip: {toskip}'.split())
260
+
261
+ with util.switchdir(ipath.parent):
262
+ f2pycli()
263
+ out, err = capfd.readouterr()
264
+ for skey in toskip.split():
265
+ assert (
266
+ f'buildmodule: Could not found the body of interfaced routine "{skey}". Skipping.'
267
+ in err)
268
+ for rkey in remaining.split():
269
+ assert f'Constructing wrapper function "{rkey}"' in out
270
+
271
+
272
+ def test_f2py_only(capfd, retreal_f77, monkeypatch):
273
+ """Test that functions can be kept by only:
274
+ CLI :: only:
275
+ """
276
+ foutl = get_io_paths(retreal_f77, mname="test")
277
+ ipath = foutl.finp
278
+ toskip = "t0 t4 t8 sd s8 s4"
279
+ tokeep = "td s0"
280
+ monkeypatch.setattr(
281
+ sys, "argv",
282
+ f'f2py {ipath} -m test only: {tokeep}'.split())
283
+
284
+ with util.switchdir(ipath.parent):
285
+ f2pycli()
286
+ out, err = capfd.readouterr()
287
+ for skey in toskip.split():
288
+ assert (
289
+ f'buildmodule: Could not find the body of interfaced routine "{skey}". Skipping.'
290
+ in err)
291
+ for rkey in tokeep.split():
292
+ assert f'Constructing wrapper function "{rkey}"' in out
293
+
294
+
295
+ def test_file_processing_switch(capfd, hello_world_f90, retreal_f77,
296
+ monkeypatch):
297
+ """Tests that it is possible to return to file processing mode
298
+ CLI :: :
299
+ BUG: numpy-gh #20520
300
+ """
301
+ foutl = get_io_paths(retreal_f77, mname="test")
302
+ ipath = foutl.finp
303
+ toskip = "t0 t4 t8 sd s8 s4"
304
+ ipath2 = Path(hello_world_f90)
305
+ tokeep = "td s0 hi" # hi is in ipath2
306
+ mname = "blah"
307
+ monkeypatch.setattr(
308
+ sys,
309
+ "argv",
310
+ f'f2py {ipath} -m {mname} only: {tokeep} : {ipath2}'.split(
311
+ ),
312
+ )
313
+
314
+ with util.switchdir(ipath.parent):
315
+ f2pycli()
316
+ out, err = capfd.readouterr()
317
+ for skey in toskip.split():
318
+ assert (
319
+ f'buildmodule: Could not find the body of interfaced routine "{skey}". Skipping.'
320
+ in err)
321
+ for rkey in tokeep.split():
322
+ assert f'Constructing wrapper function "{rkey}"' in out
323
+
324
+
325
+ def test_mod_gen_f77(capfd, hello_world_f90, monkeypatch):
326
+ """Checks the generation of files based on a module name
327
+ CLI :: -m
328
+ """
329
+ MNAME = "hi"
330
+ foutl = get_io_paths(hello_world_f90, mname=MNAME)
331
+ ipath = foutl.f90inp
332
+ monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m {MNAME}'.split())
333
+ with util.switchdir(ipath.parent):
334
+ f2pycli()
335
+
336
+ # Always generate C module
337
+ assert Path.exists(foutl.cmodf)
338
+ # File contains a function, check for F77 wrappers
339
+ assert Path.exists(foutl.wrap77)
340
+
341
+
342
+ def test_mod_gen_gh25263(capfd, hello_world_f77, monkeypatch):
343
+ """Check that pyf files are correctly generated with module structure
344
+ CLI :: -m <name> -h pyf_file
345
+ BUG: numpy-gh #20520
346
+ """
347
+ MNAME = "hi"
348
+ foutl = get_io_paths(hello_world_f77, mname=MNAME)
349
+ ipath = foutl.finp
350
+ monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m {MNAME} -h hi.pyf'.split())
351
+ with util.switchdir(ipath.parent):
352
+ f2pycli()
353
+ with Path('hi.pyf').open() as hipyf:
354
+ pyfdat = hipyf.read()
355
+ assert "python module hi" in pyfdat
356
+
357
+
358
+ def test_lower_cmod(capfd, hello_world_f77, monkeypatch):
359
+ """Lowers cases by flag or when -h is present
360
+
361
+ CLI :: --[no-]lower
362
+ """
363
+ foutl = get_io_paths(hello_world_f77, mname="test")
364
+ ipath = foutl.finp
365
+ capshi = re.compile(r"HI\(\)")
366
+ capslo = re.compile(r"hi\(\)")
367
+ # Case I: --lower is passed
368
+ monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m test --lower'.split())
369
+ with util.switchdir(ipath.parent):
370
+ f2pycli()
371
+ out, _ = capfd.readouterr()
372
+ assert capslo.search(out) is not None
373
+ assert capshi.search(out) is None
374
+ # Case II: --no-lower is passed
375
+ monkeypatch.setattr(sys, "argv",
376
+ f'f2py {ipath} -m test --no-lower'.split())
377
+ with util.switchdir(ipath.parent):
378
+ f2pycli()
379
+ out, _ = capfd.readouterr()
380
+ assert capslo.search(out) is None
381
+ assert capshi.search(out) is not None
382
+
383
+
384
+ def test_lower_sig(capfd, hello_world_f77, monkeypatch):
385
+ """Lowers cases in signature files by flag or when -h is present
386
+
387
+ CLI :: --[no-]lower -h
388
+ """
389
+ foutl = get_io_paths(hello_world_f77, mname="test")
390
+ ipath = foutl.finp
391
+ # Signature files
392
+ capshi = re.compile(r"Block: HI")
393
+ capslo = re.compile(r"Block: hi")
394
+ # Case I: --lower is implied by -h
395
+ # TODO: Clean up to prevent passing --overwrite-signature
396
+ monkeypatch.setattr(
397
+ sys,
398
+ "argv",
399
+ f'f2py {ipath} -h {foutl.pyf} -m test --overwrite-signature'.split(),
400
+ )
401
+
402
+ with util.switchdir(ipath.parent):
403
+ f2pycli()
404
+ out, _ = capfd.readouterr()
405
+ assert capslo.search(out) is not None
406
+ assert capshi.search(out) is None
407
+
408
+ # Case II: --no-lower overrides -h
409
+ monkeypatch.setattr(
410
+ sys,
411
+ "argv",
412
+ f'f2py {ipath} -h {foutl.pyf} -m test --overwrite-signature --no-lower'
413
+ .split(),
414
+ )
415
+
416
+ with util.switchdir(ipath.parent):
417
+ f2pycli()
418
+ out, _ = capfd.readouterr()
419
+ assert capslo.search(out) is None
420
+ assert capshi.search(out) is not None
421
+
422
+
423
+ def test_build_dir(capfd, hello_world_f90, monkeypatch):
424
+ """Ensures that the build directory can be specified
425
+
426
+ CLI :: --build-dir
427
+ """
428
+ ipath = Path(hello_world_f90)
429
+ mname = "blah"
430
+ odir = "tttmp"
431
+ monkeypatch.setattr(sys, "argv",
432
+ f'f2py -m {mname} {ipath} --build-dir {odir}'.split())
433
+
434
+ with util.switchdir(ipath.parent):
435
+ f2pycli()
436
+ out, _ = capfd.readouterr()
437
+ assert f"Wrote C/API module \"{mname}\"" in out
438
+
439
+
440
+ def test_overwrite(capfd, hello_world_f90, monkeypatch):
441
+ """Ensures that the build directory can be specified
442
+
443
+ CLI :: --overwrite-signature
444
+ """
445
+ ipath = Path(hello_world_f90)
446
+ monkeypatch.setattr(
447
+ sys, "argv",
448
+ f'f2py -h faker.pyf {ipath} --overwrite-signature'.split())
449
+
450
+ with util.switchdir(ipath.parent):
451
+ Path("faker.pyf").write_text("Fake news", encoding="ascii")
452
+ f2pycli()
453
+ out, _ = capfd.readouterr()
454
+ assert "Saving signatures to file" in out
455
+
456
+
457
+ def test_latexdoc(capfd, hello_world_f90, monkeypatch):
458
+ """Ensures that TeX documentation is written out
459
+
460
+ CLI :: --latex-doc
461
+ """
462
+ ipath = Path(hello_world_f90)
463
+ mname = "blah"
464
+ monkeypatch.setattr(sys, "argv",
465
+ f'f2py -m {mname} {ipath} --latex-doc'.split())
466
+
467
+ with util.switchdir(ipath.parent):
468
+ f2pycli()
469
+ out, _ = capfd.readouterr()
470
+ assert "Documentation is saved to file" in out
471
+ with Path(f"{mname}module.tex").open() as otex:
472
+ assert "\\documentclass" in otex.read()
473
+
474
+
475
+ def test_nolatexdoc(capfd, hello_world_f90, monkeypatch):
476
+ """Ensures that TeX documentation is written out
477
+
478
+ CLI :: --no-latex-doc
479
+ """
480
+ ipath = Path(hello_world_f90)
481
+ mname = "blah"
482
+ monkeypatch.setattr(sys, "argv",
483
+ f'f2py -m {mname} {ipath} --no-latex-doc'.split())
484
+
485
+ with util.switchdir(ipath.parent):
486
+ f2pycli()
487
+ out, _ = capfd.readouterr()
488
+ assert "Documentation is saved to file" not in out
489
+
490
+
491
+ def test_shortlatex(capfd, hello_world_f90, monkeypatch):
492
+ """Ensures that truncated documentation is written out
493
+
494
+ TODO: Test to ensure this has no effect without --latex-doc
495
+ CLI :: --latex-doc --short-latex
496
+ """
497
+ ipath = Path(hello_world_f90)
498
+ mname = "blah"
499
+ monkeypatch.setattr(
500
+ sys,
501
+ "argv",
502
+ f'f2py -m {mname} {ipath} --latex-doc --short-latex'.split(),
503
+ )
504
+
505
+ with util.switchdir(ipath.parent):
506
+ f2pycli()
507
+ out, _ = capfd.readouterr()
508
+ assert "Documentation is saved to file" in out
509
+ with Path(f"./{mname}module.tex").open() as otex:
510
+ assert "\\documentclass" not in otex.read()
511
+
512
+
513
+ def test_restdoc(capfd, hello_world_f90, monkeypatch):
514
+ """Ensures that RsT documentation is written out
515
+
516
+ CLI :: --rest-doc
517
+ """
518
+ ipath = Path(hello_world_f90)
519
+ mname = "blah"
520
+ monkeypatch.setattr(sys, "argv",
521
+ f'f2py -m {mname} {ipath} --rest-doc'.split())
522
+
523
+ with util.switchdir(ipath.parent):
524
+ f2pycli()
525
+ out, _ = capfd.readouterr()
526
+ assert "ReST Documentation is saved to file" in out
527
+ with Path(f"./{mname}module.rest").open() as orst:
528
+ assert r".. -*- rest -*-" in orst.read()
529
+
530
+
531
+ def test_norestexdoc(capfd, hello_world_f90, monkeypatch):
532
+ """Ensures that TeX documentation is written out
533
+
534
+ CLI :: --no-rest-doc
535
+ """
536
+ ipath = Path(hello_world_f90)
537
+ mname = "blah"
538
+ monkeypatch.setattr(sys, "argv",
539
+ f'f2py -m {mname} {ipath} --no-rest-doc'.split())
540
+
541
+ with util.switchdir(ipath.parent):
542
+ f2pycli()
543
+ out, _ = capfd.readouterr()
544
+ assert "ReST Documentation is saved to file" not in out
545
+
546
+
547
+ def test_debugcapi(capfd, hello_world_f90, monkeypatch):
548
+ """Ensures that debugging wrappers are written
549
+
550
+ CLI :: --debug-capi
551
+ """
552
+ ipath = Path(hello_world_f90)
553
+ mname = "blah"
554
+ monkeypatch.setattr(sys, "argv",
555
+ f'f2py -m {mname} {ipath} --debug-capi'.split())
556
+
557
+ with util.switchdir(ipath.parent):
558
+ f2pycli()
559
+ with Path(f"./{mname}module.c").open() as ocmod:
560
+ assert r"#define DEBUGCFUNCS" in ocmod.read()
561
+
562
+
563
+ @pytest.mark.xfail(reason="Consistently fails on CI.")
564
+ def test_debugcapi_bld(hello_world_f90, monkeypatch):
565
+ """Ensures that debugging wrappers work
566
+
567
+ CLI :: --debug-capi -c
568
+ """
569
+ ipath = Path(hello_world_f90)
570
+ mname = "blah"
571
+ monkeypatch.setattr(sys, "argv",
572
+ f'f2py -m {mname} {ipath} -c --debug-capi'.split())
573
+
574
+ with util.switchdir(ipath.parent):
575
+ f2pycli()
576
+ cmd_run = shlex.split("python3 -c \"import blah; blah.hi()\"")
577
+ rout = subprocess.run(cmd_run, capture_output=True, encoding='UTF-8')
578
+ eout = ' Hello World\n'
579
+ eerr = textwrap.dedent("""\
580
+ debug-capi:Python C/API function blah.hi()
581
+ debug-capi:float hi=:output,hidden,scalar
582
+ debug-capi:hi=0
583
+ debug-capi:Fortran subroutine `f2pywraphi(&hi)'
584
+ debug-capi:hi=0
585
+ debug-capi:Building return value.
586
+ debug-capi:Python C/API function blah.hi: successful.
587
+ debug-capi:Freeing memory.
588
+ """)
589
+ assert rout.stdout == eout
590
+ assert rout.stderr == eerr
591
+
592
+
593
+ def test_wrapfunc_def(capfd, hello_world_f90, monkeypatch):
594
+ """Ensures that fortran subroutine wrappers for F77 are included by default
595
+
596
+ CLI :: --[no]-wrap-functions
597
+ """
598
+ # Implied
599
+ ipath = Path(hello_world_f90)
600
+ mname = "blah"
601
+ monkeypatch.setattr(sys, "argv", f'f2py -m {mname} {ipath}'.split())
602
+
603
+ with util.switchdir(ipath.parent):
604
+ f2pycli()
605
+ out, _ = capfd.readouterr()
606
+ assert r"Fortran 77 wrappers are saved to" in out
607
+
608
+ # Explicit
609
+ monkeypatch.setattr(sys, "argv",
610
+ f'f2py -m {mname} {ipath} --wrap-functions'.split())
611
+
612
+ with util.switchdir(ipath.parent):
613
+ f2pycli()
614
+ out, _ = capfd.readouterr()
615
+ assert r"Fortran 77 wrappers are saved to" in out
616
+
617
+
618
+ def test_nowrapfunc(capfd, hello_world_f90, monkeypatch):
619
+ """Ensures that fortran subroutine wrappers for F77 can be disabled
620
+
621
+ CLI :: --no-wrap-functions
622
+ """
623
+ ipath = Path(hello_world_f90)
624
+ mname = "blah"
625
+ monkeypatch.setattr(sys, "argv",
626
+ f'f2py -m {mname} {ipath} --no-wrap-functions'.split())
627
+
628
+ with util.switchdir(ipath.parent):
629
+ f2pycli()
630
+ out, _ = capfd.readouterr()
631
+ assert r"Fortran 77 wrappers are saved to" not in out
632
+
633
+
634
+ def test_inclheader(capfd, hello_world_f90, monkeypatch):
635
+ """Add to the include directories
636
+
637
+ CLI :: -include
638
+ TODO: Document this in the help string
639
+ """
640
+ ipath = Path(hello_world_f90)
641
+ mname = "blah"
642
+ monkeypatch.setattr(
643
+ sys,
644
+ "argv",
645
+ f'f2py -m {mname} {ipath} -include<stdbool.h> -include<stdio.h> '.
646
+ split(),
647
+ )
648
+
649
+ with util.switchdir(ipath.parent):
650
+ f2pycli()
651
+ with Path(f"./{mname}module.c").open() as ocmod:
652
+ ocmr = ocmod.read()
653
+ assert "#include <stdbool.h>" in ocmr
654
+ assert "#include <stdio.h>" in ocmr
655
+
656
+
657
+ def test_inclpath():
658
+ """Add to the include directories
659
+
660
+ CLI :: --include-paths
661
+ """
662
+ # TODO: populate
663
+ pass
664
+
665
+
666
+ def test_hlink():
667
+ """Add to the include directories
668
+
669
+ CLI :: --help-link
670
+ """
671
+ # TODO: populate
672
+ pass
673
+
674
+
675
+ def test_f2cmap(capfd, f2cmap_f90, monkeypatch):
676
+ """Check that Fortran-to-Python KIND specs can be passed
677
+
678
+ CLI :: --f2cmap
679
+ """
680
+ ipath = Path(f2cmap_f90)
681
+ monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} --f2cmap mapfile'.split())
682
+
683
+ with util.switchdir(ipath.parent):
684
+ f2pycli()
685
+ out, _ = capfd.readouterr()
686
+ assert "Reading f2cmap from 'mapfile' ..." in out
687
+ assert "Mapping \"real(kind=real32)\" to \"float\"" in out
688
+ assert "Mapping \"real(kind=real64)\" to \"double\"" in out
689
+ assert "Mapping \"integer(kind=int64)\" to \"long_long\"" in out
690
+ assert "Successfully applied user defined f2cmap changes" in out
691
+
692
+
693
+ def test_quiet(capfd, hello_world_f90, monkeypatch):
694
+ """Reduce verbosity
695
+
696
+ CLI :: --quiet
697
+ """
698
+ ipath = Path(hello_world_f90)
699
+ monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} --quiet'.split())
700
+
701
+ with util.switchdir(ipath.parent):
702
+ f2pycli()
703
+ out, _ = capfd.readouterr()
704
+ assert len(out) == 0
705
+
706
+
707
+ def test_verbose(capfd, hello_world_f90, monkeypatch):
708
+ """Increase verbosity
709
+
710
+ CLI :: --verbose
711
+ """
712
+ ipath = Path(hello_world_f90)
713
+ monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} --verbose'.split())
714
+
715
+ with util.switchdir(ipath.parent):
716
+ f2pycli()
717
+ out, _ = capfd.readouterr()
718
+ assert "analyzeline" in out
719
+
720
+
721
+ def test_version(capfd, monkeypatch):
722
+ """Ensure version
723
+
724
+ CLI :: -v
725
+ """
726
+ monkeypatch.setattr(sys, "argv", 'f2py -v'.split())
727
+ # TODO: f2py2e should not call sys.exit() after printing the version
728
+ with pytest.raises(SystemExit):
729
+ f2pycli()
730
+ out, _ = capfd.readouterr()
731
+ import numpy as np
732
+ assert np.__version__ == out.strip()
733
+
734
+
735
+ @pytest.mark.xfail(reason="Consistently fails on CI.")
736
+ def test_npdistop(hello_world_f90, monkeypatch):
737
+ """
738
+ CLI :: -c
739
+ """
740
+ ipath = Path(hello_world_f90)
741
+ monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} -c'.split())
742
+
743
+ with util.switchdir(ipath.parent):
744
+ f2pycli()
745
+ cmd_run = shlex.split("python -c \"import blah; blah.hi()\"")
746
+ rout = subprocess.run(cmd_run, capture_output=True, encoding='UTF-8')
747
+ eout = ' Hello World\n'
748
+ assert rout.stdout == eout
749
+
750
+
751
+ # Numpy distutils flags
752
+ # TODO: These should be tested separately
753
+
754
+
755
+ def test_npd_fcompiler():
756
+ """
757
+ CLI :: -c --fcompiler
758
+ """
759
+ # TODO: populate
760
+ pass
761
+
762
+
763
+ def test_npd_compiler():
764
+ """
765
+ CLI :: -c --compiler
766
+ """
767
+ # TODO: populate
768
+ pass
769
+
770
+
771
+ def test_npd_help_fcompiler():
772
+ """
773
+ CLI :: -c --help-fcompiler
774
+ """
775
+ # TODO: populate
776
+ pass
777
+
778
+
779
+ def test_npd_f77exec():
780
+ """
781
+ CLI :: -c --f77exec
782
+ """
783
+ # TODO: populate
784
+ pass
785
+
786
+
787
+ def test_npd_f90exec():
788
+ """
789
+ CLI :: -c --f90exec
790
+ """
791
+ # TODO: populate
792
+ pass
793
+
794
+
795
+ def test_npd_f77flags():
796
+ """
797
+ CLI :: -c --f77flags
798
+ """
799
+ # TODO: populate
800
+ pass
801
+
802
+
803
+ def test_npd_f90flags():
804
+ """
805
+ CLI :: -c --f90flags
806
+ """
807
+ # TODO: populate
808
+ pass
809
+
810
+
811
+ def test_npd_opt():
812
+ """
813
+ CLI :: -c --opt
814
+ """
815
+ # TODO: populate
816
+ pass
817
+
818
+
819
+ def test_npd_arch():
820
+ """
821
+ CLI :: -c --arch
822
+ """
823
+ # TODO: populate
824
+ pass
825
+
826
+
827
+ def test_npd_noopt():
828
+ """
829
+ CLI :: -c --noopt
830
+ """
831
+ # TODO: populate
832
+ pass
833
+
834
+
835
+ def test_npd_noarch():
836
+ """
837
+ CLI :: -c --noarch
838
+ """
839
+ # TODO: populate
840
+ pass
841
+
842
+
843
+ def test_npd_debug():
844
+ """
845
+ CLI :: -c --debug
846
+ """
847
+ # TODO: populate
848
+ pass
849
+
850
+
851
+ def test_npd_link_auto():
852
+ """
853
+ CLI :: -c --link-<resource>
854
+ """
855
+ # TODO: populate
856
+ pass
857
+
858
+
859
+ def test_npd_lib():
860
+ """
861
+ CLI :: -c -L/path/to/lib/ -l<libname>
862
+ """
863
+ # TODO: populate
864
+ pass
865
+
866
+
867
+ def test_npd_define():
868
+ """
869
+ CLI :: -D<define>
870
+ """
871
+ # TODO: populate
872
+ pass
873
+
874
+
875
+ def test_npd_undefine():
876
+ """
877
+ CLI :: -U<name>
878
+ """
879
+ # TODO: populate
880
+ pass
881
+
882
+
883
+ def test_npd_incl():
884
+ """
885
+ CLI :: -I/path/to/include/
886
+ """
887
+ # TODO: populate
888
+ pass
889
+
890
+
891
+ def test_npd_linker():
892
+ """
893
+ CLI :: <filename>.o <filename>.so <filename>.a
894
+ """
895
+ # TODO: populate
896
+ pass
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_isoc.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import util
2
+ import numpy as np
3
+ import pytest
4
+ from numpy.testing import assert_allclose
5
+
6
+ class TestISOC(util.F2PyTest):
7
+ sources = [
8
+ util.getpath("tests", "src", "isocintrin", "isoCtests.f90"),
9
+ ]
10
+
11
+ # gh-24553
12
+ def test_c_double(self):
13
+ out = self.module.coddity.c_add(1, 2)
14
+ exp_out = 3
15
+ assert out == exp_out
16
+
17
+ # gh-9693
18
+ def test_bindc_function(self):
19
+ out = self.module.coddity.wat(1, 20)
20
+ exp_out = 8
21
+ assert out == exp_out
22
+
23
+ # gh-25207
24
+ def test_bindc_kinds(self):
25
+ out = self.module.coddity.c_add_int64(1, 20)
26
+ exp_out = 21
27
+ assert out == exp_out
28
+
29
+ # gh-25207
30
+ def test_bindc_add_arr(self):
31
+ a = np.array([1,2,3])
32
+ b = np.array([1,2,3])
33
+ out = self.module.coddity.add_arr(a, b)
34
+ exp_out = a*2
35
+ assert_allclose(out, exp_out)
36
+
37
+
38
+ def test_process_f2cmap_dict():
39
+ from numpy.f2py.auxfuncs import process_f2cmap_dict
40
+
41
+ f2cmap_all = {"integer": {"8": "rubbish_type"}}
42
+ new_map = {"INTEGER": {"4": "int"}}
43
+ c2py_map = {"int": "int", "rubbish_type": "long"}
44
+
45
+ exp_map, exp_maptyp = ({"integer": {"8": "rubbish_type", "4": "int"}}, ["int"])
46
+
47
+ # Call the function
48
+ res_map, res_maptyp = process_f2cmap_dict(f2cmap_all, new_map, c2py_map)
49
+
50
+ # Assert the result is as expected
51
+ assert res_map == exp_map
52
+ assert res_maptyp == exp_maptyp
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_kind.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pytest
3
+ import platform
4
+
5
+ from numpy.f2py.crackfortran import (
6
+ _selected_int_kind_func as selected_int_kind,
7
+ _selected_real_kind_func as selected_real_kind,
8
+ )
9
+ from . import util
10
+
11
+
12
+ class TestKind(util.F2PyTest):
13
+ sources = [util.getpath("tests", "src", "kind", "foo.f90")]
14
+
15
+ def test_int(self):
16
+ """Test `int` kind_func for integers up to 10**40."""
17
+ selectedintkind = self.module.selectedintkind
18
+
19
+ for i in range(40):
20
+ assert selectedintkind(i) == selected_int_kind(
21
+ i
22
+ ), f"selectedintkind({i}): expected {selected_int_kind(i)!r} but got {selectedintkind(i)!r}"
23
+
24
+ def test_real(self):
25
+ """
26
+ Test (processor-dependent) `real` kind_func for real numbers
27
+ of up to 31 digits precision (extended/quadruple).
28
+ """
29
+ selectedrealkind = self.module.selectedrealkind
30
+
31
+ for i in range(32):
32
+ assert selectedrealkind(i) == selected_real_kind(
33
+ i
34
+ ), f"selectedrealkind({i}): expected {selected_real_kind(i)!r} but got {selectedrealkind(i)!r}"
35
+
36
+ @pytest.mark.xfail(platform.machine().lower().startswith("ppc"),
37
+ reason="Some PowerPC may not support full IEEE 754 precision")
38
+ def test_quad_precision(self):
39
+ """
40
+ Test kind_func for quadruple precision [`real(16)`] of 32+ digits .
41
+ """
42
+ selectedrealkind = self.module.selectedrealkind
43
+
44
+ for i in range(32, 40):
45
+ assert selectedrealkind(i) == selected_real_kind(
46
+ i
47
+ ), f"selectedrealkind({i}): expected {selected_real_kind(i)!r} but got {selectedrealkind(i)!r}"
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_mixed.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import textwrap
3
+ import pytest
4
+
5
+ from numpy.testing import IS_PYPY
6
+ from . import util
7
+
8
+
9
+ class TestMixed(util.F2PyTest):
10
+ sources = [
11
+ util.getpath("tests", "src", "mixed", "foo.f"),
12
+ util.getpath("tests", "src", "mixed", "foo_fixed.f90"),
13
+ util.getpath("tests", "src", "mixed", "foo_free.f90"),
14
+ ]
15
+
16
+ def test_all(self):
17
+ assert self.module.bar11() == 11
18
+ assert self.module.foo_fixed.bar12() == 12
19
+ assert self.module.foo_free.bar13() == 13
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 = bar11()
26
+
27
+ Wrapper for ``bar11``.
28
+
29
+ Returns
30
+ -------
31
+ a : int
32
+ """)
33
+ assert self.module.bar11.__doc__ == expected
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_pyf_src.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This test is ported from numpy.distutils
2
+ from numpy.f2py._src_pyf import process_str
3
+ from numpy.testing import assert_equal
4
+
5
+
6
+ pyf_src = """
7
+ python module foo
8
+ <_rd=real,double precision>
9
+ interface
10
+ subroutine <s,d>foosub(tol)
11
+ <_rd>, intent(in,out) :: tol
12
+ end subroutine <s,d>foosub
13
+ end interface
14
+ end python module foo
15
+ """
16
+
17
+ expected_pyf = """
18
+ python module foo
19
+ interface
20
+ subroutine sfoosub(tol)
21
+ real, intent(in,out) :: tol
22
+ end subroutine sfoosub
23
+ subroutine dfoosub(tol)
24
+ double precision, intent(in,out) :: tol
25
+ end subroutine dfoosub
26
+ end interface
27
+ end python module foo
28
+ """
29
+
30
+
31
+ def normalize_whitespace(s):
32
+ """
33
+ Remove leading and trailing whitespace, and convert internal
34
+ stretches of whitespace to a single space.
35
+ """
36
+ return ' '.join(s.split())
37
+
38
+
39
+ def test_from_template():
40
+ """Regression test for gh-10712."""
41
+ pyf = process_str(pyf_src)
42
+ normalized_pyf = normalize_whitespace(pyf)
43
+ normalized_expected_pyf = normalize_whitespace(expected_pyf)
44
+ assert_equal(normalized_pyf, normalized_expected_pyf)
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_return_character.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from numpy import array
4
+ from . import util
5
+ import platform
6
+
7
+ IS_S390X = platform.machine() == "s390x"
8
+
9
+
10
+ class TestReturnCharacter(util.F2PyTest):
11
+ def check_function(self, t, tname):
12
+ if tname in ["t0", "t1", "s0", "s1"]:
13
+ assert t("23") == b"2"
14
+ r = t("ab")
15
+ assert r == b"a"
16
+ r = t(array("ab"))
17
+ assert r == b"a"
18
+ r = t(array(77, "u1"))
19
+ assert r == b"M"
20
+ elif tname in ["ts", "ss"]:
21
+ assert t(23) == b"23"
22
+ assert t("123456789abcdef") == b"123456789a"
23
+ elif tname in ["t5", "s5"]:
24
+ assert t(23) == b"23"
25
+ assert t("ab") == b"ab"
26
+ assert t("123456789abcdef") == b"12345"
27
+ else:
28
+ raise NotImplementedError
29
+
30
+
31
+ class TestFReturnCharacter(TestReturnCharacter):
32
+ sources = [
33
+ util.getpath("tests", "src", "return_character", "foo77.f"),
34
+ util.getpath("tests", "src", "return_character", "foo90.f90"),
35
+ ]
36
+
37
+ @pytest.mark.xfail(IS_S390X, reason="callback returns ' '")
38
+ @pytest.mark.parametrize("name", "t0,t1,t5,s0,s1,s5,ss".split(","))
39
+ def test_all_f77(self, name):
40
+ self.check_function(getattr(self.module, name), name)
41
+
42
+ @pytest.mark.xfail(IS_S390X, reason="callback returns ' '")
43
+ @pytest.mark.parametrize("name", "t0,t1,t5,ts,s0,s1,s5,ss".split(","))
44
+ def test_all_f90(self, name):
45
+ self.check_function(getattr(self.module.f90_return_char, name), name)
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_return_complex.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from numpy import array
4
+ from . import util
5
+
6
+
7
+ class TestReturnComplex(util.F2PyTest):
8
+ def check_function(self, t, tname):
9
+ if tname in ["t0", "t8", "s0", "s8"]:
10
+ err = 1e-5
11
+ else:
12
+ err = 0.0
13
+ assert abs(t(234j) - 234.0j) <= err
14
+ assert abs(t(234.6) - 234.6) <= err
15
+ assert abs(t(234) - 234.0) <= err
16
+ assert abs(t(234.6 + 3j) - (234.6 + 3j)) <= err
17
+ # assert abs(t('234')-234.)<=err
18
+ # assert abs(t('234.6')-234.6)<=err
19
+ assert abs(t(-234) + 234.0) <= err
20
+ assert abs(t([234]) - 234.0) <= err
21
+ assert abs(t((234, )) - 234.0) <= err
22
+ assert abs(t(array(234)) - 234.0) <= err
23
+ assert abs(t(array(23 + 4j, "F")) - (23 + 4j)) <= err
24
+ assert abs(t(array([234])) - 234.0) <= err
25
+ assert abs(t(array([[234]])) - 234.0) <= err
26
+ assert abs(t(array([234]).astype("b")) + 22.0) <= err
27
+ assert abs(t(array([234], "h")) - 234.0) <= err
28
+ assert abs(t(array([234], "i")) - 234.0) <= err
29
+ assert abs(t(array([234], "l")) - 234.0) <= err
30
+ assert abs(t(array([234], "q")) - 234.0) <= err
31
+ assert abs(t(array([234], "f")) - 234.0) <= err
32
+ assert abs(t(array([234], "d")) - 234.0) <= err
33
+ assert abs(t(array([234 + 3j], "F")) - (234 + 3j)) <= err
34
+ assert abs(t(array([234], "D")) - 234.0) <= err
35
+
36
+ # pytest.raises(TypeError, t, array([234], 'a1'))
37
+ pytest.raises(TypeError, t, "abc")
38
+
39
+ pytest.raises(IndexError, t, [])
40
+ pytest.raises(IndexError, t, ())
41
+
42
+ pytest.raises(TypeError, t, t)
43
+ pytest.raises(TypeError, t, {})
44
+
45
+ try:
46
+ r = t(10**400)
47
+ assert repr(r) in ["(inf+0j)", "(Infinity+0j)"]
48
+ except OverflowError:
49
+ pass
50
+
51
+
52
+ class TestFReturnComplex(TestReturnComplex):
53
+ sources = [
54
+ util.getpath("tests", "src", "return_complex", "foo77.f"),
55
+ util.getpath("tests", "src", "return_complex", "foo90.f90"),
56
+ ]
57
+
58
+ @pytest.mark.parametrize("name", "t0,t8,t16,td,s0,s8,s16,sd".split(","))
59
+ def test_all_f77(self, name):
60
+ self.check_function(getattr(self.module, name), name)
61
+
62
+ @pytest.mark.parametrize("name", "t0,t8,t16,td,s0,s8,s16,sd".split(","))
63
+ def test_all_f90(self, name):
64
+ self.check_function(getattr(self.module.f90_return_complex, name),
65
+ name)
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_return_integer.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from numpy import array
4
+ from . import util
5
+
6
+
7
+ class TestReturnInteger(util.F2PyTest):
8
+ def check_function(self, t, tname):
9
+ assert t(123) == 123
10
+ assert t(123.6) == 123
11
+ assert t("123") == 123
12
+ assert t(-123) == -123
13
+ assert t([123]) == 123
14
+ assert t((123, )) == 123
15
+ assert t(array(123)) == 123
16
+ assert t(array(123, "b")) == 123
17
+ assert t(array(123, "h")) == 123
18
+ assert t(array(123, "i")) == 123
19
+ assert t(array(123, "l")) == 123
20
+ assert t(array(123, "B")) == 123
21
+ assert t(array(123, "f")) == 123
22
+ assert t(array(123, "d")) == 123
23
+
24
+ # pytest.raises(ValueError, t, array([123],'S3'))
25
+ pytest.raises(ValueError, t, "abc")
26
+
27
+ pytest.raises(IndexError, t, [])
28
+ pytest.raises(IndexError, t, ())
29
+
30
+ pytest.raises(Exception, t, t)
31
+ pytest.raises(Exception, t, {})
32
+
33
+ if tname in ["t8", "s8"]:
34
+ pytest.raises(OverflowError, t, 100000000000000000000000)
35
+ pytest.raises(OverflowError, t, 10000000011111111111111.23)
36
+
37
+
38
+ class TestFReturnInteger(TestReturnInteger):
39
+ sources = [
40
+ util.getpath("tests", "src", "return_integer", "foo77.f"),
41
+ util.getpath("tests", "src", "return_integer", "foo90.f90"),
42
+ ]
43
+
44
+ @pytest.mark.parametrize("name",
45
+ "t0,t1,t2,t4,t8,s0,s1,s2,s4,s8".split(","))
46
+ def test_all_f77(self, name):
47
+ self.check_function(getattr(self.module, name), name)
48
+
49
+ @pytest.mark.parametrize("name",
50
+ "t0,t1,t2,t4,t8,s0,s1,s2,s4,s8".split(","))
51
+ def test_all_f90(self, name):
52
+ self.check_function(getattr(self.module.f90_return_integer, name),
53
+ name)
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_return_real.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform
2
+ import pytest
3
+ import numpy as np
4
+
5
+ from numpy import array
6
+ from . import util
7
+
8
+
9
+ class TestReturnReal(util.F2PyTest):
10
+ def check_function(self, t, tname):
11
+ if tname in ["t0", "t4", "s0", "s4"]:
12
+ err = 1e-5
13
+ else:
14
+ err = 0.0
15
+ assert abs(t(234) - 234.0) <= err
16
+ assert abs(t(234.6) - 234.6) <= err
17
+ assert abs(t("234") - 234) <= err
18
+ assert abs(t("234.6") - 234.6) <= err
19
+ assert abs(t(-234) + 234) <= err
20
+ assert abs(t([234]) - 234) <= err
21
+ assert abs(t((234, )) - 234.0) <= err
22
+ assert abs(t(array(234)) - 234.0) <= err
23
+ assert abs(t(array(234).astype("b")) + 22) <= err
24
+ assert abs(t(array(234, "h")) - 234.0) <= err
25
+ assert abs(t(array(234, "i")) - 234.0) <= err
26
+ assert abs(t(array(234, "l")) - 234.0) <= err
27
+ assert abs(t(array(234, "B")) - 234.0) <= err
28
+ assert abs(t(array(234, "f")) - 234.0) <= err
29
+ assert abs(t(array(234, "d")) - 234.0) <= err
30
+ if tname in ["t0", "t4", "s0", "s4"]:
31
+ assert t(1e200) == t(1e300) # inf
32
+
33
+ # pytest.raises(ValueError, t, array([234], 'S1'))
34
+ pytest.raises(ValueError, t, "abc")
35
+
36
+ pytest.raises(IndexError, t, [])
37
+ pytest.raises(IndexError, t, ())
38
+
39
+ pytest.raises(Exception, t, t)
40
+ pytest.raises(Exception, t, {})
41
+
42
+ try:
43
+ r = t(10**400)
44
+ assert repr(r) in ["inf", "Infinity"]
45
+ except OverflowError:
46
+ pass
47
+
48
+
49
+ @pytest.mark.skipif(
50
+ platform.system() == "Darwin",
51
+ reason="Prone to error when run with numpy/f2py/tests on mac os, "
52
+ "but not when run in isolation",
53
+ )
54
+ @pytest.mark.skipif(
55
+ np.dtype(np.intp).itemsize < 8,
56
+ reason="32-bit builds are buggy"
57
+ )
58
+ class TestCReturnReal(TestReturnReal):
59
+ suffix = ".pyf"
60
+ module_name = "c_ext_return_real"
61
+ code = """
62
+ python module c_ext_return_real
63
+ usercode \'\'\'
64
+ float t4(float value) { return value; }
65
+ void s4(float *t4, float value) { *t4 = value; }
66
+ double t8(double value) { return value; }
67
+ void s8(double *t8, double value) { *t8 = value; }
68
+ \'\'\'
69
+ interface
70
+ function t4(value)
71
+ real*4 intent(c) :: t4,value
72
+ end
73
+ function t8(value)
74
+ real*8 intent(c) :: t8,value
75
+ end
76
+ subroutine s4(t4,value)
77
+ intent(c) s4
78
+ real*4 intent(out) :: t4
79
+ real*4 intent(c) :: value
80
+ end
81
+ subroutine s8(t8,value)
82
+ intent(c) s8
83
+ real*8 intent(out) :: t8
84
+ real*8 intent(c) :: value
85
+ end
86
+ end interface
87
+ end python module c_ext_return_real
88
+ """
89
+
90
+ @pytest.mark.parametrize("name", "t4,t8,s4,s8".split(","))
91
+ def test_all(self, name):
92
+ self.check_function(getattr(self.module, name), name)
93
+
94
+
95
+ class TestFReturnReal(TestReturnReal):
96
+ sources = [
97
+ util.getpath("tests", "src", "return_real", "foo77.f"),
98
+ util.getpath("tests", "src", "return_real", "foo90.f90"),
99
+ ]
100
+
101
+ @pytest.mark.parametrize("name", "t0,t4,t8,td,s0,s4,s8,sd".split(","))
102
+ def test_all_f77(self, name):
103
+ self.check_function(getattr(self.module, name), name)
104
+
105
+ @pytest.mark.parametrize("name", "t0,t4,t8,td,s0,s4,s8,sd".split(","))
106
+ def test_all_f90(self, name):
107
+ self.check_function(getattr(self.module.f90_return_real, name), name)
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_semicolon_split.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform
2
+ import pytest
3
+ import numpy as np
4
+
5
+ from . import util
6
+
7
+
8
+ @pytest.mark.skipif(
9
+ platform.system() == "Darwin",
10
+ reason="Prone to error when run with numpy/f2py/tests on mac os, "
11
+ "but not when run in isolation",
12
+ )
13
+ @pytest.mark.skipif(
14
+ np.dtype(np.intp).itemsize < 8,
15
+ reason="32-bit builds are buggy"
16
+ )
17
+ class TestMultiline(util.F2PyTest):
18
+ suffix = ".pyf"
19
+ module_name = "multiline"
20
+ code = f"""
21
+ python module {module_name}
22
+ usercode '''
23
+ void foo(int* x) {{
24
+ char dummy = ';';
25
+ *x = 42;
26
+ }}
27
+ '''
28
+ interface
29
+ subroutine foo(x)
30
+ intent(c) foo
31
+ integer intent(out) :: x
32
+ end subroutine foo
33
+ end interface
34
+ end python module {module_name}
35
+ """
36
+
37
+ def test_multiline(self):
38
+ assert self.module.foo() == 42
39
+
40
+
41
+ @pytest.mark.skipif(
42
+ platform.system() == "Darwin",
43
+ reason="Prone to error when run with numpy/f2py/tests on mac os, "
44
+ "but not when run in isolation",
45
+ )
46
+ @pytest.mark.skipif(
47
+ np.dtype(np.intp).itemsize < 8,
48
+ reason="32-bit builds are buggy"
49
+ )
50
+ class TestCallstatement(util.F2PyTest):
51
+ suffix = ".pyf"
52
+ module_name = "callstatement"
53
+ code = f"""
54
+ python module {module_name}
55
+ usercode '''
56
+ void foo(int* x) {{
57
+ }}
58
+ '''
59
+ interface
60
+ subroutine foo(x)
61
+ intent(c) foo
62
+ integer intent(out) :: x
63
+ callprotoargument int*
64
+ callstatement {{ &
65
+ ; &
66
+ x = 42; &
67
+ }}
68
+ end subroutine foo
69
+ end interface
70
+ end python module {module_name}
71
+ """
72
+
73
+ def test_callstatement(self):
74
+ assert self.module.foo() == 42
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_size.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pytest
3
+ import numpy as np
4
+
5
+ from . import util
6
+
7
+
8
+ class TestSizeSumExample(util.F2PyTest):
9
+ sources = [util.getpath("tests", "src", "size", "foo.f90")]
10
+
11
+ @pytest.mark.slow
12
+ def test_all(self):
13
+ r = self.module.foo([[]])
14
+ assert r == [0]
15
+
16
+ r = self.module.foo([[1, 2]])
17
+ assert r == [3]
18
+
19
+ r = self.module.foo([[1, 2], [3, 4]])
20
+ assert np.allclose(r, [3, 7])
21
+
22
+ r = self.module.foo([[1, 2], [3, 4], [5, 6]])
23
+ assert np.allclose(r, [3, 7, 11])
24
+
25
+ @pytest.mark.slow
26
+ def test_transpose(self):
27
+ r = self.module.trans([[]])
28
+ assert np.allclose(r.T, np.array([[]]))
29
+
30
+ r = self.module.trans([[1, 2]])
31
+ assert np.allclose(r, [[1.], [2.]])
32
+
33
+ r = self.module.trans([[1, 2, 3], [4, 5, 6]])
34
+ assert np.allclose(r, [[1, 4], [2, 5], [3, 6]])
35
+
36
+ @pytest.mark.slow
37
+ def test_flatten(self):
38
+ r = self.module.flatten([[]])
39
+ assert np.allclose(r, [])
40
+
41
+ r = self.module.flatten([[1, 2]])
42
+ assert np.allclose(r, [1, 2])
43
+
44
+ r = self.module.flatten([[1, 2, 3], [4, 5, 6]])
45
+ assert np.allclose(r, [1, 2, 3, 4, 5, 6])
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_string.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pytest
3
+ import textwrap
4
+ import numpy as np
5
+ from . import util
6
+
7
+
8
+ class TestString(util.F2PyTest):
9
+ sources = [util.getpath("tests", "src", "string", "char.f90")]
10
+
11
+ @pytest.mark.slow
12
+ def test_char(self):
13
+ strings = np.array(["ab", "cd", "ef"], dtype="c").T
14
+ inp, out = self.module.char_test.change_strings(
15
+ strings, strings.shape[1])
16
+ assert inp == pytest.approx(strings)
17
+ expected = strings.copy()
18
+ expected[1, :] = "AAA"
19
+ assert out == pytest.approx(expected)
20
+
21
+
22
+ class TestDocStringArguments(util.F2PyTest):
23
+ sources = [util.getpath("tests", "src", "string", "string.f")]
24
+
25
+ def test_example(self):
26
+ a = np.array(b"123\0\0")
27
+ b = np.array(b"123\0\0")
28
+ c = np.array(b"123")
29
+ d = np.array(b"123")
30
+
31
+ self.module.foo(a, b, c, d)
32
+
33
+ assert a.tobytes() == b"123\0\0"
34
+ assert b.tobytes() == b"B23\0\0"
35
+ assert c.tobytes() == b"123"
36
+ assert d.tobytes() == b"D23"
37
+
38
+
39
+ class TestFixedString(util.F2PyTest):
40
+ sources = [util.getpath("tests", "src", "string", "fixed_string.f90")]
41
+
42
+ @staticmethod
43
+ def _sint(s, start=0, end=None):
44
+ """Return the content of a string buffer as integer value.
45
+
46
+ For example:
47
+ _sint('1234') -> 4321
48
+ _sint('123A') -> 17321
49
+ """
50
+ if isinstance(s, np.ndarray):
51
+ s = s.tobytes()
52
+ elif isinstance(s, str):
53
+ s = s.encode()
54
+ assert isinstance(s, bytes)
55
+ if end is None:
56
+ end = len(s)
57
+ i = 0
58
+ for j in range(start, min(end, len(s))):
59
+ i += s[j] * 10**j
60
+ return i
61
+
62
+ def _get_input(self, intent="in"):
63
+ if intent in ["in"]:
64
+ yield ""
65
+ yield "1"
66
+ yield "1234"
67
+ yield "12345"
68
+ yield b""
69
+ yield b"\0"
70
+ yield b"1"
71
+ yield b"\01"
72
+ yield b"1\0"
73
+ yield b"1234"
74
+ yield b"12345"
75
+ yield np.ndarray((), np.bytes_, buffer=b"") # array(b'', dtype='|S0')
76
+ yield np.array(b"") # array(b'', dtype='|S1')
77
+ yield np.array(b"\0")
78
+ yield np.array(b"1")
79
+ yield np.array(b"1\0")
80
+ yield np.array(b"\01")
81
+ yield np.array(b"1234")
82
+ yield np.array(b"123\0")
83
+ yield np.array(b"12345")
84
+
85
+ def test_intent_in(self):
86
+ for s in self._get_input():
87
+ r = self.module.test_in_bytes4(s)
88
+ # also checks that s is not changed inplace
89
+ expected = self._sint(s, end=4)
90
+ assert r == expected, s
91
+
92
+ def test_intent_inout(self):
93
+ for s in self._get_input(intent="inout"):
94
+ rest = self._sint(s, start=4)
95
+ r = self.module.test_inout_bytes4(s)
96
+ expected = self._sint(s, end=4)
97
+ assert r == expected
98
+
99
+ # check that the rest of input string is preserved
100
+ assert rest == self._sint(s, start=4)
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_symbolic.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from numpy.f2py.symbolic import (
4
+ Expr,
5
+ Op,
6
+ ArithOp,
7
+ Language,
8
+ as_symbol,
9
+ as_number,
10
+ as_string,
11
+ as_array,
12
+ as_complex,
13
+ as_terms,
14
+ as_factors,
15
+ eliminate_quotes,
16
+ insert_quotes,
17
+ fromstring,
18
+ as_expr,
19
+ as_apply,
20
+ as_numer_denom,
21
+ as_ternary,
22
+ as_ref,
23
+ as_deref,
24
+ normalize,
25
+ as_eq,
26
+ as_ne,
27
+ as_lt,
28
+ as_gt,
29
+ as_le,
30
+ as_ge,
31
+ )
32
+ from . import util
33
+
34
+
35
+ class TestSymbolic(util.F2PyTest):
36
+ def test_eliminate_quotes(self):
37
+ def worker(s):
38
+ r, d = eliminate_quotes(s)
39
+ s1 = insert_quotes(r, d)
40
+ assert s1 == s
41
+
42
+ for kind in ["", "mykind_"]:
43
+ worker(kind + '"1234" // "ABCD"')
44
+ worker(kind + '"1234" // ' + kind + '"ABCD"')
45
+ worker(kind + "\"1234\" // 'ABCD'")
46
+ worker(kind + '"1234" // ' + kind + "'ABCD'")
47
+ worker(kind + '"1\\"2\'AB\'34"')
48
+ worker("a = " + kind + "'1\\'2\"AB\"34'")
49
+
50
+ def test_sanity(self):
51
+ x = as_symbol("x")
52
+ y = as_symbol("y")
53
+ z = as_symbol("z")
54
+
55
+ assert x.op == Op.SYMBOL
56
+ assert repr(x) == "Expr(Op.SYMBOL, 'x')"
57
+ assert x == x
58
+ assert x != y
59
+ assert hash(x) is not None
60
+
61
+ n = as_number(123)
62
+ m = as_number(456)
63
+ assert n.op == Op.INTEGER
64
+ assert repr(n) == "Expr(Op.INTEGER, (123, 4))"
65
+ assert n == n
66
+ assert n != m
67
+ assert hash(n) is not None
68
+
69
+ fn = as_number(12.3)
70
+ fm = as_number(45.6)
71
+ assert fn.op == Op.REAL
72
+ assert repr(fn) == "Expr(Op.REAL, (12.3, 4))"
73
+ assert fn == fn
74
+ assert fn != fm
75
+ assert hash(fn) is not None
76
+
77
+ c = as_complex(1, 2)
78
+ c2 = as_complex(3, 4)
79
+ assert c.op == Op.COMPLEX
80
+ assert repr(c) == ("Expr(Op.COMPLEX, (Expr(Op.INTEGER, (1, 4)),"
81
+ " Expr(Op.INTEGER, (2, 4))))")
82
+ assert c == c
83
+ assert c != c2
84
+ assert hash(c) is not None
85
+
86
+ s = as_string("'123'")
87
+ s2 = as_string('"ABC"')
88
+ assert s.op == Op.STRING
89
+ assert repr(s) == "Expr(Op.STRING, (\"'123'\", 1))", repr(s)
90
+ assert s == s
91
+ assert s != s2
92
+
93
+ a = as_array((n, m))
94
+ b = as_array((n, ))
95
+ assert a.op == Op.ARRAY
96
+ assert repr(a) == ("Expr(Op.ARRAY, (Expr(Op.INTEGER, (123, 4)),"
97
+ " Expr(Op.INTEGER, (456, 4))))")
98
+ assert a == a
99
+ assert a != b
100
+
101
+ t = as_terms(x)
102
+ u = as_terms(y)
103
+ assert t.op == Op.TERMS
104
+ assert repr(t) == "Expr(Op.TERMS, {Expr(Op.SYMBOL, 'x'): 1})"
105
+ assert t == t
106
+ assert t != u
107
+ assert hash(t) is not None
108
+
109
+ v = as_factors(x)
110
+ w = as_factors(y)
111
+ assert v.op == Op.FACTORS
112
+ assert repr(v) == "Expr(Op.FACTORS, {Expr(Op.SYMBOL, 'x'): 1})"
113
+ assert v == v
114
+ assert w != v
115
+ assert hash(v) is not None
116
+
117
+ t = as_ternary(x, y, z)
118
+ u = as_ternary(x, z, y)
119
+ assert t.op == Op.TERNARY
120
+ assert t == t
121
+ assert t != u
122
+ assert hash(t) is not None
123
+
124
+ e = as_eq(x, y)
125
+ f = as_lt(x, y)
126
+ assert e.op == Op.RELATIONAL
127
+ assert e == e
128
+ assert e != f
129
+ assert hash(e) is not None
130
+
131
+ def test_tostring_fortran(self):
132
+ x = as_symbol("x")
133
+ y = as_symbol("y")
134
+ z = as_symbol("z")
135
+ n = as_number(123)
136
+ m = as_number(456)
137
+ a = as_array((n, m))
138
+ c = as_complex(n, m)
139
+
140
+ assert str(x) == "x"
141
+ assert str(n) == "123"
142
+ assert str(a) == "[123, 456]"
143
+ assert str(c) == "(123, 456)"
144
+
145
+ assert str(Expr(Op.TERMS, {x: 1})) == "x"
146
+ assert str(Expr(Op.TERMS, {x: 2})) == "2 * x"
147
+ assert str(Expr(Op.TERMS, {x: -1})) == "-x"
148
+ assert str(Expr(Op.TERMS, {x: -2})) == "-2 * x"
149
+ assert str(Expr(Op.TERMS, {x: 1, y: 1})) == "x + y"
150
+ assert str(Expr(Op.TERMS, {x: -1, y: -1})) == "-x - y"
151
+ assert str(Expr(Op.TERMS, {x: 2, y: 3})) == "2 * x + 3 * y"
152
+ assert str(Expr(Op.TERMS, {x: -2, y: 3})) == "-2 * x + 3 * y"
153
+ assert str(Expr(Op.TERMS, {x: 2, y: -3})) == "2 * x - 3 * y"
154
+
155
+ assert str(Expr(Op.FACTORS, {x: 1})) == "x"
156
+ assert str(Expr(Op.FACTORS, {x: 2})) == "x ** 2"
157
+ assert str(Expr(Op.FACTORS, {x: -1})) == "x ** -1"
158
+ assert str(Expr(Op.FACTORS, {x: -2})) == "x ** -2"
159
+ assert str(Expr(Op.FACTORS, {x: 1, y: 1})) == "x * y"
160
+ assert str(Expr(Op.FACTORS, {x: 2, y: 3})) == "x ** 2 * y ** 3"
161
+
162
+ v = Expr(Op.FACTORS, {x: 2, Expr(Op.TERMS, {x: 1, y: 1}): 3})
163
+ assert str(v) == "x ** 2 * (x + y) ** 3", str(v)
164
+ v = Expr(Op.FACTORS, {x: 2, Expr(Op.FACTORS, {x: 1, y: 1}): 3})
165
+ assert str(v) == "x ** 2 * (x * y) ** 3", str(v)
166
+
167
+ assert str(Expr(Op.APPLY, ("f", (), {}))) == "f()"
168
+ assert str(Expr(Op.APPLY, ("f", (x, ), {}))) == "f(x)"
169
+ assert str(Expr(Op.APPLY, ("f", (x, y), {}))) == "f(x, y)"
170
+ assert str(Expr(Op.INDEXING, ("f", x))) == "f[x]"
171
+
172
+ assert str(as_ternary(x, y, z)) == "merge(y, z, x)"
173
+ assert str(as_eq(x, y)) == "x .eq. y"
174
+ assert str(as_ne(x, y)) == "x .ne. y"
175
+ assert str(as_lt(x, y)) == "x .lt. y"
176
+ assert str(as_le(x, y)) == "x .le. y"
177
+ assert str(as_gt(x, y)) == "x .gt. y"
178
+ assert str(as_ge(x, y)) == "x .ge. y"
179
+
180
+ def test_tostring_c(self):
181
+ language = Language.C
182
+ x = as_symbol("x")
183
+ y = as_symbol("y")
184
+ z = as_symbol("z")
185
+ n = as_number(123)
186
+
187
+ assert Expr(Op.FACTORS, {x: 2}).tostring(language=language) == "x * x"
188
+ assert (Expr(Op.FACTORS, {
189
+ x + y: 2
190
+ }).tostring(language=language) == "(x + y) * (x + y)")
191
+ assert Expr(Op.FACTORS, {
192
+ x: 12
193
+ }).tostring(language=language) == "pow(x, 12)"
194
+
195
+ assert as_apply(ArithOp.DIV, x,
196
+ y).tostring(language=language) == "x / y"
197
+ assert (as_apply(ArithOp.DIV, x,
198
+ x + y).tostring(language=language) == "x / (x + y)")
199
+ assert (as_apply(ArithOp.DIV, x - y, x +
200
+ y).tostring(language=language) == "(x - y) / (x + y)")
201
+ assert (x + (x - y) / (x + y) +
202
+ n).tostring(language=language) == "123 + x + (x - y) / (x + y)"
203
+
204
+ assert as_ternary(x, y, z).tostring(language=language) == "(x?y:z)"
205
+ assert as_eq(x, y).tostring(language=language) == "x == y"
206
+ assert as_ne(x, y).tostring(language=language) == "x != y"
207
+ assert as_lt(x, y).tostring(language=language) == "x < y"
208
+ assert as_le(x, y).tostring(language=language) == "x <= y"
209
+ assert as_gt(x, y).tostring(language=language) == "x > y"
210
+ assert as_ge(x, y).tostring(language=language) == "x >= y"
211
+
212
+ def test_operations(self):
213
+ x = as_symbol("x")
214
+ y = as_symbol("y")
215
+ z = as_symbol("z")
216
+
217
+ assert x + x == Expr(Op.TERMS, {x: 2})
218
+ assert x - x == Expr(Op.INTEGER, (0, 4))
219
+ assert x + y == Expr(Op.TERMS, {x: 1, y: 1})
220
+ assert x - y == Expr(Op.TERMS, {x: 1, y: -1})
221
+ assert x * x == Expr(Op.FACTORS, {x: 2})
222
+ assert x * y == Expr(Op.FACTORS, {x: 1, y: 1})
223
+
224
+ assert +x == x
225
+ assert -x == Expr(Op.TERMS, {x: -1}), repr(-x)
226
+ assert 2 * x == Expr(Op.TERMS, {x: 2})
227
+ assert 2 + x == Expr(Op.TERMS, {x: 1, as_number(1): 2})
228
+ assert 2 * x + 3 * y == Expr(Op.TERMS, {x: 2, y: 3})
229
+ assert (x + y) * 2 == Expr(Op.TERMS, {x: 2, y: 2})
230
+
231
+ assert x**2 == Expr(Op.FACTORS, {x: 2})
232
+ assert (x + y)**2 == Expr(
233
+ Op.TERMS,
234
+ {
235
+ Expr(Op.FACTORS, {x: 2}): 1,
236
+ Expr(Op.FACTORS, {y: 2}): 1,
237
+ Expr(Op.FACTORS, {
238
+ x: 1,
239
+ y: 1
240
+ }): 2,
241
+ },
242
+ )
243
+ assert (x + y) * x == x**2 + x * y
244
+ assert (x + y)**2 == x**2 + 2 * x * y + y**2
245
+ assert (x + y)**2 + (x - y)**2 == 2 * x**2 + 2 * y**2
246
+ assert (x + y) * z == x * z + y * z
247
+ assert z * (x + y) == x * z + y * z
248
+
249
+ assert (x / 2) == as_apply(ArithOp.DIV, x, as_number(2))
250
+ assert (2 * x / 2) == x
251
+ assert (3 * x / 2) == as_apply(ArithOp.DIV, 3 * x, as_number(2))
252
+ assert (4 * x / 2) == 2 * x
253
+ assert (5 * x / 2) == as_apply(ArithOp.DIV, 5 * x, as_number(2))
254
+ assert (6 * x / 2) == 3 * x
255
+ assert ((3 * 5) * x / 6) == as_apply(ArithOp.DIV, 5 * x, as_number(2))
256
+ assert (30 * x**2 * y**4 / (24 * x**3 * y**3)) == as_apply(
257
+ ArithOp.DIV, 5 * y, 4 * x)
258
+ assert ((15 * x / 6) / 5) == as_apply(ArithOp.DIV, x,
259
+ as_number(2)), (15 * x / 6) / 5
260
+ assert (x / (5 / x)) == as_apply(ArithOp.DIV, x**2, as_number(5))
261
+
262
+ assert (x / 2.0) == Expr(Op.TERMS, {x: 0.5})
263
+
264
+ s = as_string('"ABC"')
265
+ t = as_string('"123"')
266
+
267
+ assert s // t == Expr(Op.STRING, ('"ABC123"', 1))
268
+ assert s // x == Expr(Op.CONCAT, (s, x))
269
+ assert x // s == Expr(Op.CONCAT, (x, s))
270
+
271
+ c = as_complex(1.0, 2.0)
272
+ assert -c == as_complex(-1.0, -2.0)
273
+ assert c + c == as_expr((1 + 2j) * 2)
274
+ assert c * c == as_expr((1 + 2j)**2)
275
+
276
+ def test_substitute(self):
277
+ x = as_symbol("x")
278
+ y = as_symbol("y")
279
+ z = as_symbol("z")
280
+ a = as_array((x, y))
281
+
282
+ assert x.substitute({x: y}) == y
283
+ assert (x + y).substitute({x: z}) == y + z
284
+ assert (x * y).substitute({x: z}) == y * z
285
+ assert (x**4).substitute({x: z}) == z**4
286
+ assert (x / y).substitute({x: z}) == z / y
287
+ assert x.substitute({x: y + z}) == y + z
288
+ assert a.substitute({x: y + z}) == as_array((y + z, y))
289
+
290
+ assert as_ternary(x, y,
291
+ z).substitute({x: y + z}) == as_ternary(y + z, y, z)
292
+ assert as_eq(x, y).substitute({x: y + z}) == as_eq(y + z, y)
293
+
294
+ def test_fromstring(self):
295
+
296
+ x = as_symbol("x")
297
+ y = as_symbol("y")
298
+ z = as_symbol("z")
299
+ f = as_symbol("f")
300
+ s = as_string('"ABC"')
301
+ t = as_string('"123"')
302
+ a = as_array((x, y))
303
+
304
+ assert fromstring("x") == x
305
+ assert fromstring("+ x") == x
306
+ assert fromstring("- x") == -x
307
+ assert fromstring("x + y") == x + y
308
+ assert fromstring("x + 1") == x + 1
309
+ assert fromstring("x * y") == x * y
310
+ assert fromstring("x * 2") == x * 2
311
+ assert fromstring("x / y") == x / y
312
+ assert fromstring("x ** 2", language=Language.Python) == x**2
313
+ assert fromstring("x ** 2 ** 3", language=Language.Python) == x**2**3
314
+ assert fromstring("(x + y) * z") == (x + y) * z
315
+
316
+ assert fromstring("f(x)") == f(x)
317
+ assert fromstring("f(x,y)") == f(x, y)
318
+ assert fromstring("f[x]") == f[x]
319
+ assert fromstring("f[x][y]") == f[x][y]
320
+
321
+ assert fromstring('"ABC"') == s
322
+ assert (normalize(
323
+ fromstring('"ABC" // "123" ',
324
+ language=Language.Fortran)) == s // t)
325
+ assert fromstring('f("ABC")') == f(s)
326
+ assert fromstring('MYSTRKIND_"ABC"') == as_string('"ABC"', "MYSTRKIND")
327
+
328
+ assert fromstring("(/x, y/)") == a, fromstring("(/x, y/)")
329
+ assert fromstring("f((/x, y/))") == f(a)
330
+ assert fromstring("(/(x+y)*z/)") == as_array(((x + y) * z, ))
331
+
332
+ assert fromstring("123") == as_number(123)
333
+ assert fromstring("123_2") == as_number(123, 2)
334
+ assert fromstring("123_myintkind") == as_number(123, "myintkind")
335
+
336
+ assert fromstring("123.0") == as_number(123.0, 4)
337
+ assert fromstring("123.0_4") == as_number(123.0, 4)
338
+ assert fromstring("123.0_8") == as_number(123.0, 8)
339
+ assert fromstring("123.0e0") == as_number(123.0, 4)
340
+ assert fromstring("123.0d0") == as_number(123.0, 8)
341
+ assert fromstring("123d0") == as_number(123.0, 8)
342
+ assert fromstring("123e-0") == as_number(123.0, 4)
343
+ assert fromstring("123d+0") == as_number(123.0, 8)
344
+ assert fromstring("123.0_myrealkind") == as_number(123.0, "myrealkind")
345
+ assert fromstring("3E4") == as_number(30000.0, 4)
346
+
347
+ assert fromstring("(1, 2)") == as_complex(1, 2)
348
+ assert fromstring("(1e2, PI)") == as_complex(as_number(100.0),
349
+ as_symbol("PI"))
350
+
351
+ assert fromstring("[1, 2]") == as_array((as_number(1), as_number(2)))
352
+
353
+ assert fromstring("POINT(x, y=1)") == as_apply(as_symbol("POINT"),
354
+ x,
355
+ y=as_number(1))
356
+ assert fromstring(
357
+ 'PERSON(name="John", age=50, shape=(/34, 23/))') == as_apply(
358
+ as_symbol("PERSON"),
359
+ name=as_string('"John"'),
360
+ age=as_number(50),
361
+ shape=as_array((as_number(34), as_number(23))),
362
+ )
363
+
364
+ assert fromstring("x?y:z") == as_ternary(x, y, z)
365
+
366
+ assert fromstring("*x") == as_deref(x)
367
+ assert fromstring("**x") == as_deref(as_deref(x))
368
+ assert fromstring("&x") == as_ref(x)
369
+ assert fromstring("(*x) * (*y)") == as_deref(x) * as_deref(y)
370
+ assert fromstring("(*x) * *y") == as_deref(x) * as_deref(y)
371
+ assert fromstring("*x * *y") == as_deref(x) * as_deref(y)
372
+ assert fromstring("*x**y") == as_deref(x) * as_deref(y)
373
+
374
+ assert fromstring("x == y") == as_eq(x, y)
375
+ assert fromstring("x != y") == as_ne(x, y)
376
+ assert fromstring("x < y") == as_lt(x, y)
377
+ assert fromstring("x > y") == as_gt(x, y)
378
+ assert fromstring("x <= y") == as_le(x, y)
379
+ assert fromstring("x >= y") == as_ge(x, y)
380
+
381
+ assert fromstring("x .eq. y", language=Language.Fortran) == as_eq(x, y)
382
+ assert fromstring("x .ne. y", language=Language.Fortran) == as_ne(x, y)
383
+ assert fromstring("x .lt. y", language=Language.Fortran) == as_lt(x, y)
384
+ assert fromstring("x .gt. y", language=Language.Fortran) == as_gt(x, y)
385
+ assert fromstring("x .le. y", language=Language.Fortran) == as_le(x, y)
386
+ assert fromstring("x .ge. y", language=Language.Fortran) == as_ge(x, y)
387
+
388
+ def test_traverse(self):
389
+ x = as_symbol("x")
390
+ y = as_symbol("y")
391
+ z = as_symbol("z")
392
+ f = as_symbol("f")
393
+
394
+ # Use traverse to substitute a symbol
395
+ def replace_visit(s, r=z):
396
+ if s == x:
397
+ return r
398
+
399
+ assert x.traverse(replace_visit) == z
400
+ assert y.traverse(replace_visit) == y
401
+ assert z.traverse(replace_visit) == z
402
+ assert (f(y)).traverse(replace_visit) == f(y)
403
+ assert (f(x)).traverse(replace_visit) == f(z)
404
+ assert (f[y]).traverse(replace_visit) == f[y]
405
+ assert (f[z]).traverse(replace_visit) == f[z]
406
+ assert (x + y + z).traverse(replace_visit) == (2 * z + y)
407
+ assert (x +
408
+ f(y, x - z)).traverse(replace_visit) == (z +
409
+ f(y, as_number(0)))
410
+ assert as_eq(x, y).traverse(replace_visit) == as_eq(z, y)
411
+
412
+ # Use traverse to collect symbols, method 1
413
+ function_symbols = set()
414
+ symbols = set()
415
+
416
+ def collect_symbols(s):
417
+ if s.op is Op.APPLY:
418
+ oper = s.data[0]
419
+ function_symbols.add(oper)
420
+ if oper in symbols:
421
+ symbols.remove(oper)
422
+ elif s.op is Op.SYMBOL and s not in function_symbols:
423
+ symbols.add(s)
424
+
425
+ (x + f(y, x - z)).traverse(collect_symbols)
426
+ assert function_symbols == {f}
427
+ assert symbols == {x, y, z}
428
+
429
+ # Use traverse to collect symbols, method 2
430
+ def collect_symbols2(expr, symbols):
431
+ if expr.op is Op.SYMBOL:
432
+ symbols.add(expr)
433
+
434
+ symbols = set()
435
+ (x + f(y, x - z)).traverse(collect_symbols2, symbols)
436
+ assert symbols == {x, y, z, f}
437
+
438
+ # Use traverse to partially collect symbols
439
+ def collect_symbols3(expr, symbols):
440
+ if expr.op is Op.APPLY:
441
+ # skip traversing function calls
442
+ return expr
443
+ if expr.op is Op.SYMBOL:
444
+ symbols.add(expr)
445
+
446
+ symbols = set()
447
+ (x + f(y, x - z)).traverse(collect_symbols3, symbols)
448
+ assert symbols == {x}
449
+
450
+ def test_linear_solve(self):
451
+ x = as_symbol("x")
452
+ y = as_symbol("y")
453
+ z = as_symbol("z")
454
+
455
+ assert x.linear_solve(x) == (as_number(1), as_number(0))
456
+ assert (x + 1).linear_solve(x) == (as_number(1), as_number(1))
457
+ assert (2 * x).linear_solve(x) == (as_number(2), as_number(0))
458
+ assert (2 * x + 3).linear_solve(x) == (as_number(2), as_number(3))
459
+ assert as_number(3).linear_solve(x) == (as_number(0), as_number(3))
460
+ assert y.linear_solve(x) == (as_number(0), y)
461
+ assert (y * z).linear_solve(x) == (as_number(0), y * z)
462
+
463
+ assert (x + y).linear_solve(x) == (as_number(1), y)
464
+ assert (z * x + y).linear_solve(x) == (z, y)
465
+ assert ((z + y) * x + y).linear_solve(x) == (z + y, y)
466
+ assert (z * y * x + y).linear_solve(x) == (z * y, y)
467
+
468
+ pytest.raises(RuntimeError, lambda: (x * x).linear_solve(x))
469
+
470
+ def test_as_numer_denom(self):
471
+ x = as_symbol("x")
472
+ y = as_symbol("y")
473
+ n = as_number(123)
474
+
475
+ assert as_numer_denom(x) == (x, as_number(1))
476
+ assert as_numer_denom(x / n) == (x, n)
477
+ assert as_numer_denom(n / x) == (n, x)
478
+ assert as_numer_denom(x / y) == (x, y)
479
+ assert as_numer_denom(x * y) == (x * y, as_number(1))
480
+ assert as_numer_denom(n + x / y) == (x + n * y, y)
481
+ assert as_numer_denom(n + x / (y - x / n)) == (y * n**2, y * n - x)
482
+
483
+ def test_polynomial_atoms(self):
484
+ x = as_symbol("x")
485
+ y = as_symbol("y")
486
+ n = as_number(123)
487
+
488
+ assert x.polynomial_atoms() == {x}
489
+ assert n.polynomial_atoms() == set()
490
+ assert (y[x]).polynomial_atoms() == {y[x]}
491
+ assert (y(x)).polynomial_atoms() == {y(x)}
492
+ assert (y(x) + x).polynomial_atoms() == {y(x), x}
493
+ assert (y(x) * x[y]).polynomial_atoms() == {y(x), x[y]}
494
+ assert (y(x)**x).polynomial_atoms() == {y(x)}
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/test_value_attrspec.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pytest
3
+
4
+ from . import util
5
+
6
+ class TestValueAttr(util.F2PyTest):
7
+ sources = [util.getpath("tests", "src", "value_attrspec", "gh21665.f90")]
8
+
9
+ # gh-21665
10
+ def test_long_long_map(self):
11
+ inp = 2
12
+ out = self.module.fortfuncs.square(inp)
13
+ exp_out = 4
14
+ assert out == exp_out
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/util.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for
3
+
4
+ - building and importing modules on test time, using a temporary location
5
+ - detecting if compilers are present
6
+ - determining paths to tests
7
+
8
+ """
9
+ import glob
10
+ import os
11
+ import sys
12
+ import subprocess
13
+ import tempfile
14
+ import shutil
15
+ import atexit
16
+ import textwrap
17
+ import re
18
+ import pytest
19
+ import contextlib
20
+ import numpy
21
+
22
+ from pathlib import Path
23
+ from numpy.compat import asstr
24
+ from numpy._utils import asunicode
25
+ from numpy.testing import temppath, IS_WASM
26
+ from importlib import import_module
27
+
28
+ #
29
+ # Maintaining a temporary module directory
30
+ #
31
+
32
+ _module_dir = None
33
+ _module_num = 5403
34
+
35
+ if sys.platform == "cygwin":
36
+ NUMPY_INSTALL_ROOT = Path(__file__).parent.parent.parent
37
+ _module_list = list(NUMPY_INSTALL_ROOT.glob("**/*.dll"))
38
+
39
+
40
+ def _cleanup():
41
+ global _module_dir
42
+ if _module_dir is not None:
43
+ try:
44
+ sys.path.remove(_module_dir)
45
+ except ValueError:
46
+ pass
47
+ try:
48
+ shutil.rmtree(_module_dir)
49
+ except OSError:
50
+ pass
51
+ _module_dir = None
52
+
53
+
54
+ def get_module_dir():
55
+ global _module_dir
56
+ if _module_dir is None:
57
+ _module_dir = tempfile.mkdtemp()
58
+ atexit.register(_cleanup)
59
+ if _module_dir not in sys.path:
60
+ sys.path.insert(0, _module_dir)
61
+ return _module_dir
62
+
63
+
64
+ def get_temp_module_name():
65
+ # Assume single-threaded, and the module dir usable only by this thread
66
+ global _module_num
67
+ get_module_dir()
68
+ name = "_test_ext_module_%d" % _module_num
69
+ _module_num += 1
70
+ if name in sys.modules:
71
+ # this should not be possible, but check anyway
72
+ raise RuntimeError("Temporary module name already in use.")
73
+ return name
74
+
75
+
76
+ def _memoize(func):
77
+ memo = {}
78
+
79
+ def wrapper(*a, **kw):
80
+ key = repr((a, kw))
81
+ if key not in memo:
82
+ try:
83
+ memo[key] = func(*a, **kw)
84
+ except Exception as e:
85
+ memo[key] = e
86
+ raise
87
+ ret = memo[key]
88
+ if isinstance(ret, Exception):
89
+ raise ret
90
+ return ret
91
+
92
+ wrapper.__name__ = func.__name__
93
+ return wrapper
94
+
95
+
96
+ #
97
+ # Building modules
98
+ #
99
+
100
+
101
+ @_memoize
102
+ def build_module(source_files, options=[], skip=[], only=[], module_name=None):
103
+ """
104
+ Compile and import a f2py module, built from the given files.
105
+
106
+ """
107
+
108
+ code = f"import sys; sys.path = {sys.path!r}; import numpy.f2py; numpy.f2py.main()"
109
+
110
+ d = get_module_dir()
111
+
112
+ # Copy files
113
+ dst_sources = []
114
+ f2py_sources = []
115
+ for fn in source_files:
116
+ if not os.path.isfile(fn):
117
+ raise RuntimeError("%s is not a file" % fn)
118
+ dst = os.path.join(d, os.path.basename(fn))
119
+ shutil.copyfile(fn, dst)
120
+ dst_sources.append(dst)
121
+
122
+ base, ext = os.path.splitext(dst)
123
+ if ext in (".f90", ".f", ".c", ".pyf"):
124
+ f2py_sources.append(dst)
125
+
126
+ assert f2py_sources
127
+
128
+ # Prepare options
129
+ if module_name is None:
130
+ module_name = get_temp_module_name()
131
+ f2py_opts = ["-c", "-m", module_name] + options + f2py_sources
132
+ if skip:
133
+ f2py_opts += ["skip:"] + skip
134
+ if only:
135
+ f2py_opts += ["only:"] + only
136
+
137
+ # Build
138
+ cwd = os.getcwd()
139
+ try:
140
+ os.chdir(d)
141
+ cmd = [sys.executable, "-c", code] + f2py_opts
142
+ p = subprocess.Popen(cmd,
143
+ stdout=subprocess.PIPE,
144
+ stderr=subprocess.STDOUT)
145
+ out, err = p.communicate()
146
+ if p.returncode != 0:
147
+ raise RuntimeError("Running f2py failed: %s\n%s" %
148
+ (cmd[4:], asunicode(out)))
149
+ finally:
150
+ os.chdir(cwd)
151
+
152
+ # Partial cleanup
153
+ for fn in dst_sources:
154
+ os.unlink(fn)
155
+
156
+ # Rebase (Cygwin-only)
157
+ if sys.platform == "cygwin":
158
+ # If someone starts deleting modules after import, this will
159
+ # need to change to record how big each module is, rather than
160
+ # relying on rebase being able to find that from the files.
161
+ _module_list.extend(
162
+ glob.glob(os.path.join(d, "{:s}*".format(module_name)))
163
+ )
164
+ subprocess.check_call(
165
+ ["/usr/bin/rebase", "--database", "--oblivious", "--verbose"]
166
+ + _module_list
167
+ )
168
+
169
+
170
+
171
+ # Import
172
+ return import_module(module_name)
173
+
174
+
175
+ @_memoize
176
+ def build_code(source_code,
177
+ options=[],
178
+ skip=[],
179
+ only=[],
180
+ suffix=None,
181
+ module_name=None):
182
+ """
183
+ Compile and import Fortran code using f2py.
184
+
185
+ """
186
+ if suffix is None:
187
+ suffix = ".f"
188
+ with temppath(suffix=suffix) as path:
189
+ with open(path, "w") as f:
190
+ f.write(source_code)
191
+ return build_module([path],
192
+ options=options,
193
+ skip=skip,
194
+ only=only,
195
+ module_name=module_name)
196
+
197
+
198
+ #
199
+ # Check if compilers are available at all...
200
+ #
201
+
202
+ _compiler_status = None
203
+
204
+
205
+ def _get_compiler_status():
206
+ global _compiler_status
207
+ if _compiler_status is not None:
208
+ return _compiler_status
209
+
210
+ _compiler_status = (False, False, False)
211
+ if IS_WASM:
212
+ # Can't run compiler from inside WASM.
213
+ return _compiler_status
214
+
215
+ # XXX: this is really ugly. But I don't know how to invoke Distutils
216
+ # in a safer way...
217
+ code = textwrap.dedent(f"""\
218
+ import os
219
+ import sys
220
+ sys.path = {repr(sys.path)}
221
+
222
+ def configuration(parent_name='',top_path=None):
223
+ global config
224
+ from numpy.distutils.misc_util import Configuration
225
+ config = Configuration('', parent_name, top_path)
226
+ return config
227
+
228
+ from numpy.distutils.core import setup
229
+ setup(configuration=configuration)
230
+
231
+ config_cmd = config.get_config_cmd()
232
+ have_c = config_cmd.try_compile('void foo() {{}}')
233
+ print('COMPILERS:%%d,%%d,%%d' %% (have_c,
234
+ config.have_f77c(),
235
+ config.have_f90c()))
236
+ sys.exit(99)
237
+ """)
238
+ code = code % dict(syspath=repr(sys.path))
239
+
240
+ tmpdir = tempfile.mkdtemp()
241
+ try:
242
+ script = os.path.join(tmpdir, "setup.py")
243
+
244
+ with open(script, "w") as f:
245
+ f.write(code)
246
+
247
+ cmd = [sys.executable, "setup.py", "config"]
248
+ p = subprocess.Popen(cmd,
249
+ stdout=subprocess.PIPE,
250
+ stderr=subprocess.STDOUT,
251
+ cwd=tmpdir)
252
+ out, err = p.communicate()
253
+ finally:
254
+ shutil.rmtree(tmpdir)
255
+
256
+ m = re.search(br"COMPILERS:(\d+),(\d+),(\d+)", out)
257
+ if m:
258
+ _compiler_status = (
259
+ bool(int(m.group(1))),
260
+ bool(int(m.group(2))),
261
+ bool(int(m.group(3))),
262
+ )
263
+ # Finished
264
+ return _compiler_status
265
+
266
+
267
+ def has_c_compiler():
268
+ return _get_compiler_status()[0]
269
+
270
+
271
+ def has_f77_compiler():
272
+ return _get_compiler_status()[1]
273
+
274
+
275
+ def has_f90_compiler():
276
+ return _get_compiler_status()[2]
277
+
278
+
279
+ #
280
+ # Building with distutils
281
+ #
282
+
283
+
284
+ @_memoize
285
+ def build_module_distutils(source_files, config_code, module_name, **kw):
286
+ """
287
+ Build a module via distutils and import it.
288
+
289
+ """
290
+ d = get_module_dir()
291
+
292
+ # Copy files
293
+ dst_sources = []
294
+ for fn in source_files:
295
+ if not os.path.isfile(fn):
296
+ raise RuntimeError("%s is not a file" % fn)
297
+ dst = os.path.join(d, os.path.basename(fn))
298
+ shutil.copyfile(fn, dst)
299
+ dst_sources.append(dst)
300
+
301
+ # Build script
302
+ config_code = textwrap.dedent(config_code).replace("\n", "\n ")
303
+
304
+ code = fr"""
305
+ import os
306
+ import sys
307
+ sys.path = {repr(sys.path)}
308
+
309
+ def configuration(parent_name='',top_path=None):
310
+ from numpy.distutils.misc_util import Configuration
311
+ config = Configuration('', parent_name, top_path)
312
+ {config_code}
313
+ return config
314
+
315
+ if __name__ == "__main__":
316
+ from numpy.distutils.core import setup
317
+ setup(configuration=configuration)
318
+ """
319
+ script = os.path.join(d, get_temp_module_name() + ".py")
320
+ dst_sources.append(script)
321
+ with open(script, "wb") as f:
322
+ f.write(code.encode('latin1'))
323
+
324
+ # Build
325
+ cwd = os.getcwd()
326
+ try:
327
+ os.chdir(d)
328
+ cmd = [sys.executable, script, "build_ext", "-i"]
329
+ p = subprocess.Popen(cmd,
330
+ stdout=subprocess.PIPE,
331
+ stderr=subprocess.STDOUT)
332
+ out, err = p.communicate()
333
+ if p.returncode != 0:
334
+ raise RuntimeError("Running distutils build failed: %s\n%s" %
335
+ (cmd[4:], asstr(out)))
336
+ finally:
337
+ os.chdir(cwd)
338
+
339
+ # Partial cleanup
340
+ for fn in dst_sources:
341
+ os.unlink(fn)
342
+
343
+ # Import
344
+ __import__(module_name)
345
+ return sys.modules[module_name]
346
+
347
+
348
+ #
349
+ # Unittest convenience
350
+ #
351
+
352
+
353
+ class F2PyTest:
354
+ code = None
355
+ sources = None
356
+ options = []
357
+ skip = []
358
+ only = []
359
+ suffix = ".f"
360
+ module = None
361
+
362
+ @property
363
+ def module_name(self):
364
+ cls = type(self)
365
+ return f'_{cls.__module__.rsplit(".",1)[-1]}_{cls.__name__}_ext_module'
366
+
367
+ def setup_method(self):
368
+ if sys.platform == "win32":
369
+ pytest.skip("Fails with MinGW64 Gfortran (Issue #9673)")
370
+
371
+ if self.module is not None:
372
+ return
373
+
374
+ # Check compiler availability first
375
+ if not has_c_compiler():
376
+ pytest.skip("No C compiler available")
377
+
378
+ codes = []
379
+ if self.sources:
380
+ codes.extend(self.sources)
381
+ if self.code is not None:
382
+ codes.append(self.suffix)
383
+
384
+ needs_f77 = False
385
+ needs_f90 = False
386
+ needs_pyf = False
387
+ for fn in codes:
388
+ if str(fn).endswith(".f"):
389
+ needs_f77 = True
390
+ elif str(fn).endswith(".f90"):
391
+ needs_f90 = True
392
+ elif str(fn).endswith(".pyf"):
393
+ needs_pyf = True
394
+ if needs_f77 and not has_f77_compiler():
395
+ pytest.skip("No Fortran 77 compiler available")
396
+ if needs_f90 and not has_f90_compiler():
397
+ pytest.skip("No Fortran 90 compiler available")
398
+ if needs_pyf and not (has_f90_compiler() or has_f77_compiler()):
399
+ pytest.skip("No Fortran compiler available")
400
+
401
+ # Build the module
402
+ if self.code is not None:
403
+ self.module = build_code(
404
+ self.code,
405
+ options=self.options,
406
+ skip=self.skip,
407
+ only=self.only,
408
+ suffix=self.suffix,
409
+ module_name=self.module_name,
410
+ )
411
+
412
+ if self.sources is not None:
413
+ self.module = build_module(
414
+ self.sources,
415
+ options=self.options,
416
+ skip=self.skip,
417
+ only=self.only,
418
+ module_name=self.module_name,
419
+ )
420
+
421
+
422
+ #
423
+ # Helper functions
424
+ #
425
+
426
+
427
+ def getpath(*a):
428
+ # Package root
429
+ d = Path(numpy.f2py.__file__).parent.resolve()
430
+ return d.joinpath(*a)
431
+
432
+
433
+ @contextlib.contextmanager
434
+ def switchdir(path):
435
+ curpath = Path.cwd()
436
+ os.chdir(path)
437
+ try:
438
+ yield
439
+ finally:
440
+ os.chdir(curpath)
env-llmeval/lib/python3.10/site-packages/numpy/f2py/use_rules.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Build 'use others module data' 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
+ __version__ = "$Revision: 1.3 $"[10:-1]
12
+
13
+ f2py_version = 'See `f2py -v`'
14
+
15
+
16
+ from .auxfuncs import (
17
+ applyrules, dictappend, gentitle, hasnote, outmess
18
+ )
19
+
20
+
21
+ usemodule_rules = {
22
+ 'body': """
23
+ #begintitle#
24
+ static char doc_#apiname#[] = \"\\\nVariable wrapper signature:\\n\\
25
+ \t #name# = get_#name#()\\n\\
26
+ Arguments:\\n\\
27
+ #docstr#\";
28
+ extern F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#);
29
+ static PyObject *#apiname#(PyObject *capi_self, PyObject *capi_args) {
30
+ /*#decl#*/
31
+ \tif (!PyArg_ParseTuple(capi_args, \"\")) goto capi_fail;
32
+ printf(\"c: %d\\n\",F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#));
33
+ \treturn Py_BuildValue(\"\");
34
+ capi_fail:
35
+ \treturn NULL;
36
+ }
37
+ """,
38
+ 'method': '\t{\"get_#name#\",#apiname#,METH_VARARGS|METH_KEYWORDS,doc_#apiname#},',
39
+ 'need': ['F_MODFUNC']
40
+ }
41
+
42
+ ################
43
+
44
+
45
+ def buildusevars(m, r):
46
+ ret = {}
47
+ outmess(
48
+ '\t\tBuilding use variable hooks for module "%s" (feature only for F90/F95)...\n' % (m['name']))
49
+ varsmap = {}
50
+ revmap = {}
51
+ if 'map' in r:
52
+ for k in r['map'].keys():
53
+ if r['map'][k] in revmap:
54
+ outmess('\t\t\tVariable "%s<=%s" is already mapped by "%s". Skipping.\n' % (
55
+ r['map'][k], k, revmap[r['map'][k]]))
56
+ else:
57
+ revmap[r['map'][k]] = k
58
+ if 'only' in r and r['only']:
59
+ for v in r['map'].keys():
60
+ if r['map'][v] in m['vars']:
61
+
62
+ if revmap[r['map'][v]] == v:
63
+ varsmap[v] = r['map'][v]
64
+ else:
65
+ outmess('\t\t\tIgnoring map "%s=>%s". See above.\n' %
66
+ (v, r['map'][v]))
67
+ else:
68
+ outmess(
69
+ '\t\t\tNo definition for variable "%s=>%s". Skipping.\n' % (v, r['map'][v]))
70
+ else:
71
+ for v in m['vars'].keys():
72
+ if v in revmap:
73
+ varsmap[v] = revmap[v]
74
+ else:
75
+ varsmap[v] = v
76
+ for v in varsmap.keys():
77
+ ret = dictappend(ret, buildusevar(v, varsmap[v], m['vars'], m['name']))
78
+ return ret
79
+
80
+
81
+ def buildusevar(name, realname, vars, usemodulename):
82
+ outmess('\t\t\tConstructing wrapper function for variable "%s=>%s"...\n' % (
83
+ name, realname))
84
+ ret = {}
85
+ vrd = {'name': name,
86
+ 'realname': realname,
87
+ 'REALNAME': realname.upper(),
88
+ 'usemodulename': usemodulename,
89
+ 'USEMODULENAME': usemodulename.upper(),
90
+ 'texname': name.replace('_', '\\_'),
91
+ 'begintitle': gentitle('%s=>%s' % (name, realname)),
92
+ 'endtitle': gentitle('end of %s=>%s' % (name, realname)),
93
+ 'apiname': '#modulename#_use_%s_from_%s' % (realname, usemodulename)
94
+ }
95
+ nummap = {0: 'Ro', 1: 'Ri', 2: 'Rii', 3: 'Riii', 4: 'Riv',
96
+ 5: 'Rv', 6: 'Rvi', 7: 'Rvii', 8: 'Rviii', 9: 'Rix'}
97
+ vrd['texnamename'] = name
98
+ for i in nummap.keys():
99
+ vrd['texnamename'] = vrd['texnamename'].replace(repr(i), nummap[i])
100
+ if hasnote(vars[realname]):
101
+ vrd['note'] = vars[realname]['note']
102
+ rd = dictappend({}, vrd)
103
+
104
+ print(name, realname, vars[realname])
105
+ ret = applyrules(usemodule_rules, rd)
106
+ return ret
env-llmeval/lib/python3.10/site-packages/numpy/testing/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Common test support for all numpy test scripts.
2
+
3
+ This single module should provide all the common functionality for numpy tests
4
+ in a single location, so that test scripts can just import it and work right
5
+ away.
6
+
7
+ """
8
+ from unittest import TestCase
9
+
10
+ from . import _private
11
+ from ._private.utils import *
12
+ from ._private.utils import (_assert_valid_refcount, _gen_alignment_data)
13
+ from ._private import extbuild
14
+ from . import overrides
15
+
16
+ __all__ = (
17
+ _private.utils.__all__ + ['TestCase', 'overrides']
18
+ )
19
+
20
+ from numpy._pytesttester import PytestTester
21
+ test = PytestTester(__name__)
22
+ del PytestTester
env-llmeval/lib/python3.10/site-packages/numpy/testing/__init__.pyi ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy._pytesttester import PytestTester
2
+
3
+ from unittest import (
4
+ TestCase as TestCase,
5
+ )
6
+
7
+ from numpy.testing._private.utils import (
8
+ assert_equal as assert_equal,
9
+ assert_almost_equal as assert_almost_equal,
10
+ assert_approx_equal as assert_approx_equal,
11
+ assert_array_equal as assert_array_equal,
12
+ assert_array_less as assert_array_less,
13
+ assert_string_equal as assert_string_equal,
14
+ assert_array_almost_equal as assert_array_almost_equal,
15
+ assert_raises as assert_raises,
16
+ build_err_msg as build_err_msg,
17
+ decorate_methods as decorate_methods,
18
+ jiffies as jiffies,
19
+ memusage as memusage,
20
+ print_assert_equal as print_assert_equal,
21
+ rundocs as rundocs,
22
+ runstring as runstring,
23
+ verbose as verbose,
24
+ measure as measure,
25
+ assert_ as assert_,
26
+ assert_array_almost_equal_nulp as assert_array_almost_equal_nulp,
27
+ assert_raises_regex as assert_raises_regex,
28
+ assert_array_max_ulp as assert_array_max_ulp,
29
+ assert_warns as assert_warns,
30
+ assert_no_warnings as assert_no_warnings,
31
+ assert_allclose as assert_allclose,
32
+ IgnoreException as IgnoreException,
33
+ clear_and_catch_warnings as clear_and_catch_warnings,
34
+ SkipTest as SkipTest,
35
+ KnownFailureException as KnownFailureException,
36
+ temppath as temppath,
37
+ tempdir as tempdir,
38
+ IS_PYPY as IS_PYPY,
39
+ IS_PYSTON as IS_PYSTON,
40
+ HAS_REFCOUNT as HAS_REFCOUNT,
41
+ suppress_warnings as suppress_warnings,
42
+ assert_array_compare as assert_array_compare,
43
+ assert_no_gc_cycles as assert_no_gc_cycles,
44
+ break_cycles as break_cycles,
45
+ HAS_LAPACK64 as HAS_LAPACK64,
46
+ )
47
+
48
+ __all__: list[str]
49
+ __path__: list[str]
50
+ test: PytestTester
env-llmeval/lib/python3.10/site-packages/numpy/testing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (787 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/testing/__pycache__/overrides.cpython-310.pyc ADDED
Binary file (2.57 kB). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/testing/__pycache__/print_coercion_tables.cpython-310.pyc ADDED
Binary file (4.81 kB). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/testing/__pycache__/setup.cpython-310.pyc ADDED
Binary file (831 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/numpy/testing/_private/__init__.py ADDED
File without changes