def test_invalid_init_parameter_values_rejected(): # Ensure exception for invalid srom dimensions. with pytest.raises(ValueError): SROM(0, 1) SROM(-1, 1) SROM(10, 0) SROM(10, 3)
dim = 3 sromsize = 20 #Data files for EOL samples, EOL finite difference samples, and SROM inputs srom_eol_file = "srom_data/srom_eol_m" + str(sromsize) + ".txt" srom_fd_eol_file = "srom_data/srom_fd_eol_m" + str(sromsize) + ".txt" srom_input_file = "srom_data/srom_m" + str(sromsize) + ".txt" #Get MC input/EOL samples MC_inputs = np.genfromtxt(mc_input_file) MC_eols = np.genfromtxt(mc_eol_file) #Get SROM EOL samples, FD samples and input SROM from file srom_eols = np.genfromtxt(srom_eol_file) srom_fd_eols = np.genfromtxt(srom_fd_eol_file) input_srom = SROM(sromsize, dim) input_srom.load_params(srom_input_file) #Get FD step sizes from file (the same for all samples, just pull the first) #Step sizes chosen as approximately 2% of the median sample value of inputs stepsizes = [0.0065, 0.083, 0.025] #Calculate gradient from FiniteDifference class: gradient = FD.compute_gradient(srom_eols, srom_fd_eols, stepsizes) #Create SROM surrogate, sample, and create random variable solution surrogate_PWL = SROMSurrogate(input_srom, srom_eols, gradient) srom_eol_samples = surrogate_PWL.sample(MC_inputs) solution_PWL = SampleRandomVector(srom_eol_samples) #Store EOL samples for plotting later:
def valid_srom(): return SROM(10, 1)
performance_data['min_samples'] = min_samples performance_data['max_samples'] = max_samples performance_data['samples_step'] = samples_step test_results = [] for num_test_samples in xrange(min_samples, max_samples, samples_step): if comm.rank == 0: print 'Optimizing with %s test samples...' % num_test_samples iteration_performance = [] for i in xrange( 10 ): # Repeat performance data collection in order to smooth the chart lines. input_srom = SROM(20, 1) t0 = time.time() input_srom.optimize(random_variable, num_test_samples=num_test_samples, verbose=False) iteration_performance.append(time.time() - t0) # We only need to save performance data from one process because # they should be the same due to gather operation within optimize(). if comm.rank == 0: mean_performance = np.mean(iteration_performance) test_results.append(mean_performance) if comm.rank != 0:
import numpy from os import path from SROMPy.postprocess import Postprocessor from SROMPy.srom import SROM, SROMSurrogate from SROMPy.target import SampleRandomVector #Define target random vector from samples monte_carlo_input_samples_filename = path.join("mc_data", "input_samples_MC.txt") monte_carlo_input_samples = numpy.genfromtxt( monte_carlo_input_samples_filename) target_vector = SampleRandomVector(monte_carlo_input_samples) #Define SROM and determine optimal parameters srom_size = 20 input_srom = SROM(size=srom_size, dim=3) input_srom.optimize(target_vector) #Compare the input CDFs (produces Figure 6) post_processor = Postprocessor(input_srom, target_vector) post_processor.compare_CDFs(variablenames=[r'$y_{0}$', r'log$C$', r'$n$']) #Run the model for each input SROM sample: srom_results = numpy.zeros(srom_size) (srom_samples, srom_probs) = input_srom.get_params() # TODO: define model here. model = None if model is None: raise ValueError("model has not been defined.")
samples = np.genfromtxt(target_samples) target = SampleRandomVector(samples) # Set x limits for each variable based on target: x_limits = [] for i in range(target._dim): limits = [np.min(samples[:, i]), np.max(samples[:, i])] x_limits.append(limits) # Build up srom_size-to-SROM object map for plotting routine. sroms = OrderedDict() for srom_size in srom_sizes: # Generate SROM from file: srom = SROM(srom_size, target._dim) srom_filename = "srom_m" + str(srom_size) + ".txt" srom_filename = os.path.join(srom_dir, srom_filename) srom.load_params(srom_filename) sroms[srom_size] = srom # Font size specs & plotting. axis_font_size = 25 legend_font_size = 20 Postprocessor.compare_srom_cdfs(sroms, target, plot_dir="plots", plot_suffix=plot_suffix, variable_names=variables, x_limits=x_limits, x_ticks=x_ticks,
from SROMPy.postprocess import Postprocessor from SROMPy.srom import SROM from SROMPy.target import SampleRandomVector ''' Script to generate piecewise constant SROM approximation to EOL and compare it with the Monte Carlo solution - step 3. Uses the stored EOL model outputs from step 2 and the stored input SROM from step 1. ''' mc_eol_file = "mc_data/eol_samples_MC.txt" sromsize = 20 srom_eol_file = "srom_data/srom_eol_m" + str(sromsize) + ".txt" srom_input_file = "srom_data/srom_m" + str(sromsize) + ".txt" #Get MC EOL samples MC_eols = np.genfromtxt(mc_eol_file) #Get SROM EOL samples & probabilities from input srom srom_eols = np.genfromtxt(srom_eol_file) srom_probs = np.genfromtxt(srom_input_file)[:, -1] #probs in last column #Make MC random variable & SROM to compare eol_srom = SROM(sromsize, dim=1) eol_srom.set_params(srom_eols, srom_probs) eol_mc = SampleRandomVector(MC_eols) pp = Postprocessor(eol_srom, eol_mc) pp.compare_CDFs(variablenames=["EOL"])
# Copyright 2018 United States Government as represented by the Administrator of # the National Aeronautics and Space Administration. No copyright is claimed in # the United States under Title 17, U.S. Code. All Other Rights Reserved. # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed # under the Apache License, Version 2.0 (the "License"); you may not use this # file except in compliance with the License. You may obtain a copy of the # License at http://www.apache.org/licenses/LICENSE-2.0. # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from SROMPy.postprocess import Postprocessor from SROMPy.srom import SROM from SROMPy.target import NormalRandomVariable # Initialize Normal random variable object to be modeled by SROM: normal = NormalRandomVariable(mean=3., std_dev=1.5) # Initialize SROM & optimize to model the normal random variable: srom = SROM(size=10, dim=1) srom.optimize(normal) # Compare the CDF of the SROM & target normal variable: post_processor = Postprocessor(srom, normal) post_processor.compare_cdfs()
import numpy as np from SROMPy.postprocess import Postprocessor from SROMPy.srom import SROM from SROMPy.target import SampleRandomVector ''' Generate SROM to model input distribution (samples) ''' #Specify input/output files and SROM optimization parameters dim = 3 srom_size = 20 samplesfile = "mc_data/input_samples_MC.txt" outfile = "srom_data/srom_m" + str(srom_size) + ".txt" #Define target random variable from samples MCsamples = np.genfromtxt(samplesfile) target = SampleRandomVector(MCsamples) #Define SROM, determine optimal parameters, store parameters srom = SROM(srom_size, dim) srom.optimize(target, weights=[1, 1, 1], error="SSE", num_test_samples=100) #NOTE - commented out to not overwrite paper data files: #srom.save_params(outfile) #Check out the CDFs pp = Postprocessor(srom, target) pp.compare_CDFs(variablenames=[r'$y_{0}$', r'log$C$', r'$n$'])
NOTE - this script will not run, Model class is not provided. But this script is representative of a common SROM workflow. First, we load the SROM parameters that were generated in step 1, then we get the samples for that SROM and evaluate the crack growth model for each one, and store the outputs (EOL) from the model. ''' # Initialize crack growth model (not provided). model = CrackGrowthModel() dim = 3 srom_size = 20 srom_filename = "srom_data/srom_m" + str(srom_size) + ".txt" srom_end_of_life_filename = "srom_data/srom_eol_m" + str(srom_size) + ".txt" # Initialize SROM and load parameters from file. srom = SROM(srom_size, dim) srom.load_params(srom_filename) # Evaluate the crack growth model for each SROM input sample. srom_outputs = np.zeros(srom_size) (srom_samples, srom_probabilities) = srom.get_params() for i, srom_sample in enumerate(srom_samples): srom_outputs[i] = model.evaluate(srom_sample) # Save EOL outputs for step 3: np.savetxt(srom_end_of_life_filename, srom_outputs)
samples = np.genfromtxt(targetsamples) target = SampleRandomVector(samples) #Set x limits for each variable based on target: xlimits = [] for i in range(target._dim): lims = [np.min(samples[:, i]), np.max(samples[:, i])] xlimits.append(lims) #Build up sromsize-to-SROM object map for plotting routine sroms = OrderedDict() for sromsize in sromsizes: #Generate SROM from file: srom = SROM(sromsize, target._dim) sromfile = "srom_m" + str(sromsize) + ".txt" sromfile = os.path.join(srom_dir, sromfile) srom.load_params(sromfile) sroms[sromsize] = srom #Font size specs & plotting axisfontsize = 25 legendfontsize = 20 Postprocessor.compare_srom_CDFs(sroms, target, plotdir="plots", plotsuffix=plot_suffix, variablenames=varz, xlimits=xlimits, xticks=xticks,
Run computational model for each input SROM sample - step 2 NOTE - this script will not run, Model class is not provided. But this script is representative of a common SROM workflow. First, we load the SROM parameters that were generated in step 1, then we get the samples for that SROM and evaluate the crack growth model for each one, and store the outputs (EOL) from the model. ''' #Initialize crack growth model (not provided) model = CrackGrowthModel() dim = 3 srom_size = 20 sromfile = "srom_data/srom_m" + str(srom_size) + ".txt" sromeolfile = "srom_data/srom_eol_m" + str(srom_size) + ".txt" #Initialize SROM and load parameters from file srom = SROM(srom_size, dim) srom.load_params(sromfile) #Evaluate the crack growth model for each SROM input sample srom_outputs = np.zeros(srom_size) (srom_samples, srom_probs) = srom.get_params() for i, input in enumerate(srom_samples): srom_outputs[i] = model.evaluate(input) #Save EOL outputs for step 3: np.savetxt(sromeolfile, srom_outputs)
stiffness_samples = stiffness_rv.draw_random_sample(num_samples) #Calculate maximum displacement samples using MC simulation disp_samples = np.zeros(num_samples) for i, stiff in enumerate(stiffness_samples): disp_samples[i] = model.get_max_disp(stiff) #Get Monte carlo solution as a sample-based random variable: mc_solution = SampleRandomVector(disp_samples) #-------------SROM----------------------- #generate SROM for random stiffness sromsize = 10 dim = 1 input_srom = SROM(sromsize, dim) input_srom.optimize(stiffness_rv) #Compare SROM vs target stiffness distribution: pp_input = Postprocessor(input_srom, stiffness_rv) pp_input.compare_CDFs() #Run model to get max disp for each SROM stiffness sample srom_disps = np.zeros(sromsize) (samples, probs) = input_srom.get_params() for i, stiff in enumerate(samples): srom_disps[i] = model.get_max_disp(stiff) #Form new SROM for the max disp. solution using samples from the model output_srom = SROM(sromsize, dim) output_srom.set_params(srom_disps, probs)
''' Generate SROM to model input distribution (samples) ''' # Specify input/output files and SROM optimization parameters. dim = 3 srom_size = 20 monte_carlo_end_of_life_input_filename = "mc_data/input_samples_MC.txt" monte_carlo_end_of_life_sample_filename = "mc_data/eol_samples_MC.txt" # Define target random variable from samples. monte_carlo_samples = np.genfromtxt(monte_carlo_end_of_life_sample_filename) target = SampleRandomVector(monte_carlo_samples) # Define SROM, determine optimal parameters, store parameters. input_srom = SROM(srom_size, dim) input_srom.optimize(target, weights=[1, 1, 1], error="SSE") # Compare the CDFs. pp = Postprocessor(input_srom, target) pp.compare_cdfs(save_figure=False) # Run the model for each input SROM sample: srom_end_of_life_data = np.zeros(srom_size) (srom_samples, srom_probabilities) = input_srom.get_params() for i, sample in enumerate(srom_samples): srom_end_of_life_data[i] = model.evaluate(sample) # Generate SROM surrogate for the output. eol_srom = SROMSurrogate(input_srom, srom_end_of_life_data)
stiffness_samples = stiffness_random_variable.draw_random_sample(num_samples) # Calculate maximum displacement samples using MC simulation. displacement_samples = np.zeros(num_samples) for i, stiff in enumerate(stiffness_samples): displacement_samples[i] = model.get_max_disp(stiff) # Get Monte carlo solution as a sample-based random variable: monte_carlo_solution = SampleRandomVector(displacement_samples) # -------------SROM----------------------- # Generate SROM for random stiffness. srom_size = 10 dim = 1 input_srom = SROM(srom_size, dim) input_srom.optimize(displacement_samples) # Compare SROM vs target stiffness distribution: pp_input = Postprocessor(input_srom, displacement_samples) pp_input.compare_cdfs() # Run model to get max displacement for each SROM stiffness sample. srom_displacements = np.zeros(srom_size) (samples, probabilities) = input_srom.get_params() for i, stiff in enumerate(samples): srom_displacements[i] = model.get_max_disp(stiff) # Form new SROM for the max disp. solution using samples from the model. output_srom = SROM(srom_size, dim) output_srom.set_params(srom_displacements, probabilities)
performance_data['min_samples'] = min_samples performance_data['max_samples'] = max_samples performance_data['samples_step'] = samples_step test_results = [] for num_test_samples in xrange(min_samples, max_samples, samples_step): if comm.rank == 0: print 'Optimizing with %s test samples...' % num_test_samples # Repeat performance data collection in order to smooth the chart lines. iteration_performance = [] for i in xrange(10): input_srom = SROM(20, 1) t0 = time.time() input_srom.optimize(random_variable, num_test_samples=num_test_samples) iteration_performance.append(time.time() - t0) # We only need to save performance data from one process because # they should be the same due to gather operation within optimize(). if comm.rank == 0: mean_performance = np.mean(iteration_performance) test_results.append(mean_performance) if comm.rank != 0: exit()
disp_samples[i] = model.get_max_disp(k_samples[i], m_samples[i]) #Get Monte carlo solution as a sample-based random variable: mc_solution = SampleRandomVector(disp_samples) #-------------SROM----------------------- #generate SROM for random vector of stiffness & mass sromsize = 25 dim = 2 #Assume we only have access to samples in this example and want SROM from them: km_samples = np.array([k_samples, m_samples]).T km_random_vector = SampleRandomVector(km_samples) srom = SROM(sromsize, dim) srom.optimize(km_random_vector) (samples, probs) = srom.get_params() #Run model to get max disp for each SROM stiffness sample srom_disps = np.zeros(sromsize) for i in range(sromsize): k = samples[i, 0] m = samples[i, 1] srom_disps[i] = model.get_max_disp(k, m) #Form new SROM for the max displacement solution using samples from the model srom_solution = SROM(sromsize, 1) srom_solution.set_params(srom_disps, probs) #----------------------------------------
from SROMPy.target import SampleRandomVector ''' Ex3 - unimodal 3D Script to generate PW constant SROM approximation to EOL and compare it with the monte carlo solution (w/ surrogate model) ''' mc_eol_file = "mc_data/eol_samples_MC.txt" srom_size = 20 srom_eol_file = "srom_data/srom_eol_m" + str(srom_size) + ".txt" srom_input_file = "srom_data/srom_m" + str(srom_size) + ".txt" # Get MC EOL samples. MC_eols = np.genfromtxt(mc_eol_file) # Get SROM EOL samples & probabilities from input srom. srom_end_of_life_data = np.genfromtxt(srom_eol_file) # Probabilities in last column. srom_probabilities = np.genfromtxt(srom_input_file)[:, -1] # Make MC random variable & SROM to compare. end_of_life_srom = SROM(srom_size, dim=1) end_of_life_srom.set_params(srom_end_of_life_data, srom_probabilities) end_of_life_monte_carlo = SampleRandomVector(MC_eols) pp = Postprocessor(end_of_life_srom, end_of_life_monte_carlo) pp.compare_cdfs(variable_names=["EOL"])
# Calculate maximum displacement samples using MC simulation. displacement_samples = np.zeros(num_samples) for i, stiff in enumerate(stiffness_samples): displacement_samples[i] = model.evaluate([stiff]) # Get Monte carlo solution as a sample-based random variable: monte_carlo_solution = SampleRandomVector(displacement_samples) # -------------SROM----------------------- print "Generating SROM for input (stiffness)..." # Generate SROM for random stiffness. srom_size = 10 dim = 1 input_srom = SROM(srom_size, dim) input_srom.optimize(stiffness_random_variable) # Compare SROM vs target stiffness distribution: pp_input = Postprocessor(input_srom, stiffness_random_variable) pp_input.compare_cdfs() print "Computing piecewise constant SROM approximation for output (max disp)..." # Run model to get max displacement for each SROM stiffness sample. srom_displacements = np.zeros(srom_size) (samples, probabilities) = input_srom.get_params() for i, stiff in enumerate(samples): srom_displacements[i] = model.evaluate([stiff]) # Form new SROM for the max disp. solution using samples from the model.