def Importance_Sampling(n=100):
    
    erro = 10
    
    while erro >= 0.01:
        
        contador_IS = []
        
        for i in range(1,n+1):
            
            #Gerador de quasi-aleatório com distribuição beta
            quasi = chaospy.Beta(0.9,1,0,1).sample(100,rule='Halton')
            p = np.array(random.choices(quasi,k=100)) #Escolhe um valor da lista quasi
            x = beta.pdf(p,0.9,1)
            
            contador_IS.append(np.mean(f(p)/x))
            
            #Calcula o erro padrão
            erro = np.std(contador_IS)/np.sqrt(i)
            
            #Verifica se o erro é menor que 1% a partir da 2 iteração
            if i > 10:
                if erro < 0.01:
                    break
                    
            resultado = np.mean(contador_IS)
    
            
    return resultado
Ejemplo n.º 2
0
def jacobi(order, alpha, beta, lower=-1, upper=1, physicist=False):
    """
    Gauss-Jacobi quadrature rule.

    Compute the sample points and weights for Gauss-Jacobi quadrature. The
    sample points are the roots of the nth degree Jacobi polynomial. These
    sample points and weights correctly integrate polynomials of degree
    :math:`2N-1` or less.

    Gaussian quadrature come in two variants: physicist and probabilist. For
    Gauss-Jacobi physicist means a weight function
    :math:`(1-x)^\alpha (1+x)^\beta` and
    weights that sum to :math`2^{\alpha+\beta}`, and probabilist means a weight
    function is :math:`B(\alpha, \beta) x^{\alpha-1}(1-x)^{\beta-1}` (where
    :math:`B` is the beta normalizing constant) which sum to 1.

    Args:
        order (int):
            The quadrature order.
        alpha (float):
            First Jakobi shape parameter.
        beta (float):
            Second Jakobi shape parameter.
        lower (float):
            Lower bound for the integration interval.
        upper (float):
            Upper bound for the integration interval.
        physicist (bool):
            Use physicist weights instead of probabilist.

    Returns:
        abscissas (numpy.ndarray):
            The ``order+1`` quadrature points for where to evaluate the model
            function with.
        weights (numpy.ndarray):
            The quadrature weights associated with each abscissas.

    Examples:
        >>> abscissas, weights = chaospy.quadrature.jacobi(3, alpha=2, beta=2)
        >>> abscissas
        array([[-0.69474659, -0.25056281,  0.25056281,  0.69474659]])
        >>> weights
        array([0.09535261, 0.40464739, 0.40464739, 0.09535261])

    See also:
        :func:`chaospy.quadrature.gaussian`

    """
    order = int(order)
    coefficients = chaospy.construct_recurrence_coefficients(
        order=order, dist=chaospy.Beta(alpha + 1, beta + 1, lower, upper))
    [abscissas], [weights] = chaospy.coefficients_to_quadrature(coefficients)
    weights *= 2**(alpha + beta) if physicist else 1
    return abscissas[numpy.newaxis], weights
Ejemplo n.º 3
0
def gegenbauer(
    order,
    alpha,
    lower=-1,
    upper=1,
    physicist=False,
    normed=False,
    retall=False,
):
    """
    Gegenbauer polynomials.

    Args:
        order (int):
            The polynomial order.
        alpha (float):
            Gegenbauer shape parameter.
        lower (float):
            Lower bound for the integration interval.
        upper (float):
            Upper bound for the integration interval.
        physicist (bool):
            Use physicist weights instead of probabilist.

    Examples:
        >>> polynomials, norms = chaospy.expansion.gegenbauer(4, 1, retall=True)
        >>> polynomials
        polynomial([1.0, q0, q0**2-0.25, q0**3-0.5*q0, q0**4-0.75*q0**2+0.0625])
        >>> norms
        array([1.        , 0.25      , 0.0625    , 0.015625  , 0.00390625])
        >>> chaospy.expansion.gegenbauer(3, 1, physicist=True)
        polynomial([1.0, 2.0*q0, 4.0*q0**2-0.5, 8.0*q0**3-2.0*q0])
        >>> chaospy.expansion.gegenbauer(3, 1, lower=0.5, upper=1.5, normed=True).round(3)
        polynomial([1.0, 4.0*q0-4.0, 16.0*q0**2-32.0*q0+15.0,
                    64.0*q0**3-192.0*q0**2+184.0*q0-56.0])

    """
    multiplier = 1
    if physicist:
        multiplier = numpy.arange(1, order + 1)
        multiplier = 2 * (multiplier + alpha - 1) / multiplier
    _, [polynomials], [norms] = chaospy.recurrence.analytical_stieltjes(
        order,
        chaospy.Beta(alpha + 0.5, alpha + 0.5, lower, upper),
        multiplier=multiplier,
    )
    if normed:
        polynomials = chaospy.true_divide(polynomials, numpy.sqrt(norms))
        norms[:] = 1.0
    return (polynomials, norms) if retall else polynomials
