Ejemplo n.º 1
0
def test_var_names():
    with pytest.raises(BeartypeCallHintPepParamException):
        model = PythonModel(model_script='python_model.py',
                            model_object_name='SumRVs',
                            var_names=[20],
                            delete_files=True)
        runmodel_object = RunModel(model=model)
Ejemplo n.º 2
0
def setup():
    model = PythonModel(model_script='pfn_models.py',
                        model_object_name='model_quadratic',
                        var_names=['theta_0', 'theta_1'],
                        delete_files=True)
    h_func = RunModel(model=model)
    yield h_func
Ejemplo n.º 3
0
def test_akmcs_expected_improvement_global_fit():
    from UQpy.surrogates.kriging.regression_models.LinearRegression import LinearRegression
    from UQpy.surrogates.kriging.correlation_models.ExponentialCorrelation import ExponentialCorrelation

    marginals = [Normal(loc=0., scale=4.), Normal(loc=0., scale=4.)]
    x = MonteCarloSampling(distributions=marginals,
                           nsamples=20,
                           random_state=1)
    model = PythonModel(model_script='series.py', model_object_name="series")
    rmodel = RunModel(model=model)
    regression_model = LinearRegression()
    correlation_model = ExponentialCorrelation()
    K = Kriging(
        regression_model=regression_model,
        correlation_model=correlation_model,
        optimizations_number=10,
        correlation_model_parameters=[1, 1],
        optimizer=MinimizeOptimizer('l-bfgs-b'),
    )
    # OPTIONS: 'U', 'EFF', 'Weighted-U'
    learning_function = ExpectedImprovementGlobalFit()
    a = AdaptiveKriging(distributions=marginals,
                        runmodel_object=rmodel,
                        surrogate=K,
                        learning_nsamples=10**3,
                        n_add=1,
                        learning_function=learning_function,
                        random_state=2)
    a.run(nsamples=25, samples=x.samples)

    assert a.samples[23, 0] == 11.939859785098493
    assert a.samples[20, 1] == -8.429899469300118
Ejemplo n.º 4
0
def test_direct_samples():
    model = PythonModel(model_script='python_model.py',
                        model_object_name='SumRVs')
    model_python_serial_class = RunModel(model=model, samples=x_mcs.samples)
    assert np.allclose(
        np.array(model_python_serial_class.qoi_list).flatten(),
        np.sum(x_mcs.samples, axis=1))
Ejemplo n.º 5
0
def test_rss_runmodel_object():
    """
        Check 'runmodel_object' should be a UQpy.RunModel class object.
    """
    marginals = [Uniform(loc=0., scale=2.), Uniform(loc=0., scale=1.)]
    strata = RectangularStrata(strata_number=[2, 2])
    x = TrueStratifiedSampling(distributions=marginals,
                               strata_object=strata,
                               nsamples_per_stratum=1,
                               random_state=1)
    from UQpy.surrogates.kriging.regression_models import LinearRegression
    from UQpy.surrogates.kriging.correlation_models import ExponentialCorrelation

    K = Kriging(
        regression_model=LinearRegression(),
        correlation_model=ExponentialCorrelation(),
        optimizations_number=20,
        correlation_model_parameters=[1, 1],
        optimizer=MinimizeOptimizer('l-bfgs-b'),
    )
    model = PythonModel(model_script='python_model_function.py',
                        model_object_name="y_func")
    rmodel = RunModel(model=model)
    K.fit(samples=x.samples, values=rmodel.qoi_list)
    with pytest.raises(BeartypeCallHintPepParamException):
        refinement = GradientEnhancedRefinement(strata=x.strata_object,
                                                runmodel_object='abc',
                                                surrogate=K)
        RefinedStratifiedSampling(stratified_sampling=x,
                                  samples_number=6,
                                  samples_per_iteration=2,
                                  refinement_algorithm=refinement)
