quadrature.py 6.07 KB
Newer Older
Boris Bonev's avatar
Boris Bonev committed
1
2
3
4
# coding=utf-8

# SPDX-FileCopyrightText: Copyright (c) 2022 The torch-harmonics Authors. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
5
#
Boris Bonev's avatar
Boris Bonev committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

import numpy as np

34

Boris Bonev's avatar
Boris Bonev committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def _precompute_grid(n, grid="equidistant", a=0.0, b=1.0, periodic=False):

    if (grid != "equidistant") and periodic:
        raise ValueError(f"Periodic grid is only supported on equidistant grids.")

    # compute coordinates
    if grid == "equidistant":
        xlg, wlg = trapezoidal_weights(n, a=a, b=b, periodic=periodic)
    elif grid == "legendre-gauss":
        xlg, wlg = legendre_gauss_weights(n, a=a, b=b)
    elif grid == "lobatto":
        xlg, wlg = lobatto_weights(n, a=a, b=b)
    elif grid == "equiangular":
        xlg, wlg = clenshaw_curtiss_weights(n, a=a, b=b)
    else:
        raise ValueError(f"Unknown grid type {grid}")

    return xlg, wlg

54

55
56
57
58
59
def _precompute_latitudes(nlat, grid="equiangular"):
    r"""
    Convenience routine to precompute latitudes
    """

60
    # compute coordinates in the cosine theta domain
Boris Bonev's avatar
Boris Bonev committed
61
    xlg, wlg = _precompute_grid(nlat, grid=grid, a=-1.0, b=1.0, periodic=False)
62

63
64
    # to perform the quadrature and account for the jacobian of the sphere, the quadrature rule
    # is formulated in the cosine theta domain, which is designed to integrate functions of cos theta
65
66
67
68
69
    lats = np.flip(np.arccos(xlg)).copy()
    wlg = np.flip(wlg).copy()

    return lats, wlg

70

Boris Bonev's avatar
Boris Bonev committed
71
72
73
74
75
76
def trapezoidal_weights(n, a=-1.0, b=1.0, periodic=False):
    r"""
    Helper routine which returns equidistant nodes with trapezoidal weights
    on the interval [a, b]
    """

77
78
    xlg = np.linspace(a, b, n, endpoint=periodic)
    wlg = (b - a) / (n - periodic * 1) * np.ones(n)
Boris Bonev's avatar
Boris Bonev committed
79
80
81
82
83
84
85

    if not periodic:
        wlg[0] *= 0.5
        wlg[-1] *= 0.5

    return xlg, wlg

86

Boris Bonev's avatar
Boris Bonev committed
87
def legendre_gauss_weights(n, a=-1.0, b=1.0):
88
    r"""
Boris Bonev's avatar
Boris Bonev committed
89
90
91
92
93
94
95
96
97
98
    Helper routine which returns the Legendre-Gauss nodes and weights
    on the interval [a, b]
    """

    xlg, wlg = np.polynomial.legendre.leggauss(n)
    xlg = (b - a) * 0.5 * xlg + (b + a) * 0.5
    wlg = wlg * (b - a) * 0.5

    return xlg, wlg

99

Boris Bonev's avatar
Boris Bonev committed
100
def lobatto_weights(n, a=-1.0, b=1.0, tol=1e-16, maxiter=100):
101
    r"""
Boris Bonev's avatar
Boris Bonev committed
102
103
104
105
106
107
108
109
110
111
    Helper routine which returns the Legendre-Gauss-Lobatto nodes and weights
    on the interval [a, b]
    """

    wlg = np.zeros((n,))
    tlg = np.zeros((n,))
    tmp = np.zeros((n,))

    # Vandermonde Matrix
    vdm = np.zeros((n, n))
112

Boris Bonev's avatar
Boris Bonev committed
113
    # initialize Chebyshev nodes as first guess
114
115
116
    for i in range(n):
        tlg[i] = -np.cos(np.pi * i / (n - 1))

Boris Bonev's avatar
Boris Bonev committed
117
    tmp = 2.0
118

Boris Bonev's avatar
Boris Bonev committed
119
120
    for i in range(maxiter):
        tmp = tlg
