### Complete Example: Uncertainty Analysis Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md A comprehensive example demonstrating how to define parameters with different uncertainty types (Normal, Triangular, Lognormal), run a Monte Carlo simulation using `MCRandomNumberGenerator`, and analyze the results. ```python import numpy as np from stats_arrays import MCRandomNumberGenerator, UncertaintyBase # Define parameters with uncertainty params = UncertaintyBase.from_dicts( # Material cost: normal distribution {'loc': 100, 'scale': 10, 'uncertainty_type': 3}, # Labor cost: triangular distribution {'loc': 50, 'minimum': 30, 'maximum': 80, 'uncertainty_type': 5}, # Overhead multiplier: lognormal {'loc': 0, 'scale': 0.3, 'uncertainty_type': 2} ) # Run Monte Carlo analysis rng = MCRandomNumberGenerator(params, seed=12345) n_iterations = 10000 results = [] for i in range(n_iterations): material_cost, labor_cost, overhead = rng.next() total_cost = (material_cost + labor_cost) * overhead results.append(total_cost) results = np.array(results) # Analyze results print(f"Mean cost: ${results.mean():.2f}") print(f"Std dev: ${results.std():.2f}") print(f"5th percentile: ${np.percentile(results, 5):.2f}") print(f"95th percentile: ${np.percentile(results, 95):.2f}") # Save results np.savetxt('monte_carlo_results.csv', results, delimiter=',') ``` -------------------------------- ### Install package with development and documentation requirements Source: https://github.com/brightway-lca/stats_arrays/blob/main/CONTRIBUTING.md Installs the package in editable mode with development and documentation dependencies. ```console pip install -e ".[dev,docs]" ``` -------------------------------- ### Installation & Imports Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Core classes, specific distributions, and error handling modules are imported from the stats_arrays library. ```python # Core classes from stats_arrays import ( UncertaintyBase, MCRandomNumberGenerator, UncertaintyType, uncertainty_choices, ) # Specific distributions from stats_arrays import ( NormalUncertainty, TriangularUncertainty, LognormalUncertainty, ) # Error handling from stats_arrays import InvalidParamsError, MaximumIterationsError ``` -------------------------------- ### Install package with development requirements Source: https://github.com/brightway-lca/stats_arrays/blob/main/CONTRIBUTING.md Installs the package in editable mode with development dependencies. ```console pip install -e ".[dev]" ``` -------------------------------- ### Install package with testing requirements Source: https://github.com/brightway-lca/stats_arrays/blob/main/CONTRIBUTING.md Installs the package in editable mode with testing dependencies. ```console pip install -e ".[testing]" ``` -------------------------------- ### Install pre-commit using pip Source: https://github.com/brightway-lca/stats_arrays/blob/main/CONTRIBUTING.md Installs pre-commit, a tool for managing pre-commit hooks, using pip. ```console pip install pre-commit ``` -------------------------------- ### Generate Random Samples - With Seeding for Reproducibility Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Shows how seeding the MCRandomNumberGenerator ensures reproducible random sample generation. ```python from stats_arrays import MCRandomNumberGenerator, UncertaintyBase params = UncertaintyBase.from_dicts( {'loc': 0, 'scale': 1, 'uncertainty_type': 3} ) # Seeded RNG produces same results ng1 = MCRandomNumberGenerator(params, seed=12345) sample1 = rng1.next() rng2 = MCRandomNumberGenerator(params, seed=12345) sample2 = rng2.next() assert (sample1 == sample2).all() # True - reproducible ``` -------------------------------- ### Access Distribution Info - Look Up Distribution by ID Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Demonstrates how to look up distribution information by integer ID or enum using uncertainty_choices, and how to list all available distributions. ```python from stats_arrays import uncertainty_choices, UncertaintyType # By integer ID dist = uncertainty_choices[3] print(dist.description) # "Normal uncertainty" # By enum dist = uncertainty_choices[UncertaintyType.normal] # List all available for dist_class in uncertainty_choices: print(f"{dist_class.id}: {dist_class.description}") ``` -------------------------------- ### Check Parameters Before Sampling Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Demonstrates how to validate parameters for uncertainty distributions and handle `InvalidParamsError`. ```python from stats_arrays import NormalUncertainty, InvalidParamsError params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': -1} # Error: negative scale! ) try: NormalUncertainty.validate(params) except InvalidParamsError as e: print(f"Invalid parameters: {e}") # Fix and retry fixed_params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1} ) NormalUncertainty.validate(fixed_params) ``` -------------------------------- ### Check Bounds Reasonableness Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Shows how to check if the specified minimum and maximum bounds are reasonable for a given distribution, catching `UnreasonableBoundsError`. ```python from stats_arrays import NormalUncertainty, UnreasonableBoundsError # Very tight bounds around mean params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'minimum': -0.001, 'maximum': 0.001} ) try: NormalUncertainty.check_bounds_reasonableness(params, threshold=0.1) except UnreasonableBoundsError as e: print(f"Bounds too restrictive: {e}") ``` -------------------------------- ### Get PDF for Plotting Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Generates points for the Probability Density Function (PDF) of a distribution, suitable for plotting with libraries like Matplotlib. Also shows how to provide custom x values. ```python import matplotlib.pyplot as plt from stats_arrays import TriangularUncertainty params = TriangularUncertainty.from_dicts( {'loc': 5, 'minimum': 0, 'maximum': 10, 'uncertainty_type': 5} ) # Get PDF points xs, ys = TriangularUncertainty.pdf(params) # Plot plt.plot(xs, ys) plt.xlabel('Value') plt.ylabel('Probability Density') plt.title('Triangular Distribution') plt.show() # Or provide custom x values import numpy as np xs_custom = np.linspace(0, 10, 500) xs, ys = TriangularUncertainty.pdf(params, xs_custom) ``` -------------------------------- ### Basic Usage: Define Parameters - Method 2: Using Tuples Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Shows how to define parameters using tuples, including loc, scale, shape, bounds, negative flag, and uncertainty type. ```python import numpy as np from stats_arrays import UncertaintyBase params = UncertaintyBase.from_tuples( # (loc, scale, shape, minimum, maximum, negative, uncertainty_type) (0, 1, np.nan, np.nan, np.nan, False, 3), # Normal (5, np.nan, np.nan, 3, 10, False, 5), # Triangular ) ``` -------------------------------- ### BetaPERTUncertainty Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of BetaPERTUncertainty initialization. ```python from stats_arrays import BetaPERTUncertainty # Required: minimum (A), loc (B), maximum (C) # Optional: scale (lambda, default 4.0) params = BetaPERTUncertainty.from_dicts( {'minimum': 10, 'loc': 15, 'maximum': 20, 'scale': 4} ) ``` -------------------------------- ### Common Errors and Solutions Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Illustrates how to handle common errors like `InvalidParamsError`, `ValueError` (for unknown uncertainty types), and `MaximumIterationsError` when dealing with tight bounds. ```python from stats_arrays import ( MCRandomNumberGenerator, UncertaintyBase, InvalidParamsError, MaximumIterationsError, UnknownUncertaintyType, ) # 1. Invalid parameter values try: bad_params = UncertaintyBase.from_dicts( {'loc': 2, 'uncertainty_type': 3} # Missing scale ) rng = MCRandomNumberGenerator(bad_params) except InvalidParamsError as e: print(f"Parameter error: {e}") # 2. Unknown uncertainty type try: bad_type_params = UncertaintyBase.from_dicts( {'loc': 5, 'uncertainty_type': 999} # ID 999 doesn't exist ) rng = MCRandomNumberGenerator(bad_type_params) except ValueError as e: print(f"Type error: {e}") # 3. Can't fit bounds (tight bounds relative to distribution) try: tight_params = UncertaintyBase.from_dicts( {'loc': 100, 'scale': 1000, 'minimum': 100.01, 'maximum': 100.02, 'uncertainty_type': 3} ) rng = MCRandomNumberGenerator(tight_params, maximum_iterations=50) samples = rng.generate(samples=10) except MaximumIterationsError: print("Can't fit tight bounds - try looser constraints or LatinHypercubeRNG") ``` -------------------------------- ### Generate Random Samples - Mixed Distribution Types (Typical Case) Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Demonstrates generating samples from mixed distribution types using MCRandomNumberGenerator, including single vector generation and Monte Carlo iteration. ```python from stats_arrays import MCRandomNumberGenerator, UncertaintyBase # Multiple parameters with different distributions params = UncertaintyBase.from_dicts( {'loc': 100, 'scale': 10, 'uncertainty_type': 3}, # Normal {'loc': 5, 'minimum': 3, 'maximum': 10, 'uncertainty_type': 5}, # Triangular {'loc': 1, 'scale': 0.2, 'uncertainty_type': 2} # Lognormal ) # MCRandomNumberGenerator handles mixed types automatically ng = MCRandomNumberGenerator(params, seed=42) # Generate single vector (one iteration) vector = rng.generate(samples=1) print(vector.shape) # (3,) - one sample per parameter # Generate multiple samples samples = rng.generate(samples=100) print(samples.shape) # (3, 100) - 100 samples per parameter # Iterate for Monte Carlo analysis for iteration in range(10000): vector = rng.next() # Use vector in your model... ``` -------------------------------- ### Get Distribution Statistics Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Calculates and prints statistical measures (mean, mode, median, confidence intervals) for a given distribution's parameters. ```python from stats_arrays import NormalUncertainty params = NormalUncertainty.from_dicts( {'loc': 5, 'scale': 2, 'uncertainty_type': 3} ) stats = NormalUncertainty.statistics(params) print(stats) # { # 'mean': 5.0, # 'mode': 5.0, # 'median': 5.0, # 'lower': 1.0, # 95% CI # 'upper': 9.0 # 95% CI # } ``` -------------------------------- ### StudentsTUncertainty Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of StudentsTUncertainty initialization. ```python from stats_arrays import StudentsTUncertainty # Required: shape (degrees of freedom) # Optional: loc (mu, default 0), scale (sigma, default 1) params = StudentsTUncertainty.from_dicts( {'shape': 10, 'loc': 0, 'scale': 1} ) ``` -------------------------------- ### Install pre-commit using conda or mamba Source: https://github.com/brightway-lca/stats_arrays/blob/main/CONTRIBUTING.md Installs pre-commit, a tool for managing pre-commit hooks, using conda or mamba. ```console conda install pre-commit ``` -------------------------------- ### Basic Usage: Define Parameters - Method 1: Using Dictionaries (Recommended) Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Demonstrates creating a parameter array from dictionaries, specifying location, scale, and uncertainty type for Normal, Triangular, and Lognormal distributions. ```python from stats_arrays import UncertaintyBase # Create parameter array from dictionaries params = UncertaintyBase.from_dicts( # Normal distribution: mean=0, std=1 {'loc': 0, 'scale': 1, 'uncertainty_type': 3}, # Triangular: mode=5, bounds 3-10 {'loc': 5, 'minimum': 3, 'maximum': 10, 'uncertainty_type': 5}, # Lognormal: geometric mean=1, sigma=0.5 {'loc': 0, 'scale': 0.5, 'uncertainty_type': 2} ) print(params.shape) # (3,) print(params['loc']) # [0. 5. 1.] print(params['uncertainty_type']) # [3 5 2] ``` -------------------------------- ### BetaUncertainty Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of BetaUncertainty initialization. ```python from stats_arrays import BetaUncertainty # Required: loc (alpha), shape (beta) # Optional: minimum (default 0), maximum (default 1) params = BetaUncertainty.from_dicts( {'loc': 2, 'shape': 5, 'minimum': 0, 'maximum': 1} ) ``` -------------------------------- ### DiscreteUniform Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of DiscreteUniform initialization. ```python from stats_arrays import DiscreteUniform # Required: maximum # Optional: minimum (defaults to 0 if NaN) params = DiscreteUniform.from_dicts( {'minimum': 0, 'maximum': 10} ) ``` -------------------------------- ### Scaling Distributions with Bounds Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-utilities.md Example demonstrating how to rescale distributions to a unit interval and back. ```python from stats_arrays.utils import rescale_to_unitary_interval, rescale_vector_to_params from stats_arrays import BetaUncertainty import numpy as np # Beta distribution parameters (typically [0,1]) params = BetaUncertainty.from_dicts( {'loc': 2, 'shape': 5, 'minimum': 100, 'maximum': 200, 'uncertainty_type': 10} ) # Convert to unit interval for SciPy adjusted_loc, scale = rescale_to_unitary_interval(params) # Generate samples in [0,1] unit_samples = np.random.beta(adjusted_loc, params['shape'], size=100) # Scale back to [minimum, maximum] scaled_samples = rescale_vector_to_params(params, unit_samples.reshape(1, -1)) print(scaled_samples) # Values in [100, 200] ``` -------------------------------- ### GammaUncertainty Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of GammaUncertainty initialization. ```python from stats_arrays import GammaUncertainty # Required: shape (k), scale (theta) # Optional: loc (offset), negative params = GammaUncertainty.from_dicts( {'shape': 2, 'scale': 2} ) ``` -------------------------------- ### UncertaintyChoices.__getitem__ Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-uncertainty-choices.md Example demonstrating how to get a distribution class using an integer ID or an UncertaintyType enum member, and handling a KeyError for an invalid ID. ```python from stats_arrays import uncertainty_choices, UncertaintyType # By integer ID dist = uncertainty_choices[3] # Returns NormalUncertainty # By enum dist = uncertainty_choices[UncertaintyType.normal] # Same result # Invalid ID try: dist = uncertainty_choices[999] except KeyError: print("Distribution not registered") ``` -------------------------------- ### BetaPERTUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example of creating and sampling from a BetaPERTUncertainty distribution. ```python from stats_arrays import BetaPERTUncertainty params = BetaPERTUncertainty.from_dicts( {'minimum': 10, 'loc': 15, 'maximum': 20, 'scale': 4, 'uncertainty_type': 13} ) samples = BetaPERTUncertainty.random_variables(params, size=100) ``` -------------------------------- ### StudentsTUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example of creating and sampling from a StudentsTUncertainty distribution. ```python from stats_arrays import StudentsTUncertainty params = StudentsTUncertainty.from_dicts( {'shape': 10, 'loc': 0, 'scale': 1, 'uncertainty_type': 12} ) samples = StudentsTUncertainty.random_variables(params, size=100) ``` -------------------------------- ### UniformUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example usage of UniformUncertainty class, demonstrating parameter creation with mandatory 'minimum' and 'maximum'. ```python from stats_arrays import UniformUncertainty # Required: minimum, maximum (both mandatory) params = UniformUncertainty.from_dicts( {'minimum': 0, 'maximum': 10} ) ``` -------------------------------- ### ParamsArray Creation and Usage Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/types.md Example demonstrating how to create ParamsArray instances from dictionaries and access their fields. ```python from stats_arrays import UncertaintyBase # Create from dictionary params = UncertaintyBase.from_dicts( {'loc': 2.0, 'scale': 0.5, 'uncertainty_type': 3}, # Normal {'loc': 1.5, 'minimum': 0, 'maximum': 10, 'uncertainty_type': 5} # Triangular ) # Access fields print(params['loc']) # [2. 1.5] print(params['uncertainty_type']) # [3 5] # Shape is always 1-dimensional with dtype fields print(params.shape) # (2,) print(params.dtype.names) # ('loc', 'scale', 'shape', 'minimum', 'maximum', 'negative', 'uncertainty_type') ``` -------------------------------- ### BetaUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example of creating and sampling from a BetaUncertainty distribution. ```python from stats_arrays import BetaUncertainty params = BetaUncertainty.from_dicts( {'loc': 2, 'shape': 5, 'minimum': 0, 'maximum': 1, 'uncertainty_type': 10} ) samples = BetaUncertainty.random_variables(params, size=100) ``` -------------------------------- ### Generate Random Samples - Simple Case: Single Distribution Type Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Generates random samples from a single distribution type (Normal) using RandomNumberGenerator. ```python from stats_arrays import NormalUncertainty, RandomNumberGenerator params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'uncertainty_type': 3} ) # Create RNG ng = RandomNumberGenerator(NormalUncertainty, params, size=1000) # Generate samples samples = rng.generate_random_numbers() print(samples.shape) # (1, 1000) ``` -------------------------------- ### TriangularUncertainty Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of TriangularUncertainty initialization. ```python from stats_arrays import TriangularUncertainty params = TriangularUncertainty.from_dicts( {'minimum': 0, 'loc': 5, 'maximum': 10} ) ``` -------------------------------- ### Build documentation locally Source: https://github.com/brightway-lca/stats_arrays/blob/main/CONTRIBUTING.md Builds the documentation using Sphinx, specifying the source and output directories. ```console sphinx-build docs docs/_build ``` -------------------------------- ### Basic Usage: Define Parameters - Method 3: Type-Safe with Enum Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Illustrates using the UncertaintyType enum for type-safe parameter definition with dictionaries. ```python from stats_arrays import UncertaintyType, UncertaintyBase params = UncertaintyBase.from_dicts( { 'loc': 0, 'scale': 1, 'uncertainty_type': UncertaintyType.normal # Use enum instead of 3 } ) ``` -------------------------------- ### UniformUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example demonstrating how to create UniformUncertainty parameters and generate random samples, with an assertion for bounds. ```python from stats_arrays import UniformUncertainty params = UniformUncertainty.from_dicts( {'minimum': 0, 'maximum': 10, 'uncertainty_type': 4} ) samples = UniformUncertainty.random_variables(params, size=1000) assert samples.min() >= 0 and samples.max() <= 10 ``` -------------------------------- ### GammaUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example of creating and sampling from a GammaUncertainty distribution. ```python from stats_arrays import GammaUncertainty params = GammaUncertainty.from_dicts( {'shape': 2, 'scale': 2, 'uncertainty_type': 9} ) samples = GammaUncertainty.random_variables(params, size=100) ``` -------------------------------- ### WeibullUncertainty Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of WeibullUncertainty initialization. ```python from stats_arrays import WeibullUncertainty # Required: shape (k), scale (lambda) # Optional: loc (offset), negative params = WeibullUncertainty.from_dicts( {'shape': 1.5, 'scale': 2.0} ) ``` -------------------------------- ### Creating Parameters Programmatically Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-utilities.md Example of creating an empty parameter array and filling in values. ```python from stats_arrays.utils import construct_params_array # Create empty array params = construct_params_array(length=10, include_type=True) # Fill in values params['loc'] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] params['scale'] = [1] * 10 params['uncertainty_type'] = [3] * 10 # All normal ``` -------------------------------- ### TriangularUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example demonstrating how to create TriangularUncertainty parameters and generate random samples. ```python from stats_arrays import TriangularUncertainty params = TriangularUncertainty.from_dicts( {'minimum': 0, 'loc': 5, 'maximum': 10, 'uncertainty_type': 5} ) samples = TriangularUncertainty.random_variables(params, size=100) ``` -------------------------------- ### LognormalUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example demonstrating how to create LognormalUncertainty parameters and generate random samples. ```python from stats_arrays import LognormalUncertainty params = LognormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'uncertainty_type': 2} ) samples = LognormalUncertainty.random_variables(params, size=100) # All positive by default ``` -------------------------------- ### WeibullUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example of creating and sampling from a WeibullUncertainty distribution. ```python from stats_arrays import WeibullUncertainty params = WeibullUncertainty.from_dicts( {'shape': 1.5, 'scale': 2.0, 'uncertainty_type': 8} ) samples = WeibullUncertainty.random_variables(params, size=100) ``` -------------------------------- ### GeneralizedExtremeValueUncertainty Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of GeneralizedExtremeValueUncertainty initialization. ```python from stats_arrays import GeneralizedExtremeValueUncertainty # Required: loc (mu), scale (sigma) # Optional: shape (xi, must be 0) params = GeneralizedExtremeValueUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'shape': 0} ) ``` -------------------------------- ### BernoulliUncertainty Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of BernoulliUncertainty initialization. ```python from stats_arrays import BernoulliUncertainty # Required: loc (probability, 0-1) params = BernoulliUncertainty.from_dicts( {'loc': 0.7} ) ``` -------------------------------- ### NormalUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example demonstrating how to create NormalUncertainty parameters, generate random samples, and calculate statistics. ```python from stats_arrays import NormalUncertainty params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1} ) samples = NormalUncertainty.random_variables(params, size=1000) stats = NormalUncertainty.statistics(params) # {'mean': 0.0, 'mode': 0.0, 'median': 0.0, 'lower': -2.0, 'upper': 2.0} ``` -------------------------------- ### NoUncertainty Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of NoUncertainty initialization. ```python from stats_arrays import NoUncertainty # Required: loc (fixed value) params = NoUncertainty.from_dicts( {'loc': 42} ) ``` -------------------------------- ### LognormalUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example usage of LognormalUncertainty class, showing parameter creation with optional 'negative' flag. ```python from stats_arrays import LognormalUncertainty # Required: loc (mu), scale (sigma) # Optional: negative (apply negation to samples) params = LognormalUncertainty.from_dicts( {'loc': 0, 'scale': 0.5, 'negative': False} ) ``` -------------------------------- ### GeneralizedExtremeValueUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example of using GeneralizedExtremeValueUncertainty to create parameters and generate random variables. ```python from stats_arrays import GeneralizedExtremeValueUncertainty params = GeneralizedExtremeValueUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'shape': 0, 'uncertainty_type': 11} ) samples = GeneralizedExtremeValueUncertainty.random_variables(params, size=100) ``` -------------------------------- ### NormalUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example usage of NormalUncertainty class, including parameter creation, random variable generation, and statistics calculation. ```python from stats_arrays import NormalUncertainty # Required: loc (mean), scale (std dev) params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1} ) samples = NormalUncertainty.random_variables(params, size=100) stats = NormalUncertainty.statistics(params) ``` -------------------------------- ### UndefinedUncertainty Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of UndefinedUncertainty initialization. ```python from stats_arrays import UndefinedUncertainty # Required: loc (fixed value) params = UndefinedUncertainty.from_dicts( {'loc': 42} ) ``` -------------------------------- ### BernoulliUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example of using BernoulliUncertainty to create parameters and generate random variables. ```python from stats_arrays import BernoulliUncertainty params = BernoulliUncertainty.from_dicts( {'loc': 0.7, 'uncertainty_type': 6} ) samples = BernoulliUncertainty.random_variables(params, size=100) # Array of 0s and 1s ``` -------------------------------- ### check_bounds_reasonableness example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-base-uncertainty.md An example demonstrating how to use `check_bounds_reasonableness` and catch the `UnreasonableBoundsError`. ```python from stats_arrays import NormalUncertainty, UnreasonableBoundsError params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'minimum': -0.001, 'maximum': 0.001, 'uncertainty_type': 3} ) try: NormalUncertainty.check_bounds_reasonableness(params, threshold=0.1) except UnreasonableBoundsError as e: print(e) # Bounds cover only X.XX percent ``` -------------------------------- ### MaximumIterationsError Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/errors.md Example demonstrating MaximumIterationsError when generating samples with very tight bounds. ```python from stats_arrays import MCRandomNumberGenerator, UncertaintyBase, MaximumIterationsError params = UncertaintyBase.from_dicts( {'loc': 5, 'scale': 10, 'minimum': 5.1, 'maximum': 5.2, 'uncertainty_type': 3} # Normal with very tight bounds ) try: rng = MCRandomNumberGenerator(params, maximum_iterations=10) rng.generate(1) # Will hit iteration limit except MaximumIterationsError: print("Could not generate samples within bounds") ``` -------------------------------- ### UncertaintyChoices Usage Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/types.md Example demonstrating how to use UncertaintyChoices to access distribution classes by ID or enum, and how to iterate over registered distributions. ```python from stats_arrays import uncertainty_choices, UncertaintyType, NormalUncertainty # Access by ID dist = uncertainty_choices[3] assert dist is NormalUncertainty # Access by enum dist = uncertainty_choices[UncertaintyType.normal] assert dist is NormalUncertainty # Iterate over all distributions for distribution_class in uncertainty_choices: print(distribution_class.id, distribution_class.description) # Check membership assert NormalUncertainty in uncertainty_choices ``` -------------------------------- ### UnknownUncertaintyType Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/errors.md Illustrates catching UnknownUncertaintyType when a distribution class is missing required methods. ```python from stats_arrays import RandomNumberGenerator, UnknownUncertaintyType class BadDistribution: id = 99 # Missing: bounded_random_variables method try: rng = RandomNumberGenerator(BadDistribution, params) except UnknownUncertaintyType as e: print(e) # The provided uncertainty type must have the `bounded_random_variables` method ``` -------------------------------- ### DiscreteUniform Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example of using DiscreteUniform to create parameters and generate random variables. ```python from stats_arrays import DiscreteUniform params = DiscreteUniform.from_dicts( {'minimum': 0, 'maximum': 10, 'uncertainty_type': 7} ) samples = DiscreteUniform.random_variables(params, size=100) # All integers in [0, 10) ``` -------------------------------- ### Example Usage Source: https://github.com/brightway-lca/stats_arrays/blob/main/docs/index.md Demonstrates how to create and use uncertainty distributions and a Monte Carlo random number generator. ```python >>> from stats_arrays import * >>> my_variables = UncertaintyBase.from_dicts( ... {'loc': 2, 'scale': 0.5, 'uncertainty_type': NormalUncertainty.id}, ... {'loc': 1.5, 'minimum': 0, 'maximum': 10, 'uncertainty_type': TriangularUncertainty.id} ... ) >>> my_variables array([(2.0, 0.5, nan, nan, nan, False, 3), (1.5, nan, nan, 0.0, 10.0, False, 5)], dtype=[('loc', '>> my_rng = MCRandomNumberGenerator(my_variables) >>> my_rng.next() array([ 2.74414022, 3.54748507]) >>> # can also be used as an interator >>> zip(my_rng, xrange(10)) [(array([ 2.96893108, 2.90654471]), 0), (array([ 2.31190619, 1.49471845]), 1), (array([ 3.02026168, 3.33696367]), 2), (array([ 2.04775418, 3.68356226]), 3), (array([ 2.61976694, 7.0149952 ]), 4), (array([ 1.79914025, 6.55264372]), 5), (array([ 2.2389968 , 1.11165296]), 6), (array([ 1.69236527, 3.24463981]), 7), (array([ 1.77750176, 1.90119991]), 8), (array([ 2.32664152, 0.84490754]), 9)] ``` -------------------------------- ### NoUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example of using NoUncertainty to create parameters and generate random variables. ```python from stats_arrays import NoUncertainty params = NoUncertainty.from_dicts( {'loc': 42, 'uncertainty_type': 1} ) samples = NoUncertainty.random_variables(params, size=10) # array([[ 42., 42., 42., ...]]) ``` -------------------------------- ### UncertaintyChoices.__iter__ Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-uncertainty-choices.md Example demonstrating iteration over all available distribution classes and printing their ID and description. ```python from stats_arrays import uncertainty_choices # Print all available distributions for dist_class in uncertainty_choices: print(f"ID {dist_class.id}: {dist_class.description}") ``` -------------------------------- ### random_variables example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-base-uncertainty.md An example showing how to generate random samples using `random_variables` with both unseeded and seeded random number generators. ```python from stats_arrays import NormalUncertainty import numpy as np params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'uncertainty_type': 3}, {'loc': 5, 'scale': 2, 'uncertainty_type': 3} ) # Unseeded generation samples = NormalUncertainty.random_variables(params, size=1000) # Shape: (2, 1000) # Seeded generation rng = np.random.RandomState(42) samples = NormalUncertainty.random_variables(params, size=100, seeded_random=rng) ``` -------------------------------- ### UndefinedUncertainty Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-distributions.md Example of using UndefinedUncertainty to create parameters and generate random variables. ```python from stats_arrays import UndefinedUncertainty params = UndefinedUncertainty.from_dicts( {'loc': 5, 'uncertainty_type': 0} ) samples = UndefinedUncertainty.random_variables(params, size=10) # array([[ 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.]]) ``` -------------------------------- ### UncertaintyChoices.add Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-uncertainty-choices.md Example of defining and registering a custom distribution class (ExponentialDistribution) and attempting to add it again. ```python from stats_arrays import uncertainty_choices, UncertaintyBase class ExponentialDistribution(UncertaintyBase): id = 99 description = "Exponential distribution" @classmethod def random_variables(cls, params, size, seeded_random=None): # Implementation... pass # Register custom distribution uncertainty_choices.add(ExponentialDistribution) # Now accessible dist = uncertainty_choices[99] assert dist is ExponentialDistribution # Try to add again (warning issued, not added) uncertainty_choices.add(ExponentialDistribution) ``` -------------------------------- ### UncertaintyChoices.__contains__ Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-uncertainty-choices.md Example showing how to check for the presence of a registered distribution class and a non-registered custom class. ```python from stats_arrays import uncertainty_choices, NormalUncertainty, UncertaintyBase assert NormalUncertainty in uncertainty_choices class CustomDistribution(UncertaintyBase): id = 99 assert CustomDistribution not in uncertainty_choices ``` -------------------------------- ### Run the full test suite Source: https://github.com/brightway-lca/stats_arrays/blob/main/CONTRIBUTING.md Executes the project's test suite using pytest. ```console pytest ``` -------------------------------- ### bounded_random_variables example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-base-uncertainty.md An example demonstrating the use of `bounded_random_variables` and asserting that the generated samples are within the defined bounds. ```python from stats_arrays import TriangularUncertainty params = TriangularUncertainty.from_dicts( {'loc': 5, 'minimum': 3, 'maximum': 10, 'uncertainty_type': 5} ) samples = TriangularUncertainty.bounded_random_variables(params, size=100) assert (samples >= 3).all() and (samples <= 10).all() ``` -------------------------------- ### UnreasonableBoundsError Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/errors.md Demonstrates catching UnreasonableBoundsError when bounds are too narrow. ```python from stats_arrays import NormalUncertainty, UnreasonableBoundsError params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'minimum': 0.01, 'maximum': 0.02} # Very narrow bounds ) try: NormalUncertainty.check_bounds_reasonableness(params, threshold=0.1) except UnreasonableBoundsError as e: print(e) # The provided bounds cover only X.XX percent of the possible distribution ``` -------------------------------- ### UncertaintyChoices Global Instance Usage Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/method-reference.md Example of accessing and checking the pre-instantiated uncertainty_choices object. ```python from stats_arrays import uncertainty_choices # Pre-instantiated with 14 built-in distributions uncertainty_choices[3] # NormalUncertainty len(uncertainty_choices) # 14 ``` -------------------------------- ### Example Usage of one_row_params_array Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-utilities.md Demonstrates the behavior of the one_row_params_array decorator with single and multiple row parameter arrays. ```python from stats_arrays import NormalUncertainty params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'uncertainty_type': 3} ) # Single row: works stats = NormalUncertainty.statistics(params) # Multiple rows: raises error params_multi = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'uncertainty_type': 3}, {'loc': 5, 'scale': 2, 'uncertainty_type': 3} ) try: stats = NormalUncertainty.statistics(params_multi) except MultipleRowParamsArrayError: print("Use a loop for multiple rows") for row_idx in range(len(params_multi)): row_params = params_multi[[row_idx]] stats = NormalUncertainty.statistics(row_params) ``` -------------------------------- ### from_tuples example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-base-uncertainty.md Construct a parameter array from 7-tuples. ```python import numpy as np from stats_arrays import UncertaintyBase params = UncertaintyBase.from_tuples( (2, 3, np.nan, np.nan, np.nan, False, 3), (5, np.nan, np.nan, 3, 10, False, 5) ) ``` -------------------------------- ### from_dicts example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-base-uncertainty.md Construct a parameter array from dictionaries. ```python from stats_arrays import UncertaintyBase params = UncertaintyBase.from_dicts( {'loc': 2, 'scale': 0.5, 'uncertainty_type': 3}, {'loc': 1.5, 'minimum': 0, 'maximum': 10, 'uncertainty_type': 5} ) # Returns array with 2 rows ``` -------------------------------- ### UndefinedDistributionError Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/errors.md Shows how to catch UndefinedDistributionError when performing operations on undefined distributions. ```python from stats_arrays import UndefinedUncertainty, UndefinedDistributionError params = UndefinedUncertainty.from_dicts({'loc': 5, 'uncertainty_type': 0}) try: UndefinedUncertainty.cdf(params, [1, 2, 3]) except UndefinedDistributionError: print("Cannot calculate percentages for an undefined distribution") ``` -------------------------------- ### validate example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-base-uncertainty.md Validate parameter array for the uncertainty distribution. ```python from stats_arrays import NormalUncertainty, InvalidParamsError params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'uncertainty_type': 3} ) try: NormalUncertainty.validate(params) except InvalidParamsError as e: print(f"Validation failed: {e}") ``` -------------------------------- ### Advanced: Latin Hypercube Sampling Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/quickstart.md Introduces Latin Hypercube Sampling (LHS) using LatinHypercubeRNG for faster sampling and better coverage of parameter space compared to MCRandomNumberGenerator. ```python from stats_arrays import LatinHypercubeRNG, UncertaintyBase params = UncertaintyBase.from_dicts( {'loc': 0, 'scale': 1, 'uncertainty_type': 3}, {'loc': 5, 'minimum': 3, 'maximum': 10, 'uncertainty_type': 5} ) # Create LHS generator # samples=100 means 100 strata per parameter lhs = LatinHypercubeRNG(params, seed=42, samples=100) # Generate samples (very fast, from pre-computed space) for i in range(1000): vector = lhs.next() # Much faster than MCRandomNumberGenerator with tight bounds ``` -------------------------------- ### StatsArraysError Usage Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/errors.md Example of how to catch StatsArraysError in a try-except block. ```python from stats_arrays import StatsArraysError try: # code using stats_arrays pass except StatsArraysError as e: print(f"stats_arrays error: {e}") ``` -------------------------------- ### RandomNumberGenerator.generate_random_numbers Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-random-generators.md Example usage of the generate_random_numbers method. ```python from stats_arrays import RandomNumberGenerator, NormalUncertainty params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'uncertainty_type': 3}, {'loc': 5, 'scale': 2, 'uncertainty_type': 3} ) rng = RandomNumberGenerator(NormalUncertainty, params, size=100) samples = rng.generate_random_numbers() # Shape: (2, 100) ``` -------------------------------- ### RandomNumberGenerator Iterator Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-random-generators.md Example of using the RandomNumberGenerator as an iterator. ```python from stats_arrays import RandomNumberGenerator, TriangularUncertainty params = TriangularUncertainty.from_dicts( {'loc': 5, 'minimum': 3, 'maximum': 10, 'uncertainty_type': 5} ) rng = RandomNumberGenerator(TriangularUncertainty, params, size=50) # Iterate to get 10 batches for batch_num, samples in enumerate(rng): if batch_num >= 10: break print(f"Batch {batch_num}: {samples.shape}") ``` -------------------------------- ### InvalidParamsError Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/errors.md Example demonstrating how InvalidParamsError is raised due to a negative scale parameter. ```python from stats_arrays import NormalUncertainty, InvalidParamsError try: params = NormalUncertainty.from_dicts( {'loc': 5, 'scale': -1} # negative scale! ) NormalUncertainty.validate(params) except InvalidParamsError as e: print(e) # Real, positive scale (sigma) values are required ``` -------------------------------- ### ImproperBoundsError Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/errors.md Example demonstrating how ImproperBoundsError is raised due to mode outside bounds. ```python from stats_arrays import TriangularUncertainty, ImproperBoundsError try: params = TriangularUncertainty.from_dicts( {'loc': 8, 'minimum': 3, 'maximum': 5} # mode outside bounds! ) TriangularUncertainty.validate(params) except ImproperBoundsError as e: print(e) # Most likely value outside the given bounds ``` -------------------------------- ### RandomNumberGenerator Example Usage Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-random-generators.md A comprehensive example demonstrating the creation and usage of RandomNumberGenerator with a seed. ```python from stats_arrays import RandomNumberGenerator, NormalUncertainty import numpy as np # Create parameter array params = NormalUncertainty.from_dicts( {'loc': 0, 'scale': 1, 'uncertainty_type': 3} ) # Create RNG with seed for reproducibility rng = RandomNumberGenerator( NormalUncertainty, params, size=1000, seed=42 ) # Generate once samples = rng.generate_random_numbers() print(samples.shape) # (1, 1000) # Generate multiple batches all_samples = [] for batch in rng: all_samples.append(batch) if len(all_samples) >= 5: break ``` -------------------------------- ### Example Usage Source: https://github.com/brightway-lca/stats_arrays/blob/main/README.md Demonstrates how to create uncertainty distributions, generate random numbers, and use the random number generator as an iterator. ```python >>> from stats_arrays import * >>> my_variables = UncertaintyBase.from_dicts( ... {'loc': 2, 'scale': 0.5, 'uncertainty_type': NormalUncertainty.id}, ... {'loc': 1.5, 'minimum': 0, 'maximum': 10, 'uncertainty_type': TriangularUncertainty.id} ... ) >>> my_variables array([(2.0, 0.5, nan, nan, nan, False, 3), (1.5, nan, nan, 0.0, 10.0, False, 5)], dtype=[('loc', '>> my_rng = MCRandomNumberGenerator(my_variables) >>> my_rng.next() array([ 2.74414022, 3.54748507]) >>> # can also be used as an interator >>> zip(my_rng, xrange(10)) [(array([ 2.96893108, 2.90654471]), 0), (array([ 2.31190619, 1.49471845]), 1), (array([ 3.02026168, 3.33696367]), 2), (array([ 2.04775418, 3.68356226]), 3), (array([ 2.61976694, 7.0149952 ]), 4), (array([ 1.79914025, 6.55264372]), 5), (array([ 2.2389968 , 1.11165296]), 6), (array([ 1.69236527, 3.24463981]), 7), (array([ 1.77750176, 1.90119991]), 8), (array([ 2.32664152, 0.84490754]), 9)] ``` -------------------------------- ### Building params arrays using from_tuples Source: https://github.com/brightway-lca/stats_arrays/blob/main/notebooks/stats_arrays_demo.ipynb Demonstrates creating a params array using the from_tuples constructor, which requires specifying fields in a fixed order. ```python # from_tuples: order is (loc, scale, shape, minimum, maximum, negative, uncertainty_type) params_t = UncertaintyBase.from_tuples( (2.0, 0.5, np.nan, np.nan, np.nan, False, UncertaintyType.normal), (1.0, 0.3, np.nan, np.nan, np.nan, False, UncertaintyType.lognormal), ) params_t ``` -------------------------------- ### UncertaintyType Usage Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/types.md Example showing how to use UncertaintyType enum members and access corresponding distribution classes. ```python from stats_arrays import UncertaintyType, uncertainty_choices, NormalUncertainty # All three forms are equivalent: UncertaintyType.normal # 3 (enum member) NormalUncertainty.id # 3 (class attribute) uncertainty_choices[3] # NormalUncertainty (lookup) # Use in parameter arrays params = UncertaintyBase.from_dicts( {'loc': 5, 'scale': 1, 'uncertainty_type': UncertaintyType.normal} ) # Safe comparison with array values assert params['uncertainty_type'][0] == UncertaintyType.normal ``` -------------------------------- ### Validate Before Use Example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/errors.md Shows explicit validation of parameters before use, even though it's often automatic. ```python from stats_arrays import UncertaintyBase, StatsArraysError params = UncertaintyBase.from_dicts( {'loc': 5, 'minimum': 10, 'maximum': 3, 'uncertainty_type': 5} ) try: # Distribution.validate() is called automatically by RNG constructors, # but you can call it explicitly for early validation params_dict_type = type(params) # Use the parsed type # Manually validate: for dist in uncertainty_choices: if dist.id == params['uncertainty_type'][0]: dist.validate(params) break except StatsArraysError as e: print(f"Parameter validation failed: {e}") # Fix and retry ``` -------------------------------- ### MCRandomNumberGenerator iterator interface example Source: https://github.com/brightway-lca/stats_arrays/blob/main/_autodocs/api-reference-random-generators.md Example showing how to use the iterator interface of MCRandomNumberGenerator for sequential sampling over multiple Monte Carlo iterations. ```python from stats_arrays import MCRandomNumberGenerator, UncertaintyBase params = UncertaintyBase.from_dicts( {'loc': 5, 'scale': 1, 'uncertainty_type': 3} ) rng = MCRandomNumberGenerator(params, seed=123) # Monte Carlo iteration samples_list = [] for iteration, vector in enumerate(rng): samples_list.append(vector) if iteration >= 999: # 1000 iterations break import numpy as np all_samples = np.array(samples_list) print(all_samples.shape) # (1000, 1) ```