evaluation.py 16.1 KB
Newer Older
Maximilian Schanner's avatar
Maximilian Schanner committed
1
"""
Maximilian Schanner's avatar
Maximilian Schanner committed
2
3
4
5
6
    This module is part of the CORBASS algorithm. It provides routines for the
    third and final step, the evaluation of the output from the integration
    step. These routines serve to calculate probability density functions (or
    proxys of these) for quantities of interest, such as the power spectrum,
    the dipole intensity, the dipole location etc.
Maximilian Schanner's avatar
Maximilian Schanner committed
7

Maximilian Schanner's avatar
Maximilian Schanner committed
8
9
    Copyright (C) 2019 Helmholtz Centre Potsdam GFZ,
        German Research Centre for Geosciences, Potsdam, Germany
Maximilian Schanner's avatar
Maximilian Schanner committed
10
11

    Cite as:
Maximilian Schanner's avatar
Maximilian Schanner committed
12
    Schanner, Maximilian Arthus and Mauerberger, Stefan (2019)
Maximilian Schanner's avatar
Maximilian Schanner committed
13
    CORBASS: CORrelation Based Archeomagnetic SnapShot model. V. 1.0.
Maximilian Schanner's avatar
DOI    
Maximilian Schanner committed
14
    GFZ Data Services. http://doi.org/10.5880/GFZ.2.3.2019.008
Maximilian Schanner's avatar
Maximilian Schanner committed
15

Maximilian Schanner's avatar
Maximilian Schanner committed
16
17
    This file is part of CORBASS.

Maximilian Schanner's avatar
Maximilian Schanner committed
18
19
20
21
22
23
24
25
26
27
28
    CORBASS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    CORBASS is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
Maximilian Schanner's avatar
Maximilian Schanner committed
29
    along with CORBASS. If not, see <https://www.gnu.org/licenses/>.
Maximilian Schanner's avatar
Maximilian Schanner committed
30
31
"""

Maximilian Schanner's avatar
Maximilian Schanner committed
32
33
34
import sys
if __name__ == '__main__':
    # make relative imports work
Maximilian Schanner's avatar
Maximilian Schanner committed
35
36
37
    # make relative imports work
    from pathlib import Path
    sys.path.append(str(Path(__file__).absolute().parents[1]))
Maximilian Schanner's avatar
Maximilian Schanner committed
38
39

import numpy as np
40
from scipy.stats import gaussian_kde
Maximilian Schanner's avatar
Maximilian Schanner committed
41
42
43
from scipy.special import erf

from pyfield import i2lm_l, i2lm_m, equi_sph, REARTH
Maximilian Schanner's avatar
Maximilian Schanner committed
44
from corbass.utils import scaling
Maximilian Schanner's avatar
Maximilian Schanner committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66


def power_spectrum(ls, mu_gs, sd_gs=0):
    """ For given ls, mean and standard deviation calculate the power spectrum
    """
    lmax = np.max(ls)
    ps = np.full((lmax, ) + mu_gs.shape[1:], np.nan)
    gs = (mu_gs**2 + sd_gs**2)
    for l in range(1, lmax + 1):
        mask = np.equal(ls, l)
        ps[l-1, ...] = (l+1)*gs[mask].sum(axis=0)

    return ps


def xyz2rpt(x, y, z):
    """ Transform cartesian coordinates x,y,z to spherical coordinates. """
    r = np.sqrt(x**2 + y**2 + z**2)
    return r, np.arctan2(y, x), np.arcsin(z / r)


