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

19 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-04-28 01:28 +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 typing import Callable 

11 

12from ...compat.wrapping import wrap1d 

13from ...core import DataArray, array 

14 

15 

16def _integrate(func: Callable, da: DataArray, dim: str, **kwargs) -> DataArray: 

17 if 'dx' in kwargs: 

18 raise ValueError( 

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

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

21 ) 

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

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

24 return DataArray( 

25 data=array(dims=dims, values=integral, unit=da.unit * da.coords[dim].unit) 

26 ) 

27 

28 

29@wrap1d() 

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

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

32 the composite trapezoidal rule. 

33 

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

35 

36 Examples: 

37 

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

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

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

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

42 <scipp.DataArray> 

43 Dimensions: Sizes[] 

44 Data: 

45 float64 [m^3] () 0.0217094 

46 """ 

47 import scipy.integrate as integ 

48 

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

50 

51 

52@wrap1d() 

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

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

55 

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

57 

58 Examples: 

59 

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

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

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

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

64 <scipp.DataArray> 

65 Dimensions: Sizes[] 

66 Data: 

67 float64 [m^3] () 0.021 

68 """ 

69 import scipy.integrate as integ 

70 

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

72 

73 

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