Ejemplo n.º 6
0
def test_regression_model():
    param_true = np.array([1.0, 2.0]).reshape((1, -1))
    from UQpy.run_model.model_execution.PythonModel import PythonModel
    model = PythonModel(model_script='pfn_models.py',
                        model_object_name='model_quadratic',
                        var_names=['theta_0', 'theta_1'])
    h_func = RunModel(model=model)
    h_func.run(samples=param_true)

    # Add noise
    error_covariance = 1.
    data_clean = np.array(h_func.qoi_list[0])
    noise = Normal(loc=0., scale=np.sqrt(error_covariance)).rvs(
        nsamples=4, random_state=1).reshape((4, ))
    data_3 = data_clean + noise

    candidate_model = ComputationalModel(n_parameters=2,
                                         runmodel_object=h_func,
                                         error_covariance=error_covariance)

    optimizer = MinimizeOptimizer(method='nelder-mead')
    ml_estimator = MLE(inference_model=candidate_model,
                       data=data_3,
                       n_optimizations=1,
                       random_state=1,
                       optimizer=optimizer)

    assert ml_estimator.mle[0] == 0.8689097631871134
    assert ml_estimator.mle[1] == 2.0030767805841143
Ejemplo n.º 7
0
def test_akmcs_expected_feasibility():
    from UQpy.surrogates.kriging.regression_models.LinearRegression import LinearRegression
    from UQpy.surrogates.kriging.correlation_models.ExponentialCorrelation import ExponentialCorrelation

    marginals = [Normal(loc=0., scale=4.), Normal(loc=0., scale=4.)]
    x = MonteCarloSampling(distributions=marginals,
                           nsamples=20,
                           random_state=1)
    model = PythonModel(model_script='series.py', model_object_name="series")
    rmodel = RunModel(model=model)
    regression_model = LinearRegression()
    correlation_model = ExponentialCorrelation()
    K = Kriging(
        regression_model=regression_model,
        correlation_model=correlation_model,
        optimizations_number=10,
        correlation_model_parameters=[1, 1],
        optimizer=MinimizeOptimizer('l-bfgs-b'),
    )
    # OPTIONS: 'U', 'EFF', 'Weighted-U'
    learning_function = ExpectedFeasibility(eff_a=0,
                                            eff_epsilon=2,
                                            eff_stop=0.001)
    a = AdaptiveKriging(distributions=marginals,
                        runmodel_object=rmodel,
                        surrogate=K,
                        learning_nsamples=10**3,
                        n_add=1,
                        learning_function=learning_function,
                        random_state=2)
    a.run(nsamples=25, samples=x.samples)

    assert a.samples[23, 0] == 1.366058523912817
    assert a.samples[20, 1] == -12.914668932772358
Ejemplo n.º 8
0
def test_akmcs_u():
    from UQpy.surrogates.kriging.regression_models.LinearRegression import LinearRegression
    from UQpy.surrogates.kriging.correlation_models.ExponentialCorrelation import ExponentialCorrelation

    marginals = [Normal(loc=0., scale=4.), Normal(loc=0., scale=4.)]
    x = MonteCarloSampling(distributions=marginals,
                           nsamples=20,
                           random_state=1)
    model = PythonModel(model_script='series.py', model_object_name="series")
    rmodel = RunModel(model=model)
    regression_model = LinearRegression()
    correlation_model = ExponentialCorrelation()
    K = Kriging(regression_model=regression_model,
                correlation_model=correlation_model,
                optimizer=MinimizeOptimizer('l-bfgs-b'),
                optimizations_number=10,
                correlation_model_parameters=[1, 1],
                random_state=0)
    # OPTIONS: 'U', 'EFF', 'Weighted-U'
    learning_function = UFunction(u_stop=2)
    a = AdaptiveKriging(distributions=marginals,
                        runmodel_object=rmodel,
                        surrogate=K,
                        learning_nsamples=10**3,
                        n_add=1,
                        learning_function=learning_function,
                        random_state=2)
    a.run(nsamples=25, samples=x.samples)

    assert a.samples[23, 0] == -4.141979058326188
    assert a.samples[20, 1] == -1.6476534435429009
