pythonpython-3.xnumpyellipsediscretization

Discretizing over the area of an ellipse given bounds


The problem is I have a center (x,y) and some standard deviations sigma_{x1} and sigma_{x2}, together I can use these to plot a Gaussian 3-sigma confidence interval of the center (x,y)

I need to discretize over this ellipsoid such that I can evaluate the expected value of a function as f(x,y)*p(x,y) but I am not sure how to generate the x and y "mesh". I'm not sure if mesh is the correct terminology here.

If this were a square instead the answer would be applying np.linspace(start=min, stop=max) for some arbitrary min/max value for x and y. I am not entirely sure how to proceed for non-rectangular shapes? My thought process at first was to generate a rectangular region around and then select points for which solving the ellipse equation returns something <=1 but I figure this is not the most efficient way to implement this.

Note: Currently using python 3.6.9 and numpy 1.19.4


Solution

  • I don't think you can do it much more efficiently than with the approach you already proposed. To make a grid you can use

    x, y = np.mgrid[minx:maxx:step*1j, miny:maxy:step*1j]
    

    Here mgrid is basically a multidimensional version of np.linspace.

    Then you just need to discard values outside of your ellipse and retain the ones inside. This is easiest by "masking" using logical indexing:

    mask = x**2 + y**2 < 1  # replace unit circle equation with ellipse equation
    x, y = x[mask], y[mask]
    

    Then you can evaluate your expected value using

    ev = (f(x,y) * p(x, y)).sum()
    

    (assuming both f and p can deal with vectors as inputs).