dl-py2f 1.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. dl_py2f-1.1.1/MANIFEST.in +29 -0
  2. dl_py2f-1.1.1/PKG-INFO +17 -0
  3. dl_py2f-1.1.1/dl_py2f/AUTHORS +14 -0
  4. dl_py2f-1.1.1/dl_py2f/CMakeLists.txt +54 -0
  5. dl_py2f-1.1.1/dl_py2f/LICENSE +165 -0
  6. dl_py2f-1.1.1/dl_py2f/README.md +85 -0
  7. dl_py2f-1.1.1/dl_py2f/__init__.py +291 -0
  8. dl_py2f-1.1.1/dl_py2f/dl_f2py.py +2023 -0
  9. dl_py2f-1.1.1/dl_py2f/dl_py2f.cpp +150 -0
  10. dl_py2f-1.1.1/dl_py2f/dl_py2f.f90 +1488 -0
  11. dl_py2f-1.1.1/dl_py2f/dl_py2f.h +179 -0
  12. dl_py2f-1.1.1/dl_py2f/dl_py2f.mod +0 -0
  13. dl_py2f-1.1.1/dl_py2f/export.map +72 -0
  14. dl_py2f-1.1.1/dl_py2f/libdir_debian.py +1 -0
  15. dl_py2f-1.1.1/dl_py2f/libdl_py2f.so +0 -0
  16. dl_py2f-1.1.1/dl_py2f/libpath.py.in +1 -0
  17. dl_py2f-1.1.1/dl_py2f/utils/__init__.py +22 -0
  18. dl_py2f-1.1.1/dl_py2f/utils/colours.py +425 -0
  19. dl_py2f-1.1.1/dl_py2f/utils/ctypeutils.py +68 -0
  20. dl_py2f-1.1.1/dl_py2f/utils/dictutils.py +119 -0
  21. dl_py2f-1.1.1/dl_py2f/utils/fileutils.py +126 -0
  22. dl_py2f-1.1.1/dl_py2f/utils/iterutils.py +120 -0
  23. dl_py2f-1.1.1/dl_py2f/utils/miscutils.py +152 -0
  24. dl_py2f-1.1.1/dl_py2f/utils/modutils.py +75 -0
  25. dl_py2f-1.1.1/dl_py2f/utils/nputils.py +202 -0
  26. dl_py2f-1.1.1/dl_py2f/utils/objutils.py +304 -0
  27. dl_py2f-1.1.1/dl_py2f/utils/strutils.py +111 -0
  28. dl_py2f-1.1.1/dl_py2f.egg-info/PKG-INFO +17 -0
  29. dl_py2f-1.1.1/dl_py2f.egg-info/SOURCES.txt +33 -0
  30. dl_py2f-1.1.1/dl_py2f.egg-info/dependency_links.txt +1 -0
  31. dl_py2f-1.1.1/dl_py2f.egg-info/requires.txt +1 -0
  32. dl_py2f-1.1.1/dl_py2f.egg-info/top_level.txt +1 -0
  33. dl_py2f-1.1.1/pyproject.toml +4 -0
  34. dl_py2f-1.1.1/setup.cfg +4 -0
  35. dl_py2f-1.1.1/setup.py +79 -0
