chaospy

repository·master·Indexed 19 days ago

https://github.com/jonathf/chaospy

A numerical toolbox for uncertainty quantification (UQ) using polynomial chaos expansions and advanced Monte Carlo methods. Version 4.3.21 provides tools for low-discrepancy sampling, quadrature creation, polynomial manipulations, and sensitivity analysis (including Sobol indices via Sens_m, Sens_m2, and Sens_t). It supports fitting polynomial chaos expansions through linear regression (fit_regression) and spectral projection (fit_quadrature), as well as calculating statistical moments and correlation functions.

Tokens
24.4K
Snippets
77
Records
120
Agent score
67%

What's inside chaospy

  1. Overview of Chaospy capabilities

    master

    Chaospy is a numerical toolbox for uncertainty quantification (UQ) implemented in Python. It provides tools for:

    • Polynomial Chaos Expansions: Performing uncertainty quantification using polynomial chaos.
    • Monte Carlo Methods: Advanced Monte Carlo implementations.
    • Sampling & Quadrature: Low-discrepancy sampling and quadrature creation.
    • Polynomial Manipulations: A suite of tools for working with polynomials.

    The library is designed to be composable and integrates with the scientific Python ecosystem, including numpy, scipy, scikit-learn, statsmodels, openturns, and gstools.

  2. Explore Quadrature integration in chaospy

    master
    The chaospy.quadrature module provides a comprehensive suite of tools for numerical integration (quadrature) across various types of densities and grids. It is organized into several functional categories: standard quadrature rules, discrete densities, Gaussian extensions, predefined Gaussian rules, and helper functions for grid construction.
  3. Understand the chaospy distribution hierarchy

    master

    Chaospy organizes probability distributions into a hierarchy based on their parameterization and binding state. Understanding these categories helps you choose the right distribution for your modeling needs:

    • Unbound distributions: Distributions where parameters are not constrained to specific ranges (e.g., Normal, Cauchy, StudentT).
    • Partially bound distributions: Distributions that may have parameters with specific constraints or shapes, often used in reliability or survival analysis (e.g., Gamma, Weibull, LogNormal, Pareto).
    • Bound distributions: Distributions where parameters or the support of the distribution are strictly bounded (e.g., Uniform, Beta, TruncNormal).
    • Multivariate distributions: Distributions that model multiple random variables simultaneously, capturing dependencies (e.g., MvNormal, MvStudentT).
    • Discrete distributions: Distributions for discrete random variables (e.g., Binomial, DiscreteUniform).
    • Copulas: Mathematical functions used to describe the dependence between random variables, allowing you to combine marginal distributions into a multivariate model (e.g., Clayton, Gumbel, Joe).
  4. Understand the mental model of polynomial arrays in chaospy

    master

    In chaospy, polynomials are treated as multidimensional arrays (chaospy.ndpoly). There are two ways to conceptualize them:

    1. As a collection of polynomials: A polynomial vector $\Phi$ is a collection of simpler polynomials $[\Phi_1, \dots, \Phi_N]$. This is how they are typically visualized in the REPL.
    2. As a single polynomial sum: A multivariate polynomial is defined as a sum of terms where each term's coefficient $c_n$ is a multidimensional array and the exponents $k_{nd}$ are associated with indeterminants.

    This dual representation allows chaospy to leverage numpy for fast numerical operations on the coefficients, provided the number of terms is relatively small compared to the dimensionality of the coefficients.

    >>> q0, q1 = chaospy.variable(2)
    >>> expansion = chaospy.polynomial([1, q0, q1**2])
    >>> expansion
    polynomial([1, q0, q1**2])
  5. Operator precedence for ndpoly objects in chaospy

    master

    When working with chaospy.ndpoly objects, the standard Python/NumPy operators are overloaded to support polynomial arithmetic. Be aware that these behaviors differ from numpy:

    Operatorchaospy BehaviorFunction Mapping
    /Polynomial divisionchaospy.poly_divide
    //Floor division (only if divisor is a constant)chaospy.floor_divide
    %Polynomial remainderchaospy.poly_remainder
    divmod()Polynomial division and remainderchaospy.poly_divmod
  6. Calculate sensitivity indices with chaospy

    master

    Chaospy provides functions to calculate sensitivity indices, which quantify the contribution of individual input variables to the variance of a model output. The available methods include:

    • Sens_m: First-order sensitivity indices (main effects).
    • Sens_m2: Second-order sensitivity indices (interaction effects between pairs of variables).
    • Sens_t: Total-order sensitivity indices (includes main effects and all higher-order interactions involving the variable).

    Detailed API signatures and usage patterns can be found in the full API documentation.

    import chaospy
    
    # Example usage pattern (refer to full API for specific parameter shapes)
    # sens_m = chaospy.Sens_m(model, distribution)
    # sens_m2 = chaospy.Sens_m2(model, distribution)
    # sens_t = chaospy.Sens_t(model, distribution)
  7. How polynomial comparison operators work in chaospy

    master

    Since polynomials do not have a natural total ordering, chaospy implements an opinionated ordering system that is internally consistent and backwards compatible with numpy.ndarray. The comparison logic follows a hierarchy of rules:

    1. Polynomial Order (Degree/Grade): Polynomials with higher exponents are considered larger. In multivariate cases, the order is determined by the sum of the exponents across all indeterminants. Leading coefficients and lower-order terms are ignored during this step.
    2. Lexicographical Order: If polynomials have the same order, they are sorted in reverse lexicographical order based on the indeterminant names. For composite polynomials of the same order, they are sorted lexicographically by the dominant indeterminant name.
    3. Leading Coefficient: If the leading polynomial exponents are identical, the polynomials are compared by their leading coefficients.
    4. Subsequent Terms: If the leading terms are identical, chaospy compares the next largest leading polynomial term, and so on. Unlike the first rule, missing terms are treated as 0 during this step.

    Constant polynomials behave similarly to numpy arrays when compared to scalars.

    # Polynomial order (highest exponent wins)
    q0 = chaospy.variable()
    print(q0 < q0**2 < q0**3)  # True
    
    # Multivariate order (sum of exponents wins)
    q0, q1 = chaospy.variable(2)
    print(q0**2*q1**2 < q0*q1**5 < q0**6*q1)  # True
    
    # Lexicographical order for equal order
    q0, q1, q2 = chaospy.variable(3)
    print(q0 < q1 < q2)  # True
    
    # Coefficient comparison
    print(-4*q0 < -1*q0 < 2*q0)  # True
    
    # Comparison with scalars (numpy-like)
    print(chaospy.polynomial([2, 4, 6]) > 3)  # array([False,  True,  True])
  8. Use the Distribution base class in chaospy

    master

    The Distribution class is the fundamental base class for all probability distributions in chaospy. It provides a unified interface for performing statistical operations such as sampling, calculating cumulative distribution functions (CDF), percent point functions (PPF), and moments. Most specific distributions you use will inherit from this class.

    import chaospy
    
    # While you typically use specific distributions, they all follow the Distribution interface
    # Example of common methods available on a Distribution object:
    # dist.sample(n)
    # dist.cdf(x)
    # dist.ppf(p)
    # dist.moments()
    # dist.pdf(x)
    # dist.fwd(x)
  9. How chaospy interacts with numpy

    master

    Chaospy is designed to be highly compatible with numpy. The core polynomial class, chaospy.ndpoly, is a direct subclass of numpy.ndarray. This allows chaospy to leverage numpy's speed for coefficient manipulation while behaving like a polynomial.

    Because of this relationship, there is significant overlap in functionality:

    1. Chaospy functions with numpy arrays: If you pass a numpy.ndarray to a chaospy function (e.g., chaospy.transpose), it returns the result as a chaospy polynomial.
    2. Numpy functions with chaospy polynomials: If you pass a chaospy.ndpoly object to a numpy function (e.g., numpy.transpose), it will behave as if you used the chaospy equivalent.

    Note: For this seamless integration to work with standard numpy functions, you should use Numpy version >= 1.17, which supports function dispatching to subclasses.

    >>> import numpy
    >>> import chaospy
    >>> issubclass(chaospy.ndpoly, numpy.ndarray)
    True
    
    # Using chaospy function on numpy array
    >>> num_array = numpy.array([[1, 2], [3, 4]])
    >>> chaospy.transpose(num_array)
    polynomial([[1, 3],
                [2, 4]])
    
    # Using numpy function on chaospy polynomial
    >>> poly_array = chaospy.polynomial([[1, q0-1], [q1**2, 4]])
    >>> numpy.transpose(poly_array)
    polynomial([[1, q1**2],
                [q0-1, 4]])
  10. Install chaospy via pip or Conda

    master

    You can install chaospy using standard Python package managers.

    To install via pip:

    pip install chaospy

    To install via Conda (using the conda-forge channel):

    conda install -c conda-forge chaospy
    pip install chaospy