Rinchen Sherpa
Rinchen Sherpa

Reputation: 11

How to efficiently integrate over a hexagonal region using Cubature in python?

I need to integrate a two-variable function numerically using the Cubature package in Python. The two-dimensional region over which I want to integrate is a hexagon. Integrating it in a circular region in polar coordinates is fast, but when I try to integrate it over a hexagonal region, the code becomes slow.

I did the integration in polar coordinates. Since I (think) cannot set r as a function of theta in integration limits. I instead defined the integrand function such that it becomes zero outside the hexagonal boundary. Is there an efficient / better way to do this?

#function for hexagonal boundary
def rfun(theta):
    pt = np.pi/3
    phi = theta % pt
    return (3*s)/(2*(np.cos(phi) + np.cos(pt-phi)))


def myfunction(kk,para):
    k=kk[0]
    theta=kk[1]
    cond=rfun(theta)
    if k > cond:
        ans=np.array([0.0,0.0])
    else:
        # contains my function
    return ans
                     
def integralfunction(para):
    kmin = np.array([0.0, 0.0], np.float64)  # kr, ktheta
    kmax = np.array([s, 2*np.pi], np.float64)  # kr, ktheta
    kdim = 2  # kr, ktheta
    fdim = 2  # real, imag
    
    val, err = cubature(myfunction, kdim, fdim, kmin, kmax, args=(para),
                        adaptive='h', relerr=1e-5, maxEval=1e6, vectorized=False)
    
    ireal, iimag = val
    fresult= somefunction(ireal,iimag)
    return fresult

Upvotes: 1

Views: 49

Answers (0)

Related Questions