[Numpy-discussion] need a better way to fill a grid

Vincent Schut schut at sarvision.nl
Mon Jan 24 09:56:15 EST 2011


On 01/24/2011 02:53 PM, John wrote:
> Hello,
>
> I'm trying to cycle over some vectors (lat,lon,emissions) of
> irregularly spaced lat/lon spots, and values. I need to sum the values
> each contributing to grid on a regular lat lon grid.
>
> This is what I have presently, but it is too slow. Is there a more
> efficient way to do this? I would prefer not to create an external
> module (f2py, cython) unless there is really no way to make this more
> efficient... it's the looping through the grid I guess that takes so
> long.

Use np.histogram2d with weights=emissions, and lat and lon as your x and 
y to histogram. Choose the bins to match your grid, and it will 
effectively sum the emission values for each grid cell.

Vincent.

>
> Thanks,
> john
>
>
>
>      def grid_emissions(lon,lat,emissions,grid.dx, grid.dy,
> grid.outlat0, grid.outlon0, grid.nxmax, grid.nymax):
>          """ sample the emissions into a grid to fold into model output
>          """
>
>          dx = grid.dxout
>          dy = grid.dyout
>
>          # Generate a regular grid to fill with the sum of emissions
>          xi = np.linspace(grid.outlon0,
> grid.outlon0+(grid.nxmax*grid.d), grid.nxmax)
>          yi = np.linspace(grid.outlat0,
> grid.outlat0+(grid.nymax*grid.dy), grid.nymax)
>
>          X, Y = np.meshgrid(yi, xi)
>          Z = np.zeros(X.shape)
>
>          for i,x in enumerate(xi):
>              for j,y in enumerate(yi):
>                  Z[i,j] = np.sum( emissions[\
>                           np.where(((lat>y-dy)&  (lat<y+dy))&
> ((lon>x-dx)&  (lon<x+dx)))[0]])
>
>          return Z




More information about the NumPy-Discussion mailing list