assassinlike commited on
Commit
77bfd4d
·
verified ·
1 Parent(s): 2f87a3e

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. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__init__.cpython-310.pyc +0 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__main__.cpython-310.pyc +0 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__version__.cpython-310.pyc +0 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/_isocbind.cpython-310.pyc +0 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/_src_pyf.cpython-310.pyc +0 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/auxfuncs.cpython-310.pyc +0 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/capi_maps.cpython-310.pyc +0 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/cb_rules.cpython-310.pyc +0 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/cfuncs.cpython-310.pyc +0 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/common_rules.cpython-310.pyc +0 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/crackfortran.cpython-310.pyc +0 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/diagnose.cpython-310.pyc +0 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/f2py2e.cpython-310.pyc +0 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/f90mod_rules.cpython-310.pyc +0 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/func2subr.cpython-310.pyc +0 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/rules.cpython-310.pyc +0 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/setup.cpython-310.pyc +0 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/symbolic.cpython-310.pyc +0 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/use_rules.cpython-310.pyc +0 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/_backends/__init__.py +9 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/_backends/_backend.py +46 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/_backends/_distutils.py +75 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/_backends/_meson.py +205 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/_backends/meson.build.template +54 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.c +1423 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.h +173 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__init__.py +0 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_abstract_interface.cpython-310.pyc +0 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_array_from_pyobj.cpython-310.pyc +0 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_common.cpython-310.pyc +0 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_compile_function.cpython-310.pyc +0 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_f2py2e.cpython-310.pyc +0 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_isoc.cpython-310.pyc +0 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_kind.cpython-310.pyc +0 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_module_doc.cpython-310.pyc +0 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_parameter.cpython-310.pyc +0 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_quoted_character.cpython-310.pyc +0 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_return_complex.cpython-310.pyc +0 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_return_logical.cpython-310.pyc +0 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_semicolon_split.cpython-310.pyc +0 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_string.cpython-310.pyc +0 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_symbolic.cpython-310.pyc +0 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_value_attrspec.cpython-310.pyc +0 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/test_abstract_interface.py +25 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/test_array_from_pyobj.py +686 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/test_assumed_shape.py +49 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/test_block_docstring.py +17 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/test_callback.py +243 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/test_character.py +636 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (5.37 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (238 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__version__.cpython-310.pyc ADDED
Binary file (232 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/_isocbind.cpython-310.pyc ADDED
Binary file (1.59 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/_src_pyf.cpython-310.pyc ADDED
Binary file (5.31 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/auxfuncs.cpython-310.pyc ADDED
Binary file (25.3 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/capi_maps.cpython-310.pyc ADDED
Binary file (18.5 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/cb_rules.cpython-310.pyc ADDED
Binary file (18.1 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/cfuncs.cpython-310.pyc ADDED
Binary file (45.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/common_rules.cpython-310.pyc ADDED
Binary file (4.86 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/crackfortran.cpython-310.pyc ADDED
Binary file (87.3 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/diagnose.cpython-310.pyc ADDED
Binary file (3.84 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/f2py2e.cpython-310.pyc ADDED
Binary file (22.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/f90mod_rules.cpython-310.pyc ADDED
Binary file (7.23 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/func2subr.cpython-310.pyc ADDED
Binary file (7.08 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/rules.cpython-310.pyc ADDED
Binary file (38.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/setup.cpython-310.pyc ADDED
Binary file (2.35 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/symbolic.cpython-310.pyc ADDED
Binary file (38.9 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/__pycache__/use_rules.cpython-310.pyc ADDED
Binary file (3.02 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/_backends/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ def f2py_build_generator(name):
2
+ if name == "meson":
3
+ from ._meson import MesonBackend
4
+ return MesonBackend
5
+ elif name == "distutils":
6
+ from ._distutils import DistutilsBackend
7
+ return DistutilsBackend
8
+ else:
9
+ raise ValueError(f"Unknown backend: {name}")
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/_backends/_backend.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+
6
+ class Backend(ABC):
7
+ def __init__(
8
+ self,
9
+ modulename,
10
+ sources,
11
+ extra_objects,
12
+ build_dir,
13
+ include_dirs,
14
+ library_dirs,
15
+ libraries,
16
+ define_macros,
17
+ undef_macros,
18
+ f2py_flags,
19
+ sysinfo_flags,
20
+ fc_flags,
21
+ flib_flags,
22
+ setup_flags,
23
+ remove_build_dir,
24
+ extra_dat,
25
+ ):
26
+ self.modulename = modulename
27
+ self.sources = sources
28
+ self.extra_objects = extra_objects
29
+ self.build_dir = build_dir
30
+ self.include_dirs = include_dirs
31
+ self.library_dirs = library_dirs
32
+ self.libraries = libraries
33
+ self.define_macros = define_macros
34
+ self.undef_macros = undef_macros
35
+ self.f2py_flags = f2py_flags
36
+ self.sysinfo_flags = sysinfo_flags
37
+ self.fc_flags = fc_flags
38
+ self.flib_flags = flib_flags
39
+ self.setup_flags = setup_flags
40
+ self.remove_build_dir = remove_build_dir
41
+ self.extra_dat = extra_dat
42
+
43
+ @abstractmethod
44
+ def compile(self) -> None:
45
+ """Compile the wrapper."""
46
+ pass
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/_backends/_distutils.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._backend import Backend
2
+
3
+ from numpy.distutils.core import setup, Extension
4
+ from numpy.distutils.system_info import get_info
5
+ from numpy.distutils.misc_util import dict_append
6
+ from numpy.exceptions import VisibleDeprecationWarning
7
+ import os
8
+ import sys
9
+ import shutil
10
+ import warnings
11
+
12
+
13
+ class DistutilsBackend(Backend):
14
+ def __init__(sef, *args, **kwargs):
15
+ warnings.warn(
16
+ "distutils has been deprecated since NumPy 1.26.x"
17
+ "Use the Meson backend instead, or generate wrappers"
18
+ "without -c and use a custom build script",
19
+ VisibleDeprecationWarning,
20
+ stacklevel=2,
21
+ )
22
+ super().__init__(*args, **kwargs)
23
+
24
+ def compile(self):
25
+ num_info = {}
26
+ if num_info:
27
+ self.include_dirs.extend(num_info.get("include_dirs", []))
28
+ ext_args = {
29
+ "name": self.modulename,
30
+ "sources": self.sources,
31
+ "include_dirs": self.include_dirs,
32
+ "library_dirs": self.library_dirs,
33
+ "libraries": self.libraries,
34
+ "define_macros": self.define_macros,
35
+ "undef_macros": self.undef_macros,
36
+ "extra_objects": self.extra_objects,
37
+ "f2py_options": self.f2py_flags,
38
+ }
39
+
40
+ if self.sysinfo_flags:
41
+ for n in self.sysinfo_flags:
42
+ i = get_info(n)
43
+ if not i:
44
+ print(
45
+ f"No {repr(n)} resources found"
46
+ "in system (try `f2py --help-link`)"
47
+ )
48
+ dict_append(ext_args, **i)
49
+
50
+ ext = Extension(**ext_args)
51
+
52
+ sys.argv = [sys.argv[0]] + self.setup_flags
53
+ sys.argv.extend(
54
+ [
55
+ "build",
56
+ "--build-temp",
57
+ self.build_dir,
58
+ "--build-base",
59
+ self.build_dir,
60
+ "--build-platlib",
61
+ ".",
62
+ "--disable-optimization",
63
+ ]
64
+ )
65
+
66
+ if self.fc_flags:
67
+ sys.argv.extend(["config_fc"] + self.fc_flags)
68
+ if self.flib_flags:
69
+ sys.argv.extend(["build_ext"] + self.flib_flags)
70
+
71
+ setup(ext_modules=[ext])
72
+
73
+ if self.remove_build_dir and os.path.exists(self.build_dir):
74
+ print(f"Removing build directory {self.build_dir}")
75
+ shutil.rmtree(self.build_dir)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/_backends/_meson.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import errno
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from ._backend import Backend
11
+ from string import Template
12
+ from itertools import chain
13
+
14
+ import warnings
15
+
16
+
17
+ class MesonTemplate:
18
+ """Template meson build file generation class."""
19
+
20
+ def __init__(
21
+ self,
22
+ modulename: str,
23
+ sources: list[Path],
24
+ deps: list[str],
25
+ libraries: list[str],
26
+ library_dirs: list[Path],
27
+ include_dirs: list[Path],
28
+ object_files: list[Path],
29
+ linker_args: list[str],
30
+ c_args: list[str],
31
+ build_type: str,
32
+ python_exe: str,
33
+ ):
34
+ self.modulename = modulename
35
+ self.build_template_path = (
36
+ Path(__file__).parent.absolute() / "meson.build.template"
37
+ )
38
+ self.sources = sources
39
+ self.deps = deps
40
+ self.libraries = libraries
41
+ self.library_dirs = library_dirs
42
+ if include_dirs is not None:
43
+ self.include_dirs = include_dirs
44
+ else:
45
+ self.include_dirs = []
46
+ self.substitutions = {}
47
+ self.objects = object_files
48
+ self.pipeline = [
49
+ self.initialize_template,
50
+ self.sources_substitution,
51
+ self.deps_substitution,
52
+ self.include_substitution,
53
+ self.libraries_substitution,
54
+ ]
55
+ self.build_type = build_type
56
+ self.python_exe = python_exe
57
+
58
+ def meson_build_template(self) -> str:
59
+ if not self.build_template_path.is_file():
60
+ raise FileNotFoundError(
61
+ errno.ENOENT,
62
+ "Meson build template"
63
+ f" {self.build_template_path.absolute()}"
64
+ " does not exist.",
65
+ )
66
+ return self.build_template_path.read_text()
67
+
68
+ def initialize_template(self) -> None:
69
+ self.substitutions["modulename"] = self.modulename
70
+ self.substitutions["buildtype"] = self.build_type
71
+ self.substitutions["python"] = self.python_exe
72
+
73
+ def sources_substitution(self) -> None:
74
+ indent = " " * 21
75
+ self.substitutions["source_list"] = f",\n{indent}".join(
76
+ [f"{indent}'{source}'" for source in self.sources]
77
+ )
78
+
79
+ def deps_substitution(self) -> None:
80
+ indent = " " * 21
81
+ self.substitutions["dep_list"] = f",\n{indent}".join(
82
+ [f"{indent}dependency('{dep}')" for dep in self.deps]
83
+ )
84
+
85
+ def libraries_substitution(self) -> None:
86
+ self.substitutions["lib_dir_declarations"] = "\n".join(
87
+ [
88
+ f"lib_dir_{i} = declare_dependency(link_args : ['-L{lib_dir}'])"
89
+ for i, lib_dir in enumerate(self.library_dirs)
90
+ ]
91
+ )
92
+
93
+ self.substitutions["lib_declarations"] = "\n".join(
94
+ [
95
+ f"{lib} = declare_dependency(link_args : ['-l{lib}'])"
96
+ for lib in self.libraries
97
+ ]
98
+ )
99
+
100
+ indent = " " * 21
101
+ self.substitutions["lib_list"] = f"\n{indent}".join(
102
+ [f"{indent}{lib}," for lib in self.libraries]
103
+ )
104
+ self.substitutions["lib_dir_list"] = f"\n{indent}".join(
105
+ [f"{indent}lib_dir_{i}," for i in range(len(self.library_dirs))]
106
+ )
107
+
108
+ def include_substitution(self) -> None:
109
+ indent = " " * 21
110
+ self.substitutions["inc_list"] = f",\n{indent}".join(
111
+ [f"{indent}'{inc}'" for inc in self.include_dirs]
112
+ )
113
+
114
+ def generate_meson_build(self):
115
+ for node in self.pipeline:
116
+ node()
117
+ template = Template(self.meson_build_template())
118
+ return template.substitute(self.substitutions)
119
+
120
+
121
+ class MesonBackend(Backend):
122
+ def __init__(self, *args, **kwargs):
123
+ super().__init__(*args, **kwargs)
124
+ self.dependencies = self.extra_dat.get("dependencies", [])
125
+ self.meson_build_dir = "bbdir"
126
+ self.build_type = (
127
+ "debug" if any("debug" in flag for flag in self.fc_flags) else "release"
128
+ )
129
+
130
+ def _move_exec_to_root(self, build_dir: Path):
131
+ walk_dir = Path(build_dir) / self.meson_build_dir
132
+ path_objects = chain(
133
+ walk_dir.glob(f"{self.modulename}*.so"),
134
+ walk_dir.glob(f"{self.modulename}*.pyd"),
135
+ )
136
+ # Same behavior as distutils
137
+ # https://github.com/numpy/numpy/issues/24874#issuecomment-1835632293
138
+ for path_object in path_objects:
139
+ dest_path = Path.cwd() / path_object.name
140
+ if dest_path.exists():
141
+ dest_path.unlink()
142
+ shutil.copy2(path_object, dest_path)
143
+ os.remove(path_object)
144
+
145
+ def write_meson_build(self, build_dir: Path) -> None:
146
+ """Writes the meson build file at specified location"""
147
+ meson_template = MesonTemplate(
148
+ self.modulename,
149
+ self.sources,
150
+ self.dependencies,
151
+ self.libraries,
152
+ self.library_dirs,
153
+ self.include_dirs,
154
+ self.extra_objects,
155
+ self.flib_flags,
156
+ self.fc_flags,
157
+ self.build_type,
158
+ sys.executable,
159
+ )
160
+ src = meson_template.generate_meson_build()
161
+ Path(build_dir).mkdir(parents=True, exist_ok=True)
162
+ meson_build_file = Path(build_dir) / "meson.build"
163
+ meson_build_file.write_text(src)
164
+ return meson_build_file
165
+
166
+ def _run_subprocess_command(self, command, cwd):
167
+ subprocess.run(command, cwd=cwd, check=True)
168
+
169
+ def run_meson(self, build_dir: Path):
170
+ setup_command = ["meson", "setup", self.meson_build_dir]
171
+ self._run_subprocess_command(setup_command, build_dir)
172
+ compile_command = ["meson", "compile", "-C", self.meson_build_dir]
173
+ self._run_subprocess_command(compile_command, build_dir)
174
+
175
+ def compile(self) -> None:
176
+ self.sources = _prepare_sources(self.modulename, self.sources, self.build_dir)
177
+ self.write_meson_build(self.build_dir)
178
+ self.run_meson(self.build_dir)
179
+ self._move_exec_to_root(self.build_dir)
180
+
181
+
182
+ def _prepare_sources(mname, sources, bdir):
183
+ extended_sources = sources.copy()
184
+ Path(bdir).mkdir(parents=True, exist_ok=True)
185
+ # Copy sources
186
+ for source in sources:
187
+ if Path(source).exists() and Path(source).is_file():
188
+ shutil.copy(source, bdir)
189
+ generated_sources = [
190
+ Path(f"{mname}module.c"),
191
+ Path(f"{mname}-f2pywrappers2.f90"),
192
+ Path(f"{mname}-f2pywrappers.f"),
193
+ ]
194
+ bdir = Path(bdir)
195
+ for generated_source in generated_sources:
196
+ if generated_source.exists():
197
+ shutil.copy(generated_source, bdir / generated_source.name)
198
+ extended_sources.append(generated_source.name)
199
+ generated_source.unlink()
200
+ extended_sources = [
201
+ Path(source).name
202
+ for source in extended_sources
203
+ if not Path(source).suffix == ".pyf"
204
+ ]
205
+ return extended_sources
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/_backends/meson.build.template ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ project('${modulename}',
2
+ ['c', 'fortran'],
3
+ version : '0.1',
4
+ meson_version: '>= 1.1.0',
5
+ default_options : [
6
+ 'warning_level=1',
7
+ 'buildtype=${buildtype}'
8
+ ])
9
+ fc = meson.get_compiler('fortran')
10
+
11
+ py = import('python').find_installation('${python}', pure: false)
12
+ py_dep = py.dependency()
13
+
14
+ incdir_numpy = run_command(py,
15
+ ['-c', 'import os; os.chdir(".."); import numpy; print(numpy.get_include())'],
16
+ check : true
17
+ ).stdout().strip()
18
+
19
+ incdir_f2py = run_command(py,
20
+ ['-c', 'import os; os.chdir(".."); import numpy.f2py; print(numpy.f2py.get_include())'],
21
+ check : true
22
+ ).stdout().strip()
23
+
24
+ inc_np = include_directories(incdir_numpy)
25
+ np_dep = declare_dependency(include_directories: inc_np)
26
+
27
+ incdir_f2py = incdir_numpy / '..' / '..' / 'f2py' / 'src'
28
+ inc_f2py = include_directories(incdir_f2py)
29
+ fortranobject_c = incdir_f2py / 'fortranobject.c'
30
+
31
+ inc_np = include_directories(incdir_numpy, incdir_f2py)
32
+ # gh-25000
33
+ quadmath_dep = fc.find_library('quadmath', required: false)
34
+
35
+ ${lib_declarations}
36
+ ${lib_dir_declarations}
37
+
38
+ py.extension_module('${modulename}',
39
+ [
40
+ ${source_list},
41
+ fortranobject_c
42
+ ],
43
+ include_directories: [
44
+ inc_np,
45
+ ${inc_list}
46
+ ],
47
+ dependencies : [
48
+ py_dep,
49
+ quadmath_dep,
50
+ ${dep_list}
51
+ ${lib_list}
52
+ ${lib_dir_list}
53
+ ],
54
+ install : true)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.c ADDED
@@ -0,0 +1,1423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define FORTRANOBJECT_C
2
+ #include "fortranobject.h"
3
+
4
+ #ifdef __cplusplus
5
+ extern "C" {
6
+ #endif
7
+
8
+ #include <stdarg.h>
9
+ #include <stdlib.h>
10
+ #include <string.h>
11
+
12
+ /*
13
+ This file implements: FortranObject, array_from_pyobj, copy_ND_array
14
+
15
+ Author: Pearu Peterson <pearu@cens.ioc.ee>
16
+ $Revision: 1.52 $
17
+ $Date: 2005/07/11 07:44:20 $
18
+ */
19
+
20
+ int
21
+ F2PyDict_SetItemString(PyObject *dict, char *name, PyObject *obj)
22
+ {
23
+ if (obj == NULL) {
24
+ fprintf(stderr, "Error loading %s\n", name);
25
+ if (PyErr_Occurred()) {
26
+ PyErr_Print();
27
+ PyErr_Clear();
28
+ }
29
+ return -1;
30
+ }
31
+ return PyDict_SetItemString(dict, name, obj);
32
+ }
33
+
34
+ /*
35
+ * Python-only fallback for thread-local callback pointers
36
+ */
37
+ void *
38
+ F2PySwapThreadLocalCallbackPtr(char *key, void *ptr)
39
+ {
40
+ PyObject *local_dict, *value;
41
+ void *prev;
42
+
43
+ local_dict = PyThreadState_GetDict();
44
+ if (local_dict == NULL) {
45
+ Py_FatalError(
46
+ "F2PySwapThreadLocalCallbackPtr: PyThreadState_GetDict "
47
+ "failed");
48
+ }
49
+
50
+ value = PyDict_GetItemString(local_dict, key);
51
+ if (value != NULL) {
52
+ prev = PyLong_AsVoidPtr(value);
53
+ if (PyErr_Occurred()) {
54
+ Py_FatalError(
55
+ "F2PySwapThreadLocalCallbackPtr: PyLong_AsVoidPtr failed");
56
+ }
57
+ }
58
+ else {
59
+ prev = NULL;
60
+ }
61
+
62
+ value = PyLong_FromVoidPtr((void *)ptr);
63
+ if (value == NULL) {
64
+ Py_FatalError(
65
+ "F2PySwapThreadLocalCallbackPtr: PyLong_FromVoidPtr failed");
66
+ }
67
+
68
+ if (PyDict_SetItemString(local_dict, key, value) != 0) {
69
+ Py_FatalError(
70
+ "F2PySwapThreadLocalCallbackPtr: PyDict_SetItemString failed");
71
+ }
72
+
73
+ Py_DECREF(value);
74
+
75
+ return prev;
76
+ }
77
+
78
+ void *
79
+ F2PyGetThreadLocalCallbackPtr(char *key)
80
+ {
81
+ PyObject *local_dict, *value;
82
+ void *prev;
83
+
84
+ local_dict = PyThreadState_GetDict();
85
+ if (local_dict == NULL) {
86
+ Py_FatalError(
87
+ "F2PyGetThreadLocalCallbackPtr: PyThreadState_GetDict failed");
88
+ }
89
+
90
+ value = PyDict_GetItemString(local_dict, key);
91
+ if (value != NULL) {
92
+ prev = PyLong_AsVoidPtr(value);
93
+ if (PyErr_Occurred()) {
94
+ Py_FatalError(
95
+ "F2PyGetThreadLocalCallbackPtr: PyLong_AsVoidPtr failed");
96
+ }
97
+ }
98
+ else {
99
+ prev = NULL;
100
+ }
101
+
102
+ return prev;
103
+ }
104
+
105
+ static PyArray_Descr *
106
+ get_descr_from_type_and_elsize(const int type_num, const int elsize) {
107
+ PyArray_Descr * descr = PyArray_DescrFromType(type_num);
108
+ if (type_num == NPY_STRING) {
109
+ // PyArray_DescrFromType returns descr with elsize = 0.
110
+ PyArray_DESCR_REPLACE(descr);
111
+ if (descr == NULL) {
112
+ return NULL;
113
+ }
114
+ descr->elsize = elsize;
115
+ }
116
+ return descr;
117
+ }
118
+
119
+ /************************* FortranObject *******************************/
120
+
121
+ typedef PyObject *(*fortranfunc)(PyObject *, PyObject *, PyObject *, void *);
122
+
123
+ PyObject *
124
+ PyFortranObject_New(FortranDataDef *defs, f2py_void_func init)
125
+ {
126
+ int i;
127
+ PyFortranObject *fp = NULL;
128
+ PyObject *v = NULL;
129
+ if (init != NULL) { /* Initialize F90 module objects */
130
+ (*(init))();
131
+ }
132
+ fp = PyObject_New(PyFortranObject, &PyFortran_Type);
133
+ if (fp == NULL) {
134
+ return NULL;
135
+ }
136
+ if ((fp->dict = PyDict_New()) == NULL) {
137
+ Py_DECREF(fp);
138
+ return NULL;
139
+ }
140
+ fp->len = 0;
141
+ while (defs[fp->len].name != NULL) {
142
+ fp->len++;
143
+ }
144
+ if (fp->len == 0) {
145
+ goto fail;
146
+ }
147
+ fp->defs = defs;
148
+ for (i = 0; i < fp->len; i++) {
149
+ if (fp->defs[i].rank == -1) { /* Is Fortran routine */
150
+ v = PyFortranObject_NewAsAttr(&(fp->defs[i]));
151
+ if (v == NULL) {
152
+ goto fail;
153
+ }
154
+ PyDict_SetItemString(fp->dict, fp->defs[i].name, v);
155
+ Py_XDECREF(v);
156
+ }
157
+ else if ((fp->defs[i].data) !=
158
+ NULL) { /* Is Fortran variable or array (not allocatable) */
159
+ PyArray_Descr *
160
+ descr = get_descr_from_type_and_elsize(fp->defs[i].type,
161
+ fp->defs[i].elsize);
162
+ if (descr == NULL) {
163
+ goto fail;
164
+ }
165
+ v = PyArray_NewFromDescr(&PyArray_Type, descr, fp->defs[i].rank,
166
+ fp->defs[i].dims.d, NULL, fp->defs[i].data,
167
+ NPY_ARRAY_FARRAY, NULL);
168
+ if (v == NULL) {
169
+ Py_DECREF(descr);
170
+ goto fail;
171
+ }
172
+ PyDict_SetItemString(fp->dict, fp->defs[i].name, v);
173
+ Py_XDECREF(v);
174
+ }
175
+ }
176
+ return (PyObject *)fp;
177
+ fail:
178
+ Py_XDECREF(fp);
179
+ return NULL;
180
+ }
181
+
182
+ PyObject *
183
+ PyFortranObject_NewAsAttr(FortranDataDef *defs)
184
+ { /* used for calling F90 module routines */
185
+ PyFortranObject *fp = NULL;
186
+ fp = PyObject_New(PyFortranObject, &PyFortran_Type);
187
+ if (fp == NULL)
188
+ return NULL;
189
+ if ((fp->dict = PyDict_New()) == NULL) {
190
+ PyObject_Del(fp);
191
+ return NULL;
192
+ }
193
+ fp->len = 1;
194
+ fp->defs = defs;
195
+ if (defs->rank == -1) {
196
+ PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("function %s", defs->name));
197
+ } else if (defs->rank == 0) {
198
+ PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("scalar %s", defs->name));
199
+ } else {
200
+ PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("array %s", defs->name));
201
+ }
202
+ return (PyObject *)fp;
203
+ }
204
+
205
+ /* Fortran methods */
206
+
207
+ static void
208
+ fortran_dealloc(PyFortranObject *fp)
209
+ {
210
+ Py_XDECREF(fp->dict);
211
+ PyObject_Del(fp);
212
+ }
213
+
214
+ /* Returns number of bytes consumed from buf, or -1 on error. */
215
+ static Py_ssize_t
216
+ format_def(char *buf, Py_ssize_t size, FortranDataDef def)
217
+ {
218
+ char *p = buf;
219
+ int i;
220
+ npy_intp n;
221
+
222
+ n = PyOS_snprintf(p, size, "array(%" NPY_INTP_FMT, def.dims.d[0]);
223
+ if (n < 0 || n >= size) {
224
+ return -1;
225
+ }
226
+ p += n;
227
+ size -= n;
228
+
229
+ for (i = 1; i < def.rank; i++) {
230
+ n = PyOS_snprintf(p, size, ",%" NPY_INTP_FMT, def.dims.d[i]);
231
+ if (n < 0 || n >= size) {
232
+ return -1;
233
+ }
234
+ p += n;
235
+ size -= n;
236
+ }
237
+
238
+ if (size <= 0) {
239
+ return -1;
240
+ }
241
+
242
+ *p++ = ')';
243
+ size--;
244
+
245
+ if (def.data == NULL) {
246
+ static const char notalloc[] = ", not allocated";
247
+ if ((size_t)size < sizeof(notalloc)) {
248
+ return -1;
249
+ }
250
+ memcpy(p, notalloc, sizeof(notalloc));
251
+ p += sizeof(notalloc);
252
+ size -= sizeof(notalloc);
253
+ }
254
+
255
+ return p - buf;
256
+ }
257
+
258
+ static PyObject *
259
+ fortran_doc(FortranDataDef def)
260
+ {
261
+ char *buf, *p;
262
+ PyObject *s = NULL;
263
+ Py_ssize_t n, origsize, size = 100;
264
+
265
+ if (def.doc != NULL) {
266
+ size += strlen(def.doc);
267
+ }
268
+ origsize = size;
269
+ buf = p = (char *)PyMem_Malloc(size);
270
+ if (buf == NULL) {
271
+ return PyErr_NoMemory();
272
+ }
273
+
274
+ if (def.rank == -1) {
275
+ if (def.doc) {
276
+ n = strlen(def.doc);
277
+ if (n > size) {
278
+ goto fail;
279
+ }
280
+ memcpy(p, def.doc, n);
281
+ p += n;
282
+ size -= n;
283
+ }
284
+ else {
285
+ n = PyOS_snprintf(p, size, "%s - no docs available", def.name);
286
+ if (n < 0 || n >= size) {
287
+ goto fail;
288
+ }
289
+ p += n;
290
+ size -= n;
291
+ }
292
+ }
293
+ else {
294
+ PyArray_Descr *d = PyArray_DescrFromType(def.type);
295
+ n = PyOS_snprintf(p, size, "%s : '%c'-", def.name, d->type);
296
+ Py_DECREF(d);
297
+ if (n < 0 || n >= size) {
298
+ goto fail;
299
+ }
300
+ p += n;
301
+ size -= n;
302
+
303
+ if (def.data == NULL) {
304
+ n = format_def(p, size, def);
305
+ if (n < 0) {
306
+ goto fail;
307
+ }
308
+ p += n;
309
+ size -= n;
310
+ }
311
+ else if (def.rank > 0) {
312
+ n = format_def(p, size, def);
313
+ if (n < 0) {
314
+ goto fail;
315
+ }
316
+ p += n;
317
+ size -= n;
318
+ }
319
+ else {
320
+ n = strlen("scalar");
321
+ if (size < n) {
322
+ goto fail;
323
+ }
324
+ memcpy(p, "scalar", n);
325
+ p += n;
326
+ size -= n;
327
+ }
328
+ }
329
+ if (size <= 1) {
330
+ goto fail;
331
+ }
332
+ *p++ = '\n';
333
+ size--;
334
+
335
+ /* p now points one beyond the last character of the string in buf */
336
+ s = PyUnicode_FromStringAndSize(buf, p - buf);
337
+
338
+ PyMem_Free(buf);
339
+ return s;
340
+
341
+ fail:
342
+ fprintf(stderr,
343
+ "fortranobject.c: fortran_doc: len(p)=%zd>%zd=size:"
344
+ " too long docstring required, increase size\n",
345
+ p - buf, origsize);
346
+ PyMem_Free(buf);
347
+ return NULL;
348
+ }
349
+
350
+ static FortranDataDef *save_def; /* save pointer of an allocatable array */
351
+ static void
352
+ set_data(char *d, npy_intp *f)
353
+ { /* callback from Fortran */
354
+ if (*f) /* In fortran f=allocated(d) */
355
+ save_def->data = d;
356
+ else
357
+ save_def->data = NULL;
358
+ /* printf("set_data: d=%p,f=%d\n",d,*f); */
359
+ }
360
+
361
+ static PyObject *
362
+ fortran_getattr(PyFortranObject *fp, char *name)
363
+ {
364
+ int i, j, k, flag;
365
+ if (fp->dict != NULL) {
366
+ PyObject *v = _PyDict_GetItemStringWithError(fp->dict, name);
367
+ if (v == NULL && PyErr_Occurred()) {
368
+ return NULL;
369
+ }
370
+ else if (v != NULL) {
371
+ Py_INCREF(v);
372
+ return v;
373
+ }
374
+ }
375
+ for (i = 0, j = 1; i < fp->len && (j = strcmp(name, fp->defs[i].name));
376
+ i++)
377
+ ;
378
+ if (j == 0)
379
+ if (fp->defs[i].rank != -1) { /* F90 allocatable array */
380
+ if (fp->defs[i].func == NULL)
381
+ return NULL;
382
+ for (k = 0; k < fp->defs[i].rank; ++k) fp->defs[i].dims.d[k] = -1;
383
+ save_def = &fp->defs[i];
384
+ (*(fp->defs[i].func))(&fp->defs[i].rank, fp->defs[i].dims.d,
385
+ set_data, &flag);
386
+ if (flag == 2)
387
+ k = fp->defs[i].rank + 1;
388
+ else
389
+ k = fp->defs[i].rank;
390
+ if (fp->defs[i].data != NULL) { /* array is allocated */
391
+ PyObject *v = PyArray_New(
392
+ &PyArray_Type, k, fp->defs[i].dims.d, fp->defs[i].type,
393
+ NULL, fp->defs[i].data, 0, NPY_ARRAY_FARRAY, NULL);
394
+ if (v == NULL)
395
+ return NULL;
396
+ /* Py_INCREF(v); */
397
+ return v;
398
+ }
399
+ else { /* array is not allocated */
400
+ Py_RETURN_NONE;
401
+ }
402
+ }
403
+ if (strcmp(name, "__dict__") == 0) {
404
+ Py_INCREF(fp->dict);
405
+ return fp->dict;
406
+ }
407
+ if (strcmp(name, "__doc__") == 0) {
408
+ PyObject *s = PyUnicode_FromString(""), *s2, *s3;
409
+ for (i = 0; i < fp->len; i++) {
410
+ s2 = fortran_doc(fp->defs[i]);
411
+ s3 = PyUnicode_Concat(s, s2);
412
+ Py_DECREF(s2);
413
+ Py_DECREF(s);
414
+ s = s3;
415
+ }
416
+ if (PyDict_SetItemString(fp->dict, name, s))
417
+ return NULL;
418
+ return s;
419
+ }
420
+ if ((strcmp(name, "_cpointer") == 0) && (fp->len == 1)) {
421
+ PyObject *cobj =
422
+ F2PyCapsule_FromVoidPtr((void *)(fp->defs[0].data), NULL);
423
+ if (PyDict_SetItemString(fp->dict, name, cobj))
424
+ return NULL;
425
+ return cobj;
426
+ }
427
+ PyObject *str, *ret;
428
+ str = PyUnicode_FromString(name);
429
+ ret = PyObject_GenericGetAttr((PyObject *)fp, str);
430
+ Py_DECREF(str);
431
+ return ret;
432
+ }
433
+
434
+ static int
435
+ fortran_setattr(PyFortranObject *fp, char *name, PyObject *v)
436
+ {
437
+ int i, j, flag;
438
+ PyArrayObject *arr = NULL;
439
+ for (i = 0, j = 1; i < fp->len && (j = strcmp(name, fp->defs[i].name));
440
+ i++)
441
+ ;
442
+ if (j == 0) {
443
+ if (fp->defs[i].rank == -1) {
444
+ PyErr_SetString(PyExc_AttributeError,
445
+ "over-writing fortran routine");
446
+ return -1;
447
+ }
448
+ if (fp->defs[i].func != NULL) { /* is allocatable array */
449
+ npy_intp dims[F2PY_MAX_DIMS];
450
+ int k;
451
+ save_def = &fp->defs[i];
452
+ if (v != Py_None) { /* set new value (reallocate if needed --
453
+ see f2py generated code for more
454
+ details ) */
455
+ for (k = 0; k < fp->defs[i].rank; k++) dims[k] = -1;
456
+ if ((arr = array_from_pyobj(fp->defs[i].type, dims,
457
+ fp->defs[i].rank, F2PY_INTENT_IN,
458
+ v)) == NULL)
459
+ return -1;
460
+ (*(fp->defs[i].func))(&fp->defs[i].rank, PyArray_DIMS(arr),
461
+ set_data, &flag);
462
+ }
463
+ else { /* deallocate */
464
+ for (k = 0; k < fp->defs[i].rank; k++) dims[k] = 0;
465
+ (*(fp->defs[i].func))(&fp->defs[i].rank, dims, set_data,
466
+ &flag);
467
+ for (k = 0; k < fp->defs[i].rank; k++) dims[k] = -1;
468
+ }
469
+ memcpy(fp->defs[i].dims.d, dims,
470
+ fp->defs[i].rank * sizeof(npy_intp));
471
+ }
472
+ else { /* not allocatable array */
473
+ if ((arr = array_from_pyobj(fp->defs[i].type, fp->defs[i].dims.d,
474
+ fp->defs[i].rank, F2PY_INTENT_IN,
475
+ v)) == NULL)
476
+ return -1;
477
+ }
478
+ if (fp->defs[i].data !=
479
+ NULL) { /* copy Python object to Fortran array */
480
+ npy_intp s = PyArray_MultiplyList(fp->defs[i].dims.d,
481
+ PyArray_NDIM(arr));
482
+ if (s == -1)
483
+ s = PyArray_MultiplyList(PyArray_DIMS(arr), PyArray_NDIM(arr));
484
+ if (s < 0 || (memcpy(fp->defs[i].data, PyArray_DATA(arr),
485
+ s * PyArray_ITEMSIZE(arr))) == NULL) {
486
+ if ((PyObject *)arr != v) {
487
+ Py_DECREF(arr);
488
+ }
489
+ return -1;
490
+ }
491
+ if ((PyObject *)arr != v) {
492
+ Py_DECREF(arr);
493
+ }
494
+ }
495
+ else
496
+ return (fp->defs[i].func == NULL ? -1 : 0);
497
+ return 0; /* successful */
498
+ }
499
+ if (fp->dict == NULL) {
500
+ fp->dict = PyDict_New();
501
+ if (fp->dict == NULL)
502
+ return -1;
503
+ }
504
+ if (v == NULL) {
505
+ int rv = PyDict_DelItemString(fp->dict, name);
506
+ if (rv < 0)
507
+ PyErr_SetString(PyExc_AttributeError,
508
+ "delete non-existing fortran attribute");
509
+ return rv;
510
+ }
511
+ else
512
+ return PyDict_SetItemString(fp->dict, name, v);
513
+ }
514
+
515
+ static PyObject *
516
+ fortran_call(PyFortranObject *fp, PyObject *arg, PyObject *kw)
517
+ {
518
+ int i = 0;
519
+ /* printf("fortran call
520
+ name=%s,func=%p,data=%p,%p\n",fp->defs[i].name,
521
+ fp->defs[i].func,fp->defs[i].data,&fp->defs[i].data); */
522
+ if (fp->defs[i].rank == -1) { /* is Fortran routine */
523
+ if (fp->defs[i].func == NULL) {
524
+ PyErr_Format(PyExc_RuntimeError, "no function to call");
525
+ return NULL;
526
+ }
527
+ else if (fp->defs[i].data == NULL)
528
+ /* dummy routine */
529
+ return (*((fortranfunc)(fp->defs[i].func)))((PyObject *)fp, arg,
530
+ kw, NULL);
531
+ else
532
+ return (*((fortranfunc)(fp->defs[i].func)))(
533
+ (PyObject *)fp, arg, kw, (void *)fp->defs[i].data);
534
+ }
535
+ PyErr_Format(PyExc_TypeError, "this fortran object is not callable");
536
+ return NULL;
537
+ }
538
+
539
+ static PyObject *
540
+ fortran_repr(PyFortranObject *fp)
541
+ {
542
+ PyObject *name = NULL, *repr = NULL;
543
+ name = PyObject_GetAttrString((PyObject *)fp, "__name__");
544
+ PyErr_Clear();
545
+ if (name != NULL && PyUnicode_Check(name)) {
546
+ repr = PyUnicode_FromFormat("<fortran %U>", name);
547
+ }
548
+ else {
549
+ repr = PyUnicode_FromString("<fortran object>");
550
+ }
551
+ Py_XDECREF(name);
552
+ return repr;
553
+ }
554
+
555
+ PyTypeObject PyFortran_Type = {
556
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fortran",
557
+ .tp_basicsize = sizeof(PyFortranObject),
558
+ .tp_dealloc = (destructor)fortran_dealloc,
559
+ .tp_getattr = (getattrfunc)fortran_getattr,
560
+ .tp_setattr = (setattrfunc)fortran_setattr,
561
+ .tp_repr = (reprfunc)fortran_repr,
562
+ .tp_call = (ternaryfunc)fortran_call,
563
+ };
564
+
565
+ /************************* f2py_report_atexit *******************************/
566
+
567
+ #ifdef F2PY_REPORT_ATEXIT
568
+ static int passed_time = 0;
569
+ static int passed_counter = 0;
570
+ static int passed_call_time = 0;
571
+ static struct timeb start_time;
572
+ static struct timeb stop_time;
573
+ static struct timeb start_call_time;
574
+ static struct timeb stop_call_time;
575
+ static int cb_passed_time = 0;
576
+ static int cb_passed_counter = 0;
577
+ static int cb_passed_call_time = 0;
578
+ static struct timeb cb_start_time;
579
+ static struct timeb cb_stop_time;
580
+ static struct timeb cb_start_call_time;
581
+ static struct timeb cb_stop_call_time;
582
+
583
+ extern void
584
+ f2py_start_clock(void)
585
+ {
586
+ ftime(&start_time);
587
+ }
588
+ extern void
589
+ f2py_start_call_clock(void)
590
+ {
591
+ f2py_stop_clock();
592
+ ftime(&start_call_time);
593
+ }
594
+ extern void
595
+ f2py_stop_clock(void)
596
+ {
597
+ ftime(&stop_time);
598
+ passed_time += 1000 * (stop_time.time - start_time.time);
599
+ passed_time += stop_time.millitm - start_time.millitm;
600
+ }
601
+ extern void
602
+ f2py_stop_call_clock(void)
603
+ {
604
+ ftime(&stop_call_time);
605
+ passed_call_time += 1000 * (stop_call_time.time - start_call_time.time);
606
+ passed_call_time += stop_call_time.millitm - start_call_time.millitm;
607
+ passed_counter += 1;
608
+ f2py_start_clock();
609
+ }
610
+
611
+ extern void
612
+ f2py_cb_start_clock(void)
613
+ {
614
+ ftime(&cb_start_time);
615
+ }
616
+ extern void
617
+ f2py_cb_start_call_clock(void)
618
+ {
619
+ f2py_cb_stop_clock();
620
+ ftime(&cb_start_call_time);
621
+ }
622
+ extern void
623
+ f2py_cb_stop_clock(void)
624
+ {
625
+ ftime(&cb_stop_time);
626
+ cb_passed_time += 1000 * (cb_stop_time.time - cb_start_time.time);
627
+ cb_passed_time += cb_stop_time.millitm - cb_start_time.millitm;
628
+ }
629
+ extern void
630
+ f2py_cb_stop_call_clock(void)
631
+ {
632
+ ftime(&cb_stop_call_time);
633
+ cb_passed_call_time +=
634
+ 1000 * (cb_stop_call_time.time - cb_start_call_time.time);
635
+ cb_passed_call_time +=
636
+ cb_stop_call_time.millitm - cb_start_call_time.millitm;
637
+ cb_passed_counter += 1;
638
+ f2py_cb_start_clock();
639
+ }
640
+
641
+ static int f2py_report_on_exit_been_here = 0;
642
+ extern void
643
+ f2py_report_on_exit(int exit_flag, void *name)
644
+ {
645
+ if (f2py_report_on_exit_been_here) {
646
+ fprintf(stderr, " %s\n", (char *)name);
647
+ return;
648
+ }
649
+ f2py_report_on_exit_been_here = 1;
650
+ fprintf(stderr, " /-----------------------\\\n");
651
+ fprintf(stderr, " < F2PY performance report >\n");
652
+ fprintf(stderr, " \\-----------------------/\n");
653
+ fprintf(stderr, "Overall time spent in ...\n");
654
+ fprintf(stderr, "(a) wrapped (Fortran/C) functions : %8d msec\n",
655
+ passed_call_time);
656
+ fprintf(stderr, "(b) f2py interface, %6d calls : %8d msec\n",
657
+ passed_counter, passed_time);
658
+ fprintf(stderr, "(c) call-back (Python) functions : %8d msec\n",
659
+ cb_passed_call_time);
660
+ fprintf(stderr, "(d) f2py call-back interface, %6d calls : %8d msec\n",
661
+ cb_passed_counter, cb_passed_time);
662
+
663
+ fprintf(stderr,
664
+ "(e) wrapped (Fortran/C) functions (actual) : %8d msec\n\n",
665
+ passed_call_time - cb_passed_call_time - cb_passed_time);
666
+ fprintf(stderr,
667
+ "Use -DF2PY_REPORT_ATEXIT_DISABLE to disable this message.\n");
668
+ fprintf(stderr, "Exit status: %d\n", exit_flag);
669
+ fprintf(stderr, "Modules : %s\n", (char *)name);
670
+ }
671
+ #endif
672
+
673
+ /********************** report on array copy ****************************/
674
+
675
+ #ifdef F2PY_REPORT_ON_ARRAY_COPY
676
+ static void
677
+ f2py_report_on_array_copy(PyArrayObject *arr)
678
+ {
679
+ const npy_intp arr_size = PyArray_Size((PyObject *)arr);
680
+ if (arr_size > F2PY_REPORT_ON_ARRAY_COPY) {
681
+ fprintf(stderr,
682
+ "copied an array: size=%ld, elsize=%" NPY_INTP_FMT "\n",
683
+ arr_size, (npy_intp)PyArray_ITEMSIZE(arr));
684
+ }
685
+ }
686
+ static void
687
+ f2py_report_on_array_copy_fromany(void)
688
+ {
689
+ fprintf(stderr, "created an array from object\n");
690
+ }
691
+
692
+ #define F2PY_REPORT_ON_ARRAY_COPY_FROMARR \
693
+ f2py_report_on_array_copy((PyArrayObject *)arr)
694
+ #define F2PY_REPORT_ON_ARRAY_COPY_FROMANY f2py_report_on_array_copy_fromany()
695
+ #else
696
+ #define F2PY_REPORT_ON_ARRAY_COPY_FROMARR
697
+ #define F2PY_REPORT_ON_ARRAY_COPY_FROMANY
698
+ #endif
699
+
700
+ /************************* array_from_obj *******************************/
701
+
702
+ /*
703
+ * File: array_from_pyobj.c
704
+ *
705
+ * Description:
706
+ * ------------
707
+ * Provides array_from_pyobj function that returns a contiguous array
708
+ * object with the given dimensions and required storage order, either
709
+ * in row-major (C) or column-major (Fortran) order. The function
710
+ * array_from_pyobj is very flexible about its Python object argument
711
+ * that can be any number, list, tuple, or array.
712
+ *
713
+ * array_from_pyobj is used in f2py generated Python extension
714
+ * modules.
715
+ *
716
+ * Author: Pearu Peterson <pearu@cens.ioc.ee>
717
+ * Created: 13-16 January 2002
718
+ * $Id: fortranobject.c,v 1.52 2005/07/11 07:44:20 pearu Exp $
719
+ */
720
+
721
+ static int check_and_fix_dimensions(const PyArrayObject* arr,
722
+ const int rank,
723
+ npy_intp *dims,
724
+ const char *errmess);
725
+
726
+ static int
727
+ find_first_negative_dimension(const int rank, const npy_intp *dims)
728
+ {
729
+ int i;
730
+ for (i = 0; i < rank; ++i) {
731
+ if (dims[i] < 0) {
732
+ return i;
733
+ }
734
+ }
735
+ return -1;
736
+ }
737
+
738
+ #ifdef DEBUG_COPY_ND_ARRAY
739
+ void
740
+ dump_dims(int rank, npy_intp const *dims)
741
+ {
742
+ int i;
743
+ printf("[");
744
+ for (i = 0; i < rank; ++i) {
745
+ printf("%3" NPY_INTP_FMT, dims[i]);
746
+ }
747
+ printf("]\n");
748
+ }
749
+ void
750
+ dump_attrs(const PyArrayObject *obj)
751
+ {
752
+ const PyArrayObject_fields *arr = (const PyArrayObject_fields *)obj;
753
+ int rank = PyArray_NDIM(arr);
754
+ npy_intp size = PyArray_Size((PyObject *)arr);
755
+ printf("\trank = %d, flags = %d, size = %" NPY_INTP_FMT "\n", rank,
756
+ arr->flags, size);
757
+ printf("\tstrides = ");
758
+ dump_dims(rank, arr->strides);
759
+ printf("\tdimensions = ");
760
+ dump_dims(rank, arr->dimensions);
761
+ }
762
+ #endif
763
+
764
+ #define SWAPTYPE(a, b, t) \
765
+ { \
766
+ t c; \
767
+ c = (a); \
768
+ (a) = (b); \
769
+ (b) = c; \
770
+ }
771
+
772
+ static int
773
+ swap_arrays(PyArrayObject *obj1, PyArrayObject *obj2)
774
+ {
775
+ PyArrayObject_fields *arr1 = (PyArrayObject_fields *)obj1,
776
+ *arr2 = (PyArrayObject_fields *)obj2;
777
+ SWAPTYPE(arr1->data, arr2->data, char *);
778
+ SWAPTYPE(arr1->nd, arr2->nd, int);
779
+ SWAPTYPE(arr1->dimensions, arr2->dimensions, npy_intp *);
780
+ SWAPTYPE(arr1->strides, arr2->strides, npy_intp *);
781
+ SWAPTYPE(arr1->base, arr2->base, PyObject *);
782
+ SWAPTYPE(arr1->descr, arr2->descr, PyArray_Descr *);
783
+ SWAPTYPE(arr1->flags, arr2->flags, int);
784
+ /* SWAPTYPE(arr1->weakreflist,arr2->weakreflist,PyObject*); */
785
+ return 0;
786
+ }
787
+
788
+ #define ARRAY_ISCOMPATIBLE(arr,type_num) \
789
+ ((PyArray_ISINTEGER(arr) && PyTypeNum_ISINTEGER(type_num)) || \
790
+ (PyArray_ISFLOAT(arr) && PyTypeNum_ISFLOAT(type_num)) || \
791
+ (PyArray_ISCOMPLEX(arr) && PyTypeNum_ISCOMPLEX(type_num)) || \
792
+ (PyArray_ISBOOL(arr) && PyTypeNum_ISBOOL(type_num)) || \
793
+ (PyArray_ISSTRING(arr) && PyTypeNum_ISSTRING(type_num)))
794
+
795
+ static int
796
+ get_elsize(PyObject *obj) {
797
+ /*
798
+ get_elsize determines array itemsize from a Python object. Returns
799
+ elsize if successful, -1 otherwise.
800
+
801
+ Supported types of the input are: numpy.ndarray, bytes, str, tuple,
802
+ list.
803
+ */
804
+
805
+ if (PyArray_Check(obj)) {
806
+ return PyArray_DESCR((PyArrayObject *)obj)->elsize;
807
+ } else if (PyBytes_Check(obj)) {
808
+ return PyBytes_GET_SIZE(obj);
809
+ } else if (PyUnicode_Check(obj)) {
810
+ return PyUnicode_GET_LENGTH(obj);
811
+ } else if (PySequence_Check(obj)) {
812
+ PyObject* fast = PySequence_Fast(obj, "f2py:fortranobject.c:get_elsize");
813
+ if (fast != NULL) {
814
+ Py_ssize_t i, n = PySequence_Fast_GET_SIZE(fast);
815
+ int sz, elsize = 0;
816
+ for (i=0; i<n; i++) {
817
+ sz = get_elsize(PySequence_Fast_GET_ITEM(fast, i) /* borrowed */);
818
+ if (sz > elsize) {
819
+ elsize = sz;
820
+ }
821
+ }
822
+ Py_DECREF(fast);
823
+ return elsize;
824
+ }
825
+ }
826
+ return -1;
827
+ }
828
+
829
+ extern PyArrayObject *
830
+ ndarray_from_pyobj(const int type_num,
831
+ const int elsize_,
832
+ npy_intp *dims,
833
+ const int rank,
834
+ const int intent,
835
+ PyObject *obj,
836
+ const char *errmess) {
837
+ /*
838
+ * Return an array with given element type and shape from a Python
839
+ * object while taking into account the usage intent of the array.
840
+ *
841
+ * - element type is defined by type_num and elsize
842
+ * - shape is defined by dims and rank
843
+ *
844
+ * ndarray_from_pyobj is used to convert Python object arguments
845
+ * to numpy ndarrays with given type and shape that data is passed
846
+ * to interfaced Fortran or C functions.
847
+ *
848
+ * errmess (if not NULL), contains a prefix of an error message
849
+ * for an exception to be triggered within this function.
850
+ *
851
+ * Negative elsize value means that elsize is to be determined
852
+ * from the Python object in runtime.
853
+ *
854
+ * Note on strings
855
+ * ---------------
856
+ *
857
+ * String type (type_num == NPY_STRING) does not have fixed
858
+ * element size and, by default, the type object sets it to
859
+ * 0. Therefore, for string types, one has to use elsize
860
+ * argument. For other types, elsize value is ignored.
861
+ *
862
+ * NumPy defines the type of a fixed-width string as
863
+ * dtype('S<width>'). In addition, there is also dtype('c'), that
864
+ * appears as dtype('S1') (these have the same type_num value),
865
+ * but is actually different (.char attribute is either 'S' or
866
+ * 'c', respecitely).
867
+ *
868
+ * In Fortran, character arrays and strings are different
869
+ * concepts. The relation between Fortran types, NumPy dtypes,
870
+ * and type_num-elsize pairs, is defined as follows:
871
+ *
872
+ * character*5 foo | dtype('S5') | elsize=5, shape=()
873
+ * character(5) foo | dtype('S1') | elsize=1, shape=(5)
874
+ * character*5 foo(n) | dtype('S5') | elsize=5, shape=(n,)
875
+ * character(5) foo(n) | dtype('S1') | elsize=1, shape=(5, n)
876
+ * character*(*) foo | dtype('S') | elsize=-1, shape=()
877
+ *
878
+ * Note about reference counting
879
+ * -----------------------------
880
+ *
881
+ * If the caller returns the array to Python, it must be done with
882
+ * Py_BuildValue("N",arr). Otherwise, if obj!=arr then the caller
883
+ * must call Py_DECREF(arr).
884
+ *
885
+ * Note on intent(cache,out,..)
886
+ * ----------------------------
887
+ * Don't expect correct data when returning intent(cache) array.
888
+ *
889
+ */
890
+ char mess[F2PY_MESSAGE_BUFFER_SIZE];
891
+ PyArrayObject *arr = NULL;
892
+ int elsize = (elsize_ < 0 ? get_elsize(obj) : elsize_);
893
+ if (elsize < 0) {
894
+ if (errmess != NULL) {
895
+ strcpy(mess, errmess);
896
+ }
897
+ sprintf(mess + strlen(mess),
898
+ " -- failed to determine element size from %s",
899
+ Py_TYPE(obj)->tp_name);
900
+ PyErr_SetString(PyExc_SystemError, mess);
901
+ return NULL;
902
+ }
903
+ PyArray_Descr * descr = get_descr_from_type_and_elsize(type_num, elsize); // new reference
904
+ if (descr == NULL) {
905
+ return NULL;
906
+ }
907
+ elsize = descr->elsize;
908
+ if ((intent & F2PY_INTENT_HIDE)
909
+ || ((intent & F2PY_INTENT_CACHE) && (obj == Py_None))
910
+ || ((intent & F2PY_OPTIONAL) && (obj == Py_None))
911
+ ) {
912
+ /* intent(cache), optional, intent(hide) */
913
+ int ineg = find_first_negative_dimension(rank, dims);
914
+ if (ineg >= 0) {
915
+ int i;
916
+ strcpy(mess, "failed to create intent(cache|hide)|optional array"
917
+ "-- must have defined dimensions but got (");
918
+ for(i = 0; i < rank; ++i)
919
+ sprintf(mess + strlen(mess), "%" NPY_INTP_FMT ",", dims[i]);
920
+ strcat(mess, ")");
921
+ PyErr_SetString(PyExc_ValueError, mess);
922
+ Py_DECREF(descr);
923
+ return NULL;
924
+ }
925
+ arr = (PyArrayObject *) \
926
+ PyArray_NewFromDescr(&PyArray_Type, descr, rank, dims,
927
+ NULL, NULL, !(intent & F2PY_INTENT_C), NULL);
928
+ if (arr == NULL) {
929
+ Py_DECREF(descr);
930
+ return NULL;
931
+ }
932
+ if (PyArray_ITEMSIZE(arr) != elsize) {
933
+ strcpy(mess, "failed to create intent(cache|hide)|optional array");
934
+ sprintf(mess+strlen(mess)," -- expected elsize=%d got %" NPY_INTP_FMT, elsize, (npy_intp)PyArray_ITEMSIZE(arr));
935
+ PyErr_SetString(PyExc_ValueError,mess);
936
+ Py_DECREF(arr);
937
+ return NULL;
938
+ }
939
+ if (!(intent & F2PY_INTENT_CACHE)) {
940
+ PyArray_FILLWBYTE(arr, 0);
941
+ }
942
+ return arr;
943
+ }
944
+
945
+ if (PyArray_Check(obj)) {
946
+ arr = (PyArrayObject *)obj;
947
+ if (intent & F2PY_INTENT_CACHE) {
948
+ /* intent(cache) */
949
+ if (PyArray_ISONESEGMENT(arr)
950
+ && PyArray_ITEMSIZE(arr) >= elsize) {
951
+ if (check_and_fix_dimensions(arr, rank, dims, errmess)) {
952
+ Py_DECREF(descr);
953
+ return NULL;
954
+ }
955
+ if (intent & F2PY_INTENT_OUT)
956
+ Py_INCREF(arr);
957
+ Py_DECREF(descr);
958
+ return arr;
959
+ }
960
+ strcpy(mess, "failed to initialize intent(cache) array");
961
+ if (!PyArray_ISONESEGMENT(arr))
962
+ strcat(mess, " -- input must be in one segment");
963
+ if (PyArray_ITEMSIZE(arr) < elsize)
964
+ sprintf(mess + strlen(mess),
965
+ " -- expected at least elsize=%d but got "
966
+ "%" NPY_INTP_FMT,
967
+ elsize, (npy_intp)PyArray_ITEMSIZE(arr));
968
+ PyErr_SetString(PyExc_ValueError, mess);
969
+ Py_DECREF(descr);
970
+ return NULL;
971
+ }
972
+
973
+ /* here we have always intent(in) or intent(inout) or intent(inplace)
974
+ */
975
+
976
+ if (check_and_fix_dimensions(arr, rank, dims, errmess)) {
977
+ Py_DECREF(descr);
978
+ return NULL;
979
+ }
980
+ /*
981
+ printf("intent alignment=%d\n", F2PY_GET_ALIGNMENT(intent));
982
+ printf("alignment check=%d\n", F2PY_CHECK_ALIGNMENT(arr, intent));
983
+ int i;
984
+ for (i=1;i<=16;i++)
985
+ printf("i=%d isaligned=%d\n", i, ARRAY_ISALIGNED(arr, i));
986
+ */
987
+ if ((! (intent & F2PY_INTENT_COPY)) &&
988
+ PyArray_ITEMSIZE(arr) == elsize &&
989
+ ARRAY_ISCOMPATIBLE(arr,type_num) &&
990
+ F2PY_CHECK_ALIGNMENT(arr, intent)) {
991
+ if ((intent & F2PY_INTENT_INOUT || intent & F2PY_INTENT_INPLACE)
992
+ ? ((intent & F2PY_INTENT_C) ? PyArray_ISCARRAY(arr) : PyArray_ISFARRAY(arr))
993
+ : ((intent & F2PY_INTENT_C) ? PyArray_ISCARRAY_RO(arr) : PyArray_ISFARRAY_RO(arr))) {
994
+ if ((intent & F2PY_INTENT_OUT)) {
995
+ Py_INCREF(arr);
996
+ }
997
+ /* Returning input array */
998
+ Py_DECREF(descr);
999
+ return arr;
1000
+ }
1001
+ }
1002
+ if (intent & F2PY_INTENT_INOUT) {
1003
+ strcpy(mess, "failed to initialize intent(inout) array");
1004
+ /* Must use PyArray_IS*ARRAY because intent(inout) requires
1005
+ * writable input */
1006
+ if ((intent & F2PY_INTENT_C) && !PyArray_ISCARRAY(arr))
1007
+ strcat(mess, " -- input not contiguous");
1008
+ if (!(intent & F2PY_INTENT_C) && !PyArray_ISFARRAY(arr))
1009
+ strcat(mess, " -- input not fortran contiguous");
1010
+ if (PyArray_ITEMSIZE(arr) != elsize)
1011
+ sprintf(mess + strlen(mess),
1012
+ " -- expected elsize=%d but got %" NPY_INTP_FMT,
1013
+ elsize,
1014
+ (npy_intp)PyArray_ITEMSIZE(arr)
1015
+ );
1016
+ if (!(ARRAY_ISCOMPATIBLE(arr, type_num))) {
1017
+ sprintf(mess + strlen(mess),
1018
+ " -- input '%c' not compatible to '%c'",
1019
+ PyArray_DESCR(arr)->type, descr->type);
1020
+ }
1021
+ if (!(F2PY_CHECK_ALIGNMENT(arr, intent)))
1022
+ sprintf(mess + strlen(mess), " -- input not %d-aligned",
1023
+ F2PY_GET_ALIGNMENT(intent));
1024
+ PyErr_SetString(PyExc_ValueError, mess);
1025
+ Py_DECREF(descr);
1026
+ return NULL;
1027
+ }
1028
+
1029
+ /* here we have always intent(in) or intent(inplace) */
1030
+
1031
+ {
1032
+ PyArrayObject * retarr = (PyArrayObject *) \
1033
+ PyArray_NewFromDescr(&PyArray_Type, descr, PyArray_NDIM(arr), PyArray_DIMS(arr),
1034
+ NULL, NULL, !(intent & F2PY_INTENT_C), NULL);
1035
+ if (retarr==NULL) {
1036
+ Py_DECREF(descr);
1037
+ return NULL;
1038
+ }
1039
+ F2PY_REPORT_ON_ARRAY_COPY_FROMARR;
1040
+ if (PyArray_CopyInto(retarr, arr)) {
1041
+ Py_DECREF(retarr);
1042
+ return NULL;
1043
+ }
1044
+ if (intent & F2PY_INTENT_INPLACE) {
1045
+ if (swap_arrays(arr,retarr)) {
1046
+ Py_DECREF(retarr);
1047
+ return NULL; /* XXX: set exception */
1048
+ }
1049
+ Py_XDECREF(retarr);
1050
+ if (intent & F2PY_INTENT_OUT)
1051
+ Py_INCREF(arr);
1052
+ } else {
1053
+ arr = retarr;
1054
+ }
1055
+ }
1056
+ return arr;
1057
+ }
1058
+
1059
+ if ((intent & F2PY_INTENT_INOUT) || (intent & F2PY_INTENT_INPLACE) ||
1060
+ (intent & F2PY_INTENT_CACHE)) {
1061
+ PyErr_Format(PyExc_TypeError,
1062
+ "failed to initialize intent(inout|inplace|cache) "
1063
+ "array, input '%s' object is not an array",
1064
+ Py_TYPE(obj)->tp_name);
1065
+ Py_DECREF(descr);
1066
+ return NULL;
1067
+ }
1068
+
1069
+ {
1070
+ F2PY_REPORT_ON_ARRAY_COPY_FROMANY;
1071
+ arr = (PyArrayObject *)PyArray_FromAny(
1072
+ obj, descr, 0, 0,
1073
+ ((intent & F2PY_INTENT_C) ? NPY_ARRAY_CARRAY
1074
+ : NPY_ARRAY_FARRAY) |
1075
+ NPY_ARRAY_FORCECAST,
1076
+ NULL);
1077
+ // Warning: in the case of NPY_STRING, PyArray_FromAny may
1078
+ // reset descr->elsize, e.g. dtype('S0') becomes dtype('S1').
1079
+ if (arr == NULL) {
1080
+ Py_DECREF(descr);
1081
+ return NULL;
1082
+ }
1083
+ if (type_num != NPY_STRING && PyArray_ITEMSIZE(arr) != elsize) {
1084
+ // This is internal sanity tests: elsize has been set to
1085
+ // descr->elsize in the beginning of this function.
1086
+ strcpy(mess, "failed to initialize intent(in) array");
1087
+ sprintf(mess + strlen(mess),
1088
+ " -- expected elsize=%d got %" NPY_INTP_FMT, elsize,
1089
+ (npy_intp)PyArray_ITEMSIZE(arr));
1090
+ PyErr_SetString(PyExc_ValueError, mess);
1091
+ Py_DECREF(arr);
1092
+ return NULL;
1093
+ }
1094
+ if (check_and_fix_dimensions(arr, rank, dims, errmess)) {
1095
+ Py_DECREF(arr);
1096
+ return NULL;
1097
+ }
1098
+ return arr;
1099
+ }
1100
+ }
1101
+
1102
+ extern PyArrayObject *
1103
+ array_from_pyobj(const int type_num,
1104
+ npy_intp *dims,
1105
+ const int rank,
1106
+ const int intent,
1107
+ PyObject *obj) {
1108
+ /*
1109
+ Same as ndarray_from_pyobj but with elsize determined from type,
1110
+ if possible. Provided for backward compatibility.
1111
+ */
1112
+ PyArray_Descr* descr = PyArray_DescrFromType(type_num);
1113
+ int elsize = descr->elsize;
1114
+ Py_DECREF(descr);
1115
+ return ndarray_from_pyobj(type_num, elsize, dims, rank, intent, obj, NULL);
1116
+ }
1117
+
1118
+ /*****************************************/
1119
+ /* Helper functions for array_from_pyobj */
1120
+ /*****************************************/
1121
+
1122
+ static int
1123
+ check_and_fix_dimensions(const PyArrayObject* arr, const int rank,
1124
+ npy_intp *dims, const char *errmess)
1125
+ {
1126
+ /*
1127
+ * This function fills in blanks (that are -1's) in dims list using
1128
+ * the dimensions from arr. It also checks that non-blank dims will
1129
+ * match with the corresponding values in arr dimensions.
1130
+ *
1131
+ * Returns 0 if the function is successful.
1132
+ *
1133
+ * If an error condition is detected, an exception is set and 1 is
1134
+ * returned.
1135
+ */
1136
+ char mess[F2PY_MESSAGE_BUFFER_SIZE];
1137
+ const npy_intp arr_size =
1138
+ (PyArray_NDIM(arr)) ? PyArray_Size((PyObject *)arr) : 1;
1139
+ #ifdef DEBUG_COPY_ND_ARRAY
1140
+ dump_attrs(arr);
1141
+ printf("check_and_fix_dimensions:init: dims=");
1142
+ dump_dims(rank, dims);
1143
+ #endif
1144
+ if (rank > PyArray_NDIM(arr)) { /* [1,2] -> [[1],[2]]; 1 -> [[1]] */
1145
+ npy_intp new_size = 1;
1146
+ int free_axe = -1;
1147
+ int i;
1148
+ npy_intp d;
1149
+ /* Fill dims where -1 or 0; check dimensions; calc new_size; */
1150
+ for (i = 0; i < PyArray_NDIM(arr); ++i) {
1151
+ d = PyArray_DIM(arr, i);
1152
+ if (dims[i] >= 0) {
1153
+ if (d > 1 && dims[i] != d) {
1154
+ PyErr_Format(
1155
+ PyExc_ValueError,
1156
+ "%d-th dimension must be fixed to %" NPY_INTP_FMT
1157
+ " but got %" NPY_INTP_FMT "\n",
1158
+ i, dims[i], d);
1159
+ return 1;
1160
+ }
1161
+ if (!dims[i])
1162
+ dims[i] = 1;
1163
+ }
1164
+ else {
1165
+ dims[i] = d ? d : 1;
1166
+ }
1167
+ new_size *= dims[i];
1168
+ }
1169
+ for (i = PyArray_NDIM(arr); i < rank; ++i)
1170
+ if (dims[i] > 1) {
1171
+ PyErr_Format(PyExc_ValueError,
1172
+ "%d-th dimension must be %" NPY_INTP_FMT
1173
+ " but got 0 (not defined).\n",
1174
+ i, dims[i]);
1175
+ return 1;
1176
+ }
1177
+ else if (free_axe < 0)
1178
+ free_axe = i;
1179
+ else
1180
+ dims[i] = 1;
1181
+ if (free_axe >= 0) {
1182
+ dims[free_axe] = arr_size / new_size;
1183
+ new_size *= dims[free_axe];
1184
+ }
1185
+ if (new_size != arr_size) {
1186
+ PyErr_Format(PyExc_ValueError,
1187
+ "unexpected array size: new_size=%" NPY_INTP_FMT
1188
+ ", got array with arr_size=%" NPY_INTP_FMT
1189
+ " (maybe too many free indices)\n",
1190
+ new_size, arr_size);
1191
+ return 1;
1192
+ }
1193
+ }
1194
+ else if (rank == PyArray_NDIM(arr)) {
1195
+ npy_intp new_size = 1;
1196
+ int i;
1197
+ npy_intp d;
1198
+ for (i = 0; i < rank; ++i) {
1199
+ d = PyArray_DIM(arr, i);
1200
+ if (dims[i] >= 0) {
1201
+ if (d > 1 && d != dims[i]) {
1202
+ if (errmess != NULL) {
1203
+ strcpy(mess, errmess);
1204
+ }
1205
+ sprintf(mess + strlen(mess),
1206
+ " -- %d-th dimension must be fixed to %"
1207
+ NPY_INTP_FMT " but got %" NPY_INTP_FMT,
1208
+ i, dims[i], d);
1209
+ PyErr_SetString(PyExc_ValueError, mess);
1210
+ return 1;
1211
+ }
1212
+ if (!dims[i])
1213
+ dims[i] = 1;
1214
+ }
1215
+ else
1216
+ dims[i] = d;
1217
+ new_size *= dims[i];
1218
+ }
1219
+ if (new_size != arr_size) {
1220
+ PyErr_Format(PyExc_ValueError,
1221
+ "unexpected array size: new_size=%" NPY_INTP_FMT
1222
+ ", got array with arr_size=%" NPY_INTP_FMT "\n",
1223
+ new_size, arr_size);
1224
+ return 1;
1225
+ }
1226
+ }
1227
+ else { /* [[1,2]] -> [[1],[2]] */
1228
+ int i, j;
1229
+ npy_intp d;
1230
+ int effrank;
1231
+ npy_intp size;
1232
+ for (i = 0, effrank = 0; i < PyArray_NDIM(arr); ++i)
1233
+ if (PyArray_DIM(arr, i) > 1)
1234
+ ++effrank;
1235
+ if (dims[rank - 1] >= 0)
1236
+ if (effrank > rank) {
1237
+ PyErr_Format(PyExc_ValueError,
1238
+ "too many axes: %d (effrank=%d), "
1239
+ "expected rank=%d\n",
1240
+ PyArray_NDIM(arr), effrank, rank);
1241
+ return 1;
1242
+ }
1243
+
1244
+ for (i = 0, j = 0; i < rank; ++i) {
1245
+ while (j < PyArray_NDIM(arr) && PyArray_DIM(arr, j) < 2) ++j;
1246
+ if (j >= PyArray_NDIM(arr))
1247
+ d = 1;
1248
+ else
1249
+ d = PyArray_DIM(arr, j++);
1250
+ if (dims[i] >= 0) {
1251
+ if (d > 1 && d != dims[i]) {
1252
+ if (errmess != NULL) {
1253
+ strcpy(mess, errmess);
1254
+ }
1255
+ sprintf(mess + strlen(mess),
1256
+ " -- %d-th dimension must be fixed to %"
1257
+ NPY_INTP_FMT " but got %" NPY_INTP_FMT
1258
+ " (real index=%d)\n",
1259
+ i, dims[i], d, j-1);
1260
+ PyErr_SetString(PyExc_ValueError, mess);
1261
+ return 1;
1262
+ }
1263
+ if (!dims[i])
1264
+ dims[i] = 1;
1265
+ }
1266
+ else
1267
+ dims[i] = d;
1268
+ }
1269
+
1270
+ for (i = rank; i < PyArray_NDIM(arr);
1271
+ ++i) { /* [[1,2],[3,4]] -> [1,2,3,4] */
1272
+ while (j < PyArray_NDIM(arr) && PyArray_DIM(arr, j) < 2) ++j;
1273
+ if (j >= PyArray_NDIM(arr))
1274
+ d = 1;
1275
+ else
1276
+ d = PyArray_DIM(arr, j++);
1277
+ dims[rank - 1] *= d;
1278
+ }
1279
+ for (i = 0, size = 1; i < rank; ++i) size *= dims[i];
1280
+ if (size != arr_size) {
1281
+ char msg[200];
1282
+ int len;
1283
+ snprintf(msg, sizeof(msg),
1284
+ "unexpected array size: size=%" NPY_INTP_FMT
1285
+ ", arr_size=%" NPY_INTP_FMT
1286
+ ", rank=%d, effrank=%d, arr.nd=%d, dims=[",
1287
+ size, arr_size, rank, effrank, PyArray_NDIM(arr));
1288
+ for (i = 0; i < rank; ++i) {
1289
+ len = strlen(msg);
1290
+ snprintf(msg + len, sizeof(msg) - len, " %" NPY_INTP_FMT,
1291
+ dims[i]);
1292
+ }
1293
+ len = strlen(msg);
1294
+ snprintf(msg + len, sizeof(msg) - len, " ], arr.dims=[");
1295
+ for (i = 0; i < PyArray_NDIM(arr); ++i) {
1296
+ len = strlen(msg);
1297
+ snprintf(msg + len, sizeof(msg) - len, " %" NPY_INTP_FMT,
1298
+ PyArray_DIM(arr, i));
1299
+ }
1300
+ len = strlen(msg);
1301
+ snprintf(msg + len, sizeof(msg) - len, " ]\n");
1302
+ PyErr_SetString(PyExc_ValueError, msg);
1303
+ return 1;
1304
+ }
1305
+ }
1306
+ #ifdef DEBUG_COPY_ND_ARRAY
1307
+ printf("check_and_fix_dimensions:end: dims=");
1308
+ dump_dims(rank, dims);
1309
+ #endif
1310
+ return 0;
1311
+ }
1312
+
1313
+ /* End of file: array_from_pyobj.c */
1314
+
1315
+ /************************* copy_ND_array *******************************/
1316
+
1317
+ extern int
1318
+ copy_ND_array(const PyArrayObject *arr, PyArrayObject *out)
1319
+ {
1320
+ F2PY_REPORT_ON_ARRAY_COPY_FROMARR;
1321
+ return PyArray_CopyInto(out, (PyArrayObject *)arr);
1322
+ }
1323
+
1324
+ /********************* Various utility functions ***********************/
1325
+
1326
+ extern int
1327
+ f2py_describe(PyObject *obj, char *buf) {
1328
+ /*
1329
+ Write the description of a Python object to buf. The caller must
1330
+ provide buffer with size sufficient to write the description.
1331
+
1332
+ Return 1 on success.
1333
+ */
1334
+ char localbuf[F2PY_MESSAGE_BUFFER_SIZE];
1335
+ if (PyBytes_Check(obj)) {
1336
+ sprintf(localbuf, "%d-%s", (npy_int)PyBytes_GET_SIZE(obj), Py_TYPE(obj)->tp_name);
1337
+ } else if (PyUnicode_Check(obj)) {
1338
+ sprintf(localbuf, "%d-%s", (npy_int)PyUnicode_GET_LENGTH(obj), Py_TYPE(obj)->tp_name);
1339
+ } else if (PyArray_CheckScalar(obj)) {
1340
+ PyArrayObject* arr = (PyArrayObject*)obj;
1341
+ sprintf(localbuf, "%c%" NPY_INTP_FMT "-%s-scalar", PyArray_DESCR(arr)->kind, PyArray_ITEMSIZE(arr), Py_TYPE(obj)->tp_name);
1342
+ } else if (PyArray_Check(obj)) {
1343
+ int i;
1344
+ PyArrayObject* arr = (PyArrayObject*)obj;
1345
+ strcpy(localbuf, "(");
1346
+ for (i=0; i<PyArray_NDIM(arr); i++) {
1347
+ if (i) {
1348
+ strcat(localbuf, " ");
1349
+ }
1350
+ sprintf(localbuf + strlen(localbuf), "%" NPY_INTP_FMT ",", PyArray_DIM(arr, i));
1351
+ }
1352
+ sprintf(localbuf + strlen(localbuf), ")-%c%" NPY_INTP_FMT "-%s", PyArray_DESCR(arr)->kind, PyArray_ITEMSIZE(arr), Py_TYPE(obj)->tp_name);
1353
+ } else if (PySequence_Check(obj)) {
1354
+ sprintf(localbuf, "%d-%s", (npy_int)PySequence_Length(obj), Py_TYPE(obj)->tp_name);
1355
+ } else {
1356
+ sprintf(localbuf, "%s instance", Py_TYPE(obj)->tp_name);
1357
+ }
1358
+ // TODO: detect the size of buf and make sure that size(buf) >= size(localbuf).
1359
+ strcpy(buf, localbuf);
1360
+ return 1;
1361
+ }
1362
+
1363
+ extern npy_intp
1364
+ f2py_size_impl(PyArrayObject* var, ...)
1365
+ {
1366
+ npy_intp sz = 0;
1367
+ npy_intp dim;
1368
+ npy_intp rank;
1369
+ va_list argp;
1370
+ va_start(argp, var);
1371
+ dim = va_arg(argp, npy_int);
1372
+ if (dim==-1)
1373
+ {
1374
+ sz = PyArray_SIZE(var);
1375
+ }
1376
+ else
1377
+ {
1378
+ rank = PyArray_NDIM(var);
1379
+ if (dim>=1 && dim<=rank)
1380
+ sz = PyArray_DIM(var, dim-1);
1381
+ else
1382
+ fprintf(stderr, "f2py_size: 2nd argument value=%" NPY_INTP_FMT
1383
+ " fails to satisfy 1<=value<=%" NPY_INTP_FMT
1384
+ ". Result will be 0.\n", dim, rank);
1385
+ }
1386
+ va_end(argp);
1387
+ return sz;
1388
+ }
1389
+
1390
+ /*********************************************/
1391
+ /* Compatibility functions for Python >= 3.0 */
1392
+ /*********************************************/
1393
+
1394
+ PyObject *
1395
+ F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *))
1396
+ {
1397
+ PyObject *ret = PyCapsule_New(ptr, NULL, dtor);
1398
+ if (ret == NULL) {
1399
+ PyErr_Clear();
1400
+ }
1401
+ return ret;
1402
+ }
1403
+
1404
+ void *
1405
+ F2PyCapsule_AsVoidPtr(PyObject *obj)
1406
+ {
1407
+ void *ret = PyCapsule_GetPointer(obj, NULL);
1408
+ if (ret == NULL) {
1409
+ PyErr_Clear();
1410
+ }
1411
+ return ret;
1412
+ }
1413
+
1414
+ int
1415
+ F2PyCapsule_Check(PyObject *ptr)
1416
+ {
1417
+ return PyCapsule_CheckExact(ptr);
1418
+ }
1419
+
1420
+ #ifdef __cplusplus
1421
+ }
1422
+ #endif
1423
+ /************************* EOF fortranobject.c *******************************/
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.h ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef Py_FORTRANOBJECT_H
2
+ #define Py_FORTRANOBJECT_H
3
+ #ifdef __cplusplus
4
+ extern "C" {
5
+ #endif
6
+
7
+ #include <Python.h>
8
+
9
+ #ifndef NPY_NO_DEPRECATED_API
10
+ #define NPY_NO_DEPRECATED_API NPY_API_VERSION
11
+ #endif
12
+ #ifdef FORTRANOBJECT_C
13
+ #define NO_IMPORT_ARRAY
14
+ #endif
15
+ #define PY_ARRAY_UNIQUE_SYMBOL _npy_f2py_ARRAY_API
16
+ #include "numpy/arrayobject.h"
17
+ #include "numpy/npy_3kcompat.h"
18
+
19
+ #ifdef F2PY_REPORT_ATEXIT
20
+ #include <sys/timeb.h>
21
+ // clang-format off
22
+ extern void f2py_start_clock(void);
23
+ extern void f2py_stop_clock(void);
24
+ extern void f2py_start_call_clock(void);
25
+ extern void f2py_stop_call_clock(void);
26
+ extern void f2py_cb_start_clock(void);
27
+ extern void f2py_cb_stop_clock(void);
28
+ extern void f2py_cb_start_call_clock(void);
29
+ extern void f2py_cb_stop_call_clock(void);
30
+ extern void f2py_report_on_exit(int, void *);
31
+ // clang-format on
32
+ #endif
33
+
34
+ #ifdef DMALLOC
35
+ #include "dmalloc.h"
36
+ #endif
37
+
38
+ /* Fortran object interface */
39
+
40
+ /*
41
+ 123456789-123456789-123456789-123456789-123456789-123456789-123456789-12
42
+
43
+ PyFortranObject represents various Fortran objects:
44
+ Fortran (module) routines, COMMON blocks, module data.
45
+
46
+ Author: Pearu Peterson <pearu@cens.ioc.ee>
47
+ */
48
+
49
+ #define F2PY_MAX_DIMS 40
50
+ #define F2PY_MESSAGE_BUFFER_SIZE 300 // Increase on "stack smashing detected"
51
+
52
+ typedef void (*f2py_set_data_func)(char *, npy_intp *);
53
+ typedef void (*f2py_void_func)(void);
54
+ typedef void (*f2py_init_func)(int *, npy_intp *, f2py_set_data_func, int *);
55
+
56
+ /*typedef void* (*f2py_c_func)(void*,...);*/
57
+
58
+ typedef void *(*f2pycfunc)(void);
59
+
60
+ typedef struct {
61
+ char *name; /* attribute (array||routine) name */
62
+ int rank; /* array rank, 0 for scalar, max is F2PY_MAX_DIMS,
63
+ || rank=-1 for Fortran routine */
64
+ struct {
65
+ npy_intp d[F2PY_MAX_DIMS];
66
+ } dims; /* dimensions of the array, || not used */
67
+ int type; /* PyArray_<type> || not used */
68
+ int elsize; /* Element size || not used */
69
+ char *data; /* pointer to array || Fortran routine */
70
+ f2py_init_func func; /* initialization function for
71
+ allocatable arrays:
72
+ func(&rank,dims,set_ptr_func,name,len(name))
73
+ || C/API wrapper for Fortran routine */
74
+ char *doc; /* documentation string; only recommended
75
+ for routines. */
76
+ } FortranDataDef;
77
+
78
+ typedef struct {
79
+ PyObject_HEAD
80
+ int len; /* Number of attributes */
81
+ FortranDataDef *defs; /* An array of FortranDataDef's */
82
+ PyObject *dict; /* Fortran object attribute dictionary */
83
+ } PyFortranObject;
84
+
85
+ #define PyFortran_Check(op) (Py_TYPE(op) == &PyFortran_Type)
86
+ #define PyFortran_Check1(op) (0 == strcmp(Py_TYPE(op)->tp_name, "fortran"))
87
+
88
+ extern PyTypeObject PyFortran_Type;
89
+ extern int
90
+ F2PyDict_SetItemString(PyObject *dict, char *name, PyObject *obj);
91
+ extern PyObject *
92
+ PyFortranObject_New(FortranDataDef *defs, f2py_void_func init);
93
+ extern PyObject *
94
+ PyFortranObject_NewAsAttr(FortranDataDef *defs);
95
+
96
+ PyObject *
97
+ F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *));
98
+ void *
99
+ F2PyCapsule_AsVoidPtr(PyObject *obj);
100
+ int
101
+ F2PyCapsule_Check(PyObject *ptr);
102
+
103
+ extern void *
104
+ F2PySwapThreadLocalCallbackPtr(char *key, void *ptr);
105
+ extern void *
106
+ F2PyGetThreadLocalCallbackPtr(char *key);
107
+
108
+ #define ISCONTIGUOUS(m) (PyArray_FLAGS(m) & NPY_ARRAY_C_CONTIGUOUS)
109
+ #define F2PY_INTENT_IN 1
110
+ #define F2PY_INTENT_INOUT 2
111
+ #define F2PY_INTENT_OUT 4
112
+ #define F2PY_INTENT_HIDE 8
113
+ #define F2PY_INTENT_CACHE 16
114
+ #define F2PY_INTENT_COPY 32
115
+ #define F2PY_INTENT_C 64
116
+ #define F2PY_OPTIONAL 128
117
+ #define F2PY_INTENT_INPLACE 256
118
+ #define F2PY_INTENT_ALIGNED4 512
119
+ #define F2PY_INTENT_ALIGNED8 1024
120
+ #define F2PY_INTENT_ALIGNED16 2048
121
+
122
+ #define ARRAY_ISALIGNED(ARR, SIZE) ((size_t)(PyArray_DATA(ARR)) % (SIZE) == 0)
123
+ #define F2PY_ALIGN4(intent) (intent & F2PY_INTENT_ALIGNED4)
124
+ #define F2PY_ALIGN8(intent) (intent & F2PY_INTENT_ALIGNED8)
125
+ #define F2PY_ALIGN16(intent) (intent & F2PY_INTENT_ALIGNED16)
126
+
127
+ #define F2PY_GET_ALIGNMENT(intent) \
128
+ (F2PY_ALIGN4(intent) \
129
+ ? 4 \
130
+ : (F2PY_ALIGN8(intent) ? 8 : (F2PY_ALIGN16(intent) ? 16 : 1)))
131
+ #define F2PY_CHECK_ALIGNMENT(arr, intent) \
132
+ ARRAY_ISALIGNED(arr, F2PY_GET_ALIGNMENT(intent))
133
+ #define F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr) ((PyArray_DESCR(arr)->type_num == NPY_STRING && PyArray_DESCR(arr)->elsize >= 1) \
134
+ || PyArray_DESCR(arr)->type_num == NPY_UINT8)
135
+ #define F2PY_IS_UNICODE_ARRAY(arr) (PyArray_DESCR(arr)->type_num == NPY_UNICODE)
136
+
137
+ extern PyArrayObject *
138
+ ndarray_from_pyobj(const int type_num, const int elsize_, npy_intp *dims,
139
+ const int rank, const int intent, PyObject *obj,
140
+ const char *errmess);
141
+
142
+ extern PyArrayObject *
143
+ array_from_pyobj(const int type_num, npy_intp *dims, const int rank,
144
+ const int intent, PyObject *obj);
145
+ extern int
146
+ copy_ND_array(const PyArrayObject *in, PyArrayObject *out);
147
+
148
+ #ifdef DEBUG_COPY_ND_ARRAY
149
+ extern void
150
+ dump_attrs(const PyArrayObject *arr);
151
+ #endif
152
+
153
+ extern int f2py_describe(PyObject *obj, char *buf);
154
+
155
+ /* Utility CPP macros and functions that can be used in signature file
156
+ expressions. See signature-file.rst for documentation.
157
+ */
158
+
159
+ #define f2py_itemsize(var) (PyArray_DESCR((capi_ ## var ## _as_array))->elsize)
160
+ #define f2py_size(var, ...) f2py_size_impl((PyArrayObject *)(capi_ ## var ## _as_array), ## __VA_ARGS__, -1)
161
+ #define f2py_rank(var) var ## _Rank
162
+ #define f2py_shape(var,dim) var ## _Dims[dim]
163
+ #define f2py_len(var) f2py_shape(var,0)
164
+ #define f2py_fshape(var,dim) f2py_shape(var,rank(var)-dim-1)
165
+ #define f2py_flen(var) f2py_fshape(var,0)
166
+ #define f2py_slen(var) capi_ ## var ## _len
167
+
168
+ extern npy_intp f2py_size_impl(PyArrayObject* var, ...);
169
+
170
+ #ifdef __cplusplus
171
+ }
172
+ #endif
173
+ #endif /* !Py_FORTRANOBJECT_H */
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__init__.py ADDED
File without changes
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (190 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_abstract_interface.cpython-310.pyc ADDED
Binary file (1.39 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_array_from_pyobj.cpython-310.pyc ADDED
Binary file (20.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_common.cpython-310.pyc ADDED
Binary file (1.41 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_compile_function.cpython-310.pyc ADDED
Binary file (2.42 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_f2py2e.cpython-310.pyc ADDED
Binary file (23.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_isoc.cpython-310.pyc ADDED
Binary file (1.83 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_kind.cpython-310.pyc ADDED
Binary file (1.85 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_module_doc.cpython-310.pyc ADDED
Binary file (1.28 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_parameter.cpython-310.pyc ADDED
Binary file (2.92 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_quoted_character.cpython-310.pyc ADDED
Binary file (940 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_return_complex.cpython-310.pyc ADDED
Binary file (2.46 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_return_logical.cpython-310.pyc ADDED
Binary file (2.43 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_semicolon_split.cpython-310.pyc ADDED
Binary file (1.98 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_string.cpython-310.pyc ADDED
Binary file (3.36 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_symbolic.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_value_attrspec.cpython-310.pyc ADDED
Binary file (763 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/test_abstract_interface.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import pytest
3
+ import textwrap
4
+ from . import util
5
+ from numpy.f2py import crackfortran
6
+ from numpy.testing import IS_WASM
7
+
8
+
9
+ @pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
10
+ class TestAbstractInterface(util.F2PyTest):
11
+ sources = [util.getpath("tests", "src", "abstract_interface", "foo.f90")]
12
+
13
+ skip = ["add1", "add2"]
14
+
15
+ def test_abstract_interface(self):
16
+ assert self.module.ops_module.foo(3, 5) == (8, 13)
17
+
18
+ def test_parse_abstract_interface(self):
19
+ # Test gh18403
20
+ fpath = util.getpath("tests", "src", "abstract_interface",
21
+ "gh18403_mod.f90")
22
+ mod = crackfortran.crackfortran([str(fpath)])
23
+ assert len(mod) == 1
24
+ assert len(mod[0]["body"]) == 1
25
+ assert mod[0]["body"][0]["block"] == "abstract interface"
data/tefig/envs/olmes-eval/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!
data/tefig/envs/olmes-eval/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)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/test_block_docstring.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import pytest
3
+ from . import util
4
+
5
+ from numpy.testing import IS_PYPY
6
+
7
+
8
+ class TestBlockDocString(util.F2PyTest):
9
+ sources = [util.getpath("tests", "src", "block_docstring", "foo.f")]
10
+
11
+ @pytest.mark.skipif(sys.platform == "win32",
12
+ reason="Fails with MinGW64 Gfortran (Issue #9673)")
13
+ @pytest.mark.xfail(IS_PYPY,
14
+ reason="PyPy cannot modify tp_doc after PyType_Ready")
15
+ def test_block_docstring(self):
16
+ expected = "bar : 'i'-array(2,3)\n"
17
+ assert self.module.block.__doc__ == expected
data/tefig/envs/olmes-eval/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
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/numpy/f2py/tests/test_character.py ADDED
@@ -0,0 +1,636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import textwrap
3
+ from numpy.testing import assert_array_equal, assert_equal, assert_raises
4
+ import numpy as np
5
+ from numpy.f2py.tests import util
6
+
7
+
8
+ class TestCharacterString(util.F2PyTest):
9
+ # options = ['--debug-capi', '--build-dir', '/tmp/test-build-f2py']
10
+ suffix = '.f90'
11
+ fprefix = 'test_character_string'
12
+ length_list = ['1', '3', 'star']
13
+
14
+ code = ''
15
+ for length in length_list:
16
+ fsuffix = length
17
+ clength = dict(star='(*)').get(length, length)
18
+
19
+ code += textwrap.dedent(f"""
20
+
21
+ subroutine {fprefix}_input_{fsuffix}(c, o, n)
22
+ character*{clength}, intent(in) :: c
23
+ integer n
24
+ !f2py integer, depend(c), intent(hide) :: n = slen(c)
25
+ integer*1, dimension(n) :: o
26
+ !f2py intent(out) o
27
+ o = transfer(c, o)
28
+ end subroutine {fprefix}_input_{fsuffix}
29
+
30
+ subroutine {fprefix}_output_{fsuffix}(c, o, n)
31
+ character*{clength}, intent(out) :: c
32
+ integer n
33
+ integer*1, dimension(n), intent(in) :: o
34
+ !f2py integer, depend(o), intent(hide) :: n = len(o)
35
+ c = transfer(o, c)
36
+ end subroutine {fprefix}_output_{fsuffix}
37
+
38
+ subroutine {fprefix}_array_input_{fsuffix}(c, o, m, n)
39
+ integer m, i, n
40
+ character*{clength}, intent(in), dimension(m) :: c
41
+ !f2py integer, depend(c), intent(hide) :: m = len(c)
42
+ !f2py integer, depend(c), intent(hide) :: n = f2py_itemsize(c)
43
+ integer*1, dimension(m, n), intent(out) :: o
44
+ do i=1,m
45
+ o(i, :) = transfer(c(i), o(i, :))
46
+ end do
47
+ end subroutine {fprefix}_array_input_{fsuffix}
48
+
49
+ subroutine {fprefix}_array_output_{fsuffix}(c, o, m, n)
50
+ character*{clength}, intent(out), dimension(m) :: c
51
+ integer n
52
+ integer*1, dimension(m, n), intent(in) :: o
53
+ !f2py character(f2py_len=n) :: c
54
+ !f2py integer, depend(o), intent(hide) :: m = len(o)
55
+ !f2py integer, depend(o), intent(hide) :: n = shape(o, 1)
56
+ do i=1,m
57
+ c(i) = transfer(o(i, :), c(i))
58
+ end do
59
+ end subroutine {fprefix}_array_output_{fsuffix}
60
+
61
+ subroutine {fprefix}_2d_array_input_{fsuffix}(c, o, m1, m2, n)
62
+ integer m1, m2, i, j, n
63
+ character*{clength}, intent(in), dimension(m1, m2) :: c
64
+ !f2py integer, depend(c), intent(hide) :: m1 = len(c)
65
+ !f2py integer, depend(c), intent(hide) :: m2 = shape(c, 1)
66
+ !f2py integer, depend(c), intent(hide) :: n = f2py_itemsize(c)
67
+ integer*1, dimension(m1, m2, n), intent(out) :: o
68
+ do i=1,m1
69
+ do j=1,m2
70
+ o(i, j, :) = transfer(c(i, j), o(i, j, :))
71
+ end do
72
+ end do
73
+ end subroutine {fprefix}_2d_array_input_{fsuffix}
74
+ """)
75
+
76
+ @pytest.mark.parametrize("length", length_list)
77
+ def test_input(self, length):
78
+ fsuffix = {'(*)': 'star'}.get(length, length)
79
+ f = getattr(self.module, self.fprefix + '_input_' + fsuffix)
80
+
81
+ a = {'1': 'a', '3': 'abc', 'star': 'abcde' * 3}[length]
82
+
83
+ assert_array_equal(f(a), np.array(list(map(ord, a)), dtype='u1'))
84
+
85
+ @pytest.mark.parametrize("length", length_list[:-1])
86
+ def test_output(self, length):
87
+ fsuffix = length
88
+ f = getattr(self.module, self.fprefix + '_output_' + fsuffix)
89
+
90
+ a = {'1': 'a', '3': 'abc'}[length]
91
+
92
+ assert_array_equal(f(np.array(list(map(ord, a)), dtype='u1')),
93
+ a.encode())
94
+
95
+ @pytest.mark.parametrize("length", length_list)
96
+ def test_array_input(self, length):
97
+ fsuffix = length
98
+ f = getattr(self.module, self.fprefix + '_array_input_' + fsuffix)
99
+
100
+ a = np.array([{'1': 'a', '3': 'abc', 'star': 'abcde' * 3}[length],
101
+ {'1': 'A', '3': 'ABC', 'star': 'ABCDE' * 3}[length],
102
+ ], dtype='S')
103
+
104
+ expected = np.array([[c for c in s] for s in a], dtype='u1')
105
+ assert_array_equal(f(a), expected)
106
+
107
+ @pytest.mark.parametrize("length", length_list)
108
+ def test_array_output(self, length):
109
+ fsuffix = length
110
+ f = getattr(self.module, self.fprefix + '_array_output_' + fsuffix)
111
+
112
+ expected = np.array(
113
+ [{'1': 'a', '3': 'abc', 'star': 'abcde' * 3}[length],
114
+ {'1': 'A', '3': 'ABC', 'star': 'ABCDE' * 3}[length]], dtype='S')
115
+
116
+ a = np.array([[c for c in s] for s in expected], dtype='u1')
117
+ assert_array_equal(f(a), expected)
118
+
119
+ @pytest.mark.parametrize("length", length_list)
120
+ def test_2d_array_input(self, length):
121
+ fsuffix = length
122
+ f = getattr(self.module, self.fprefix + '_2d_array_input_' + fsuffix)
123
+
124
+ a = np.array([[{'1': 'a', '3': 'abc', 'star': 'abcde' * 3}[length],
125
+ {'1': 'A', '3': 'ABC', 'star': 'ABCDE' * 3}[length]],
126
+ [{'1': 'f', '3': 'fgh', 'star': 'fghij' * 3}[length],
127
+ {'1': 'F', '3': 'FGH', 'star': 'FGHIJ' * 3}[length]]],
128
+ dtype='S')
129
+ expected = np.array([[[c for c in item] for item in row] for row in a],
130
+ dtype='u1', order='F')
131
+ assert_array_equal(f(a), expected)
132
+
133
+
134
+ class TestCharacter(util.F2PyTest):
135
+ # options = ['--debug-capi', '--build-dir', '/tmp/test-build-f2py']
136
+ suffix = '.f90'
137
+ fprefix = 'test_character'
138
+
139
+ code = textwrap.dedent(f"""
140
+ subroutine {fprefix}_input(c, o)
141
+ character, intent(in) :: c
142
+ integer*1 o
143
+ !f2py intent(out) o
144
+ o = transfer(c, o)
145
+ end subroutine {fprefix}_input
146
+
147
+ subroutine {fprefix}_output(c, o)
148
+ character :: c
149
+ integer*1, intent(in) :: o
150
+ !f2py intent(out) c
151
+ c = transfer(o, c)
152
+ end subroutine {fprefix}_output
153
+
154
+ subroutine {fprefix}_input_output(c, o)
155
+ character, intent(in) :: c
156
+ character o
157
+ !f2py intent(out) o
158
+ o = c
159
+ end subroutine {fprefix}_input_output
160
+
161
+ subroutine {fprefix}_inout(c, n)
162
+ character :: c, n
163
+ !f2py intent(in) n
164
+ !f2py intent(inout) c
165
+ c = n
166
+ end subroutine {fprefix}_inout
167
+
168
+ function {fprefix}_return(o) result (c)
169
+ character :: c
170
+ character, intent(in) :: o
171
+ c = transfer(o, c)
172
+ end function {fprefix}_return
173
+
174
+ subroutine {fprefix}_array_input(c, o)
175
+ character, intent(in) :: c(3)
176
+ integer*1 o(3)
177
+ !f2py intent(out) o
178
+ integer i
179
+ do i=1,3
180
+ o(i) = transfer(c(i), o(i))
181
+ end do
182
+ end subroutine {fprefix}_array_input
183
+
184
+ subroutine {fprefix}_2d_array_input(c, o)
185
+ character, intent(in) :: c(2, 3)
186
+ integer*1 o(2, 3)
187
+ !f2py intent(out) o
188
+ integer i, j
189
+ do i=1,2
190
+ do j=1,3
191
+ o(i, j) = transfer(c(i, j), o(i, j))
192
+ end do
193
+ end do
194
+ end subroutine {fprefix}_2d_array_input
195
+
196
+ subroutine {fprefix}_array_output(c, o)
197
+ character :: c(3)
198
+ integer*1, intent(in) :: o(3)
199
+ !f2py intent(out) c
200
+ do i=1,3
201
+ c(i) = transfer(o(i), c(i))
202
+ end do
203
+ end subroutine {fprefix}_array_output
204
+
205
+ subroutine {fprefix}_array_inout(c, n)
206
+ character :: c(3), n(3)
207
+ !f2py intent(in) n(3)
208
+ !f2py intent(inout) c(3)
209
+ do i=1,3
210
+ c(i) = n(i)
211
+ end do
212
+ end subroutine {fprefix}_array_inout
213
+
214
+ subroutine {fprefix}_2d_array_inout(c, n)
215
+ character :: c(2, 3), n(2, 3)
216
+ !f2py intent(in) n(2, 3)
217
+ !f2py intent(inout) c(2. 3)
218
+ integer i, j
219
+ do i=1,2
220
+ do j=1,3
221
+ c(i, j) = n(i, j)
222
+ end do
223
+ end do
224
+ end subroutine {fprefix}_2d_array_inout
225
+
226
+ function {fprefix}_array_return(o) result (c)
227
+ character, dimension(3) :: c
228
+ character, intent(in) :: o(3)
229
+ do i=1,3
230
+ c(i) = o(i)
231
+ end do
232
+ end function {fprefix}_array_return
233
+
234
+ function {fprefix}_optional(o) result (c)
235
+ character, intent(in) :: o
236
+ !f2py character o = "a"
237
+ character :: c
238
+ c = o
239
+ end function {fprefix}_optional
240
+ """)
241
+
242
+ @pytest.mark.parametrize("dtype", ['c', 'S1'])
243
+ def test_input(self, dtype):
244
+ f = getattr(self.module, self.fprefix + '_input')
245
+
246
+ assert_equal(f(np.array('a', dtype=dtype)), ord('a'))
247
+ assert_equal(f(np.array(b'a', dtype=dtype)), ord('a'))
248
+ assert_equal(f(np.array(['a'], dtype=dtype)), ord('a'))
249
+ assert_equal(f(np.array('abc', dtype=dtype)), ord('a'))
250
+ assert_equal(f(np.array([['a']], dtype=dtype)), ord('a'))
251
+
252
+ def test_input_varia(self):
253
+ f = getattr(self.module, self.fprefix + '_input')
254
+
255
+ assert_equal(f('a'), ord('a'))
256
+ assert_equal(f(b'a'), ord(b'a'))
257
+ assert_equal(f(''), 0)
258
+ assert_equal(f(b''), 0)
259
+ assert_equal(f(b'\0'), 0)
260
+ assert_equal(f('ab'), ord('a'))
261
+ assert_equal(f(b'ab'), ord('a'))
262
+ assert_equal(f(['a']), ord('a'))
263
+
264
+ assert_equal(f(np.array(b'a')), ord('a'))
265
+ assert_equal(f(np.array([b'a'])), ord('a'))
266
+ a = np.array('a')
267
+ assert_equal(f(a), ord('a'))
268
+ a = np.array(['a'])
269
+ assert_equal(f(a), ord('a'))
270
+
271
+ try:
272
+ f([])
273
+ except IndexError as msg:
274
+ if not str(msg).endswith(' got 0-list'):
275
+ raise
276
+ else:
277
+ raise SystemError(f'{f.__name__} should have failed on empty list')
278
+
279
+ try:
280
+ f(97)
281
+ except TypeError as msg:
282
+ if not str(msg).endswith(' got int instance'):
283
+ raise
284
+ else:
285
+ raise SystemError(f'{f.__name__} should have failed on int value')
286
+
287
+ @pytest.mark.parametrize("dtype", ['c', 'S1', 'U1'])
288
+ def test_array_input(self, dtype):
289
+ f = getattr(self.module, self.fprefix + '_array_input')
290
+
291
+ assert_array_equal(f(np.array(['a', 'b', 'c'], dtype=dtype)),
292
+ np.array(list(map(ord, 'abc')), dtype='i1'))
293
+ assert_array_equal(f(np.array([b'a', b'b', b'c'], dtype=dtype)),
294
+ np.array(list(map(ord, 'abc')), dtype='i1'))
295
+
296
+ def test_array_input_varia(self):
297
+ f = getattr(self.module, self.fprefix + '_array_input')
298
+ assert_array_equal(f(['a', 'b', 'c']),
299
+ np.array(list(map(ord, 'abc')), dtype='i1'))
300
+ assert_array_equal(f([b'a', b'b', b'c']),
301
+ np.array(list(map(ord, 'abc')), dtype='i1'))
302
+
303
+ try:
304
+ f(['a', 'b', 'c', 'd'])
305
+ except ValueError as msg:
306
+ if not str(msg).endswith(
307
+ 'th dimension must be fixed to 3 but got 4'):
308
+ raise
309
+ else:
310
+ raise SystemError(
311
+ f'{f.__name__} should have failed on wrong input')
312
+
313
+ @pytest.mark.parametrize("dtype", ['c', 'S1', 'U1'])
314
+ def test_2d_array_input(self, dtype):
315
+ f = getattr(self.module, self.fprefix + '_2d_array_input')
316
+
317
+ a = np.array([['a', 'b', 'c'],
318
+ ['d', 'e', 'f']], dtype=dtype, order='F')
319
+ expected = a.view(np.uint32 if dtype == 'U1' else np.uint8)
320
+ assert_array_equal(f(a), expected)
321
+
322
+ def test_output(self):
323
+ f = getattr(self.module, self.fprefix + '_output')
324
+
325
+ assert_equal(f(ord(b'a')), b'a')
326
+ assert_equal(f(0), b'\0')
327
+
328
+ def test_array_output(self):
329
+ f = getattr(self.module, self.fprefix + '_array_output')
330
+
331
+ assert_array_equal(f(list(map(ord, 'abc'))),
332
+ np.array(list('abc'), dtype='S1'))
333
+
334
+ def test_input_output(self):
335
+ f = getattr(self.module, self.fprefix + '_input_output')
336
+
337
+ assert_equal(f(b'a'), b'a')
338
+ assert_equal(f('a'), b'a')
339
+ assert_equal(f(''), b'\0')
340
+
341
+ @pytest.mark.parametrize("dtype", ['c', 'S1'])
342
+ def test_inout(self, dtype):
343
+ f = getattr(self.module, self.fprefix + '_inout')
344
+
345
+ a = np.array(list('abc'), dtype=dtype)
346
+ f(a, 'A')
347
+ assert_array_equal(a, np.array(list('Abc'), dtype=a.dtype))
348
+ f(a[1:], 'B')
349
+ assert_array_equal(a, np.array(list('ABc'), dtype=a.dtype))
350
+
351
+ a = np.array(['abc'], dtype=dtype)
352
+ f(a, 'A')
353
+ assert_array_equal(a, np.array(['Abc'], dtype=a.dtype))
354
+
355
+ def test_inout_varia(self):
356
+ f = getattr(self.module, self.fprefix + '_inout')
357
+ a = np.array('abc', dtype='S3')
358
+ f(a, 'A')
359
+ assert_array_equal(a, np.array('Abc', dtype=a.dtype))
360
+
361
+ a = np.array(['abc'], dtype='S3')
362
+ f(a, 'A')
363
+ assert_array_equal(a, np.array(['Abc'], dtype=a.dtype))
364
+
365
+ try:
366
+ f('abc', 'A')
367
+ except ValueError as msg:
368
+ if not str(msg).endswith(' got 3-str'):
369
+ raise
370
+ else:
371
+ raise SystemError(f'{f.__name__} should have failed on str value')
372
+
373
+ @pytest.mark.parametrize("dtype", ['c', 'S1'])
374
+ def test_array_inout(self, dtype):
375
+ f = getattr(self.module, self.fprefix + '_array_inout')
376
+ n = np.array(['A', 'B', 'C'], dtype=dtype, order='F')
377
+
378
+ a = np.array(['a', 'b', 'c'], dtype=dtype, order='F')
379
+ f(a, n)
380
+ assert_array_equal(a, n)
381
+
382
+ a = np.array(['a', 'b', 'c', 'd'], dtype=dtype)
383
+ f(a[1:], n)
384
+ assert_array_equal(a, np.array(['a', 'A', 'B', 'C'], dtype=dtype))
385
+
386
+ a = np.array([['a', 'b', 'c']], dtype=dtype, order='F')
387
+ f(a, n)
388
+ assert_array_equal(a, np.array([['A', 'B', 'C']], dtype=dtype))
389
+
390
+ a = np.array(['a', 'b', 'c', 'd'], dtype=dtype, order='F')
391
+ try:
392
+ f(a, n)
393
+ except ValueError as msg:
394
+ if not str(msg).endswith(
395
+ 'th dimension must be fixed to 3 but got 4'):
396
+ raise
397
+ else:
398
+ raise SystemError(
399
+ f'{f.__name__} should have failed on wrong input')
400
+
401
+ @pytest.mark.parametrize("dtype", ['c', 'S1'])
402
+ def test_2d_array_inout(self, dtype):
403
+ f = getattr(self.module, self.fprefix + '_2d_array_inout')
404
+ n = np.array([['A', 'B', 'C'],
405
+ ['D', 'E', 'F']],
406
+ dtype=dtype, order='F')
407
+ a = np.array([['a', 'b', 'c'],
408
+ ['d', 'e', 'f']],
409
+ dtype=dtype, order='F')
410
+ f(a, n)
411
+ assert_array_equal(a, n)
412
+
413
+ def test_return(self):
414
+ f = getattr(self.module, self.fprefix + '_return')
415
+
416
+ assert_equal(f('a'), b'a')
417
+
418
+ @pytest.mark.skip('fortran function returning array segfaults')
419
+ def test_array_return(self):
420
+ f = getattr(self.module, self.fprefix + '_array_return')
421
+
422
+ a = np.array(list('abc'), dtype='S1')
423
+ assert_array_equal(f(a), a)
424
+
425
+ def test_optional(self):
426
+ f = getattr(self.module, self.fprefix + '_optional')
427
+
428
+ assert_equal(f(), b"a")
429
+ assert_equal(f(b'B'), b"B")
430
+
431
+
432
+ class TestMiscCharacter(util.F2PyTest):
433
+ # options = ['--debug-capi', '--build-dir', '/tmp/test-build-f2py']
434
+ suffix = '.f90'
435
+ fprefix = 'test_misc_character'
436
+
437
+ code = textwrap.dedent(f"""
438
+ subroutine {fprefix}_gh18684(x, y, m)
439
+ character(len=5), dimension(m), intent(in) :: x
440
+ character*5, dimension(m), intent(out) :: y
441
+ integer i, m
442
+ !f2py integer, intent(hide), depend(x) :: m = f2py_len(x)
443
+ do i=1,m
444
+ y(i) = x(i)
445
+ end do
446
+ end subroutine {fprefix}_gh18684
447
+
448
+ subroutine {fprefix}_gh6308(x, i)
449
+ integer i
450
+ !f2py check(i>=0 && i<12) i
451
+ character*5 name, x
452
+ common name(12)
453
+ name(i + 1) = x
454
+ end subroutine {fprefix}_gh6308
455
+
456
+ subroutine {fprefix}_gh4519(x)
457
+ character(len=*), intent(in) :: x(:)
458
+ !f2py intent(out) x
459
+ integer :: i
460
+ ! Uncomment for debug printing:
461
+ !do i=1, size(x)
462
+ ! print*, "x(",i,")=", x(i)
463
+ !end do
464
+ end subroutine {fprefix}_gh4519
465
+
466
+ pure function {fprefix}_gh3425(x) result (y)
467
+ character(len=*), intent(in) :: x
468
+ character(len=len(x)) :: y
469
+ integer :: i
470
+ do i = 1, len(x)
471
+ j = iachar(x(i:i))
472
+ if (j>=iachar("a") .and. j<=iachar("z") ) then
473
+ y(i:i) = achar(j-32)
474
+ else
475
+ y(i:i) = x(i:i)
476
+ endif
477
+ end do
478
+ end function {fprefix}_gh3425
479
+
480
+ subroutine {fprefix}_character_bc_new(x, y, z)
481
+ character, intent(in) :: x
482
+ character, intent(out) :: y
483
+ !f2py character, depend(x) :: y = x
484
+ !f2py character, dimension((x=='a'?1:2)), depend(x), intent(out) :: z
485
+ character, dimension(*) :: z
486
+ !f2py character, optional, check(x == 'a' || x == 'b') :: x = 'a'
487
+ !f2py callstatement (*f2py_func)(&x, &y, z)
488
+ !f2py callprotoargument character*, character*, character*
489
+ if (y.eq.x) then
490
+ y = x
491
+ else
492
+ y = 'e'
493
+ endif
494
+ z(1) = 'c'
495
+ end subroutine {fprefix}_character_bc_new
496
+
497
+ subroutine {fprefix}_character_bc_old(x, y, z)
498
+ character, intent(in) :: x
499
+ character, intent(out) :: y
500
+ !f2py character, depend(x) :: y = x[0]
501
+ !f2py character, dimension((*x=='a'?1:2)), depend(x), intent(out) :: z
502
+ character, dimension(*) :: z
503
+ !f2py character, optional, check(*x == 'a' || x[0] == 'b') :: x = 'a'
504
+ !f2py callstatement (*f2py_func)(x, y, z)
505
+ !f2py callprotoargument char*, char*, char*
506
+ if (y.eq.x) then
507
+ y = x
508
+ else
509
+ y = 'e'
510
+ endif
511
+ z(1) = 'c'
512
+ end subroutine {fprefix}_character_bc_old
513
+ """)
514
+
515
+ def test_gh18684(self):
516
+ # Test character(len=5) and character*5 usages
517
+ f = getattr(self.module, self.fprefix + '_gh18684')
518
+ x = np.array(["abcde", "fghij"], dtype='S5')
519
+ y = f(x)
520
+
521
+ assert_array_equal(x, y)
522
+
523
+ def test_gh6308(self):
524
+ # Test character string array in a common block
525
+ f = getattr(self.module, self.fprefix + '_gh6308')
526
+
527
+ assert_equal(self.module._BLNK_.name.dtype, np.dtype('S5'))
528
+ assert_equal(len(self.module._BLNK_.name), 12)
529
+ f("abcde", 0)
530
+ assert_equal(self.module._BLNK_.name[0], b"abcde")
531
+ f("12345", 5)
532
+ assert_equal(self.module._BLNK_.name[5], b"12345")
533
+
534
+ def test_gh4519(self):
535
+ # Test array of assumed length strings
536
+ f = getattr(self.module, self.fprefix + '_gh4519')
537
+
538
+ for x, expected in [
539
+ ('a', dict(shape=(), dtype=np.dtype('S1'))),
540
+ ('text', dict(shape=(), dtype=np.dtype('S4'))),
541
+ (np.array(['1', '2', '3'], dtype='S1'),
542
+ dict(shape=(3,), dtype=np.dtype('S1'))),
543
+ (['1', '2', '34'],
544
+ dict(shape=(3,), dtype=np.dtype('S2'))),
545
+ (['', ''], dict(shape=(2,), dtype=np.dtype('S1')))]:
546
+ r = f(x)
547
+ for k, v in expected.items():
548
+ assert_equal(getattr(r, k), v)
549
+
550
+ def test_gh3425(self):
551
+ # Test returning a copy of assumed length string
552
+ f = getattr(self.module, self.fprefix + '_gh3425')
553
+ # f is equivalent to bytes.upper
554
+
555
+ assert_equal(f('abC'), b'ABC')
556
+ assert_equal(f(''), b'')
557
+ assert_equal(f('abC12d'), b'ABC12D')
558
+
559
+ @pytest.mark.parametrize("state", ['new', 'old'])
560
+ def test_character_bc(self, state):
561
+ f = getattr(self.module, self.fprefix + '_character_bc_' + state)
562
+
563
+ c, a = f()
564
+ assert_equal(c, b'a')
565
+ assert_equal(len(a), 1)
566
+
567
+ c, a = f(b'b')
568
+ assert_equal(c, b'b')
569
+ assert_equal(len(a), 2)
570
+
571
+ assert_raises(Exception, lambda: f(b'c'))
572
+
573
+
574
+ class TestStringScalarArr(util.F2PyTest):
575
+ sources = [util.getpath("tests", "src", "string", "scalar_string.f90")]
576
+
577
+ def test_char(self):
578
+ for out in (self.module.string_test.string,
579
+ self.module.string_test.string77):
580
+ expected = ()
581
+ assert out.shape == expected
582
+ expected = '|S8'
583
+ assert out.dtype == expected
584
+
585
+ def test_char_arr(self):
586
+ for out in (self.module.string_test.strarr,
587
+ self.module.string_test.strarr77):
588
+ expected = (5,7)
589
+ assert out.shape == expected
590
+ expected = '|S12'
591
+ assert out.dtype == expected
592
+
593
+ class TestStringAssumedLength(util.F2PyTest):
594
+ sources = [util.getpath("tests", "src", "string", "gh24008.f")]
595
+
596
+ def test_gh24008(self):
597
+ self.module.greet("joe", "bob")
598
+
599
+ class TestStringOptionalInOut(util.F2PyTest):
600
+ sources = [util.getpath("tests", "src", "string", "gh24662.f90")]
601
+
602
+ def test_gh24662(self):
603
+ self.module.string_inout_optional()
604
+ a = np.array('hi', dtype='S32')
605
+ self.module.string_inout_optional(a)
606
+ assert "output string" in a.tobytes().decode()
607
+ with pytest.raises(Exception):
608
+ aa = "Hi"
609
+ self.module.string_inout_optional(aa)
610
+
611
+
612
+ @pytest.mark.slow
613
+ class TestNewCharHandling(util.F2PyTest):
614
+ # from v1.24 onwards, gh-19388
615
+ sources = [
616
+ util.getpath("tests", "src", "string", "gh25286.pyf"),
617
+ util.getpath("tests", "src", "string", "gh25286.f90")
618
+ ]
619
+ module_name = "_char_handling_test"
620
+
621
+ def test_gh25286(self):
622
+ info = self.module.charint('T')
623
+ assert info == 2
624
+
625
+ @pytest.mark.slow
626
+ class TestBCCharHandling(util.F2PyTest):
627
+ # SciPy style, "incorrect" bindings with a hook
628
+ sources = [
629
+ util.getpath("tests", "src", "string", "gh25286_bc.pyf"),
630
+ util.getpath("tests", "src", "string", "gh25286.f90")
631
+ ]
632
+ module_name = "_char_handling_test"
633
+
634
+ def test_gh25286(self):
635
+ info = self.module.charint('T')
636
+ assert info == 2