### Install Documentation Dependencies Source: https://salib.readthedocs.io/en/latest/developers_guide.html Install the necessary Python packages for building documentation. This command should be run from the SALib project's root directory. ```bash $ pip install -e .[doc] ``` -------------------------------- ### Basic Problem Setup for Sampling Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/advanced.rst.txt This is a standard setup for defining a problem with 3 variables and their bounds, used for parameter sampling. ```python from SALib.sample import saltelli from SALib.analyze import sobol from SALib.test_functions import Ishigami import numpy as np problem = { 'num_vars': 3, 'names': ['x1', 'x2', 'x3'], 'bounds': [[-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359]] } param_values = saltelli.sample(problem, 1024) ``` -------------------------------- ### Install SALib using pip Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/getting-started.rst.txt Installs the latest stable version of SALib and its dependencies from PyPI. ```bash pip install SALib ``` -------------------------------- ### Install and Run Pre-commit Hooks Source: https://salib.readthedocs.io/en/latest/_sources/developers_guide.md.txt Install the pre-commit framework and run all configured hooks across all files in the repository. This helps catch formatting and style issues before committing. ```bash # pre-commit install pre-commit run --all-files ``` -------------------------------- ### Basic Setup for Sampling Source: https://salib.readthedocs.io/en/latest/user_guide/advanced.html Initializes the problem definition and generates parameter values using Saltelli sampling. This is a prerequisite for most SALib analyses. ```python from SALib.sample import saltelli from SALib.analyze import sobol from SALib.test_functions import Ishigami import numpy as np problem = { 'num_vars': 3, 'names': ['x1', 'x2', 'x3'], 'bounds': [[-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359]] } param_values = saltelli.sample(problem, 1024) ``` -------------------------------- ### Install Documentation Dependencies Source: https://salib.readthedocs.io/en/latest/_sources/developers_guide.md.txt Install the necessary Python packages for building the project's documentation. This includes the project itself in editable mode and the 'doc' extra dependencies. ```bash pip install -e .[doc] ``` -------------------------------- ### Install SALib Development Version Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/getting-started.rst.txt Installs the latest development version of SALib from its GitHub repository. Note: This version may be unstable. ```bash git clone https://github.com/SALib/SALib.git cd SALib pip install . ``` -------------------------------- ### SALib.sample.common_args Source: https://salib.readthedocs.io/en/latest/api/SALib.html Provides common arguments and setup functions for sampling modules. ```APIDOC ## SALib.sample.common_args ### Description Common utility functions for sampling modules, including argument creation and setup. ### Functions - `create()`: Creates common arguments for sampling. - `run_cli()`: Runs the command-line interface for sampling. - `setup()`: Sets up the sampling environment. ``` -------------------------------- ### Discrepancy Analysis Setup Source: https://salib.readthedocs.io/en/latest/api/SALib.analyze.html Imports necessary libraries and defines the problem, sample inputs (X), and model outputs (Y) for discrepancy analysis. ```python >>> import numpy as np >>> from SALib.sample import latin >>> from SALib.analyze import discrepancy >>> from SALib.test_functions import Ishigami ``` -------------------------------- ### PAWN Analysis Example Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/pawn.html Example demonstrating how to perform PAWN sensitivity analysis. This requires a problem definition, input samples (X), and corresponding output samples (Y). ```python from SALib.analyze import pawn from SALib.test_functions import Ishigami from SALib.sample import latin problem = { 'num_vars': 3, 'names': ['x1', 'x2', 'x3'], 'bounds': [[-np.pi, np.pi]]*3 } X = latin.sample(problem, 1000) Y = Ishigami.evaluate(X) Si = pawn.analyze(problem, X, Y, S=10, print_to_console=False) ``` -------------------------------- ### Test SALib Installation with Sobol Analysis Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/getting-started.rst.txt A Python script to verify the SALib installation by performing a Sobol sensitivity analysis on the Ishigami test function. It includes sampling, model evaluation, and analysis steps. ```python from SALib.analyze.sobol import analyze from SALib.sample.sobol import sample from SALib.test_functions import Ishigami import numpy as np # Define the model inputs problem = { 'num_vars': 3, 'names': ['x1', 'x2', 'x3'], 'bounds': [[-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359]] } # Generate samples param_values = sample(problem, 1024) # Run model (example) Y = Ishigami.evaluate(param_values) # Perform analysis Si = analyze(problem, Y, print_to_console=True) # Print the first-order sensitivity indices print(Si['S1']) ``` -------------------------------- ### SALib Imports and Setup for Bin Analysis Source: https://salib.readthedocs.io/en/latest/user_guide/basics.html Import necessary libraries and define the problem for sensitivity analysis when dealing with models that have parameters not included in the analysis (e.g., time or position). ```python import numpy as np import matplotlib.pyplot as plt from SALib.sample import saltelli from SALib.analyze import sobol ``` -------------------------------- ### RBD-FAST Analysis Example Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/rbd_fast.html Demonstrates how to perform RBD-FAST analysis on model inputs and outputs. Requires prior sampling and evaluation of the model. ```python X = latin.sample(problem, 1000) Y = Ishigami.evaluate(X) Si = rbd_fast.analyze(problem, X, Y, print_to_console=False) ``` -------------------------------- ### Sobol Analysis Example Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/sobol.html Demonstrates how to perform Sobol analysis on model outputs. Requires problem definition, model outputs, and optionally parameters for second-order calculations and parallel processing. ```python >>> X = saltelli.sample(problem, 512) >>> Y = Ishigami.evaluate(X) >>> Si = sobol.analyze(problem, Y, print_to_console=True) ``` -------------------------------- ### Import Necessary Libraries for SALib Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/basics.rst.txt Import the required SALib sampling and analysis functions, a test function, and NumPy for data handling. This is the initial setup for a SALib analysis. ```python from SALib.sample import saltelli from SALib.analyze import sobol from SALib.test_functions import Ishigami import numpy as np ``` -------------------------------- ### Create Argument Parser with Setup Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/common_args.html Creates an argument parser for sensitivity analysis, optionally extending it with custom arguments provided by a cli_parser function. This is useful for building more complex CLIs that build upon the standard SALib arguments. ```python def create(cli_parser=None): parser = argparse.ArgumentParser( description="Perform sensitivity analysis on model output" ) parser = setup(parser) if cli_parser: parser = cli_parser(parser) return parser ``` -------------------------------- ### Discrepancy Analysis Example Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/discrepancy.html Demonstrates how to perform discrepancy analysis using SALib. Requires sampling and a test function. Ensure problem definition, input (X), and output (Y) are prepared. ```python import numpy as np from SALib.sample import latin from SALib.analyze import discrepancy from SALib.test_functions import Ishigami problem = { 'num_vars': 3, 'names': ['x1', 'x2', 'x3'], 'bounds': [[-np.pi, np.pi]]*3 } X = latin.sample(problem, 1000) Y = Ishigami.evaluate(X) Si = discrepancy.analyze(problem, X, Y, print_to_console=True) ``` -------------------------------- ### RBD-FAST CLI Example Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/rbd_fast.html This snippet demonstrates how to use the RBD-FAST analysis method via the command-line interface. It shows argument parsing for model input, output, and analysis parameters. ```python # coding=utf8 "-M", "--M", type=int, required=False, default=10, help="Inference parameter" ) parser.add_argument( "-r", "--resamples", type=int, required=False, default=100, help="Number of bootstrap resamples for Sobol " "confidence intervals", ) return parser [docs] def cli_action(args): problem = read_param_file(args.paramfile) X = np.loadtxt(args.model_input_file, delimiter=args.delimiter) Y = np.loadtxt( args.model_output_file, delimiter=args.delimiter, usecols=(args.column,) ) analyze( problem, X, Y, M=args.M, num_resamples=args.resamples, print_to_console=True, seed=args.seed, ) if __name__ == "__main__": common_args.run_cli(cli_parse, cli_action) ``` -------------------------------- ### FF Analysis Example Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/ff.html Demonstrates how to perform a fractional factorial analysis. Requires a problem definition, model inputs (X), and model outputs (Y). Can include second-order effects and print results to the console. ```python X = sample(problem) Y = X[:, 0] + (0.1 * X[:, 1]) + ((1.2 * X[:, 2]) * (0.2 + X[:, 0])) analyze(problem, X, Y, second_order=True, print_to_console=True) ``` -------------------------------- ### Morris Analysis Example Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/morris.html Demonstrates how to perform Morris analysis using SALib. This involves sampling with `SALib.sample.morris`, evaluating the model, and then analyzing the results with `SALib.analyze.morris`. Ensure the `num_levels` parameter matches between sampling and analysis. ```python >>> X = morris.sample(problem, 1000, num_levels=4) >>> Y = Ishigami.evaluate(X) >>> Si = morris.analyze(problem, X, Y, conf_level=0.95, >>> print_to_console=True, num_levels=4) ``` -------------------------------- ### Setup Argument Parser for Sensitivity Analysis Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/common_args.html Defines common command-line arguments for sensitivity analysis tasks, including parameter files, model output files, and optional settings like column delimiter and random seed. Use this function to initialize a parser with standard options. ```python import argparse [docs] def setup(parser): parser = argparse.ArgumentParser( description="Perform sensitivity analysis on model output" ) parser.add_argument( "-p", "--paramfile", type=str, required=True, help="Parameter range file" ) parser.add_argument( "-Y", "--model-output-file", type=str, required=True, help="Model output file" ) parser.add_argument( "-c", "--column", type=int, required=False, default=0, help="Column of output to analyze", ) parser.add_argument( "--delimiter", type=str, required=False, default=" ", help="Column delimiter in model output file", ) parser.add_argument( "-s", "--seed", type=int, required=False, default=None, help="Random Seed" ) return parser ``` -------------------------------- ### Enhanced HDMR Analysis Example Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/enhanced_hdmr.html Demonstrates how to use the enhanced HDMR analysis method within the SALib framework. This involves defining a problem, sampling inputs, evaluating the model, and then performing the enhanced HDMR analysis. The resulting emulator can also be accessed. ```python import numpy as np from SALib.test_functions import Ishigami from SALib.util import ProblemSpec sp = ProblemSpec({ 'names': ['X1', 'X2', 'X3'], 'bounds': [[-np.pi, np.pi]] * 3, 'outputs': ['Y'] }) (sp.sample_saltelli(2048) .evaluate(Ishigami.evaluate) .analyze_enhanced_hdmr() ) sp.emulate() ``` -------------------------------- ### Lake Problem Specification and Analysis Example Source: https://salib.readthedocs.io/en/latest/_modules/SALib/test_functions/lake_problem.html Demonstrates how to define the lake problem's parameters, generate samples using Latin Hypercube Sampling, evaluate the function, and perform sensitivity analysis using the delta method. This snippet is useful for understanding the typical workflow of using SALib for a specific test problem. ```python from SALib.sample import latin from SALib.analyze import delta SEED_VAL = 101 LAKE_SPEC = { "num_vars": 7, "names": ["a", "q", "b", "mean", "stdev", "delta", "alpha"], "bounds": [ [0.0, 0.1], [2.0, 4.5], [0.1, 0.45], [0.01, 0.05], [0.001, 0.005], [0.93, 0.99], [0.2, 0.5], ], "outputs": ["max_P", "Utility", "Inertia", "Reliability"], } latin_samples = latin.sample(LAKE_SPEC, 1000, seed=SEED_VAL) Y = evaluate(latin_samples) for i, name in enumerate(LAKE_SPEC["outputs"]): Si = delta.analyze(LAKE_SPEC, latin_samples, Y[:, i]) print(name) print(Si.to_df()) ``` -------------------------------- ### SALib.sample.common_args.setup Source: https://salib.readthedocs.io/en/latest/api/SALib.sample.html Adds common sampling options to a CLI parser object. ```APIDOC ## SALib.sample.common_args.setup ### Description Add common sampling options to CLI parser. ### Parameters * **parser** (_argparse object_) ### Return type Updated argparse object ``` -------------------------------- ### Install Core Dependencies Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/getting-started.rst.txt Installs essential Python libraries such as NumPy, SciPy, pandas, and matplotlib, which are core dependencies for SALib. ```bash pip install numpy scipy pandas matplotlib ``` -------------------------------- ### Build Documentation Locally on *nix Source: https://salib.readthedocs.io/en/latest/_sources/developers_guide.md.txt Navigate to the docs directory and build the HTML documentation using the make command. This is for Unix-like systems. ```bash cd docs make html ``` -------------------------------- ### Sample, Evaluate, and Analyze with SALib Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/basics.rst.txt Demonstrates the core SALib workflow: sampling parameters using `saltelli.sample`, evaluating the model for each parameter set, and analyzing the results using `sobol.analyze` for each output bin. ```python # sample param_values = saltelli.sample(problem, 2**6) # evaluate x = np.linspace(-1, 1, 100) y = np.array([parabola(x, *params) for params in param_values]) # analyse sobol_indices = [sobol.analyze(problem, Y) for Y in y.T] ``` -------------------------------- ### DGSM Analysis Example Source: https://salib.readthedocs.io/en/latest/api/SALib.analyze.html Example of how to use the DGSM analyze function. Requires problem definition, model inputs (X), and model outputs (Y). ```python >>> X = finite_diff.sample(problem, 1000) >>> Y = Ishigami.evaluate(X) >>> Si = dgsm.analyze(problem, X, Y, print_to_console=False) ``` -------------------------------- ### Build Documentation Locally on Windows Source: https://salib.readthedocs.io/en/latest/developers_guide.html Build the HTML documentation locally on Windows using the command prompt. Navigate to the 'docs' directory first. ```bash > cd docs > sphinx-build . ./html ``` -------------------------------- ### SALib.analyze.common_args.setup Source: https://salib.readthedocs.io/en/latest/api/SALib.analyze.html Sets up a command-line argument parser with common arguments required for SALib analysis. This function is typically called before parsing arguments. ```APIDOC ## SALib.analyze.common_args.setup ### Description Sets up a command-line argument parser with common arguments required for SALib analysis. This function is typically called before parsing arguments. ### Signature `SALib.analyze.common_args.setup(_parser_)` ### Parameters * `_parser_` (object): An argument parser object (e.g., from `argparse.ArgumentParser`) to which the common analysis arguments will be added. ``` -------------------------------- ### Delta Analysis Example Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/delta.html Perform Delta Moment-Independent Analysis and print results to the console. This example demonstrates a typical usage scenario for analyzing model outputs. ```python from SALib.test_functions import Ishigami from SALib.sample import latin from SALib.analyze import delta problem = { 'num_vars': 3, 'names': ['x1', 'x2', 'x3'], 'bounds': [[-np.pi, np.pi]]*3 } X = latin.sample(problem, 1000) Y = Ishigami.evaluate(X) Si = delta.analyze(problem, X, Y, print_to_console=True) ``` -------------------------------- ### sample Source: https://salib.readthedocs.io/en/latest/api/SALib.util.html Create samples using a given function. The function must accept the SALib problem specification as its first parameter and return a NumPy array. ```APIDOC ## sample ### Description Create sample using given function. ### Parameters #### Positional Parameters - **func** (function) - Sampling method to use. The given function must accept the SALib problem specification as the first parameter and return a numpy array. - **args** (list) - Additional arguments to be passed to func - **kwargs** (dict) - Additional keyword arguments passed to func ### Returns - **self** (ProblemSpec object) ``` -------------------------------- ### Build Documentation Locally on Windows Source: https://salib.readthedocs.io/en/latest/_sources/developers_guide.md.txt Navigate to the docs directory and build the HTML documentation using the sphinx-build command. This is for Windows command prompt. ```bash > cd docs > sphinx-build . ./html ``` -------------------------------- ### Enhanced HDMR Parameter Setup Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/enhanced_hdmr.html Initializes core parameters for Enhanced HDMR analysis, including dimensions, polynomial order, and bootstrap settings. This setup is crucial before performing sensitivity calculations. ```python from SALib.util import ResultDict from collections import defaultdict from itertools import combinations as comb import math import numpy as np from collections import namedtuple def enhanced_hdmr(X, y, d, max_order, poly_order, bootstrap, subset, extended_base=False, f0=None): """ Calculate the first, second, and third order HDMR component functions. Parameters ---------- X : numpy.array The input matrix from which to compute the sensitivity indices. Shape (N, d) where N is the number of samples and d is the number of dimensions. y : numpy.array The output vector from the model. Shape (N,) d : int The number of dimensions in the input space. max_order : int The maximum order of the component functions to compute. Can be 1, 2, or 3. poly_order : int The polynomial order of the component functions. bootstrap : int The number of bootstrap samples to use for confidence intervals. If 1, no bootstrapping is performed. subset : int The number of samples to use for each bootstrap iteration. extended_base : bool, optional Whether to use an extended basis for the component functions. Defaults to False. f0 : float, optional The value of the 0-th component function. If None, it is computed from the input data. Returns ------- Si : dict A dictionary containing the sensitivity indices and their confidence intervals. The keys are: - "S" : numpy.array Sensitivity index (total contribution) - "S_conf" : numpy.array Statistical confidence interval of `S` - "S_sum" : numpy.array Sum of sensitivity indexes (total contribution) - "S_sum_conf" : numpy.array Statistical confidence interval of sum of `S` - "Sa" : numpy.array Sensitivity index (uncorrelated contribution) - "Sa_conf" : numpy.array Statistical confidence interval of `Sa` - "Sa_sum" : numpy.array Sum of sensitivity indexes (uncorrelated contribution) - "Sa_sum_conf" : numpy.array Statistical confidence interval of sum of `Sa` - "Sb" : numpy.array Sensitivity index (correlated contribution) - "Sb_conf" : numpy.array Statistical confidence interval of `Sb` - "Sb_sum" : numpy.array Sum of sensitivity indexes (correlated contribution) - "Sb_sum_conf" : numpy.array Statistical confidence interval of sum of `Sb` - "ST" : numpy.array Total Sensitivity indexes of features/inputs - "ST_conf" : numpy.array Statistical confidence interval of `ST` - "Signf" : numpy.array Signigicancy for each bootstrap iteration - "Term" : numpy.array Component name """ cp = defaultdict(int) cp["n_comp_func"], cp["n_coeff"] = [0] * 3, [0] * 3 cp["n_comp_func"][0] = d cp["n_coeff"][0] = poly_order if max_order > 1: cp["n_comp_func"][1] = math.comb(d, 2) cp["n_coeff"][1] = poly_order**2 if extended_base: cp["n_coeff"][1] += 2 * poly_order if max_order == 3: cp["n_comp_func"][2] = math.comb(d, 3) cp["n_coeff"][2] = poly_order**3 if extended_base: cp["n_coeff"][2] += 3 * poly_order + 3 * poly_order**2 # Setup Bootstrap (if bootstrap > 1) idx = ( np.arange(0, N).reshape(-1, 1) if bootstrap == 1 else np.argsort(np.random.rand(N, bootstrap), axis=0)[:subset] ) CoreParams = namedtuple( "CoreParams", [ "N", "d", "max_order", "ext_base", "subset", "p_o", "nc1", "nc2", "nc3", "nc_t", "nt1", "nt2", "nt3", "tnt1", "tnt2", "tnt3", "a_tnt", "x", "idx", "beta", "gamma", "f0", ], ) n_comp_func = cp["n_comp_func"] n_coeff = cp["n_coeff"] hdmr = CoreParams( N, d, max_order, extended_base, subset, poly_order, n_comp_func[0], n_comp_func[1], n_comp_func[2], sum(n_comp_func), n_coeff[0], n_coeff[1], n_coeff[2], n_coeff[0] * n_comp_func[0], n_coeff[1] * n_comp_func[1], n_coeff[2] * n_comp_func[2], n_coeff[0] * n_comp_func[0] + n_coeff[1] * n_comp_func[1] + n_coeff[2] * n_comp_func[2], np.zeros( ( n_coeff[0] * n_comp_func[0] + n_coeff[1] * n_comp_func[1] + n_coeff[2] * n_comp_func[2], bootstrap, ) ), idx, np.array(list(comb(range(d), 2))), np.array(list(comb(range(d), 3))), f0, ) # Create Sensitivity Indices Result Dictionary keys = ( "Sa", "Sa_conf", "Sb", "Sb_conf", "S", "S_conf", "Signf", "Sa_sum", "Sa_sum_conf", "Sb_sum", "Sb_sum_conf", "S_sum", "S_sum_conf", ) Si = ResultDict( ( (k, np.zeros((hdmr.nc_t, bootstrap))) if k in ("S", "Sa", "Sb", "Signf") else (k, np.zeros(hdmr.nc_t)) ) for k in keys ) Si["Term"] = problem["names"] Si["ST"] = np.full(hdmr.nc_t, np.nan) Si["ST_conf"] = np.full(hdmr.nc_t, np.nan) # Generate index column for printing results if max_order > 1: for i in range(hdmr.nc2): Si["Term"].extend( [ "/".join( [ problem["names"][hdmr.beta[i, 0]], problem["names"][hdmr.beta[i, 1]], ] ) ] ) if max_order == 3: for i in range(hdmr.nc3): Si["Term"].extend( [ "/".join( [ problem["names"][hdmr.gamma[i, 0]], problem["names"][hdmr.gamma[i, 1]], ] ) ] ) return Si ``` -------------------------------- ### SALib.sample.latin.cli_action Source: https://salib.readthedocs.io/en/latest/_modules/SALib/sample/latin.html Action to run the Latin hypercube sampling method from the command line. ```APIDOC ## SALib.sample.latin.cli_action ### Description Run sampling method from the command line. ### Parameters #### Parameters - **args** (argparse namespace) - The command-line arguments. ### Action Reads the problem definition from a parameter file, performs Latin hypercube sampling using the `sample` function, and saves the resulting parameter values to a specified output file. ``` -------------------------------- ### sample Source: https://salib.readthedocs.io/en/latest/api/SALib.html Create sample using given function. ```APIDOC ## sample ### Description Create sample using given function. ### Parameters #### Parameters * **func** (function) – Sampling method to use. The given function must accept the SALib problem specification as the first parameter and return a numpy array. * ***args** (list) – Additional arguments to be passed to func * ****kwargs** (dict) – Additional keyword arguments passed to func ### Returns * **self** (ProblemSpec object) ### Return type ProblemSpec object ``` -------------------------------- ### SALib.analyze.common_args Source: https://salib.readthedocs.io/en/latest/api/SALib.html Provides common arguments and setup functions for analysis modules. ```APIDOC ## SALib.analyze.common_args ### Description Common utility functions for analysis modules, including argument creation and setup. ### Functions - `create()`: Creates common arguments for analysis. - `run_cli()`: Runs the command-line interface for analysis. - `setup()`: Sets up the analysis environment. ``` -------------------------------- ### LocalOptimisation.get_max_sum_ind Source: https://salib.readthedocs.io/en/latest/api/SALib.sample.morris.html Gets the indices that belong to the maximum distance in distances. This is a helper function for the optimization process. ```APIDOC ## LocalOptimisation.get_max_sum_ind ### Description Get the indices that belong to the maximum distance in distances. ### Parameters * **indices_list** (_list_) - A list of tuples representing trajectory indices. * **distances** (_numpy.ndarray_) - A numpy array of size M representing distances. * **i** (_int_) - An index. * **m** (_int_) - An index. ### Returns * **list** - A list of indices corresponding to the maximum distance. ``` -------------------------------- ### Initialize ProblemSpec for Parabola Analysis Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/basics_with_interface.rst.txt Initialize ProblemSpec with parameter names and bounds for 'a' and 'b'. This setup is for a problem where 'x' is not a parameter to be analyzed. ```python sp = ProblemSpec({ 'names': ['a', 'b'], 'bounds': [[0, 1]]*2, }) ``` -------------------------------- ### Standard SALib Workflow with Wrapped Model Source: https://salib.readthedocs.io/en/latest/user_guide/wrappers.html This snippet illustrates the traditional SALib workflow using dictionaries for problem definition, sampling with `saltelli`, and analyzing results from a wrapped model. It highlights the manual iteration for model evaluation. ```python import numpy as np from SALib.sample import saltelli from SALib.analyze import sobol def linear(a: float, b: float, x: float) -> float: return a + b * x def wrapped_linear(X: np.ndarray, func=linear) -> np.ndarray: N, D = X.shape results = np.empty(N) for i in range(N): a, b, x = X[i, :] results[i] = func(a, b, x) return results problem = { 'names': ['a', 'b', 'x'], 'bounds': [ [-1, 0], [-1, 0], [-1, 1], ], 'num_vars': 3 } X = saltelli.sample(problem, 64) Y = np.empty(X.shape[0]) for i in range(X.shape[0]): Y[i] = wrapped_linear(X[i, :]) res = sobol.analyze(problem, Y) res.to_df() ``` -------------------------------- ### SALib.util.util_funcs.avail_approaches Source: https://salib.readthedocs.io/en/latest/api/SALib.util.html Creates a list of available SALib modules within a specified package. ```APIDOC ## SALib.util.util_funcs.avail_approaches(pkg) ### Description Create list of available modules. ### Parameters #### Path Parameters - **pkg** (module) - The module to inspect. ### Returns - **method** (list) - A list of available submodules. ``` -------------------------------- ### HDMR Core Parameters Setup Source: https://salib.readthedocs.io/en/latest/_modules/SALib/analyze/enhanced_hdmr.html Establishes the core parameters for an HDMR expansion, returning them in a namedtuple and ResultDict. This function is central to all HDMR-related procedures. ```python def _core_params( problem: Dict, N: int, d: int, f0: float, poly_order: int, max_order: int, bootstrap: int, subset: int, extended_base: bool, ) -> Tuple[namedtuple, ResultDict]: """This function establishes the core parameters of an HDMR (High Dimensional Model Representation) expansion and returns them in a namedtuple an ResultDict datatype. These parameters are used across all functions and procedures related to HDMR. Parameters ---------- problem : Dict Problem definition N : int Number of samples in input matrix `X`. d : int Dimensionality of the problem. f0 : float Zero-th component function poly_order : int Polynomial order to be used to calculate orthonormal polynomial. max_order : int Maximum functional ANOVA expansion order. bootstrap : int Number of iteration to be used in bootstrap. subset : int Number of samples to be used in bootstrap. extended_base : bool Whether to use extended basis matrix or not. Returns ------- hdmr : namedtuple Core parameters of hdmr expansion Si : ResultDict Sensitivity Indices HDMR Attributes --------------- N : int Number of samples in input matrix `X`. d : int Dimensionality of the problem. max_order : int Maximum functional ANOVA expansion order. ext_base : bool Whether to use extended basis matrix or not. subset : int Number of samples to be used in bootstrap. p_o : int Polynomial order to be used to calculated orthonormal polynomial. nc1 : int Number of component functions in 1st order. nc2 : int Number of component functions in 2nd order. nc3 int Number of component functions in 3rd order. nc_t : int Total number of component functions. nt1 : int Total number of terms(columns) for a given 1st order component function nt2 : int Total number of terms(columns) for a given 2nd order component function nt3 : int Total number of terms(columns) for a given 3rd order component function tnt1 : int Total number of terms(columns) for all 1st order component functions tnt2 : int Total number of terms(columns) for all 2nd order component functions tnt3 : int Total number of terms(columns) for all 3rd order component functions a_tnt : int All terms (columns) in a hdmr expansion x : numpy.array Solution of hdmr expansion idx : numpy.array Indexes of subsamples to be used for bootstrap beta : numpy.array Arrangement of second-order component functions gamma : numpy.array """ pass ``` -------------------------------- ### Problem Specification with Alternate Distributions Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/advanced.rst.txt This example shows how to define a problem with custom sampling distributions for each variable, including lognormal and triangular distributions. ```python problem = { 'names': ['x1', 'x2', 'x3'], 'num_vars': 3, 'bounds': [[-np.pi, np.pi], [1.0, 0.2], [3, 0.5]], 'groups': ['G1', 'G2', 'G1'], 'dists': ['unif', 'lognorm', 'triang'] } ``` -------------------------------- ### Run Tests Source: https://salib.readthedocs.io/en/latest/developers_guide.html Execute the test suite for the SALib project. Run this command from the project's root directory. ```bash $ pytest ``` -------------------------------- ### Convert ResultDict to Pandas DataFrame Source: https://salib.readthedocs.io/en/latest/api/SALib.util.html Use the `to_df` method to convert the ResultDict object into a Pandas DataFrame for further analysis or visualization. Ensure Pandas is installed. ```python from SALib.util import ResultDict # Assuming 'results' is a ResultDict object results_df = results.to_df() ``` -------------------------------- ### Instantiate and Use SampleMorris Strategy Source: https://salib.readthedocs.io/en/latest/api/SALib.sample.morris.html Demonstrates how to instantiate the LocalOptimisation strategy and use it with SampleMorris to generate samples. This is useful for setting up a Morris sampling context. ```python >>> localoptimisation = LocalOptimisation() >>> context = SampleMorris(localoptimisation) >>> context.sample(input_sample, num_samples, num_params, k_choices, groups) ``` -------------------------------- ### Perform Morris Analysis Source: https://salib.readthedocs.io/en/latest/api/SALib.analyze.html Example of how to perform Morris analysis using SALib.analyze.morris.analyze. This involves sampling inputs with SALib.sample.morris, evaluating the model, and then analyzing the results. ```python X = morris.sample(problem, 1000, num_levels=4) Y = Ishigami.evaluate(X) Si = morris.analyze(problem, X, Y, conf_level=0.95, print_to_console=True, num_levels=4) ``` -------------------------------- ### Define Problem for Sensitivity Analysis Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/basics.rst.txt Defines the problem structure for SALib, specifying the number of variables, their names, and their bounds. This example includes only parameters 'a' and 'b'. ```python problem = { 'num_vars': 2, 'names': ['a', 'b'], 'bounds': [[0, 1]]*2 } ``` -------------------------------- ### Define a simple linear model Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/wrappers.rst.txt This is a basic Python function that takes three scalar arguments and returns their sum. It serves as an example model to be wrapped. ```python def linear(a, b, x): """Return y = a + b + x""" return a + b + x ``` -------------------------------- ### Define Problem Dictionary for Bin Analysis Source: https://salib.readthedocs.io/en/latest/user_guide/basics.html Define the 'problem' dictionary, specifying only the parameters that will be subject to sensitivity analysis, excluding variables like 'x' in this example. ```python problem = { 'num_vars': 2, 'names': ['a', 'b'], 'bounds': [[0, 1]]*2 } ``` -------------------------------- ### SALib.util.avail_approaches Source: https://salib.readthedocs.io/en/latest/api/SALib.util.html Creates a list of available submodules within a given package. This function is useful for discovering and inspecting the structure of the SALib library. ```APIDOC ## SALib.util.avail_approaches ### Description Creates a list of available submodules within a given package. This function is useful for discovering and inspecting the structure of the SALib library. ### Parameters #### Path Parameters - **pkg** (module) - Required - The module to inspect. ### Returns - **method** (list) - A list of available submodules. ``` -------------------------------- ### Define Parabola Function Source: https://salib.readthedocs.io/en/latest/_sources/user_guide/basics.rst.txt Defines a simple parabola function `y = a + b*x**2` used as an example model for sensitivity analysis. The parameters 'a' and 'b' are the variables of interest. ```python def parabola(x, a, b): """Return y = a + b*x**2.""" return a + b*x**2 ``` -------------------------------- ### SALib.sample.fast_sampler.cli_action Source: https://salib.readthedocs.io/en/latest/_modules/SALib/sample/fast_sampler.html Executes the sampling method using provided arguments. ```APIDOC ## SALib.sample.fast_sampler.cli_action ### Description Runs the sampling method using the provided arguments from the CLI. ### Parameters * **args** (argparse namespace) - The namespace object containing parsed command-line arguments, including 'paramfile', 'samples', 'M', 'seed', 'output', 'delimiter', and 'precision'. ``` -------------------------------- ### SALib.sample.finite_diff.sample Source: https://salib.readthedocs.io/en/latest/_modules/SALib/sample/finite_diff.html Generates a matrix of samples for Derivative-based Global Sensitivity Measure (DGSM) by starting from a QMC (Sobol') sequence and applying finite differences with a specified delta percentage. ```APIDOC ## SALib.sample.finite_diff.sample ### Description Generate matrix of samples for Derivative-based Global Sensitivity Measure (DGSM). Start from a QMC (Sobol') sequence and finite difference with delta % steps. ### Parameters * **problem** (dict) - SALib problem specification. * **N** (int) - Number of samples. * **delta** (float, optional) - Finite difference step size (percent). Defaults to 0.01. * **seed** (Optional[Union[int, np.random.Generator]], optional) - If `seed` is None the `numpy.random.Generator` generator is used. If `seed` is an int, a new ``Generator`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` instance then that instance is used. Default is None. * **skip_values** (int, optional) - How many values of the Sobol sequence to skip. Defaults to 1024. ### Returns * **np.array** - DGSM sequence. ### References 1. Sobol', I.M., Kucherenko, S., 2009. Derivative based global sensitivity measures and their link with global sensitivity indices. Mathematics and Computers in Simulation 79, 3009-3017. https://doi.org/10.1016/j.matcom.2009.01.023 2. Sobol', I.M., Kucherenko, S., 2010. Derivative based global sensitivity measures. Procedia - Social and Behavioral Sciences 2, 7745-7746. https://doi.org/10.1016/j.sbspro.2010.05.208 ```