Ejemplo n.º 9
0
def test_akmcs_samples_error():
    from UQpy.surrogates.kriging.regression_models.LinearRegression import LinearRegression
    from UQpy.surrogates.kriging.correlation_models.ExponentialCorrelation import ExponentialCorrelation

    marginals = [Normal(loc=0., scale=4.), Normal(loc=0., scale=4.)]
    x = MonteCarloSampling(distributions=marginals,
                           nsamples=20,
                           random_state=0)
    model = PythonModel(model_script='series.py', model_object_name="series")
    rmodel = RunModel(model=model)
    regression_model = LinearRegression()
    correlation_model = ExponentialCorrelation()
    K = Kriging(regression_model=regression_model,
                correlation_model=correlation_model,
                optimizer=MinimizeOptimizer('l-bfgs-b'),
                optimizations_number=10,
                correlation_model_parameters=[1, 1],
                random_state=1)
    # OPTIONS: 'U', 'EFF', 'Weighted-U'
    learning_function = WeightedUFunction(weighted_u_stop=2)
    with pytest.raises(NotImplementedError):
        a = AdaptiveKriging(distributions=[Normal(loc=0., scale=4.)] * 3,
                            runmodel_object=rmodel,
                            surrogate=K,
                            learning_nsamples=10**3,
                            n_add=1,
                            learning_function=learning_function,
                            random_state=2,
                            samples=x.samples)
Ejemplo n.º 10
0
def test_python_serial_workflow_function():
    model = PythonModel(model_script='python_model.py',
                        model_object_name='sum_rvs')
    model_python_serial_function = RunModel(model=model)
    model_python_serial_function.run(samples=x_mcs.samples)
    assert np.allclose(
        np.array(model_python_serial_function.qoi_list).flatten(),
        np.sum(x_mcs.samples, axis=1))
Ejemplo n.º 11
0
def test_python_serial_workflow_class_vectorized():
    model = PythonModel(model_script='python_model.py',
                        model_object_name='SumRVs')
    model_python_serial_class = RunModel(model=model)
    model_python_serial_class.run(samples=x_mcs.samples)
    assert np.allclose(
        np.array(model_python_serial_class.qoi_list).flatten(),
        np.sum(x_mcs.samples, axis=1))
Ejemplo n.º 12
0
def test_python_parallel_workflow_function():
    model = PythonModel(model_script='python_model.py',
                        model_object_name='sum_rvs')
    model_python_parallel_function = RunModel(model=model, ntasks=3)
    model_python_parallel_function.run(samples=x_mcs.samples)
    assert np.allclose(
        np.array(model_python_parallel_function.qoi_list).flatten(),
        np.sum(x_mcs.samples, axis=1))
    shutil.rmtree(model_python_parallel_function.model_dir)
Ejemplo n.º 13
0
def test_append_samples_true():
    model = PythonModel(model_script='python_model.py',
                        model_object_name='SumRVs')
    model_python_serial_class = RunModel(model=model, samples=x_mcs.samples)
    assert np.allclose(
        np.array(model_python_serial_class.qoi_list).flatten(),
        np.sum(x_mcs.samples, axis=1))
    model_python_serial_class.run(x_mcs_new.samples, append_samples=True)
    assert np.allclose(
        np.array(model_python_serial_class.qoi_list).flatten(),
        np.sum(np.vstack((x_mcs.samples, x_mcs_new.samples)), axis=1))
