Last active
July 20, 2021 17:37
-
-
Save tupui/ee6e685219c06c429338569e7ee7ff2a to your computer and use it in GitHub Desktop.
Integration convergence using Halton sequence: scrambling effect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Integration convergence using Halton sequence: scrambling effect. | |
Compute the convergence rate for integrating functions using Halton low | |
discrepancy sequence [1]_. We are interested in the effect of scrambling [2]_. | |
Two sets of functions are considered: | |
(i) The first set of functions are synthetic examples specifically designed | |
to verify the correctness of the implementation [4]_. | |
(ii) The second set is categorized into types A, B and C [3]_. These categories | |
state how the variables are important with respect to the function output: | |
- type A, Functions with a low number of important variables, | |
- type B, Functions with almost equally important variables but with | |
low interactions with each other, | |
- type C, Functions with almost equally important variables and with | |
high interactions with each other. | |
The theoretical integral for these functions in the unit hypercube is 1. | |
Quality of the integration is computed using the Root Mean Square Error (RMSE). | |
.. note:: This script relies on Scipy >= 1.7. Pull Request: | |
https://github.com/scipy/scipy/pull/10844 | |
References | |
---------- | |
.. [1] Halton, "On the efficiency of certain quasi-random sequences of | |
points in evaluating multi-dimensional integrals", Numerische | |
Mathematik, 1960. | |
.. [2] A. B. Owen. "A randomized Halton algorithm in R", | |
arXiv:1706.02808, 2017. | |
.. [3] Sergei Kucherenko and Daniel Albrecht and Andrea Saltelli. Exploring | |
multi-dimensional spaces: a Comparison of Latin Hypercube and Quasi Monte | |
Carlo Sampling Techniques. arXiv 1505.02350, 2015. | |
.. [4] Art B. Owen. On dropping the first Sobol' point. arXiv 2008.08051, | |
2020. | |
--------------------------- | |
MIT License | |
Copyright (c) 2020 Pamphile Tupui ROY | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
""" | |
import os | |
from collections import namedtuple | |
import numpy as np | |
from scipy.stats import qmc | |
import matplotlib.pyplot as plt | |
from matplotlib.container import ErrorbarContainer | |
from matplotlib.legend_handler import HandlerErrorbar | |
path = 'halton_convergence/int' | |
os.makedirs(path, exist_ok=True) | |
generate = True | |
n_conv = 50 | |
ns_gen = np.arange(1, 1000, 5) | |
# Functions definitions | |
_exp1 = 1 - np.exp(1) | |
def art_1(sample): | |
# dim 5, true value 0 | |
return np.sum(np.exp(sample) + _exp1, axis=1) | |
def art_2(sample): | |
# dim 5, true value 5/3 + 5*(5 - 1)/4 | |
return np.sum(sample, axis=1) ** 2 | |
def art_3(sample): | |
# dim 3, true value 0 | |
return np.prod(np.exp(sample) + _exp1, axis=1) | |
def type_a(sample, dim=30): | |
# true value 1 | |
a = np.arange(1, dim + 1) | |
f = 1. | |
for i in range(dim): | |
f *= (abs(4. * sample[:, i] - 2) + a[i]) / (1. + a[i]) | |
return f | |
def type_b(sample, dim=30): | |
# true value 1 | |
f = 1. | |
for d in range(1, dim + 1): | |
f *= (d - sample[:, d - 1]) / (d - 0.5) | |
return f | |
def type_c(sample, dim=10): | |
# true value 1 | |
f = 2 ** dim * np.prod(sample, axis=1) | |
return f | |
functions = namedtuple('functions', ['name', 'func', 'dim', 'ref']) | |
benchmark = [ | |
functions('Art 1', art_1, 5, 0), | |
functions('Art 2', art_2, 5, 5 / 3 + 5 * (5 - 1) / 4), | |
functions('Art 3', art_3, 3, 0), | |
functions('Type A', type_a, 30, 1), | |
functions('Type B', type_b, 30, 1), | |
functions('Type C', type_c, 10, 1) | |
] | |
def conv_method(sampler, func, n_samples, n_conv, ref): | |
samples = [sampler(n_samples) for _ in range(n_conv)] | |
samples = np.array(samples) | |
evals = [np.sum(func(sample)) / n_samples for sample in samples] | |
squared_errors = (ref - np.array(evals)) ** 2 | |
rmse = (np.sum(squared_errors) / n_conv) ** 0.5 | |
return rmse, 0. # can add another metric | |
# Analysis | |
if generate: | |
sample_mc_rmse = [] | |
sample_halton = [] | |
sample_halton_0 = [] | |
for ns in ns_gen: | |
print(f'-> ns={ns}') | |
_sample_mc_rmse = [] | |
_sample_halton = [] | |
_sample_halton_0 = [] | |
for case in benchmark: | |
# Monte Carlo | |
sampler_mc = lambda x: np.random.random((x, case.dim)) | |
conv_res = conv_method(sampler_mc, case.func, ns, n_conv, case.ref) | |
_sample_mc_rmse.append(conv_res) | |
# Halton | |
engine = qmc.Halton(d=case.dim, scramble=False) | |
conv_res = conv_method(engine.random, case.func, ns, 1, case.ref) | |
_sample_halton.append(conv_res) | |
# Halton scrambled | |
def _sampler_halton_0(ns): | |
engine = qmc.Halton(d=case.dim, scramble=True) | |
return engine.random(ns) | |
conv_res = conv_method(_sampler_halton_0, case.func, ns, n_conv, case.ref) | |
_sample_halton_0.append(conv_res) | |
sample_mc_rmse.append(_sample_mc_rmse) | |
sample_halton.append(_sample_halton) | |
sample_halton_0.append(_sample_halton_0) | |
np.save(os.path.join(path, 'mc.npy'), sample_mc_rmse) | |
np.save(os.path.join(path, 'halton.npy'), sample_halton) | |
np.save(os.path.join(path, 'halton_0.npy'), sample_halton_0) | |
else: | |
sample_mc_rmse = np.load(os.path.join(path, 'mc.npy')) | |
sample_halton = np.load(os.path.join(path, 'halton.npy')) | |
sample_halton_0 = np.load(os.path.join(path, 'halton_0.npy')) | |
sample_mc_rmse = np.array(sample_mc_rmse) | |
sample_halton = np.array(sample_halton) | |
sample_halton_0 = np.array(sample_halton_0) | |
# Plot | |
for i, case in enumerate(benchmark): | |
func = case.name | |
fig, ax = plt.subplots() | |
ratio_1 = sample_halton[:, i, 0][0] / ns_gen[0] ** (-1/2) | |
ratio_2 = sample_halton_0[:, i, 0][0] / ns_gen[0] ** (-2/2) | |
ax.plot(ns_gen, ns_gen ** (-1/2) * ratio_1, ls='-', c='k') | |
ax.plot(ns_gen, ns_gen ** (-2/2) * ratio_2, ls='-', c='k') | |
ax.plot(ns_gen, sample_halton[:, i, 0], | |
ls=':', label="Halton unscrambled") | |
ax.plot(ns_gen, sample_halton_0[:, i, 0], | |
ls='-', label="Halton scrambled") | |
ax.set_xlabel(r'$N_s$') | |
ax.set_ylabel(r'$\epsilon$') | |
ax.set_xscale('log') | |
ax.set_yscale('log') | |
ax.set_xticks([1, 5, 10, 50, 100, 500, 1000]) | |
ax.set_xticklabels([1, 5, 10, 50, 100, 500, 1000]) | |
fig.legend(labelspacing=0.7, bbox_to_anchor=(0.5, 0.43), | |
handler_map={ErrorbarContainer: HandlerErrorbar(xerr_size=0.7)}) | |
fig.tight_layout() | |
#plt.show() | |
fig.savefig(os.path.join(path, f'halton_conv_integration_{func}.png'), | |
transparent=True, bbox_inches='tight') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For instance, Art2: