diff --git a/.gitignore b/.gitignore index e1d4710a..a6208076 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ build.sh build/ *.pyc .venv +build-meson/ diff --git a/INSTALL b/INSTALL index 8630926c..c840f668 100644 --- a/INSTALL +++ b/INSTALL @@ -21,3 +21,16 @@ Installation is performed using the command: Assimulo is then installed under Python dist-packages. To test the installation, run "pytest". + +Building with meson-python (Python >= 3.12, where numpy.distutils no longer exists) +------------------------------------------------------------------------------------ + pip install --no-build-isolation \ + -Csetup-args=-Dsundials-home=$CONDA_PREFIX \ + -Csetup-args=-Dsuperlu-home=$CONDA_PREFIX \ + -Csetup-args=-Dblas-home=$CONDA_PREFIX/lib -Csetup-args=-Dlapack-home=$CONDA_PREFIX/lib . + +Options (meson.options): sundials-home, superlu-home, blas-home, lapack-home, fortran +(auto/enabled/disabled), extra-fortran-flags (default --std=legacy). Needs meson-python, +Cython >= 3, numpy, a C compiler and, for the Fortran solvers, gfortran. The build produces +the same 19 extension modules as setup.py with the same compiler flags; tools/dump_examples.py +and tests/test_build_equivalence.py compare two builds bit for bit. diff --git a/build-support/assimulo/lib/meson.build b/build-support/assimulo/lib/meson.build new file mode 100644 index 00000000..d882faae --- /dev/null +++ b/build-support/assimulo/lib/meson.build @@ -0,0 +1,4 @@ +foreach f : ['__init__.py', 'sundials_includes.pxd', 'sundials_constants.pxi', 'sundials_callbacks.pxi', + 'sundials_callbacks_ida_cvode.pxi', 'sundials_callbacks_kinsol.pxi'] + stage += {'lib/' + f: configure_file(input: '../../../src/lib' / f, output: f, copy: true)} +endforeach diff --git a/build-support/assimulo/meson.build b/build-support/assimulo/meson.build new file mode 100644 index 00000000..f5c99ac9 --- /dev/null +++ b/build-support/assimulo/meson.build @@ -0,0 +1,12 @@ +# A mirror of the Cython sources under the package name (what setup.py copies to build/assimulo/), +# so that "from assimulo.ode cimport ODE" resolves and each .pyx is compiled as assimulo.. +stage = {} +foreach f : ['__init__.py', 'constants.pxi', + 'ode.pyx', 'ode.pxd', 'explicit_ode.pyx', 'explicit_ode.pxd', 'implicit_ode.pyx', 'implicit_ode.pxd', + 'algebraic.pyx', 'algebraic.pxd', 'problem.pyx', 'problem.pxd', 'special_systems.pyx', + 'support.pyx', 'support.pxd'] + stage += {f: configure_file(input: '../../src' / f, output: f, copy: true)} +endforeach +subdir('lib') +subdir('solvers') +subdir('thirdparty') diff --git a/build-support/assimulo/solvers/meson.build b/build-support/assimulo/solvers/meson.build new file mode 100644 index 00000000..694c6e01 --- /dev/null +++ b/build-support/assimulo/solvers/meson.build @@ -0,0 +1,3 @@ +foreach f : ['__init__.py', 'euler.pyx', 'sundials.pyx', 'kinsol.pyx'] + stage += {'solvers/' + f: configure_file(input: '../../../src/solvers' / f, output: f, copy: true)} +endforeach diff --git a/build-support/assimulo/thirdparty/meson.build b/build-support/assimulo/thirdparty/meson.build new file mode 100644 index 00000000..69423d8f --- /dev/null +++ b/build-support/assimulo/thirdparty/meson.build @@ -0,0 +1 @@ +subdir('radau5') diff --git a/build-support/assimulo/thirdparty/radau5/meson.build b/build-support/assimulo/thirdparty/radau5/meson.build new file mode 100644 index 00000000..af25fe90 --- /dev/null +++ b/build-support/assimulo/thirdparty/radau5/meson.build @@ -0,0 +1,3 @@ +foreach f : ['radau5ode.pyx', 'radau5ode.pxd'] + stage += {'thirdparty/radau5/' + f: configure_file(input: '../../../../thirdparty/radau5' / f, output: f, copy: true)} +endforeach diff --git a/build-support/meson.build b/build-support/meson.build new file mode 100644 index 00000000..b3531981 --- /dev/null +++ b/build-support/meson.build @@ -0,0 +1 @@ +subdir('assimulo') diff --git a/examples/meson.build b/examples/meson.build new file mode 100644 index 00000000..37ef91a5 --- /dev/null +++ b/examples/meson.build @@ -0,0 +1,9 @@ +# The examples ship inside the package (assimulo.examples); tests/test_examples.py runs them. +example_py = run_command(py, ['-c', 'import glob, os, sys; print("\\n".join(sorted(os.path.basename(f) for f in glob.glob(os.path.join(sys.argv[1], "*.py")))))', + meson.current_source_dir()], check: true).stdout().strip().split('\n') +example_files = [] +foreach f : example_py + example_files += files(f) +endforeach +py.install_sources(example_files, subdir: pkg / 'examples') +install_data('kinsol_ors_matrix.mtx', install_dir: py.get_install_dir() / pkg / 'examples') diff --git a/meson.build b/meson.build new file mode 100644 index 00000000..9710df6f --- /dev/null +++ b/meson.build @@ -0,0 +1,114 @@ +project('assimulo', 'c', + version: '3.8.0', + meson_version: '>= 1.1.0', + default_options: ['c_std=c99', 'warning_level=1']) + +# ---------------------------------------------------------------- tools and python +py = import('python').find_installation(pure: false) +py_dep = py.dependency() +cc = meson.get_compiler('c') +fs = import('fs') + +have_fortran = add_languages('fortran', native: false, required: get_option('fortran')) + +np_incdir = run_command(py, ['-c', 'import numpy; print(numpy.get_include())'], check: true).stdout().strip() +np_inc = include_directories(np_incdir) +f2py_srcdir = run_command(py, ['-c', 'import numpy.f2py, os; print(os.path.join(os.path.dirname(numpy.f2py.__file__), "src"))'], + check: true).stdout().strip() +f2py_inc = include_directories(f2py_srcdir) + +# Same flags as the numpy.distutils build (setup.py), so that both builds give identical numerics +c_flags = cc.get_supported_arguments(['-O2', '-fno-strict-aliasing', '-fwrapv', '-fno-merge-constants', '-msse', '-msse2', '-msse3']) +cython_c_flags = c_flags + ['-DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION'] # Cython modules only; f2py's C uses the older API +fortran_flags = [] +if have_fortran + fc = meson.get_compiler('fortran') + fortran_flags = fc.get_supported_arguments(['-O3', '-funroll-loops', '-fno-second-underscore', '-fPIC'] + get_option('extra-fortran-flags')) +endif + +# ---------------------------------------------------------------- SUNDIALS +sundials_home = get_option('sundials-home') +if sundials_home == '' + sundials_home = '/usr/local' +endif +sundials_incdir = sundials_home / 'include' +sundials_libdir = sundials_home / 'lib' +have_sundials = fs.exists(sundials_incdir / 'cvodes' / 'cvodes.h') +sundials_libs = [] +sundials_cython_env = [] +if have_sundials + sconf = run_command(py, [meson.current_source_dir() / 'tools' / 'sundials_config.py', sundials_incdir], check: true).stdout().strip().split(' ') + sundials_version = sconf[0].split('.') + sundials_index_bits = sconf[1] + sundials_with_superlu = sconf[2] == '1' + sundials_rtol_vec = sconf[3] == '1' + message('SUNDIALS @0@ found in @1@ (index @2@ bit, SuperLU_MT @3@)'.format(sconf[0], sundials_home, sundials_index_bits, sundials_with_superlu)) + sundials_libnames = ['sundials_cvodes', 'sundials_nvecserial', 'sundials_idas', 'sundials_sunlinsoldense', + 'sundials_sunlinsolspgmr', 'sundials_sunmatrixdense', 'sundials_sunmatrixsparse'] + if sundials_version[0].to_int() >= 7 + sundials_libnames += ['sundials_core'] + endif + kinsol_libnames = ['sundials_kinsol', 'sundials_nvecserial'] + if sundials_version[0].to_int() >= 7 + kinsol_libnames += ['sundials_core'] + endif +else + warning('SUNDIALS not found under ' + sundials_home + ': CVode, IDA and Kinsol will not be built (-Dsundials-home=...)') +endif + +# ---------------------------------------------------------------- SuperLU_MT +superlu_home = get_option('superlu-home') +have_superlu = false +superlu_libs = [] +superlu_inc = [] +if superlu_home != '' + # layouts: a SuperLU_MT source tree (SRC/), an install prefix (include/), or a conda-forge + # prefix whose sundials package ships the library (include/superlu_mt/, lib/) + # (slu_mt_ddefs.h is specific to SuperLU_MT; supermatrix.h also exists in plain SuperLU) + superlu_incdir = superlu_home / 'SRC' + foreach cand : [superlu_home / 'include', superlu_home / 'include' / 'superlu_mt'] + if not fs.exists(superlu_incdir / 'slu_mt_ddefs.h') + superlu_incdir = cand + endif + endforeach + if fs.exists(superlu_incdir / 'slu_mt_ddefs.h') + have_superlu = true + superlu_inc = include_directories(superlu_incdir) + superlu_libdir = superlu_home / 'lib' + superlu_libs = [cc.find_library('superlu_mt_OPENMP', dirs: [superlu_libdir], static: true), + cc.find_library('blas_OPENMP', dirs: [superlu_libdir], required: false)] + message('SuperLU_MT found in ' + superlu_home) + else + warning('SuperLU_MT not found under ' + superlu_home + ' (no slu_mt_ddefs.h): sparse solvers disabled') + endif +endif + +# ---------------------------------------------------------------- BLAS / LAPACK (GLIMDA, SuperLU) +blas_dirs = get_option('blas-home') != '' ? [get_option('blas-home')] : [] +lapack_dirs = get_option('lapack-home') != '' ? [get_option('lapack-home')] : [] +blas_dep = cc.find_library('blas', dirs: blas_dirs, required: false) +lapack_dep = cc.find_library('lapack', dirs: lapack_dirs, required: false) +m_dep = cc.find_library('m', required: false) +gomp_dep = cc.find_library('gomp', required: false) + +# ---------------------------------------------------------------- Cython +# The .pyx files cimport "assimulo.ode" etc.: build-support/assimulo/ holds copies of the .pxd +# files under that package name for the Cython include path (the sources live in src/). +# Cython is driven by tools/cythonize_one.py (a compile-time env with a version tuple cannot +# be passed on cython's command line). +subdir('build-support') +cythonize = [py, meson.current_source_dir() / 'tools' / 'cythonize_one.py'] +stage_dir = meson.current_build_dir() / 'build-support' +cython_inc = ['-I', stage_dir, '-I', stage_dir / 'assimulo', '-I', stage_dir / 'assimulo' / 'lib', + '-I', stage_dir / 'assimulo' / 'thirdparty' / 'radau5'] # same as setup.py's include_path +sundials_cython_env = [] +if have_sundials + sundials_cython_env = ['-E', 'SUNDIALS_VERSION=(@0@,@1@,@2@)'.format(sundials_version[0], sundials_version[1], sundials_version[2]), + '-E', 'SUNDIALS_WITH_SUPERLU=' + ((sundials_with_superlu and have_superlu) ? 'True' : 'False'), + '-E', 'SUNDIALS_VECTOR_SIZE="@0@"'.format(sundials_index_bits), + '-E', 'SUNDIALS_CVODE_RTOL_VEC=' + (sundials_rtol_vec ? 'True' : 'False')] +endif + +subdir('src') +subdir('thirdparty') +subdir('examples') diff --git a/meson.options b/meson.options new file mode 100644 index 00000000..cacf2c13 --- /dev/null +++ b/meson.options @@ -0,0 +1,12 @@ +option('sundials-home', type: 'string', value: '', + description: 'Prefix of the SUNDIALS installation (include/ and lib/ below it); empty: /usr/local') +option('superlu-home', type: 'string', value: '', + description: 'Prefix of SuperLU_MT (include/ or SRC/ with supermatrix.h, lib/ with libsuperlu_mt_OPENMP.a); empty: no sparse Radau5/CVode') +option('blas-home', type: 'string', value: '', + description: 'Directory containing libblas (GLIMDA, SuperLU); empty: compiler default paths') +option('lapack-home', type: 'string', value: '', + description: 'Directory containing liblapack (GLIMDA); empty: compiler default paths') +option('fortran', type: 'feature', value: 'auto', + description: 'Build the Fortran solvers (Dopri5, RodasODE, Radau5/Radar5 Fortran, LSODAR, ODASSL, DASP3, GLIMDA)') +option('extra-fortran-flags', type: 'array', value: ['--std=legacy'], + description: 'Extra Fortran compile flags') diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..ee5057e0 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,25 @@ +[build-system] +build-backend = "mesonpy" +requires = ["meson-python>=0.15.0", "Cython>=3.0", "numpy>=1.25"] + +[project] +name = "Assimulo" +version = "3.8.0" +description = "A package for solving ordinary differential equations and differential algebraic equations" +readme = "README.md" +license = {text = "LGPL-3.0"} +requires-python = ">=3.9" +dependencies = ["numpy", "scipy", "matplotlib"] +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)", + "Topic :: Scientific/Engineering :: Mathematics", +] + +[project.urls] +Homepage = "https://github.com/modelon-community/Assimulo" + +[tool.meson-python.args] +# The numerics of the shipped solvers are compared bit for bit against the numpy.distutils +# build (-O2 for C, -O3 -funroll-loops for Fortran); the flags live in meson.build. +setup = ["-Dbuildtype=release"] diff --git a/src/lib/meson.build b/src/lib/meson.build new file mode 100644 index 00000000..a056fbb9 --- /dev/null +++ b/src/lib/meson.build @@ -0,0 +1,3 @@ +py.install_sources(['__init__.py', 'radau_core.py'], subdir: pkg / 'lib') +sundials_pxi = files('sundials_includes.pxd', 'sundials_constants.pxi', 'sundials_callbacks.pxi', + 'sundials_callbacks_ida_cvode.pxi', 'sundials_callbacks_kinsol.pxi') diff --git a/src/meson.build b/src/meson.build new file mode 100644 index 00000000..4a0a6069 --- /dev/null +++ b/src/meson.build @@ -0,0 +1,33 @@ +# ---------------------------------------------------------------- package files +pkg = 'assimulo' +version_txt = configure_file(output: 'version.txt', command: [py, '-c', 'import sys; print("@0@")'.format(meson.project_version())], + capture: true) +install_data(version_txt, install_dir: py.get_install_dir() / pkg) +py.install_sources(['__init__.py', 'exception.py', 'problem_algebraic.py', + 'ode.pxd', 'explicit_ode.pxd', 'implicit_ode.pxd', 'algebraic.pxd', 'problem.pxd', 'support.pxd'], + subdir: pkg) +install_data(['../LICENSE', '../CHANGELOG', '../README.md'], install_dir: py.get_install_dir() / pkg) + +# ---------------------------------------------------------------- core Cython modules +core_pxd = files('ode.pxd', 'explicit_ode.pxd', 'implicit_ode.pxd', 'algebraic.pxd', 'problem.pxd', 'support.pxd', 'constants.pxi') + +src_inc = include_directories('.') # ode_event_locator.h, declared in explicit_ode.pxd + +core_modules = { + 'explicit_ode': ['ode_event_locator.c'], + 'algebraic': [], 'implicit_ode': [], 'ode': [], 'problem': [], 'special_systems': [], 'support': [], +} +foreach name, extra_c : core_modules + c_src = custom_target(name + '_cython', + input: stage[name + '.pyx'], output: name + '.c', + command: cythonize + ['@INPUT@', '@OUTPUT@', '-m', pkg + '.' + name] + cython_inc, + depend_files: core_pxd) + py.extension_module(name, [c_src] + extra_c, + include_directories: [np_inc, src_inc], + c_args: cython_c_flags, + dependencies: [py_dep], + install: true, subdir: pkg) +endforeach + +subdir('lib') +subdir('solvers') diff --git a/src/solvers/meson.build b/src/solvers/meson.build new file mode 100644 index 00000000..24204159 --- /dev/null +++ b/src/solvers/meson.build @@ -0,0 +1,36 @@ +py.install_sources(['__init__.py', 'dasp3.py', 'glimda.py', 'odassl.py', 'odepack.py', 'radar5.py', 'radau5.py', + 'rosenbrock.py', 'runge_kutta.py'], subdir: pkg / 'solvers') + +# Euler +euler_c = custom_target('euler_cython', input: stage['solvers/euler.pyx'], output: 'euler.c', + command: cythonize + ['@INPUT@', '@OUTPUT@', '-m', pkg + '.solvers.euler'] + cython_inc, depend_files: core_pxd) +py.extension_module('euler', euler_c, include_directories: [np_inc, src_inc], c_args: cython_c_flags, + dependencies: [py_dep], install: true, subdir: pkg / 'solvers') + +# SUNDIALS: CVode / IDA and Kinsol +if have_sundials + sundials_incs = [np_inc, src_inc, include_directories(sundials_incdir)] + sundials_deps = [py_dep] + foreach l : sundials_libnames + sundials_deps += cc.find_library(l, dirs: [sundials_libdir]) + endforeach + kinsol_deps = [py_dep] + foreach l : kinsol_libnames + kinsol_deps += cc.find_library(l, dirs: [sundials_libdir]) + endforeach + if sundials_with_superlu and have_superlu + sundials_deps += [cc.find_library('sundials_sunlinsolsuperlumt', dirs: [sundials_libdir])] + superlu_libs + kinsol_deps += superlu_libs + sundials_incs += [superlu_inc] + endif + sundials_c = custom_target('sundials_cython', input: stage['solvers/sundials.pyx'], output: 'sundials.c', + command: cythonize + ['@INPUT@', '@OUTPUT@', '-m', pkg + '.solvers.sundials'] + cython_inc + sundials_cython_env, + depend_files: core_pxd + sundials_pxi) + py.extension_module('sundials', sundials_c, include_directories: sundials_incs, c_args: cython_c_flags, + dependencies: sundials_deps, install: true, subdir: pkg / 'solvers') + kinsol_c = custom_target('kinsol_cython', input: stage['solvers/kinsol.pyx'], output: 'kinsol.c', + command: cythonize + ['@INPUT@', '@OUTPUT@', '-m', pkg + '.solvers.kinsol'] + cython_inc + sundials_cython_env, + depend_files: core_pxd + sundials_pxi) + py.extension_module('kinsol', kinsol_c, include_directories: sundials_incs, c_args: cython_c_flags, + dependencies: kinsol_deps, install: true, subdir: pkg / 'solvers') +endif diff --git a/tests/test_build_equivalence.py b/tests/test_build_equivalence.py new file mode 100644 index 00000000..95ece49d --- /dev/null +++ b/tests/test_build_equivalence.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2026 Modelon AB +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, version 3 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . + +"""Bit-for-bit equivalence of this build with a reference build. + + python tools/dump_examples.py reference.npz # with the reference build installed + ASSIMULO_REFERENCE_RESULTS=reference.npz pytest tests/test_build_equivalence.py + +Skipped when no reference file is given. The reference is specific to the machine and the +compilers (the point is to compare two builds of the same sources on the same machine, e.g. +the numpy.distutils build against the meson-python build). +""" +import os +import sys + +import pytest + +TOOLS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools") + + +@pytest.mark.skipif(not os.environ.get("ASSIMULO_REFERENCE_RESULTS"), + reason="set ASSIMULO_REFERENCE_RESULTS to a dump made with tools/dump_examples.py") +def test_examples_bit_identical_to_reference(tmp_path): + sys.path.insert(0, TOOLS) + import dump_examples + out, skipped = dump_examples.run_all() + assert not skipped, skipped + current = str(tmp_path / "current.npz") + dump_examples.save(current, out, skipped) + assert dump_examples.compare(os.environ["ASSIMULO_REFERENCE_RESULTS"], current) diff --git a/thirdparty/meson.build b/thirdparty/meson.build new file mode 100644 index 00000000..5ac8c526 --- /dev/null +++ b/thirdparty/meson.build @@ -0,0 +1,64 @@ +# ---------------------------------------------------------------- Radau5 (C) -> assimulo.lib.radau5ode +radau5_dir = 'radau5' +radau5_src = files(radau5_dir / 'radau5.c', radau5_dir / 'radau5_io.c') +radau5_c_args = cython_c_flags +radau5_deps = [py_dep, m_dep] +radau5_incs = [np_inc, src_inc, include_directories(radau5_dir)] +if have_superlu + radau5_src += files(radau5_dir / 'superlu_double.c', radau5_dir / 'superlu_complex.c', radau5_dir / 'superlu_util.c') + radau5_c_args += ['-D__RADAU5_WITH_SUPERLU'] + radau5_deps += superlu_libs + [blas_dep, gomp_dep] + radau5_incs += [superlu_inc] +endif +radau5ode_c = custom_target('radau5ode_cython', input: stage['thirdparty/radau5/radau5ode.pyx'], output: 'radau5ode.c', + command: cythonize + ['@INPUT@', '@OUTPUT@', '-m', pkg + '.thirdparty.radau5.radau5ode'] + cython_inc, # as setup.py; installed as assimulo.lib.radau5ode + depend_files: core_pxd + files(radau5_dir / 'radau5ode.pxd')) +py.extension_module('radau5ode', [radau5ode_c] + radau5_src, include_directories: radau5_incs, + c_args: radau5_c_args, dependencies: radau5_deps, install: true, subdir: pkg / 'lib') +install_data(radau5_dir / 'LICENSE_HAIRER', install_dir: py.get_install_dir() / pkg / 'lib') + +# ---------------------------------------------------------------- Fortran solvers (f2py) -> assimulo.lib.* +if have_fortran + f2py_gen = [py, meson.current_source_dir() / '..' / 'tools' / 'f2py_generate.py'] + fortranobject = files(f2py_srcdir / 'fortranobject.c') + + # name : [directory, signature file, fortran sources, extra fortran args, extra deps] + fortran_modules = { + 'dopri5': ['hairer', 'dopri5.pyf', ['dopri5.f'], [], []], + 'rodas': ['hairer', 'rodas_decsol.pyf', ['rodas_decsol.f'], [], []], + 'radau5': ['hairer', 'radau_decsol.pyf', ['radau_decsol.f'], [], []], + 'radar5': ['hairer', 'radar5.pyf', ['contr5.f90', 'radar5_int.f90', 'radar5.f90', 'dontr5.f90', 'decsol.f90', 'dc_decdel.f90'], [], []], + 'odepack': ['odepack', 'odepack.pyf', ['opkdmain.f', 'opkda1.f', 'opkda2.f', 'odepack_aux.f90'], [], []], + 'odassl': ['odassl', 'odassl.pyf', ['odassl.f', 'odastp.f', 'odacor.f', 'odajac.f', 'd1mach.f', 'daxpy.f', 'ddanrm.f', 'ddatrp.f', + 'ddot.f', 'ddwats.f', 'dgefa.f', 'dgesl.f', 'dscal.f', 'idamax.f', 'xerrwv.f'], [], []], + 'dasp3dp': ['dasp3', 'dasp3dp.pyf', ['DASP3.f', 'ANORM.f', 'CTRACT.f', 'DECOMP.f', 'HMAX.f', 'INIVAL.f', 'JACEST.f', 'PDERIV.f', + 'PREPOL.f', 'SOLVE.f', 'SPAPAT.f'], ['-fdefault-double-8', '-fdefault-real-8'], []], + } + if blas_dep.found() and lapack_dep.found() + fortran_modules += {'glimda': ['glimda', 'glimda_complete.pyf', ['glimda_complete.f'], [], [lapack_dep, blas_dep]]} + else + warning('BLAS/LAPACK not found: GLIMDA will not be built (-Dblas-home=... -Dlapack-home=...)') + endif + + foreach name, spec : fortran_modules + dir = spec[0] + f_src = [] + foreach f : spec[2] + f_src += files(dir / f) + endforeach + gen = custom_target(name + '_f2py', + input: dir / spec[1], + output: [name + 'module.c', name + '-f2pywrappers.f', name + '-f2pywrappers2.f90'], + command: f2py_gen + ['@INPUT@', '@OUTDIR@', name]) + py.extension_module(name, [gen, fortranobject] + f_src, + include_directories: [np_inc, f2py_inc], + c_args: c_flags, + fortran_args: fortran_flags + spec[3], + dependencies: [py_dep] + spec[4], + install: true, subdir: pkg / 'lib') + lic = dir / 'LICENSE_' + (dir == 'hairer' ? 'HAIRER' : dir.to_upper()) + if fs.exists(lic) + install_data(lic, install_dir: py.get_install_dir() / pkg / 'lib') + endif + endforeach +endif diff --git a/tools/cythonize_one.py b/tools/cythonize_one.py new file mode 100644 index 00000000..8302b48f --- /dev/null +++ b/tools/cythonize_one.py @@ -0,0 +1,35 @@ +"""Cythonize one .pyx for meson, with a compile-time environment (the SUNDIALS facts) that +cannot be passed on cython's command line (tuples split at commas). + + python tools/cythonize_one.py -m [-I dir ...] [-E NAME=PYTHON_LITERAL ...] +""" +import ast, os, sys + +from Cython.Compiler import Options +from Cython.Compiler.Main import CompilationOptions, compile_single, default_options + +args = sys.argv[1:] +pyx, out = args[0], args[1] +include_path, env, module = [], {}, None +i = 2 +while i < len(args): + if args[i] == "-m": + module = args[i + 1]; i += 2 + elif args[i] == "-I": + include_path.append(args[i + 1]); i += 2 + elif args[i] == "-E": + name, value = args[i + 1].split("=", 1) + env[name] = ast.literal_eval(value); i += 2 + else: + sys.exit("unknown argument %s" % args[i]) + +options = CompilationOptions(default_options) +options.include_path = include_path +options.output_file = out +options.compile_time_env = env +options.language_level = "3str" +options.compiler_directives = {"language_level": "3str"} +options.emit_linenums = False +result = compile_single(pyx, options, full_module_name=module) +if result.num_errors: + sys.exit(1) diff --git a/tools/dump_examples.py b/tools/dump_examples.py new file mode 100644 index 00000000..208370a1 --- /dev/null +++ b/tools/dump_examples.py @@ -0,0 +1,116 @@ +"""Run every Assimulo example and dump solver trajectories + statistics, so that two builds of +Assimulo (e.g. the numpy.distutils build and the meson-python build, or two compilers) can be +compared bit for bit. + + python tools/dump_examples.py OUT.npz # dump with the currently installed assimulo + python tools/dump_examples.py --compare A.npz B.npz + +tests/test_build_equivalence.py runs the same comparison against the file named by the +environment variable ASSIMULO_REFERENCE_RESULTS. + +Records per example: t_sol, y_sol (and yd_sol for implicit problems), the statistics dict, and +for Kinsol the solution vector. Examples that need a missing solver are skipped and listed. +""" +import importlib, io, json, os, sys, contextlib, traceback +import numpy as np + + + +def run_all(): + """Runs the examples of the *installed* assimulo package (assimulo.examples).""" + import matplotlib + matplotlib.use("Agg") + import assimulo.examples as ex + examples_dir = os.path.dirname(ex.__file__) + out, skipped = {}, {} + for f in sorted(os.listdir(examples_dir)): + if not f.endswith(".py") or f == "__init__.py": + continue + name = f[:-3] + try: + mod = importlib.import_module("assimulo.examples." + name) + if not hasattr(mod, "run_example"): + continue + with contextlib.redirect_stdout(io.StringIO()): + try: + res = mod.run_example(with_plots=False) + except TypeError: + res = mod.run_example() + except Exception as e: + skipped[name] = "%s: %s" % (type(e).__name__, str(e)[:120]) + continue + objs = res if isinstance(res, tuple) else (res,) + rec = {} + for o in objs: + for attr in ("t_sol", "y_sol", "yd_sol"): + if hasattr(o, attr) and getattr(o, attr) is not None and len(getattr(o, attr)): + rec[attr] = np.asarray(getattr(o, attr), dtype=float) + if hasattr(o, "statistics"): + st = o.statistics + try: + rec["statistics"] = {k: float(st[k]) for k in st.statistics.keys()} + except Exception: + pass + if hasattr(o, "y") and "y_sol" not in rec: # Kinsol: solution vector + try: + rec["y"] = np.asarray(o.y, dtype=float) + except Exception: + pass + out[name] = rec + return out, skipped + + +def save(path, out, skipped): + flat = {} + for name, rec in out.items(): + for k, v in rec.items(): + if k == "statistics": + flat[name + "/statistics"] = np.array(json.dumps(v, sort_keys=True)) + else: + flat[name + "/" + k] = v + flat["__skipped__"] = np.array(json.dumps(skipped, sort_keys=True)) + import assimulo + flat["__assimulo_file__"] = np.array(assimulo.__file__) + np.savez_compressed(path, **flat) + + +def compare(a_path, b_path): + A, B = np.load(a_path), np.load(b_path) + print("A:", str(A["__assimulo_file__"]), "\nB:", str(B["__assimulo_file__"])) + keys = sorted(set(A.files) | set(B.files)) + ident, differ, missing = 0, [], [] + for k in keys: + if k.startswith("__"): + continue + if k not in A.files or k not in B.files: + missing.append(k); continue + a, b = A[k], B[k] + if a.dtype.kind in "US": + same = str(a) == str(b) + if not same: + differ.append((k, "statistics differ: %s vs %s" % (str(a)[:80], str(b)[:80]))) + else: + ident += 1 + continue + if a.shape != b.shape: + differ.append((k, "shape %s vs %s" % (a.shape, b.shape))); continue + if np.array_equal(a, b): + ident += 1 + else: + d = np.abs(a - b); rel = d.max() / (np.abs(a).max() + 1e-300) + differ.append((k, "max abs diff %.3e, rel %.3e, %d of %d entries" % (d.max(), rel, int((d > 0).sum()), a.size))) + print("identical arrays/statistics: %d; differing: %d; missing on one side: %d" % (ident, len(differ), len(missing))) + for k, msg in differ: + print(" DIFF %-45s %s" % (k, msg)) + for k in missing: + print(" MISSING %s" % k) + print("skipped A:", str(A["__skipped__"])); print("skipped B:", str(B["__skipped__"])) + return len(differ) == 0 and len(missing) == 0 + + +if __name__ == "__main__": + if sys.argv[1] == "--compare": + sys.exit(0 if compare(sys.argv[2], sys.argv[3]) else 1) + out, skipped = run_all() + save(sys.argv[1], out, skipped) + print("dumped %d examples, skipped %d: %s" % (len(out), len(skipped), json.dumps(skipped, indent=1) if skipped else "")) diff --git a/tools/f2py_generate.py b/tools/f2py_generate.py new file mode 100644 index 00000000..6f206a7d --- /dev/null +++ b/tools/f2py_generate.py @@ -0,0 +1,18 @@ +"""Run f2py on a .pyf signature file for meson and make sure every declared output exists. + + python tools/f2py_generate.py + +f2py writes module.c and, only when the wrapped routines need them, +-f2pywrappers.f / -f2pywrappers2.f90; meson's custom_target needs +a fixed list of outputs, so missing wrapper files are created empty (an empty +Fortran source compiles to an empty object). +""" +import os, subprocess, sys + +pyf, outdir, module = sys.argv[1:4] +os.makedirs(outdir, exist_ok=True) +subprocess.check_call([sys.executable, "-m", "numpy.f2py", "--build-dir", outdir, pyf]) +for name in ("%smodule.c" % module, "%s-f2pywrappers.f" % module, "%s-f2pywrappers2.f90" % module): + p = os.path.join(outdir, name) + if not os.path.exists(p): + open(p, "w").close() diff --git a/tools/sundials_config.py b/tools/sundials_config.py new file mode 100644 index 00000000..8f6e4cf2 --- /dev/null +++ b/tools/sundials_config.py @@ -0,0 +1,29 @@ +"""Print SUNDIALS build facts for meson: version, index size, SuperLU_MT and rtol-vector support. + + python tools/sundials_config.py + +Output (one line): major.minor.patch index_bits superlu(0|1) rtolvec(0|1) +Mirrors what setup.py's check_SUNDIALS() reads from sundials/sundials_config.h. +""" +import os, sys + +inc = sys.argv[1] +path = os.path.join(inc, "sundials", "sundials_config.h") +if not os.path.exists(path): + sys.exit("no sundials_config.h under %s" % inc) +version, bits, superlu, rtolvec = None, "32", 0, 0 +with open(path) as f: + for line in f: + if line.startswith("#define") and ("SUNDIALS_PACKAGE_VERSION" in line or "SUNDIALS_VERSION " in line): + version = line.split()[-1].strip('"').split("-dev")[0] + elif line.startswith("#define") and "SUNDIALS_INT64_T" in line: + bits = "64" + elif line.startswith("#define") and "SUNDIALS_INT32_T" in line: + bits = "32" + elif line.startswith("#define") and "SUNDIALS_SUPERLUMT" in line: + superlu = 1 + elif line.startswith("#define") and "SUNDIALS_CVODE_RTOL_VEC" in line: + rtolvec = 1 +if version is None: + sys.exit("no SUNDIALS version in %s" % path) +print(version, bits, superlu, rtolvec)