Calculation of the wind direction from the u and v components of a grib

618 Views Asked by At
import xarray as xr
import numpy as np

# Open GRIB with xarray
data_wind = xr.open_dataset('test.grib', engine='cfgrib')

# Extract wind from grib
u_variable = data_wind['u10']
v_variable = data_wind['v10']

# Convert var 
u = u_variable.values
v = v_variable.values


# Compute wind direction
wind_dir = np.mod(180 + (180/np.pi) * np.arctan2(v, u), 360)

Hi,

I'm currently trying to calculate the wind direction at each grid point of a grib. However, with the method I'm currently using, I have no way to be sure that the u and v values used in wind_dir are coming from the same point in space and time... Does anyone have any idea how I can make sure this is the case ?

thank you in advance

Antoine

I tried to set up a loop that goes through all the points, but without success

1

There are 1 best solutions below

0
jprockbelly On

Assuming your grib file is constructed correctly, what you are worried about is handled by the magic of xarray. It "knows" how to match coordinates and times, and you shouldn't need to worry about it.

In your example, you can look at the output of u.shape and v.shape. This should give you a three member tuple representing the lat, lon and time steps, which xarray uses to match data across these dimensions. wind_dir.shape should give the same result, as it will have the same dimensions as the inputs. If these are not the same you'll get an error in the wind_dir calculation step.

Here's an example you can play with

import pandas as pd

ds = xr.Dataset(
    {
        "v": xr.DataArray(
            [
                [[1.1, 2.2, 3.3], [2.2, 3.3, 4.4], [4.4, 5.5, 6.6]],
                [[1.2, 2.3, 3.4], [2.3, 3.4, 4.5], [4.5, 5.6, 6.7]],
            ],
            coords={
                "time": pd.DatetimeIndex(["2023-11-07", "2023-11-08"]),
                "latitude": [-10.25, -11.25, -12.25],
                "longitude": [112.25, 113.25, 114.25],
                    },
            dims=["time", "latitude", "longitude"],
            attrs={"long_name": "some variable"},
        ),
    },
)

# create u variable 
ds["u"] = ds.v

print(ds.v.shape) # (2, 3, 3)
print(ds.u.shape) # (2, 3, 3)

ds.v - ds.u # array of zeros

PS. You can slightly simplify the direction calculation like so:

wind_dir = np.degrees(np.arctan2(u, v)) % 360