skyborn-spharm 0.1.0__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.
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2025, Qianye Su
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the [copyright holder] nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,37 @@
1
+ PLEASE READ THIS SOFTWARE LICENSE ("LICENSE") CAREFULLY.
2
+
3
+ Copyright 2004 the University Corporation for Atmospheric
4
+ Research ("UCAR"). All rights reserved. Developed by NCAR's
5
+ Computational and Information Systems Laboratory, UCAR,
6
+ http://www2.cisl.ucar.edu. Redistribution and use of the Software
7
+ in source and binary forms, with or without modification, is
8
+ permitted provided that the following conditions are met:
9
+
10
+ * Neither the names of NCAR's Computational and
11
+ Information Systems Laboratory, the University Corporation for
12
+ Atmospheric Research, nor the names of its sponsors or
13
+ contributors may be used to endorse or promote products derived
14
+ from this Software without specific prior written permission.
15
+
16
+ * Redistributions of source code must retain the above
17
+ copyright notices, this list of conditions, and the disclaimer
18
+ below.
19
+
20
+ * Redistributions in binary form must reproduce the above
21
+ copyright notice, this list of conditions, and the disclaimer
22
+ below in the documentation and/or other materials provided with
23
+ the distribution.
24
+
25
+ THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26
+ EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE WARRANTIES
27
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28
+ NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT
29
+ HOLDERS BE LIABLE FOR ANY CLAIM, INDIRECT, INCIDENTAL, SPECIAL,
30
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY, WHETHER
31
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
32
+ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
33
+ DEALINGS WITH THE SOFTWARE.
34
+
35
+ SPHEREPACK is a product of the Computational & Information
36
+ Systems Laboratory at the National Center for Atmospheric
37
+ Research (NCAR).
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: skyborn-spharm
3
+ Version: 0.1.0
4
+ Summary: Modern Fortran-accelerated spherical harmonic transforms for Python (SPHEREPACK + reduced Gaussian grids)
5
+ Author-email: Qianye Su <suqianye2000@gmail.com>
6
+ License-Expression: BSD-3-Clause
7
+ Project-URL: Homepage, https://github.com/skyborn-org/skyborn-spharm
8
+ Project-URL: Repository, https://github.com/skyborn-org/skyborn-spharm
9
+ Project-URL: Documentation, https://skyborn.readthedocs.io/
10
+ Project-URL: Bug Tracker, https://github.com/skyborn-org/skyborn-spharm/issues
11
+ Keywords: atmospheric-science,meteorology,spherical-harmonics,spherepack,gaussian-grid
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
15
+ Classifier: Topic :: Scientific/Engineering :: Physics
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Operating System :: MacOS
24
+ Classifier: Operating System :: Microsoft :: Windows
25
+ Classifier: Operating System :: POSIX :: Linux
26
+ Requires-Python: >=3.9
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ License-File: LICENSE.spherepack
30
+ Requires-Dist: numpy>=1.24.0
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=7.0; extra == "dev"
33
+ Requires-Dist: matplotlib; extra == "dev"
34
+ Requires-Dist: pandas; extra == "dev"
35
+ Requires-Dist: xarray; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # skyborn-spharm (`skybornspharm`)
39
+
40
+ Modern, prebuilt-wheel spherical harmonic transforms in Python backed by NCAR SPHEREPACK Fortran/OpenMP kernels and native **reduced Gaussian grid** support (ECMWF IFS / ERA5 style).
41
+
42
+ Part of the [**Skyborn** (`skyborn-org`)](https://github.com/skyborn-org) ecosystem.
43
+
44
+ ## Why `skyborn-spharm`?
45
+
46
+ - **Drop-in modern replacement for `pyspharm`**: Full Python 3.9–3.14 and NumPy 1.24–2.x support with prebuilt wheels for Linux (`manylinux2014` & `manylinux_2_28`), macOS (`arm64` & `x86_64`), and Windows (`win_amd64`).
47
+ - **Zero extra runtime dependencies**: Depends only on `numpy`.
48
+ - **Thread-safe & OpenMP accelerated**: Modernized Fortran 90 kernels with Meson build system.
49
+ - **Reduced Gaussian Grid Support**: Direct transforms on packed reduced Gaussian grids (`ReducedGaussianSpharmt`).
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ pip install skyborn-spharm
55
+ ```
56
+
57
+ ## Quick Start
58
+
59
+ ```python
60
+ import numpy as np
61
+ from skybornspharm import Spharmt, gaussian_lats_wts
62
+
63
+ nlon, nlat = 144, 73
64
+ sht = Spharmt(nlon=nlon, nlat=nlat, gridtype="gaussian")
65
+ field = np.random.randn(nlat, nlon)
66
+
67
+ spec = sht.grdtospec(field)
68
+ reconstructed = sht.spectogrd(spec)
69
+ ```
70
+
71
+ Note: `skyborn.spharm` in the `skyborn` package seamlessly re-exports `skybornspharm`.
72
+
73
+ ## License
74
+
75
+ - Python wrappers and modern extensions: BSD 3-Clause License ([LICENSE](LICENSE))
76
+ - Underlying SPHEREPACK routines: SPHEREPACK License ([LICENSE.spherepack](LICENSE.spherepack))
@@ -0,0 +1,39 @@
1
+ # skyborn-spharm (`skybornspharm`)
2
+
3
+ Modern, prebuilt-wheel spherical harmonic transforms in Python backed by NCAR SPHEREPACK Fortran/OpenMP kernels and native **reduced Gaussian grid** support (ECMWF IFS / ERA5 style).
4
+
5
+ Part of the [**Skyborn** (`skyborn-org`)](https://github.com/skyborn-org) ecosystem.
6
+
7
+ ## Why `skyborn-spharm`?
8
+
9
+ - **Drop-in modern replacement for `pyspharm`**: Full Python 3.9–3.14 and NumPy 1.24–2.x support with prebuilt wheels for Linux (`manylinux2014` & `manylinux_2_28`), macOS (`arm64` & `x86_64`), and Windows (`win_amd64`).
10
+ - **Zero extra runtime dependencies**: Depends only on `numpy`.
11
+ - **Thread-safe & OpenMP accelerated**: Modernized Fortran 90 kernels with Meson build system.
12
+ - **Reduced Gaussian Grid Support**: Direct transforms on packed reduced Gaussian grids (`ReducedGaussianSpharmt`).
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ pip install skyborn-spharm
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ```python
23
+ import numpy as np
24
+ from skybornspharm import Spharmt, gaussian_lats_wts
25
+
26
+ nlon, nlat = 144, 73
27
+ sht = Spharmt(nlon=nlon, nlat=nlat, gridtype="gaussian")
28
+ field = np.random.randn(nlat, nlon)
29
+
30
+ spec = sht.grdtospec(field)
31
+ reconstructed = sht.spectogrd(spec)
32
+ ```
33
+
34
+ Note: `skyborn.spharm` in the `skyborn` package seamlessly re-exports `skybornspharm`.
35
+
36
+ ## License
37
+
38
+ - Python wrappers and modern extensions: BSD 3-Clause License ([LICENSE](LICENSE))
39
+ - Underlying SPHEREPACK routines: SPHEREPACK License ([LICENSE.spherepack](LICENSE.spherepack))
@@ -0,0 +1,103 @@
1
+ [build-system]
2
+ requires = [
3
+ "setuptools>=61.0",
4
+ "wheel",
5
+ "numpy>=1.24.0",
6
+ "meson",
7
+ "ninja",
8
+ ]
9
+ build-backend = "setuptools.build_meta"
10
+
11
+ [project]
12
+ name = "skyborn-spharm"
13
+ dynamic = ["version"]
14
+ description = "Modern Fortran-accelerated spherical harmonic transforms for Python (SPHEREPACK + reduced Gaussian grids)"
15
+ readme = "README.md"
16
+ authors = [{ name = "Qianye Su", email = "suqianye2000@gmail.com" }]
17
+ license = "BSD-3-Clause"
18
+ license-files = ["LICENSE", "LICENSE.spherepack"]
19
+ requires-python = ">=3.9"
20
+ keywords = [
21
+ "atmospheric-science",
22
+ "meteorology",
23
+ "spherical-harmonics",
24
+ "spherepack",
25
+ "gaussian-grid",
26
+ ]
27
+ classifiers = [
28
+ "Development Status :: 4 - Beta",
29
+ "Intended Audience :: Science/Research",
30
+ "Topic :: Scientific/Engineering :: Atmospheric Science",
31
+ "Topic :: Scientific/Engineering :: Physics",
32
+ "Programming Language :: Python :: 3",
33
+ "Programming Language :: Python :: 3.9",
34
+ "Programming Language :: Python :: 3.10",
35
+ "Programming Language :: Python :: 3.11",
36
+ "Programming Language :: Python :: 3.12",
37
+ "Programming Language :: Python :: 3.13",
38
+ "Programming Language :: Python :: 3.14",
39
+ "Operating System :: MacOS",
40
+ "Operating System :: Microsoft :: Windows",
41
+ "Operating System :: POSIX :: Linux",
42
+ ]
43
+ dependencies = [
44
+ "numpy>=1.24.0",
45
+ ]
46
+
47
+ [project.optional-dependencies]
48
+ dev = [
49
+ "pytest>=7.0",
50
+ "matplotlib",
51
+ "pandas",
52
+ "xarray",
53
+ ]
54
+
55
+ [project.urls]
56
+ "Homepage" = "https://github.com/skyborn-org/skyborn-spharm"
57
+ "Repository" = "https://github.com/skyborn-org/skyborn-spharm"
58
+ "Documentation" = "https://skyborn.readthedocs.io/"
59
+ "Bug Tracker" = "https://github.com/skyborn-org/skyborn-spharm/issues"
60
+
61
+ [tool.setuptools]
62
+ package-dir = { "" = "src" }
63
+ include-package-data = false
64
+
65
+ [tool.setuptools.packages.find]
66
+ where = ["src"]
67
+ exclude = [
68
+ "*.build*",
69
+ "*.build*.*",
70
+ "*.build",
71
+ "*.build.*",
72
+ ]
73
+
74
+ [tool.setuptools.exclude-package-data]
75
+ "*" = [
76
+ "*.pyc",
77
+ "*.pyo",
78
+ "__pycache__/*",
79
+ "build/*",
80
+ "build_local/*",
81
+ "meson-private/*",
82
+ "meson-logs/*",
83
+ "meson-info/*",
84
+ ]
85
+
86
+ [tool.setuptools.dynamic]
87
+ version = { attr = "skybornspharm.__version__" }
88
+
89
+ [tool.black]
90
+ line-length = 88
91
+ target-version = ["py39", "py310", "py311", "py312", "py313", "py314"]
92
+
93
+ [tool.isort]
94
+ profile = "black"
95
+ line_length = 88
96
+ src_paths = ["src", "tests"]
97
+
98
+ [tool.pytest.ini_options]
99
+ minversion = "6.0"
100
+ testpaths = ["tests"]
101
+ python_files = ["test_*.py"]
102
+ python_classes = ["Test*"]
103
+ python_functions = ["test_*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,354 @@
1
+ """Setup script for skyborn-spharm - Meson Fortran/C build with incremental Ninja caching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import platform
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+ from pathlib import Path
12
+
13
+ from setuptools import Distribution, setup
14
+ from setuptools.command.build_ext import build_ext
15
+ from setuptools.command.develop import develop
16
+ from setuptools.command.install import install
17
+ from setuptools.command.install_lib import install_lib
18
+ from wheel.bdist_wheel import bdist_wheel
19
+
20
+ CONDA_BUILD_MODE = os.environ.get("CONDA_BUILD") == "1"
21
+
22
+
23
+ def _active_python_prefix() -> Path:
24
+ return Path(sys.prefix).resolve()
25
+
26
+
27
+ def configure_compiler_environment():
28
+ if CONDA_BUILD_MODE:
29
+ return
30
+ if platform.system() == "Darwin" and "CC" not in os.environ:
31
+ fc_path = shutil.which(os.environ.get("FC", "gfortran"))
32
+ if fc_path and ("/opt/homebrew" in fc_path or "/usr/local" in fc_path):
33
+ fc_dir = Path(fc_path).resolve().parent
34
+ gcc_bins = sorted(fc_dir.glob("gcc-[0-9]*"))
35
+ if not gcc_bins:
36
+ gcc_bins = sorted(Path("/opt/homebrew/bin").glob("gcc-[0-9]*"))
37
+ if gcc_bins:
38
+ cc_bin = str(gcc_bins[-1])
39
+ os.environ["CC"] = cc_bin
40
+ cxx_bin = cc_bin.replace("/gcc-", "/g++-")
41
+ if os.path.exists(cxx_bin):
42
+ os.environ.setdefault("CXX", cxx_bin)
43
+ os.environ.setdefault("FC", "gfortran")
44
+ os.environ.setdefault("F77", os.environ["FC"])
45
+ os.environ.setdefault("F90", os.environ["FC"])
46
+ os.environ.setdefault("CC", "gcc")
47
+
48
+
49
+ configure_compiler_environment()
50
+
51
+
52
+ class MesonBuildExt(build_ext):
53
+ """Custom build_ext invoking Meson + Ninja with incremental inplace caching."""
54
+
55
+ @staticmethod
56
+ def _resolve_tool_command(executable_name: str, module_name: str, *args: str):
57
+ executable_path = shutil.which(executable_name)
58
+ if executable_path:
59
+ return [executable_path, *args]
60
+ return [sys.executable, "-m", module_name, *args]
61
+
62
+ @staticmethod
63
+ def _meson_command(*args: str):
64
+ return MesonBuildExt._resolve_tool_command(
65
+ "meson", "mesonbuild.mesonmain", *args
66
+ )
67
+
68
+ @staticmethod
69
+ def _ninja_command(*args: str):
70
+ return MesonBuildExt._resolve_tool_command("ninja", "ninja", *args)
71
+
72
+ @staticmethod
73
+ def _write_meson_native_file(build_dir: Path) -> Path:
74
+ native_file = (build_dir / "meson-python-native.ini").resolve()
75
+ python_executable = Path(os.path.abspath(sys.executable)).as_posix()
76
+ native_file.write_text(
77
+ "[binaries]\n"
78
+ f"python = '{python_executable}'\n"
79
+ f"build_python = '{python_executable}'\n",
80
+ encoding="utf-8",
81
+ )
82
+ return native_file
83
+
84
+ @staticmethod
85
+ def _write_build_python_shim(build_dir: Path) -> Path:
86
+ python_executable = shutil.which("python") or os.path.abspath(sys.executable)
87
+ if os.name == "nt":
88
+ shim_path = (build_dir / "build_python.bat").resolve()
89
+ with shim_path.open("w", encoding="utf-8", newline="\r\n") as handle:
90
+ handle.write("@echo off\r\n")
91
+ handle.write(f'"{python_executable}" %*\r\n')
92
+ else:
93
+ shim_path = (build_dir / "build_python").resolve()
94
+ python_executable = Path(os.path.abspath(python_executable)).as_posix()
95
+ with shim_path.open("w", encoding="utf-8", newline="\n") as handle:
96
+ handle.write("#!/bin/sh\n")
97
+ handle.write(f'exec "{python_executable}" "$@"\n')
98
+ shim_path.chmod(0o755)
99
+ return shim_path
100
+
101
+ def run(self):
102
+ self.build_meson_modules()
103
+ super().run()
104
+ self.prune_installed_import_libraries()
105
+
106
+ def prune_installed_import_libraries(self):
107
+ if self.inplace or not getattr(self, "build_lib", None):
108
+ return
109
+ build_lib_path = Path(self.build_lib)
110
+ if not build_lib_path.exists():
111
+ return
112
+ for import_lib in build_lib_path.rglob("*.dll.a"):
113
+ import_lib.unlink()
114
+
115
+ def _discover_meson_modules(self):
116
+ pkg_root = Path("src") / "skybornspharm"
117
+ modules = []
118
+ for meson_file in sorted(pkg_root.rglob("meson.build")):
119
+ rel_dir = meson_file.parent.relative_to(pkg_root)
120
+ name = ".".join(rel_dir.parts) if rel_dir.parts else "skybornspharm"
121
+ modules.append({"name": name, "path": meson_file.parent})
122
+ return modules
123
+
124
+ def build_meson_modules(self):
125
+ for module in self._discover_meson_modules():
126
+ self.build_meson_module(module)
127
+
128
+ def _prepare_meson_env(self, build_dir: Path) -> dict[str, str]:
129
+ env = os.environ.copy()
130
+ active_prefix = _active_python_prefix()
131
+ conda_prefix = str(active_prefix) if active_prefix.exists() else ""
132
+ build_dir_path = str(build_dir.resolve())
133
+ system = platform.system()
134
+
135
+ if conda_prefix:
136
+ env["CONDA_PREFIX"] = conda_prefix
137
+ current_path = env.get("PATH", "")
138
+ if system == "Windows":
139
+ path_entries = [
140
+ build_dir_path,
141
+ conda_prefix,
142
+ os.path.join(conda_prefix, "Scripts"),
143
+ os.path.join(conda_prefix, "bin"),
144
+ os.path.join(conda_prefix, "Library", "bin"),
145
+ os.path.join(conda_prefix, "Library", "mingw-w64", "bin"),
146
+ os.path.join(conda_prefix, "Library", "usr", "bin"),
147
+ ]
148
+ path_entries = [entry for entry in path_entries if os.path.isdir(entry)]
149
+ env["PATH"] = ";".join(path_entries + [current_path])
150
+ if CONDA_BUILD_MODE:
151
+ toolchain = {
152
+ "CC": "x86_64-w64-mingw32-gcc.exe",
153
+ "CXX": "x86_64-w64-mingw32-g++.exe",
154
+ "FC": "x86_64-w64-mingw32-gfortran.exe",
155
+ "F77": "x86_64-w64-mingw32-gfortran.exe",
156
+ "F90": "x86_64-w64-mingw32-gfortran.exe",
157
+ "AR": "x86_64-w64-mingw32-ar.exe",
158
+ "RANLIB": "x86_64-w64-mingw32-ranlib.exe",
159
+ }
160
+ for key, exe in toolchain.items():
161
+ found = shutil.which(exe, path=env["PATH"])
162
+ if found:
163
+ env[key] = found
164
+ elif system in ("Linux", "Darwin"):
165
+ conda_bin = os.path.join(conda_prefix, "bin")
166
+ path_entries = [build_dir_path]
167
+ if os.path.isdir(conda_bin):
168
+ path_entries.append(conda_bin)
169
+ env["PATH"] = ":".join(path_entries + [current_path])
170
+ if system == "Linux" and (
171
+ CONDA_BUILD_MODE or os.path.exists(os.path.join(conda_bin, "gfortran"))
172
+ ):
173
+ conda_lib = os.path.join(conda_prefix, "lib")
174
+ cur_lib = env.get("LD_LIBRARY_PATH", "")
175
+ env["LD_LIBRARY_PATH"] = (
176
+ f"{conda_lib}:{cur_lib}" if cur_lib else conda_lib
177
+ )
178
+ if CONDA_BUILD_MODE and system == "Darwin":
179
+ for key in (
180
+ "AR",
181
+ "RANLIB",
182
+ "GCC_AR",
183
+ "GCC_RANLIB",
184
+ "LD",
185
+ "LDSHARED",
186
+ "CC_LD",
187
+ "CXX_LD",
188
+ "FC_LD",
189
+ "F77_LD",
190
+ "F90_LD",
191
+ ):
192
+ env.pop(key, None)
193
+ ar_path = shutil.which("llvm-ar", path=conda_bin) or shutil.which(
194
+ "ar", path="/usr/bin"
195
+ )
196
+ ranlib_path = shutil.which(
197
+ "llvm-ranlib", path=conda_bin
198
+ ) or shutil.which("ranlib", path="/usr/bin")
199
+ if ar_path or ranlib_path:
200
+ shim_dir = tempfile.mkdtemp(prefix="skybornspharm-tools-")
201
+ for nm in ("ar", "gcc-ar", "gar"):
202
+ if ar_path:
203
+ p = os.path.join(shim_dir, nm)
204
+ with open(p, "w", encoding="utf-8") as h:
205
+ h.write(
206
+ '#!/bin/sh\nif [ "x$1" = "x--version" ]; then echo "GNU ar (shim)"; exit 0; fi\n'
207
+ f'exec "{ar_path}" "$@"\n'
208
+ )
209
+ os.chmod(p, 0o755)
210
+ for nm in ("ranlib", "gcc-ranlib"):
211
+ if ranlib_path:
212
+ p = os.path.join(shim_dir, nm)
213
+ with open(p, "w", encoding="utf-8") as h:
214
+ h.write(
215
+ '#!/bin/sh\nif [ "x$1" = "x--version" ]; then echo "GNU ranlib (shim)"; exit 0; fi\n'
216
+ f'exec "{ranlib_path}" "$@"\n'
217
+ )
218
+ os.chmod(p, 0o755)
219
+ env["PATH"] = f"{shim_dir}:{env['PATH']}"
220
+ else:
221
+ current_path = env.get("PATH", "")
222
+ path_sep = ";" if system == "Windows" else ":"
223
+ env["PATH"] = (
224
+ f"{build_dir_path}{path_sep}{current_path}"
225
+ if current_path
226
+ else build_dir_path
227
+ )
228
+ return env
229
+
230
+ def build_meson_module(self, module):
231
+ module_path = module["path"]
232
+ build_dir = module_path / "build"
233
+ clean_requested = os.environ.get("SKYBORN_CLEAN_BUILD") == "1"
234
+ can_reuse = (
235
+ bool(self.inplace)
236
+ and not clean_requested
237
+ and (build_dir / "build.ninja").exists()
238
+ )
239
+ env = self._prepare_meson_env(build_dir)
240
+
241
+ if not can_reuse:
242
+ if build_dir.exists():
243
+ shutil.rmtree(build_dir)
244
+ build_dir.mkdir(parents=True, exist_ok=True)
245
+ native_file = self._write_meson_native_file(build_dir)
246
+ self._write_build_python_shim(build_dir)
247
+
248
+ setup_cmd = self._meson_command(
249
+ "setup",
250
+ "build",
251
+ ".",
252
+ "--buildtype=release",
253
+ "--native-file",
254
+ str(native_file),
255
+ )
256
+ setup_cmd.append(
257
+ "-Db_lto=false" if (CONDA_BUILD_MODE or not self.inplace) else "-Db_lto=true"
258
+ )
259
+ if not self.inplace and getattr(self, "build_lib", None):
260
+ build_lib_path = Path(self.build_lib).resolve()
261
+ setup_cmd.extend(
262
+ [
263
+ f"--python.purelibdir={build_lib_path}",
264
+ f"--python.platlibdir={build_lib_path}",
265
+ ]
266
+ )
267
+ subprocess.run(setup_cmd, cwd=str(module_path), check=True, env=env)
268
+
269
+ subprocess.run(
270
+ self._meson_command("compile", "-C", "build"),
271
+ cwd=str(module_path),
272
+ check=True,
273
+ env=env,
274
+ )
275
+
276
+ if not self.inplace and getattr(self, "build_lib", None):
277
+ subprocess.run(
278
+ self._meson_command("install", "-C", "build", "--only-changed"),
279
+ cwd=str(module_path),
280
+ check=True,
281
+ env=env,
282
+ )
283
+ self.prune_installed_import_libraries()
284
+
285
+
286
+ class CustomDevelop(develop):
287
+ def run(self):
288
+ self.run_command("build_ext")
289
+ super().run()
290
+
291
+
292
+ class CustomInstall(install):
293
+ def run(self):
294
+ self.run_command("build_ext")
295
+ super().run()
296
+
297
+
298
+ class CustomInstallLib(install_lib):
299
+ """Prune transient build artifacts, sources, and bytecode from installed tree."""
300
+
301
+ _PRUNE_DIR_NAMES = {
302
+ "__pycache__",
303
+ "build",
304
+ "build_local",
305
+ "meson-private",
306
+ "meson-logs",
307
+ "meson-info",
308
+ "src",
309
+ }
310
+ _PRUNE_FILES = {"build_split_pyf.py"}
311
+
312
+ def run(self):
313
+ super().run()
314
+ package_root = Path(self.install_dir) / "skybornspharm"
315
+ if not package_root.exists():
316
+ return
317
+ for fname in self._PRUNE_FILES:
318
+ target = package_root / fname
319
+ if target.exists():
320
+ target.unlink()
321
+ for path in sorted(
322
+ package_root.rglob("*"), key=lambda item: len(item.parts), reverse=True
323
+ ):
324
+ if path.is_dir() and (
325
+ path.name in self._PRUNE_DIR_NAMES or path.name.startswith("build_")
326
+ ):
327
+ shutil.rmtree(path, ignore_errors=True)
328
+ elif path.is_file() and path.suffix.lower() in {".pyc", ".pyo"}:
329
+ path.unlink()
330
+
331
+
332
+ class BinaryDistribution(Distribution):
333
+ def has_ext_modules(self):
334
+ return True
335
+
336
+
337
+ class CustomBdistWheel(bdist_wheel):
338
+ def finalize_options(self):
339
+ super().finalize_options()
340
+ self.root_is_pure = False
341
+
342
+
343
+ if __name__ == "__main__":
344
+ setup(
345
+ cmdclass={
346
+ "bdist_wheel": CustomBdistWheel,
347
+ "build_ext": MesonBuildExt,
348
+ "develop": CustomDevelop,
349
+ "install": CustomInstall,
350
+ "install_lib": CustomInstallLib,
351
+ },
352
+ distclass=BinaryDistribution,
353
+ ext_modules=[],
354
+ )