Ejemplo n.º 14
0
def test_subset():  # Define the structural problem
    n_variables = 2
    model = 'pfn5.py'
    Example = 'Example1'

    omega = 6
    epsilon = 0.01
    mu_m = 5
    sigma_m = 1
    mu_k = 125
    sigma_k = 25
    m = np.linspace(mu_m - 3 * sigma_m, mu_m + 3 * sigma_m, 101)
    d_m = Normal(loc=mu_m, scale=sigma_m)
    d_k = Normal(loc=mu_k, scale=sigma_k)
    dist_nominal = JointIndependent(marginals=[d_m, d_k])

    from UQpy.sampling import Stretch

    n_samples_set = 1000
    p_cond = 0.1
    n_chains = int(n_samples_set * p_cond)

    mc = MonteCarloSampling(distributions=dist_nominal,
                            nsamples=n_samples_set,
                            random_state=1)

    init_sus_samples = mc.samples
    from UQpy.run_model.RunModel import RunModel
    from UQpy.run_model.model_execution.PythonModel import PythonModel

    model = PythonModel(model_script=model, model_object_name=Example)
    RunModelObject_SuS = RunModel(model=model)

    sampling = Stretch(pdf_target=dist_nominal.pdf,
                       dimension=2,
                       n_chains=1000,
                       random_state=0)

    SuS_object = SubsetSimulation(sampling=sampling,
                                  runmodel_object=RunModelObject_SuS,
                                  conditional_probability=p_cond,
                                  nsamples_per_subset=n_samples_set,
                                  samples_init=init_sus_samples)

    print(SuS_object.failure_probability)
    assert SuS_object.failure_probability == 3.1200000000000006e-05
Ejemplo n.º 15
0
def test_vor_gerss():
    """
    Test the 6 samples generated by GE-RSS using voronoi stratification
    """
    marginals = [Uniform(loc=0., scale=2.), Uniform(loc=0., scale=1.)]
    strata_vor = VoronoiStrata(seeds_number=4, dimension=2, random_state=10)
    x_vor = TrueStratifiedSampling(
        distributions=marginals,
        strata_object=strata_vor,
        nsamples_per_stratum=1,
    )
    from UQpy.surrogates.kriging.regression_models.LinearRegression import LinearRegression
    from UQpy.surrogates.kriging.correlation_models.ExponentialCorrelation import ExponentialCorrelation
    model = PythonModel(model_script='python_model_function.py',
                        model_object_name="y_func")
    rmodel = RunModel(model=model)
    K_ = Kriging(regression_model=LinearRegression(),
                 correlation_model=ExponentialCorrelation(),
                 optimizations_number=20,
                 optimizer=MinimizeOptimizer('l-bfgs-b'),
                 random_state=0,
                 correlation_model_parameters=[1, 1])

    K_.fit(samples=x_vor.samples, values=rmodel.qoi_list)
    z_vor = RefinedStratifiedSampling(
        stratified_sampling=x_vor,
        nsamples=6,
        random_state=x_vor.random_state,
        refinement_algorithm=GradientEnhancedRefinement(
            strata=x_vor.strata_object,
            runmodel_object=rmodel,
            surrogate=K_,
            nearest_points_number=4))
    assert np.allclose(
        z_vor.samples,
        np.array([[1.78345908, 0.01640854], [1.46201137, 0.70862104],
                  [0.4021338, 0.05290083], [0.1062376, 0.88958226],
                  [0.61246269, 0.47160095], [1.16609055, 0.30832536]]))
    assert np.allclose(
        z_vor.samplesU01,
        np.array([[0.89172954, 0.01640854], [0.73100569, 0.70862104],
                  [0.2010669, 0.05290083], [0.0531188, 0.88958226],
                  [0.30623134, 0.47160095], [0.58304527, 0.30832536]]))
Ejemplo n.º 16
0
def test_form_example():
    path = os.path.abspath(os.path.dirname(__file__))
    os.chdir(path)
    model = PythonModel(model_script='pfn3.py',
                        model_object_name='example1',
                        delete_files=True)
    RunModelObject = RunModel(model=model)
    dist1 = Normal(loc=200., scale=20.)
    dist2 = Normal(loc=150, scale=10.)
    Q = FORM(distributions=[dist1, dist2],
             runmodel_object=RunModelObject,
             tol1=1e-5,
             tol2=1e-5)
    Q.run()

    # print results
    np.allclose(Q.DesignPoint_U, np.array([-2., 1.]))
    np.allclose(Q.DesignPoint_X, np.array([160., 160.]))
    assert Q.beta[0] == 2.236067977499917
    assert Q.failure_probability[0] == 0.012673659338729965
    np.allclose(Q.dg_u_record, np.array([0., 0.]))
