Coverage for install/scipp/scipy/integrate/__init__.py: 95%

21 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-11-17 01:51 +0000

1# SPDX-License-Identifier: BSD-3-Clause 

2# Copyright (c) 2023 Scipp contributors (https://github.com/scipp) 

3# @author Simon Heybrock 

4"""Sub-package for integration. 

5 

6This subpackage provides wrappers for a subset of functions from 

7:py:mod:`scipy.integrate`. 

8""" 

9 

10from collections.abc import Callable 

11from typing import Any 

12 

13import numpy.typing as npt 

14 

15from ...compat.wrapping import wrap1d 

16from ...core import DataArray, array 

17 

18 

19def _integrate( 

20 func: Callable[..., npt.NDArray[Any]], da: DataArray, dim: str, **kwargs: Any 

21) -> DataArray: 

22 if 'dx' in kwargs: 

23 raise ValueError( 

24 "Invalid argument 'dx': Spacing of integration points is " 

25 f"given by the '{dim}' coord." 

26 ) 

27 integral = func(x=da.coords[dim].values, y=da.values, **kwargs) 

28 dims = [d for d in da.dims if d != dim] 

29 unit = da.unit * da.coords[dim].unit # type: ignore[operator] # from unit = None 

30 return DataArray(data=array(dims=dims, values=integral, unit=unit)) 

31 

32 

33@wrap1d() 

34def trapezoid(da: DataArray, dim: str, **kwargs: Any) -> DataArray: 

35 """Integrate data array along the given dimension with 

36 the composite trapezoidal rule. 

37 

38 This is a wrapper around :py:func:`scipy.integrate.trapezoid`. 

39 

40 Examples: 

41 

42 >>> x = sc.geomspace(dim='x', start=0.1, stop=0.4, num=4, unit='m') 

43 >>> da = sc.DataArray(x*x, coords={'x': x}) 

44 >>> from scipp.scipy.integrate import trapezoid 

45 >>> trapezoid(da, 'x') 

46 <scipp.DataArray> 

47 Dimensions: Sizes[] 

48 Data: 

49 float64 [m^3] () 0.0217094 

50 """ 

51 import scipy.integrate as integ 

52 

53 return _integrate(integ.trapezoid, da, dim, **kwargs) 

54 

55 

56@wrap1d() 

57def simpson(da: DataArray, dim: str, **kwargs: Any) -> DataArray: 

58 """Integrate data array along the given dimension with the composite Simpson's rule. 

59 

60 This is a wrapper around :py:func:`scipy.integrate.simpson`. 

61 

62 Examples: 

63 

64 >>> x = sc.geomspace(dim='x', start=0.1, stop=0.4, num=4, unit='m') 

65 >>> da = sc.DataArray(x*x, coords={'x': x}) 

66 >>> from scipp.scipy.integrate import simpson 

67 >>> simpson(da, 'x') 

68 <scipp.DataArray> 

69 Dimensions: Sizes[] 

70 Data: 

71 float64 [m^3] () 0.021 

72 """ 

73 import scipy.integrate as integ 

74 

75 return _integrate(integ.simpson, da, dim, **kwargs) 

76 

77 

78__all__ = ['simpson', 'trapezoid']