121
122
123
124

        vdm[:, 0] = 1.0
        vdm[:, 1] = tlg

Boris Bonev's avatar
Boris Bonev committed
125
        for k in range(2, n):
126
127
128
129
130
131
132
133
            vdm[:, k] = ((2 * k - 1) * tlg * vdm[:, k - 1] - (k - 1) * vdm[:, k - 2]) / k

        tlg = tmp - (tlg * vdm[:, n - 1] - vdm[:, n - 2]) / (n * vdm[:, n - 1])

        if max(abs(tlg - tmp).flatten()) < tol:
            break

    wlg = 2.0 / ((n * (n - 1)) * (vdm[:, n - 1] ** 2))
Boris Bonev's avatar
Boris Bonev committed
134
135
136
137

    # rescale
    tlg = (b - a) * 0.5 * tlg + (b + a) * 0.5
    wlg = wlg * (b - a) * 0.5
138

Boris Bonev's avatar
Boris Bonev committed
139
140
141
142
    return tlg, wlg


def clenshaw_curtiss_weights(n, a=-1.0, b=1.0):
143
    r"""
Boris Bonev's avatar
Boris Bonev committed
144
145
146
147
148
149
    Computation of the Clenshaw-Curtis quadrature nodes and weights.
    This implementation follows

    [1] Joerg Waldvogel, Fast Construction of the Fejer and Clenshaw-Curtis Quadrature Rules; BIT Numerical Mathematics, Vol. 43, No. 1, pp. 001–018.
    """

150
    assert n > 1
Boris Bonev's avatar
Boris Bonev committed
151
152
153
154

    tcc = np.cos(np.linspace(np.pi, 0, n))

    if n == 2:
155
        wcc = np.array([1.0, 1.0])
Boris Bonev's avatar
Boris Bonev committed
156
157
158
159
160
161
162
    else:

        n1 = n - 1
        N = np.arange(1, n1, 2)
        l = len(N)
        m = n1 - l

163
        v = np.concatenate([2 / N / (N - 2), 1 / N[-1:], np.zeros(m)])
Boris Bonev's avatar
Boris Bonev committed
164
165
166
167
168
        v = 0 - v[:-1] - v[-1:0:-1]

        g0 = -np.ones(n1)
        g0[l] = g0[l] + n1
        g0[m] = g0[m] + n1
169
        g = g0 / (n1**2 - 1 + (n1 % 2))
Boris Bonev's avatar
Boris Bonev committed
170
171
172
173
174
175
176
177
178
        wcc = np.fft.ifft(v + g).real
        wcc = np.concatenate((wcc, wcc[:1]))

    # rescale
    tcc = (b - a) * 0.5 * tcc + (b + a) * 0.5
    wcc = wcc * (b - a) * 0.5

    return tcc, wcc

179

Boris Bonev's avatar
Boris Bonev committed
180
def fejer2_weights(n, a=-1.0, b=1.0):
181
    r"""
Boris Bonev's avatar
Boris Bonev committed
182
183
184
185
186
187
    Computation of the Fejer quadrature nodes and weights.
    This implementation follows

    [1] Joerg Waldvogel, Fast Construction of the Fejer and Clenshaw-Curtis Quadrature Rules; BIT Numerical Mathematics, Vol. 43, No. 1, pp. 001–018.
    """

188
    assert n > 2
Boris Bonev's avatar
Boris Bonev committed
189
190
191
192
193
194
195
196

    tcc = np.cos(np.linspace(np.pi, 0, n))

    n1 = n - 1
    N = np.arange(1, n1, 2)
    l = len(N)
    m = n1 - l

197
    v = np.concatenate([2 / N / (N - 2), 1 / N[-1:], np.zeros(m)])
Boris Bonev's avatar
Boris Bonev committed
198
199
200
201
202
203
204
205
206
    v = 0 - v[:-1] - v[-1:0:-1]

    wcc = np.fft.ifft(v).real
    wcc = np.concatenate((wcc, wcc[:1]))

    # rescale
    tcc = (b - a) * 0.5 * tcc + (b + a) * 0.5
    wcc = wcc * (b - a) * 0.5

207
    return tcc, wcc