Search code examples
pythonlistscipytuplesquad

Python scipy integrate.quad with TypeError: 'NoneType' object is not iterable


I am trying to define the following integral using scipy: enter image description here

and here is my code:

import numpy as np
import scipy.integrate as integrate
from scipy.stats import norm

def integrand(xi, thetai, *theta):
  sum = 0
  for thetaj in theta:
    prod = 1
    for t in tuple(list(theta).remove(thetaj)):
      prod = prod * (1 - norm.cdf(xi - t))
    sum = sum + norm.cdf(xi - thetaj) * prod
  return sum * norm.pdf(xi - thetai)

def integral(thetai, *theta):
  return (integrate.quad(integrand, -np.inf, np.inf, args=(thetai, *theta, )))[0]

print(integral(0.12849237,0.67286398,0.1124954,-0.3242629,0.28836734,0.33057082,-0.0843643,-0.085148,-0.7902458,-0.4907209,-0.5297461,-0.6957624))

However, when I run that code, the following error shows up: TypeError: 'NoneType' object is not iterable for the line for t in tuple(list(theta).remove(thetaj)):

and I am having troubles to debug it.


Solution

  • list.remove is an in-place operation, so it does not return a list. Therefore, when you do tuple(list(theta).remove(thetaj)) you end up with tuple(None), which is giving the error. Instead, you should simply check if t is (approximately) thetaj and skip it if it is.

    def integrand(xi, thetai, *theta):
        s = 0
        for thetaj in theta:
            prod = 1
            for t in theta:
                if abs(t - thetaj) < 1e-10:
                    continue
                prod = prod * (1 - norm.cdf(xi - t))
            s = s + norm.cdf(xi - thetaj) * prod
        return s * norm.pdf(xi - thetai)