Ejemplo n.º 4
0
def chebyshev_2(
    order,
    lower=-1,
    upper=1,
    physicist=False,
    normed=False,
    retall=False,
):
    """
    Chebyshev polynomials of the second kind.

    Args:
        order (int):
            The quadrature order.
        lower (float):
            Lower bound for the integration interval.
        upper (float):
            Upper bound for the integration interval.
        physicist (bool):
            Use physicist weights instead of probabilist.

    Returns:
        (numpoly.ndpoly, numpy.ndarray):
            Chebyshev polynomial expansion. Norms of the orthogonal
            expansion on the form ``E(orth**2, dist)``.

    Examples:
        >>> polynomials, norms = chaospy.expansion.chebyshev_2(4, retall=True)
        >>> polynomials
        polynomial([1.0, q0, q0**2-0.25, q0**3-0.5*q0, q0**4-0.75*q0**2+0.0625])
        >>> norms
        array([1.        , 0.25      , 0.0625    , 0.015625  , 0.00390625])
        >>> chaospy.expansion.chebyshev_2(3, physicist=True)
        polynomial([1.0, 2.0*q0, 4.0*q0**2-0.5, 8.0*q0**3-2.0*q0])
        >>> chaospy.expansion.chebyshev_2(3, lower=0.5, upper=1.5, normed=True).round(3)
        polynomial([1.0, 4.0*q0-4.0, 16.0*q0**2-32.0*q0+15.0,
                    64.0*q0**3-192.0*q0**2+184.0*q0-56.0])

    """
    multiplier = 2 if physicist else 1
    _, [polynomials], [norms] = chaospy.recurrence.analytical_stieltjes(
        order, chaospy.Beta(1.5, 1.5, lower, upper), multiplier=multiplier
    )
    if normed:
        polynomials = chaospy.true_divide(polynomials, numpy.sqrt(norms))
        norms[:] = 1.0
    return (polynomials, norms) if retall else polynomials
Ejemplo n.º 5
0
def chebyshev_1(
    order,
    lower=-1,
    upper=1,
    physicist=False,
    normed=False,
    retall=False,
):
    """
    Chebyshev polynomials of the first kind.

    Args:
        order (int):
            The polynomial order.
        lower (float):
            Lower bound for the integration interval.
        upper (float):
            Upper bound for the integration interval.
        physicist (bool):
            Use physicist weights instead of probabilist.

    Returns:
        (numpoly.ndpoly, numpy.ndarray):
            Chebyshev polynomial expansion. Norms of the orthogonal
            expansion on the form ``E(orth**2, dist)``.

    Examples:
        >>> polynomials, norms = chaospy.expansion.chebyshev_1(4, retall=True)
        >>> polynomials
        polynomial([1.0, q0, q0**2-0.5, q0**3-0.75*q0, q0**4-q0**2+0.125])
        >>> norms
        array([1.       , 0.5      , 0.125    , 0.03125  , 0.0078125])
        >>> chaospy.expansion.chebyshev_1(3, physicist=True)
        polynomial([1.0, q0, 2.0*q0**2-1.0, 4.0*q0**3-2.5*q0])
        >>> chaospy.expansion.chebyshev_1(3, lower=0.5, upper=1.5, normed=True).round(3)
        polynomial([1.0, 2.828*q0-2.828, 11.314*q0**2-22.627*q0+9.899,
                    45.255*q0**3-135.765*q0**2+127.279*q0-36.77])

    """
    multiplier = 1 + numpy.arange(order).astype(bool) if physicist else 1
    _, [polynomials], [norms] = chaospy.recurrence.analytical_stieltjes(
        order, chaospy.Beta(0.5, 0.5, lower, upper), multiplier=multiplier
    )
    if normed:
        polynomials = chaospy.true_divide(polynomials, numpy.sqrt(norms))
        norms[:] = 1.0
    return (polynomials, norms) if retall else polynomials