Ejemplo n.º 17
0
def test_rss_kriging_object():
    """
        Check 'kriging_object', it should have 'fit' and 'predict' methods.
    """
    marginals = [Uniform(loc=0., scale=2.), Uniform(loc=0., scale=1.)]
    strata = RectangularStrata(strata_number=[2, 2])
    x = TrueStratifiedSampling(distributions=marginals,
                               strata_object=strata,
                               nsamples_per_stratum=1,
                               random_state=1)
    model = PythonModel(model_script='python_model_function.py',
                        model_object_name="y_func")
    rmodel = RunModel(model=model)
    with pytest.raises(NotImplementedError):
        refinement = GradientEnhancedRefinement(strata=x.strata_object,
                                                runmodel_object=rmodel,
                                                surrogate="abc")
        RefinedStratifiedSampling(stratified_sampling=x,
                                  nsamples=6,
                                  samples_per_iteration=2,
                                  refinement_algorithm=refinement)
Ejemplo n.º 18
0
def test_rect_gerss():
    """
    Test the 6 samples generated by GE-RSS using rectangular stratification
    """
    marginals = [Uniform(loc=0., scale=2.), Uniform(loc=0., scale=1.)]
    strata = RectangularStrata(strata_number=[2, 2], random_state=1)
    x = TrueStratifiedSampling(distributions=marginals,
                               strata_object=strata,
                               nsamples_per_stratum=1)
    model = PythonModel(model_script='python_model_function.py',
                        model_object_name="y_func")
    rmodel = RunModel(model=model)
    from UQpy.surrogates.kriging.regression_models import LinearRegression
    from UQpy.surrogates.kriging.correlation_models import ExponentialCorrelation

    K = Kriging(
        regression_model=LinearRegression(),
        correlation_model=ExponentialCorrelation(),
        optimizations_number=20,
        random_state=0,
        correlation_model_parameters=[1, 1],
        optimizer=MinimizeOptimizer('l-bfgs-b'),
    )
    K.fit(samples=x.samples, values=rmodel.qoi_list)
    refinement = GradientEnhancedRefinement(strata=x.strata_object,
                                            runmodel_object=rmodel,
                                            surrogate=K,
                                            nearest_points_number=4)
    z = RefinedStratifiedSampling(stratified_sampling=x,
                                  random_state=2,
                                  refinement_algorithm=refinement)
    z.run(nsamples=6)
    assert np.allclose(
        z.samples,
        np.array([[0.417022, 0.36016225], [1.00011437, 0.15116629],
                  [0.14675589, 0.5461693], [1.18626021, 0.67278036],
                  [1.51296312, 0.77483124], [0.74237455, 0.66026822]]))
Ejemplo n.º 19
0
from UQpy.run_model.model_execution.PythonModel import PythonModel
from UQpy.run_model.RunModel import RunModel
from UQpy.distributions import Uniform
from UQpy.sensitivity import MorrisSensitivity
import matplotlib.pyplot as plt

# %% md
#
# Set-up problem with g-function.

# %%

a_values = [0.001, 89.9, 5.54, 42.10, 0.78, 1.26, 0.04, 0.79, 74.51, 4.32, 82.51, 41.62]
na = len(a_values)

model = PythonModel(model_script='local_pfn.py', model_object_name='gfun_sensitivity', delete_files=True,
                    a_values=a_values, var_names=['X{}'.format(i) for i in range(na)])
runmodel_object = RunModel(model=model)

dist_object = [Uniform(), ] * na

sens = MorrisSensitivity(runmodel_object=runmodel_object,
                         distributions=dist_object,
                         n_levels=20,
                         maximize_dispersion=True)
sens.run(n_trajectories=10)

print(['a{}={}'.format(i + 1, ai) for i, ai in enumerate(a_values)])