def intensity(posterior, mu_dips, cov_dips, r_ref, r_at=REARTH,
67
              n_samps=50000, n_points=1001,
Maximilian Schanner's avatar
Maximilian Schanner committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
              ret_samps=False):
    """ Calculate the pdf of the dipole intensity, by sampling and
    kde-smoothing.

    Parameters
    ----------
    posterior : array-like of shape (N, N, N)
        The posterior from the integration
    mu_dips : array-like of shape length (N, 3)
        The dipole coefficients from the integration
    cov_coeffs : array-like of shape (N, 3, 3)
        The corresponding covariance matrices
    r_ref : float
        The reference radius for the input dipole coefficients
82
83
84
    n_samps: int (optional, default is 10000)
        The number of samples
    ret_samps : bool (optional, default is False)
Maximilian Schanner's avatar
Maximilian Schanner committed
85
        Wether to also return the raw samples
86
    n_points : int (optional, default is default 1001)
Maximilian Schanner's avatar
Maximilian Schanner committed
87
        Number of evaluation points for the smoothed pdf
88
    r_at : float (optional, default is REARTH)
Maximilian Schanner's avatar
Maximilian Schanner committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
        The reference radius for the output intensity

    Returns
    -------
    points : array-like of length n_points
        The array on which the pdf is evaluated
    pdf : array-like of length n_points
        The dipole intensity pdf, evaluated on 'points'
    """

    mu_dips, cov_dips = rescale_coeff_results(r_ref, r_at, mu_dips,
                                              cov_dips)

    gm_weights = posterior / posterior.sum()
    ens_dip = sample_GM(gm_weights.flatten(), mu_dips, cov_dips,
104
                        n_samps=n_samps)
Maximilian Schanner's avatar
Maximilian Schanner committed
105
106
107
108
109
110
111
112
113
114
115
116
117
    # transform to spherical coordinates, keep only intensity
    # the correspondence is g_1_0=z, g_1_1=x, g_1_-1=y
    ens_inte, _, _ = xyz2rpt(ens_dip[1], ens_dip[2], ens_dip[0])
    smooth = gaussian_kde(ens_inte)
    points = np.linspace(ens_inte.min(), ens_inte.max(), n_points)
    pdf = smooth(points)

    if ret_samps:
        return points, pdf, ens_inte
    else:
        return points, pdf


118
def location(posterior, mu_dips, cov_dips, n_points=10000,
Maximilian Schanner's avatar
Maximilian Schanner committed
119
120
121
122
123
124
125
126
127
128
129
130
             bounds=[[0., np.deg2rad(30)], [0, 2*np.pi]]):
    """ From the posterior and corresponding dipole coefficients, calculate
    the pdf of the dipole location

    Parameters
    ----------
    posterior : array-like of shape (N, N, N)
        The posterior from the integration
    mu_dips : array-like of shape length (N, 3)
        The dipole coefficients from the integration
    cov_coeffs : array-like of shape (N, 3, 3)
        The corresponding covariance matrices
131
    n_points : int (optional, default is 10000)
Maximilian Schanner's avatar
Maximilian Schanner committed
132
        The (approximate) number of gridpoints to evaluate the location on
133
134
135
    bounds : 2x2 array-like (optional,
            default is [[0., np.deg2rad(30)],
                        [0., 2*np.pi]])
Maximilian Schanner's avatar
Maximilian Schanner committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
        The interval over which the density shall be plotted, in rad. This is
        useful, since in most cases the dipole will be close to the geographic
        north pole, thus the default intervall covers only latitudes down to
        30 deg.

    Returns
    -------
    lat : array-like
        The latitudes of the gridpoints
    lon : array-like
        The longitudes of the gridpoints
    dens : array-like
        The dipole location pdf, evaluated at the gridpoints
    """
150
151
152
153
    # set up grid to evaluate on    
    (ti, tf), (pi, pf) = bounds
    theta, phi = zip(*equi_sph(n_points, ti, tf, pi, pf))

Maximilian Schanner's avatar
Maximilian Schanner committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    phi = np.asarray(phi)
    theta = np.pi/2. - np.asarray(theta)
    # allocate array for the density
    dens = np.zeros_like(theta)

    n = len(posterior)
    # calculate the density
    for it in range(n**3):
        prc = np.linalg.inv(cov_dips[it])
        zv = np.array([np.sin(theta),
                       np.cos(theta) * np.cos(phi),
                       np.cos(theta) * np.sin(phi)])
        zalpha = np.einsum('i..., ij, j...->...', zv, prc, zv)
        zr0 = np.einsum('i, ij, j...->...', -mu_dips[it], prc, zv)
        zr0 /= zalpha
        zk = np.exp((zr0**2 * zalpha - np.einsum('i,ij,j->',
                                                 mu_dips[it],
                                                 prc,
                                                 mu_dips[it])) / 2.)
        za = zr0*np.sqrt(zalpha)
        dummy = np.sqrt(np.pi/2.) * (za**2 + 1) * (erf(za / np.sqrt(2)) + 1) \
            + za * np.exp(-za**2 / 2)

        dens += posterior[np.unravel_index(it, posterior.shape)] \
            / np.sqrt((2*np.pi)**3 * np.linalg.det(cov_dips[it])) \
            * np.cos(theta) * zk / np.sqrt(zalpha**3) * dummy