Ejemplo n.º 6
0
def jacobi(
    order,
    alpha,
    beta,
    lower=-1,
    upper=1,
    physicist=False,
    normed=False,
    retall=False,
):
    """
    Jacobi polynomial expansion.

    Examples:
        >>> polynomials, norms = chaospy.expansion.jacobi(4, 0.5, 0.5, retall=True)
        >>> polynomials
        polynomial([1.0, q0, q0**2-0.5, q0**3-0.75*q0, q0**4-q0**2+0.125])
        >>> norms
        array([1.       , 0.5      , 0.125    , 0.03125  , 0.0078125])
        >>> chaospy.expansion.jacobi(3, 0.5, 0.5,  physicist=True).round(4)
        polynomial([1.0, 1.5*q0, 2.5*q0**2-0.8333, 4.375*q0**3-2.1146*q0])
        >>> chaospy.expansion.jacobi(3, 1.5, 0.5, normed=True)
        polynomial([1.0, 2.0*q0, 4.0*q0**2-1.0, 8.0*q0**3-4.0*q0])

    """
    multiplier = 1
    if physicist:
        multiplier = numpy.arange(1, order + 1)
        multiplier = ((2 * multiplier + alpha + beta - 1) *
                      (2 * multiplier + alpha + beta) /
                      (2 * multiplier * (multiplier + alpha + beta)))
    _, [polynomials], [norms] = chaospy.recurrence.analytical_stieltjes(
        order,
        chaospy.Beta(alpha, beta, lower=lower, upper=upper),
        multiplier=multiplier,
    )
    if normed:
        polynomials = chaospy.true_divide(polynomials, numpy.sqrt(norms))
        norms[:] = 1.0
    return (polynomials, norms) if retall else polynomials
Ejemplo n.º 7
0
output_filename = params["out_file"]["default"]
output_columns = ["IC_prev_avg_max", "IC_ex_max"]

encoder = uq.encoders.GenericEncoder(template_fname=HOME + '/corona.template',
                                     delimiter='$',
                                     target_filename='corona_in.json')
decoder = uq.decoders.SimpleCSV(target_filename=output_filename,
                                output_columns=output_columns)

# Add the SC app (automatically set as current app)
campaign.add_app(name="sc", params=params, encoder=encoder, decoder=decoder)

# Create the sampler
vary = {
    "seed": cp.DiscreteUniform(2**14, 2**16),
    "lockdown_effect": cp.Beta(alpha=14, beta=42),
    "phase_interval": cp.Gamma(shape=25, scale=2),
    "uptake": cp.Beta(alpha=16, beta=2),
    # "Rzero": cp.Gamma(shape=100,scale=.025),
    # "duration_infectiousness": cp.Gamma(shape=25,scale=.2),
    # "shape_exposed_time": cp.Gamma(shape=17.5,scale=1),
    # "intervention_effect_var_inv": cp.Gamma(shape=2,scale=.05)
}

#sampler = uq.sampling.SCSampler(vary=vary, polynomial_order=3,
#                                   quadrature_rule='G', sparse=False)
sampler = uq.sampling.MCSampler(vary=vary, n_mc_samples=2000)

# Associate the sampler with the campaign
campaign.set_sampler(sampler)
Ejemplo n.º 8
0
output_filename = params["out_file"]["default"]
output_columns = ["IC_prev_avg_max", "IC_ex_max"]

encoder = uq.encoders.GenericEncoder(template_fname=HOME + '/corona.template',
                                     delimiter='$',
                                     target_filename='corona_in.json')
decoder = uq.decoders.SimpleCSV(target_filename=output_filename,
                                output_columns=output_columns)

campaign.add_app(name="mc", params=params, encoder=encoder, decoder=decoder)

# Create the sampler
vary = {
    "seed": cp.DiscreteUniform(2**14, 2**16),
    "intervention_effect": cp.Beta(alpha=38, beta=70),
    "uptake": cp.Beta(alpha=16, beta=2),
    "Rzero": cp.Gamma(shape=100, scale=.025),
    "duration_infectiousness": cp.Gamma(shape=25, scale=.2),
    "shape_exposed_time": cp.Gamma(shape=17.5, scale=1),
    "intervention_effect_var_inv": cp.Gamma(shape=2, scale=.05)
}

# For estimation of the cdf and heatmap
sampler = uq.sampling.RandomSampler(vary=vary, max_num=1e2)

# For the computation of the Sobol indices
# sampler = uq.sampling.MCSampler(vary=vary, n_mc_samples=100)

# Associate the sampler with the campaign
campaign.set_sampler(sampler)
Ejemplo n.º 9
0
import pytest

import chaospy
from chaospy.recurrence import RECURRENCE_ALGORITHMS

ANALYTICAL_DISTRIBUTIONS = {
    "beta": chaospy.Beta(4, 2),
    "expon": chaospy.Exponential(1),
    "gamma": chaospy.Gamma(2, 2),
    "lognorm": chaospy.LogNormal(-10, 0.1),
    "normal": chaospy.Normal(2, 3),
    "student": chaospy.StudentT(df=25, mu=0.5),
    "uniform": chaospy.Uniform(-1, 2),
}


