def test_python_serial_workflow_function_vectorized(): 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))
def test_python_serial_workflow_class(): 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))
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)
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))
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)
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)
def test_third_party_parallel(): names = ['var1', 'var11', 'var111'] model = ThirdPartyModel(model_script='python_model_sum_scalar.py', fmt="{:>10.4f}", delete_files=True, input_template='sum_scalar.py', var_names=names, model_object_name="matlab", output_script='process_third_party_output.py', output_object_name='read_output') m = RunModel(model=model, ntasks=3) m.run(x_mcs.samples) assert np.allclose(np.array(m.qoi_list).flatten(), np.sum(x_mcs.samples, axis=1), atol=1e-4) shutil.rmtree(m.model.model_dir)
def test_derivatives_6_second(): model = PythonModel(model_script='pfn2.py', model_object_name='model_j', delete_files=True) h_func = RunModel(model=model) dist1 = Normal(loc=500, scale=100) dist2 = Normal(loc=1000, scale=100) point_u = np.array([1.73673009, 0.16383283]) rx = np.array([[1.0, 0.0], [0.0, 1.0]]) ntf_obj = Nataf(distributions=[dist1, dist2], corr_x=rx) hessian = TaylorSeries._derivatives(point_u=point_u, runmodel_object=h_func, nataf_object=ntf_obj, order='second') np.testing.assert_allclose(hessian, [[-0.00720754, 0.00477726], [0.00477726, -0.00316643]], rtol=1e-04)
def test_third_party_var_names(): names = ['var1', 'var11', 'var111', 'var1111'] with pytest.raises(TypeError): model = ThirdPartyModel(model_script='python_model_sum_scalar.py', fmt="{:>10.4f}", delete_files=True, input_template='sum_scalar.py', model_object_name="matlab", output_script='process_third_party_output.py', output_object_name='read_output') model_third_party_default_names = RunModel(model=model, ntasks=3, samples=x_mcs.samples)
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]]))
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)
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]]))
def setup(): model = PythonModel(model_script='pfn1.py', model_object_name='model_i', delete_files=True) h_func = RunModel(model=model) yield h_func
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)
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)
# There are two probabilistic input variables, the fire load density and the yield strength. # %% var_names = ['qtd', 'fy'] # %% md # # Create the model object # %% abaqus_sfe_model = RunModel(model_script='abaqus_fire_analysis.py', input_template='abaqus_input.py', output_script='extract_abaqus_output.py', var_names=var_names, ntasks=24, model_dir='SFE_MCS', verbose=True, cores_per_task=1) print('Example: Created the model object.') # %% md # # Towards defining the sampling scheme # The fire load density is assumed to be uniformly distributed between 50 :math:`MJ/m^2` and 450 :math:`MJ/m^2`. # The yield strength is assumed to be normally distributed, with the parameters # being: mean = 250 :math:`MPa` and coefficient of variation of :math:`7%`. # # Creating samples using MCS. # %%
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)
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")
def test_models(): a = os.getcwd() if "inference" not in a: os.chdir("../inference") data_ex1 = np.loadtxt('data_ex1a.txt') model = PythonModel(model_script='pfn_linear.py', model_object_name='model_linear', var_names=['theta_0']) runmodel4 = RunModel(model=model) model1 = PythonModel(model_script='pfn_quadratic.py', model_object_name='model_quadratic', var_names=['theta_0', 'theta_1']) runmodel5 = RunModel(model=model1) model2 = PythonModel(model_script='pfn_cubic.py', model_object_name='model_cubic', var_names=['theta_0', 'theta_1', 'theta_2']) runmodel6 = RunModel(model=model2) prior1 = Normal() prior2 = JointIndependent(marginals=[Normal(), Normal()]) prior3 = JointIndependent(marginals=[Normal(), Normal(), Normal()]) model_n_params = [1, 2, 3] model1 = ComputationalModel(n_parameters=1, runmodel_object=runmodel4, prior=prior1, error_covariance=np.ones(50), name='model_linear') model2 = ComputationalModel(n_parameters=2, runmodel_object=runmodel5, prior=prior2, error_covariance=np.ones(50), name='model_quadratic') model3 = ComputationalModel(n_parameters=3, runmodel_object=runmodel6, prior=prior3, error_covariance=np.ones(50), name='model_cubic') proposals = [ Normal(0, 10), JointIndependent([Normal(0, 1), Normal(0, 1)]), JointIndependent([Normal(0, 1), Normal(0, 2), Normal(0.025)]) ] # sampling = mh1 = MetropolisHastings(args_target=(data_ex1, ), log_pdf_target=model1.evaluate_log_posterior, jump=1, burn_length=500, proposal=proposals[0], random_state=0, seed=[0.]) mh2 = MetropolisHastings(args_target=(data_ex1, ), log_pdf_target=model2.evaluate_log_posterior, jump=1, burn_length=500, proposal=proposals[1], random_state=0, seed=[0., 0.]) mh3 = MetropolisHastings(args_target=(data_ex1, ), log_pdf_target=model3.evaluate_log_posterior, jump=1, burn_length=500, proposal=proposals[2], random_state=0, seed=[0., 0., 0.]) e1 = BayesParameterEstimation(inference_model=model1, data=data_ex1, sampling_class=mh1) e2 = BayesParameterEstimation(inference_model=model2, data=data_ex1, sampling_class=mh2) e3 = BayesParameterEstimation(inference_model=model3, data=data_ex1, sampling_class=mh3) selection = BayesModelSelection( parameter_estimators=[e1, e2, e3], prior_probabilities=[1. / 3., 1. / 3., 1. / 3.], nsamples=[2000, 2000, 2000]) selection.sort_models() assert selection.probabilities[0] == 1.0 assert selection.probabilities[1] == 0.0 assert selection.probabilities[2] == 0.0 assert selection.candidate_models[0].name == 'model_quadratic' assert selection.candidate_models[1].name == 'model_cubic' assert selection.candidate_models[2].name == 'model_linear'