180
    lat = np.rad2deg(theta)
Maximilian Schanner's avatar
Maximilian Schanner committed
181
    lat[np.where(180 < lat)] -= 360
182
    lon = np.rad2deg(phi)
Maximilian Schanner's avatar
Maximilian Schanner committed
183
184
185
186

    return lat, lon, dens


187
def sample_GM(weights, mus, covs, n_samps=10000):
Maximilian Schanner's avatar
Maximilian Schanner committed
188
189
190
191
192
193
194
195
196
197
    """ Sample from a Gaussian mixture distribution

    Parameters
    ----------
    weights : array-like
        The weights of the mixture, the sum should be one
    mus : array-like
        The means of the mixture components
    covs : array-like
        The covariance-matrices of the mixture components
198
199
    n_samps: int (optional, default is 10000)
        The number of samples
Maximilian Schanner's avatar
Maximilian Schanner committed
200
201
202
203

    Returns
    -------
    ens : numpy.ndarray
204
        n_samps samples from the Gaussian mixture
Maximilian Schanner's avatar
Maximilian Schanner committed
205
206
207
208
209
210
211
212
    """
    if not np.isclose(sum(weights), 1.):
        raise ValueError("Sum of the weights has to be one!")

    n = len(weights)

    # sample indices, corresponding to parameter pairs
    # weights are given by the posterior
213
    par_samps = np.random.choice(n, size=n_samps, replace=True,
Maximilian Schanner's avatar
Maximilian Schanner committed
214
                                 p=weights)
215
216
217
    # TODO: Is it possible to boost this?
    ens = [np.random.multivariate_normal(mean=mus[it], cov=covs[it])
           for it in par_samps]
Maximilian Schanner's avatar
Maximilian Schanner committed
218

219
    return np.asarray(ens).T
Maximilian Schanner's avatar
Maximilian Schanner committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265


def rescale_coeff_results(r_from, r_to, mu_coeffs, cov_coeffs):
    """ rescale an array of coefficient means and covariances from r_from
    to r_to

    Parameters
    ----------
    r_from : float
        The reference radius for the input coefficients
    r_to : float
        The reference radius for the output coefficients
    mu_coeffs : array-like
        The coefficient array
    cov_coeffs : array-like
        The corresponding covariances

    Returns
    -------
    mu_coeffs_resc : array-like
        The rescaled coefficients
    cov_coeffs_resc : array-like
        The rescaled covariances
    """
    scale = scaling(r_from, r_to, i2lm_l(len(mu_coeffs[0])-1))

    mu_coeffs_resc = scale[None, :]*mu_coeffs
    cov_coeffs_resc = scale[None, :]*cov_coeffs*scale[:, None]

    return mu_coeffs_resc, cov_coeffs_resc


def coeffs(posterior, mu_coeffs, cov_coeffs, r_ref, r_at=REARTH):
    """ Calculate the coefficient means and percentiles to output the model
    coefficients

    Parameters
    ----------
    posterior : array-like
        The posterior from the integration
    mu_dips : array-like
        The coefficients from the integration
    cov_coeffs : array-like
        The corresponding covariance matrices
    r_ref : float
        The reference radius for the input coefficients
266
    r_at : float (optional, default is REARTH)
Maximilian Schanner's avatar
Maximilian Schanner committed
267
268
269
270
271
272
273
274
        The reference radius for the output coefficients

    Returns
    -------
    ls : array-like
        The coefficient degrees
    ms : array-like
        The coefficient orders
Maximilian Schanner's avatar
Maximilian Schanner committed
275
276
277
278
    mean : array-like
        The Gauss coefficient means
    sd : array-like
        The Gauss coefficient standard deviation
Maximilian Schanner's avatar
Maximilian Schanner committed
279
280
281
282
283
284
285
286
287
288
289
290
    coeffs_16 : array-like
        The 16% percentiles
    coeffs_84 : array-like
        The 84% percentiles
    """
    ls = [i2lm_l(it) for it in range(len(mu_coeffs[0]))]
    ms = [i2lm_m(it) for it in range(len(mu_coeffs[0]))]

    mu_coeffs, cov_coeffs = rescale_coeff_results(r_ref, r_at, mu_coeffs,
                                                  cov_coeffs)

    gm_weights = posterior / posterior.sum()