@pytest.fixture(params=RECURRENCE_ALGORITHMS)
def recurrence_algorithm(request):
    """Parameterization of name of recurrence algorithms."""
    yield request.param


@pytest.fixture(params=ANALYTICAL_DISTRIBUTIONS.keys())
def analytical_distribution(request):
    """Parameterization of distribution with analytical TTR methods."""
    return ANALYTICAL_DISTRIBUTIONS[request.param]
Ejemplo n.º 10
0
"""Testing polynomial related to distributions."""
import chaospy
import numpy
import pytest

DISTRIBUTIONS = {
    "discrete": chaospy.DiscreteUniform(-10, 10),
    "normal": chaospy.Normal(0, 1),
    "uniform": chaospy.Uniform(-1, 1),
    "exponential": chaospy.Exponential(1),
    "gamma": chaospy.Gamma(1),
    "beta": chaospy.Beta(3, 3, lower=-1, upper=1),
    "mvnormal": chaospy.MvNormal([0], [1]),
    "custom": chaospy.UserDistribution(
        cdf=lambda x: (x+1)/2,
        pdf=lambda x: 1/2.,
        lower=lambda: -1,
        upper=lambda: 1,
        ppf=lambda q: 2*q-1,
        mom=lambda k: ((k+1.)%2)/(k+1),
        ttr=lambda k: (0., k*k/(4.*k*k-1)),
    ),
}
BUILDERS = {
    "stieltjes": chaospy.expansion.stieltjes,
    "cholesky": chaospy.expansion.cholesky,
    # "gram_schmidt": chaospy.expansion.gram_schmidt,
}


@pytest.fixture(params=DISTRIBUTIONS)
Ejemplo n.º 11
0
import sobol_seq
import chaospy
import matplotlib.pyplot as plt

sobolSeq = sobol_seq.i4_sobol_generate(2, 25000)
x = sobolSeq[:, 0]
y = sobolSeq[:, 1]

plt.scatter(x, y, s=0.25)
plt.show()

sobolSeq = sobol_seq.i4_sobol_generate(2, 4675)
x = sobolSeq[:, 0]
y = sobolSeq[:, 1]

plt.scatter(x, y, s=1)
plt.show()

a = 1
b = 1.5
distribution = chaospy.Beta(a, b)
betaSeq = distribution.sample(25000, 'S')
plt.hist(betaSeq, bins=100)
plt.show()
Ejemplo n.º 12
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul  2 09:41:32 2020

@author: federica
"""

import numpy as np
import chaospy as cp
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 20})
plt.rcParams['figure.figsize'] = 16, 20

# Contact tracing
beta_tpE = cp.Beta(alpha=2, beta=6)
beta_tcr = cp.Beta(alpha=10, beta=2)
gamma_trI = cp.Gamma(shape=2, scale=.2)

x_CT = np.linspace(0, 1.5, 151)

# Flattening the curve
beta_int1 = cp.Beta(alpha=38, beta=70)
beta_up = cp.Beta(alpha=16, beta=2)

x_FT = np.linspace(0, 1, 101)

# Intermittent lockdown & Phased Opening
beta_lockeffect = cp.Beta(alpha=14, beta=42)
gamma_locklength = cp.Gamma(shape=20, scale=2)
gamma_liftlength = cp.Gamma(shape=15, scale=1)
Ejemplo n.º 13
0
output_filename = params["out_file"]["default"]
output_columns = ["IC_prev_avg_max", "IC_ex_max"]

encoder = uq.encoders.GenericEncoder(template_fname=HOME + '/corona.template',
                                     delimiter='$',
                                     target_filename='corona_in.json')
decoder = uq.decoders.SimpleCSV(target_filename=output_filename,
                                output_columns=output_columns)

campaign.add_app(name='mc', params=params, encoder=encoder, decoder=decoder)

# Create the sampler
vary = {
    "seed": cp.DiscreteUniform(2**14, 2**16),
    "trace_prob_E": cp.Beta(alpha=2, beta=6),
    "trace_rate_I": cp.Gamma(shape=2, scale=.2),
    "trace_contact_reduction": cp.Beta(alpha=10, beta=2),
    "Rzero": cp.Gamma(shape=100, scale=.025),
    "duration_infectiousness": cp.Gamma(shape=25, scale=.2),
    "shape_exposed_time": cp.Gamma(shape=17.5, scale=1),
    "intervention_effect_var_inv": cp.Gamma(shape=2, scale=.05)
}

# For estimation of the cdf and heatmap
sampler = uq.sampling.RandomSampler(vary=vary, max_num=1e3)

# For the computation of the Sobol indices
# sampler = uq.sampling.MCSampler(vary=vary, n_mc_samples=100)

# Associate the sampler with the campaign