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
#%% md # # :class:`.RunModel` class is used to define an object to evaluate the model at sample points. #%% rmodel = RunModel(model_script='local_python_model_function.py') #%% md # # This figure shows the actual function defined in python model script. #%% rmodel1 = RunModel(model_script='local_python_model_function.py') rmodel1.run(samples=x.samples) num = 50 x1 = np.linspace(0, 1, num) x2 = np.linspace(0, 1, num) x1v, x2v = np.meshgrid(x1, x2) y_act = np.zeros([num, num]) r1 = RunModel(model_script='local_python_model_function.py') for i in range(num): for j in range(num): r1.run(samples=np.array([[x1v[i, j], x2v[i, j]]])) y_act[i, j] = r1.qoi_list[-1] fig1 = plt.figure() ax = fig1.gca(projection='3d') # Plot for estimated values
#%% md # # First we generate synthetic data, and add some noise to it. #%% # Generate data param_true = np.array([1.0, 2.0]).reshape((1, -1)) print('Shape of true parameter vector: {}'.format(param_true.shape)) model = PythonModel(model_script='local_pfn_models.py', model_object_name='model_quadratic', delete_files=True, 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=50).reshape((50,)) data_3 = data_clean + noise print('Shape of data: {}'.format(data_3.shape)) #%% md # # Then we create an instance of the Model class, using model_type='python', and we perform maximum likelihood estimation # of the two parameters. #%%
strata_object=strata, nsamples_per_stratum=1, random_state=1) # %% md # # RunModel is used to evaluate function values at sample points. Model is defined as a function in python file # 'python_model_function.py'. # %% model = PythonModel(model_script='local_python_model_function.py', model_object_name="y_func") rmodel = RunModel(model=model) rmodel.run(samples=x.samples) # %% md # # Using UQpy GaussianProcessRegression class to generate a surrogate for generated data. In this illustration, Quadratic regression model and # Exponential correlation model are used. # %% regression_model = ConstantRegression() kernel = Matern(nu=0.5) from UQpy.utilities.MinimizeOptimizer import MinimizeOptimizer optimizer = MinimizeOptimizer(method="L-BFGS-B") K = GaussianProcessRegression(regression_model=regression_model,
# %% md # # Monte Carlo Simulation # ----------------------- # Probability of failure and covariance is estimated using Monte Carlo Simulation. 10,000 samples are generated # randomly using :class:`.MonteCarloSampling` class and model is evaluated at all samples. # %% start_time = time.time() # Code b = MonteCarloSampling(distributions=marginals, nsamples=10**4, random_state=4) model = PythonModel(model_script='local_series.py', model_object_name='series') r1model = RunModel(model=model) r1model.run(samples=b.samples) gx = np.array(r1model.qoi_list) pf_mcs = np.sum(np.array(gx) < 0) / b.nsamples cov_pf_mcs = np.sqrt((1 - pf_mcs) / (pf_mcs * b.nsamples)) elapsed_time = time.time() - start_time time.strftime("%H:%M:%S", time.gmtime(elapsed_time)) # %% md # # Results from Monte Carlo Simulation. # %% print('Time: ', elapsed_time) print('Function evaluation: ', b.nsamples)
# # RunModel class is used to estimate the function value at sample points generated using # :class:`.TrueStratifiedSampling` class. #%% rmodel = RunModel(model_script='local_python_model_function.py', vec=False) #%% md # # This figure shows the actual function defined in python model script. #%% rmodel1 = RunModel(model_script='local_python_model_function.py', vec=False) rmodel1.run(samples=x.samples) num = 100 x1 = np.linspace(0, 1, num) x2 = np.linspace(0, 1, num) x1v, x2v = np.meshgrid(x1, x2) y_act = np.zeros([num, num]) r1model = RunModel(model_script='local_python_model_function.py') for i in range(num): for j in range(num): r1model.run(samples=np.array([[x1v[i, j], x2v[i, j]]]), append_samples=False) y_act[i, j] = r1model.qoi_list[0] fig1 = plt.figure() ax1 = fig1.gca(projection='3d') # Plot for estimated values surf = ax1.plot_surface(x1v, x2v, y_act, cmap=cm.coolwarm, linewidth=0, antialiased=False)
# 1.1 Pass samples as ndarray, Python class called, serial execution # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # This examples uses the following files: # - model_script = python_model.py # %% if pick_model in {'scalar', 'all'}: # Call to RunModel - Here we run the model while instantiating the RunModel object. t = time.time() m11 = RunModel(ntasks=1, model_script='python_model.py', model_object_name='SumRVs', model_dir='Python_Runs', verbose=True) m11.run(samples=x_mcs.samples, ) t_ser_python = time.time() - t print("\nTime for serial execution:") print(t_ser_python) print() print("The values returned from the Matlab simulation:") print(m11.qoi_list) # %% md # # 1.2 Pass samples as list, Python function called, parallel execution # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # This examples uses the following files: # - model_script = python_model.py # %%
strata_object=strata, nsamples_per_stratum=1, random_state=2) # %% md # # RunModel is used to evaluate function values at sample points. Model is defined as a function in python file # 'python_model_function.py'. # %% model = PythonModel(model_script='local_python_model_1Dfunction.py', model_object_name='y_func', delete_files=True) rmodel = RunModel(model=model) rmodel.run(samples=x.samples) from UQpy.surrogates.gaussian_process.regression_models import LinearRegression from UQpy.utilities.MinimizeOptimizer import MinimizeOptimizer bounds = [[10**(-3), 10**3], [10**(-3), 10**2]] optimizer = MinimizeOptimizer(method='L-BFGS-B', bounds=bounds) K = GaussianProcessRegression(regression_model=LinearRegression(), kernel=RBF(), optimizer=optimizer, optimizations_number=20, hyperparameters=[1, 0.1], random_state=2) K.fit(samples=x.samples, values=rmodel.qoi_list) print(K.hyperparameters)
# This examples uses the following files: # # - model_script = matlab_model_sum_scalar.py # - input_template = sum_scalar.m # - output_script = process_matlab_output.py # %% if pick_model == 'scalar' or pick_model == 'all': # Call to RunModel - Here we run the model while instantiating the RunModel object. t = time.time() m = RunModel(ntasks=1, model_script='matlab_model_sum_scalar.py', input_template='sum_scalar.m', var_names=names, model_object_name="matlab", output_script='process_matlab_output.py', output_object_name='read_output', resume=False, model_dir='Matlab_Model', fmt="{:>10.4f}", verbose=True) m.run(x_mcs.samples) t_ser_matlab = time.time() - t print("\nTime for serial execution:") print(t_ser_matlab) print() print("The values returned from the Matlab simulation:") print(m.qoi_list) # %% md # # 1.2 Samples passed as list, no format specification, parallel execution # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # This examples uses the following files: # # - model_script = matlab_model_sum_scalar.py
prop={'size': 12}, bbox_to_anchor=(1, 0.75)) plt.show() # %% md # # Run the model 'eigenvalue_model.py' for each sample generated through :class:`.TrueStratifiedSampling` class. This # model defines the stiffness matrix corresponding to each sample and estimate the eigenvalues of the matrix. # %% m = PythonModel(model_script='local_eigenvalue_model.py', model_object_name="RunPythonModel") model = RunModel(model=m) # model = RunModel(model_script='local_eigenvalue_model.py') model.run(samples=y.samples) r_srom = model.qoi_list # %% md # # :class:`MonteCarloSampling` class is used to generate 1000 samples. # %% x_mcs = MonteCarloSampling(distributions=marginals, nsamples=1000) # %% md # # Run the model 'eigenvalue_model.py' for each sample generated through :class:`.MonteCarloSampling` class. # %%
plt.show() m = PythonModel(model_script='local_Resonance_pfn.py', model_object_name="RunPythonModel") model = RunModel(model=m) # %% md # # Monte Carlo Simulation # %% x_mcs = MonteCarloSampling(distributions=[d1, d2]) x_mcs.run(nsamples=1000000) model.run(samples=x_mcs.samples) A = np.asarray(model.qoi_list) < 0 pf = np.shape(np.asarray( model.qoi_list)[np.asarray(model.qoi_list) < 0])[0] / 1000000 print(pf) ntrials = 1 pf_stretch = np.zeros((ntrials, 1)) cov1_stretch = np.zeros((ntrials, 1)) cov2_stretch = np.zeros((ntrials, 1)) m = np.ones(2) m[0] = 5 m[1] = 125 C = np.eye(2) C[0, 0] = 1
dist_object = [ Uniform(), ] * na # %% md # # First plot contour of the function, clearly X2 has little influence on the function compared to X1. # %% x = np.arange(0, 1, 0.02) y = np.arange(0, 1, 0.02) xx, yy = np.meshgrid(x, y, sparse=False) runmodel_object.run(samples=np.vstack([xx.reshape((-1, )), yy.reshape((-1, ))]).T, append_samples=False) h = plt.contourf(x, y, np.array(runmodel_object.qoi_list).reshape(xx.shape)) plt.xlabel('X1') plt.ylabel('X2') plt.show() sens = MorrisSensitivity(runmodel_object=runmodel_object, distributions=dist_object, n_levels=9) sens.run(n_trajectories=10) fig, ax = plt.subplots(figsize=(4, 4)) for trajectory in sens.trajectories_physical_space[:5]: ax.plot(trajectory[:, 0], trajectory[:, 1], marker='x', linewidth=3) ax.set_xlim([0, 1])