291
    ens = sample_GM(gm_weights.flatten(), mu_coeffs, cov_coeffs)
Maximilian Schanner's avatar
Maximilian Schanner committed
292
293
294

    err_16, err_84 = np.percentile(ens, (16, 84), axis=1)
    mean = (mu_coeffs.T * gm_weights.flatten()).sum(axis=1)
Maximilian Schanner's avatar
Maximilian Schanner committed
295
    var = np.zeros_like(mean)
Maximilian Schanner's avatar
Maximilian Schanner committed
296
297
298
299
300
301
302
303
304

    for it in range(gm_weights.size):
        var += cov_coeffs[it].diagonal() \
            * gm_weights[np.unravel_index(it, gm_weights.shape)]
        var += mu_coeffs[it]**2 \
            * gm_weights[np.unravel_index(it, gm_weights.shape)]

    var -= mean**2

Maximilian Schanner's avatar
Maximilian Schanner committed
305
    return np.array(ls), np.array(ms), mean, np.sqrt(var), err_16, err_84
Maximilian Schanner's avatar
Maximilian Schanner committed
306
307


308
def spectrum(posterior, mu_coeffs, cov_coeffs, r_ref, r_at=REARTH):
Maximilian Schanner's avatar
Maximilian Schanner committed
309
310
311
312
313
314
315
316
317
318
319
320
321
    """ Calculate the power spectrum resulting from the mixture and find the
    68% confidence-interval by sampling

    Parameters
    ----------
    posterior : array-like
        The posterior from the integration
    mu_dips : array-like
        The coefficients from the integration
    cov_coeffs : array-like
        The corresponding covariance matrices
    r_ref : float
        The reference radius for the input coefficients
322
    r_at : float (optional, default is REARTH)
Maximilian Schanner's avatar
Maximilian Schanner committed
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
        The reference radius for the output coefficients

    Returns
    -------
    ls_out : array-like
        The Gauss coefficient degrees
    mean_ps : array-like
        The corresponding mean of the power spectrum
    a16_ps : array-like
        The 16% percentiles
    a84_ps : arary-like
        The 84% percentiles
    """

    mu_coeffs, cov_coeffs = rescale_coeff_results(r_ref, r_at, mu_coeffs,
                                                  cov_coeffs)

    gm_weights = posterior / posterior.sum()

342
    ens = sample_GM(gm_weights.flatten(), mu_coeffs, cov_coeffs)
Maximilian Schanner's avatar
Maximilian Schanner committed
343
344
345

    # 1st two moments of mixture
    mean = np.sum(mu_coeffs * gm_weights.flatten()[:, None], axis=0)
Maximilian Schanner's avatar
Maximilian Schanner committed
346
    cov = np.zeros_like(cov_coeffs[0])
Maximilian Schanner's avatar
Maximilian Schanner committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396

    for it in range(gm_weights.size):
        cov += cov_coeffs[it] \
            * gm_weights[np.unravel_index(it, gm_weights.shape)]
        cov += np.outer(mu_coeffs[it] - mean,
                        mu_coeffs[it] - mean) \
            * gm_weights[np.unravel_index(it, gm_weights.shape)]

    ls = [i2lm_l(it) for it in range(len(mu_coeffs[0]))]
    mean_ps = power_spectrum(ls, mean, np.sqrt(cov.diagonal()))
    samp_ps = power_spectrum(ls, ens)
    a16_ps, a84_ps = np.percentile(samp_ps, (16, 84), axis=1)

    ls_out = np.arange(1, max(ls) + 1)
    return ls_out, mean_ps, a16_ps, a84_ps


