def laguerre( order, alpha=0.0, physicist=False, normed=False, retall=False, ): """ Examples: >>> polynomials, norms = chaospy.expansion.laguerre(3, retall=True) >>> polynomials polynomial([1.0, q0-1.0, q0**2-4.0*q0+2.0, q0**3-9.0*q0**2+18.0*q0-6.0]) >>> norms array([ 1., 1., 4., 36.]) >>> chaospy.expansion.laguerre(3, physicist=True).round(5) polynomial([1.0, -q0+1.0, 0.5*q0**2-2.0*q0+2.0, -0.16667*q0**3+1.5*q0**2-5.33333*q0+4.66667]) >>> chaospy.expansion.laguerre(3, alpha=2, normed=True).round(3) polynomial([1.0, 0.577*q0-1.732, 0.204*q0**2-1.633*q0+2.449, 0.053*q0**3-0.791*q0**2+3.162*q0-3.162]) """ multiplier = -1.0 / numpy.arange(1, order + 1) if physicist else 1.0 _, [polynomials], [norms] = chaospy.recurrence.analytical_stieltjes( order, chaospy.Gamma(alpha + 1), multiplier=multiplier) if normed: polynomials = chaospy.true_divide(polynomials, numpy.sqrt(norms)) norms[:] = 1.0 return (polynomials, norms) if retall else polynomials
def plot_figures(): """Plot figures for multivariate distribution section.""" rc("figure", figsize=[8., 4.]) rc("figure.subplot", left=.08, top=.95, right=.98) seed(1000) Q1 = cp.Gamma(2) Q2 = cp.Normal(0, Q1) Q = cp.J(Q1, Q2) #end subplot(121) s, t = meshgrid(linspace(0, 5, 200), linspace(-6, 6, 200)) contourf(s, t, Q.pdf([s, t]), 50) xlabel("$q_1$") ylabel("$q_2$") subplot(122) Qr = Q.sample(500) scatter(*Qr) xlabel("$Q_1$") ylabel("$Q_2$") axis([0, 5, -6, 6]) savefig("mv1.png") clf() Q2 = cp.Gamma(1) Q1 = cp.Normal(Q2**2, Q2 + 1) Q = cp.J(Q1, Q2) #end subplot(121) s, t = meshgrid(linspace(-4, 7, 200), linspace(0, 3, 200)) contourf(s, t, Q.pdf([s, t]), 30) xlabel("$q_1$") ylabel("$q_2$") subplot(122) Qr = Q.sample(500) scatter(*Qr) xlabel("$Q_1$") ylabel("$Q_2$") axis([-4, 7, 0, 3]) savefig("mv2.png") clf()
def test_compare_scipy_Gamma(): shape = 3.0 dist_cp = cp.Gamma(shape=shape, scale=1.0, shift=0) r0, r1 = dist_cp.range() x = np.linspace(r0, r1, 300, endpoint=True) pdf_sp = stats.gamma.pdf(x, shape, scale=1.0, loc=0) cdf_sp = stats.gamma.cdf(x, shape, scale=1.0, loc=0) np.testing.assert_allclose(pdf_sp, dist_cp.pdf(x)) np.testing.assert_allclose(cdf_sp, dist_cp.cdf(x))
def laguerre(order, alpha=0.0, physicist=False): r""" Generalized Gauss-Laguerre quadrature rule. Compute the sample points and weights for Gauss-Laguerre quadrature. The sample points are the roots of the nth degree Laguerre 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-Laguerre physicist means a weight function :math:`x^\alpha e^{-x}` and weights that sum to :math`\Gamma(\alpha+1)`, and probabilist means a weight function is :math:`x^\alpha e^{-x}` and sum to 1. Args: order (int): The quadrature order. alpha (float): Shape parameter. Defaults to non-generalized Laguerre if 0. 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.laguerre(2) >>> abscissas array([[0.41577456, 2.29428036, 6.28994508]]) >>> weights array([0.71109301, 0.27851773, 0.01038926]) See also: :func:`chaospy.quadrature.gaussian` """ order = int(order) coefficients = chaospy.construct_recurrence_coefficients( order=order, dist=chaospy.Gamma(alpha + 1)) [abscissas], [weights] = chaospy.coefficients_to_quadrature(coefficients) weights *= gamma(alpha + 1) if physicist else 1 return abscissas[numpy.newaxis], weights
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) # Will draw all (of the finite set of samples)
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), "lockdown_effect": cp.Beta(alpha=14, beta=42), "lockdown_length": cp.Gamma(shape=20, scale=2), "lift_length": cp.Gamma(shape=15, scale=1), "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
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), "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) } # 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)
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]
"""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)
""" 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) gamma_phase_interval = cp.Gamma(shape=25, scale=2)
"""Test dependent distributions with 1-D components.""" from pytest import raises import numpy import chaospy DIST1 = chaospy.Uniform(1, 2) DIST2 = chaospy.Gamma(DIST1) JOINT1 = chaospy.J(DIST1, DIST2) JOINT2 = chaospy.J(DIST2, DIST1) def test_1d_stochastic_dependencies(): """Ensure ``stochastic_dependencies`` behaves as expected for dependent 1-D distributions.""" assert not DIST1.stochastic_dependent assert DIST2.stochastic_dependent assert JOINT1.stochastic_dependent assert JOINT2.stochastic_dependent def test_1d_dependent_bounds(): """Ensure lower and upper bounds works for dependent 1-D distributions.""" assert numpy.isclose(DIST2.lower, 0) assert numpy.isclose(DIST2.upper, 35.84367486) assert numpy.allclose(JOINT1.lower, [1, 0]) assert numpy.allclose(JOINT1.upper, [2, 35.84367486]) assert numpy.allclose(JOINT2.lower, [0, 1]) assert numpy.allclose(JOINT2.upper, [35.84367486, 2]) def test_1d_dependent_mapping(): """Ensure inverse and forward behaves as expected for dependent 1-D distributions."""
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) } # 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 campaign.set_sampler(sampler) # Will draw all (of the finite set of samples) campaign.draw_samples()
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), "lockdown_length": cp.Gamma(shape=20, scale=2), "lift_length": cp.Gamma(shape=15, scale=1), "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.MCSampler(vary=vary, n_mc_samples=2000) # Associate the sampler with the campaign campaign.set_sampler(sampler) # Will draw all (of the finite set of samples) campaign.draw_samples()
"""Test dependent distributions with 2-D components.""" from pytest import raises import numpy import chaospy DIST1 = chaospy.J(chaospy.Uniform(1, 2), chaospy.Uniform(2, 4)) DIST2 = chaospy.J(chaospy.Gamma(DIST1[0]), chaospy.Gamma(DIST1[1])) JOINT1 = chaospy.J(DIST1, DIST2) JOINT2 = chaospy.J(DIST2, DIST1) def test_2d_stochastic_dependencies(): """Ensure ``stochastic_dependencies`` behaves as expected for dependent 2-D distributions.""" assert not DIST1.stochastic_dependent assert DIST2.stochastic_dependent assert JOINT1.stochastic_dependent assert JOINT2.stochastic_dependent def test_2d_dependencies(): """Ensure 2-D dependencies behaves as expected.""" grid1 = numpy.array([[0, 0, 1, 1], [0, 1, 0, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) grid2 = numpy.array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1], [0, 1, 0, 1]]) inv_map1 = numpy.array( [[1, 1, 2, 2], [2, 4, 2, 4], [32.2369909, 32.2369909, 35.84367486, 35.84367486], [35.84367486, 41.71021463, 35.84367486, 41.71021463]]) inv_map2 = numpy.array( [[32.2369909, 32.2369909, 35.84367486, 35.84367486],