geocat-comp icon indicating copy to clipboard operation
geocat-comp copied to clipboard

Add lonFlip function

Open brianpm opened this issue 10 months ago • 2 comments

A very common operation performed with global data is to convert the longitude convention from/to [0,360] to/from [-180, 180]. This was available in NCL as lonFlip.

There are probably many ways this could be implemented. I've written this function a bunch of times. My current version assumes global data and that the data is an xarray object, and it at least seems to work:

def lonFlip(data, lonname=None):
    # NOTE: this assumes global values
    if lonname is None:
        lonname = 'lon'
    tmplon = data[lonname]
    tmpdata = data.roll( {lonname: (len(tmplon) // 2)}, roll_coords=True)
    lonroll = tmpdata[lonname].values
    if tmplon.min() >= 0:
        # flip to -180:180
        tmpdata[lonname] = xr.DataArray(np.where(lonroll >= 180, lonroll - 360, lonroll), dims=[lonname], attrs=data[lonname].attrs)
    else:
        # flip from -180:180 to 0:360
        tmpdata[lonname] = xr.DataArray(((lonroll + 360) % 360), dims=[lonname], attrs=data[lonname].attrs)
    return tmpdata

brianpm avatar Apr 13 '24 16:04 brianpm