if __name__ == '__main__':
    from matplotlib import pyplot as plt
    import cartopy.crs as ccrs

    from utils import load
    from integration import IntegrationResult

    pars = load(sys.argv)

    n_bins = len(pars.data)

    # set up figures
    int_fig, int_ax = plt.subplots(n_bins, 1, figsize=(4, 3*n_bins),
                                   squeeze=False)
    int_fig.canvas.set_window_title('PDF of dipole intensity')
    cff_fig, cff_ax = plt.subplots(n_bins, 1, figsize=(4, 3*n_bins),
                                   squeeze=False)
    cff_fig.canvas.set_window_title('Dipole coefficients')

    loc_fig = plt.figure(figsize=(4, 3*n_bins))
    loc_fig.canvas.set_window_title('PDF of dipole location')

    spc_fig, spc_ax = plt.subplots(n_bins, 1, figsize=(4, 3*n_bins),
                                   squeeze=False)
    spc_fig.canvas.set_window_title('Power spectrum')

    # global projection for locations
    ax_proj = ccrs.Stereographic(central_latitude=90., scale_factor=20)

    cntr = 0                                # a counter
    for bin_name, data in pars.data:
        try:
            fh = np.load(f'{pars.bin_fname(bin_name)}'
397
                         f'{IntegrationResult.suffix_large}')
Maximilian Schanner's avatar
Maximilian Schanner committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
        except FileNotFoundError:
            print(f"No integration results for bin {bin_name} found. Skipping "
                  f"this bin. The plot will be empty.")
            cntr += 1
            continue
        else:
            # calculate and plot the coefficients
            ls, ms, mean, var, err_16, err_84 = \
                coeffs(fh['posterior'], fh['mu_coeffs'], fh['cov_coeffs'],
                       r_ref=pars.r_ref)
            cff_ax[cntr, 0].errorbar(ms[0:3], mean[0:3],
                                     yerr=[mean[0:3]-err_16[0:3],
                                           err_84[0:3]-mean[0:3]],
                                     marker='x', ls='')
            cff_ax[cntr, 0].set_xticks(ms[0:3])

            # calculate and plot the dipole intensity
            mu_dips = fh['mu_coeffs'][:, 0:3]
            cov_dips = fh['cov_coeffs'][:, 0:3, 0:3]

            arr, pdf, samps = intensity(fh['posterior'], mu_dips, cov_dips,
                                        r_ref=pars.r_ref, ret_samps=True)

            int_ax[cntr, 0].hist(samps, bins=100, density=True)
            int_ax[cntr, 0].plot(arr, pdf, lw=3, alpha=0.8)

            # calculate and plot the dipole location
            lat, lon, dens = location(fh['posterior'], mu_dips, cov_dips)
            sph_ax = loc_fig.add_subplot(n_bins, 1, 1 + cntr,
                                         projection=ax_proj)
            sph_ax.coastlines(zorder=1)
            sph_ax.gridlines()
            sph_ax.set_global()

            spltlat, spltlon, _ = ax_proj.transform_points(ccrs.Geodetic(),
                                                           lat,
                                                           lon).T

            sph_ax.tripcolor(spltlat, spltlon, dens, zorder=0,
                             cmap='Purples')

            # calculate and plot the power spectrum
            plt_l, mu_ps, a16_ps, a84_ps = spectrum(fh['posterior'],
                                                    fh['mu_coeffs'],
                                                    fh['cov_coeffs'],
                                                    pars.r_ref,
                                                    r_at=pars.r_ref)

            spc_ax[cntr, 0].errorbar(plt_l, mu_ps,
                                     yerr=[mu_ps-a16_ps, a84_ps-mu_ps],
                                     marker='x')
            spc_ax[cntr, 0].set_yscale('log')
            spc_ax[cntr, 0].set_xticks(plt_l)

            fh.close()

            cff_ax[cntr, 0].set_title(str(bin_name))
            int_ax[cntr, 0].set_title(str(bin_name))
            int_ax[cntr, 0].set_yticks([])
            sph_ax.set_title(str(bin_name))
            spc_ax[cntr, 0].set_title(str(bin_name))

            cntr += 1

    plt.show()