# [SciPy-User] Re[SciPy-user] binning to polar coordinates

Jerome Kieffer Jerome.Kieffer@esrf...
Tue Aug 28 08:01:07 CDT 2012

```On Tue, 28 Aug 2012 03:33:11 -0700 (PDT)
arsbbr <arsbbr@gmx.net> wrote:

>
> Hi,
>
> I'm trying to rebin some uniform gridded data to polar coordinates. The
> original data (Z) is noisy but on a fine grid.
>
> ### snip
>
> # define grid in cartesian coordinates
> x = arange(-500, 500)
> y = arange(-500, 500)
> X, Y = meshgrid(x, y)
> Z = X**2 + Y**2
> Z += uniform(-5000, 5000, size=Z.shape))
>
> # transform to polar coordinates
>
> def cart2pol(x, y):
>     theta = arctan2(y, x)
>     rho = sqrt(x**2 + y**2)
>     return (theta, rho)
>
> THETA_xy, RHO_xy = cart2pol(X, Y)
>
> # define new polar grid
> theta = arange(-pi, pi, 0.1)
> rho = arange(0.1 ,500, 2.0)
>
> THETA, RHO = meshgrid(theta, rho)
>
> # Tried to use griddata, but it gives of course very jumpy results, because
> it
> # does not take the average over the pixels in a patch (dTHETA, dRHO) but an
> interpolation at the
> # exact new point.
>
> interpolate.griddata((THETA_xy.ravel(), RHO_xy.ravel()),
>    Z.ravel(), (THETA, RHO), method='linear')
>
> ### snip
>
> Is there a method that rebins the data to a new grid, possibly taking the
> average
> of the Z-values inside a patch (dTHETA, dRHO)?

Try to use 2D-weighted histogram (divided by unweighted histograms).
This unfortunately does dot split pixels over various bins so it works badly when the number of output bins is large.

w=histogram2d(THETA_xy.ravel(),RHO_xy.ravel(),(int(2*pi/0.1),500//2),weights=Z.ravel())
u=histogram2d(THETA_xy.ravel(),RHO_xy.ravel(),(int(2*pi/0.1),500//2))
imshow (w[0]/u[0])

If you want to split pixels, I am working on more sophisticated algorithm to do that in
https://github.com/kif/pyFAI  Tell me if you are interested.

Cheers,
--
Jérôme Kieffer
On-Line Data analysis / Software Group
ISDD / ESRF
tel +33 476 882 445
```