├── .coveragerc ├── .gitignore ├── .idea ├── codeStyles │ └── codeStyleConfig.xml └── dictionaries │ └── lmorrill.xml ├── .travis.yml ├── LICENSE ├── Pipfile ├── Pipfile.lock ├── README.md ├── SROMPy ├── __init__.py ├── optimize │ ├── Gradient.py │ ├── ObjectiveFunction.py │ ├── Optimizer.py │ └── __init__.py ├── postprocess │ ├── Postprocessor.py │ └── __init__.py ├── srom │ ├── FiniteDifference.py │ ├── SROM.py │ ├── SROMSurrogate.py │ └── __init__.py └── target │ ├── AnalyticRandomVector.py │ ├── BetaRandomVariable.py │ ├── DiscreteRandomVector.py │ ├── GammaRandomVariable.py │ ├── NormalRandomVariable.py │ ├── RandomEntity.py │ ├── RandomVariable.py │ ├── RandomVector.py │ ├── SampleRandomVector.py │ ├── UniformRandomVariable.py │ └── __init__.py ├── docs ├── Makefile ├── SROMPy_doc.pdf ├── _build │ └── html │ │ ├── .buildinfo │ │ ├── _images │ │ ├── disp_CDFs_pw_constant.png │ │ ├── disp_CDFs_pw_linear.png │ │ ├── math │ │ │ ├── 02e99335fa7566885ffc47f9d1d14dd30bff14cb.png │ │ │ ├── 032ffd36302c5d12a2f2e5b029c92c5015455208.png │ │ │ ├── 1d281d91e34a74f064c179fd70612c7bfe765eaa.png │ │ │ ├── 307b3725cbb03398131f9ca542d79aff4933195f.png │ │ │ ├── 3666981dc77862de77b6ecfcb64aad59b425cbaf.png │ │ │ ├── 3f2fdf96d3bf24c77cfcc7d5a41069bbcd828a71.png │ │ │ ├── 40708f3d3ce870020c1bd88b8b4d8aec109c5f6e.png │ │ │ ├── 410a9d0df9c135dd73b269cba7ef04dcfd932b1f.png │ │ │ ├── 5635a7c34414599c2452d72430811e816b460335.png │ │ │ ├── 58feb749986ef5862e812ca6c32b924a2f7aca6c.png │ │ │ ├── 666f10b1d5338fe962e81b37cefb54d6633fd29f.png │ │ │ ├── 678113eb2ebf18c078cf3e4cff8e8aac2f347485.png │ │ │ ├── 683f2dd9129a91d21aaf1c04afa6f78b39d4cb0a.png │ │ │ ├── 7c3feb481455fd0d728caa23fd6d452e41728198.png │ │ │ ├── 877d234f4cec6974ce218fc2e975a486a7972dfd.png │ │ │ ├── 88342b20a6b5fba2b278a773e8ef013b315593af.png │ │ │ ├── 89c0eb02cd0320e298c606fba3c33cdcee62c413.png │ │ │ ├── 8b25e6d1d67015300bc0d13c686a6410a47a7d3a.png │ │ │ ├── 9ff109b8cdf1585b2fd1f195f1e2b51ca3ebc027.png │ │ │ ├── a4f983455bdb6ec51b3fdaa4d3ddc93e712f4c75.png │ │ │ ├── ad7538581b1f02e87be67296fedce555dc704479.png │ │ │ ├── af115195c8b6c13c7f47455427b364a26eef1356.png │ │ │ ├── b125a026740c3cb29d8f1b0bef027d3e0be86939.png │ │ │ ├── b9228c12487f73d548763c61745e3cf8e492cfd2.png │ │ │ ├── bcb2457ac9d8995a4f34d57cadac7ecbbe58f3bd.png │ │ │ ├── d748cfdac5dabbf89592b7f10bc320c27d98ebc3.png │ │ │ ├── ef2f48e90f954011166511275c879f923b479f04.png │ │ │ ├── fdd92017f5b9e8043b027461d74ddd99c720079c.png │ │ │ └── fed776613749e7ff592fc8648bbd65278d6a7dae.png │ │ ├── spring_mass_diagram.png │ │ ├── stiffness_CDFs.pdf │ │ └── stiffness_CDFs.png │ │ ├── _sources │ │ ├── example.rst.txt │ │ ├── example.txt │ │ ├── index.rst.txt │ │ ├── index.txt │ │ ├── intro.rst.txt │ │ ├── intro.txt │ │ ├── source_code.rst.txt │ │ └── source_code.txt │ │ ├── _static │ │ ├── ajax-loader.gif │ │ ├── alabaster.css │ │ ├── basic.css │ │ ├── comment-bright.png │ │ ├── comment-close.png │ │ ├── comment.png │ │ ├── custom.css │ │ ├── doctools.js │ │ ├── documentation_options.js │ │ ├── down-pressed.png │ │ ├── down.png │ │ ├── file.png │ │ ├── jquery-1.11.1.js │ │ ├── jquery-3.2.1.js │ │ ├── jquery.js │ │ ├── language_data.js │ │ ├── minus.png │ │ ├── plus.png │ │ ├── pygments.css │ │ ├── searchtools.js │ │ ├── underscore-1.3.1.js │ │ ├── underscore.js │ │ ├── up-pressed.png │ │ ├── up.png │ │ └── websupport.js │ │ ├── example.html │ │ ├── genindex.html │ │ ├── index.html │ │ ├── intro.html │ │ ├── objects.inv │ │ ├── py-modindex.html │ │ ├── search.html │ │ ├── searchindex.js │ │ └── source_code.html ├── conf.py ├── example.rst ├── images │ ├── disp_CDFs_pw_constant.pdf │ ├── disp_CDFs_pw_constant.png │ ├── disp_CDFs_pw_linear.pdf │ ├── disp_CDFs_pw_linear.png │ ├── spring_mass_diagram.png │ ├── stiffness_CDFs.pdf │ └── stiffness_CDFs.png ├── index.rst ├── intro.rst ├── make.bat ├── references │ ├── Emery_2016_Reliability_via_SROMs.pdf │ ├── SROMPy-NASA-TM-2018-219824.pdf │ ├── SROMs_for_random_vectors.pdf │ ├── comparison_paper_collocation_galerkin_sroms.pdf │ └── srom_local_approx_grigoriu.pdf └── source_code.rst ├── examples ├── basic_tests │ ├── normal_rv_srom.pdf │ ├── normal_rv_srom.png │ └── normal_rv_srom.py ├── parallel_performance_tests │ ├── generate_chart_strong_scalability.py │ ├── generate_chart_weak_scalability.py │ ├── generate_data_strong_scalability.py │ └── generate_data_weak_scalability.py ├── phm18 │ ├── .DS_Store │ ├── PHM18_Jwarner.pptx │ ├── README │ ├── compare_input_srom_CDFs.py │ ├── compare_pwconst_srom_eol_CDFs.py │ ├── compare_pwlin_srom_eol_CDFs.py │ ├── generate_input_srom.py │ ├── generate_pwconstant_eol.py │ ├── generate_pwlinear_eol.py │ ├── mc_data │ │ ├── eol_samples_MC.txt │ │ └── input_samples_MC.txt │ ├── normal_rv_srom.py │ ├── phm_srompy_demo_ex.py │ ├── plot_input_histograms.py │ ├── plot_pwconstant_eol_demo.py │ ├── plots │ │ └── .DS_Store │ ├── run_model.py │ ├── srom_data │ │ ├── .DS_Store │ │ ├── srom_eol_m10.txt │ │ ├── srom_eol_m20.txt │ │ ├── srom_eol_m5.txt │ │ ├── srom_eol_samples_m10.txt │ │ ├── srom_eol_samples_m20.txt │ │ ├── srom_eol_samples_m5.txt │ │ ├── srom_fd_eol_m10.txt │ │ ├── srom_fd_eol_m20.txt │ │ ├── srom_fd_eol_m5.txt │ │ ├── srom_m10.txt │ │ ├── srom_m20.txt │ │ └── srom_m5.txt │ └── srompy_demo_script.py └── spring_mass │ ├── Spring Mass 1D Example.ipynb │ ├── model.py │ ├── run_spring_mass_1D.py │ ├── run_spring_mass_2D.py │ └── spring_mass_model.py ├── requirements.txt ├── setup.py └── tests ├── optimize ├── __init__.py ├── test_Gradient.py ├── test_ObjectiveFunction.py └── test_Optimizer.py ├── postprocess ├── __init__.py └── test_Postprocessor.py ├── srom ├── __init__.py ├── test_FiniteDifference.py ├── test_SROM.py └── test_SROMSurrogate.py └── target ├── __init__.py ├── test_AnalyticRandomVector.py ├── test_BetaRandomVariable.py ├── test_DiscreteRandomVector.py ├── test_GammaRandomVariable.py ├── test_NormalRandomVariable.py ├── test_RandomVector.py ├── test_SampleRandomVector.py └── test_UniformRandomVariable.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | exclude_lines = 3 | # Have to re-enable the standard pragma 4 | pragma: no cover 5 | 6 | # Don't complain if tests don't hit defensive assertion code: 7 | raise NotImplementedError -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *swp* 2 | *.pyc 3 | docs/_* 4 | srom/*.pyc 5 | srom/__init__.pyc 6 | target/*.pyc 7 | optimize/*.pyc 8 | srom/*swp* 9 | target/*swp* 10 | optimize/*swp* 11 | examples/phm17/data/* 12 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/dictionaries/lmorrill.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | srom 5 | 6 | 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | 5 | install: 6 | - export PYTHONPATH=$PYTHONPATH:$(pwd)/SROMPy 7 | - pip install scipy 8 | - pip install matplotlib 9 | - pip install pytest==4.0 pytest-cov 10 | - pip install coveralls 11 | 12 | script: 13 | - pytest tests --cov=SROMPy 14 | 15 | after_script: 16 | - coveralls 17 | -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | url = "https://pypi.org/simple" 3 | verify_ssl = true 4 | name = "pypi" 5 | 6 | [dev-packages] 7 | 8 | [packages] 9 | numpy = "*" 10 | scipy = "*" 11 | matplotlib = "*" 12 | pytest = "*" 13 | 14 | [requires] 15 | python_version = "2.7" 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SROMPy - **S**tochastic **R**educed **O**rder **M**odels with **Py**thon 2 | ========================================================================== 3 | 4 | Coverage Status Coverage Status 5 | 6 | General 7 | -------- 8 | 9 | Python module for generating Stochastic Reduced Order Models (SROMs) and applying them for uncertainty quantification problems. See documentation in `docs/` directory for details. 10 | 11 | Dependencies 12 | ------------- 13 | SROMPy is intended for use with Python 2.7 and relies on the following packages: 14 | * numpy 15 | * scipy 16 | * matplotlib 17 | * mpi4py (optional for running in parallel) 18 | * pytest (optional if the testing suite is to be run) 19 | 20 | A requirements.txt file is included for easy installation of dependecies with pip: 21 | 22 | ``` 23 | pip install -r requirements.txt 24 | ``` 25 | 26 | Example Usage 27 | -------------- 28 | 29 | ```python 30 | from SROMPy.postprocess import Postprocessor 31 | from SROMPy.srom import SROM 32 | from SROMPy.target import NormalRandomVariable 33 | 34 | #Initialize Normal random variable object to be modeled by SROM: 35 | normal = NormalRandomVariable(mean=3., std_dev=1.5) 36 | 37 | #Initialize SROM & optimize to model the normal random variable: 38 | srom = SROM(size=10, dim=1) 39 | srom.optimize(normal) 40 | 41 | #Compare the CDF of the SROM & target normal variable: 42 | post_processor = Postprocessor(srom, normal) 43 | post_processor.compare_CDFs() 44 | ``` 45 | 46 | The above code snippet produces the following CDF comparison plot: 47 | 48 | ![CDF comparison](https://github.com/nasa/SROMPy/blob/master/examples/basic_tests/normal_rv_srom.png) 49 | 50 | Getting Started 51 | ---------------- 52 | SROMPy can be installed via pip from [PyPI](https://pypi.org/project/SROMPy/): 53 | 54 | ``` 55 | pip install srompy 56 | ``` 57 | 58 | SROMPy can also be installed using the `git clone` command: 59 | 60 | ``` 61 | git clone https://github.com/nasa/SROMPy.git 62 | ``` 63 | 64 | The best way to get started with SROMPy is to take a look at the scripts in the examples/ directory. A simple example of propagating uncertainty through a spring mass system can be found in the examples/spring_mass/, while the examples/phm18/ directory contains scripts necessary to reproduce the results in the following conference paper on probabilistic prognostics: https://www.phmpapers.org/index.php/phmconf/article/view/551. For more information, see the source code documentation in docs/SROMPy_doc.pdf (a work in progress) or the technical report below that accompanied the release of SROMPy. 65 | 66 | Tests 67 | ------ 68 | The tests can be performed by running "py.test" from the tests/ directory to ensure a proper installation. 69 | 70 | Reference 71 | ------------- 72 | If you use SROMPy for your research, please cite the technical report: 73 | 74 | Warner, J. E. (2018). Stochastic reduced order models with Python (SROMPy). NASA/TM-2018-219824. 75 | 76 | The report can be found in the `docs/references` directory. Thanks! 77 | 78 | Developers 79 | ----------- 80 | 81 | UQ Center of Excellence
82 | NASA Langley Research Center
83 | Hampton, Virginia
84 | 85 | This software was funded by and developed under the High Performance Computing Incubator (HPCI) at NASA Langley Research Center.
86 | 87 | Contributors: James Warner (james.e.warner@nasa.gov), Luke Morrill, Juan Barrientos 88 | 89 | License 90 | --------- 91 | 92 | Copyright 2018 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. No copyright is claimed in the United States under Title 17, U.S. Code. All Other Rights Reserved. 93 | 94 | The Stochastic Reduced Order Models with Python (SROMPy) platform is licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. 95 | 96 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /SROMPy/__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 | name = "SROMPy" 17 | -------------------------------------------------------------------------------- /SROMPy/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 | 16 | name = "optimize" 17 | from .ObjectiveFunction import ObjectiveFunction 18 | from .Gradient import Gradient 19 | from .Optimizer import Optimizer 20 | 21 | -------------------------------------------------------------------------------- /SROMPy/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 | name = "postprocess" 17 | from .Postprocessor import Postprocessor 18 | -------------------------------------------------------------------------------- /SROMPy/srom/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 | """ 17 | Finite Difference static class for calculating gradients 18 | """ 19 | 20 | import copy 21 | import numpy as np 22 | 23 | 24 | class FiniteDifference(object): 25 | """ 26 | Class that contains static methods for assisting in computing gradients 27 | needed to implement the piecewise-linear SROM surrogate using the finite 28 | difference method. 29 | """ 30 | 31 | def __init__(self): 32 | pass 33 | 34 | @staticmethod 35 | def get_perturbed_samples(samples, perturbation_factor=None, 36 | perturbation_values=None): 37 | """ 38 | Returns the perturbed SROM samples that must be run through model 39 | to estimate gradients with finite difference. 40 | 41 | input: 42 | samples: np array (m x d) - original input srom samples 43 | perturbation_factor: float - if specified, computes the 44 | perturbation size in each dimension as 45 | (max_i - min_i)*perturbation_factor. 46 | max/min_i are the max/min sample values in dim. i. 47 | perturbation_values: list of float - if specified uses the values 48 | in the array for perturbations in each dimension. 49 | 50 | -Must specify either perturbation_factor or perturbation_values 51 | 52 | output: 53 | returns perturbed_samples: np array (m*d x d) 54 | samples = | x^(1)_1 + delta_1, ..., x^(1)_d | 55 | | ... , ..., ... | 56 | | x^(m)_1 + delta_1, ..., x^(m)_d | 57 | .... 58 | | x^(1)_1, ..., x^(1)_d + delta_d| 59 | | ... , ..., ... | 60 | | x^(m)_1, ..., x^(m)_d + delta_d| 61 | 62 | """ 63 | 64 | if perturbation_factor is None and perturbation_values is None: 65 | raise IOError("Must specify either perturbation_factor or " 66 | "perturbation_values") 67 | 68 | # Initialize FD samples array. 69 | # Handle 1 dimension case, adjust shape: 70 | if len(samples.shape) == 1: 71 | samples.shape = (len(samples), 1) 72 | (srom_size, dim) = samples.shape 73 | fd_samples = np.zeros((srom_size*dim, dim)) 74 | 75 | # Calculate perturbation_values from perturbation_factor if values 76 | # weren't specified: 77 | if perturbation_values is None: 78 | perturbation_values = np.array((dim, 1)) 79 | for i in range(dim): 80 | ran = np.max(samples[:, i]) - np.min(samples[:, i]) 81 | perturbation_values[i] = ran * perturbation_factor 82 | else: 83 | if len(perturbation_values) != dim: 84 | raise ValueError("Length of perturbation_values must equal " 85 | "dimension!") 86 | 87 | for i in range(dim): 88 | samples_i = copy.deepcopy(samples) 89 | samples_i[:, i] += perturbation_values[i] 90 | fd_samples[i*srom_size:(i+1)*srom_size, :] = samples_i 91 | 92 | return fd_samples 93 | 94 | @staticmethod 95 | def compute_gradient(outputs, perturbed_outputs, perturbation_values): 96 | """ 97 | Calculates gradients based on original sample outputs, perturbed 98 | sample outputs, and the size or perturbations. 99 | 100 | NOTE - it is being assumed here and other places that the output is 101 | scalar 102 | 103 | inputs: 104 | (mx1 array) 105 | outputs = | y(x^(1))| 106 | | ... | 107 | | y(x^(m))| 108 | 109 | (mxd array) 110 | perturbed_outputs = | y(x^(1) + delta_1), ..., y(x^(1)+ delta_d)| 111 | | ... , ..., ... | 112 | | y(x^(m) + delta_1), ..., y(x^(m)+delta_d)| 113 | 114 | (dx1 array) 115 | perturbed_values = [delta_1, ..., delta_d] 116 | 117 | outputs: 118 | (mxd array) 119 | gradients = | dy(x^{(1)})/dx_1, ..., dy(x^{(1)})/dx_d | 120 | | ... , ..., ... | 121 | | dy(x^{(m)})/dx_1, ..., dy(x^{(m)})/dx_d | 122 | """ 123 | 124 | if len(perturbed_outputs.shape) == 1: 125 | perturbed_outputs.shape = (len(perturbed_outputs), 1) 126 | (srom_size, dim) = perturbed_outputs.shape 127 | 128 | if len(outputs) != srom_size: 129 | raise ValueError("# output samples must match perturbed outputs") 130 | 131 | if len(perturbation_values) != dim: 132 | raise ValueError("length of perturbation_values must match " 133 | "dimension") 134 | 135 | gradients = np.zeros((srom_size, dim)) 136 | 137 | for i in range(dim): 138 | grad = ((perturbed_outputs[:, i] - outputs.flatten()) 139 | / perturbation_values[i]) 140 | gradients[:, i] = grad 141 | 142 | return gradients 143 | 144 | -------------------------------------------------------------------------------- /SROMPy/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 | name = "SROM" 17 | from .SROM import SROM 18 | from .SROMSurrogate import SROMSurrogate 19 | from .FiniteDifference import FiniteDifference 20 | -------------------------------------------------------------------------------- /SROMPy/target/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 | """ 17 | Class for implementing a beta random variable 18 | """ 19 | 20 | import numpy as np 21 | from scipy.stats import beta as scipy_beta 22 | 23 | from SROMPy.target.RandomVariable import RandomVariable 24 | 25 | 26 | class BetaRandomVariable(RandomVariable): 27 | """ 28 | Class for implementing a beta random variable 29 | """ 30 | 31 | def __init__(self, alpha, beta, shift=0, scale=1, max_moment=10): 32 | """ 33 | Initialize the beta random variable with the standard alpha and beta 34 | shape parameters (follows convention for a & b in numpy.random.beta). 35 | Optionally specify shift & scale parameters to translate and scale the 36 | random variable, e.g.: 37 | new_beta = shift + scale * standard_beta. 38 | 39 | If one wants to specify a beta random variable to match a given 40 | support (min, max), mean, and variance, use the static method 41 | get_beta_shape_params() to convert to inputs for this constructor. 42 | 43 | Implementation wraps scipy.stats.beta to get statistics/samples. 44 | """ 45 | 46 | if alpha < 0: 47 | raise ValueError("Alpha shape param must be non-negative") 48 | if beta < 0: 49 | raise ValueError("Beta shape param must be non-negative") 50 | if scale <= 0: 51 | raise ValueError("Scale param must be positive") 52 | 53 | self._alpha = alpha 54 | self._beta = beta 55 | self._shift = shift 56 | self._scale = scale 57 | self._moments = None 58 | 59 | # Set dimension (scalar), min/max. 60 | self._dim = 1 61 | self.mins = [shift] 62 | self.maxs = [shift + scale] 63 | 64 | # Cache moments. 65 | self.generate_moments(max_moment) 66 | self._max_moment = max_moment 67 | 68 | @staticmethod 69 | def get_beta_shape_params(min_value, max_value, mean, variance): 70 | """ 71 | Returns the beta shape parameters (alpha, beta) and the shift/scale 72 | parameters that produce a beta random variable with the specified 73 | minimum value, maximum value, mean, and variance. Can be called prior 74 | to initialization of this class if only this info is known about the 75 | random variable being modeled. 76 | Returns a list of length 4 ordered [alpha, beta, shift, scale] 77 | """ 78 | 79 | # Cast to make sure we have floats for calculations. 80 | min_value = float(min_value) 81 | max_value = float(max_value) 82 | mean_val = float(mean) 83 | variance = float(variance) 84 | 85 | # Scale mean/variance to lie in [0,1] for standard beta distribution. 86 | mean_std = (mean_val - min_value) / (max_value - min_value) 87 | var_std = (1. / (max_value - min_value)) ** 2.0 * variance 88 | 89 | # Get shape params based on scaled mean/variance: 90 | alpha = mean_std*(mean_std*(1. - mean_std) / var_std - 1.) 91 | beta = (mean_std*(1 - mean_std)/var_std - 1) - alpha 92 | shift = min_value 93 | scale = max_value - min_value 94 | 95 | return [alpha, beta, shift, scale] 96 | 97 | def get_variance(self): 98 | """ 99 | Returns variance of beta random variable 100 | """ 101 | a = self._alpha 102 | b = self._beta 103 | var = (a*b)/(((a+b)**2) * (a + b + 1))*self._scale**2 104 | return var 105 | 106 | def compute_moments(self, max_order): 107 | """ 108 | Returns moments up to order 'max_order' in numpy array. 109 | """ 110 | 111 | # TODO - calculate moments above max_moment on the fly & 112 | # append to stored 113 | if max_order <= self._max_moment: 114 | moments = self._moments[:max_order] 115 | else: 116 | raise NotImplementedError("Moment above max_moment not handled yet") 117 | 118 | return moments 119 | 120 | def compute_cdf(self, x_grid): 121 | """ 122 | Returns numpy array of beta CDF values at the points contained in x_grid 123 | """ 124 | 125 | return scipy_beta.cdf(x_grid, self._alpha, self._beta, self._shift, 126 | self._scale) 127 | 128 | def compute_inv_cdf(self, x_grid): 129 | """ 130 | Returns np array of inverse beta CDF values at pts in x_grid 131 | """ 132 | return scipy_beta.ppf(x_grid, self._alpha, self._beta, self._shift, 133 | self._scale) 134 | 135 | def compute_pdf(self, x_grid): 136 | """ 137 | Returns numpy array of beta pdf values at the points contained in x_grid 138 | """ 139 | return scipy_beta.pdf(x_grid, self._alpha, self._beta, self._shift, 140 | self._scale) 141 | 142 | def draw_random_sample(self, sample_size): 143 | """ 144 | Draws random samples from the beta random variable. Returns numpy 145 | array of length 'sample_size' containing these samples 146 | """ 147 | 148 | # Use scipy beta rv to return shifted/scaled samples automatically. 149 | return scipy_beta.rvs(self._alpha, self._beta, self._shift, self._scale, 150 | sample_size) 151 | 152 | def generate_moments(self, max_moment): 153 | """ 154 | Calculate & store moments to retrieve more efficiently later 155 | """ 156 | 157 | self._moments = np.zeros((max_moment, 1)) 158 | 159 | # Rely on scipy.stats to return non-central moment. 160 | for i in range(max_moment): 161 | self._moments[i] = scipy_beta.moment(i + 1, self._alpha, self._beta, 162 | self._shift, self._scale) 163 | -------------------------------------------------------------------------------- /SROMPy/target/DiscreteRandomVector.py: -------------------------------------------------------------------------------- 1 | """ 2 | Class for defining a discrete random vector as a target to be matched with a 3 | SROM. Similar to the sample-based random vector, but in general will have 4 | probabilities that are not equal. 5 | """ 6 | 7 | import numpy as np 8 | 9 | from SROMPy.target.RandomVector import RandomVector 10 | 11 | 12 | class DiscreteRandomVector(RandomVector): 13 | """ 14 | Discrete random vector. Defines a target that can be matched with a SROM 15 | that is created from samples and corresponding probabilities. Implements 16 | basic discrete statistics (similar to those of an SROM). 17 | 18 | :param samples: set of realizations/samples of the random vector 19 | :type samples: np array, size: (# samples x dim) 20 | :param probabilities: probabilties associated with each sample 21 | :type probabilities: np array, length = # samples 22 | :param max_moment: max. order moment to precompute and store 23 | :type max_moment: int 24 | """ 25 | 26 | def __init__(self, samples, probabilities, max_moment=10): 27 | 28 | # Check for 1D case (random variable). 29 | if len(samples.shape) == 1: 30 | samples = samples.reshape((len(samples), 1)) 31 | 32 | self._validate_inputs(samples, probabilities) 33 | 34 | self._set_member_variables(samples, probabilities, max_moment) 35 | 36 | # Cache statistics so they can be returned quickly later. 37 | self._precompute_moments() 38 | self._precompute_correlation_matrix() 39 | 40 | self._cdf_x_grid_cache = None 41 | self._cdf_cache = None 42 | 43 | def compute_moments(self, max_order): 44 | """ 45 | Return precomputed moments up to specified order. 46 | 47 | :param max_order: Maximum order of moments to return 48 | :type max_order: int 49 | 50 | Returns (max_order x dim) size Numpy array with SROM moments for 51 | each dimension. 52 | """ 53 | 54 | # TODO - calculate moments above max_moment on the fly & 55 | # append to stored 56 | if max_order <= self._max_moment: 57 | moments = self._moments[:max_order, :] 58 | else: 59 | raise NotImplementedError("Moment above max_moment not handled yet") 60 | 61 | return moments 62 | 63 | def compute_cdf(self, x_grid): 64 | """ 65 | Computes the marginal CDF values in each dimension. 66 | 67 | :param x_grid: Grid of points to compute CDF values on. If 1d array is 68 | provided, the same points are used to evaluate CDF in each 69 | dimension. If 2d array is provided, calculates CDF values on 70 | different points, but must have same # points for each dimension. 71 | Size is (# grid pts) x (dim) or (# grid pts) x (1). 72 | :type x_grid: Numpy array. 73 | 74 | Returns: Numpy array of CDF values at x_grid points. Size is (# grid 75 | pts) x (dim). 76 | 77 | Note: 78 | * Increasing the number of grid points can significantly slow 79 | down the SROM optimization problem. 80 | * Providing a 2d array for x_grid can specify a different range 81 | of values for each dimension, but must use the same number of pts. 82 | """ 83 | 84 | # Account for 1d random variable. 85 | if len(x_grid.shape) == 1: 86 | x_grid = x_grid.reshape((len(x_grid), 1)) 87 | (num_pts, dim) = x_grid.shape 88 | 89 | # If only one grid was provided for multiple dims, repeat to generalize 90 | if (dim == 1) and (self._dim > 1): 91 | x_grid = np.repeat(x_grid, self._dim, axis=1) 92 | 93 | # Check if we've computed/stored cdf values for this x_grid: 94 | cache_flag = self._is_cdf_cached(x_grid) 95 | 96 | if cache_flag: 97 | return self._cdf_cache 98 | else: 99 | 100 | cdf_values = np.zeros((num_pts, self._dim)) 101 | 102 | # Vectorized indicator implementation for CDF 103 | # CDF(x) = sum_{k=1}^m 1( sample^(k) < x) prob^(k) 104 | for i, grid in enumerate(x_grid.T): 105 | for k, sample in enumerate(self._samples): 106 | indices = grid >= sample[i] 107 | cdf_values[indices, i] += self._probabilities[k] 108 | 109 | # Cache these values to return next time: 110 | self._cdf_x_grid_cache = x_grid 111 | self._cdf_cache = cdf_values 112 | 113 | return cdf_values 114 | 115 | def compute_correlation_matrix(self): 116 | """ 117 | Returns precomputed correlation matrix. 118 | """ 119 | return self._corr_matrix 120 | 121 | def draw_random_sample(self, sample_size): 122 | """ 123 | Randomly draws a sample of this random vector. 124 | 125 | :param sample_size: number of samples to return 126 | :type sample_size: int 127 | 128 | sample_size must be smaller than total # of samples. For discrete 129 | random vector, we return a randomly selected # of samples 130 | """ 131 | 132 | if sample_size > self._num_samples: 133 | raise ValueError("Sample size can't be more than total # samples") 134 | 135 | # Generate random indices for samples array. 136 | all_indices = np.arange(self._num_samples) 137 | random_indices = np.random.choice(all_indices, sample_size, 138 | replace=False) 139 | 140 | sample = self._samples[random_indices, :] 141 | 142 | return sample 143 | 144 | def _precompute_moments(self): 145 | """ 146 | Precomputes and stores moments and stores in moments member variable 147 | array. 148 | """ 149 | 150 | self._moments = np.zeros((self._max_moment, self._dim)) 151 | 152 | for order in range(self._max_moment): 153 | 154 | # moment_q = sum_{k=1}^m p(k) * x(k)^q 155 | moment_q = np.zeros((1, self._dim)) 156 | for k, sample in enumerate(self._samples): 157 | moment_q = moment_q + self._probabilities[k] * \ 158 | pow(sample, order+1) 159 | 160 | self._moments[order, :] = moment_q 161 | 162 | def _precompute_correlation_matrix(self): 163 | """ 164 | Precomputes and stores correlation matrix and stores in 165 | "_corr_matrix" member variable array. 166 | """ 167 | corr = np.zeros((self._dim, self._dim)) 168 | 169 | for k, sample in enumerate(self._samples): 170 | corr = corr + np.outer(sample, sample) * self._probabilities[k] 171 | 172 | self._corr_matrix = corr 173 | 174 | def _is_cdf_cached(self, x_grid): 175 | """ 176 | Checks to see if we've already computed CDF values for this particular 177 | x-grid, returns True if so 178 | """ 179 | 180 | # Indicates we haven't calculated any cdfs yet. 181 | if self._cdf_x_grid_cache is None: 182 | return False 183 | 184 | return np.array_equal(self._cdf_x_grid_cache, x_grid) 185 | 186 | def _set_member_variables(self, samples, probabilities, max_moment): 187 | """ 188 | Sets all member variables 189 | """ 190 | 191 | (num_samples, dim) = samples.shape 192 | self._samples = samples 193 | self._probabilities = probabilities 194 | self._max_moment = max_moment 195 | self._num_samples = num_samples 196 | 197 | # Initialize cached cdf/x values to optimize performance. 198 | self._cdf_x_grid_cache = None 199 | self._cdf_cache = None 200 | 201 | # min/max sample values needed for SROM optimization. 202 | self.mins = np.min(samples, axis=0) 203 | self.maxs = np.max(samples, axis=0) 204 | 205 | # Parent class (RandomVector) constructor, sets self._dim. 206 | super(DiscreteRandomVector, self).__init__(dim) 207 | 208 | @staticmethod 209 | def _validate_inputs(samples, probabilities): 210 | """ 211 | Check shapes/sizes/types? of arrays for samples/probabilities and proper 212 | probabilities 213 | """ 214 | 215 | (num_samples, dim) = samples.shape 216 | num_probabilities = len(probabilities) 217 | 218 | if num_samples != num_probabilities: 219 | msg = "Length of probability array must match # of samples" 220 | raise ValueError(msg) 221 | 222 | if num_samples < dim: 223 | msg = "Number of samples is less than dim, check sample array shape" 224 | raise ValueError(msg) 225 | 226 | if (probabilities < 0).any(): 227 | raise ValueError("Probabilities cannot be negative!") 228 | 229 | if not np.isclose(np.sum(probabilities), 1.0): 230 | raise ValueError("Probabilities must sum to one!") 231 | -------------------------------------------------------------------------------- /SROMPy/target/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 | """ 17 | Class for implementing a gamma random variable 18 | """ 19 | 20 | import numpy as np 21 | from scipy.stats import gamma as scipygamma 22 | 23 | from SROMPy.target.RandomVariable import RandomVariable 24 | 25 | 26 | class GammaRandomVariable(RandomVariable): 27 | """ 28 | Class for implementing a gamma random variable 29 | """ 30 | 31 | def __init__(self, alpha, shift=0, scale=1, max_moment=10): 32 | """ 33 | Initialize the gamma random variable with the standard alpha 34 | shape parameter (follows convention for a in scipy.stats.gamma). 35 | Optionally specify shift & scale parameters to translate and scale the 36 | random variable, e.g.: 37 | new_gamma = shift + scale * standard_gamma. 38 | 39 | Implementation wraps scipy.stats.gamma to get statistics/samples. 40 | """ 41 | 42 | if alpha < 0: 43 | raise ValueError("Alpha shape param must be non-negative") 44 | if scale <= 0: 45 | raise ValueError("Scale param must be positive") 46 | 47 | self._alpha = alpha 48 | self._shift = shift 49 | self._scale = scale 50 | self._moments = None 51 | 52 | # Set dimension (scalar), min/max. 53 | self._dim = 1 54 | self.mins = [shift] 55 | 56 | # NOTE Gamma max is technically infinite, do this on variance (3 STDs)? 57 | self.maxs = [shift + 2 * self.get_variance() ** 0.5] 58 | 59 | # Cache moments. 60 | self.generate_moments(max_moment) 61 | self._max_moment = max_moment 62 | 63 | def get_variance(self): 64 | """ 65 | Returns variance of gamma random variable 66 | """ 67 | return scipygamma.var(self._alpha, self._shift, self._scale) 68 | 69 | def compute_moments(self, max_order): 70 | """ 71 | Returns moments up to order 'max_order' in numpy array. 72 | """ 73 | 74 | # TODO - calculate moments above max_moment on the fly & 75 | # append to stored 76 | if max_order <= self._max_moment: 77 | moments = self._moments[:max_order] 78 | else: 79 | raise NotImplementedError("Moment above max_moment not handled yet") 80 | 81 | return moments 82 | 83 | def compute_cdf(self, x_grid): 84 | """ 85 | Returns numpy array of gamma CDF values at the points contained in x_grid 86 | """ 87 | 88 | return scipygamma.cdf(x_grid, self._alpha, self._shift, self._scale) 89 | 90 | def compute_inv_cdf(self, x_grid): 91 | """ 92 | Returns np array of inverse gamma CDF values at pts in x_grid 93 | """ 94 | return scipygamma.ppf(x_grid, self._alpha, self._shift, self._scale) 95 | 96 | def compute_pdf(self, x_grid): 97 | """ 98 | Returns numpy array of gamma pdf values at the points contained 99 | in x_grid 100 | """ 101 | return scipygamma.pdf(x_grid, self._alpha, self._shift, self._scale) 102 | 103 | def draw_random_sample(self, sample_sz): 104 | """ 105 | Draws random samples from the gamma random variable. Returns numpy 106 | array of length 'sample_size' containing these samples 107 | """ 108 | 109 | # Use scipy gamma rv to return shifted/scaled samples automatically. 110 | return scipygamma.rvs(self._alpha, self._shift, self._scale, sample_sz) 111 | 112 | def generate_moments(self, max_moment): 113 | """ 114 | Calculate & store moments to retrieve more efficiently later 115 | """ 116 | 117 | self._moments = np.zeros((max_moment, 1)) 118 | 119 | # Rely on scipy.stats to return non-central moment. 120 | for i in range(max_moment): 121 | self._moments[i] = scipygamma.moment(i+1, self._alpha, self._shift, 122 | self._scale) 123 | -------------------------------------------------------------------------------- /SROMPy/target/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 | """ 17 | Class for defining a normal random variable 18 | """ 19 | 20 | import numpy as np 21 | from scipy.stats import norm as scipy_normal 22 | 23 | from SROMPy.target.RandomVariable import RandomVariable 24 | 25 | 26 | class NormalRandomVariable(RandomVariable): 27 | """ 28 | Class for defining a normal random variable 29 | """ 30 | 31 | def __init__(self, mean=0., std_dev=1.0, max_moment=10): 32 | """ 33 | Initialize the normal (gaussian) random variable with provided mean 34 | and standard deviation. Implementation wraps scipy.stats.norm to get 35 | statistics/samples. 36 | """ 37 | 38 | if std_dev <= 0: 39 | raise ValueError("Normal standard deviation must be positive") 40 | 41 | self._mean = mean 42 | self._std = std_dev 43 | self._moments = None 44 | 45 | # Set dimension (scalar), min/max to equal mean +/- 4stds. 46 | self._dim = 1 47 | self.mins = [mean - 4. * std_dev] 48 | self.maxs = [mean + 4. * std_dev] 49 | 50 | # Cache moments 51 | self.generate_moments(max_moment) 52 | self._max_moment = max_moment 53 | 54 | def get_variance(self): 55 | """ 56 | Returns variance of normal random variable 57 | """ 58 | return self._std**2.0 59 | 60 | def compute_moments(self, max_order): 61 | """ 62 | Returns moments up to order 'max_order' in numpy array. 63 | """ 64 | 65 | # TODO - calculate moments above max_moment on the fly & 66 | # append to stored 67 | if max_order <= self._max_moment: 68 | moments = self._moments[:max_order] 69 | else: 70 | raise NotImplementedError("Moment above max_moment not handled yet") 71 | 72 | return moments 73 | 74 | def compute_cdf(self, x_grid): 75 | """ 76 | Returns numpy array of normal CDF values at the points contained 77 | in x_grid 78 | """ 79 | 80 | return scipy_normal.cdf(x_grid, self._mean, self._std) 81 | 82 | def compute_inv_cdf(self, x_grid): 83 | """ 84 | Returns np array of inverse normal CDF values at pts in x_grid 85 | """ 86 | return scipy_normal.ppf(x_grid, self._mean, self._std) 87 | 88 | def compute_pdf(self, x_grid): 89 | """ 90 | Returns numpy array of normal pdf values at the points contained 91 | in x_grid 92 | """ 93 | return scipy_normal.pdf(x_grid, self._mean, self._std) 94 | 95 | def draw_random_sample(self, sample_size): 96 | """ 97 | Draws random samples from the normal random variable. Returns numpy 98 | array of length 'sample_size' containing these samples 99 | """ 100 | 101 | # Use scipy normal rv to return shifted/scaled samples automatically. 102 | return scipy_normal.rvs(self._mean, self._std, sample_size) 103 | 104 | def generate_moments(self, max_moment): 105 | """ 106 | Calculate & store moments to retrieve more efficiently later 107 | """ 108 | 109 | self._moments = np.zeros((max_moment, 1)) 110 | 111 | # Rely on scipy.stats to return non-central moment. 112 | for i in range(max_moment): 113 | self._moments[i] = scipy_normal.moment(i + 1, self._mean, self._std) 114 | -------------------------------------------------------------------------------- /SROMPy/target/RandomEntity.py: -------------------------------------------------------------------------------- 1 | """ 2 | Abstract class providing a base class for RandomVariable and RandomVector. 3 | """ 4 | 5 | 6 | class RandomEntity(object): 7 | 8 | pass 9 | -------------------------------------------------------------------------------- /SROMPy/target/RandomVariable.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 abc 17 | from SROMPy.target.RandomEntity import RandomEntity 18 | 19 | """ 20 | Abstract class defining the target random variable being matched by an SROM. 21 | Inherited by BetaRandomVariable and GammaRandomVariable, 22 | and NormalRandomVariable. 23 | """ 24 | 25 | 26 | class RandomVariable(RandomEntity): 27 | 28 | @abc.abstractmethod 29 | def get_variance(self, max_order): 30 | return 31 | 32 | @abc.abstractmethod 33 | def compute_moments(self, x_grid): 34 | return 35 | 36 | @abc.abstractmethod 37 | def compute_cdf(self): 38 | return 39 | 40 | @abc.abstractmethod 41 | def compute_inv_cdf(self, sample_size): 42 | return 43 | 44 | @abc.abstractmethod 45 | def compute_pdf(self): 46 | return 47 | 48 | @abc.abstractmethod 49 | def draw_random_sample(self): 50 | return 51 | 52 | @abc.abstractmethod 53 | def generate_moments(self): 54 | return 55 | -------------------------------------------------------------------------------- /SROMPy/target/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 abc 17 | from SROMPy.target.RandomEntity import RandomEntity 18 | 19 | ''' 20 | Abstract class defining the target random vector being matched by an SROM. 21 | Inherited by AnalyticRandomVector and SampleRandomVector to define analytically 22 | specified and sample-based random vectors, respectively. 23 | ''' 24 | 25 | 26 | class RandomVector(RandomEntity): 27 | 28 | def __init__(self, dim): 29 | 30 | self._dim = int(dim) 31 | 32 | @property 33 | def dim(self): 34 | return self._dim 35 | 36 | @abc.abstractmethod 37 | def compute_moments(self, max_order): 38 | return 39 | 40 | @abc.abstractmethod 41 | def compute_cdf(self, x_grid): 42 | return 43 | 44 | @abc.abstractmethod 45 | def compute_correlation_matrix(self): 46 | return 47 | 48 | @abc.abstractmethod 49 | def draw_random_sample(self, sample_size): 50 | return 51 | -------------------------------------------------------------------------------- /SROMPy/target/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 | """ 17 | Class for defining a uniform random variable 18 | """ 19 | 20 | import numpy as np 21 | from scipy.stats import uniform as scipy_uniform 22 | 23 | from SROMPy.target.RandomVariable import RandomVariable 24 | 25 | 26 | class UniformRandomVariable(RandomVariable): 27 | """ 28 | Class for defining a uniform random variable 29 | """ 30 | 31 | def __init__(self, min_val=0., max_val=0., max_moment=10): 32 | """ 33 | Initialize the uniform (gaussian) random variable with provided 34 | minimum/maximum values. Implementation wraps scipy.stats.uniform to get 35 | statistics/samples. Caches moments up to max_moment for speedup. 36 | """ 37 | 38 | if min_val >= max_val: 39 | raise ValueError("Minimum value must be less than maximum value") 40 | 41 | self._minimum_value = min_val 42 | self._range_size = max_val - min_val 43 | self._moments = None 44 | 45 | # Set dimension (scalar), min/max to equal mean +/- 4stds. 46 | self.dim = 1 47 | self.mins = [min_val] 48 | self.maxs = [max_val] 49 | 50 | # Cache moments. 51 | self.generate_moments(max_moment) 52 | self._max_moment = max_moment 53 | 54 | def get_variance(self): 55 | """ 56 | Returns variance of uniform random variable 57 | """ 58 | return self._std**2.0 59 | 60 | def compute_moments(self, max_order): 61 | """ 62 | Returns moments up to order 'max_order' in numpy array. 63 | """ 64 | 65 | # TODO - calculate moments above max_moment on the fly & 66 | # append to stored 67 | if max_order <= self._max_moment: 68 | moments = self._moments[:max_order] 69 | else: 70 | raise NotImplementedError("Moment above max_moment not handled yet") 71 | 72 | return moments 73 | 74 | def compute_cdf(self, x_grid): 75 | """ 76 | Returns numpy array of uniform CDF values at the points contained 77 | in x_grid. 78 | """ 79 | 80 | return scipy_uniform.cdf(x_grid, self._minimum_value, self._range_size) 81 | 82 | def compute_inv_cdf(self, x_grid): 83 | """ 84 | Returns np array of inverse uniform CDF values at pts in x_grid 85 | """ 86 | return scipy_uniform.ppf(x_grid, self._minimum_value, self._range_size) 87 | 88 | def compute_pdf(self, x_grid): 89 | """ 90 | Returns numpy array of uniform pdf values at the points contained 91 | in x_grid 92 | """ 93 | return scipy_uniform.pdf(x_grid, self._minimum_value, self._range_size) 94 | 95 | def draw_random_sample(self, sample_size): 96 | """ 97 | Draws random samples from the uniform random variable. Returns numpy 98 | array of length 'sample_size' containing these samples 99 | """ 100 | 101 | # Use scipy uniform rv to return shifted/scaled samples automatically. 102 | return scipy_uniform.rvs(self._minimum_value, self._range_size, 103 | sample_size) 104 | 105 | def generate_moments(self, max_moment): 106 | """ 107 | Calculate & store moments to retrieve more efficiently later 108 | """ 109 | 110 | self._moments = np.zeros((max_moment, 1)) 111 | 112 | # Rely on scipy.stats to return non-central moment. 113 | for i in range(max_moment): 114 | self._moments[i] = scipy_uniform.moment(i + 1, self._minimum_value, 115 | self._range_size) 116 | -------------------------------------------------------------------------------- /SROMPy/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 | name = "target" 17 | from .AnalyticRandomVector import AnalyticRandomVector 18 | from .BetaRandomVariable import BetaRandomVariable 19 | from .DiscreteRandomVector import DiscreteRandomVector 20 | from .GammaRandomVariable import GammaRandomVariable 21 | from .NormalRandomVariable import NormalRandomVariable 22 | from .RandomVariable import RandomVariable 23 | from .RandomVector import RandomVector 24 | from .SampleRandomVector import SampleRandomVector 25 | from .UniformRandomVariable import UniformRandomVariable 26 | -------------------------------------------------------------------------------- /docs/SROMPy_doc.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/SROMPy_doc.pdf -------------------------------------------------------------------------------- /docs/_build/html/.buildinfo: -------------------------------------------------------------------------------- 1 | # Sphinx build info version 1 2 | # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. 3 | config: 07582fd2dbce8a3fac0655334bd002aa 4 | tags: 645f666f9bcd5a90fca523b33c5a78b7 5 | -------------------------------------------------------------------------------- /docs/_build/html/_images/disp_CDFs_pw_constant.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/disp_CDFs_pw_constant.png -------------------------------------------------------------------------------- /docs/_build/html/_images/disp_CDFs_pw_linear.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/disp_CDFs_pw_linear.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/02e99335fa7566885ffc47f9d1d14dd30bff14cb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/02e99335fa7566885ffc47f9d1d14dd30bff14cb.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/032ffd36302c5d12a2f2e5b029c92c5015455208.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/032ffd36302c5d12a2f2e5b029c92c5015455208.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/1d281d91e34a74f064c179fd70612c7bfe765eaa.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/1d281d91e34a74f064c179fd70612c7bfe765eaa.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/307b3725cbb03398131f9ca542d79aff4933195f.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/307b3725cbb03398131f9ca542d79aff4933195f.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/3666981dc77862de77b6ecfcb64aad59b425cbaf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/3666981dc77862de77b6ecfcb64aad59b425cbaf.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/3f2fdf96d3bf24c77cfcc7d5a41069bbcd828a71.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/3f2fdf96d3bf24c77cfcc7d5a41069bbcd828a71.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/40708f3d3ce870020c1bd88b8b4d8aec109c5f6e.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/40708f3d3ce870020c1bd88b8b4d8aec109c5f6e.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/410a9d0df9c135dd73b269cba7ef04dcfd932b1f.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/410a9d0df9c135dd73b269cba7ef04dcfd932b1f.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/5635a7c34414599c2452d72430811e816b460335.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/5635a7c34414599c2452d72430811e816b460335.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/58feb749986ef5862e812ca6c32b924a2f7aca6c.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/58feb749986ef5862e812ca6c32b924a2f7aca6c.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/666f10b1d5338fe962e81b37cefb54d6633fd29f.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/666f10b1d5338fe962e81b37cefb54d6633fd29f.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/678113eb2ebf18c078cf3e4cff8e8aac2f347485.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/678113eb2ebf18c078cf3e4cff8e8aac2f347485.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/683f2dd9129a91d21aaf1c04afa6f78b39d4cb0a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/683f2dd9129a91d21aaf1c04afa6f78b39d4cb0a.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/7c3feb481455fd0d728caa23fd6d452e41728198.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/7c3feb481455fd0d728caa23fd6d452e41728198.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/877d234f4cec6974ce218fc2e975a486a7972dfd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/877d234f4cec6974ce218fc2e975a486a7972dfd.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/88342b20a6b5fba2b278a773e8ef013b315593af.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/88342b20a6b5fba2b278a773e8ef013b315593af.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/89c0eb02cd0320e298c606fba3c33cdcee62c413.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/89c0eb02cd0320e298c606fba3c33cdcee62c413.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/8b25e6d1d67015300bc0d13c686a6410a47a7d3a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/8b25e6d1d67015300bc0d13c686a6410a47a7d3a.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/9ff109b8cdf1585b2fd1f195f1e2b51ca3ebc027.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/9ff109b8cdf1585b2fd1f195f1e2b51ca3ebc027.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/a4f983455bdb6ec51b3fdaa4d3ddc93e712f4c75.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/a4f983455bdb6ec51b3fdaa4d3ddc93e712f4c75.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/ad7538581b1f02e87be67296fedce555dc704479.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/ad7538581b1f02e87be67296fedce555dc704479.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/af115195c8b6c13c7f47455427b364a26eef1356.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/af115195c8b6c13c7f47455427b364a26eef1356.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/b125a026740c3cb29d8f1b0bef027d3e0be86939.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/b125a026740c3cb29d8f1b0bef027d3e0be86939.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/b9228c12487f73d548763c61745e3cf8e492cfd2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/b9228c12487f73d548763c61745e3cf8e492cfd2.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/bcb2457ac9d8995a4f34d57cadac7ecbbe58f3bd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/bcb2457ac9d8995a4f34d57cadac7ecbbe58f3bd.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/d748cfdac5dabbf89592b7f10bc320c27d98ebc3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/d748cfdac5dabbf89592b7f10bc320c27d98ebc3.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/ef2f48e90f954011166511275c879f923b479f04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/ef2f48e90f954011166511275c879f923b479f04.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/fdd92017f5b9e8043b027461d74ddd99c720079c.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/fdd92017f5b9e8043b027461d74ddd99c720079c.png -------------------------------------------------------------------------------- /docs/_build/html/_images/math/fed776613749e7ff592fc8648bbd65278d6a7dae.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/math/fed776613749e7ff592fc8648bbd65278d6a7dae.png -------------------------------------------------------------------------------- /docs/_build/html/_images/spring_mass_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/spring_mass_diagram.png -------------------------------------------------------------------------------- /docs/_build/html/_images/stiffness_CDFs.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/stiffness_CDFs.pdf -------------------------------------------------------------------------------- /docs/_build/html/_images/stiffness_CDFs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_images/stiffness_CDFs.png -------------------------------------------------------------------------------- /docs/_build/html/_sources/index.rst.txt: -------------------------------------------------------------------------------- 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/_build/html/_sources/index.txt: -------------------------------------------------------------------------------- 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/_build/html/_sources/intro.rst.txt: -------------------------------------------------------------------------------- 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/_build/html/_sources/intro.txt: -------------------------------------------------------------------------------- 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/_build/html/_sources/source_code.rst.txt: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /docs/_build/html/_sources/source_code.txt: -------------------------------------------------------------------------------- 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:: 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:: target 27 | .. autoclass:: NormalRandomVariable 28 | :members: 29 | .. autoclass:: BetaRandomVariable 30 | :members: 31 | .. autoclass:: GammaRandomVariable 32 | :members: 33 | .. autoclass:: AnalyticRV 34 | :members: 35 | .. autoclass:: SampleRV 36 | :members: 37 | 38 | Postprocessor Documentation 39 | ---------------------------- 40 | 41 | .. automodule:: postprocess 42 | .. autoclass:: Postprocessor 43 | :members: 44 | 45 | -------------------------------------------------------------------------------- /docs/_build/html/_static/ajax-loader.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/ajax-loader.gif -------------------------------------------------------------------------------- /docs/_build/html/_static/comment-bright.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/comment-bright.png -------------------------------------------------------------------------------- /docs/_build/html/_static/comment-close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/comment-close.png -------------------------------------------------------------------------------- /docs/_build/html/_static/comment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/comment.png -------------------------------------------------------------------------------- /docs/_build/html/_static/custom.css: -------------------------------------------------------------------------------- 1 | /* This file intentionally left blank. */ 2 | -------------------------------------------------------------------------------- /docs/_build/html/_static/documentation_options.js: -------------------------------------------------------------------------------- 1 | var DOCUMENTATION_OPTIONS = { 2 | URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), 3 | VERSION: '1.0', 4 | LANGUAGE: 'None', 5 | COLLAPSE_INDEX: false, 6 | FILE_SUFFIX: '.html', 7 | HAS_SOURCE: true, 8 | SOURCELINK_SUFFIX: '.txt', 9 | NAVIGATION_WITH_KEYS: false, 10 | }; -------------------------------------------------------------------------------- /docs/_build/html/_static/down-pressed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/down-pressed.png -------------------------------------------------------------------------------- /docs/_build/html/_static/down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/down.png -------------------------------------------------------------------------------- /docs/_build/html/_static/file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/file.png -------------------------------------------------------------------------------- /docs/_build/html/_static/minus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/minus.png -------------------------------------------------------------------------------- /docs/_build/html/_static/plus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/plus.png -------------------------------------------------------------------------------- /docs/_build/html/_static/pygments.css: -------------------------------------------------------------------------------- 1 | .highlight .hll { background-color: #ffffcc } 2 | .highlight { background: #eeffcc; } 3 | .highlight .c { color: #408090; font-style: italic } /* Comment */ 4 | .highlight .err { border: 1px solid #FF0000 } /* Error */ 5 | .highlight .k { color: #007020; font-weight: bold } /* Keyword */ 6 | .highlight .o { color: #666666 } /* Operator */ 7 | .highlight .ch { color: #408090; font-style: italic } /* Comment.Hashbang */ 8 | .highlight .cm { color: #408090; font-style: italic } /* Comment.Multiline */ 9 | .highlight .cp { color: #007020 } /* Comment.Preproc */ 10 | .highlight .cpf { color: #408090; font-style: italic } /* Comment.PreprocFile */ 11 | .highlight .c1 { color: #408090; font-style: italic } /* Comment.Single */ 12 | .highlight .cs { color: #408090; background-color: #fff0f0 } /* Comment.Special */ 13 | .highlight .gd { color: #A00000 } /* Generic.Deleted */ 14 | .highlight .ge { font-style: italic } /* Generic.Emph */ 15 | .highlight .gr { color: #FF0000 } /* Generic.Error */ 16 | .highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */ 17 | .highlight .gi { color: #00A000 } /* Generic.Inserted */ 18 | .highlight .go { color: #333333 } /* Generic.Output */ 19 | .highlight .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */ 20 | .highlight .gs { font-weight: bold } /* Generic.Strong */ 21 | .highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ 22 | .highlight .gt { color: #0044DD } /* Generic.Traceback */ 23 | .highlight .kc { color: #007020; font-weight: bold } /* Keyword.Constant */ 24 | .highlight .kd { color: #007020; font-weight: bold } /* Keyword.Declaration */ 25 | .highlight .kn { color: #007020; font-weight: bold } /* Keyword.Namespace */ 26 | .highlight .kp { color: #007020 } /* Keyword.Pseudo */ 27 | .highlight .kr { color: #007020; font-weight: bold } /* Keyword.Reserved */ 28 | .highlight .kt { color: #902000 } /* Keyword.Type */ 29 | .highlight .m { color: #208050 } /* Literal.Number */ 30 | .highlight .s { color: #4070a0 } /* Literal.String */ 31 | .highlight .na { color: #4070a0 } /* Name.Attribute */ 32 | .highlight .nb { color: #007020 } /* Name.Builtin */ 33 | .highlight .nc { color: #0e84b5; font-weight: bold } /* Name.Class */ 34 | .highlight .no { color: #60add5 } /* Name.Constant */ 35 | .highlight .nd { color: #555555; font-weight: bold } /* Name.Decorator */ 36 | .highlight .ni { color: #d55537; font-weight: bold } /* Name.Entity */ 37 | .highlight .ne { color: #007020 } /* Name.Exception */ 38 | .highlight .nf { color: #06287e } /* Name.Function */ 39 | .highlight .nl { color: #002070; font-weight: bold } /* Name.Label */ 40 | .highlight .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */ 41 | .highlight .nt { color: #062873; font-weight: bold } /* Name.Tag */ 42 | .highlight .nv { color: #bb60d5 } /* Name.Variable */ 43 | .highlight .ow { color: #007020; font-weight: bold } /* Operator.Word */ 44 | .highlight .w { color: #bbbbbb } /* Text.Whitespace */ 45 | .highlight .mb { color: #208050 } /* Literal.Number.Bin */ 46 | .highlight .mf { color: #208050 } /* Literal.Number.Float */ 47 | .highlight .mh { color: #208050 } /* Literal.Number.Hex */ 48 | .highlight .mi { color: #208050 } /* Literal.Number.Integer */ 49 | .highlight .mo { color: #208050 } /* Literal.Number.Oct */ 50 | .highlight .sa { color: #4070a0 } /* Literal.String.Affix */ 51 | .highlight .sb { color: #4070a0 } /* Literal.String.Backtick */ 52 | .highlight .sc { color: #4070a0 } /* Literal.String.Char */ 53 | .highlight .dl { color: #4070a0 } /* Literal.String.Delimiter */ 54 | .highlight .sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */ 55 | .highlight .s2 { color: #4070a0 } /* Literal.String.Double */ 56 | .highlight .se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */ 57 | .highlight .sh { color: #4070a0 } /* Literal.String.Heredoc */ 58 | .highlight .si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */ 59 | .highlight .sx { color: #c65d09 } /* Literal.String.Other */ 60 | .highlight .sr { color: #235388 } /* Literal.String.Regex */ 61 | .highlight .s1 { color: #4070a0 } /* Literal.String.Single */ 62 | .highlight .ss { color: #517918 } /* Literal.String.Symbol */ 63 | .highlight .bp { color: #007020 } /* Name.Builtin.Pseudo */ 64 | .highlight .fm { color: #06287e } /* Name.Function.Magic */ 65 | .highlight .vc { color: #bb60d5 } /* Name.Variable.Class */ 66 | .highlight .vg { color: #bb60d5 } /* Name.Variable.Global */ 67 | .highlight .vi { color: #bb60d5 } /* Name.Variable.Instance */ 68 | .highlight .vm { color: #bb60d5 } /* Name.Variable.Magic */ 69 | .highlight .il { color: #208050 } /* Literal.Number.Integer.Long */ -------------------------------------------------------------------------------- /docs/_build/html/_static/up-pressed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/up-pressed.png -------------------------------------------------------------------------------- /docs/_build/html/_static/up.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/_static/up.png -------------------------------------------------------------------------------- /docs/_build/html/index.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | Welcome to SROMPy’s documentation! — SROMPy 1.0 documentation 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 |
31 |
32 | 33 | 34 | 70 | 71 |
72 |
73 | 121 |
122 |
123 | 134 | 135 | 136 | 137 | 138 | 139 | -------------------------------------------------------------------------------- /docs/_build/html/intro.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | Introduction — SROMPy 1.0 documentation 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
32 |
33 | 34 | 35 |
36 | 37 |
38 |

