Skip to content

ENH: tools gauss-hermite quadrature #5499

Open

Description

@josef-pkt

mainly to park an old script for how to do gauss-hermite integration with scipy.
code is most likely outdated because scipy deprecated some of the orthogonal polynomial function.

related to numerical integration:

Stata uses adaptive quadrature for mixed models, which I haven't figured out (and I'm not sure we can do it in a computational efficient/vectorized way).
#2516 PR for GSOC project for MixedGLM, uses Laplace IIRC
Bayesian Mixed GLM is in master

Activity

  1. josef-pkt commented on Feb 14, 2019

    @josef-pkt
    MemberAuthor

    \josef\work-oth2\work-oth2_moved\try_hermite_quadrature.py
    might be superseded by some MixedPoisson examples (if I find it)

    # -*- coding: utf-8 -*-
    """Expectation of a function wrt. normal distribution using 
    Gauss-Hermite Quadrature
    
    
    Created on Fri Nov 18 23:46:53 2011
    Author: Josef Perktold
    """
    
    import numpy as np
    
    from scipy.special import orthogonal as orth
    
    from numpy import exp
    
    
    sqrt2pi = np.sqrt(2*np.pi)
    sqrt2pii = 1. / sqrt2pi
    #_norm_pdf_logC = math.log(_norm_pdf_C)
    def _norm_pdf(x):
        return np.exp(-x**2/2.0) / sqrt2pi
        
    def expect_norm(func, loc=0, scale=1, n_points=5):
        p, w = orth.he_roots(n_points)
        vals = func(p*scale + loc) 
        
        return np.dot(vals, w) * sqrt2pii
        
    def expect_norm2(func, loc=0, scale=1, n_points=5):
        p, w = orth.h_roots(n_points)
        vals = func(p * scale * np.sqrt(2.) + loc) 
        return np.dot(vals, w) * sqrt2pii * np.sqrt(2.)
    
    
    if __name__ == '__main__':
    
        from scipy import stats, integrate
        
        print orth.h_roots(5)  #weight function = exp(-x**2)
        print orth.he_roots(5) #weight function = exp(-(x/2)**2)
        
        def get_func(a, k):
            def func(x):
                return a*x**k
            return func
            
        
            
            
        
        func = get_func(0.5, 3)
        print stats.norm.expect(func)
        p, w = orth.he_roots(25)
        print np.dot(func(p), w) / _norm_pdf_C
        print expect_norm(func, loc=0, scale=1, n_points=5)
        print expect_norm2(func, loc=0, scale=1, n_points=5)
        
        func = get_func(1, 4)
        print stats.norm.expect(func)
        print expect_norm(func, loc=0, scale=1, n_points=5)
        print expect_norm2(func, loc=0, scale=1, n_points=5)
        print stats.norm.expect(func, loc=1, scale=2)
        print expect_norm(func, loc=1, scale=2, n_points=5)
        print expect_norm2(func, loc=1, scale=2, n_points=5)
    
  2. josef-pkt commented on Feb 19, 2020

    @josef-pkt
    MemberAuthor

    just found by chance
    https://github.com/nschloe/quadpy
    includes adaptive quadrature, disadvantage: has sympy as listed requirement
    also uses
    https://github.com/nschloe/orthopy
    more orthogonal polynomial features than numpy

    quadpy docs say it can integrate vectorized function, which would be very useful in our case.
    But I don't know if it fits our requirements.

    update
    looks like those are now closed source with license requirement.

  3. added this to the 0.15 milestone on Apr 7, 2023
  4. josef-pkt commented on Apr 7, 2023

    @josef-pkt
    MemberAuthor

    _norm_pdf_C = math.sqrt(2*pi) old scipy distribution function, now removed from scipy

    examples with updated code

    from scipy import stats, integrate
    ​
    print(orth.h_roots(5))  #weight function = exp(-x**2)
    print(orth.he_roots(5)) #weight function = exp(-(x/2)**2)
    ​
    def get_func(a, k):
        def func(x):
            return a*x**k
        return func
    ​
    ​
    ​
    func = get_func(0.5, 3)
    print("\n0.5, 3")
    print(stats.norm.expect(func))
    p, w = orth.he_roots(25)
    print(np.dot(func(p), w) * sqrt2pi)
    print(expect_norm(func, loc=0, scale=1, n_points=5))
    print(expect_norm2(func, loc=0, scale=1, n_points=5))
    ​
    func = get_func(1, 4)
    print("\n1, 4")
    print(stats.norm.expect(func))
    print(expect_norm(func, loc=0, scale=1, n_points=5))
    print(expect_norm2(func, loc=0, scale=1, n_points=5))
    print("\n1, 4, loc=1, scale=2")
    print(stats.norm.expect(func, loc=1, scale=2))
    print(expect_norm(func, loc=1, scale=2, n_points=5))
    print(expect_norm2(func, loc=1, scale=2, n_points=5))
    
    (array([-2.02018287, -0.95857246,  0.        ,  0.95857246,  2.02018287]), array([0.01995324, 0.39361932, 0.94530872, 0.39361932, 0.01995324]))
    (array([-2.85697001, -1.35562618,  0.        ,  1.35562618,  2.85697001]), array([0.02821815, 0.55666179, 1.33686841, 0.55666179, 0.02821815]))
    
    0.5, 3
    0.0
    0.0
    0.0
    0.0
    
    1, 4
    3.0000000000000053
    2.9999999999999942
    2.9999999999999973
    
    1, 4, loc=1, scale=2
    73.00000000000004
    72.99999999999989
    72.99999999999996
    
  5. josef-pkt commented on Oct 31, 2025

    @josef-pkt
    MemberAuthor

    google search now also has an AI. Semi-random topic to try it out

    asking for gauss hermite in python
    the code uses numpy polynomial to get points and weights. (I'm not sure what the status in scipy is. Some parts changed and I have not used this in a long time.

    Note: this does not include the sqrt(2 pi) term for integration w.r.t. normal distribution.

    from numpy.polynomial.hermite_e import hermegauss
    
    # This quadrature is for integrals of the form:
    # I = integral(exp(-x^2/2) * f(x), -inf, inf)
    
    def gauss_hermite_e_integration(func, n_points):
        x, w = hermegauss(n_points)
        integral_approx = np.sum(w * func(x))
        return integral_approx
    

    Aside:
    google ai also shows the function to integrate a function w.r.t. Lebesque measure instead of normal distribution.
    In this case we need to divide the function by the weight function to compensate for the gauss-hermite weights.
    Maybe we never want to use that.
    (Once upon a time, I went through the other orthogonal polynomials and the corresponding distribution functions, if applicable.
    That's useful for integrating w.r.t. those distributions. (*))

    def general_gauss_hermite_integration(g_func, n_points):
        """
        Approximate the integral of a general function g(x) from -inf to inf.
        """
        x, w = hermgauss(n_points)
        
        # Define f(x) = g(x) / w(x) where w(x) = exp(-x^2).
        # It is crucial to perform this division analytically if possible
        # to avoid numerical instability.
        f_func = lambda x: g_func(x) * np.exp(x**2)
        
        integral_approx = np.sum(w * f_func(x))
        
        return integral_approx
    

    (*) Google AI can answer that (but copying the table produces html)
    They reference https://openturns.github.io/openturns/latest/theory/meta_modeling/orthogonal_polynomials.html

    which includes the following table (support didn't copy)

    Distribution Support Polynomial family In the library
    Normal   Hermite HermiteFactory
    Uniform   Legendre LegendreFactory
    Gamma   Laguerre LaguerreFactory
    Beta   Jacobi JacobiFactory
    Poisson   Charlier CharlierFactory
    Binomial   Krawtchouk KrawtchoukFactory
    Negative Binomial   Meixner MeixnerFactory

    edit

    current scipy: function roots_hermitenorm
    https://docs.scipy.org/doc/scipy-1.16.2/reference/generated/scipy.special.roots_hermitenorm.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions