Stochastic reduced order models with Python (SROMPy) is a software package developed to enable user-friendly utilization of the stochastic reduced order model (SROM) approach for uncertainty quantification. A SROM is a low dimensional, discrete approximation to a random quantity that enables efficient and non-intrusive stochastic computations. With SROMPy, a user can easily generate a SROM to approximate a random variable or vector described by several different types of probability distributions using the Python programming language. Once a SROM is constructed, the software also contains functionality to propagate uncertainty through a user-defined computational model to estimate statistics of a given quantity of interest.
48 | Please activate JavaScript to enable the search
49 | functionality.
50 |
51 |
52 |
53 | From here you can search these documents. Enter your search
54 | words into the box below and click "search". Note that the search
55 | function will automatically search for all of the words. Pages
56 | containing fewer words won't appear in the result list.
57 |
109 |
117 |
118 |
119 |
120 |
121 |
122 |
--------------------------------------------------------------------------------
/docs/images/disp_CDFs_pw_constant.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/images/disp_CDFs_pw_constant.pdf
--------------------------------------------------------------------------------
/docs/images/disp_CDFs_pw_constant.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/images/disp_CDFs_pw_constant.png
--------------------------------------------------------------------------------
/docs/images/disp_CDFs_pw_linear.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/images/disp_CDFs_pw_linear.pdf
--------------------------------------------------------------------------------
/docs/images/disp_CDFs_pw_linear.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/images/disp_CDFs_pw_linear.png
--------------------------------------------------------------------------------
/docs/images/spring_mass_diagram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/images/spring_mass_diagram.png
--------------------------------------------------------------------------------
/docs/images/stiffness_CDFs.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/images/stiffness_CDFs.pdf
--------------------------------------------------------------------------------
/docs/images/stiffness_CDFs.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/images/stiffness_CDFs.png
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | .. SROMPy documentation master file, created by
2 | sphinx-quickstart on Mon Mar 26 11:47:09 2018.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | Welcome to SROMPy's documentation!
7 | ==================================
8 |
9 | Contents:
10 |
11 | .. toctree::
12 | :maxdepth: 2
13 |
14 | intro
15 | example
16 | source_code
17 |
18 |
19 | Indices and tables
20 | ==================
21 |
22 | * :ref:`genindex`
23 | * :ref:`modindex`
24 | * :ref:`search`
25 |
26 |
--------------------------------------------------------------------------------
/docs/intro.rst:
--------------------------------------------------------------------------------
1 |
2 | Introduction
3 | =============
4 |
5 |
6 | Stochastic reduced order models with Python (SROMPy) is a software package developed to enable user-friendly utilization of the stochastic reduced order model (SROM) approach for uncertainty quantification. A SROM is a low dimensional, discrete approximation to a random quantity that enables efficient and non-intrusive stochastic computations. With SROMPy, a user can easily generate a SROM to approximate a random variable or vector described by several different types of probability distributions using the Python programming language. Once a SROM is constructed, the software also contains functionality to propagate uncertainty through a user-defined computational model to estimate statistics of a given quantity of interest.
7 |
--------------------------------------------------------------------------------
/docs/references/Emery_2016_Reliability_via_SROMs.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/references/Emery_2016_Reliability_via_SROMs.pdf
--------------------------------------------------------------------------------
/docs/references/SROMPy-NASA-TM-2018-219824.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/references/SROMPy-NASA-TM-2018-219824.pdf
--------------------------------------------------------------------------------
/docs/references/SROMs_for_random_vectors.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/references/SROMs_for_random_vectors.pdf
--------------------------------------------------------------------------------
/docs/references/comparison_paper_collocation_galerkin_sroms.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/references/comparison_paper_collocation_galerkin_sroms.pdf
--------------------------------------------------------------------------------
/docs/references/srom_local_approx_grigoriu.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/references/srom_local_approx_grigoriu.pdf
--------------------------------------------------------------------------------
/docs/source_code.rst:
--------------------------------------------------------------------------------
1 |
2 |
3 | .. _sourcecode-section:
4 |
5 | Source Code Documentation
6 | ==========================
7 |
8 | Documentation for the primary SROMPy classes.
9 |
10 | SROM Module Documentation
11 | -------------------------
12 |
13 | .. automodule:: SROMPy.srom
14 | .. autoclass:: SROM
15 | :members:
16 |
17 | .. autoclass:: SROMSurrogate
18 | :members:
19 |
20 | .. autoclass:: FiniteDifference
21 | :members:
22 |
23 | Target Random Quantity Documentation
24 | --------------------------------------------
25 |
26 | .. automodule:: SROMPy.target
27 | .. autoclass:: NormalRandomVariable
28 | :members:
29 | .. autoclass:: BetaRandomVariable
30 | :members:
31 | .. autoclass:: DiscreteRandomVector
32 | :members:
33 | .. autoclass:: GammaRandomVariable
34 | :members:
35 | .. autoclass:: UniformRandomVariable
36 | :members:
37 | .. autoclass:: AnalyticRandomVector
38 | :members:
39 | .. autoclass:: SampleRandomVector
40 | :members:
41 |
42 | Postprocessor Documentation
43 | ----------------------------
44 |
45 | .. automodule:: SROMPy.postprocess
46 | .. autoclass:: Postprocessor
47 | :members:
48 |
49 |
--------------------------------------------------------------------------------
/examples/basic_tests/normal_rv_srom.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/examples/basic_tests/normal_rv_srom.pdf
--------------------------------------------------------------------------------
/examples/basic_tests/normal_rv_srom.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/examples/basic_tests/normal_rv_srom.png
--------------------------------------------------------------------------------
/examples/basic_tests/normal_rv_srom.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | from SROMPy.postprocess import Postprocessor
17 | from SROMPy.srom import SROM
18 | from SROMPy.target import NormalRandomVariable
19 |
20 | # Initialize Normal random variable object to be modeled by SROM:
21 | normal = NormalRandomVariable(mean=3., std_dev=1.5)
22 |
23 | # Initialize SROM & optimize to model the normal random variable:
24 | srom = SROM(size=10, dim=1)
25 | srom.optimize(normal)
26 |
27 | # Compare the CDF of the SROM & target normal variable:
28 | post_processor = Postprocessor(srom, normal)
29 | post_processor.compare_cdfs()
30 |
31 |
--------------------------------------------------------------------------------
/examples/parallel_performance_tests/generate_chart_strong_scalability.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import pickle
3 | import os
4 |
5 | # Load performance data, which is a pickled dictionary.
6 | data_filename = os.path.join("data", "strong_scalability_data.txt")
7 |
8 | all_performance_data = {}
9 | if os.path.isfile(data_filename):
10 |
11 | print 'Loading previously saved data set for modification:'
12 |
13 | data_file = open(data_filename, 'r')
14 | all_performance_data = pickle.load(data_file)
15 | data_file.close()
16 |
17 | print all_performance_data
18 |
19 | else:
20 |
21 | print 'Chart data not found!'
22 | exit()
23 |
24 | # Generate the plots.
25 | fig, ax = plt.subplots(1)
26 |
27 | # Generate a line in the chart for each sample size.
28 | for num_samples in all_performance_data.keys():
29 |
30 | performance_data = all_performance_data[num_samples]
31 | baseline_time = performance_data[1]
32 |
33 | x_values = []
34 | actual_y_values = []
35 | cpu_num = 1
36 |
37 | while cpu_num in performance_data:
38 |
39 | x_values.append(cpu_num)
40 | actual_y_values.append(baseline_time / performance_data[cpu_num])
41 |
42 | cpu_num += 1
43 |
44 | plt.plot(x_values, actual_y_values, label=str(num_samples) + ' samples')
45 |
46 | plt.plot(x_values, x_values, 'r--', label='Ideal', linewidth=2)
47 |
48 | # Add labels, legend, and title.
49 | plt.xlabel('Number of CPUs')
50 | plt.ylabel('Speedup factor')
51 | plt.legend()
52 |
53 | fig.canvas.set_window_title("Strong Scalability ")
54 | plt.title("Speedup vs Number of CPUs")
55 |
56 | plt.show()
57 |
--------------------------------------------------------------------------------
/examples/parallel_performance_tests/generate_chart_weak_scalability.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 | import pickle
4 | import os
5 |
6 | # Load data. Should be a file with performance data for each number of CPUs.
7 | all_speedup_data = []
8 |
9 | print 'Loading performance data.'
10 |
11 | data_filename = os.path.join("data", "weak_scalability_data.txt")
12 | if os.path.isfile(data_filename):
13 |
14 | data_file = open(data_filename, 'r')
15 | performance_data = pickle.load(data_file)
16 | serial_performance = np.array(performance_data[1])
17 | data_file.close()
18 |
19 | min_samples = performance_data['min_samples']
20 | max_samples = performance_data['max_samples']
21 | samples_step = performance_data['samples_step']
22 |
23 | else:
24 |
25 | print 'Chart data not found!'
26 | exit()
27 |
28 | # Get parallel performance data for as many data files as are available.
29 | num_cpus = 2
30 | while num_cpus in performance_data:
31 |
32 | parallel_performance = np.array(performance_data[num_cpus])
33 | all_speedup_data.append(serial_performance / parallel_performance)
34 |
35 | num_cpus += 1
36 |
37 | print 'Found data for up to %s CPUs.' % str(num_cpus - 1)
38 |
39 | # Generate the plots.
40 | fig, ax = plt.subplots(1)
41 |
42 | x_values = np.arange(min_samples, max_samples, samples_step)
43 |
44 | for i, speedup_data in enumerate(all_speedup_data):
45 |
46 | label_text = str(i + 2) + ' CPUs'
47 | ax.plot(x_values, speedup_data, label=label_text)
48 |
49 | # Add labels, legend, and title.
50 | plt.xlabel('Number of Samples')
51 | plt.ylabel('Speedup factor')
52 | plt.legend()
53 | plt.ylim(0, 10) # May need adjustment to fit legend without overlapping data.
54 |
55 | fig.canvas.set_window_title("Weak Scalability")
56 | plt.title("Parallel Speedup Factor vs Number of Samples")
57 |
58 | plt.show()
59 |
--------------------------------------------------------------------------------
/examples/parallel_performance_tests/generate_data_strong_scalability.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import time
3 | import pickle
4 | from mpi4py import MPI
5 | import sys
6 |
7 | # TODO: FIND ALTERNATIVE TO THIS PYTHONPATH HACK
8 | import os
9 | import sys
10 |
11 | # PYTHONPATH is not found when running mpiexec, so inject it so that we can
12 | # load SROMPy modules...
13 | if 'PYTHONPATH' not in os.environ:
14 |
15 | base_path = os.path.abspath('.')
16 |
17 | sys.path.insert(0, base_path)
18 | sys.path.insert(0, os.path.join(base_path, 'SROMPy'))
19 |
20 | from SROMPy.srom import SROM
21 | from SROMPy.target import BetaRandomVariable
22 |
23 | # Get number of test samples from command line, or use default.
24 | num_test_samples = 60 # LCM max # CPUs or a multiple of that is recommended.
25 | if len(sys.argv) > 1:
26 | try:
27 | num_test_samples = int(sys.argv[1])
28 | except ValueError:
29 | print 'Argument must be a positive integer.'
30 | exit()
31 |
32 | # Get MPI information.
33 | comm = MPI.COMM_WORLD
34 |
35 | if comm.rank == 0:
36 | print 'Will compute using %s samples on %s CPU%s.' % (num_test_samples, comm.size, 's' if comm.size > 1 else '')
37 |
38 | # Load previously saved scalability data if available.
39 | data_filename = os.path.join("data", "strong_scalability_data.txt")
40 |
41 | if os.path.isfile(data_filename):
42 |
43 | if comm.rank == 0:
44 | print 'Loading previously saved data set for modification:'
45 |
46 | data_file = open(data_filename, 'r')
47 | performance_data = pickle.load(data_file)
48 | data_file.close()
49 |
50 | if comm.rank == 0:
51 | print performance_data
52 |
53 | else:
54 |
55 | if comm.rank == 0:
56 | print 'No previous performance data found. Creating new data set.'
57 | performance_data = {}
58 |
59 | # Random variable to optimize to.
60 | random_variable = BetaRandomVariable(alpha=3., beta=2., shift=1., scale=2.5)
61 |
62 | # performance data is two nested dictionaries.
63 | # top level key is number of samples
64 | # inner level has cpu number as keys with time data as values.
65 | #
66 | # ex: { 60: { 2: 5.2, 3: 1.8 } }
67 | #
68 | # In above example have two tests both with 60 samples;
69 | # one with 2 cpus and one with 3 cpus.
70 |
71 | if num_test_samples not in performance_data:
72 | performance_data[num_test_samples] = {}
73 |
74 | # Repeat performance data collection in order to smooth the chart lines.
75 | iteration_performance = []
76 | for i in xrange(10):
77 |
78 | input_srom = SROM(20, 1)
79 |
80 | t0 = time.time()
81 | input_srom.optimize(random_variable, num_test_samples=num_test_samples)
82 | iteration_performance.append(time.time() - t0)
83 |
84 | mean_performance = np.mean(iteration_performance)
85 |
86 | if comm.rank != 0:
87 | exit()
88 |
89 | performance_data[num_test_samples][comm.size] = mean_performance
90 |
91 | print '%s test samples across %s CPUs took %s seconds.' % (num_test_samples, comm.size, float(mean_performance))
92 |
93 | print 'Writing results to disk...'
94 | print performance_data
95 |
96 | if not os.path.isdir('data'):
97 | os.mkdir('data')
98 |
99 | data_file = open(data_filename, 'w')
100 | pickle.dump(performance_data, data_file)
101 | data_file.close()
102 |
--------------------------------------------------------------------------------
/examples/parallel_performance_tests/generate_data_weak_scalability.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import time
3 | import pickle
4 | from mpi4py import MPI
5 |
6 | # TODO: FIND ALTERNATIVE TO THIS PYTHONPATH HACK
7 | import os
8 | import sys
9 |
10 | # PYTHONPATH is not found when running mpiexec,
11 | # so inject it so that we can load SROMPy modules...
12 | if 'PYTHONPATH' not in os.environ:
13 | base_path = os.path.abspath('.')
14 | sys.path.insert(0, base_path)
15 | sys.path.insert(0, os.path.join(base_path, 'SROMPy'))
16 |
17 | from SROMPy.srom import SROM
18 | from SROMPy.target import BetaRandomVariable
19 |
20 | # Random variable to optimize to.
21 | random_variable = BetaRandomVariable(alpha=3., beta=2., shift=1., scale=2.5)
22 |
23 | # Run each SROM optimization 10 times to generate performance data.
24 | performance_data = []
25 |
26 | # Get MPI information.
27 | comm = MPI.COMM_WORLD
28 |
29 | # Load previously saved scalability data if available.
30 | data_filename = os.path.join("data", "weak_scalability_data.txt")
31 |
32 | if os.path.isfile(data_filename):
33 |
34 | if comm.rank == 0:
35 | print 'Loading previously saved data set for modification:'
36 |
37 | data_file = open(data_filename, 'r')
38 | performance_data = pickle.load(data_file)
39 | data_file.close()
40 |
41 | if comm.rank == 0:
42 | print performance_data
43 |
44 | else:
45 |
46 | if comm.rank == 0:
47 | print 'No previous performance data found. Creating new data set.'
48 |
49 | performance_data = {}
50 |
51 | if comm.rank == 0:
52 | print 'Performing computation with %s CPUs.' % comm.size
53 |
54 | min_samples = 6
55 | max_samples = 301
56 | samples_step = 30
57 |
58 | performance_data['min_samples'] = min_samples
59 | performance_data['max_samples'] = max_samples
60 | performance_data['samples_step'] = samples_step
61 |
62 | test_results = []
63 | for num_test_samples in xrange(min_samples, max_samples, samples_step):
64 |
65 | if comm.rank == 0:
66 | print 'Optimizing with %s test samples...' % num_test_samples
67 |
68 | # Repeat performance data collection in order to smooth the chart lines.
69 | iteration_performance = []
70 | for i in xrange(10):
71 |
72 | input_srom = SROM(20, 1)
73 |
74 | t0 = time.time()
75 | input_srom.optimize(random_variable, num_test_samples=num_test_samples)
76 | iteration_performance.append(time.time() - t0)
77 |
78 | # We only need to save performance data from one process because
79 | # they should be the same due to gather operation within optimize().
80 | if comm.rank == 0:
81 |
82 | mean_performance = np.mean(iteration_performance)
83 | test_results.append(mean_performance)
84 |
85 | if comm.rank != 0:
86 | exit()
87 |
88 | performance_data[comm.size] = test_results
89 |
90 | # Create data directory to store output if necessary.
91 | if not os.path.isdir('data'):
92 | os.mkdir('data')
93 |
94 | data_file = open(data_filename, 'w')
95 | pickle.dump(performance_data, data_file)
96 | data_file.close()
97 |
--------------------------------------------------------------------------------
/examples/phm18/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/examples/phm18/.DS_Store
--------------------------------------------------------------------------------
/examples/phm18/PHM18_Jwarner.pptx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/examples/phm18/PHM18_Jwarner.pptx
--------------------------------------------------------------------------------
/examples/phm18/README:
--------------------------------------------------------------------------------
1 | This readme file provides an overview of the source code and data provided in this directory that reproduces the results and figures in the PHM18 Conference Paper, "Rapid Uncertainty Quantification for High-Fidelity Prognostics Using SROMPy and Python" by J. E. Warner, P. E. Leser, and J. D. Hochhalter.
2 | The slides presented at the PHM18 conference are available in the file PHM18_Jwarner.pptx. The conference paper can be downloaded at:
3 | https://www.phmpapers.org/index.php/phmconf/article/download/551/phmc_18_551
4 |
5 | Two data directories provided: mc_data and srom_data, containing the sample data files for the Monte Carlo solution and data files needed for SROM solutions, respectively.
6 |
7 | #--------------------SROM Uncertainty Propagation Procedure--------------------
8 |
9 | The scripts that implement the SROM solution procedure are as follows:
10 | *Step 1 - generate_input_srom.py
11 | *Step 2 - run_model.py
12 | *Step 3 - generate_pwconstant_eol.py or generate_pwlinear_eol.py
13 |
14 | These three steps correspond to the three steps described in Section 2.1.3 of the conference paper.
15 |
16 | Notes:
17 | *Step 1 solves the SROM optimization problem which has inherent randomness due to numerical sampling, so the SROMs and results produced will vary slightly from those in the paper.
18 | *Step 2 is only a representative script and will not run. The true model used in this study depends on a commercial code and is therefore not included. However, the code reflects a common SROM workflow and can be modified to solve a new problem of interest. Also, the input/output data from the crack growth model are included in the mc_data directory.
19 |
20 | #--------------------Scripts for Reproducing PHM18 Results---------------------
21 |
22 | Scripts for producing Figures in paper:
23 | Figure 1 - normal_rv_srom.py
24 | *Note - due to randomness of the SROM optimization algorithm, the resulting
25 | plot will vary from the one shown in the paper when re-run.
26 | Figure 3 - plot_input_pdfs.py
27 | Figure 4 - compare_input_srom_CDFs.py
28 | Figure 5(a) - compare_pwconst_srom_eol_CDFs.py
29 | Figure 5(b) - compare_pwlin_srom_eol_CDFs.py
30 | Figure 6 - generate_input_srom.py
31 | *Note - due to randomness of the SROM optimization algorithm, the resulting
32 | plots will vary from those shown in the paper when re-run.
33 | Figure 7 - plot_pwconstant_eol_demo.py
34 |
35 | Script from the SROMPy demo in Section 3.3/Appendix of the paper:
36 | srompy_demo_script.py
37 |
--------------------------------------------------------------------------------
/examples/phm18/compare_input_srom_CDFs.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import os
17 | import numpy as np
18 | from collections import OrderedDict
19 |
20 | from SROMPy.target import SampleRandomVector
21 | from SROMPy.srom import SROM
22 | from SROMPy.postprocess import Postprocessor
23 |
24 | '''
25 | Compare SROMs for inputs - produce figure 3 in the paper
26 | '''
27 |
28 | # Target Monte Carlo input samples for comparison.
29 | target_samples = "mc_data/input_samples_MC.txt"
30 |
31 | # SElect 3 SROM sizes.
32 | srom_sizes = [5, 10, 20]
33 | srom_dir = "srom_data"
34 |
35 | # Plotting specs:
36 | variables = [r'$y_{0}$', r'log$C$', r'$n$']
37 | cdf_y_label = True # Label y axis as "CDF"
38 | plot_dir = "plots"
39 | plot_suffix = "SROM_input_CDF_m"
40 | for m in srom_sizes:
41 | plot_suffix += "_" + str(m)
42 |
43 | # x_tick labels for each variable for clarity.
44 | y0_ticks = ['', '0.245', '', '0.255', '', '0.265', '', '0.275']
45 | log_c_ticks = ['', '-8.8', '', '-8.4', '', '-8.0', '', '-7.6']
46 | n_ticks = ['1.0', '', '1.5', '', '2.0', '', '2.5', '', '3.0']
47 | x_ticks = [y0_ticks, log_c_ticks, n_ticks]
48 |
49 | # Load / initialize target random variable from samples:
50 | samples = np.genfromtxt(target_samples)
51 | target = SampleRandomVector(samples)
52 |
53 | # Set x limits for each variable based on target:
54 | x_limits = []
55 | for i in range(target._dim):
56 | limits = [np.min(samples[:, i]), np.max(samples[:, i])]
57 | x_limits.append(limits)
58 |
59 | # Build up srom_size-to-SROM object map for plotting routine.
60 | sroms = OrderedDict()
61 |
62 | for srom_size in srom_sizes:
63 |
64 | # Generate SROM from file:
65 | srom = SROM(srom_size, target._dim)
66 | srom_filename = "srom_m" + str(srom_size) + ".txt"
67 | srom_filename = os.path.join(srom_dir, srom_filename)
68 | srom.load_params(srom_filename)
69 | sroms[srom_size] = srom
70 |
71 | # Font size specs & plotting.
72 | axis_font_size = 25
73 | legend_font_size = 20
74 | Postprocessor.compare_srom_cdfs(sroms, target, plot_dir="plots",
75 | plot_suffix=plot_suffix,
76 | variable_names=variables,
77 | x_limits=x_limits,
78 | x_ticks=x_ticks,
79 | cdf_y_label=cdf_y_label,
80 | axis_font_size=axis_font_size,
81 | legend_font_size=legend_font_size)
82 |
83 |
--------------------------------------------------------------------------------
/examples/phm18/compare_pwconst_srom_eol_CDFs.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import os
17 | import numpy as np
18 | from collections import OrderedDict
19 |
20 | from SROMPy.target import SampleRandomVector
21 | from SROMPy.srom import SROM, SROMSurrogate
22 | from SROMPy.postprocess import Postprocessor
23 |
24 | '''
25 | Compare piecewise constant SROM approximations to the EOL for m=5,10,20
26 | Produces Figure 5(a) in the paper
27 | '''
28 |
29 | # Target Monte Carlo input samples for comparison.
30 | target_samples = "mc_data/eol_samples_MC.txt"
31 |
32 | # SElect 3 SROM sizes.
33 | srom_sizes = [5, 10, 20]
34 | srom_dir = "srom_data"
35 |
36 | # Plotting specs:
37 | variables = [r'EOL (Cycles)']
38 | x_limits = [[1.0e6, 2.0e6]]
39 | y_limits = [[-0.01, 1.1]]
40 | x_ticks = [[r'$1.0 \times 10^6$', '', r'$1.4 \times 10^6$', '',
41 | r'$1.8 \times 10^6$','']]
42 | x_axis_padding = 5
43 | axis_font_size = 24
44 | label_font_size = 20
45 | legend_font_size = 20
46 | show_plot = False
47 | cdf_y_label = True # Label y axis as "CDF".
48 | plot_dir = "plots"
49 | plot_suffix = "SROM_pwconst_eol_CDF_m"
50 | for m in srom_sizes:
51 | plot_suffix += "_" + str(m)
52 |
53 | # Load / initialize target random variable from samples:
54 | samples = np.genfromtxt(target_samples)
55 | target = SampleRandomVector(samples)
56 |
57 | # Build up srom_size-to-SROM object map for plotting routine
58 | sroms = OrderedDict()
59 |
60 | for srom_size in srom_sizes:
61 |
62 | # Generate input SROM from file:
63 | srom = SROM(srom_size, target._dim)
64 | srom_filename = "srom_m" + str(srom_size) + ".txt"
65 | srom_filename = os.path.join(srom_dir, srom_filename)
66 | srom.load_params(srom_filename)
67 |
68 | # Generate SROM surrogate for output from EOLs & input srom:
69 | end_of_life_filename = "srom_eol_m" + str(srom_size) + ".txt"
70 | end_of_life_filename = os.path.join(srom_dir, end_of_life_filename)
71 | end_of_life_data = np.genfromtxt(end_of_life_filename)
72 |
73 | sroms[srom_size] = SROMSurrogate(srom, end_of_life_data)
74 |
75 | Postprocessor.compare_srom_cdfs(sroms, target, plot_dir="plots",
76 | plot_suffix=plot_suffix,
77 | variable_names=variables, y_limits=y_limits,
78 | x_ticks=x_ticks, cdf_y_label=True,
79 | x_axis_padding=x_axis_padding,
80 | axis_font_size=axis_font_size,
81 | label_font_size=label_font_size,
82 | legend_font_size=legend_font_size)
83 |
84 |
--------------------------------------------------------------------------------
/examples/phm18/compare_pwlin_srom_eol_CDFs.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import os
17 | import numpy as np
18 | from collections import OrderedDict
19 |
20 | from SROMPy.target import SampleRandomVector
21 | from SROMPy.srom import SROM, SROMSurrogate
22 | from SROMPy.postprocess import Postprocessor
23 |
24 | '''
25 | Compare piecewise linear SROM approximations to the EOL for m=5,10,20
26 | Produces Figure 5(b) in the paper
27 | '''
28 |
29 | # Target Monte Carlo input samples for comparison.
30 | target_samples = "mc_data/eol_samples_MC.txt"
31 |
32 | # SElect 3 SROM sizes.
33 | srom_sizes = [5, 10, 20]
34 | srom_dir = "srom_data"
35 |
36 | # Plotting specs:
37 | variables = [r'EOL (Cycles)']
38 | x_limits = [[1.0e6, 2.0e6]]
39 | y_limits = [[-0.01, 1.1]]
40 | x_ticks = [[r'$1.0 \times 10^6$', '', r'$1.4 \times 10^6$', '',
41 | r'$1.8 \times 10^6$','']]
42 |
43 | x_axis_padding = 5
44 | axis_font_size = 24
45 | label_font_size = 20
46 | legend_font_size = 20
47 | cdf_y_label = True # Label y axis as "CDF".
48 | plot_dir = "plots"
49 | plot_suffix = "SROM_pwlin_eol_CDF_m"
50 | for m in srom_sizes:
51 | plot_suffix += "_" + str(m)
52 |
53 | # Load / initialize target random variable from samples:
54 | samples = np.genfromtxt(target_samples)
55 | target = SampleRandomVector(samples)
56 |
57 | # Build up srom_size-to-SROM object map for plotting routine
58 | sroms = OrderedDict()
59 |
60 | for srom_size in srom_sizes:
61 |
62 | # Get EOL SROM Surrogate samples to make SampleRV representation of CDF
63 | end_of_life_sample_filename = "srom_eol_samples_m" + str(srom_size) + ".txt"
64 | end_of_life_sample_filename = os.path.join(srom_dir, end_of_life_sample_filename)
65 | end_of_life_samples = np.genfromtxt(end_of_life_sample_filename)
66 |
67 | sroms[srom_size] = SampleRandomVector(end_of_life_samples)
68 |
69 | Postprocessor.compare_srom_cdfs(sroms, target, plot_dir="plots",
70 | plot_suffix=plot_suffix,
71 | variable_names=variables, y_limits=y_limits,
72 | x_ticks=x_ticks, cdf_y_label=True,
73 | x_axis_padding=x_axis_padding,
74 | axis_font_size=axis_font_size,
75 | label_font_size=label_font_size,
76 | legend_font_size=legend_font_size)
77 |
78 |
--------------------------------------------------------------------------------
/examples/phm18/generate_input_srom.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 |
18 | from SROMPy.postprocess import Postprocessor
19 | from SROMPy.srom import SROM
20 | from SROMPy.target import SampleRandomVector
21 |
22 | '''
23 | Generate SROM to model input distribution (samples)
24 | '''
25 |
26 | # Specify input/output files and SROM optimization parameters.
27 | dim = 3
28 | srom_size = 20
29 | samples_file = "mc_data/input_samples_MC.txt"
30 | outfile = "srom_data/srom_m" + str(srom_size) + ".txt"
31 |
32 | # Define target random variable from samples
33 | mc_samples = np.genfromtxt(samples_file)
34 | target = SampleRandomVector(mc_samples)
35 |
36 | # Define SROM, determine optimal parameters, store parameters
37 | srom = SROM(srom_size, dim)
38 | srom.optimize(target, weights=[1, 1, 1], error="SSE", num_test_samples=100)
39 |
40 | # NOTE - commented out to not overwrite paper data files:
41 | # srom.save_params(outfile)
42 |
43 | # Check out the CDFs.
44 | pp = Postprocessor(srom, target)
45 | pp.compare_cdfs(variable_names=[r'$y_{0}$', r'log$C$', r'$n$'])
46 |
47 |
--------------------------------------------------------------------------------
/examples/phm18/generate_pwconstant_eol.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 |
18 | from SROMPy.postprocess import Postprocessor
19 | from SROMPy.srom import SROM
20 | from SROMPy.target import SampleRandomVector
21 |
22 | '''
23 | Script to generate piecewise constant SROM approximation to EOL and compare it
24 | with the Monte Carlo solution - step 3. Uses the stored EOL model outputs
25 | from step 2 and the stored input SROM from step 1.
26 | '''
27 |
28 | monte_carlo_end_of_life_filename = "mc_data/eol_samples_MC.txt"
29 |
30 | srom_size = 20
31 |
32 | srom_end_of_life_filename = "srom_data/srom_eol_m" + str(srom_size) + ".txt"
33 | srom_input_file = "srom_data/srom_m" + str(srom_size) + ".txt"
34 |
35 | # Get MC EOL samples.
36 | monte_carlo_end_of_life_data = np.genfromtxt(monte_carlo_end_of_life_filename)
37 |
38 | # Get SROM EOL samples & probabilities from input srom.
39 | srom_end_of_life_data = np.genfromtxt(srom_end_of_life_filename)
40 |
41 | # Probabilities in last column.
42 | srom_probabilities = np.genfromtxt(srom_input_file)[:, -1]
43 |
44 | # Make MC random variable & SROM to compare.
45 | end_of_life_srom = SROM(srom_size, dim=1)
46 | end_of_life_srom.set_params(srom_end_of_life_data, srom_probabilities)
47 | end_of_life_mc = SampleRandomVector(monte_carlo_end_of_life_data)
48 |
49 | pp = Postprocessor(end_of_life_srom, end_of_life_mc)
50 | pp.compare_cdfs(variable_names=["EOL"])
51 |
--------------------------------------------------------------------------------
/examples/phm18/generate_pwlinear_eol.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 |
18 | from SROMPy.postprocess import Postprocessor
19 | from SROMPy.srom import SROM, SROMSurrogate, FiniteDifference as FD
20 | from SROMPy.target import SampleRandomVector
21 |
22 | '''
23 | Script to generate piecewise linear SROM approximation to EOL and compare it
24 | with the Monte Carlo solution - step 3. Uses the stored EOL model outputs
25 | from step 2 and the stored input SROM from step 1. In LINEAR case, need to
26 | estimate gradients with finite difference. To do so, the model was run with
27 | perturbed values of the inputs and the resulting EOLs were stored in the files
28 | named "srom_fd_eol_m<>.txt".
29 | '''
30 |
31 | # Monte Carlo sample data:
32 | monte_carlo_end_of_life_sample_filename = "mc_data/eol_samples_MC.txt"
33 | monte_carlo_end_of_life_input_filename = "mc_data/input_samples_MC.txt"
34 |
35 | dim = 3
36 | srom_size = 20
37 |
38 | # Data files for EOL samples, EOL finite difference samples, and SROM inputs.
39 | srom_end_of_life_filename = "srom_data/srom_eol_m" + \
40 | str(srom_size) + ".txt"
41 |
42 | srom_fd_end_of_life_filename = "srom_data/srom_fd_eol_m" + \
43 | str(srom_size) + ".txt"
44 |
45 | srom_input_file = "srom_data/srom_m" + str(srom_size) + ".txt"
46 |
47 | # Get MC input/EOL samples.
48 | monte_carlo_inputs = np.genfromtxt(monte_carlo_end_of_life_input_filename)
49 | monte_carlo_end_of_life_data = \
50 | np.genfromtxt(monte_carlo_end_of_life_sample_filename)
51 |
52 | # Get SROM EOL samples, FD samples and input SROM from file.
53 | srom_end_of_life_data = np.genfromtxt(srom_end_of_life_filename)
54 | srom_fd_end_of_life_data = np.genfromtxt(srom_fd_end_of_life_filename)
55 | input_srom = SROM(srom_size, dim)
56 | input_srom.load_params(srom_input_file)
57 |
58 | # Get FD step sizes from file (the same for all samples, just pull the first)
59 | # Step sizes chosen as approximately 2% of the median sample value of inputs
60 | step_sizes = [0.0065, 0.083, 0.025]
61 |
62 | # Calculate gradient from FiniteDifference class:
63 | gradient = FD.compute_gradient(srom_end_of_life_data, srom_fd_end_of_life_data,
64 | step_sizes)
65 |
66 | # Create SROM surrogate, sample, and create random variable solution.
67 | surrogate_PWL = SROMSurrogate(input_srom, srom_end_of_life_data, gradient)
68 | srom_end_of_life_samples = surrogate_PWL.sample(monte_carlo_inputs)
69 | solution_PWL = SampleRandomVector(srom_end_of_life_samples)
70 |
71 | # Store EOL samples for plotting later:
72 | end_of_life_filename = "srom_data/srom_eol_samples_m" + str(srom_size) + ".txt"
73 | # np.savetxt(end_of_life_filename, srom_eol_samples)
74 | # NOTE - avoid overwriting paper data
75 |
76 | # Make MC random variable solution.
77 | end_of_life_monte_carlo = SampleRandomVector(monte_carlo_end_of_life_data)
78 |
79 | # Compare solutions.
80 | pp = Postprocessor(solution_PWL, end_of_life_monte_carlo)
81 | pp.compare_cdfs()
82 |
--------------------------------------------------------------------------------
/examples/phm18/normal_rv_srom.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | from SROMPy.postprocess import Postprocessor
17 | from SROMPy.srom import SROM
18 | from SROMPy.target import NormalRandomVariable
19 |
20 | # Initialize Normal random variable object to be modeled by SROM:
21 | normal = NormalRandomVariable(mean=3., std_dev=1.5)
22 |
23 | # Initialize SROM & optimize to model the normal random variable:
24 | srom = SROM(size=10, dim=1)
25 | srom.optimize(normal)
26 |
27 | # Compare the CDF of the SROM & target normal variable:
28 | pp = Postprocessor(srom, normal)
29 | pp.compare_cdfs()
30 |
31 |
--------------------------------------------------------------------------------
/examples/phm18/phm_srompy_demo_ex.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 |
18 | #from model import Model (assume this exists)
19 | from SROMPy.postprocess import Postprocessor
20 | from SROMPy.srom import SROM, SROMSurrogate
21 | from SROMPy.target import SampleRandomVector
22 |
23 | '''
24 | Generate SROM to model input distribution (samples)
25 | '''
26 |
27 | # Specify input/output files and SROM optimization parameters.
28 | dim = 3
29 | srom_size = 20
30 | monte_carlo_end_of_life_input_filename = "mc_data/input_samples_MC.txt"
31 | monte_carlo_end_of_life_sample_filename = "mc_data/eol_samples_MC.txt"
32 |
33 | # Define target random variable from samples.
34 | monte_carlo_samples = np.genfromtxt(monte_carlo_end_of_life_input_filename)
35 | target = SampleRandomVector(monte_carlo_samples)
36 |
37 | # Define SROM, determine optimal parameters, store parameters.
38 | input_srom = SROM(srom_size, dim)
39 | input_srom.optimize(target, weights=[1, 1, 1], error="SSE")
40 |
41 | # Compare the CDFs.
42 | pp = Postprocessor(input_srom, target)
43 | pp.compare_cdfs(save_figure=False)
44 |
45 | # Run the model for each input SROM sample:
46 | srom_end_of_life_data = np.zeros(srom_size)
47 | (srom_samples, srom_probabilities) = input_srom.get_params()
48 | for i, sample in enumerate(srom_samples):
49 | srom_end_of_life_data[i] = model.evaluate(sample)
50 |
51 | # Generate SROM surrogate for the output.
52 | eol_srom = SROMSurrogate(input_srom, srom_end_of_life_data)
53 |
54 | # Make random variable with MC eol solution.
55 | monte_carlo_eols = np.genfromtxt(monte_carlo_end_of_life_sample_filename)
56 | eol_mc = SampleRandomVector(monte_carlo_eols)
57 |
58 | # Compare final EOL solutions SROM vs MC:
59 | pp = Postprocessor(eol_srom, eol_mc)
60 | pp.compare_cdfs()
61 |
62 |
--------------------------------------------------------------------------------
/examples/phm18/plot_input_histograms.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 | import scipy
18 | import scipy.interpolate as interp
19 | import matplotlib.pyplot as plt
20 | from matplotlib.patches import Rectangle
21 | import scipy.stats as st
22 |
23 |
24 | title_font = {'fontname': 'Arial', 'size': 22, 'weight': 'bold',
25 | 'verticalalignment': 'bottom'}
26 | axis_font = {'fontname': 'Arial', 'size': 30, 'weight': 'normal'}
27 | lines = ['--', '-', ':', '-.']
28 | colors = ['r', 'g', 'b', 'k']
29 |
30 | label_font = 'Arial'
31 | label_size = 26
32 | legend_font = 16.5
33 | line_width = 8
34 |
35 | sample_file = "mc_data/input_samples_MC.txt"
36 | samples = np.genfromtxt(sample_file)
37 | n_samples = samples[:, 2]
38 | y_samples = samples[:, 0]
39 | c_samples = samples[:, 1]
40 |
41 | n_limits = [np.min(n_samples), np.max(n_samples)]
42 | y_limits = [np.min(y_samples), np.max(y_samples)]
43 | c_limits = [np.min(c_samples), np.max(c_samples)]
44 |
45 |
46 | n_bins = 20
47 | y_bins = 20
48 | c_bins = 20
49 |
50 | # Plot n:
51 |
52 | fig = plt.figure()
53 | ax = plt.subplot()
54 |
55 | plt.hist(n_samples, color='cornflowerblue', ec='black')
56 |
57 | for label in (ax.get_xticklabels() + ax.get_yticklabels()):
58 | label.set_fontname(label_font)
59 | label.set_fontsize(label_size)
60 | plt.xlabel(r'$n$', **axis_font)
61 | plt.ylabel("Frequency", **axis_font)
62 | for label in ax.xaxis.get_ticklabels()[0::2]:
63 | label.set_visible(False)
64 | plt.tight_layout()
65 | plt.savefig("plots/n_hist.pdf")
66 | plt.show()
67 |
68 | # Plot y0:
69 | fig = plt.figure()
70 | ax = plt.subplot()
71 |
72 | plt.hist(y_samples, color='cornflowerblue', ec='black')
73 |
74 | for label in (ax.get_xticklabels() + ax.get_yticklabels()):
75 | label.set_fontname(label_font)
76 | label.set_fontsize(label_size)
77 | plt.xlabel(r'$y_0$', **axis_font)
78 | plt.ylabel("Frequency", **axis_font)
79 | for label in ax.xaxis.get_ticklabels()[1::2]:
80 | label.set_visible(False)
81 | plt.tight_layout()
82 | plt.savefig("plots/y_hist.pdf")
83 | plt.show()
84 |
85 |
86 | # Plot C
87 | fig = plt.figure()
88 | ax = plt.subplot()
89 |
90 | plt.hist(c_samples, color='cornflowerblue', ec='black')
91 |
92 | for label in (ax.get_xticklabels() + ax.get_yticklabels()):
93 | label.set_fontname(label_font)
94 | label.set_fontsize(label_size)
95 | plt.xlabel(r'log$C$', **axis_font)
96 | plt.ylabel("Frequency", **axis_font)
97 | for label in ax.xaxis.get_ticklabels()[1::2]:
98 | label.set_visible(False)
99 | plt.tight_layout()
100 | plt.savefig("plots/c_hist.pdf")
101 | plt.show()
102 |
--------------------------------------------------------------------------------
/examples/phm18/plot_pwconstant_eol_demo.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 |
18 | from SROMPy.postprocess import Postprocessor
19 | from SROMPy.srom import SROM
20 | from SROMPy.target import SampleRandomVector
21 |
22 | '''
23 | Ex3 - unimodal 3D
24 | Script to generate PW constant SROM approximation to EOL and compare it with the
25 | monte carlo solution (w/ surrogate model)
26 | '''
27 |
28 | mc_eol_file = "mc_data/eol_samples_MC.txt"
29 |
30 | srom_size = 20
31 |
32 | srom_eol_file = "srom_data/srom_eol_m" + str(srom_size) + ".txt"
33 | srom_input_file = "srom_data/srom_m" + str(srom_size) + ".txt"
34 |
35 | # Get MC EOL samples.
36 | MC_eols = np.genfromtxt(mc_eol_file)
37 |
38 | # Get SROM EOL samples & probabilities from input srom.
39 | srom_end_of_life_data = np.genfromtxt(srom_eol_file)
40 |
41 | # Probabilities in last column.
42 | srom_probabilities = np.genfromtxt(srom_input_file)[:, -1]
43 |
44 | # Make MC random variable & SROM to compare.
45 | end_of_life_srom = SROM(srom_size, dim=1)
46 | end_of_life_srom.set_params(srom_end_of_life_data, srom_probabilities)
47 | end_of_life_monte_carlo = SampleRandomVector(MC_eols)
48 |
49 | pp = Postprocessor(end_of_life_srom, end_of_life_monte_carlo)
50 | pp.compare_cdfs(variable_names=["EOL"])
51 |
52 |
--------------------------------------------------------------------------------
/examples/phm18/plots/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/examples/phm18/plots/.DS_Store
--------------------------------------------------------------------------------
/examples/phm18/run_model.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 |
18 | from SROMPy.srom import SROM
19 |
20 | from Model import CrackGrowthModel
21 |
22 | '''
23 | Run computational model for each input SROM sample - step 2
24 | NOTE - this script will not run, Model class is not provided. But this
25 | script is representative of a common SROM workflow.
26 |
27 | First, we load the SROM parameters that were generated in step 1, then we
28 | get the samples for that SROM and evaluate the crack growth model for each one,
29 | and store the outputs (EOL) from the model.
30 | '''
31 |
32 | # Initialize crack growth model (not provided).
33 | model = CrackGrowthModel()
34 |
35 | dim = 3
36 | srom_size = 20
37 |
38 | srom_filename = "srom_data/srom_m" + str(srom_size) + ".txt"
39 | srom_end_of_life_filename = "srom_data/srom_eol_m" + str(srom_size) + ".txt"
40 |
41 | # Initialize SROM and load parameters from file.
42 | srom = SROM(srom_size, dim)
43 | srom.load_params(srom_filename)
44 |
45 | # Evaluate the crack growth model for each SROM input sample.
46 | srom_outputs = np.zeros(srom_size)
47 | (srom_samples, srom_probabilities) = srom.get_params()
48 |
49 | for i, srom_sample in enumerate(srom_samples):
50 | srom_outputs[i] = model.evaluate(srom_sample)
51 |
52 | # Save EOL outputs for step 3:
53 | np.savetxt(srom_end_of_life_filename, srom_outputs)
54 |
--------------------------------------------------------------------------------
/examples/phm18/srom_data/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/examples/phm18/srom_data/.DS_Store
--------------------------------------------------------------------------------
/examples/phm18/srom_data/srom_eol_m10.txt:
--------------------------------------------------------------------------------
1 | 1.668915000000000000e+06
2 | 1.221072000000000000e+06
3 | 1.272231000000000000e+06
4 | 1.342337000000000000e+06
5 | 1.427819000000000000e+06
6 | 1.159506000000000000e+06
7 | 1.160239000000000000e+06
8 | 1.069957000000000000e+06
9 | 1.077028000000000000e+06
10 | 1.043429000000000000e+06
11 |
--------------------------------------------------------------------------------
/examples/phm18/srom_data/srom_eol_m20.txt:
--------------------------------------------------------------------------------
1 | 1.198987000000000000e+06
2 | 1.433067000000000000e+06
3 | 1.560759000000000000e+06
4 | 1.540986000000000000e+06
5 | 1.293223000000000000e+06
6 | 1.070235000000000000e+06
7 | 1.065424000000000000e+06
8 | 1.086934000000000000e+06
9 | 1.319736000000000000e+06
10 | 1.293930000000000000e+06
11 | 1.109348000000000000e+06
12 | 1.366202000000000000e+06
13 | 1.286186000000000000e+06
14 | 1.802757000000000000e+06
15 | 1.263653000000000000e+06
16 | 1.312279000000000000e+06
17 | 1.447179000000000000e+06
18 | 1.155651000000000000e+06
19 | 1.277218000000000000e+06
20 | 1.566580000000000000e+06
21 |
--------------------------------------------------------------------------------
/examples/phm18/srom_data/srom_eol_m5.txt:
--------------------------------------------------------------------------------
1 | 1.441231000000000000e+06
2 | 1.264512000000000000e+06
3 | 1.162957000000000000e+06
4 | 1.791496000000000000e+06
5 | 1.585264000000000000e+06
6 |
--------------------------------------------------------------------------------
/examples/phm18/srom_data/srom_fd_eol_m10.txt:
--------------------------------------------------------------------------------
1 | # FD_EOLs
2 | 1.685776000000000000e+06 1.392657000000000000e+06 1.603223000000000000e+06
3 | 1.229046000000000000e+06 1.015348000000000000e+06 1.173899000000000000e+06
4 | 1.279537000000000000e+06 1.056985000000000000e+06 1.221103000000000000e+06
5 | 1.345136000000000000e+06 1.111584000000000000e+06 1.283262000000000000e+06
6 | 1.438578000000000000e+06 1.188265000000000000e+06 1.370311000000000000e+06
7 | 1.162105000000000000e+06 9.602190000000000000e+05 1.110887000000000000e+06
8 | 1.168219000000000000e+06 9.652450000000000000e+05 1.116394000000000000e+06
9 | 1.076657000000000000e+06 8.894020000000000000e+05 1.030448000000000000e+06
10 | 1.080735000000000000e+06 8.927480000000000000e+05 1.033877000000000000e+06
11 | 1.051522000000000000e+06 8.685630000000000000e+05 1.007057000000000000e+06
12 |
--------------------------------------------------------------------------------
/examples/phm18/srom_data/srom_fd_eol_m20.txt:
--------------------------------------------------------------------------------
1 | # FD_EOLs
2 | 1.206035000000000000e+06 9.960940000000000000e+05 1.151921000000000000e+06
3 | 1.439871000000000000e+06 1.189632000000000000e+06 1.371858000000000000e+06
4 | 1.571855000000000000e+06 1.298368000000000000e+06 1.496758000000000000e+06
5 | 1.549718000000000000e+06 1.280243000000000000e+06 1.475113000000000000e+06
6 | 1.299861000000000000e+06 1.073490000000000000e+06 1.240051000000000000e+06
7 | 1.085270000000000000e+06 8.966170000000000000e+05 1.038839000000000000e+06
8 | 1.071754000000000000e+06 8.854800000000000000e+05 1.025825000000000000e+06
9 | 1.095136000000000000e+06 9.047680000000000000e+05 1.047821000000000000e+06
10 | 1.325390000000000000e+06 1.094993000000000000e+06 1.263440000000000000e+06
11 | 1.306740000000000000e+06 1.079438000000000000e+06 1.246135000000000000e+06
12 | 1.112695000000000000e+06 9.192120000000000000e+05 1.064170000000000000e+06
13 | 1.370947000000000000e+06 1.132572000000000000e+06 1.307360000000000000e+06
14 | 1.299975000000000000e+06 1.073867000000000000e+06 1.240065000000000000e+06
15 | 1.820802000000000000e+06 1.504930000000000000e+06 1.729921000000000000e+06
16 | 1.274615000000000000e+06 1.052561000000000000e+06 1.216199000000000000e+06
17 | 1.321962000000000000e+06 1.092083000000000000e+06 1.261070000000000000e+06
18 | 1.462961000000000000e+06 1.208483000000000000e+06 1.393927000000000000e+06
19 | 1.161507000000000000e+06 9.595660000000000000e+05 1.110802000000000000e+06
20 | 1.280893000000000000e+06 1.057017000000000000e+06 1.222036000000000000e+06
21 | 1.590593000000000000e+06 1.313994000000000000e+06 1.513804000000000000e+06
22 |
--------------------------------------------------------------------------------
/examples/phm18/srom_data/srom_fd_eol_m5.txt:
--------------------------------------------------------------------------------
1 | # FD_EOLs
2 | 1.453816000000000000e+06 1.201002000000000000e+06 1.384336000000000000e+06
3 | 1.272520000000000000e+06 1.050988000000000000e+06 1.214723000000000000e+06
4 | 1.168367000000000000e+06 9.652410000000000000e+05 1.116326000000000000e+06
5 | 1.805105000000000000e+06 1.491410000000000000e+06 1.715165000000000000e+06
6 | 1.592068000000000000e+06 1.315094000000000000e+06 1.515578000000000000e+06
7 |
--------------------------------------------------------------------------------
/examples/phm18/srom_data/srom_m10.txt:
--------------------------------------------------------------------------------
1 | 2.568821665185548886e-01 -7.765783588984234598e+00 1.536040254375189207e+00 4.217279388739028634e-02
2 | 2.592131228928665210e-01 -8.399826430271321698e+00 2.460354965265195037e+00 1.796965352333590449e-01
3 | 2.533544235095424590e-01 -8.280230908187739658e+00 2.287523781974549753e+00 7.122919879976159774e-02
4 | 2.615814043153491530e-01 -8.163994724565393213e+00 2.122538921119849764e+00 2.604663669971343243e-01
5 | 2.627591734872008478e-01 -7.975386527300311279e+00 1.862414707764594057e+00 1.290702311710882066e-01
6 | 2.573338328007236386e-01 -8.468288246248489415e+00 2.575575151797061313e+00 7.147316583685428548e-02
7 | 2.648473269292197507e-01 -8.450959667707618195e+00 2.555336500890772466e+00 1.663664564210535490e-01
8 | 2.627026356976246979e-01 -8.752989194626110248e+00 2.988548060137862894e+00 1.772623041935519547e-02
9 | 2.563332245602912285e-01 -8.652914673761520348e+00 2.852261502424745299e+00 5.764606167901468320e-02
10 | 2.694921051896355668e-01 -8.866748604591299099e+00 3.158211572732896766e+00 4.152959554988873772e-03
11 |
--------------------------------------------------------------------------------
/examples/phm18/srom_data/srom_m20.txt:
--------------------------------------------------------------------------------
1 | 2.598002305651649357e-01 -8.400554233786786895e+00 2.471616414956669949e+00 3.006222522771030969e-01
2 | 2.492418029734114471e-01 -7.992133820934541610e+00 1.876445455701280185e+00 1.257635340644285525e-02
3 | 2.590785887583300084e-01 -7.958558234503473550e+00 1.795448696271744637e+00 3.542638147729246928e-02
4 | 2.583453948348154450e-01 -7.880015651083062345e+00 1.709781048080719845e+00 1.228390132801792517e-02
5 | 2.592099030860439135e-01 -8.201205286427205365e+00 2.184091421701571001e+00 1.243318370418408821e-16
6 | 2.717545602742327815e-01 -8.752604241050704559e+00 2.993824617919186526e+00 7.820534368607971049e-03
7 | 2.622890109278329662e-01 -8.767509067761896091e+00 3.010013740684101879e+00 1.331442564813357932e-02
8 | 2.673252123178272432e-01 -8.672087784550358336e+00 2.876524965911357423e+00 2.865873509182802203e-02
9 | 2.554572583040783940e-01 -8.191016460032193081e+00 2.160160296169512772e+00 2.642081156889321963e-02
10 | 2.665764734167221928e-01 -8.151267270779431584e+00 2.125832669044352308e+00 5.797985466590560577e-02
11 | 2.580084533415294978e-01 -8.610913745069714409e+00 2.782255277543388861e+00 7.166828045520778900e-02
12 | 2.561370790761392513e-01 -8.130859061472724747e+00 2.069466599873532431e+00 5.689798132824054611e-02
13 | 2.673784944525706142e-01 -8.186910203656626805e+00 2.172839556473091349e+00 2.131958612253247523e-02
14 | 2.574661809310814786e-01 -7.565491078718604712e+00 1.272246670289759463e+00 8.699706938575543433e-03
15 | 2.641791925923542284e-01 -8.230230370092160186e+00 2.233656802686045051e+00 1.812206498479612127e-01
16 | 2.613450494567907678e-01 -8.200052757218120547e+00 2.175514198767107388e+00 1.735692924452943153e-02
17 | 2.677699128243509197e-01 -8.027054050894870230e+00 1.918821451177603610e+00 7.194017578237760224e-02
18 | 2.581411215436096307e-01 -8.609495611826002204e+00 2.756184690497581080e+00 6.748822384895197118e-03
19 | 2.521500348180324425e-01 -8.250642485487089672e+00 2.250199057802261038e+00 2.155127204343965097e-02
20 | 2.544051575399174370e-01 -7.880743691874196877e+00 1.700867287807144468e+00 4.749334602001581418e-02
21 |
--------------------------------------------------------------------------------
/examples/phm18/srom_data/srom_m5.txt:
--------------------------------------------------------------------------------
1 | 2.600471901192854540e-01 -7.941184533891902930e+00 1.815530019890077673e+00 1.114464370871669219e-01
2 | 2.621102963796680396e-01 -8.316348654153211228e+00 2.339115428858288492e+00 5.458234685603942093e-01
3 | 2.575466254924950738e-01 -8.480581454503420602e+00 2.588531953935919727e+00 2.715666545168916035e-01
4 | 2.574035507503111275e-01 -7.638208899806222973e+00 1.357197810856806353e+00 1.511436709503886228e-02
5 | 2.528131647894858447e-01 -7.925014827806417195e+00 1.747183906971978562e+00 5.604907274050837523e-02
6 |
--------------------------------------------------------------------------------
/examples/phm18/srompy_demo_script.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy
17 | from os import path
18 | from SROMPy.postprocess import Postprocessor
19 | from SROMPy.srom import SROM, SROMSurrogate
20 | from SROMPy.target import SampleRandomVector
21 |
22 | # Define target random vector from samples.
23 | monte_carlo_input_samples_filename = path.join("mc_data", "input_samples_MC.txt")
24 | monte_carlo_input_samples = numpy.genfromtxt(monte_carlo_input_samples_filename)
25 | target_vector = SampleRandomVector(monte_carlo_input_samples)
26 |
27 | # Define SROM and determine optimal parameters.
28 | srom_size = 20
29 | input_srom = SROM(size=srom_size, dim=3)
30 | input_srom.optimize(target_vector)
31 |
32 | # Compare the input CDFs (produces Figure 6).
33 | post_processor = Postprocessor(input_srom, target_vector)
34 | post_processor.compare_cdfs(variable_names=
35 | [r'$y_{0}$', r'log$C$', r'$n$'])
36 |
37 | # Run the model for each input SROM sample:
38 | srom_results = numpy.zeros(srom_size)
39 | (srom_samples, srom_probabilities) = input_srom.get_params()
40 |
41 | # TODO: define model here.
42 | model = None
43 |
44 | if model is None:
45 | raise ValueError("model has not been defined.")
46 |
47 | for i, sample in enumerate(srom_samples):
48 | srom_results[i] = model.evaluate(sample)
49 |
50 | # Generate SROM surrogate for the end of life.
51 | srom_surrogate_model = SROMSurrogate(input_srom, srom_results)
52 |
53 | # Make random variable with MC end of life solution.
54 | monte_carlo_results_filename = "eol_samples_MC.txt"
55 | monte_carlo_results_samples = numpy.genfromtxt(monte_carlo_results_filename)
56 | target_vector = SampleRandomVector(monte_carlo_results_samples)
57 |
58 | # Compare final EOL solutions SROM vs MC:
59 | # (produces Figure 7)
60 | post_processor = Postprocessor(srom_surrogate_model, target_vector)
61 | post_processor.compare_cdfs(variable_names=["EOL"])
62 |
--------------------------------------------------------------------------------
/examples/spring_mass/model.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 |
17 | import numpy as np
18 | import matplotlib.pyplot as plt
19 | from scipy.integrate import odeint
20 |
21 | # ------------------------------------------------------
22 | # Helper function to use scipy integrator in model class
23 |
24 |
25 | def mass_spring(state, t, k, m):
26 | """
27 | Return velocity/acceleration given velocity/position and values for
28 | stiffness and mass
29 | """
30 |
31 | # Unpack the state vector.
32 | x = state[0]
33 | xd = state[1]
34 |
35 | g = 9.8 # Meters per second.
36 |
37 | # Compute acceleration xdd.
38 | xdd = ((-k*x)/m) + g
39 |
40 | # return the two state derivatives
41 | return [xd, xdd]
42 |
43 | # ------------------------------------------------------
44 |
45 |
46 | class SpringMass1D(object):
47 | """
48 | Defines Spring Mass model with 1 free param (stiffness of spring, k)
49 | """
50 | def __init__(self, m=1.5, state0=None, time_grid=None):
51 |
52 | self._m = m
53 |
54 | # Give default initial conditions & time grid if not specified.
55 | if state0 is None:
56 | state0 = [0.0, 0.0]
57 | if time_grid is None:
58 | time_grid = np.arange(0.0, 10.0, 0.1)
59 |
60 | self._state0 = state0
61 | self._t = time_grid
62 |
63 | def simulate(self, k=2.5):
64 | """
65 | Simulate spring mass system for given spring constant. Returns state
66 | (position, velocity) at all points in time grid
67 | """
68 |
69 | return odeint(mass_spring, self._state0, self._t, args=(k, self._m))
70 |
71 | def get_max_disp(self, k=2.5):
72 | """
73 | Returns the max displacement over the course of the simulation
74 | """
75 |
76 | state = self.simulate(k)
77 | return max(state[:, 0])
78 |
79 |
80 | class SpringMass2D(object):
81 | """
82 | Defines Spring Mass model with 2 free params (spring stiffness, k & mass, m)
83 | """
84 | def __init__(self, state0=None, time_grid=None):
85 |
86 | # Give default initial conditions & time grid if not specified.
87 | if state0 is None:
88 | state0 = [0.0, 0.0]
89 | if time_grid is None:
90 | time_grid = np.arange(0.0, 10.0, 0.1)
91 |
92 | self._state0 = state0
93 | self._t = time_grid
94 |
95 | def simulate(self, k=2.5, m=1.5):
96 | """
97 | Simulate spring mass system for given spring constant. Returns state
98 | (position, velocity) at all points in time grid
99 | """
100 |
101 | return odeint(mass_spring, self._state0, self._t, args=(k, m))
102 |
103 | def get_max_disp(self, k=2.5, m=1.5):
104 | """
105 | Returns the max displacement over the course of the simulation
106 | """
107 |
108 | state = self.simulate(k, m)
109 | return max(state[:, 0])
110 |
111 |
112 | if __name__ == '__main__':
113 |
114 | k = 2.5 # Newtons per metre.
115 | m = 1.5 # Kilograms.
116 | state0 = [0.0, 0.0] # Initial conditions.
117 | t = np.arange(0.0, 10.0, 0.1) # Time grid for simulation.
118 |
119 | # Initialize model & simulate.
120 | model = SpringMass2D(state0, t)
121 | state = model.simulate(k, m)
122 | print "shape = ", state.shape
123 |
124 | # Plot results.
125 | plt.figure()
126 | plt.plot(t, state)
127 | plt.xlabel('TIME (sec)')
128 | plt.ylabel('States')
129 | plt.title('Mass-Spring System')
130 | plt.legend(('$x$ (m)', '$\dot{x}$ (m/sec)'))
131 | plt.show()
132 |
--------------------------------------------------------------------------------
/examples/spring_mass/run_spring_mass_1D.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | '''
17 | This is a simple example meant to demonstrate SROMPy functionality. Estimates
18 | the maximum displacement of a spring-mass system with a random stiffness using
19 | SROMs and compares the solution to Monte Carlo simulation. This example is
20 | explained in more detail in the report:
21 |
22 | Warner, J. E. (2018). Stochastic reduced order models with Python (SROMPy). NASA/TM-2018-219824.
23 |
24 | Note there are minor differences here due to updates in the SROMPy module
25 | '''
26 |
27 | import numpy as np
28 |
29 | from spring_mass_model import SpringMassModel
30 | from SROMPy.postprocess import Postprocessor
31 | from SROMPy.srom import SROM, FiniteDifference as FD, SROMSurrogate
32 | from SROMPy.target import SampleRandomVector, BetaRandomVariable
33 |
34 | # Random variable for spring stiffness
35 | stiffness_random_variable = \
36 | BetaRandomVariable(alpha=3., beta=2., shift=1., scale=2.5)
37 |
38 | # Specify spring-mass system:
39 | m = 1.5 # Deterministic mass.
40 | state0 = [0., 0.] # Initial conditions.
41 | time_step = 0.01
42 |
43 | # Initialize model,
44 | model = SpringMassModel(m, state0=state0, time_step=time_step)
45 |
46 | # ----------Monte Carlo------------------
47 |
48 | print "Generating Monte Carlo reference solution..."
49 |
50 | # Generate stiffness input samples for Monte Carlo.
51 | num_samples = 5000
52 | stiffness_samples = stiffness_random_variable.draw_random_sample(num_samples)
53 |
54 | # Calculate maximum displacement samples using MC simulation.
55 | displacement_samples = np.zeros(num_samples)
56 | for i, stiff in enumerate(stiffness_samples):
57 | displacement_samples[i] = model.evaluate([stiff])
58 |
59 | # Get Monte carlo solution as a sample-based random variable:
60 | monte_carlo_solution = SampleRandomVector(displacement_samples)
61 |
62 | # -------------SROM-----------------------
63 |
64 | print "Generating SROM for input (stiffness)..."
65 |
66 | # Generate SROM for random stiffness.
67 | srom_size = 10
68 | dim = 1
69 | input_srom = SROM(srom_size, dim)
70 | input_srom.optimize(stiffness_random_variable)
71 |
72 | # Compare SROM vs target stiffness distribution:
73 | pp_input = Postprocessor(input_srom, stiffness_random_variable)
74 | pp_input.compare_cdfs()
75 |
76 | print "Computing piecewise constant SROM approximation for output (max disp)..."
77 |
78 | # Run model to get max displacement for each SROM stiffness sample.
79 | srom_displacements = np.zeros(srom_size)
80 | (samples, probabilities) = input_srom.get_params()
81 | for i, stiff in enumerate(samples):
82 | srom_displacements[i] = model.evaluate([stiff])
83 |
84 | # Form new SROM for the max disp. solution using samples from the model.
85 | output_srom = SROM(srom_size, dim)
86 | output_srom.set_params(srom_displacements, probabilities)
87 |
88 | # Compare solutions.
89 | pp_output = Postprocessor(output_srom, monte_carlo_solution)
90 | pp_output.compare_cdfs()
91 |
92 | #Compare mean estimates for output:
93 | print "Monte Carlo mean estimate: ", np.mean(displacement_samples)
94 | print "SROM mean estimate: ", output_srom.compute_moments(1)[0][0]
95 |
96 | # --------Piecewise LINEAR surrogate with gradient info-------
97 |
98 | # Need to calculate gradient of output wrt input samples first.
99 |
100 | # Perturbation size for finite difference.
101 | step_size = 1e-12
102 | samples_fd = FD.get_perturbed_samples(samples, perturbation_values=[step_size])
103 |
104 | print "Computing piecewise linear SROM approximation for output (max disp)..."
105 |
106 | # Run model to get perturbed outputs for FD calc.
107 | perturbed_displacements = np.zeros(srom_size)
108 | for i, stiff in enumerate(samples_fd):
109 | perturbed_displacements[i] = model.evaluate([stiff])
110 | gradient = FD.compute_gradient(srom_displacements, perturbed_displacements,
111 | [step_size])
112 |
113 | surrogate_PWL = SROMSurrogate(input_srom, srom_displacements, gradient)
114 | output_samples = surrogate_PWL.sample(stiffness_samples)
115 | solution_PWL = SampleRandomVector(output_samples)
116 |
117 | pp_pwl = Postprocessor(solution_PWL, monte_carlo_solution)
118 | pp_pwl.compare_cdfs()
119 |
120 |
121 |
--------------------------------------------------------------------------------
/examples/spring_mass/run_spring_mass_2D.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 |
18 | from model import SpringMass2D
19 | from SROMPy.postprocess import Postprocessor
20 | from SROMPy.srom import SROM
21 | from SROMPy.target import BetaRandomVariable as beta
22 | from SROMPy.target import SampleRandomVector
23 |
24 | #Specify spring-mass system:
25 | state0 = [0., 0.] #initial conditions
26 | t_grid = np.arange(0., 10., 0.1) #time
27 |
28 | #random variable for spring stiffness & mass
29 | stiffness_rv = beta(alpha=3., beta=2., shift=1., scale=2.5)
30 | mass_rv = beta(alpha=2./3., beta=1./3., shift=0.5, scale=1.5)
31 |
32 | #Initialize model
33 | model = SpringMass2D(state0, t_grid)
34 |
35 | #Generate samples of random variables for sample based random vector
36 | k_samples = stiffness_rv.draw_random_sample(5000)
37 | m_samples = mass_rv.draw_random_sample(5000)
38 | km_samples = np.array([k_samples, m_samples]).T
39 |
40 | #----------Monte Carlo------------------
41 |
42 | #Generate stiffness input samples for Monte Carlo
43 | num_samples = 5000
44 |
45 | k_samples = stiffness_rv.draw_random_sample(num_samples)
46 | m_samples = mass_rv.draw_random_sample(num_samples)
47 |
48 | #Calculate maximum displacement samples using MC simulation
49 | disp_samples = np.zeros(num_samples)
50 | for i in range(num_samples):
51 | disp_samples[i] = model.get_max_disp(k_samples[i], m_samples[i])
52 |
53 | #Get Monte carlo solution as a sample-based random variable:
54 | mc_solution = SampleRandomVector(disp_samples)
55 |
56 | #-------------SROM-----------------------
57 |
58 | #generate SROM for random vector of stiffness & mass
59 | sromsize = 25
60 | dim = 2
61 |
62 | #Assume we only have access to samples in this example and want SROM from them:
63 | km_samples = np.array([k_samples, m_samples]).T
64 | km_random_vector = SampleRandomVector(km_samples)
65 |
66 | srom = SROM(sromsize, dim)
67 | srom.optimize(km_random_vector)
68 | (samples, probs) = srom.get_params()
69 |
70 | #Run model to get max disp for each SROM stiffness sample
71 | srom_disps = np.zeros(sromsize)
72 | for i in range(sromsize):
73 | k = samples[i,0]
74 | m = samples[i,1]
75 | srom_disps[i] = model.get_max_disp(k, m)
76 |
77 | #Form new SROM for the max displacement solution using samples from the model
78 | srom_solution = SROM(sromsize, 1)
79 | srom_solution.set_params(srom_disps, probs)
80 |
81 | #----------------------------------------
82 |
83 | #Compare solutions
84 | pp = Postprocessor(srom_solution, mc_solution)
85 | pp.compare_cdfs()
86 |
87 |
88 |
--------------------------------------------------------------------------------
/examples/spring_mass/spring_mass_model.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from scipy.integrate import odeint
3 |
4 | class SpringMassModel():
5 | """
6 | Defines Spring Mass model with 1 free param (stiffness of spring, k). The
7 | quantity of interest that is returned by the evaluate() function is the
8 | maximum displacement using the specified time step (for a simulation of
9 | 10 seconds)
10 | """
11 |
12 | def __init__(self, mass=1.5, gravity=9.8, state0=None, time_step=None):
13 |
14 | self._mass = mass
15 | self._gravity = gravity
16 |
17 | # Give default initial conditions & time grid if not specified
18 | if state0 is None:
19 | state0 = [0.0, 0.0]
20 | if time_step is None:
21 | time_grid = np.arange(0.0, 10.0, 0.1)
22 | else:
23 | time_grid = np.arange(0.0, 10.0, time_step)
24 |
25 | self._state0 = state0
26 | self._t = time_grid
27 |
28 | def simulate(self, stiffness):
29 | """
30 | Simulate spring mass system for given spring constant. Returns state
31 | (position, velocity) at all points in time grid
32 | """
33 | return odeint(self._integration_func, self._state0, self._t,
34 | args=(stiffness, self._mass, self._gravity))
35 |
36 | def evaluate(self, inputs):
37 | """
38 | Returns the max displacement over the course of the simulation.
39 | MLMCPy convention is that evaluated takes in an array and returns an
40 | array (even for 1D examples like this one).
41 | """
42 | stiffness = inputs[0]
43 | state = self.simulate(stiffness)
44 | return np.array([max(state[:, 0])])
45 |
46 | @staticmethod
47 | def _integration_func(state, t, k, m, g):
48 | """
49 | Return velocity/acceleration given velocity/position and values for
50 | stiffness and mass. Helper function for numerical integrator
51 | """
52 |
53 | # unpack the state vector
54 | x = state[0]
55 | xd = state[1]
56 |
57 | # compute acceleration xdd
58 | xdd = ((-k * x) / m) + g
59 |
60 | # return the two state derivatives
61 | return [xd, xdd]
62 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy
2 | scipy
3 | matplotlib
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import setuptools
17 |
18 | with open("README.md", "r") as fh:
19 | long_description = fh.read()
20 |
21 | setuptools.setup(
22 | name="SROMPy",
23 | version="0.1.0",
24 | author="James Warner ",
25 | author_email="james.e.warner@nasa.gov",
26 | description="Stochastic Reduced Order Models with Python",
27 | long_description=long_description,
28 | long_description_content_type="text/markdown",
29 | url="https://github.com/NASA/SROMPy",
30 | packages=["SROMPy",
31 | "SROMPy.optimize",
32 | "SROMPy.postprocess",
33 | "SROMPy.srom",
34 | "SROMPy.target"],
35 | package_dir={'SROMPy': 'SROMPy'},
36 | install_requires=['numpy', 'scipy', 'matplotlib'],
37 | classifiers=[
38 | "Programming Language :: Python :: 2.7",
39 | "License :: OSI Approved :: Apache Software License",
40 | "Operating System :: OS Independent",
41 | ],
42 | )
43 |
--------------------------------------------------------------------------------
/tests/optimize/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
--------------------------------------------------------------------------------
/tests/optimize/test_Gradient.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 | import pytest
18 | import os
19 | import sys
20 |
21 | if 'PYTHONPATH' not in os.environ:
22 | base_path = os.path.abspath('.')
23 |
24 | sys.path.insert(0, base_path)
25 |
26 | from SROMPy.srom import SROM
27 | from SROMPy.optimize import Gradient
28 | from SROMPy.target import SampleRandomVector
29 |
30 |
31 | @pytest.fixture
32 | def sample_random_vector():
33 | np.random.seed(1)
34 | random_vector = np.random.rand(10)
35 | return SampleRandomVector(random_vector)
36 |
37 |
38 | @pytest.fixture
39 | def valid_srom():
40 | return SROM(10, 1)
41 |
42 |
43 | @pytest.fixture
44 | def gradient(sample_random_vector, valid_srom):
45 | return Gradient(srom=valid_srom,
46 | target_random_variable=sample_random_vector,
47 | error='mean')
48 |
49 |
50 | @pytest.fixture
51 | def gradient_joint(sample_random_vector, valid_srom):
52 | return Gradient(srom=valid_srom,
53 | target_random_variable=sample_random_vector,
54 | error='SSE',
55 | scale=0.01,
56 | joint_opt=True)
57 |
58 |
59 | def test_invalid_init_parameter_values_rejected(sample_random_vector, valid_srom):
60 | # Ensure no exception using default parameters.
61 | Gradient(srom=valid_srom, target_random_variable=sample_random_vector)
62 |
63 | # Ensure exception if obj_weights parameter is too small.
64 | with pytest.raises(ValueError):
65 | Gradient(srom=valid_srom, target_random_variable=sample_random_vector,
66 | obj_weights=np.ones((2,)))
67 |
68 | # Ensure exception if specified error parameter is invalid.
69 | with pytest.raises(ValueError):
70 | Gradient(srom=valid_srom, target_random_variable=sample_random_vector,
71 | error='test')
72 |
73 |
74 | def test_evaluate_returns_expected_result(valid_srom, gradient):
75 | samples = np.ones((valid_srom._size, valid_srom._dim))
76 | probabilities = np.ones(valid_srom._size)
77 |
78 | results = gradient.evaluate(samples, probabilities)
79 |
80 | assert isinstance(results, np.ndarray)
81 | assert results.size == valid_srom._size
82 |
83 |
84 | def test_gradient_joint(valid_srom, gradient_joint):
85 | samples = np.ones((valid_srom.size, valid_srom.dim))
86 | probabilities = np.ones(valid_srom.size)
87 |
88 | results = gradient_joint.evaluate(samples, probabilities)
89 |
90 | assert isinstance(results, np.ndarray)
91 | assert results.size == (valid_srom.size * valid_srom.dim + valid_srom.size)
92 |
--------------------------------------------------------------------------------
/tests/optimize/test_ObjectiveFunction.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 | import pytest
18 | import os
19 | import sys
20 |
21 | if 'PYTHONPATH' not in os.environ:
22 | base_path = os.path.abspath('.')
23 |
24 | sys.path.insert(0, base_path)
25 |
26 | from SROMPy.srom import SROM
27 | from SROMPy.optimize import ObjectiveFunction
28 | from SROMPy.target import SampleRandomVector
29 |
30 |
31 | @pytest.fixture
32 | def sample_random_vector():
33 | np.random.seed(1)
34 | random_vector = np.random.rand(10)
35 | return SampleRandomVector(random_vector)
36 |
37 |
38 | @pytest.fixture
39 | def valid_srom():
40 | return SROM(10, 1)
41 |
42 |
43 | @pytest.fixture
44 | def valid_srom_smooth():
45 | srom = SROM(10, 1)
46 | srom._scale = 0.1
47 | return srom
48 |
49 |
50 | def test_invalid_init_parameter_values_rejected(valid_srom,
51 | sample_random_vector):
52 | with pytest.raises(TypeError):
53 | ObjectiveFunction(srom="srom",
54 | target=sample_random_vector,
55 | obj_weights=None,
56 | error="MEAN",
57 | max_moment=2,
58 | num_cdf_grid_points=100)
59 |
60 | with pytest.raises(TypeError):
61 | ObjectiveFunction(srom=valid_srom,
62 | target="victor",
63 | obj_weights=None,
64 | error="MEAN",
65 | max_moment=2,
66 | num_cdf_grid_points=100)
67 |
68 | with pytest.raises(TypeError):
69 | ObjectiveFunction(srom=valid_srom,
70 | target=sample_random_vector,
71 | obj_weights="heavy",
72 | error="MEAN",
73 | max_moment=2,
74 | num_cdf_grid_points=100)
75 |
76 | with pytest.raises(TypeError):
77 | ObjectiveFunction(srom=valid_srom,
78 | target=sample_random_vector,
79 | obj_weights=None,
80 | error=1.,
81 | max_moment=2,
82 | num_cdf_grid_points=100)
83 |
84 | with pytest.raises(TypeError):
85 | ObjectiveFunction(srom=valid_srom,
86 | target=sample_random_vector,
87 | obj_weights=None,
88 | error="MEAN",
89 | max_moment="first",
90 | num_cdf_grid_points=100)
91 |
92 | with pytest.raises(TypeError):
93 | ObjectiveFunction(srom=valid_srom,
94 | target=sample_random_vector,
95 | obj_weights=None,
96 | error="MEAN",
97 | max_moment=2,
98 | num_cdf_grid_points=[1, 2])
99 |
100 | with pytest.raises(ValueError):
101 | ObjectiveFunction(srom=valid_srom,
102 | target=sample_random_vector,
103 | obj_weights=np.zeros((5, 2)),
104 | error="MEAN",
105 | max_moment=2,
106 | num_cdf_grid_points=100)
107 |
108 | with pytest.raises(ValueError):
109 | ObjectiveFunction(srom=valid_srom,
110 | target=sample_random_vector,
111 | obj_weights=np.zeros(5),
112 | error="MEAN",
113 | max_moment=2,
114 | num_cdf_grid_points=100)
115 |
116 | with pytest.raises(ValueError):
117 | ObjectiveFunction(srom=valid_srom,
118 | target=sample_random_vector,
119 | obj_weights=np.ones(3) * -1,
120 | error="MEAN",
121 | max_moment=2,
122 | num_cdf_grid_points=100)
123 |
124 | sample_random_vector._dim = 0
125 | with pytest.raises(ValueError):
126 | ObjectiveFunction(srom=valid_srom,
127 | target=sample_random_vector,
128 | obj_weights=None,
129 | error="MEAN",
130 | max_moment=2,
131 | num_cdf_grid_points=100)
132 |
133 |
134 | def test_evaluate_returns_expected_result(valid_srom, sample_random_vector):
135 | samples = np.ones((valid_srom._size, valid_srom._dim))
136 | probabilities = np.ones(valid_srom._size)
137 |
138 | for objective_weights in [[0., .05, 1.], [7., .4, .1]]:
139 | for error_function in ["mean", "max", "sse"]:
140 | for max_moment in [1, 2, 3, 4]:
141 | for num_cdf_grid_points in [2, 15, 70]:
142 | objective_function = \
143 | ObjectiveFunction(srom=valid_srom,
144 | target=sample_random_vector,
145 | obj_weights=objective_weights,
146 | error=error_function,
147 | max_moment=max_moment,
148 | num_cdf_grid_points=
149 | num_cdf_grid_points)
150 |
151 | error = objective_function.evaluate(samples, probabilities)
152 |
153 | assert isinstance(error, float)
154 | assert error > 0.
155 |
156 |
157 | def test_evaluate_returns_expected_result_smooth(valid_srom_smooth, sample_random_vector):
158 | samples = np.ones((valid_srom_smooth._size, valid_srom_smooth._dim))
159 | probabilities = np.ones(valid_srom_smooth._size)
160 |
161 | for objective_weights in [[0., .05, 1.], [7., .4, .1]]:
162 | for error_function in ["mean", "max", "sse"]:
163 | for max_moment in [1, 2, 3, 4]:
164 | for num_cdf_grid_points in [2, 15, 70]:
165 | objective_function = \
166 | ObjectiveFunction(srom=valid_srom_smooth,
167 | target=sample_random_vector,
168 | obj_weights=objective_weights,
169 | error=error_function,
170 | max_moment=max_moment,
171 | num_cdf_grid_points=
172 | num_cdf_grid_points)
173 |
174 | error = objective_function.evaluate(samples, probabilities)
175 |
176 | assert isinstance(error, float)
177 | assert error > 0.
178 |
--------------------------------------------------------------------------------
/tests/optimize/test_Optimizer.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 | import numpy as np
18 | import os
19 | import sys
20 |
21 | if 'PYTHONPATH' not in os.environ:
22 |
23 | base_path = os.path.abspath('.')
24 |
25 | sys.path.insert(0, base_path)
26 |
27 |
28 | from SROMPy.optimize import Optimizer
29 | from SROMPy.srom import SROM
30 | from SROMPy.target import SampleRandomVector
31 |
32 |
33 | @pytest.fixture
34 | def sample_random_vector():
35 |
36 | np.random.seed(1)
37 | random_vector = np.random.rand(10)
38 | return SampleRandomVector(random_vector)
39 |
40 |
41 | @pytest.fixture
42 | def valid_srom():
43 | return SROM(10, 1)
44 |
45 |
46 | def test_invalid_init_parameter_values_rejected(sample_random_vector,
47 | valid_srom):
48 |
49 | # Ensure no exception using default parameters.
50 | Optimizer(sample_random_vector, valid_srom)
51 |
52 | # TODO: Ensure no exception using valid values for all parameters.
53 | Optimizer(sample_random_vector,
54 | valid_srom,
55 | np.array([1., 1., 1.]))
56 |
57 | # Ensure exception for invalid target parameter.
58 | with pytest.raises(TypeError):
59 | Optimizer([], valid_srom)
60 |
61 | with pytest.raises(TypeError):
62 | Optimizer(np.zeros(10), valid_srom)
63 |
64 | # Ensure exception for invalid srom parameter.
65 | with pytest.raises(TypeError):
66 | Optimizer(sample_random_vector, None)
67 |
68 | # Ensure exception for invalid weights.
69 | with pytest.raises(ValueError):
70 | Optimizer(sample_random_vector, valid_srom, np.array([[1., 1.],
71 | [1., 1.]]))
72 |
73 | with pytest.raises(ValueError):
74 | Optimizer(sample_random_vector, valid_srom, np.array([1., 1.]))
75 |
76 | with pytest.raises(ValueError):
77 | Optimizer(sample_random_vector, valid_srom, np.array([1., 1., -1.]))
78 |
79 | # Ensure invalid error strings are rejected.
80 | with pytest.raises(TypeError):
81 | Optimizer(sample_random_vector, valid_srom, error=4)
82 |
83 | with pytest.raises(ValueError):
84 | Optimizer(sample_random_vector, valid_srom, error="BEST")
85 |
86 | # Ensure max moment is a positive integer.
87 | with pytest.raises(TypeError):
88 | Optimizer(sample_random_vector, valid_srom, max_moment="five")
89 |
90 | with pytest.raises(ValueError):
91 | Optimizer(sample_random_vector, valid_srom, max_moment=0)
92 |
93 | # Ensure cdf_grid_pts is a positive integer.
94 | with pytest.raises(TypeError):
95 | Optimizer(sample_random_vector, valid_srom, cdf_grid_pts="five")
96 |
97 | with pytest.raises(ValueError):
98 | Optimizer(sample_random_vector, valid_srom, cdf_grid_pts=0)
99 |
100 | # Add the scale checker for scale parameter
101 | with pytest.raises(TypeError):
102 | Optimizer(sample_random_vector, valid_srom, scale="scale")
103 |
104 |
105 | def test_invalid_get_optimal_params_parameter_values_rejected(sample_random_vector,
106 | valid_srom):
107 |
108 | # Ensure no errors with valid parameters.
109 | optimizer = Optimizer(sample_random_vector, valid_srom)
110 |
111 | # Ensure num_test_samples is positive integer.
112 | with pytest.raises(TypeError):
113 | optimizer.get_optimal_params(num_test_samples="One")
114 |
115 | with pytest.raises(ValueError):
116 | optimizer.get_optimal_params(num_test_samples=0)
117 |
118 | # Add the qmc checker
119 | with pytest.raises(ValueError):
120 | optimizer.get_optimal_params(qmc_engine="wrong_engine")
121 |
122 |
123 | def test_get_optimal_params_expected_output(sample_random_vector, valid_srom):
124 |
125 | # Ensure that output corresponding to a known input processed
126 | # with a preset random seed remains consistent.
127 | optimizer = Optimizer(sample_random_vector, valid_srom)
128 |
129 | samples, probabilities = optimizer.get_optimal_params(num_test_samples=10,
130 | verbose=False)
131 |
132 | assert np.allclose([np.sum(probabilities)], [1.])
133 |
134 |
135 | def test_get_joint_optimal_params(sample_random_vector, valid_srom):
136 |
137 | # Ensure that output corresponding to a known input processed
138 | # with a preset random seed remains consistent.
139 | optimizer = Optimizer(sample_random_vector, valid_srom, joint_opt=True, scale=0.1)
140 |
141 | samples, probabilities = optimizer.get_optimal_params(num_test_samples=10,
142 | joint_opt=True,
143 | verbose=True)
144 | assert np.allclose([np.sum(probabilities)], [1.])
145 |
--------------------------------------------------------------------------------
/tests/postprocess/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 |
--------------------------------------------------------------------------------
/tests/postprocess/test_Postprocessor.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import numpy as np
17 | import pytest
18 | import os
19 | import sys
20 |
21 | if 'PYTHONPATH' not in os.environ:
22 |
23 | base_path = os.path.abspath('.')
24 |
25 | sys.path.insert(0, base_path)
26 |
27 |
28 | from SROMPy.srom import SROM
29 | from SROMPy.postprocess import Postprocessor
30 | from SROMPy.target import SampleRandomVector
31 |
32 |
33 | @pytest.fixture
34 | def sample_random_vector():
35 |
36 | np.random.seed(1)
37 | random_vector = np.random.rand(10)
38 | return SampleRandomVector(random_vector)
39 |
40 |
41 | @pytest.fixture
42 | def valid_srom():
43 | return SROM(10, 1)
44 |
45 |
46 | @pytest.fixture
47 | def initialized_srom(valid_srom):
48 | valid_srom.set_params(np.random.rand(10), np.random.rand(10))
49 | return valid_srom
50 |
51 |
52 | # TODO: Find a way to test that Postprocessor checks for required functions
53 | # on the random entity.
54 | # @pytest.mark.parametrize('required_function', ['compute_cdf',
55 | # 'compute_moments'])
56 | # def test_checks_for_random_entity_required_functions(initialized_srom,
57 | # sample_random_vector,
58 | # required_function):
59 | #
60 | # # delatter did not seem to work on a function, so this is a workaround.
61 | # setattr(sample_random_vector, required_function, "str")
62 | # delattr(sample_random_vector, required_function)
63 | #
64 | # with pytest.raises(TypeError):
65 | # Postprocessor(initialized_srom, sample_random_vector)
66 |
--------------------------------------------------------------------------------
/tests/srom/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 |
--------------------------------------------------------------------------------
/tests/srom/test_FiniteDifference.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 | import os
18 | import sys
19 |
20 | if 'PYTHONPATH' not in os.environ:
21 |
22 | base_path = os.path.abspath('.')
23 |
24 | sys.path.insert(0, base_path)
25 |
26 |
27 | def test_1():
28 | pass
29 |
30 |
31 |
--------------------------------------------------------------------------------
/tests/srom/test_SROM.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 | import numpy as np
18 | import os
19 | import sys
20 |
21 | if 'PYTHONPATH' not in os.environ:
22 |
23 | base_path = os.path.abspath('.')
24 |
25 | sys.path.insert(0, base_path)
26 |
27 |
28 | from SROMPy.srom import SROM
29 | from SROMPy.target import SampleRandomVector
30 | from SROMPy.target import RandomVector
31 |
32 |
33 | def test_invalid_init_parameter_values_rejected():
34 |
35 | # Ensure exception for invalid srom dimensions.
36 | with pytest.raises(ValueError):
37 | SROM(0, 1)
38 | SROM(-1, 1)
39 | SROM(10, 0)
40 | SROM(10, 3)
41 |
42 |
43 | def test_invalid_optimize_parameter_values_rejected():
44 |
45 | pass
46 |
--------------------------------------------------------------------------------
/tests/srom/test_SROMSurrogate.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 | import os
18 | import sys
19 |
20 | if 'PYTHONPATH' not in os.environ:
21 |
22 | base_path = os.path.abspath('.')
23 |
24 | sys.path.insert(0, base_path)
25 |
26 |
27 |
28 | def test_1():
29 | pass
30 |
31 |
32 |
--------------------------------------------------------------------------------
/tests/target/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 |
--------------------------------------------------------------------------------
/tests/target/test_AnalyticRandomVector.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 | import os
18 | import sys
19 |
20 | if 'PYTHONPATH' not in os.environ:
21 |
22 | base_path = os.path.abspath('.')
23 |
24 | sys.path.insert(0, base_path)
25 |
26 |
27 |
28 | def test_1():
29 | pass
30 |
31 |
32 |
--------------------------------------------------------------------------------
/tests/target/test_BetaRandomVariable.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 | import os
18 | import sys
19 |
20 | if 'PYTHONPATH' not in os.environ:
21 |
22 | base_path = os.path.abspath('.')
23 |
24 | sys.path.insert(0, base_path)
25 |
26 |
27 |
28 | def test_1():
29 | pass
30 |
31 |
32 |
--------------------------------------------------------------------------------
/tests/target/test_DiscreteRandomVector.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 | import numpy as np
18 | import os
19 | import sys
20 |
21 | if 'PYTHONPATH' not in os.environ:
22 |
23 | base_path = os.path.abspath('.')
24 |
25 | sys.path.insert(0, base_path)
26 |
27 |
28 | from SROMPy.target.DiscreteRandomVector import DiscreteRandomVector
29 |
30 |
31 |
32 | @pytest.fixture
33 | def simple_discrete_rv_1d():
34 |
35 | samples = np.array([1,2,3,4])
36 | probabilities = np.array([0.25, 0.25, 0.25, 0.25])
37 |
38 | discrete_rv = DiscreteRandomVector(samples, probabilities)
39 | return discrete_rv
40 |
41 | @pytest.fixture
42 | def simple_discrete_rv_2d():
43 |
44 | samples = np.array([[1,4],
45 | [2,5],
46 | [3,6],
47 | [4,7]])
48 | probabilities = np.array([0.25, 0.25, 0.25, 0.25])
49 |
50 | discrete_rv = DiscreteRandomVector(samples, probabilities)
51 | return discrete_rv
52 |
53 |
54 | def test_compute_moments_simple_1d(simple_discrete_rv_1d):
55 |
56 | moments = simple_discrete_rv_1d.compute_moments(max_order=2)
57 |
58 | #Check first two moments
59 | assert np.isclose(moments[0], 2.5)
60 | assert np.isclose( moments[1], 7.5)
61 | assert len(moments) == 2
62 |
63 | def test_compute_cdfs_simple_1d(simple_discrete_rv_1d):
64 |
65 | x_grid = np.array([0.5, 1.5, 2.5, 3.5, 4.5])
66 | cdf_vals = simple_discrete_rv_1d.compute_cdf(x_grid)
67 |
68 | true_cdf_vals = [0., 0.25, 0.5, 0.75, 1.0]
69 |
70 | for i, true_val in enumerate(true_cdf_vals):
71 | assert np.isclose(cdf_vals[i], true_val)
72 |
73 |
74 | def test_compute_moments_simple_2d(simple_discrete_rv_2d):
75 |
76 | moments = simple_discrete_rv_2d.compute_moments(max_order=2)
77 |
78 | #Check mean and variance in both dimensions:
79 | assert np.isclose(moments[0,0], 2.5)
80 | assert np.isclose( moments[1,0], 7.5)
81 | assert np.isclose(moments[0,1], 5.5)
82 | assert np.isclose( moments[1,1], 31.5)
83 |
84 | def test_compute_cdfs_simple_2d(simple_discrete_rv_2d):
85 |
86 | #CDFs are evaluated on the same x-grid for each dimension
87 | x_grid = np.array([0.5, 2.5, 4.5, 6.5, 7.5])
88 | cdf_vals = simple_discrete_rv_2d.compute_cdf(x_grid)
89 |
90 | true_cdf_vals_dim1 = [0., 0.5, 1.0, 1.0, 1.0]
91 | for i, true_val in enumerate(true_cdf_vals_dim1):
92 | assert np.isclose(cdf_vals[i,0], true_val)
93 |
94 | true_cdf_vals_dim2 = [0., 0., 0.25, 0.75, 1.0]
95 | for i, true_val in enumerate(true_cdf_vals_dim2):
96 | assert np.isclose(cdf_vals[i,1], true_val)
97 |
98 | def test_raise_value_error_for_bad_probabilities():
99 |
100 | samples = np.array([1,2,3,4])
101 |
102 | probs_wrong_dim = np.array([0.25, 0.25, 0.5])
103 | with pytest.raises(ValueError):
104 | discrete_rv = DiscreteRandomVector(samples, probs_wrong_dim)
105 |
106 | probs_wrong_sum = np.array([0.25, 0.25, 0.25, 0.1])
107 | with pytest.raises(ValueError):
108 | discrete_rv = DiscreteRandomVector(samples, probs_wrong_sum)
109 |
110 | probs_neg_value = np.array([0.5, 0.5, 0.25, -0.25 ])
111 | with pytest.raises(ValueError):
112 | discrete_rv = DiscreteRandomVector(samples, probs_neg_value)
113 |
114 | def test_raise_value_error_for_bad_samples_1d():
115 |
116 | probabilities = np.array([0.25,0.25,0.25,0.25])
117 |
118 | samples_wrong_size = np.array([1,2,3])
119 | with pytest.raises(ValueError):
120 | discrete_rv = DiscreteRandomVector(samples_wrong_size, probabilities)
121 |
122 | samples_wrong_shape = np.array([[1,2],[3,4]])
123 | with pytest.raises(ValueError):
124 | discrete_rv = DiscreteRandomVector(samples_wrong_shape, probabilities)
125 |
126 |
127 |
128 |
--------------------------------------------------------------------------------
/tests/target/test_GammaRandomVariable.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 | import os
18 | import sys
19 |
20 | if 'PYTHONPATH' not in os.environ:
21 |
22 | base_path = os.path.abspath('.')
23 |
24 | sys.path.insert(0, base_path)
25 |
26 |
27 |
28 | def test_1():
29 | pass
30 |
31 |
32 |
--------------------------------------------------------------------------------
/tests/target/test_NormalRandomVariable.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 |
18 |
19 | def test_1():
20 | pass
21 |
22 |
23 |
--------------------------------------------------------------------------------
/tests/target/test_RandomVector.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 |
18 |
19 | def test_1():
20 | pass
21 |
22 |
23 |
--------------------------------------------------------------------------------
/tests/target/test_SampleRandomVector.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 |
18 |
19 | def test_1():
20 | pass
21 |
22 |
23 |
--------------------------------------------------------------------------------
/tests/target/test_UniformRandomVariable.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 United States Government as represented by the Administrator of
2 | # the National Aeronautics and Space Administration. No copyright is claimed in
3 | # the United States under Title 17, U.S. Code. All Other Rights Reserved.
4 |
5 | # The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed
6 | # under the Apache License, Version 2.0 (the "License"); you may not use this
7 | # file except in compliance with the License. You may obtain a copy of the
8 | # License at http://www.apache.org/licenses/LICENSE-2.0.
9 |
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | # License for the specific language governing permissions and limitations
14 | # under the License.
15 |
16 | import pytest
17 |
18 | from SROMPy.target import UniformRandomVariable
19 |
20 |
21 | def test_raises_exception_for_invalid_variable_range():
22 |
23 | minimum_value = 5
24 | maximum_value = 3
25 |
26 | with pytest.raises(ValueError):
27 | UniformRandomVariable(minimum_value, maximum_value)
28 |
29 |
--------------------------------------------------------------------------------