fig, ax = plt.subplots()
ax.scatter(sens.mustar_indices, sens.sigma_indices)
for i, (mu, sig) in enumerate(zip(sens.mustar_indices, sens.sigma_indices)):
Ejemplo n.º 20
0
def setup():
    model = PythonModel(model_script='pfn.py', model_object_name='gfun_sensitivity', delete_files=True,
                        a_values=[0.001, 99.], var_names=['X{}'.format(i) for i in range(2)])
    runmodel_object = RunModel(model=model)
    dist_object = [Uniform(), Uniform()]
    yield runmodel_object, dist_object
Ejemplo n.º 21
0
def setup():
    path = os.path.abspath(os.path.dirname(__file__))
    os.chdir(path)
    model = PythonModel(model_script='pfn4.py', model_object_name='model_k', delete_files=True)
    h_func = RunModel(model=model)
    yield h_func
Ejemplo n.º 22
0
def test_python_serial_workflow_function_wrong_object_name():
    with pytest.raises(AttributeError):
        model = PythonModel(model_script='python_model.py',
                            model_object_name="random_model_name")
        model = RunModel(model=model)
        model.run(x_mcs.samples)
Ejemplo n.º 23
0
def test_python_serial_workflow_function_no_objects():
    with pytest.raises(TypeError):
        model = PythonModel(model_script='python_model_blank.py')
        model = RunModel(model=model)
        model.run(x_mcs.samples)
Ejemplo n.º 24
0
def setup():
    model = PythonModel(model_script='pfn1.py',
                        model_object_name='model_i',
                        delete_files=True)
    h_func = RunModel(model=model)
    yield h_func
Ejemplo n.º 25
0
import shutil

from UQpy.run_model.RunModel import RunModel
from UQpy.run_model.model_execution.PythonModel import PythonModel
from UQpy.distributions import Uniform
from UQpy.sensitivity import MorrisSensitivity
import matplotlib.pyplot as plt

#%% md
#
# Set-up problem with g-function.

#%%

model = PythonModel(model_script='local_pfn.py',
                    model_object_name='fun2_sensitivity',
                    delete_files=True,
                    var_names=['X{}'.format(i) for i in range(5)])
runmodel_object = RunModel(model=model)

dist_object = [
    Uniform(),
] * 5

sens = MorrisSensitivity(runmodel_object=runmodel_object,
                         distributions=dist_object,
                         n_levels=20,
                         maximize_dispersion=True)
sens.run(n_trajectories=10)

fig, ax = plt.subplots(figsize=(5, 3.5))
ax.scatter(sens.mustar_indices, sens.sigma_indices, s=60)
Ejemplo n.º 26
0
def test_model_script():
    with pytest.raises(ValueError):
        model = PythonModel(model_script='random_file_name',
                            model_object_name='SumRVs',
                            delete_files=True)
        runmodel_object = RunModel(model=model)
Ejemplo n.º 27
0
# %%

# %% md
#
# Initially we have to import the necessary modules.

# %%

from UQpy.run_model.RunModel import RunModel
from UQpy.run_model.model_execution.PythonModel import PythonModel
from UQpy.distributions import Normal
from UQpy.reliability import FORM

dist1 = Normal(loc=20., scale=3.5)
dist2 = Normal(loc=5., scale=0.8)
dist3 = Normal(loc=4., scale=0.4)

model = PythonModel(
    model_script='pfn.py',
    model_object_name="example3",
)
RunModelObject3 = RunModel(model=model)

Z0 = FORM(distributions=[dist1, dist2, dist3], runmodel_object=RunModelObject3)
Z0.run()

print('Design point in standard normal space: %s' % Z0.DesignPoint_U)
print('Design point in original space: %s' % Z0.DesignPoint_X)
print('Hasofer-Lind reliability index: %s' % Z0.beta)
print('FORM probability of failure: %s' % Z0.failure_probability)
Ejemplo n.º 28
0
def test_samples():
    with pytest.raises(BeartypeCallHintPepParamException):
        model = PythonModel(model_script='python_model.py',
                            model_object_name='SumRVs',
                            delete_files=True)
        runmodel_object = RunModel(model=model, samples="samples_string")