From 4835dfa4806c6476afcf8dae3c3589ced17377ad Mon Sep 17 00:00:00 2001 From: Alexander Blech Date: Tue, 10 Nov 2026 03:56:32 +0100 Subject: [PATCH 1/7] Configure ruff with the agreed lint rules Line length stays at the default of 88. The data tables are excluded, as they will move out of the package. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 04cc6b4..dec9c3e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -83,3 +83,31 @@ testpaths = ["tests"] # Turn warnings into errors. Ignore a warning only with an explicit filter and a # comment giving the reason. filterwarnings = ["error"] + +[tool.ruff] +# The data tables are left as they are, as they will move out of the package. +# Code examples in Markdown keep their hand-written layout. +extend-exclude = ["src/openquad/data/", "*.md"] + +[tool.ruff.lint] +select = [ + "E", # pycodestyle errors + "F", # pyflakes + "W", # pycodestyle warnings + "I", # isort + "B", # flake8-bugbear + "UP", # pyupgrade + "C4", # flake8-comprehensions + "NPY", # NumPy-specific rules + "PT", # flake8-pytest-style + "PIE", # flake8-pie + "RET", # flake8-return + "RUF", # ruff-specific rules + "SIM", # flake8-simplify + "PTH", # flake8-use-pathlib + "PGH", # pygrep-hooks + "FURB", # refurb +] + +[tool.ruff.lint.isort] +known-first-party = ["openquad"] From 4aa495be66486314e0cce6b8bd1b701285b01b3f Mon Sep 17 00:00:00 2001 From: Alexander Blech Date: Tue, 10 Nov 2026 03:59:42 +0100 Subject: [PATCH 2/7] Use raw docstrings where they contain LaTeX \theta was read as a tab and \phi as an invalid escape. Since warnings fail the tests, editing these files made the suite fail on import. Co-Authored-By: Claude Opus 5.5 --- src/openquad/fibonacci.py | 2 +- src/openquad/grid.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/openquad/fibonacci.py b/src/openquad/fibonacci.py index 0328dac..d2c173d 100644 --- a/src/openquad/fibonacci.py +++ b/src/openquad/fibonacci.py @@ -56,7 +56,7 @@ class FibonacciSphere(AtomicS2Quadrature, QuadratureWithoutDegree): #TODO: is there a restriction for the available sizes? def _points_weights(self): - """Spherical Fibonacci point sets for S2 quadrature. + r"""Spherical Fibonacci point sets for S2 quadrature. Algorithm taken from Eq. (4) in Marques et al., Computer Graphics Forum 32, 8 (2013) diff --git a/src/openquad/grid.py b/src/openquad/grid.py index 1cbb5b0..3808c08 100644 --- a/src/openquad/grid.py +++ b/src/openquad/grid.py @@ -8,7 +8,7 @@ def angles_from_xyz(xyz, axis=0): - """Calculate the spherical polar angles of a set of cartesian + r"""Calculate the spherical polar angles of a set of cartesian coordinates. $\theta$ denotes the polar angle, while $\phi$ denotes the azimuthal angle. @@ -37,7 +37,7 @@ def angles_from_xyz(xyz, axis=0): def xyz_from_angles(theta_phi, axis=0): - """Calculate the cartesian coordinates from a set of spherical + r"""Calculate the cartesian coordinates from a set of spherical polar angles. $\theta$ denotes the polar angle, while $\phi$ denotes the azimuthal angle. From f3fde52c38ffb0d84709b2184990f1d1dcb5c06f Mon Sep 17 00:00:00 2001 From: Alexander Blech Date: Tue, 10 Nov 2026 04:00:59 +0100 Subject: [PATCH 3/7] Format code with ruff Formatting only, produced by ruff 0.17.2. Syntax trees are unchanged up to whitespace in docstrings. Co-Authored-By: Claude Opus 5.5 --- doc/conf.py | 48 ++-- src/conftest.py | 3 +- src/openquad/__init__.py | 4 +- src/openquad/base.py | 44 ++-- src/openquad/fibonacci.py | 29 ++- src/openquad/gauss.py | 26 +-- src/openquad/geometries.py | 284 ++++++++++++----------- src/openquad/graef.py | 22 +- src/openquad/grid.py | 44 ++-- src/openquad/karney.py | 7 +- src/openquad/lebedev.py | 5 +- src/openquad/monte_carlo.py | 70 +++--- src/openquad/newton_cotes.py | 43 ++-- src/openquad/womersley.py | 30 ++- tests/test_Rn_quadrature.py | 162 +++++++------ tests/test_S2_quadrature.py | 170 ++++++++------ tests/test_SO3_quadrature.py | 215 ++++++++++------- tests/test_base_1d_quadrature_methods.py | 31 +-- tests/test_base_2d_quadrature_methods.py | 43 ++-- tests/test_base_3d_quadrature_methods.py | 50 ++-- 20 files changed, 717 insertions(+), 613 deletions(-) diff --git a/doc/conf.py b/doc/conf.py index 3b262dc..6ac175f 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -12,9 +12,9 @@ # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information -project = 'OpenQuad' -copyright = '2024, OpenQuad developers' -author = 'Alexander Blech et al.' +project = "OpenQuad" +copyright = "2024, OpenQuad developers" +author = "Alexander Blech et al." release = openquad.__version__ # -- General configuration --------------------------------------------------- @@ -25,21 +25,19 @@ # nitpick_ignore = [("py:class", "callable")] extensions = [ - 'autoapi.extension', - 'sphinx.ext.intersphinx', - 'sphinx.ext.doctest', - 'sphinx_design', - 'sphinx_copybutton', - 'numpydoc', + "autoapi.extension", + "sphinx.ext.intersphinx", + "sphinx.ext.doctest", + "sphinx_design", + "sphinx_copybutton", + "numpydoc", ] -intersphinx_mapping = get_intersphinx_mapping( -packages={"python", "numpy", "scipy"} -) -#intersphinx_disabled_reftypes = ["*"] +intersphinx_mapping = get_intersphinx_mapping(packages={"python", "numpy", "scipy"}) +# intersphinx_disabled_reftypes = ["*"] -templates_path = ['_templates'] -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +templates_path = ["_templates"] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # Will be included in the beginning of every RST file rst_prolog = """ @@ -49,7 +47,7 @@ # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output -html_theme = 'pydata_sphinx_theme' +html_theme = "pydata_sphinx_theme" html_theme_options = { "logo": { @@ -76,22 +74,22 @@ "footer_center": ["sphinx-version"], "navbar_end": [ "theme-switcher", - #"version-switcher", + # "version-switcher", "navbar-icon-links", ], "use_edit_page_button": False, "navbar_align": "content", - #"show_version_warning_banner": True, + # "show_version_warning_banner": True, "show_toc_level": 2, - "show_nav_level": 2, #TODO - "navigation_depth": 4, #TODO - #"collapse_navigation": True, - "announcement": "https://raw.githubusercontent.com/qucontrol/openquad/main/doc/_templates/announcement_banner.html" + "show_nav_level": 2, # TODO + "navigation_depth": 4, # TODO + # "collapse_navigation": True, + "announcement": "https://raw.githubusercontent.com/qucontrol/openquad/main/doc/_templates/announcement_banner.html", } -html_static_path = ['_static'] -html_css_files = ['openquad.css'] +html_static_path = ["_static"] +html_css_files = ["openquad.css"] html_copy_source = False html_show_sourcelink = False @@ -117,6 +115,7 @@ "inherited-members", ] + def skip_submodules(app, what, name, obj, skip, options): if what == "module": skip = True @@ -124,6 +123,7 @@ def skip_submodules(app, what, name, obj, skip, options): skip = True return skip + # ----------------------------------------------------------------------------- def setup(sphinx): sphinx.connect("autoapi-skip-member", skip_submodules) diff --git a/src/conftest.py b/src/conftest.py index 4cf2bf0..d856db7 100644 --- a/src/conftest.py +++ b/src/conftest.py @@ -3,10 +3,11 @@ This file is automatically evaluated by pytest. It ensures that we can write doctests without distracting import statements in the doctest. """ + import pytest import numpy as np @pytest.fixture(autouse=True) def set_doctest_env(doctest_namespace): - doctest_namespace['np'] = np + doctest_namespace["np"] = np diff --git a/src/openquad/__init__.py b/src/openquad/__init__.py index cc7c54c..fe4c326 100644 --- a/src/openquad/__init__.py +++ b/src/openquad/__init__.py @@ -2,12 +2,12 @@ # SPDX-FileCopyrightText: 2024 Alexander Blech # SPDX-License-Identifier: MPL-2.0 -__version__ = '0.3.0+dev' +__version__ = "0.3.0+dev" # Expose top-level interface from .geometries import Rn, S2, SO3 -__all__ = ['Rn', 'S2', 'SO3'] +__all__ = ["Rn", "S2", "SO3"] # Expose submodules from . import ( diff --git a/src/openquad/base.py b/src/openquad/base.py index 3bece4d..6ba6bd9 100644 --- a/src/openquad/base.py +++ b/src/openquad/base.py @@ -7,12 +7,11 @@ import numpy as np -QUAD_DATA_DIR = (Path.cwd() / __file__).parent / 'data' +QUAD_DATA_DIR = (Path.cwd() / __file__).parent / "data" """Directory where quadrature grids are stored.""" class AtomicQuadrature(ABC): - @property @abstractmethod def dim(self): @@ -45,8 +44,10 @@ def _check_size_allowed(self, value): raise ValueError("`size` must be larger than zero") if hasattr(self, "_available_sizes"): if value not in self._available_sizes: - msg = (f"`size` {value} not available. Possible values are:" - f"{self._available_sizes}") + msg = ( + f"`size` {value} not available. Possible values are:" + f"{self._available_sizes}" + ) raise ValueError(msg) @property @@ -71,8 +72,10 @@ def _check_degree_allowed(self, value): raise ValueError("`degree` must not be negative") if hasattr(self, "_available_degrees"): if value not in self._available_degrees: - msg = (f"`degree` {value} not available. Possible values are:" - f"{self._available_degrees}") + msg = ( + f"`degree` {value} not available. Possible values are:" + f"{self._available_degrees}" + ) raise ValueError(msg) def __init__(self, *pw_args, jacobian=None, **pw_kwargs): @@ -85,7 +88,7 @@ def __init__(self, *pw_args, jacobian=None, **pw_kwargs): w = self._apply_jacobian(x, w, jacobian) self.points = x self.weights = w - #TODO: ensure that points are contiguous? + # TODO: ensure that points are contiguous? # Maybe necessary for reliable reshaping? @abstractmethod @@ -102,18 +105,19 @@ def _points_weights(self, **kwargs): msg = f"{self.__class__} missing method _points_weights" raise NotImplementedError(msg) - def _load_points_weights(self, folder, type, suffix=''): + def _load_points_weights(self, folder, type, suffix=""): if self.degree is not None: filename = f"{type}_size{self.size}_degree{self.degree}{suffix}.npy" else: filename = f"{type}_size{self.size}{suffix}.npy" - data = np.load(QUAD_DATA_DIR / folder / filename, - allow_pickle=False, fix_imports=False) - if data.shape[0] not in [self.dim, self.dim+1]: + data = np.load( + QUAD_DATA_DIR / folder / filename, allow_pickle=False, fix_imports=False + ) + if data.shape[0] not in [self.dim, self.dim + 1]: raise TypeError( f"Read data has wrong shape {data.shape} for dim {self.dim}" ) - points = data[0:self.dim] + points = data[0 : self.dim] if data.shape[0] == self.dim + 1: weights = data[-1] else: @@ -121,7 +125,8 @@ def _load_points_weights(self, folder, type, suffix=''): return points, weights def _apply_jacobian(self, x, w, jacobian): - if self.dim == 1: x = np.expand_dims(x, 0) + if self.dim == 1: + x = np.expand_dims(x, 0) try: w = w * jacobian(*x) except: @@ -154,7 +159,6 @@ def _integrate_sample(self, f_samples, axis=-1): class QuadratureWithoutDegree(AtomicQuadrature): - def __init__(self, size, *args, **kwargs): self.size = size self.degree = None @@ -162,7 +166,6 @@ def __init__(self, size, *args, **kwargs): class QuadratureWithFixedDegree(AtomicQuadrature): - def __init__(self, size, *args, **kwargs): self.size = size self.degree = self._get_degree() @@ -182,7 +185,6 @@ def _get_degree(self): class QuadratureWithDegree(AtomicQuadrature): - def __init__(self, *args, size=None, degree=None, **kwargs): if size is not None and degree is None: self.size = size @@ -203,7 +205,7 @@ def _get_size(self, degree): overwritten in the corresponding child class. """ - if hasattr(self, '_available_sizes'): + if hasattr(self, "_available_sizes"): selection = np.nonzero(self._available_degrees == degree) return self._available_sizes[selection].min() else: @@ -219,7 +221,7 @@ def _get_degree(self, size): be overwritten in the corresponding child class. """ - if hasattr(self, '_available_degrees'): + if hasattr(self, "_available_degrees"): selection = np.nonzero(self._available_sizes == size) return self._available_degrees[selection].max() else: @@ -228,7 +230,6 @@ def _get_degree(self, size): class AtomicR1Quadrature(AtomicQuadrature): - dim = 1 @property @@ -244,14 +245,13 @@ def __init__(self, a, b, *args, periodic=False, **kwargs): raise ValueError("`a` must not be equal to `b`") self._periodic = periodic super().__init__(*args, a=a, b=b, **kwargs) - if self._periodic and self._has_endpoints: # drop endpoint + if self._periodic and self._has_endpoints: # drop endpoint self.weights[0] += self.weights[-1] self.weights = self.weights[:-1] self.points = self.points[:-1] class AtomicS2Quadrature(AtomicQuadrature): - dim = 2 def __init__(self, *args, swap_angles=False, **kwargs): @@ -265,7 +265,6 @@ def __init__(self, *args, swap_angles=False, **kwargs): class AtomicSO3Quadrature(AtomicQuadrature): - dim = 3 def __init__(self, *args, **kwargs): @@ -274,7 +273,6 @@ def __init__(self, *args, **kwargs): class NoQuadrature(ABC): - dim = 1 def __init__(self, points, *args, **kwargs): diff --git a/src/openquad/fibonacci.py b/src/openquad/fibonacci.py index d2c173d..7bca2d5 100644 --- a/src/openquad/fibonacci.py +++ b/src/openquad/fibonacci.py @@ -5,7 +5,7 @@ from functools import lru_cache import numpy as np -from .base import (AtomicSO3Quadrature, AtomicS2Quadrature, QuadratureWithoutDegree) +from .base import AtomicSO3Quadrature, AtomicS2Quadrature, QuadratureWithoutDegree @lru_cache(maxsize=100) @@ -28,7 +28,7 @@ def fibonacci(i): elif i < 2: return i else: - return fibonacci(i-1) + fibonacci(i-2) + return fibonacci(i - 1) + fibonacci(i - 2) def _get_available_sizes_for_ZCW2(max_size): @@ -46,14 +46,13 @@ def _get_available_sizes_for_ZCW2(max_size): current_size = -1 while max_size > current_size: M += 1 - current_size = fibonacci(M_offset+M+2) + current_size = fibonacci(M_offset + M + 2) available_sizes.append(current_size) return np.asarray(available_sizes) class FibonacciSphere(AtomicS2Quadrature, QuadratureWithoutDegree): - - #TODO: is there a restriction for the available sizes? + # TODO: is there a restriction for the available sizes? def _points_weights(self): r"""Spherical Fibonacci point sets for S2 quadrature. @@ -73,16 +72,15 @@ def _points_weights(self): """ N = self.size j = np.arange(self.size) - theta = np.arccos(1 - (2*j + 1) / N) - phi = (4*np.pi * j / (1+np.sqrt(5))) % (2*np.pi) + theta = np.arccos(1 - (2 * j + 1) / N) + phi = (4 * np.pi * j / (1 + np.sqrt(5))) % (2 * np.pi) points = np.stack((theta, phi), axis=0) - weights = np.ones(self.size) / self.size * (4*np.pi) + weights = np.ones(self.size) / self.size * (4 * np.pi) return points, weights class ZCW2(AtomicS2Quadrature, QuadratureWithoutDegree): - - _TABLE = _get_available_sizes_for_ZCW2(max_size=1e+7) + _TABLE = _get_available_sizes_for_ZCW2(max_size=1e7) _available_sizes = _TABLE def _points_weights(self): @@ -100,15 +98,15 @@ def _points_weights(self): """ M_offset = 6 - c = [1, 2, 1] # for integration of full sphere + c = [1, 2, 1] # for integration of full sphere N = self.size M = self._get_M(N) g_M = fibonacci(M + M_offset) j = np.arange(self.size) - theta = np.arccos(c[0] * (c[1] * np.mod(j/N, 1) - 1)) - phi = 2*np.pi / c[2] * np.mod(j*g_M/N, 1) + theta = np.arccos(c[0] * (c[1] * np.mod(j / N, 1) - 1)) + phi = 2 * np.pi / c[2] * np.mod(j * g_M / N, 1) points = np.stack((theta, phi), axis=0) - weights = np.ones(self.size) / self.size * (4*np.pi) + weights = np.ones(self.size) / self.size * (4 * np.pi) return points, weights def _get_M(self, N): @@ -126,7 +124,6 @@ def _get_M(self, N): class ZCW3(AtomicSO3Quadrature, QuadratureWithoutDegree): - def _points_weights(self): """ZCW method for SO3 quadrature. @@ -141,4 +138,4 @@ def _points_weights(self): """ raise NotImplementedError("ZCW3 not yet implemented") - #TODO + # TODO diff --git a/src/openquad/gauss.py b/src/openquad/gauss.py index 8a95636..07c0b44 100644 --- a/src/openquad/gauss.py +++ b/src/openquad/gauss.py @@ -9,7 +9,6 @@ class GaussLegendre(AtomicR1Quadrature, QuadratureWithDegree): - _has_endpoints = False def _get_size(self, degree): @@ -20,12 +19,12 @@ def _get_degree(self, size): def _points_weights(self, a, b): """Calculate Gauss-Legendre quadrature points and weights. - + This function returns the quadrature points and weights suitable for integrating a function on the interval :math:`[a, b]`. The Jacobian for the transformation from the interval :math:`[-1, 1]` to :math:`[a, b]` is already included in the weights. - + Parameters ---------- size : int @@ -36,21 +35,20 @@ def _points_weights(self, a, b): Lower limit of integration. b : float Upper limit of integration. - + Returns ------- points : ndarray Sample points. weights : ndarray Quadrature weights. - + """ x, w = special.roots_legendre(self.size) - return (b-a)/2 * x + (a+b)/2, w * (b-a)/2 + return (b - a) / 2 * x + (a + b) / 2, w * (b - a) / 2 class GaussLobattoLegendre(AtomicR1Quadrature, QuadratureWithDegree): - _has_endpoints = True def _get_size(self, degree): @@ -93,11 +91,11 @@ def _points_weights(self, a, b): """ N = self.size if N < 2: - msg = ("Gauss-Lobatto rule requires at least two sample points") + msg = "Gauss-Lobatto rule requires at least two sample points" raise ValueError(msg) - coeffs = np.append(np.zeros(N-1), 1) - x = np.concatenate(([-1.0], - np.polynomial.legendre.Legendre(coeffs).deriv().roots(), - [1.0])) - w = 2 / (N*(N-1) * special.eval_legendre(N-1, x)**2) - return (b-a)/2 * x + (a+b)/2, w * (b-a)/2 + coeffs = np.append(np.zeros(N - 1), 1) + x = np.concatenate( + ([-1.0], np.polynomial.legendre.Legendre(coeffs).deriv().roots(), [1.0]) + ) + w = 2 / (N * (N - 1) * special.eval_legendre(N - 1, x) ** 2) + return (b - a) / 2 * x + (a + b) / 2, w * (b - a) / 2 diff --git a/src/openquad/geometries.py b/src/openquad/geometries.py index 4dcefa0..55c1356 100644 --- a/src/openquad/geometries.py +++ b/src/openquad/geometries.py @@ -8,6 +8,7 @@ #TODO """ + from abc import ABC, abstractmethod from copy import deepcopy import numpy as np @@ -30,69 +31,68 @@ # TODO: move to submodule? class GeometryQuadrature(ABC): - _available_methods = { - 'none': NoQuadrature, + "none": NoQuadrature, # 1d methods: - 'composite trapezoid': CompositeTrapezoid, - 'composite simpson': CompositeSimpson, - 'romberg': Romberg, - 'gausslegendre': GaussLegendre, - 'gausslobattolegendre': GaussLobattoLegendre, - '1d-montecarlo': MonteCarloR1, + "composite trapezoid": CompositeTrapezoid, + "composite simpson": CompositeSimpson, + "romberg": Romberg, + "gausslegendre": GaussLegendre, + "gausslobattolegendre": GaussLobattoLegendre, + "1d-montecarlo": MonteCarloR1, # two-angle methods: - 's2-gauss-lebedevlaikov': LebedevLaikov, - 's2-gauss-graef': GraefS2Gauss, - 's2-design-graef': GraefS2Design, - 's2-design-womersley': WomersleyS2Design, - 's2-covering-fibonacci': FibonacciSphere, - 's2-covering-zcw': ZCW2, - 's2-montecarlo': MonteCarloS2, + "s2-gauss-lebedevlaikov": LebedevLaikov, + "s2-gauss-graef": GraefS2Gauss, + "s2-design-graef": GraefS2Design, + "s2-design-womersley": WomersleyS2Design, + "s2-covering-fibonacci": FibonacciSphere, + "s2-covering-zcw": ZCW2, + "s2-montecarlo": MonteCarloS2, # three-angle methods: - 'so3-covering-karney': KarneySO3, - 'so3-gauss-graef': GraefSO3Gauss, - 'so3-chebyshev-graef': GraefSO3Chebyshev, - 'so3-chebyshev-womersley': WomersleySO3Chebyshev, - 'so3-covering-zcw': ZCW3, - 'so3-montecarlo': MonteCarloSO3, + "so3-covering-karney": KarneySO3, + "so3-gauss-graef": GraefSO3Gauss, + "so3-chebyshev-graef": GraefSO3Chebyshev, + "so3-chebyshev-womersley": WomersleySO3Chebyshev, + "so3-covering-zcw": ZCW3, + "so3-montecarlo": MonteCarloSO3, } _method_aliases = { # dummy quadrature - 'none': 'none', + "none": "none", # composite trapezoid rule - 'composite trapezoid': 'composite trapezoid', - 'trapezoid': 'composite trapezoid', + "composite trapezoid": "composite trapezoid", + "trapezoid": "composite trapezoid", # composite simpson rule - 'composite simpson': 'composite simpson', - 'simpson': 'composite simpson', + "composite simpson": "composite simpson", + "simpson": "composite simpson", # Romberg integration - 'romberg': 'romberg', + "romberg": "romberg", # Gauss-Legendre quadrature - 'gausslegendre': 'gausslegendre', + "gausslegendre": "gausslegendre", # Gauss-Lobatto-Legendre - 'gausslobattolegendre': 'gausslobattolegendre', + "gausslobattolegendre": "gausslobattolegendre", # Lebedev Laikov - 's2-gauss-lebedevlaikov': 's2-gauss-lebedevlaikov', - 'lebedevlaikov': 's2-gauss-lebedevlaikov', - 'lebedev': 's2-gauss-lebedevlaikov', + "s2-gauss-lebedevlaikov": "s2-gauss-lebedevlaikov", + "lebedevlaikov": "s2-gauss-lebedevlaikov", + "lebedev": "s2-gauss-lebedevlaikov", # 1d Monte-Carlo - '1d-montecarlo': '1d-montecarlo', + "1d-montecarlo": "1d-montecarlo", # two-angle Monte-Carlo - 's2-montecarlo': 's2-montecarlo', + "s2-montecarlo": "s2-montecarlo", # three-angle Monte-Carlo - 'so3-montecarlo': 'so3-montecarlo', + "so3-montecarlo": "so3-montecarlo", # other methods without aliases - 's2-gauss-graef': 's2-gauss-graef', - 's2-design-graef': 's2-design-graef', - 's2-design-womersley': 's2-design-womersley', - 's2-covering-fibonacci': 's2-covering-fibonacci', - 's2-fibonacci': 's2-covering-fibonacci', - 's2-covering-zcw': 's2-covering-zcw', - 'so3-covering-karney': 'so3-covering-karney', - 'so3-gauss-graef': 'so3-gauss-graef', - 'so3-chebyshev-graef': 'so3-chebyshev-graef', - 'so3-chebyshev-womersley': 'so3-chebyshev-womersley', - 'so3-covering-zcw': 'so3-covering-zcw', + "s2-gauss-graef": "s2-gauss-graef", + "s2-design-graef": "s2-design-graef", + "s2-design-womersley": "s2-design-womersley", + "s2-covering-fibonacci": "s2-covering-fibonacci", + "s2-fibonacci": "s2-covering-fibonacci", + "s2-covering-zcw": "s2-covering-zcw", + "so3-covering-karney": "so3-covering-karney", + "so3-gauss-graef": "so3-gauss-graef", + "so3-chebyshev-graef": "so3-chebyshev-graef", + "so3-chebyshev-womersley": "so3-chebyshev-womersley", + "so3-covering-zcw": "so3-covering-zcw", } @property @@ -155,11 +155,8 @@ def _initialize_quadrature_methods(self, method_objects, method_options): """Fill options and initialize quadrature method objects.""" collected_dims = 0 for method_object, options in zip(method_objects, method_options): - # figure out, on which dimensions the current method is acting: - self._dims.append(tuple( - np.arange(method_object.dim) + collected_dims - )) + self._dims.append(tuple(np.arange(method_object.dim) + collected_dims)) collected_dims += method_object.dim # fill remaining options @@ -178,32 +175,30 @@ def _initialize_quadrature_methods(self, method_objects, method_options): def _check_and_fill_options(self, options, dims): """Check the integrations options and fill remaining fields.""" a, b, jacobian = self._get_interval(dims) - for key, value in zip( - ['a', 'b', 'jacobian'], - [a, b, jacobian] - ): - if key not in options and value == 'user': + for key, value in zip(["a", "b", "jacobian"], [a, b, jacobian]): + if key not in options and value == "user": raise ValueError(f"Option `{key}` needs to be specified by the user") - elif key in options and value == 'auto': - raise ValueError(f"Option `{key}` is set automatically and must not be given") - elif key not in options and value != 'auto': + elif key in options and value == "auto": + raise ValueError( + f"Option `{key}` is set automatically and must not be given" + ) + elif key not in options and value != "auto": options[key] = value # use periodic boundaries if possible - if ( - (isinstance(self, S2) and dims == (1,)) or - (isinstance(self, SO3) and dims in [(0,), (2,)]) + if (isinstance(self, S2) and dims == (1,)) or ( + isinstance(self, SO3) and dims in [(0,), (2,)] ): - options['periodic'] = True + options["periodic"] = True # determine ordering of angles for spherical quadrature schemes: if self.dim == 3 and len(dims) == 2 and dims == (0, 1): - options['swap_angles'] = True + options["swap_angles"] = True # assuming swap_angles=False by default in 2d quadrature classes return options def _construct_weights_and_meshgrids(self): """Construct combined quadrature weights and grid.""" self._weights = np.prod( - np.meshgrid(*self._method_weights, indexing='ij', copy=False), + np.meshgrid(*self._method_weights, indexing="ij", copy=False), axis=0, ).flatten() # For creating the quadrature meshgrid, I need to handle the cases @@ -215,26 +210,42 @@ def _construct_weights_and_meshgrids(self): # TODO: could be merged with the case below? elif np.all(np.asarray(self._ndims) == 1): # If all subgrids have dimension one, it is easy: - meshgrid = np.meshgrid(*self._method_points, indexing='ij', copy=False), + meshgrid = (np.meshgrid(*self._method_points, indexing="ij", copy=False),) elif self._ndims[0] == 1 and self._ndims[1] == 2: # If some subgrids have more than one dimension, I need to build # the meshgrid gradually: - p0, p1 = np.meshgrid(self._method_points[0][0], self._method_points[1][0], - indexing='ij', copy=False) - p0, p2 = np.meshgrid(self._method_points[0][0], self._method_points[1][1], - indexing='ij', copy=False) + p0, p1 = np.meshgrid( + self._method_points[0][0], + self._method_points[1][0], + indexing="ij", + copy=False, + ) + p0, p2 = np.meshgrid( + self._method_points[0][0], + self._method_points[1][1], + indexing="ij", + copy=False, + ) meshgrid = np.stack((p0, p1, p2), axis=0) elif self._ndims[0] == 2 and self._ndims[1] == 1: - p0, p2 = np.meshgrid(self._method_points[0][0], self._method_points[1][0], - indexing='ij', copy=False) - p1, p2 = np.meshgrid(self._method_points[0][1], self._method_points[1][0], - indexing='ij', copy=False) + p0, p2 = np.meshgrid( + self._method_points[0][0], + self._method_points[1][0], + indexing="ij", + copy=False, + ) + p1, p2 = np.meshgrid( + self._method_points[0][1], + self._method_points[1][0], + indexing="ij", + copy=False, + ) meshgrid = np.stack((p0, p1, p2), axis=0) else: raise ValueError("Error in constructing quadrature grid") - #TODO: is there a more elegant solution than the one above? + # TODO: is there a more elegant solution than the one above? self._points = np.reshape(meshgrid, (self.dim, -1)) - #TODO: do I need to set copy=True? + # TODO: do I need to set copy=True? # This could be necessary to make sure that reshaping is reliable, # independent from the data's memory layout @@ -266,14 +277,16 @@ def _get_interval(self, dims): This needs to be the sample points as single argument. """ - #TODO: raise NotImplementedError ? + # TODO: raise NotImplementedError ? # see https://docs.python.org/3/library/exceptions.html#NotImplementedError a = None b = None jacobian = None return a, b, jacobian - def integrate(self, f, f_kwargs={}, axis=-1):#, dim=None):#, squeeze=True):#, order=None, only=None): + def integrate( + self, f, f_kwargs={}, axis=-1 + ): # , dim=None):#, squeeze=True):#, order=None, only=None): """Integrate the given data or callable. Parameters @@ -305,13 +318,13 @@ def integrate(self, f, f_kwargs={}, axis=-1):#, dim=None):#, squeeze=True):#, or else: f_array = f - #squeeze : bool, optional + # squeeze : bool, optional # Some SciPy integration method return zero for integration of an # axis with length one. If True, axes of length one are squeezed, # i.e. the result of the integration is the single value of the # integrand along this axes. Axes that are not integrated are not # affected by the squeeze. - #dim : int or sequence of ints, optional + # dim : int or sequence of ints, optional # Specifies which dimensions are to be integrated. # If None, integrate all dimensions. # options for dim: @@ -319,12 +332,13 @@ def integrate(self, f, f_kwargs={}, axis=-1):#, dim=None):#, squeeze=True):#, or # (0, 1) # ((0, 1), 2) #no! dim = None - if dim is not None: # integrate speficic dimensions + if dim is not None: # integrate speficic dimensions # This blew up in complexity; I won't allow it for now. raise NotImplementedError - if np.ndim(dim) == 0: dim = (dim,) + if np.ndim(dim) == 0: + dim = (dim,) assert len(dim) > 0 and len(dim) <= self.dim - dim = sorted(dim) # the implementation below depends on it! + dim = sorted(dim) # the implementation below depends on it! method_index = [] for d in dim: # figure out, which method to use for dimension d; after the @@ -343,11 +357,11 @@ def integrate(self, f, f_kwargs={}, axis=-1):#, dim=None):#, squeeze=True):#, or axes = [] reduced_axes = 0 for m in np.flip(method_index): - axes.append(-len(self._methods)+m+reduced_axes) + axes.append(-len(self._methods) + m + reduced_axes) reduced_axes += 1 # the following was an older try: - #if dim is not None: + # if dim is not None: # if np.ndim(dim) == 0: dim = (dim,) # assert len(dim) > 0 and len(dim) <= self.dim # # reshape the sample points @@ -356,12 +370,12 @@ def integrate(self, f, f_kwargs={}, axis=-1):#, dim=None):#, squeeze=True):#, or # for d in dim: # result = self._methods[d].integrate(y, axis=axis+d) - else: # integrate all dimensions of a sample + else: # integrate all dimensions of a sample method_index = list(range(len(self._methods))) axes = np.repeat(-1, len(self._methods)) f_array = np.moveaxis(f_array, axis, -1) - shape = f_array.shape[:-1]+self.shape + shape = f_array.shape[:-1] + self.shape result = f_array.reshape(shape) # iterate over angles/methods, starting with the last: for i_m, m in enumerate(np.flip(method_index)): @@ -453,7 +467,7 @@ class SO3(GeometryQuadrature): quaternions : ndarray Sampling points in the form of unit quaternions, :math:`(q_r, q_i, q_j, q_k)`, where :math:`q_r` is the scalar part [3]. - + Notes ----- @@ -470,7 +484,7 @@ class SO3(GeometryQuadrature): * [3]: Wikipedia page: https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation * [4]: GitHub: - https://github.com/moble/quaternionic + https://github.com/moble/quaternionic Examples -------- @@ -509,20 +523,16 @@ class SO3(GeometryQuadrature): dim = 3 """int: Dimension of this geometry.""" - def __init__(self, method_specs, polar_sampling='cos'): - _allowed_samplings = ['angle', 'cos'] + def __init__(self, method_specs, polar_sampling="cos"): + _allowed_samplings = ["angle", "cos"] if polar_sampling not in _allowed_samplings: - raise ValueError( - f"`polar_sampling needs to be one of {_allowed_samplings}" - ) + raise ValueError(f"`polar_sampling needs to be one of {_allowed_samplings}") self._polar_sampling = polar_sampling super().__init__(method_specs) # in case we sample the polar integral in terms of cos(angle), # transform the sample points back to the angle: - if self._polar_sampling == 'cos' and len(self._methods) > 2: - self._points[1] = ( - np.flip(np.arccos(self._points[1]), axis=0) - ) + if self._polar_sampling == "cos" and len(self._methods) > 2: + self._points[1] = np.flip(np.arccos(self._points[1]), axis=0) self.weights = self._weights self.points = self._points self.angles = self._points @@ -530,26 +540,28 @@ def __init__(self, method_specs, polar_sampling='cos'): def _get_interval(self, dims): """Determine the integration boundaries and the Jacobian.""" - if len(dims) == 3: # SO3 quadrature scheme - return 'auto', 'auto', 'auto' - elif len(dims) == 2: # spherical quadrature scheme - return 'auto', 'auto', 'auto' - elif len(dims) == 1 and dims[0] == 1: # 1d method for beta - if self._polar_sampling == 'angle': + if len(dims) == 3: # SO3 quadrature scheme + return "auto", "auto", "auto" + elif len(dims) == 2: # spherical quadrature scheme + return "auto", "auto", "auto" + elif len(dims) == 1 and dims[0] == 1: # 1d method for beta + if self._polar_sampling == "angle": return 0, π, np.sin - elif self._polar_sampling == 'cos': + elif self._polar_sampling == "cos": return -1, 1, None - elif len(dims) == 1 and (dims[0] == 0 or dims[0] == 2) : # 1d method for alpha or gamma - return 0, 2*π, None + elif len(dims) == 1 and ( + dims[0] == 0 or dims[0] == 2 + ): # 1d method for alpha or gamma + return 0, 2 * π, None else: raise ValueError("Cannot determine integration interval") def savetxt(self, filename, weights=True): - grid = SO3Grid('Euler angles', self.angles) + grid = SO3Grid("Euler angles", self.angles) if weights: - grid.save(filename, 'Euler angles', weights=self.weights) + grid.save(filename, "Euler angles", weights=self.weights) else: - grid.save(filename, 'Euler angles') + grid.save(filename, "Euler angles") class S2(GeometryQuadrature): @@ -612,8 +624,8 @@ class S2(GeometryQuadrature): xyz : ndarray Sampling points in cartesian coordinates, :math:`(x, y, z)`. This array has shape ``(3, size)``. - - + + References ---------- * [1]: Wikipedia page: @@ -622,7 +634,7 @@ class S2(GeometryQuadrature): https://en.wikipedia.org/wiki/N-sphere * [3]: Wikipedia page: https://en.wikipedia.org/wiki/Spherical_coordinate_system - + Examples -------- @@ -650,20 +662,16 @@ def dim(self): """int: Dimension of this geometry.""" return 2 - def __init__(self, method_specs, polar_sampling='cos'): - _allowed_samplings = ['angle', 'cos'] + def __init__(self, method_specs, polar_sampling="cos"): + _allowed_samplings = ["angle", "cos"] if polar_sampling not in _allowed_samplings: - raise ValueError( - f"`polar_sampling needs to be one of {_allowed_samplings}" - ) + raise ValueError(f"`polar_sampling needs to be one of {_allowed_samplings}") self._polar_sampling = polar_sampling super().__init__(method_specs) # in case we sample the polar integral in terms of cos(angle), # transform the sample points back to the angle: - if self._polar_sampling == 'cos' and len(self._methods) > 1: - self._points[0] = ( - np.flip(np.arccos(self._points[0]), axis=0) - ) + if self._polar_sampling == "cos" and len(self._methods) > 1: + self._points[0] = np.flip(np.arccos(self._points[0]), axis=0) self.weights = self._weights self.points = self._points self.angles = self._points @@ -671,24 +679,24 @@ def __init__(self, method_specs, polar_sampling='cos'): def _get_interval(self, dims): """Determine the integration boundaries and the Jacobian.""" - if len(dims) == 2: # Spherical quadrature scheme - return 'auto', 'auto', 'auto' - elif len(dims) == 1 and dims[0] == 0: # Polar angle - if self._polar_sampling == 'angle': + if len(dims) == 2: # Spherical quadrature scheme + return "auto", "auto", "auto" + elif len(dims) == 1 and dims[0] == 0: # Polar angle + if self._polar_sampling == "angle": return 0, π, np.sin - elif self._polar_sampling == 'cos': + elif self._polar_sampling == "cos": return -1, 1, None - elif len(dims) == 1 and dims[0] == 1: # Azimuthal angle - return 0, 2*π, None + elif len(dims) == 1 and dims[0] == 1: # Azimuthal angle + return 0, 2 * π, None else: raise ValueError("Cannot determine integration interval") def savetxt(self, filename, weights=True): - grid = S2Grid('angles', self.angles) + grid = S2Grid("angles", self.angles) if weights: - grid.save(filename, 'angles', weights=self.weights) + grid.save(filename, "angles", weights=self.weights) else: - grid.save(filename, 'angles') + grid.save(filename, "angles") class Rn(GeometryQuadrature): @@ -733,7 +741,7 @@ class Rn(GeometryQuadrature): See below, for examples. .. note:: - + Currently, only one-dimensional quadrature methods are supported. @@ -752,20 +760,20 @@ class Rn(GeometryQuadrature): Quadrature weights. The array has shape ``(size,)``. r : ndarray Equivalent to `points` - + Notes ----- This class can be used to generate quadrature methods over arbitrary domains. See the examples below. - + References ---------- * [1]: Wikipedia page: https://en.wikipedia.org/wiki/Euclidean_space * [2]: Wikipedia page: https://en.wikipedia.org/wiki/Cartesian_coordinate_system - + Examples -------- @@ -806,7 +814,7 @@ class Rn(GeometryQuadrature): """ - dim = None #TODO: can this be more elegant? + dim = None # TODO: can this be more elegant? # Maybe, make dim an instance attribute for consistency """Dimension of this geometry. @@ -822,13 +830,13 @@ def __init__(self, method_specs): super().__init__(method_specs) self.weights = self._weights self.points = self._points - self.r = self._points #TODO: deprecate self.r? + self.r = self._points # TODO: deprecate self.r? def _get_interval(self, dims): """Determine the integration boundaries and the Jacobian.""" # All integration bounds need to be set by the user in this quadrature class. # Specification of Jacobians is optional. - return 'user', 'user', None + return "user", "user", None def savetxt(self, filename, weights=True): msg = "Writing grids not yet implemented for this class" diff --git a/src/openquad/graef.py b/src/openquad/graef.py index 1a5c143..005e1b1 100644 --- a/src/openquad/graef.py +++ b/src/openquad/graef.py @@ -4,7 +4,7 @@ import numpy as np -from .base import (AtomicSO3Quadrature, AtomicS2Quadrature, QuadratureWithDegree) +from .base import AtomicSO3Quadrature, AtomicS2Quadrature, QuadratureWithDegree from .data.graef import ( S2_GAUSS_METHODS, S2_SPHERICAL_DESIGNS, @@ -14,7 +14,6 @@ class GraefS2Gauss(AtomicS2Quadrature, QuadratureWithDegree): - _TABLE = np.asarray(S2_GAUSS_METHODS, dtype=int) _available_sizes = _TABLE[:, 1] _available_degrees = _TABLE[:, 0] @@ -33,13 +32,12 @@ def _points_weights(self): Quadrature weights. """ - points, weights = self._load_points_weights('graef', 's2_gauss') - weights = weights * (4*np.pi) + points, weights = self._load_points_weights("graef", "s2_gauss") + weights = weights * (4 * np.pi) return points, weights class GraefS2Design(AtomicS2Quadrature, QuadratureWithDegree): - _TABLE = np.asarray(S2_SPHERICAL_DESIGNS, dtype=int) _available_sizes = _TABLE[:, 1] _available_degrees = _TABLE[:, 0] @@ -58,13 +56,12 @@ def _points_weights(self): Quadrature weights. """ - points, weights = self._load_points_weights('graef', 's2_design') - weights = weights * (4*np.pi) + points, weights = self._load_points_weights("graef", "s2_design") + weights = weights * (4 * np.pi) return points, weights class GraefSO3Gauss(AtomicSO3Quadrature, QuadratureWithDegree): - _TABLE = np.asarray(SO3_GAUSS_METHODS, dtype=int) _available_sizes = _TABLE[:, 1] _available_degrees = _TABLE[:, 0] @@ -83,13 +80,12 @@ def _points_weights(self): Quadrature weights. """ - points, weights = self._load_points_weights('graef', 'so3_gauss') - weights = weights * (8*np.pi**2) + points, weights = self._load_points_weights("graef", "so3_gauss") + weights = weights * (8 * np.pi**2) return points, weights class GraefSO3Chebyshev(AtomicSO3Quadrature, QuadratureWithDegree): - _TABLE = np.asarray(SO3_CHEBYSHEV_METHODS, dtype=int) _available_sizes = _TABLE[:, 1] _available_degrees = _TABLE[:, 0] @@ -108,6 +104,6 @@ def _points_weights(self): Quadrature weights. """ - points, weights = self._load_points_weights('graef', 'so3_chebyshev') - weights = weights * (8*np.pi**2) + points, weights = self._load_points_weights("graef", "so3_chebyshev") + weights = weights * (8 * np.pi**2) return points, weights diff --git a/src/openquad/grid.py b/src/openquad/grid.py index 3808c08..7f34fae 100644 --- a/src/openquad/grid.py +++ b/src/openquad/grid.py @@ -12,7 +12,7 @@ def angles_from_xyz(xyz, axis=0): coordinates. $\theta$ denotes the polar angle, while $\phi$ denotes the azimuthal angle. - + Parameters ---------- xyz : array_like @@ -32,7 +32,7 @@ def angles_from_xyz(xyz, axis=0): xyz = np.moveaxis(xyz, axis, 0) x, y, z = xyz θ = np.arccos(z / 1.0) - ϕ = np.arctan2(y, x) % (2*np.pi) + ϕ = np.arctan2(y, x) % (2 * np.pi) return np.moveaxis([θ, ϕ], 0, axis) @@ -41,7 +41,7 @@ def xyz_from_angles(theta_phi, axis=0): polar angles. $\theta$ denotes the polar angle, while $\phi$ denotes the azimuthal angle. - + Parameters ---------- theta_phi : array_like @@ -83,7 +83,7 @@ def euler_angles_from_quaternions(quaternions, axis=0): """ quaternions = np.moveaxis(quaternions, axis, -1) - angles = quaternions.as_euler_angles % (2*np.pi) + angles = quaternions.as_euler_angles % (2 * np.pi) return np.moveaxis(angles, -1, axis) @@ -111,7 +111,7 @@ def quaternions_from_euler_angles(angles, axis=0): class Grid(ABC): """TODO""" - + @abstractmethod def _get_file_data_and_header(self, representation): """TODO""" @@ -126,10 +126,9 @@ def save(self, filename, representation, weights=None): if weights is not None: data = np.vstack((*data, weights)) header = header + f"{'weights':>25}" - index = np.arange(1, data.shape[-1]+1) - fmt = '%10i' + data.shape[0] * '%25.16e' - np.savetxt(filename, np.vstack((index, *data)).T, - fmt=fmt, header=header) + index = np.arange(1, data.shape[-1] + 1) + fmt = "%10i" + data.shape[0] * "%25.16e" + np.savetxt(filename, np.vstack((index, *data)).T, fmt=fmt, header=header) class S2Grid(Grid): @@ -138,6 +137,7 @@ class S2Grid(Grid): Grid points are stored either as spherical polar angles `theta` and `phi` or in terms of cartesian coordinates `x`, `y` and `z`. """ + def __init__(self, representation, points, axis=0): """ Parameters @@ -159,9 +159,9 @@ def __init__(self, representation, points, axis=0): self._xyz = None points = np.moveaxis(points, axis, 0) - if representation == 'angles': + if representation == "angles": self.angles = points.reshape(2, -1) - elif representation == 'xyz': + elif representation == "xyz": self.xyz = points.reshape(3, -1) else: raise ValueError(f"Unknown representation: {representation}") @@ -194,10 +194,10 @@ def _get_file_data_and_header(self, representation): + f"\nRepresentation: {representation}\n" + f"Number of grid points: {self.N}\n" ) - if representation == 'angles': + if representation == "angles": data = self.angles header = header + f"{'index':>8}{'theta (rad)':>25}{'phi (rad)':>25}" - elif representation == 'xyz': + elif representation == "xyz": data = self.xyz header = header + f"{'index':>8}{'x':>25}{'y':>25}{'z':>25}" else: @@ -211,6 +211,7 @@ class SO3Grid(Grid): Orientations are stored in several representations: Euler angles, quaternions. """ + def __init__(self, representation, points, axis=0): """ Parameters @@ -232,9 +233,9 @@ def __init__(self, representation, points, axis=0): self._angles = None self._quaternions = None - if representation == 'Euler angles': + if representation == "Euler angles": self.angles = points.reshape(3, -1) - elif representation == 'quaternions': + elif representation == "quaternions": self.quaternions = points.reshape(-1, 4) else: raise ValueError(f"Unknown representation: {representation}") @@ -267,12 +268,17 @@ def _get_file_data_and_header(self, representation): + f"\nRepresentation: {representation}\n" + f"Number of grid points: {self.N}\n" ) - if representation == 'Euler angles': + if representation == "Euler angles": data = self.angles - header = header + f"{'index':>8}{'alpha (rad)':>25}{'beta (rad)':>25}{'gamma (rad)':>25}" - elif representation == 'quaternions': + header = ( + header + + f"{'index':>8}{'alpha (rad)':>25}{'beta (rad)':>25}{'gamma (rad)':>25}" + ) + elif representation == "quaternions": data = self.quaternions - header = header + f"{'index':>8}{'q_0':>25}{'q_1':>25}{'q_2':>25}{'q_3':>25}" + header = ( + header + f"{'index':>8}{'q_0':>25}{'q_1':>25}{'q_2':>25}{'q_3':>25}" + ) else: raise ValueError(f"Unknown representation: {representation}") return data, header diff --git a/src/openquad/karney.py b/src/openquad/karney.py index fdbd35f..e736312 100644 --- a/src/openquad/karney.py +++ b/src/openquad/karney.py @@ -9,8 +9,7 @@ class KarneySO3(AtomicSO3Quadrature, QuadratureWithoutDegree): - - _TABLE = np.array(SO3_COVERINGS, dtype='object') + _TABLE = np.array(SO3_COVERINGS, dtype="object") _available_sizes = _TABLE[:, 0].astype(int) def _points_weights(self): @@ -29,6 +28,6 @@ def _points_weights(self): Quadrature weights. """ - points, weights = self._load_points_weights('karney', 'so3_covering') - weights = weights * (8*np.pi**2) + points, weights = self._load_points_weights("karney", "so3_covering") + weights = weights * (8 * np.pi**2) return points, weights diff --git a/src/openquad/lebedev.py b/src/openquad/lebedev.py index 9a836d6..d785f9b 100644 --- a/src/openquad/lebedev.py +++ b/src/openquad/lebedev.py @@ -9,7 +9,6 @@ class LebedevLaikov(AtomicS2Quadrature, QuadratureWithDegree): - _TABLE = np.asarray(LEBEDEV_LAIKOV_QUADRATURES, dtype=int) _available_sizes = _TABLE[:, 1] _available_degrees = _TABLE[:, 0] @@ -35,6 +34,6 @@ def _points_weights(self): Array of ones. This is only returned to retain a common interface. """ - points, weights = self._load_points_weights('lebedev', 's2_gauss') - weights = weights * (4*np.pi) + points, weights = self._load_points_weights("lebedev", "s2_gauss") + weights = weights * (4 * np.pi) return points, weights diff --git a/src/openquad/monte_carlo.py b/src/openquad/monte_carlo.py index c9cb582..1637288 100644 --- a/src/openquad/monte_carlo.py +++ b/src/openquad/monte_carlo.py @@ -5,11 +5,15 @@ import numpy as np import quaternionic -from .base import QuadratureWithoutDegree, AtomicR1Quadrature, AtomicS2Quadrature, AtomicSO3Quadrature +from .base import ( + QuadratureWithoutDegree, + AtomicR1Quadrature, + AtomicS2Quadrature, + AtomicSO3Quadrature, +) class MonteCarloR1(AtomicR1Quadrature, QuadratureWithoutDegree): - _has_endpoints = False def __init__(self, size, a, b, jacobian=None, seed=None, **kwargs): @@ -17,12 +21,12 @@ def __init__(self, size, a, b, jacobian=None, seed=None, **kwargs): def _points_weights(self, a, b, seed): """One-dimensional Monte-Carlo integration. - + Parameters ---------- size : int Number of random sampling points. - + Returns ------- points : ndarray @@ -33,23 +37,22 @@ def _points_weights(self, a, b, seed): """ rng = np.random.default_rng(seed=seed) x = rng.uniform(a, b, self.size) - w = np.ones(self.size, dtype=float) / self.size * (b-a)/2 + w = np.ones(self.size, dtype=float) / self.size * (b - a) / 2 return x, w class MonteCarloS2(AtomicS2Quadrature, QuadratureWithoutDegree): - def __init__(self, size, seed=None): super().__init__(size=size, seed=seed) def _points_weights(self, seed): """Monte-Carlo integration on the unit sphere. - + Parameters ---------- size : int Number of random sampling points. - + Returns ------- points : ndarray @@ -59,14 +62,14 @@ def _points_weights(self, seed): """ x = self._sample_spherical_polar_angles(self.size, seed) - w = np.ones(self.size, dtype=float) / self.size * (4*np.pi) + w = np.ones(self.size, dtype=float) / self.size * (4 * np.pi) return x, w def _sample_spherical_polar_angles(self, n, seed=None): """Generate a uniform distribution of points on the unit sphere. The unit sphere is sampled in spherical polar coodinates. - + Parameters ---------- n : int @@ -74,7 +77,7 @@ def _sample_spherical_polar_angles(self, n, seed=None): seed : int, optional Seed for the pseudo-random number generator. If None, it will be determined by the OS. - + Returns ------- angles : ndarray @@ -84,20 +87,19 @@ def _sample_spherical_polar_angles(self, n, seed=None): """ rng = np.random.default_rng(seed=seed) - phi = rng.uniform(0, 2*np.pi, n) + phi = rng.uniform(0, 2 * np.pi, n) u = rng.uniform(-1, 1, n) theta = np.arccos(u) return np.array([theta, phi]) class MonteCarloSO3(AtomicSO3Quadrature, QuadratureWithoutDegree): - - def __init__(self, size, seed=None, method='quaternions'): + def __init__(self, size, seed=None, method="quaternions"): super().__init__(size=size, seed=seed, method=method) def _points_weights(self, seed, method): """Three-angle Monte-Carlo integration. - + Parameters ---------- size : int @@ -105,7 +107,7 @@ def _points_weights(self, seed, method): method : str Sampling method. Possible options are `'quaternions'` and `'angles'`. - + Returns ------- points : ndarray @@ -115,19 +117,19 @@ def _points_weights(self, seed, method): """ x = self.random_rotations(self.size, method, seed) - w = np.ones(self.size, dtype=float) / self.size * (8*np.pi**2) + w = np.ones(self.size, dtype=float) / self.size * (8 * np.pi**2) return x, w def random_rotations(self, n, method, seed=None): """Generate uniform random 3d rotations. - + The parameter `method` controls which method is used to sample orientation space: For ``method='quaternions'``, orientation space is sampled in quaternion representation with Showmake's method. For ``method='angles'``, orientation space is sampled in Euler angle representation. Both methods yield uniform sampling without clustering at the poles. - + Parameters ---------- n : int @@ -137,7 +139,7 @@ def random_rotations(self, n, method, seed=None): seed : int, optional Seed for the pseudo-random number generator. If None, it will be determined by the OS. - + Returns ------- angles : ndarray @@ -145,10 +147,10 @@ def random_rotations(self, n, method, seed=None): The Euler angles are stored in the first axis. """ - if method == 'quaternions': + if method == "quaternions": quaternions = self._sample_quaternions(n, seed) x = quaternions.to_euler_angles.T - elif method == 'angles': + elif method == "angles": x = self._sample_euler_angles(n, seed) else: raise ValueError(f"Invalid sampling method: {method}") @@ -156,9 +158,9 @@ def random_rotations(self, n, method, seed=None): def _sample_quaternions(self, n, seed=None): """Generate uniform random 3d rotations in quaternion representation. - + This function uses Shoemake's method. - + Parameters ---------- n : int @@ -166,7 +168,7 @@ def _sample_quaternions(self, n, seed=None): seed : int, optional Seed for the pseudo-random number generator. If None, it will be determined by the OS. - + Returns ------- quaternsions : quaternionic array @@ -176,17 +178,17 @@ def _sample_quaternions(self, n, seed=None): """ rng = np.random.default_rng(seed=seed) x = rng.random((3, n)) - s1 = np.sin(2*np.pi*x[0]) - s2 = np.sin(2*np.pi*x[1]) - c1 = np.cos(2*np.pi*x[0]) - c2 = np.cos(2*np.pi*x[1]) + s1 = np.sin(2 * np.pi * x[0]) + s2 = np.sin(2 * np.pi * x[1]) + c1 = np.cos(2 * np.pi * x[0]) + c2 = np.cos(2 * np.pi * x[1]) r1 = np.sqrt(1 - x[2]) r2 = np.sqrt(x[2]) - return quaternionic.array(np.transpose([c2*r2, s1*r1, c1*r1, s2*r2])) + return quaternionic.array(np.transpose([c2 * r2, s1 * r1, c1 * r1, s2 * r2])) def _sample_euler_angles(self, n, seed=None): """Generate uniform random 3d rotations in Euler angle representation. - + Parameters ---------- n : int @@ -194,7 +196,7 @@ def _sample_euler_angles(self, n, seed=None): seed : int, optional Seed for the pseudo-random number generator. If None, it will be determined by the OS. - + Returns ------- angles : ndarray @@ -203,8 +205,8 @@ def _sample_euler_angles(self, n, seed=None): """ rng = np.random.default_rng(seed=seed) - alpha = rng.uniform(0, 2*np.pi, n) - gamma = rng.uniform(0, 2*np.pi, n) + alpha = rng.uniform(0, 2 * np.pi, n) + gamma = rng.uniform(0, 2 * np.pi, n) u = rng.uniform(-1, 1, n) beta = np.arccos(u) return np.array([alpha, beta, gamma]) diff --git a/src/openquad/newton_cotes.py b/src/openquad/newton_cotes.py index 4480908..3585862 100644 --- a/src/openquad/newton_cotes.py +++ b/src/openquad/newton_cotes.py @@ -9,7 +9,6 @@ class CompositeTrapezoid(AtomicR1Quadrature, QuadratureWithFixedDegree): - _has_endpoints = True def _get_degree(self): @@ -17,14 +16,14 @@ def _get_degree(self): def _points_weights(self, a, b): """Composite trapezoid rule. - + Composite trapezoid rule for integrating a function on the interval :math:`[a,b]`. If `period=True` assume peridoic boundary conditions. In this case, the function value of point `a` is reused for the point `b`, effectively increasing the number of subintervals of :math:`[a,b]` by one. - + Parameters ---------- size : int @@ -37,7 +36,7 @@ def _points_weights(self, a, b): Upper limit of integration. periodic : logical, optional If True, assume periodic boundary conditions. - + Returns ------- points : ndarray @@ -46,7 +45,8 @@ def _points_weights(self, a, b): Array of ones. This is only returned to retain a common interface. """ N = self.size - if self._periodic: N += 1 + if self._periodic: + N += 1 if N < 2: msg = "Trapezoid method requires at least two sample points" raise ValueError(msg) @@ -58,7 +58,6 @@ def _points_weights(self, a, b): class CompositeSimpson(AtomicR1Quadrature, QuadratureWithFixedDegree): - _has_endpoints = True def _get_degree(self): @@ -66,10 +65,10 @@ def _get_degree(self): def _points_weights(self, a, b): """Composite Simpson's rule. - + Composite Simpson's rule for integrating a function on the interval :math:`[a,b]`. - + Parameters ---------- size : int @@ -80,7 +79,7 @@ def _points_weights(self, a, b): Lower limit of integration. b : float Upper limit of integration. - + Returns ------- points : ndarray @@ -89,7 +88,8 @@ def _points_weights(self, a, b): Array of ones. This is only returned to retain a common interface. """ N = self.size - if self._periodic: N += 1 + if self._periodic: + N += 1 if N < 3: msg = "Simpson method requires at least three sample points" raise ValueError(msg) @@ -116,23 +116,22 @@ def _points_weights(self, a, b): class Romberg(AtomicR1Quadrature, QuadratureWithFixedDegree): - _has_endpoints = True def _get_degree(self): # Romberg is in some situations equivalent to Trapz, Simps and Boole, # i.e. it can have degree at least up to five. I don't know, if there # is a general formula for the degree for higher order of Romb. - return None #TODO? + return None # TODO? def _points_weights(self, a, b): """Romberg integration. The number of sample points must be one plus a non-negative power of 2. - + This function currently wraps SciPy's `romb` implementation for integrating a function on the interval :math:`[a, b]`. - + Parameters ---------- size : int @@ -143,7 +142,7 @@ def _points_weights(self, a, b): Lower limit of integration. b : float Upper limit of integration. - + Returns ------- points : ndarray @@ -153,13 +152,16 @@ def _points_weights(self, a, b): """ # Check that we have a valid number of sample points N = self.size - if self._periodic: N += 1 + if self._periodic: + N += 1 n = 1 while n < N - 1: n <<= 1 if n != N - 1: - raise ValueError("Number of samples for Romberg integration" - "must be one plus a non-negative power of 2") + raise ValueError( + "Number of samples for Romberg integration" + "must be one plus a non-negative power of 2" + ) x = np.linspace(a, b, N) w = np.ones(N) return x, w @@ -167,7 +169,6 @@ def _points_weights(self, a, b): def _integrate_sample(self, f_samples, axis=-1): dx = self.points[1] - self.points[0] f_samples = np.moveaxis(f_samples, axis, -1) - if self._periodic: # add entry for endpoint of interval - f_samples = np.concatenate((f_samples, f_samples[...,:1]), - axis=-1) + if self._periodic: # add entry for endpoint of interval + f_samples = np.concatenate((f_samples, f_samples[..., :1]), axis=-1) return romb(f_samples, dx=dx, axis=-1) diff --git a/src/openquad/womersley.py b/src/openquad/womersley.py index 9d3dc39..7bc346f 100644 --- a/src/openquad/womersley.py +++ b/src/openquad/womersley.py @@ -4,12 +4,11 @@ import numpy as np -from .base import (AtomicSO3Quadrature, AtomicS2Quadrature, QuadratureWithDegree) +from .base import AtomicSO3Quadrature, AtomicS2Quadrature, QuadratureWithDegree from .data.womersley import S2_SPHERICAL_DESIGNS class WomersleyS2Design(AtomicS2Quadrature, QuadratureWithDegree): - _TABLE = np.asarray(S2_SPHERICAL_DESIGNS, dtype=int) _available_sizes = _TABLE[:, 1] _available_degrees = _TABLE[:, 0] @@ -33,12 +32,12 @@ def _points_weights(self, symmetric): """ if symmetric is not None: if symmetric: - suffix = '_sym' + suffix = "_sym" else: - suffix = '_nosym' + suffix = "_nosym" points, weights = self._load_points_weights( - 'womersley', - 's2_design', + "womersley", + "s2_design", suffix, ) if symmetric is None: @@ -46,22 +45,21 @@ def _points_weights(self, symmetric): # asymmetric try: points, weights = self._load_points_weights( - 'womersley', - 's2_design', - '_sym', + "womersley", + "s2_design", + "_sym", ) except FileNotFoundError: points, weights = self._load_points_weights( - 'womersley', - 's2_design', - '_nosym', + "womersley", + "s2_design", + "_nosym", ) - weights = weights * (4*np.pi) + weights = weights * (4 * np.pi) return points, weights class WomersleySO3Chebyshev(AtomicSO3Quadrature, QuadratureWithDegree): - _TABLE = np.asarray(S2_SPHERICAL_DESIGNS, dtype=int) _available_sizes = _TABLE[:, 1] // 2 _available_degrees = (_TABLE[:, 0] - 1) // 2 @@ -84,11 +82,11 @@ def _points_weights(self): msg = "SO3 quadratures from Womersley not yet implemented" raise NotImplementedError(msg) - points, weights = self._load_points_weights('womersley', 's3_design') + points, weights = self._load_points_weights("womersley", "s3_design") # data contains the cartesian coordinates # TODO: identify opposite points # TODO: convert to Euler angle representation # TODO: remove NotImplementedError at beginning of this method points = ... - weights = np.ones(self.size) / self.size * (8*np.pi**2) + weights = np.ones(self.size) / self.size * (8 * np.pi**2) return points, weights diff --git a/tests/test_Rn_quadrature.py b/tests/test_Rn_quadrature.py index f64213d..970d600 100644 --- a/tests/test_Rn_quadrature.py +++ b/tests/test_Rn_quadrature.py @@ -6,6 +6,7 @@ from openquad import Rn + def f(theta, phi): """Test integrand. Integral should yield 1.""" assert np.shape(theta) == np.shape(phi) @@ -15,86 +16,105 @@ def f(theta, phi): + 4 * special.sph_harm_y(4, 2, theta, phi) + 5 * special.sph_harm_y(5, 4, theta, phi) ) - return poly / (4*np.pi) + return poly / (4 * np.pi) def test_test_function(): """Make sure that the integral over the test function yields 1.""" - assert integrate.dblquad(lambda t, p: np.sin(t)*f(t, p).real, 0, 2*np.pi, 0, np.pi)[0] == pytest.approx(1) - assert integrate.dblquad(lambda t, p: np.sin(t)*f(t, p).imag, 0, 2*np.pi, 0, np.pi)[0] == pytest.approx(0) + assert integrate.dblquad( + lambda t, p: np.sin(t) * f(t, p).real, 0, 2 * np.pi, 0, np.pi + )[0] == pytest.approx(1) + assert integrate.dblquad( + lambda t, p: np.sin(t) * f(t, p).imag, 0, 2 * np.pi, 0, np.pi + )[0] == pytest.approx(0) def test_initialization(): # Wrong initializations # Before checking the method specification for consistency, # the methods shall raise an error, if a wrong type is given. - with pytest.raises(TypeError): # missing method specifier + with pytest.raises(TypeError): # missing method specifier quad = Rn() - with pytest.raises(ValueError, match="empty"): # empty method specifier + with pytest.raises(ValueError, match="empty"): # empty method specifier quad = Rn([]) # unsopproted types for method specifier # (we allow for ducktyping) - #with pytest.raises(TypeError): #TODO remove test + # with pytest.raises(TypeError): #TODO remove test # quad = Rn(()) - #with pytest.raises(TypeError): + # with pytest.raises(TypeError): # quad = Rn('str') - #with pytest.raises(TypeError): #TODO: remove? + # with pytest.raises(TypeError): #TODO: remove? # quad = Rn([('str', [])]) - #with pytest.raises(TypeError): #TODO: remove? + # with pytest.raises(TypeError): #TODO: remove? # quad = Rn([('str', ())]) # Invalid methods # Given the type of the specifier is correct, first the validity of the # method shall be checked before checking the remaining options. - with pytest.raises(ValueError, match='Invalid'): - quad = Rn([('invalid', {})]) - with pytest.raises(ValueError, match='Invalid'): - quad = Rn([('s2-gauss-lebedevlaikov', {})]) # example of 2d method - with pytest.raises(ValueError, match='Invalid'): - quad = Rn([('so3-montecarlo', {})]) # example of 3d method - + with pytest.raises(ValueError, match="Invalid"): + quad = Rn([("invalid", {})]) + with pytest.raises(ValueError, match="Invalid"): + quad = Rn([("s2-gauss-lebedevlaikov", {})]) # example of 2d method + with pytest.raises(ValueError, match="Invalid"): + quad = Rn([("so3-montecarlo", {})]) # example of 3d method + # Invalid method options # Now given that the type of the specifier is correct and that a valid # combination of methods has been choosen, check the remaining options # for the method. - with pytest.raises(TypeError, match='not both'): # either degree or size - quad = Rn([ - ('gausslegendre', {'size':5, 'degree':4, 'a':0, 'b':1}), - ]) - with pytest.raises(TypeError, match='`size` or `degree` must be given'): - quad = Rn([ - ('gausslegendre', {'a':0, 'b':np.pi}), - ]) - with pytest.raises(ValueError, match='`a`'): # no interval specified - quad = Rn([ - ('trapezoid', {'size':33, 'b':np.pi, 'jacobian':np.sin}), - ]) - with pytest.raises(TypeError, match='unexpected'): # unexpected argument - quad = Rn([ - ('trapezoid', {'size':5, 'a':0, 'b':1, 'unexpected':True}), - ]) + with pytest.raises(TypeError, match="not both"): # either degree or size + quad = Rn( + [ + ("gausslegendre", {"size": 5, "degree": 4, "a": 0, "b": 1}), + ] + ) + with pytest.raises(TypeError, match="`size` or `degree` must be given"): + quad = Rn( + [ + ("gausslegendre", {"a": 0, "b": np.pi}), + ] + ) + with pytest.raises(ValueError, match="`a`"): # no interval specified + quad = Rn( + [ + ("trapezoid", {"size": 33, "b": np.pi, "jacobian": np.sin}), + ] + ) + with pytest.raises(TypeError, match="unexpected"): # unexpected argument + quad = Rn( + [ + ("trapezoid", {"size": 5, "a": 0, "b": 1, "unexpected": True}), + ] + ) # Test optional parameters - with pytest.raises(TypeError, match='jacobian'): - quad = Rn([ - ('trapezoid', {'size':33, 'a':0, 'b':np.pi, 'jacobian':np.ones(11)}), - ]) + with pytest.raises(TypeError, match="jacobian"): + quad = Rn( + [ + ( + "trapezoid", + {"size": 33, "a": 0, "b": np.pi, "jacobian": np.ones(11)}, + ), + ] + ) # Valid initializations with does_not_raise(): - quad = Rn([('trapezoid', {'size':33, 'a':0, 'b':np.pi})]) - quad = Rn([('tRaPeZoId', {'size':33, 'a':0, 'b':np.pi})]) - quad = Rn([('trapezoid', {'size':33, 'a':0, 'b':np.pi})]) - quad = Rn([ - ('trapezoid', {'size':33, 'a':0, 'b':np.pi, 'jacobian':np.sin}), - ]) + quad = Rn([("trapezoid", {"size": 33, "a": 0, "b": np.pi})]) + quad = Rn([("tRaPeZoId", {"size": 33, "a": 0, "b": np.pi})]) + quad = Rn([("trapezoid", {"size": 33, "a": 0, "b": np.pi})]) + quad = Rn( + [ + ("trapezoid", {"size": 33, "a": 0, "b": np.pi, "jacobian": np.sin}), + ] + ) def test_only_1d_methods_allowed(): - with pytest.raises(ValueError, match='Invalid'): - quad = Rn([('s2-gauss-lebedevlaikov', {})]) # example of 2d method - with pytest.raises(ValueError, match='Invalid'): - quad = Rn([('so3-montecarlo', {})]) # example of 3d method + with pytest.raises(ValueError, match="Invalid"): + quad = Rn([("s2-gauss-lebedevlaikov", {})]) # example of 2d method + with pytest.raises(ValueError, match="Invalid"): + quad = Rn([("so3-montecarlo", {})]) # example of 3d method def test_fields(): @@ -102,13 +122,15 @@ def test_fields(): n1 = 5 n2 = 6 x1 = np.linspace(0, 1, n1) - quad = Rn([ - ('trapezoid', {'size':n1, 'a':0, 'b':1}), - ('gausslegendre', {'size':n2, 'a':0, 'b':2}), - ]) + quad = Rn( + [ + ("trapezoid", {"size": n1, "a": 0, "b": 1}), + ("gausslegendre", {"size": n2, "a": 0, "b": 2}), + ] + ) # test submethod properties: assert quad._methods[0].degree == 1 - assert quad._methods[1].degree == 2*n2-1 + assert quad._methods[1].degree == 2 * n2 - 1 assert quad._methods[0].size == n1 assert quad._methods[1].size == n2 assert len(quad._method_weights) == 2 @@ -119,30 +141,32 @@ def test_fields(): # test hidden properties: assert quad._ndims == [1, 1] - assert quad._dims == [(0,), (1,)] # do I really need this? + assert quad._dims == [(0,), (1,)] # do I really need this? assert quad._sizes == [n1, n2] - assert quad._degrees == [1, 2*n2-1] - assert quad._points.size == (2*n1*n2) - assert quad._points.shape == (2, n1*n2) - + assert quad._degrees == [1, 2 * n2 - 1] + assert quad._points.size == (2 * n1 * n2) + assert quad._points.shape == (2, n1 * n2) + # test public properties: assert quad.dim == 2 - assert quad.size == n1*n2 + assert quad.size == n1 * n2 assert quad.shape == (n1, n2) - assert quad.weights.shape == (n1*n2,) - assert quad.points.shape == (2, n1*n2) + assert quad.weights.shape == (n1 * n2,) + assert quad.points.shape == (2, n1 * n2) assert np.all(quad.points == quad._points) - assert np.all(quad.r == quad.points) # TODO: remove? - #assert quad.grid.points.shape == (2, n1*n2) + assert np.all(quad.r == quad.points) # TODO: remove? + # assert quad.grid.points.shape == (2, n1*n2) assert quad.weights.reshape(quad.shape).shape == (n1, n2) assert quad.points.reshape(quad.dim, *quad.shape).shape == (2, n1, n2) def test_integration(): - quad = Rn([ - ('gausslegendre', {'size':11, 'a':0, 'b':np.pi, 'jacobian':np.sin}), - ('simpson', {'size':13, 'a':0, 'b':2*np.pi}), - ]) + quad = Rn( + [ + ("gausslegendre", {"size": 11, "a": 0, "b": np.pi, "jacobian": np.sin}), + ("simpson", {"size": 13, "a": 0, "b": 2 * np.pi}), + ] + ) # Complete integration # callable assert quad.integrate(f) == pytest.approx(1) @@ -151,8 +175,8 @@ def test_integration(): assert quad.integrate(f_samples) == pytest.approx(1) # TODO: shaped array? - #TODO: below? + # TODO: below? ## Partial integration (of a sample) - #f_samples = f(*quad.points) - #print(quad.integrate(f_samples, dim=0)) - #print(quad.integrate(f_samples, dim=(0, 1))) + # f_samples = f(*quad.points) + # print(quad.integrate(f_samples, dim=0)) + # print(quad.integrate(f_samples, dim=(0, 1))) diff --git a/tests/test_S2_quadrature.py b/tests/test_S2_quadrature.py index 4e7026d..4a4fd8b 100644 --- a/tests/test_S2_quadrature.py +++ b/tests/test_S2_quadrature.py @@ -17,18 +17,22 @@ def f(theta, phi): + 4 * special.sph_harm_y(4, 2, theta, phi) + 5 * special.sph_harm_y(5, 4, theta, phi) ) - return poly / (4*np.pi) + return poly / (4 * np.pi) def test_test_function(): """Make sure that the integral over the test function yields 1.""" - assert integrate.dblquad(lambda t, p: np.sin(t)*f(t, p).real, 0, 2*np.pi, 0, np.pi)[0] == pytest.approx(1) - assert integrate.dblquad(lambda t, p: np.sin(t)*f(t, p).imag, 0, 2*np.pi, 0, np.pi)[0] == pytest.approx(0) + assert integrate.dblquad( + lambda t, p: np.sin(t) * f(t, p).real, 0, 2 * np.pi, 0, np.pi + )[0] == pytest.approx(1) + assert integrate.dblquad( + lambda t, p: np.sin(t) * f(t, p).imag, 0, 2 * np.pi, 0, np.pi + )[0] == pytest.approx(0) ## see answer in this post: ## https://stackoverflow.com/a/68012715 -#@pytest.mark.parametrize( +# @pytest.mark.parametrize( # "methods_spec, expectation, match", # [ # ([('trapezoid',)], pytest.raises(ValueError), "invalid choice of methods"), @@ -36,64 +40,71 @@ def test_test_function(): # ([('gausslegendre',), ('gausslegendre',), ('gausslegendre',)], pytest.raises(ValueError), "invalid choice of methods"), # ([('gausslegendre',), ('s2-gauss-lebedevlaikov',)], pytest.raises(ValueError), "invalid choice of methods"), # ([('ZCW',)], pytest.raises(ValueError), "invalid choice of methods"), -# +# def test_initialization(): # Wrong initializations # Before checking the method specification for consistency, # the methods shall raise an error, if a wrong type is given. - with pytest.raises(TypeError): # missing method specifier + with pytest.raises(TypeError): # missing method specifier quad = S2() - with pytest.raises(ValueError, match="empty"): # empty method specifier + with pytest.raises(ValueError, match="empty"): # empty method specifier quad = S2([]) # Invalid methods # Given the type of the specifier is correct, first the validity of the # method shall be checked before checking the remaining options. - with pytest.raises(ValueError, match='Invalid'): - quad = S2([('invalid', {})]) with pytest.raises(ValueError, match="Invalid"): - quad = S2([('trapezoid', {})]) + quad = S2([("invalid", {})]) with pytest.raises(ValueError, match="Invalid"): - quad = S2([('gausslegendre', {})]) + quad = S2([("trapezoid", {})]) with pytest.raises(ValueError, match="Invalid"): - quad = S2([ - ('gausslegendre', {}), - ('gausslegendre', {}), - ('gausslegendre', {})]) + quad = S2([("gausslegendre", {})]) with pytest.raises(ValueError, match="Invalid"): - quad = S2([('gausslegendre', {}), ('lebedevlaikov', {})]) + quad = S2([("gausslegendre", {}), ("gausslegendre", {}), ("gausslegendre", {})]) with pytest.raises(ValueError, match="Invalid"): - quad = S2([('so3-montecarlo', {})]) + quad = S2([("gausslegendre", {}), ("lebedevlaikov", {})]) + with pytest.raises(ValueError, match="Invalid"): + quad = S2([("so3-montecarlo", {})]) # Invalid method options # Now given that the type of the specifier is correct and that a valid # combination of methods has been choosen, check the remaining options # for the method. - with pytest.raises(TypeError, match='not both'): # either degree or size - quad = S2([ - ('s2-gauss-lebedevlaikov', {'size':6, 'degree':3}), - ]) - with pytest.raises(TypeError, match='unexpected'): # unexpected argument - quad = S2([ - ('s2-gauss-lebedevlaikov', {'size':6, 'unexpected':True}), - ]) + with pytest.raises(TypeError, match="not both"): # either degree or size + quad = S2( + [ + ("s2-gauss-lebedevlaikov", {"size": 6, "degree": 3}), + ] + ) + with pytest.raises(TypeError, match="unexpected"): # unexpected argument + quad = S2( + [ + ("s2-gauss-lebedevlaikov", {"size": 6, "unexpected": True}), + ] + ) # Valid initializations with does_not_raise(): - quad = S2([ - ('gAuSslObAtTolEgEnDrE', {'size':5}), - ('trapezoid', {'size':5}), - ]) - quad = S2([ - ('simpson', {'size':5}), - ('Trapezoid', {'size':5}), - ]) - quad = S2([('s2-gauss-lebedevlaikov', {'size':6})]) - quad = S2([('s2-gauss-lebedevlaikov', {'degree':3})]) - quad = S2([ - ('none', {'points':[0]}), - ('trapezoid', {'size':5}), - ]) + quad = S2( + [ + ("gAuSslObAtTolEgEnDrE", {"size": 5}), + ("trapezoid", {"size": 5}), + ] + ) + quad = S2( + [ + ("simpson", {"size": 5}), + ("Trapezoid", {"size": 5}), + ] + ) + quad = S2([("s2-gauss-lebedevlaikov", {"size": 6})]) + quad = S2([("s2-gauss-lebedevlaikov", {"degree": 3})]) + quad = S2( + [ + ("none", {"points": [0]}), + ("trapezoid", {"size": 5}), + ] + ) def test_fields_product_method(): @@ -104,13 +115,15 @@ def test_fields_product_method(): n1 = 5 n2 = 6 x1 = np.linspace(-1, 1, n1) - quad = S2([ - ('trapezoid', {'size':n1}), - ('gausslegendre', {'size':n2}), - ]) + quad = S2( + [ + ("trapezoid", {"size": n1}), + ("gausslegendre", {"size": n2}), + ] + ) # test submethod properties: assert quad._methods[0].degree == 1 - assert quad._methods[1].degree == 2*n2-1 + assert quad._methods[1].degree == 2 * n2 - 1 assert quad._methods[0].size == n1 assert quad._methods[1].size == n2 assert len(quad._method_weights) == 2 @@ -121,22 +134,22 @@ def test_fields_product_method(): # test hidden properties assert quad._ndims == [1, 1] - assert quad._dims == [(0,), (1,)] # do I really need this? + assert quad._dims == [(0,), (1,)] # do I really need this? assert quad._sizes == [n1, n2] - assert quad._degrees == [1, 2*n2-1] - assert quad._points.size == (2*n1*n2) - assert quad._points.shape == (2, n1*n2) + assert quad._degrees == [1, 2 * n2 - 1] + assert quad._points.size == (2 * n1 * n2) + assert quad._points.shape == (2, n1 * n2) # test public properties: assert quad.dim == 2 - assert quad.size == n1*n2 + assert quad.size == n1 * n2 assert quad.shape == (n1, n2) - assert quad.weights.shape == (n1*n2,) - assert quad.angles.shape == (2, n1*n2) - assert quad.xyz.shape == (3, n1*n2) + assert quad.weights.shape == (n1 * n2,) + assert quad.angles.shape == (2, n1 * n2) + assert quad.xyz.shape == (3, n1 * n2) assert np.all(quad.angles == quad._points) - #assert quad.grid.angles.shape == (2, n1*n2) - #assert quad.grid.xyz.shape == (3, n1*n2) + # assert quad.grid.angles.shape == (2, n1*n2) + # assert quad.grid.xyz.shape == (3, n1*n2) assert quad.weights.reshape(quad.shape).shape == (n1, n2) assert quad.angles.reshape(2, *quad.shape).shape == (2, n1, n2) assert quad.xyz.reshape(3, *quad.shape).shape == (3, n1, n2) @@ -146,11 +159,13 @@ def test_fields_non_product_method(): """Test the various fields of the quadrature class. Here we test a non-product method. """ - degree = 3 # degree of scheme - n = 6 # number of sample points - quad = S2([ - ('s2-gauss-lebedevlaikov', {'degree':degree}), - ]) + degree = 3 # degree of scheme + n = 6 # number of sample points + quad = S2( + [ + ("s2-gauss-lebedevlaikov", {"degree": degree}), + ] + ) # test submethod properties: assert quad._methods[0].degree == degree assert quad._methods[0].size == n @@ -160,7 +175,7 @@ def test_fields_non_product_method(): # test hidden properties: assert quad._ndims == [2] - assert quad._dims == [(0, 1)] # do I really need this? + assert quad._dims == [(0, 1)] # do I really need this? assert quad._sizes == [n] assert quad._degrees == [degree] assert quad._points.shape == (2, n) @@ -174,34 +189,41 @@ def test_fields_non_product_method(): assert quad.xyz.shape == (3, n) print(quad.angles) assert np.all(quad.angles == quad._points) - #assert quad.grid.angles.shape == (2, n) - #assert quad.grid.xyz.shape == (3, n) + # assert quad.grid.angles.shape == (2, n) + # assert quad.grid.xyz.shape == (3, n) assert quad.weights.reshape(quad.shape).shape == (n,) assert quad.angles.reshape(2, *quad.shape).shape == (2, n) assert quad.xyz.reshape(3, *quad.shape).shape == (3, n) - def test_integration(): - quad = S2([ - ('gausslegendre', dict(size=6)), - ('trapezoid', dict(size=5)), - ], polar_sampling='cos') + quad = S2( + [ + ("gausslegendre", dict(size=6)), + ("trapezoid", dict(size=5)), + ], + polar_sampling="cos", + ) assert quad.integrate(f) == pytest.approx(1) f_samples = f(*quad.angles) assert quad.integrate(f_samples) == pytest.approx(1) - quad = S2([ - ('gausslegendre', dict(size=6)), - ('trapezoid', dict(size=5)), - ], polar_sampling='angle') + quad = S2( + [ + ("gausslegendre", dict(size=6)), + ("trapezoid", dict(size=5)), + ], + polar_sampling="angle", + ) assert quad.integrate(f) == pytest.approx(1) f_samples = f(*quad.angles) assert quad.integrate(f_samples) == pytest.approx(1) - quad = S2([ - ('s2-gauss-lebedevlaikov', {'degree':9}), - ]) + quad = S2( + [ + ("s2-gauss-lebedevlaikov", {"degree": 9}), + ] + ) assert quad.integrate(f) == pytest.approx(1) f_samples = f(*quad.angles) assert quad.integrate(f_samples) == pytest.approx(1) diff --git a/tests/test_SO3_quadrature.py b/tests/test_SO3_quadrature.py index a4342be..6c61cf9 100644 --- a/tests/test_SO3_quadrature.py +++ b/tests/test_SO3_quadrature.py @@ -10,7 +10,7 @@ from openquad import SO3 -#@pytest.fixture() +# @pytest.fixture() def f_q(quaternions): """Test integrand for quaternions. Integral should yield 1. @@ -26,10 +26,10 @@ def f_q(quaternions): assert poly.shape == (len(quaternions),) else: assert poly.shape == () - return poly / (8*np.pi**2) + return poly / (8 * np.pi**2) -#@pytest.fixture() +# @pytest.fixture() def f_abg(alpha, beta, gamma): """Test integrand for Euler angles. Integral should yield 1. @@ -39,7 +39,7 @@ def f_abg(alpha, beta, gamma): return f_q(quaternions) -#@pytest.fixture() +# @pytest.fixture() def f_vector_q(quaternions): """Test vector integrand, containing the orientations in the first axis. Integral should yield 1. @@ -47,80 +47,97 @@ def f_vector_q(quaternions): l_max = 1 wigner = spherical.Wigner(l_max) idx_min = wigner.Dindex(1, -1, -1) - idx_max = wigner.Dindex(1+1, -1+1, -2+1) - poly = ( - 1 - + 1 * wigner.D(quaternions)[..., idx_min:idx_max].reshape(-1, 3, 3) - ) + idx_max = wigner.Dindex(1 + 1, -1 + 1, -2 + 1) + poly = 1 + 1 * wigner.D(quaternions)[..., idx_min:idx_max].reshape(-1, 3, 3) assert poly.shape == (len(quaternions), 3, 3) - return poly / (8*np.pi**2) + return poly / (8 * np.pi**2) def test_test_function(): """Make sure that the integral over the test function yields 1.""" - assert integrate.tplquad(lambda a, b, g: np.sin(b)*f_abg(a, b, g).real, 0, 2*np.pi, 0, np.pi, 0, 2*np.pi)[0] == pytest.approx(1) - #assert integrate.tplquad(lambda a, b, g: np.sin(b)*f_abg(a, b, g).imag, 0, 2*np.pi, 0, np.pi, 0, 2*np.pi, epsabs=1e-1)[0] == pytest.approx(0) + assert integrate.tplquad( + lambda a, b, g: np.sin(b) * f_abg(a, b, g).real, + 0, + 2 * np.pi, + 0, + np.pi, + 0, + 2 * np.pi, + )[0] == pytest.approx(1) + # assert integrate.tplquad(lambda a, b, g: np.sin(b)*f_abg(a, b, g).imag, 0, 2*np.pi, 0, np.pi, 0, 2*np.pi, epsabs=1e-1)[0] == pytest.approx(0) def test_initialization(): # Wrong initializations # Before checking the method specification for consistency, # the methods shall raise an error, if a wrong type is given. - with pytest.raises(TypeError): # missing method specifier + with pytest.raises(TypeError): # missing method specifier quad = SO3() - with pytest.raises(ValueError, match="empty"): # empty method specifier + with pytest.raises(ValueError, match="empty"): # empty method specifier quad = SO3([]) # Invalid methods # Given the type of the specifier is correct, first the validity of the # method shall be checked before checking the remaining options. with pytest.raises(ValueError, match="Invalid"): - quad = SO3([('trapezoid', {})]) + quad = SO3([("trapezoid", {})]) with pytest.raises(ValueError, match="Invalid"): - quad = SO3([('s2-gauss-lebedevlaikov', {})]) + quad = SO3([("s2-gauss-lebedevlaikov", {})]) with pytest.raises(ValueError, match="Invalid"): - quad = SO3([ - ('simpson', {}), - ('simpson', {}), - ('simpson', {}), - ('simpson', {}), - ]) + quad = SO3( + [ + ("simpson", {}), + ("simpson", {}), + ("simpson", {}), + ("simpson", {}), + ] + ) with pytest.raises(ValueError, match="Invalid"): - quad = SO3([ - ('s2-gauss-lebedevlaikov', {}), - ('gausslegendre', {}), - ('gausslegendre', {}) - ]) + quad = SO3( + [ + ("s2-gauss-lebedevlaikov", {}), + ("gausslegendre", {}), + ("gausslegendre", {}), + ] + ) with pytest.raises(ValueError, match="Invalid"): - quad = SO3([('s2-gauss-lebedevlaikov', {}), ('s2-gauss-lebedevlaikov', {})]) + quad = SO3([("s2-gauss-lebedevlaikov", {}), ("s2-gauss-lebedevlaikov", {})]) # Invalid method options # Now given that the type of the specifier is correct and that a valid # combination of methods has been choosen, check the remaining options # for the method. - with pytest.raises(TypeError, match='not both'): # either degree or size - quad = SO3([ - ('s2-gauss-lebedevlaikov', {'size':6, 'degree':3}), - ('gausslegendre', {'size':6, 'degree':11}), - ]) - with pytest.raises(TypeError, match='unexpected'): # unexpected argument - quad = SO3([ - ('so3-montecarlo', {'size':6, 'unexpected':True}), - ]) + with pytest.raises(TypeError, match="not both"): # either degree or size + quad = SO3( + [ + ("s2-gauss-lebedevlaikov", {"size": 6, "degree": 3}), + ("gausslegendre", {"size": 6, "degree": 11}), + ] + ) + with pytest.raises(TypeError, match="unexpected"): # unexpected argument + quad = SO3( + [ + ("so3-montecarlo", {"size": 6, "unexpected": True}), + ] + ) # Valid initializations with does_not_raise(): - quad = SO3([ - ('s2-gauss-LebeDevlaikov', {'degree':5}), - ('Trapezoid', {'size':5}), - ]) - quad = SO3([ - ('simpson', {'size':5}), - ('Trapezoid', {'size':5}), - ('Gausslegendre', {'size':5}), - ]) - quad = SO3([('so3-montecarlo', {'size':5})]) - quad = SO3([('so3-montecarlo', {'size':5, 'seed':1})]) + quad = SO3( + [ + ("s2-gauss-LebeDevlaikov", {"degree": 5}), + ("Trapezoid", {"size": 5}), + ] + ) + quad = SO3( + [ + ("simpson", {"size": 5}), + ("Trapezoid", {"size": 5}), + ("Gausslegendre", {"size": 5}), + ] + ) + quad = SO3([("so3-montecarlo", {"size": 5})]) + quad = SO3([("so3-montecarlo", {"size": 5, "seed": 1})]) def test_fields(): @@ -128,10 +145,12 @@ def test_fields(): degree_12 = 3 n12 = 6 n3 = 4 - quad = SO3([ - ('s2-gauss-lebedevlaikov', {'degree': degree_12}), - ('trapezoid', {'size': n3}), - ]) + quad = SO3( + [ + ("s2-gauss-lebedevlaikov", {"degree": degree_12}), + ("trapezoid", {"size": n3}), + ] + ) # test submethod properties: assert quad._methods[0].degree == degree_12 assert quad._methods[1].degree == 1 @@ -144,22 +163,22 @@ def test_fields(): # test private properties assert quad._ndims == [2, 1] - assert quad._dims == [(0, 1), (2,)] # do I really need this? + assert quad._dims == [(0, 1), (2,)] # do I really need this? assert quad._sizes == [n12, n3] assert quad._degrees == [degree_12, 1] - assert quad._points.size == (3*n12*n3) - assert quad._points.shape == (3, n12*n3) + assert quad._points.size == (3 * n12 * n3) + assert quad._points.shape == (3, n12 * n3) # test public properties: assert quad.dim == 3 - assert quad.size == n12*n3 + assert quad.size == n12 * n3 assert quad.shape == (n12, n3) - assert quad.weights.shape == (n12*n3,) - assert quad.angles.shape == (3, n12*n3) - assert quad.quaternions.shape == (n12*n3, 4) + assert quad.weights.shape == (n12 * n3,) + assert quad.angles.shape == (3, n12 * n3) + assert quad.quaternions.shape == (n12 * n3, 4) assert np.all(quad.angles == quad._points) - #assert quad.grid.angles.shape == (3, n12*n3) - #assert quad.grid.quaternions.shape == (n12*n3, 4) ??? + # assert quad.grid.angles.shape == (3, n12*n3) + # assert quad.grid.quaternions.shape == (n12*n3, 4) ??? assert quad.weights.reshape(quad.shape).shape == (n12, n3) assert quad.angles.reshape(3, *quad.shape).shape == (3, n12, n3) assert quad.quaternions.reshape(*quad.shape, 4).shape == (n12, n3, 4) @@ -169,36 +188,46 @@ def test_integration(): """Test integration for different methods. Euler angles are used in this test. """ - quad = SO3([ - ('trapezoid', dict(size=7)), - ('gausslegendre', dict(size=9)), - ('trapezoid', dict(size=5)), - ], polar_sampling='cos') + quad = SO3( + [ + ("trapezoid", dict(size=7)), + ("gausslegendre", dict(size=9)), + ("trapezoid", dict(size=5)), + ], + polar_sampling="cos", + ) assert quad.integrate(f_abg) == pytest.approx(1) f_samples = f_abg(*quad.angles) assert quad.integrate(f_samples) == pytest.approx(1) - quad = SO3([ - ('trapezoid', dict(size=7)), - ('gausslegendre', dict(size=9)), - ('trapezoid', dict(size=5)), - ], polar_sampling='angle') + quad = SO3( + [ + ("trapezoid", dict(size=7)), + ("gausslegendre", dict(size=9)), + ("trapezoid", dict(size=5)), + ], + polar_sampling="angle", + ) assert quad.integrate(f_abg) == pytest.approx(1) f_samples = f_abg(*quad.angles) assert quad.integrate(f_samples) == pytest.approx(1) - quad = SO3([ - ('trapezoid', {'size':11}), - ('s2-gauss-lebedevlaikov', {'degree':5}), - ]) + quad = SO3( + [ + ("trapezoid", {"size": 11}), + ("s2-gauss-lebedevlaikov", {"degree": 5}), + ] + ) assert quad.integrate(f_abg) == pytest.approx(1) f_samples = f_abg(*quad.angles) assert quad.integrate(f_samples) == pytest.approx(1) - quad = SO3([ - ('s2-gauss-lebedevlaikov', {'degree':5}), - ('trapezoid', {'size':11}), - ]) + quad = SO3( + [ + ("s2-gauss-lebedevlaikov", {"degree": 5}), + ("trapezoid", {"size": 11}), + ] + ) assert quad.integrate(f_abg) == pytest.approx(1) f_samples = f_abg(*quad.angles) assert quad.integrate(f_samples) == pytest.approx(1) @@ -210,9 +239,11 @@ def test_integration(): ) def test_integration_monte_carlo(): """Test integration with Monte Carlo sampling.""" - quad = SO3([ - ('so3-montecarlo', {'size':500, 'seed':0}), - ]) + quad = SO3( + [ + ("so3-montecarlo", {"size": 500, "seed": 0}), + ] + ) assert quad.integrate(f_abg) == pytest.approx(1) f_samples = f_abg(*quad.angles) assert quad.integrate(f_samples) == pytest.approx(1) @@ -220,20 +251,24 @@ def test_integration_monte_carlo(): def test_integration_quaternions(): """Test integration with quaternions.""" - quad = SO3([ - ('s2-gauss-lebedevlaikov', {'degree':5}), - ('trapezoid', {'size':11}), - ]) + quad = SO3( + [ + ("s2-gauss-lebedevlaikov", {"degree": 5}), + ("trapezoid", {"size": 11}), + ] + ) f_samples = f_q(quad.quaternions) assert quad.integrate(f_samples) == pytest.approx(1) def test_integration_axis(): """Test axis keyword in integration method.""" - quad = SO3([ - ('s2-gauss-lebedevlaikov', {'degree':7}), - ('trapezoid', {'size':11}), - ]) + quad = SO3( + [ + ("s2-gauss-lebedevlaikov", {"degree": 7}), + ("trapezoid", {"size": 11}), + ] + ) f_vector = f_vector_q(quad.quaternions) result = quad.integrate(f_vector, axis=0) assert result.shape == (3, 3) diff --git a/tests/test_base_1d_quadrature_methods.py b/tests/test_base_1d_quadrature_methods.py index 2051e6a..c88b6dc 100644 --- a/tests/test_base_1d_quadrature_methods.py +++ b/tests/test_base_1d_quadrature_methods.py @@ -7,10 +7,11 @@ from openquad.newton_cotes import CompositeTrapezoid, CompositeSimpson, Romberg from openquad.gauss import GaussLegendre, GaussLobattoLegendre -#@pytest.fixture() + +# @pytest.fixture() def f(x): """Test integrand. Integral should yield 1.""" - return (5*x + 4*x**2 + 3*x**3 + 2*x**4 + 1*x**5) / 215750 + return (5 * x + 4 * x**2 + 3 * x**3 + 2 * x**4 + 1 * x**5) / 215750 def test_test_function(): @@ -28,7 +29,7 @@ def test_test_function(): (Romberg, False), (GaussLegendre, True), (GaussLobattoLegendre, True), - ] + ], ) def test_initialization(method, has_poly_acc): # missing required arguments @@ -42,7 +43,7 @@ def test_initialization(method, has_poly_acc): quad = method(size=5, b=1) with pytest.raises(TypeError): quad = method(a=0, b=1) - + # duplicate arguments if has_poly_acc: with pytest.raises(TypeError, match="not both"): @@ -82,9 +83,9 @@ def test_initialization(method, has_poly_acc): (CompositeSimpson, 21, True, lambda size: 3), (CompositeSimpson, 22, True, lambda size: 3), (Romberg, 9, False, lambda size: None), - (GaussLegendre, 5, True, lambda size: 2*size - 1), - (GaussLobattoLegendre, 5, True, lambda size: 2*size - 3), - ] + (GaussLegendre, 5, True, lambda size: 2 * size - 1), + (GaussLobattoLegendre, 5, True, lambda size: 2 * size - 3), + ], ) def test_fields_and_integration(method, size, has_normalized_weights, poly_acc): a = 0 @@ -99,7 +100,7 @@ def test_fields_and_integration(method, size, has_normalized_weights, poly_acc): # test weights if has_normalized_weights: - assert np.sum(quad.weights) == pytest.approx(b-a) + assert np.sum(quad.weights) == pytest.approx(b - a) else: assert np.all(quad.weights == np.ones(size)) @@ -119,14 +120,15 @@ def test_fields_and_integration(method, size, has_normalized_weights, poly_acc): [ (GaussLegendre, 1e-13), pytest.param( - GaussLobattoLegendre, 1e-13, + GaussLobattoLegendre, + 1e-13, marks=pytest.mark.xfail( reason="Error 1.7e-12 against required 1e-13. Gauss-Lobatto weights " "are also wrong at larger sizes: at size 30 they sum to 2.169 " "instead of 3 on [-1, 2]", ), ), - ] + ], ) def test_poly_acc(method, tol): """Test the polynomial accuracy of the given method by checking that all @@ -134,18 +136,19 @@ def test_poly_acc(method, tol): Here, Legendre polynomials integrated from -1 to 1. """ - max_degree = 100 - for degree in np.arange(max_degree +1): + max_degree = 100 + for degree in np.arange(max_degree + 1): quad = method(degree=degree, a=-1, b=1) # First, test that the weights are normalized: assert np.sum(quad.weights) == pytest.approx(2) # Then, test the integration of all polynomials: - orders = np.arange(degree+1)[:, np.newaxis] + orders = np.arange(degree + 1)[:, np.newaxis] Pls = special.eval_legendre(orders, quad.points) results = quad.integrate(Pls, axis=-1) - truevals = np.concatenate(([2], np.zeros(Pls.shape[0]-1))) + truevals = np.concatenate(([2], np.zeros(Pls.shape[0] - 1))) assert np.abs(results - truevals).max() == pytest.approx(0, abs=tol) + def none_type_quadrature(): points = np.linspace(0, 1, 10) quad = NoQuadrature(points=points) diff --git a/tests/test_base_2d_quadrature_methods.py b/tests/test_base_2d_quadrature_methods.py index ce4083d..263421c 100644 --- a/tests/test_base_2d_quadrature_methods.py +++ b/tests/test_base_2d_quadrature_methods.py @@ -23,13 +23,17 @@ def f(theta, phi): + 4 * special.sph_harm_y(4, 2, theta, phi) + 5 * special.sph_harm_y(5, 4, theta, phi) ) - return poly / (4*np.pi) + return poly / (4 * np.pi) def test_testfuction(): """Make sure that the integral over the test function yields 1.""" - assert integrate.dblquad(lambda t, p: np.sin(t)*f(t, p).real, 0, 2*np.pi, 0, np.pi)[0] == pytest.approx(1) - assert integrate.dblquad(lambda t, p: np.sin(t)*f(t, p).imag, 0, 2*np.pi, 0, np.pi)[0] == pytest.approx(0) + assert integrate.dblquad( + lambda t, p: np.sin(t) * f(t, p).real, 0, 2 * np.pi, 0, np.pi + )[0] == pytest.approx(1) + assert integrate.dblquad( + lambda t, p: np.sin(t) * f(t, p).imag, 0, 2 * np.pi, 0, np.pi + )[0] == pytest.approx(0) @pytest.mark.parametrize( @@ -41,7 +45,7 @@ def test_testfuction(): (WomersleyS2Design, 6, 3, True), (FibonacciSphere, 13, None, False), (ZCW2, 21, None, False), - ] + ], ) def test_initialization(method, size, degree, has_degree): # missing required arguments @@ -80,28 +84,34 @@ def test_initialization(method, size, degree, has_degree): (LebedevLaikov, 14, 5, {}), (GraefS2Gauss, 12, 5, {}), (GraefS2Design, 12, 5, {}), - (WomersleyS2Design, 12, 5, {'symmetric':True}), - (WomersleyS2Design, 18, 5, {'symmetric':False}), + (WomersleyS2Design, 12, 5, {"symmetric": True}), + (WomersleyS2Design, 18, 5, {"symmetric": False}), pytest.param( - FibonacciSphere, 21, None, {}, + FibonacciSphere, + 21, + None, + {}, marks=pytest.mark.xfail( reason="Covering without a degree: integral 0.975 against required " "1 +- 1e-6. Tolerance suspected, unconfirmed", ), ), pytest.param( - ZCW2, 21, None, {}, + ZCW2, + 21, + None, + {}, marks=pytest.mark.xfail( reason="Covering without a degree: integral 0.940 against required " "1 +- 1e-6. Tolerance suspected, unconfirmed", ), ), - ] + ], ) def test_fields_and_integration(method, size, degree, kwargs): tol = 1e-6 quad = method(size=size, **kwargs) - + # test fields assert quad.dim == 2 assert quad.degree == degree @@ -109,7 +119,7 @@ def test_fields_and_integration(method, size, degree, kwargs): # test weights assert quad.weights.shape == (size,) - assert np.sum(quad.weights) == pytest.approx(4*np.pi) + assert np.sum(quad.weights) == pytest.approx(4 * np.pi) # test grid dimension assert quad.points.shape == (2, size) @@ -123,7 +133,6 @@ def test_fields_and_integration(method, size, degree, kwargs): assert quad.integrate(f_samples) == pytest.approx(1, rel=tol) - @pytest.mark.parametrize( "method, tol, kwargs", [ @@ -131,7 +140,7 @@ def test_fields_and_integration(method, size, degree, kwargs): (GraefS2Gauss, 1e-9, {}), (GraefS2Design, 1e-8, {}), (WomersleyS2Design, 1e-12, {}), - ] + ], ) def test_poly_acc(method, tol, kwargs): max_degree = 50 @@ -141,12 +150,10 @@ def test_poly_acc(method, tol, kwargs): for degree in tested_degree: quad = method(degree=degree, **kwargs) # First, test that the weights are normalized: - assert np.sum(quad.weights) == pytest.approx(4*np.pi) + assert np.sum(quad.weights) == pytest.approx(4 * np.pi) # Then, test the integration of all polynomials: q = quaternionic.array.from_spherical_coordinates(*quad.angles) - Ylm = wigner.sYlm(0, q)[:, :wigner.Yindex(degree, degree)+1] + Ylm = wigner.sYlm(0, q)[:, : wigner.Yindex(degree, degree) + 1] results = quad.integrate(Ylm, axis=0) - truevals = np.concatenate( - ([np.sqrt(4*np.pi)], np.zeros(Ylm.shape[-1]-1)) - ) + truevals = np.concatenate(([np.sqrt(4 * np.pi)], np.zeros(Ylm.shape[-1] - 1))) assert np.abs(results - truevals).max() == pytest.approx(0, abs=tol) diff --git a/tests/test_base_3d_quadrature_methods.py b/tests/test_base_3d_quadrature_methods.py index 75468b3..8cabd49 100644 --- a/tests/test_base_3d_quadrature_methods.py +++ b/tests/test_base_3d_quadrature_methods.py @@ -29,7 +29,7 @@ def f_q(quaternions): assert poly.shape == (len(quaternions),) else: assert poly.shape == () - return poly / (8*np.pi**2) + return poly / (8 * np.pi**2) def f_abg(alpha, beta, gamma): @@ -43,8 +43,16 @@ def f_abg(alpha, beta, gamma): def test_test_function(): """Make sure that the integral over the test function yields 1.""" - assert integrate.tplquad(lambda a, b, g: np.sin(b)*f_abg(a, b, g).real, 0, 2*np.pi, 0, np.pi, 0, 2*np.pi)[0] == pytest.approx(1) - #assert integrate.tplquad(lambda a, b, g: np.sin(b)*f_abg(a, b, g).imag, 0, 2*np.pi, 0, np.pi, 0, 2*np.pi, epsabs=1e-1)[0] == pytest.approx(0) + assert integrate.tplquad( + lambda a, b, g: np.sin(b) * f_abg(a, b, g).real, + 0, + 2 * np.pi, + 0, + np.pi, + 0, + 2 * np.pi, + )[0] == pytest.approx(1) + # assert integrate.tplquad(lambda a, b, g: np.sin(b)*f_abg(a, b, g).imag, 0, 2*np.pi, 0, np.pi, 0, 2*np.pi, epsabs=1e-1)[0] == pytest.approx(0) @pytest.mark.parametrize( @@ -53,10 +61,10 @@ def test_test_function(): (MonteCarloSO3, 10, None), (GraefSO3Gauss, 4, 1), (GraefSO3Chebyshev, 4, 1), - #(WomersleySO3Chebyshev, 4, 1), - #(ZCW3, 4, None), + # (WomersleySO3Chebyshev, 4, 1), + # (ZCW3, 4, None), (KarneySO3, 24, None), - ] + ], ) def test_initialization(method, size, degree): # missing required arguments @@ -93,22 +101,26 @@ def test_initialization(method, size, degree): "method, size, degree, tol, kwargs", [ pytest.param( - MonteCarloSO3, 1000, None, 1e-2, {'seed':0, 'method':'quaternions'}, + MonteCarloSO3, + 1000, + None, + 1e-2, + {"seed": 0, "method": "quaternions"}, marks=pytest.mark.xfail( reason="Monte Carlo error of 2-4% against required 1e-2. " "Tolerance suspected, unconfirmed", ), ), - (MonteCarloSO3, 5000, None, 1e-2, {'seed':0, 'method':'angles'}), + (MonteCarloSO3, 5000, None, 1e-2, {"seed": 0, "method": "angles"}), (KarneySO3, 24, None, 1e-8, {}), (GraefSO3Gauss, 23, 3, 1e-8, {}), (GraefSO3Chebyshev, 24, 3, 1e-8, {}), - #(WomersleySO3Chebyshev, 10, 10, 1e-8, {}), - ] + # (WomersleySO3Chebyshev, 10, 10, 1e-8, {}), + ], ) def test_fields_and_integration(method, size, degree, tol, kwargs): quad = method(size=size, **kwargs) - + # test fields assert quad.dim == 3 assert quad.degree == degree @@ -116,7 +128,7 @@ def test_fields_and_integration(method, size, degree, tol, kwargs): # test weights assert quad.weights.shape == (size,) - assert np.sum(quad.weights) == pytest.approx(8*np.pi**2) + assert np.sum(quad.weights) == pytest.approx(8 * np.pi**2) # test grid dimension assert quad.points.shape == (3, size) @@ -133,11 +145,11 @@ def test_fields_and_integration(method, size, degree, tol, kwargs): @pytest.mark.parametrize( "method, tol, kwargs", [ - #TODO: set accuracy + # TODO: set accuracy (GraefSO3Gauss, 1e-9, {}), (GraefSO3Chebyshev, 1e-6, {}), - #(WomersleySO3Chebyshev, 1e-12, {}), - ] + # (WomersleySO3Chebyshev, 1e-12, {}), + ], ) def test_degree(method, tol, kwargs): max_degree = 30 @@ -147,12 +159,10 @@ def test_degree(method, tol, kwargs): for degree in tested_degrees: quad = method(degree=degree, **kwargs) # First, test that the weights are normalized: - assert np.sum(quad.weights) == pytest.approx(8*np.pi**2) + assert np.sum(quad.weights) == pytest.approx(8 * np.pi**2) # Then, test the integration of all polynomials: q = quaternionic.array.from_euler_angles(*quad.angles) - Dlmm = wigner.D(q)[:, :wigner.Dindex(degree, degree, degree)+1] + Dlmm = wigner.D(q)[:, : wigner.Dindex(degree, degree, degree) + 1] results = quad.integrate(Dlmm, axis=0) - truevals = np.concatenate( - ([8*np.pi**2], np.zeros(Dlmm.shape[-1]-1)) - ) + truevals = np.concatenate(([8 * np.pi**2], np.zeros(Dlmm.shape[-1] - 1))) assert np.abs(results - truevals).max() == pytest.approx(0, abs=tol) From 86d68adf9aeb9d65a9554d269480297bb040b337 Mon Sep 17 00:00:00 2001 From: Alexander Blech Date: Tue, 10 Nov 2026 04:00:59 +0100 Subject: [PATCH 4/7] Skip the format commit in git blame Co-Authored-By: Claude Opus 5.5 --- .git-blame-ignore-revs | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..0abce45 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# Commits that only reformat code, skipped by `git blame` and GitHub's blame view. +# Use locally with: git config blame.ignoreRevsFile .git-blame-ignore-revs + +# Format code with ruff +f3fde52c38ffb0d84709b2184990f1d1dcb5c06f From 7cca00af13e6194ac8b38c8787c8c1ca75c2faeb Mon Sep 17 00:00:00 2001 From: Alexander Blech Date: Tue, 10 Nov 2026 04:01:36 +0100 Subject: [PATCH 5/7] Ignore existing lint findings per file The 113 findings present after formatting are listed by rule per file, not fixed. New files get the full rule set. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index dec9c3e..3f06e11 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -111,3 +111,33 @@ select = [ [tool.ruff.lint.isort] known-first-party = ["openquad"] + +[tool.ruff.lint.per-file-ignores] +# Findings present when ruff was introduced, not fixed yet. Remove a code once the +# file is fixed or replaced. New files get the full rule set. +"doc/conf.py" = ["F401", "SIM114"] +"src/conftest.py" = ["I001"] +"src/openquad/__init__.py" = ["F401", "I001", "RUF022"] +"src/openquad/base.py" = [ + "B006", "B024", "B904", "E722", "I001", "PIE790", "RET505", "SIM102", "SIM108", +] +"src/openquad/fibonacci.py" = ["I001", "RET506"] +"src/openquad/geometries.py" = [ + "B006", "B007", "B905", "F541", "I001", "PIE790", "PT018", "RET503", "RET505", + "RET506", "RUF012", "SIM113", "SIM114", "W293", +] +"src/openquad/graef.py" = ["I001"] +"src/openquad/grid.py" = ["E501", "I001"] +"src/openquad/karney.py" = ["I001"] +"src/openquad/monte_carlo.py" = ["F821", "I001"] +"src/openquad/newton_cotes.py" = ["F401", "I001"] +"src/openquad/womersley.py" = ["I001", "SIM108"] +"tests/test_Rn_quadrature.py" = ["F841", "I001"] +"tests/test_S2_quadrature.py" = ["C408", "E501", "F841", "I001"] +"tests/test_SO3_quadrature.py" = ["C408", "E501", "F841", "I001"] +"tests/test_base.py" = ["F401", "I001", "SIM118"] +"tests/test_base_1d_quadrature_methods.py" = [ + "E731", "F821", "F841", "I001", "PT006", "PT011", +] +"tests/test_base_2d_quadrature_methods.py" = ["F401", "F841", "I001", "PT006"] +"tests/test_base_3d_quadrature_methods.py" = ["E501", "F401", "F841", "I001", "PT006"] From 265dddef53c54097ab44ffe75352201be1dcb543 Mon Sep 17 00:00:00 2001 From: Alexander Blech Date: Tue, 10 Nov 2026 04:02:57 +0100 Subject: [PATCH 6/7] Fix spelling found by codespell Comments, docstrings and documentation only. Reson, as in J. Magn. Reson., is added to the codespell ignore list. Co-Authored-By: Claude Opus 5.5 --- doc/api/methods.rst | 12 ++++++------ doc/contributing/contributing.rst | 2 +- doc/contributing/index.rst | 2 +- doc/index.rst | 2 +- doc/using/howtos.rst | 2 +- doc/using/intro_package.rst | 2 +- doc/using/intro_using.rst | 2 +- pyproject.toml | 4 ++++ src/openquad/geometries.py | 6 +++--- src/openquad/grid.py | 4 ++-- src/openquad/monte_carlo.py | 2 +- tests/test_Rn_quadrature.py | 2 +- tests/test_S2_quadrature.py | 2 +- tests/test_SO3_quadrature.py | 2 +- 14 files changed, 25 insertions(+), 21 deletions(-) diff --git a/doc/api/methods.rst b/doc/api/methods.rst index 37ff323..f30a4a0 100644 --- a/doc/api/methods.rst +++ b/doc/api/methods.rst @@ -20,14 +20,14 @@ The first entry denotes the input string for the method specification, cf. the * ``Romberg``: `Romberg's method `_, see :func:`scipy.integrate.romberg` * ``1d-MonteCarlo``:`Monte Carlo integration `_ -These methods need the following additional keyword paramters: +These methods need the following additional keyword parameters: * ``size``: float: Number of sampling points. * ``degree``: float: Degree of exactness. For Gauss methods alternative to ``size``. * ``a`` : float: Lower boundary of the integral. * ``b`` : float: Upper boundary of the integral. * ``jacobian`` : callable, optional: Jacobian to apply to the coordinate. -* ``periodic`` : logical, optinal: If ``True``, assume periodic boundary conditions. +* ``periodic`` : logical, optional: If ``True``, assume periodic boundary conditions. :math:`\mathrm{S}^2` methods @@ -41,10 +41,10 @@ These methods need the following additional keyword paramters: * ``S2-Covering-ZCW``: near-uniform coverings with the `ZCW`_ method * ``S2-MonteCarlo``: `Monte Carlo integration `_ -These methods need the following additional keyword paramters: +These methods need the following additional keyword parameters: * ``size``: float: Number of sampling points. -* ``degree``: float: Degree of exactness. For Gauss methods and spherical desings alternative to ``size``. +* ``degree``: float: Degree of exactness. For Gauss methods and spherical designs alternative to ``size``. :math:`\mathrm{SO}(3)` methods @@ -55,7 +55,7 @@ These methods need the following additional keyword paramters: * ``SO3-Covering-Karney``: near-uniform coverings from `Charles Karney`_ * ``SO3-MonteCarlo``: `Monte Carlo integration `_ -These methods need the following additional keyword paramters: +These methods need the following additional keyword parameters: * ``size``: float: Number of sampling points. * ``degree``: float: Degree of exactness. For Gauss and Chebyshev methods alternative to ``size``. @@ -66,7 +66,7 @@ These methods need the following additional keyword paramters: The following extensions are planned for the next release: * Implementing the three-dimensional unit sphere, :math:`\mathrm{S}^3`. - * Adding spherical desings and coverings from `Neil Sloane and Ronald Hardin`_. + * Adding spherical designs and coverings from `Neil Sloane and Ronald Hardin`_. * Providing a way to use :math:`\mathrm{S}^3` quadratures for :math:`\mathrm{SO}(3)` and vice versa. * Implementing a class for the unit circle, :math:`\mathrm{S}^1`. diff --git a/doc/contributing/contributing.rst b/doc/contributing/contributing.rst index 3c9b924..2f35af3 100644 --- a/doc/contributing/contributing.rst +++ b/doc/contributing/contributing.rst @@ -52,7 +52,7 @@ issues in commits. .. _Linking a pull request to an issue: https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue -Relases follow `semantic versioning`_ and need to be compatible with `PyPA +Releases follow `semantic versioning`_ and need to be compatible with `PyPA version specifiers`_ (former `PEP440`_). .. _semantic versioning: https://semver.org/ diff --git a/doc/contributing/index.rst b/doc/contributing/index.rst index 7dfb2d6..73e5122 100644 --- a/doc/contributing/index.rst +++ b/doc/contributing/index.rst @@ -1,6 +1,6 @@ .. _contributing: -Contributer guide +Contributor guide ================= Contributions are very welcome! Whether you're reporting bugs, suggesting new diff --git a/doc/index.rst b/doc/index.rst index 324e43d..ecf8c07 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -10,7 +10,7 @@ OpenQuad documentation User guide Tutorials API reference - Contributer guide + Contributor guide .. Cite me **Version**: |release| diff --git a/doc/using/howtos.rst b/doc/using/howtos.rst index e73280d..1fa9145 100644 --- a/doc/using/howtos.rst +++ b/doc/using/howtos.rst @@ -3,7 +3,7 @@ How-tos ------- -Recipies to achieve common tasks using |openquad|, targeted towards users familiar with the basic concepts. +Recipes to achieve common tasks using |openquad|, targeted towards users familiar with the basic concepts. For detailed description of the classes and methods contained in |openquad|, see the :ref:`API reference `. diff --git a/doc/using/intro_package.rst b/doc/using/intro_package.rst index 33ad300..92994e4 100644 --- a/doc/using/intro_package.rst +++ b/doc/using/intro_package.rst @@ -11,7 +11,7 @@ features. Currently, the following geometries are implemented: -- :math:`n`-dimensional Euclidian spaces, :math:`\mathrm{R}^n`: :class:`openquad.Rn` +- :math:`n`-dimensional Euclidean spaces, :math:`\mathrm{R}^n`: :class:`openquad.Rn` - the surface of the 2d unit sphere, :math:`\mathrm{S}^2`: :class:`openquad.S2` - the space of all orientations in 3d-space, i.e., the rotation group :math:`\mathrm{SO}(3)`: :class:`openquad.SO3` diff --git a/doc/using/intro_using.rst b/doc/using/intro_using.rst index 4f9d4d8..fec90ff 100644 --- a/doc/using/intro_using.rst +++ b/doc/using/intro_using.rst @@ -56,7 +56,7 @@ Sample points and weights """"""""""""""""""""""""" Sample points and weights are stored as NumPy arrays in :attr:`~openquad.S2.points` and -:attr:`~openquad.S2.weights`, respecitvely. +:attr:`~openquad.S2.weights`, respectively. .. doctest:: diff --git a/pyproject.toml b/pyproject.toml index 3f06e11..25c4a55 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -84,6 +84,10 @@ testpaths = ["tests"] # comment giving the reason. filterwarnings = ["error"] +[tool.codespell] +# "Reson" abbreviates the journal J. Magn. Reson. +ignore-words-list = "reson" + [tool.ruff] # The data tables are left as they are, as they will move out of the package. # Code examples in Markdown keep their hand-written layout. diff --git a/src/openquad/geometries.py b/src/openquad/geometries.py index 55c1356..827928c 100644 --- a/src/openquad/geometries.py +++ b/src/openquad/geometries.py @@ -116,7 +116,7 @@ def __init__(self, method_specs): method_objects = [] method_options = [] if len(method_specs) < 1: - raise ValueError("Method speficication must not be empty") + raise ValueError("Method specification must not be empty") for i, method_spec in enumerate(method_specs): method_str, options = deepcopy(method_spec) method_objects.append(self._select_method_object(method_str)) @@ -206,7 +206,7 @@ def _construct_weights_and_meshgrids(self): if self._ndims[0] == self.dim: # the points form already the meshgrid meshgrid = self._method_points[0] - # TODO: make sure it is contigous? + # TODO: make sure it is contiguous? # TODO: could be merged with the case below? elif np.all(np.asarray(self._ndims) == 1): # If all subgrids have dimension one, it is easy: @@ -332,7 +332,7 @@ def integrate( # (0, 1) # ((0, 1), 2) #no! dim = None - if dim is not None: # integrate speficic dimensions + if dim is not None: # integrate specific dimensions # This blew up in complexity; I won't allow it for now. raise NotImplementedError if np.ndim(dim) == 0: diff --git a/src/openquad/grid.py b/src/openquad/grid.py index 7f34fae..934f26e 100644 --- a/src/openquad/grid.py +++ b/src/openquad/grid.py @@ -67,7 +67,7 @@ def xyz_from_angles(theta_phi, axis=0): def euler_angles_from_quaternions(quaternions, axis=0): """Convert quaternions to Euler angles. - Paramters + Parameters --------- angles : quaternion array Array of quaternions @@ -90,7 +90,7 @@ def euler_angles_from_quaternions(quaternions, axis=0): def quaternions_from_euler_angles(angles, axis=0): """Convert Euler angles to quaternions. - Paramters + Parameters --------- angles : array_like Array of Euler angles. diff --git a/src/openquad/monte_carlo.py b/src/openquad/monte_carlo.py index 1637288..66649a0 100644 --- a/src/openquad/monte_carlo.py +++ b/src/openquad/monte_carlo.py @@ -68,7 +68,7 @@ def _points_weights(self, seed): def _sample_spherical_polar_angles(self, n, seed=None): """Generate a uniform distribution of points on the unit sphere. - The unit sphere is sampled in spherical polar coodinates. + The unit sphere is sampled in spherical polar coordinates. Parameters ---------- diff --git a/tests/test_Rn_quadrature.py b/tests/test_Rn_quadrature.py index 970d600..68b59c9 100644 --- a/tests/test_Rn_quadrature.py +++ b/tests/test_Rn_quadrature.py @@ -60,7 +60,7 @@ def test_initialization(): # Invalid method options # Now given that the type of the specifier is correct and that a valid - # combination of methods has been choosen, check the remaining options + # combination of methods has been chosen, check the remaining options # for the method. with pytest.raises(TypeError, match="not both"): # either degree or size quad = Rn( diff --git a/tests/test_S2_quadrature.py b/tests/test_S2_quadrature.py index 4a4fd8b..79a781d 100644 --- a/tests/test_S2_quadrature.py +++ b/tests/test_S2_quadrature.py @@ -68,7 +68,7 @@ def test_initialization(): # Invalid method options # Now given that the type of the specifier is correct and that a valid - # combination of methods has been choosen, check the remaining options + # combination of methods has been chosen, check the remaining options # for the method. with pytest.raises(TypeError, match="not both"): # either degree or size quad = S2( diff --git a/tests/test_SO3_quadrature.py b/tests/test_SO3_quadrature.py index 6c61cf9..81e3be1 100644 --- a/tests/test_SO3_quadrature.py +++ b/tests/test_SO3_quadrature.py @@ -105,7 +105,7 @@ def test_initialization(): # Invalid method options # Now given that the type of the specifier is correct and that a valid - # combination of methods has been choosen, check the remaining options + # combination of methods has been chosen, check the remaining options # for the method. with pytest.raises(TypeError, match="not both"): # either degree or size quad = SO3( From a8751cb4b81f33965a1027184924f964c8c31584 Mon Sep 17 00:00:00 2001 From: Alexander Blech Date: Tue, 10 Nov 2026 04:04:35 +0100 Subject: [PATCH 7/7] Add prek checks and run them in CI Ruff check and format, codespell, and validation of the workflow and of pyproject.toml, at pinned versions. The new Lint job runs the same checks, and Pass now also waits for it. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 23 +++++++++++++++++++++-- .pre-commit-config.yaml | 28 ++++++++++++++++++++++++++++ doc/contributing/contributing.rst | 11 +++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 .pre-commit-config.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c6f927f..7662f75 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,7 @@ # SPDX-FileCopyrightText: 2026 Alexander Blech # SPDX-License-Identifier: MPL-2.0 -# Tests and docs build on every pull request, on pushes to main, and weekly. +# Lint, tests and docs build on every pull request, on pushes to main, and weekly. # Dependencies are resolved fresh on each run, so a new library release can turn # CI red with no change here. The weekly run is there to catch exactly that. @@ -29,6 +29,25 @@ env: PIP_DISABLE_PIP_VERSION_CHECK: "1" jobs: + lint: + name: Lint + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.13" + # prek installs the checks at the versions in .pre-commit-config.yaml. + - name: Install + run: | + python -m pip install --upgrade pip + python -m pip install --group lint + - name: Run checks + run: prek run --all-files --show-diff-on-failure + tests: name: Tests (${{ matrix.os }}, Python ${{ matrix.python }}) runs-on: ${{ matrix.os }} @@ -82,7 +101,7 @@ jobs: pass: name: Pass if: always() - needs: [tests, docs] + needs: [lint, tests, docs] runs-on: ubuntu-latest timeout-minutes: 5 steps: diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..a8c4c28 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,28 @@ +# OpenQuad - open database for multi-dimensional numerical integration +# SPDX-FileCopyrightText: 2026 Alexander Blech +# SPDX-License-Identifier: MPL-2.0 + +# Checks run before each commit after `prek install`, and in CI with +# `prek run --all-files`. Versions are pinned; `prek update` moves them forward. + +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.17.2 + hooks: + - id: ruff-check + - id: ruff-format + + - repo: https://github.com/codespell-project/codespell + rev: v2.4.3 + hooks: + - id: codespell + + - repo: https://github.com/python-jsonschema/check-jsonschema + rev: 0.39.0 + hooks: + - id: check-github-workflows + + - repo: https://github.com/abravalheri/validate-pyproject + rev: v0.27 + hooks: + - id: validate-pyproject diff --git a/doc/contributing/contributing.rst b/doc/contributing/contributing.rst index 2f35af3..7bec5aa 100644 --- a/doc/contributing/contributing.rst +++ b/doc/contributing/contributing.rst @@ -67,11 +67,22 @@ Code needs to be compatible with `PEP 8`_. It is formatted with `Ruff`_, which follows the Black code style, with Ruff's default line length of 88 characters. +Formatting, linting, spelling and the project configuration are checked with +`prek`_, which is part of the development installation. The checks and their +versions are listed in ``.pre-commit-config.yaml``, and CI runs the same ones. +Run ``prek install`` once to check every commit before it is made, or run all +checks on demand: + +.. code-block:: bash + + prek run --all-files + Docstrings are written according to the `NumPy Style Guide`_, e.g. see this `comprehensive example`_. .. _PEP 8: https://peps.python.org/pep-0008/ .. _Ruff: https://docs.astral.sh/ruff/formatter/ +.. _prek: https://prek.j178.dev/ .. _NumPy Style Guide: https://numpydoc.readthedocs.io/en/latest/format.html .. _comprehensive example: https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_numpy.html