Introduction

39 |

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.

40 |
41 | 42 | 43 |
44 | 45 |
46 |
47 | 96 |
97 |
98 | 109 | 110 | 111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /docs/_build/html/objects.inv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/SROMPy/41d8c9373b0b2d529d057feab015a6fc0f9b0f40/docs/_build/html/objects.inv -------------------------------------------------------------------------------- /docs/_build/html/py-modindex.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | Python Module Index — SROMPy 1.0 documentation 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 |
32 |
33 |
34 | 35 | 36 |
37 | 38 | 39 |

Python Module Index

40 | 41 |
42 | s 43 |
44 | 45 | 46 | 47 | 49 | 50 | 52 | 55 | 56 | 57 | 60 | 61 | 62 | 65 | 66 | 67 | 70 |
 
48 | s
53 | SROMPy 54 |
    58 | SROMPy.postprocess 59 |
    63 | SROMPy.srom 64 |
    68 | SROMPy.target 69 |
71 | 72 | 73 |
74 | 75 |
76 |
77 | 124 |
125 |
126 | 134 | 135 | 136 | 137 | 138 | 139 | -------------------------------------------------------------------------------- /docs/_build/html/search.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | Search — SROMPy 1.0 documentation 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 |
38 |
39 |
40 | 41 | 42 |
43 | 44 |

Search

45 |
46 | 47 |

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 |

58 |
59 | 60 | 61 | 62 |
63 | 64 |
65 | 66 |
67 | 68 |
69 | 70 |
71 |
72 | 107 |
108 |
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 | --------------------------------------------------------------------------------