@@ -0,0 +1,29 @@
1
+ include dl_py2f/CMakeLists.txt
2
+ include dl_py2f/dl_py2f.f90
3
+ include dl_py2f/dl_py2f.cpp
4
+ include dl_py2f/dl_py2f.h
5
+ include dl_py2f/dl_py2f.mod
6
+ include dl_py2f/export.map
7
+ include dl_py2f/libdl_py2f.so
8
+ include dl_py2f/export.map
9
+
10
+ # If there are subdirectories with sources, add them too, e.g.:
11
+ # recursive-include src *.f90 *.F90 *.c *.cpp *.h *.hpp
12
+
13
+ # Always good practice to include docs:
14
+ include dl_py2f/README.md
15
+ include dl_py2f/AUTHORS
16
+ include dl_py2f/LICENSE
17
+ include dl_py2f/libpath.py.in
18
+
19
+ include dl_py2f/utils/colours.py
20
+ include dl_py2f/utils/ctypeutils.py
21
+ include dl_py2f/utils/dictutils.py
22
+ include dl_py2f/utils/fileutils.py
23
+ include dl_py2f/utils/iterutils.py
24
+ include dl_py2f/utils/miscutils.py
25
+ include dl_py2f/utils/modutils.py
26
+ include dl_py2f/utils/nputils.py
27
+ include dl_py2f/utils/objutils.py
28
+ include dl_py2f/utils/strutils.py
29
+ include dl_py2f/utils/__init__.py
dl_py2f-1.1.1/PKG-INFO ADDED
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.4
2
+ Name: dl_py2f
3
+ Version: 1.1.1
4
+ Summary: DL_PY2F: A library for Python-Fortran interoperability
5
+ Home-page: https://github.com/stfc/dl_py2f
6
+ Author: You Lu
7
+ Author-email: you.lu@stfc.ac.uk
8
+ License: GNU Lesser General Public License v3.0
9
+ Requires-Python: >=3.9
10
+ Requires-Dist: numpy>=1.26
11
+ Dynamic: author
12
+ Dynamic: author-email
13
+ Dynamic: home-page
14
+ Dynamic: license
15
+ Dynamic: requires-dist
16
+ Dynamic: requires-python
17
+ Dynamic: summary
@@ -0,0 +1,14 @@
1
+ DL_PY2F authors:
2
+
3
+ You Lu and Thomas W. Keal
4
+
5
+ STFC Scientific Computing
6
+ Sci-Tech Daresbury
7
+ WARRINGTON
8
+ WA4 4AD
9
+ United Kingdom
10
+
11
+ you.lu@stfc.ac.uk
12
+
13
+ Source code making use of the DL_PY2F library should contain a proper acknowledgement by reference to:
14
+ Y. Lu and T. W. Keal, submitted to Journal of Open Source Software (March 2025)
@@ -0,0 +1,54 @@
1
+ cmake_minimum_required(VERSION 3.16)
2
+ cmake_policy(SET CMP0048 NEW)
3
+ project(DL_PY2F
4
+ VERSION 1.1.1
5
+ DESCRIPTION "DL_PY2F: A library for Python-Fortran interoperability"
6
+ LANGUAGES CXX Fortran)
7
+ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
8
+ set(CMAKE_Fortran_MODULE_DIRECTORY ${PROJECT_BINARY_DIR}/modules)
9
+ include_directories(${PROJECT_BINARY_DIR}/modules)
10
+ configure_file(libpath.py.in ${CMAKE_CURRENT_LIST_DIR}/libpath.py @ONLY)
11
+ add_library(dl_py2f SHARED dl_py2f.f90 dl_py2f.cpp)
12
+ if("${DL_PY2F_ARCH}" STREQUAL "cpe-gnu")
13
+ set_target_properties(dl_py2f PROPERTIES COMPILE_FLAGS "-fcheck=no-bounds")
14
+ elseif("${DL_PY2F_ARCH}" STREQUAL "cray")
15
+ if(DEBUG)
16
+ set_target_properties(dl_py2f PROPERTIES COMPILE_FLAGS "-dynamic -O0 -g -v")
17
+ else()
18
+ set_target_properties(dl_py2f PROPERTIES COMPILE_FLAGS "-dynamic -O0")
19
+ endif()
20
+ endif()
21
+ if(CMAKE_C_COMPILER_ID STREQUAL GNU)
22
+ list(APPEND CMAKE_CXX_FLAGS -fpermissive)
23
+ endif()
24
+ set_target_properties(dl_py2f PROPERTIES PUBLIC_HEADER ${CMAKE_Fortran_MODULE_DIRECTORY}/dl_py2f.mod)
25
+ set_target_properties(dl_py2f PROPERTIES LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_LIST_DIR}/export.map")
26
+ target_include_directories(dl_py2f PRIVATE ${CMAKE_CURRENT_LIST_DIR})
27
+ set_property(DIRECTORY ${PROJECT_BINARY_DIR}
28
+ APPEND
29
+ PROPERTY ADDITIONAL_MAKE_CLEAN_FILES Makefile;CMakeCache.txt;cmake_install.cmake;__pycache__;${PROJECT_BINARY_DIR}/modules;${PROJECT_BINARY_DIR}/lib;CMakeFiles
30
+ )
31
+
32
+
33
+ # YL 11/08/2025: rules for installation (Debian only)
34
+
35
+ set(CMAKE_INSTALL_LIBDIR /lib/x86_64-linux-gnu)
36
+ set(CMAKE_INSTALL_INCLUDEDIR /usr/include/x86_64-linux-gnu)
37
+
38
+ install(TARGETS dl_py2f
39
+ LIBRARY
40
+ DESTINATION ${CMAKE_INSTALL_LIBDIR}
41
+ COMPONENT Libraries
42
+ PUBLIC_HEADER
43
+ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
44
+ COMPONENT Headers)
45
+
46
+ install(FILES dl_f2py.py __init__.py
47
+ DESTINATION /usr/lib/python3/dist-packages/dl_py2f)
48
+
49
+ install(FILES libdir_debian.py
50
+ DESTINATION /usr/lib/python3/dist-packages/dl_py2f
51
+ RENAME libpath.py)
52
+
53
+ install(DIRECTORY utils
54
+ DESTINATION /usr/lib/python3/dist-packages/dl_py2f)
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,85 @@
1
+ # DL_PY2F
2
+
3
+ # About
4
+
5
+ [`DL_PY2F`](https://github.com/stfc/dl_py2f) is an open-source library for the creation of modern interfaces and data structures in Python that can interoperate with existing scientific software written in Fortran and manipulate their data.
6
+ `DL_PY2F` is intended for use with Python-based software packages where data are managed using Python/NumPy and need to be accessed for computations performed by Fortran code.
7
+ A great advantage of `DL_PY2F` for the application developers is that the attributes of the Python instance are conveniently retrieved by querying their names in a dictionary-like way on the Fortran side.
8
+ `DL_PY2F` also provides utility tools to facilitate initialisation and enhancement of the Python instances.
9
+
10
+ ## License
11
+
12
+ `DL_PY2F` is open source and released under [GNU Lesser General Public License v3.0](https://www.gnu.org/licenses/lgpl-3.0.en.html). It is available for download from the [repository](https://github.com/stfc/dl_py2f).
13
+
14
+ ## Authors
15
+
16
+ `DL_PY2F` was created and implemented by You Lu at [STFC Scientific Computing](https://www.sc.stfc.ac.uk).
17
+
18
+ ## Citing `DL_PY2F`
19
+
20
+ Applications using `DL_PY2F` should cite:
21
+
22
+ You Lu and Thomas W. Keal, *Journal of Open Source Software*, in preparation
23
+
24
+ ## Project status
25
+
26
+ The Python-to-Fortran interoperability has been comprehensively tested using both GNU and Intel compilers.
27
+
28
+ :warning: **Warning:** However, the method for Fortran-to-Python interoperability is still undergoing testing and validation, and is currently limited to use with the GNU compiler gfortran, as the proprietary .mod file format used by the Intel compiler is not yet supported.
29
+
30
+ # Getting started
31
+
32
+ ## Required libraries and tools
33
+
34
+
35
+ | Tools & Libraries | Min. version | Note |
36
+ |:------------------------------|:-------------|:-----|
37
+ | gcc/gfortran | 7.3 | |
38
+ | OR icc/ifort | 17 | :warning: |
39
+ | cmake | 3.16 | |
40
+ | python3-dev | 3.8 | |
41
+ | python3-numpy | 1.21.5 | |
42
+
43
+ :bulb: The above package names are based on Ubuntu Linux. They may vary on other
44
+ operating systems.
45
+
46
+ :warning: The Fortran-to-Python method does **NOT** yet work with the Intel compilers as Intel's proprietary
47
+ .mod file format is unpublished and unsupported.
48
+
49
+ ## Using and testing `DL_PY2F`
50
+
51
+ `DL_PY2F` is a mixed ABI/API library to be used by another software package. Here is a prototype package which is an example demonstrating in details how to compile and use `DL_PY2F`:
52
+
53
+ https://github.com/stfc/dl_py2f-example
54
+
55
+ The [example](https://github.com/stfc/dl_py2f-example) also works as a test bench for validating `DL_PY2F`. Please follow the instructions therein to compile and run it.
56
+
57
+ Apart from the source code on the [github repository](https://github.com/stfc/dl_py2f), `DL_PY2F` has also been published and deployed in a [launchpad.net PPA](https://launchpad.net/~dl-py2f/+archive/ubuntu/ppa) and can be installed systemwide using `apt`:
58
+
59
+ `sudo add-apt-repository ppa:dl-py2f/ppa`
60
+
61
+ `sudo apt update`
62
+
63
+ `sudo apt install dl-py2f`
64
+
65
+ :warning: Since Debian PPA does not allow underscore `_`, the package name published on [launchpad.net](https://launchpad.net/~dl-py2f/+archive/ubuntu/ppa) is **`dl-py2f`** but not `dl_py2f`.
66
+
67
+ :bulb: `sudo` access is required for installing system-wide packages using `apt`.
68
+
69
+ The use of system installed `DL_PY2F` is also demonstrated in the [example](https://github.com/stfc/dl_py2f-example) package.
70
+
71
+ For more information about the usage of `DL_PY2F` please also read the paper: [You Lu and Thomas W. Keal, *Journal of Open Source Software*, in preparation](https://joss.theoj.org/papers/).
72
+
73
+ # Miscellaneous
74
+
75
+ ## Support
76
+
77
+ Please raise an Issue on the [project's page](https://github.com/stfc/dl_py2f) if you have a question or find an issue about the code.
78
+
79
+ ## Contributing
80
+
81
+ Contributions are welcome in the form of Issue/PR on [github.com](https://github.com/stfc/dl_py2f).
82
+
83
+ ## Acknowledgements
84
+
85
+ The `DL_PY2F` library was created during the redevelopment of [ChemShell](https://chemshell.org) as a Python-based package, which was funded by EPSRC under the grant [EP/K038419/1](https://gtr.ukri.org/projects?ref=EP/K038419/1). Ongoing support for the development of `DL_PY2F` as part of ChemShell is provided under EPSRC grants [EP/R001847/1](https://gtr.ukri.org/projects?ref=EP%2FR001847%2F1) and [EP/W014378/1](https://gtr.ukri.org/projects?ref=EP%2FW014378%2F1), and the [Computational Science Centre for Research Communities (CoSeC)](https://www.cosec.ac.uk), via the support provided to the [Materials Chemistry Consortium](https://mcc.hec.ac.uk). We acknowledge helpful discussions and suggestions for improvement from Paul Sherwood, Joseph Thacker, and Thomas Durrant.
@@ -0,0 +1,291 @@
1
+ # Copyright (C) 2025 The authors of DL_PY2F
2
+ #
3
+ # This file is part of DL_PY2F.
4
+ #
5
+ # DL_PY2F is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU Lesser General Public License as
7
+ # published by the Free Software Foundation, either version 3 of the
8
+ # License, or (at your option) any later version.
9
+ #
10
+ # DL_PY2F is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ # GNU Lesser General Public License for more details.
14
+ #
15
+ # You should have received a copy of the GNU Lesser General Public
16
+ # License along with DL_PY2F. If not, see
17
+ # <https://www.gnu.org/licenses/>.
18
+
19
+ # you.lu@stfc.ac.uk
20
+ __author__ = [ 'You Lu', 'Thomas W. Keal' ]
21
+ __copyright__ = 'Copyright (C) 2025 The authors of DL_PY2F'
22
+ __credits__ = [ 'You Lu', 'Thomas W. Keal' ]
23
+ __license__ = 'LGPLv3'
24
+ __version__ = '25.0 (beta)'
25
+ __maintainer__ = __author__[0]
26
+ __email__ = 'you.lu@stfc.ac.uk'
27
+ __status__ = ''
28
+ __dictname = '_kwargs'
29
+ __arrname = '_master'
30
+ def __getType(obj):
31
+ from numpy import ndarray, float64, float32, int64, int32
32
+ from types import ModuleType, FunctionType
33
+ if isinstance(obj, ndarray):
34
+ return list
35
+ elif isinstance(obj, list):
36
+ return list
37
+ elif isinstance(obj, str):
38
+ return str
39
+ elif isinstance(obj, bytes):
40
+ return bytes
41
+ elif isinstance(obj, float64) or isinstance(obj, float32):
42
+ return float
43
+ elif isinstance(obj, int64) or isinstance(obj, int32):
44
+ return int
45
+ elif isinstance(obj, ModuleType):
46
+ return ModuleType
47
+ elif isinstance(obj, FunctionType):
48
+ return FunctionType
49
+ elif hasattr(obj, __dictname) and type(obj).__module__ != 'builtins':
50
+ return object
51
+ else:
52
+ return type(obj)
53
+ def py2f(obj, debug=0, byref=False):
54
+ from ctypes import CFUNCTYPE, c_int, c_long, c_double, c_bool, c_char, c_wchar_p, c_char_p, c_void_p, addressof, pointer, POINTER, Structure
55
+ from numpy import array, asarray, ctypeslib, ma, str_
56
+ from types import ModuleType
57
+ from sys import stdout
58
+ if debug > 2:
59
+ print("\n DL_PY2F: obj type = {}\n".format(type(obj)))
60
+ stdout.flush()
61
+ MAXLEN = 256
62
+ ATTRLEN = 32
63
+ dictbuff = getattr(obj, __dictname)
64
+ _kwargs = sorted(dictbuff.items())
65
+ fbuff = []
66
+ initialiser = []
67
+ def _appendInitAtoF(_initialiser, _obj, _key, _default_type):
68
+ if isinstance(_obj, ma.core.MaskedArray):
69
+ databuff = _obj.torecords()['_data'][_key]
70
+ else:
71
+ databuff = getattr(_obj, _key)
72
+ try:
73
+ _initialiser.append((__getType(databuff).__name__ + " "*ATTRLEN)[:ATTRLEN].encode('ascii'))
74
+ except:
75
+ _initialiser.append((__getType(databuff).__class__.__name__ + " "*ATTRLEN)[:ATTRLEN].encode('ascii'))
76
+ try:
77
+ _initialiser.append((_obj.synons[_key.strip()] + " "*ATTRLEN)[:ATTRLEN].encode('ascii'))
78
+ except:
79
+ _initialiser.append((_key+' '*ATTRLEN)[:ATTRLEN].encode('ascii'))
80
+ if _default_type is list:
81
+ abuff = asarray(databuff)
82
+ if abuff.dtype.name.startswith('void'):
83
+ size = abuff.size*len(abuff.dtype.names)
84
+ else:
85
+ size = abuff.size
86
+ _initialiser += [ (abuff.dtype.name+' '*ATTRLEN)[:ATTRLEN].encode('ascii'),
87
+ c_long(size),
88
+ c_long(abuff.shape[0]) ]
89
+ else:
90
+ _initialiser += [ (' '*ATTRLEN)[:ATTRLEN].encode('ascii') ] + [ c_long(0) ]*2
91
+ if isinstance(_obj, ma.core.MaskedArray):
92
+ _initialiser.append(c_bool(_default_type is list and _key in _obj.torecords()['_data'].dtype.fields))
93
+ else:
94
+ _initialiser.append(c_bool(_default_type is list and _key in getattr(_obj, '_fields', [])))
95
+ def __list2ndp(obj, key, foo):
96
+ if hasattr(foo, "dtype"):
97
+ selectcases = { 'int64' : c_long,
98
+ 'int32' : c_int,
99
+ 'float64' : c_double,
100
+ 'float32' : c_double,
101
+ 'bool' : c_long,
102
+ 'object' : c_long,
103
+ 'bytes64' :'U8',
104
+ 'bytes32' :'U8',
105
+ 'bytes128':'U8',
106
+ 'str32' :'U8',
107
+ 'str64' :'U8',
108
+ 'str256' :'U8',
109
+ 'record' : foo.dtype,
110
+ 'void' : foo.dtype,
111
+ }
112
+ def _addNPArray(_ctype, _key, _val):
113
+ npptr = ctypeslib.ndpointer(_ctype)
114
+ if _val.size > 0:
115
+ npptr._shape_ = _val.shape
116
+ fbuff.append((_key, npptr))
117
+ initialiser.append(asarray(_val, dtype=_ctype).ctypes.data)
118
+ def _addRecArray(_ctype, _arr):
119
+ for field in _ctype.names:
120
+ _appendInitAtoF(initialiser, foo, field, list)
121
+ _addNPArray(selectcases[_ctype.fields[field][0].name], field, _arr[field])
122
+ def _addFlexible(_ctype, _key, _val):
123
+ npptr = ctypeslib.ndpointer(_ctype)
124
+ if _val.size > 0:
125
+ npptr._shape_ = (_val.shape[0],len(_val.dtype.names))
126
+ fbuff.append((_key, npptr))
127
+ initialiser.append(asarray(_val, dtype=_ctype).ctypes.data)
128
+ try:
129
+ _addNPArray(selectcases[foo.dtype.name], key, getattr(obj, key))
130
+ except KeyError:
131
+ if foo.dtype.name[:6] == 'record':
132
+ _addRecArray(selectcases[foo.dtype.name[:6]], getattr(obj, key))
133
+ elif foo.dtype.name[:4] == 'void':
134
+ _addFlexible(selectcases[foo.dtype.name[:4]], key, getattr(obj, key))
135
+ else:
136
+ try:
137
+ initialiser.append(asarray([i for i in getattr(obj, key)], dtype=c_long).ctypes.data)
138
+ fbuff.append((key, ctypeslib.ndpointer(c_long)))
139
+ except ValueError:
140
+ if all([type(i) in [str,str_] for i in getattr(obj, key)]):
141
+ fbuff.append((key, c_char_p))
142
+ initialiser[-6] = ('str'+' '*ATTRLEN)[:ATTRLEN].encode('ascii')
143
+ initialiser.append(c_char_p((';'.join(foo) + " "*MAXLEN)[:MAXLEN].encode('ascii')))
144
+ else:
145
+ initialiser.append(None)
146
+ fbuff.append((key, c_void_p))
147
+ except:
148
+ if debug > 2:
149
+ print(" >>> DL_PY2F WARNING: cannot convert non-integer list/tuple `%s` of"%key, obj, "to NumPy ndarray")
150
+ initialiser.append(None)
151
+ fbuff.append((key, c_void_p))
152
+ def __int2cint(obj, key, foo):
153
+ fbuff.append((key, POINTER(c_long)))
154
+ initialiser.append(pointer(c_long(foo)))
155
+ def __func2cfunptr(obj, key, foo):
156
+ from typing import get_type_hints
157
+ selectcases = { float: c_double,
158
+ int : c_long }
159
+ c_type = selectcases.get(get_type_hints(foo).get('return', int), c_long)
160
+ fbuff.append((key, POINTER(CFUNCTYPE(c_type, c_void_p))))
161
+ initialiser.append(pointer(CFUNCTYPE(c_type, c_void_p)(foo)))
162
+ def __str2bytes(obj, key, foo):
163
+ fbuff.append((key, c_char_p))
164
+ initialiser.append(c_char_p((foo + " "*MAXLEN)[:MAXLEN].encode('ascii')))
165
+ def __module2bytes(obj, key, foo):
166
+ fbuff.append((key, c_char_p))
167
+ initialiser.append(c_char_p((foo.__name__ + " "*MAXLEN)[:MAXLEN].encode('ascii')))
168
+ def __obj2ptr(obj, key, foo):
169
+ bar = py2f(foo)
170
+ fbuff.append((key, POINTER(type(bar))))
171
+ initialiser.append(pointer(bar))
172
+ def __dict2None(obj, key, foo):
173
+ if debug > 2:
174
+ print(" >>> DL_PY2F WARNING: unsupport <class dict> entry \""+key+"\" will be treated as None.")
175
+ fbuff.append((key, c_void_p))
176
+ initialiser.append(None)
177
+ def __float2cdouble(obj, key, foo):
178
+ fbuff.append((key, POINTER(c_double)))
179
+ initialiser.append(pointer(c_double(foo)))
180
+ def __bool2cbool(obj, key, foo):
181
+ fbuff.append((key, POINTER(c_bool)))
182
+ initialiser.append(pointer(c_bool(foo)))
183
+ def __None2ptr(obj, key, foo):
184
+ fbuff.append((key, c_void_p))
185
+ initialiser.append(None)
186
+ selectcases = {
187
+ bool :__bool2cbool,
188
+ dict :__dict2None,
189
+ float :__float2cdouble,
190
+ int :__int2cint,
191
+ list :__list2ndp,
192
+ object :__obj2ptr,
193
+ tuple :__list2ndp,
194
+ type(lambda x:x):__func2cfunptr,
195
+ str :__str2bytes,
196
+ ModuleType :__module2bytes,
197
+ type(None) :__None2ptr }
198
+ for key, default_val in _kwargs:
199
+ if key.startswith('_'):
200
+ continue
201
+ try:
202
+ isRec = getattr(obj, key).dtype.name.startswith('record')
203
+ except:
204
+ isRec = False
205
+ if not isRec:
206
+ _appendInitAtoF(initialiser, obj, key, __getType(default_val))
207
+ try:
208
+ selectcases[__getType(getattr(obj, key))](obj, key, getattr(obj, key))
209
+ except KeyError:
210
+ print(" >>> DL_PY2F ERROR: type "+str(__getType(getattr(obj, key)))+" of entry \""+key+"\" not supported.\n")
211
+ fields = [ item for sublist in zip(zip([ 'type' + f[0] for f in fbuff ],
212
+ [ c_char*ATTRLEN for f in fbuff ]),
213
+ zip([ f[0] + ' '*ATTRLEN for f in fbuff ],
214
+ [ c_char*ATTRLEN for f in fbuff ]),
215
+ zip([ 'dtype' + f[0] for f in fbuff ],
216
+ [ c_char*ATTRLEN for f in fbuff ]),
217
+ zip([ 'size' + f[0] for f in fbuff ],
218
+ [ c_long for f in fbuff ]),
219
+ zip([ 'sizem' + f[0] for f in fbuff ],
220
+ [ c_long for f in fbuff ]),
221
+ zip([ 'isfield' + f[0] for f in fbuff ],
222
+ [ c_bool for f in fbuff ]),
223
+ fbuff)
224
+ for item in sublist ]
225
+ if len(fields) != len(initialiser) or debug > 4:
226
+ if len(fields) != len(initialiser):
227
+ print(" >>> DL_PY2F WARNING: fields (len: {}) and initialiser (len: {}) mismatch:".format(len(fields),len(initialiser)))
228
+ print(" Python object:", obj)
229
+ else:
230
+ print(" >>> DL_PY2F DEBUG: data structure of PY2F object")
231
+ print(" "*4+"-"*48)
232
+ print(" {:20} | {}".format('field', 'initialiser'))
233
+ for i in range(max(len(fields), len(initialiser))):
234
+ try:
235
+ if type(initialiser[i]) is bytes and fields[i][0].startswith('type'):
236
+ print(" "*4+"-"*48)
237
+ print(" {:20} | {}".format(fields[i][0].strip(), initialiser[i]))
238
+ except IndexError:
239
+ try:
240
+ print(" {:20} | {}".format('', initialiser[i]))
241
+ except:
242
+ print(" {:20} | ".format(fields[i][0].strip()))
243
+ print(" "*4+"-"*48)
244
+ stdout.flush()
245
+ fields.insert(0, ('nattrs', c_long))
246
+ initialiser.insert(0, c_long(int((len(fields)-1)/7)))
247
+ fields.insert(1, ('_class', c_char_p))
248
+ initialiser.insert(1, c_char_p((obj.__module__ + '.' + obj.__class__.__name__ + " "*MAXLEN)[:MAXLEN].encode('ascii')))
249
+ fields.insert(2, ('_address', c_long))
250
+ initialiser.insert(2, addressof(obj))
251
+ fields.insert(3, ('width', c_long))
252
+ try:
253
+ if hasattr(obj, __arrname):
254
+ _master = getattr(obj, __arrname)
255
+ width_list = [ _master[field].shape[1] if _master[field].ndim == 2 else
256
+ array(_master.dtype.fields[field][0].names).size for field in _master.dtype.fields ]
257
+ _width = sum(width_list)
258
+ initialiser.insert(3, c_long(_width))
259
+ except:
260
+ initialiser.insert(3, c_long(0))
261
+ fields.insert(4, ('debug', POINTER(c_long)))
262
+ initialiser.insert(4, pointer(c_long(debug)))
263
+ stdout.flush()
264
+ if debug >= 5:
265
+ print("\n >>> DL_PY2F DEBUG: Components of wrapped Python object", obj)
266
+ print("\n {:5} {:32} {:24} {}".format('index', 'field name', 'field type', 'value'))
267
+ for i, v in enumerate(initialiser):
268
+ if not (i-5)%7:
269
+ print()
270
+ print(" {:5d} {:32.32} {:24.24} {}".format(i, '\"'+fields[i][0]+'\"', fields[i][1].__name__, v))
271
+ class CStruct(Structure):
272
+ _fields_ = fields
273
+ def __new__(cls, *args):
274
+ inst = Structure.__new__(cls)
275
+ stdout.flush()
276
+ return inst
277
+ if not byref:
278
+ return CStruct(*initialiser)
279
+ else:
280
+ from ctypes import byref as ctypes_byref
281
+ from sys import stdout
282
+ try:
283
+ return ctypes_byref(CStruct(*initialiser))
284
+ except:
285
+ print(" >>> DL_PY2F ERROR: obj =", obj)
286
+ stdout.flush()
287
+ raise
288
+ import os, sys
289
+ sys.path.append(os.path.dirname(__file__))
290
+ from .dl_f2py import DL_DL
291
+ from . import utils