regionmask¶

Per Halvorsen
2025-01-01
GitHub | LinkedIn | Website

In gis_intro.ipynb we used geojson to define regions of interest, giving us the flexibility to define regions as we see fit. An alternative here could have been to use regionmask, a Python library that provides predefined regions for scientific purposes.

While region masking could be useful for other projects, we decided to not use it for this project. Such scientific regions coculd be useful if we want to measure whale migrations from one region to another, but that was downprioritized for this project.

I'll keep the exploration code here for future reference.

Scientific regions¶

We'll use a scientific region defined in regionmask's documentation: https://regionmask.readthedocs.io/en/stable/defined_scientific.html

In [1]:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import numpy as np
import regionmask
import xarray as xr
In [2]:
regionmask.defined_regions.ar6.all
Out[2]:
<regionmask.Regions 'AR6 reference regions'>
Source:   Iturbide et al., 2020 (ESSD)
overlap:  False

Regions:
 0 GIC      Greenland/Iceland
 1 NWN      N.W.North-America
 2 NEN      N.E.North-America
 3 WNA        W.North-America
 4 CNA        C.North-America
..  ..                    ...
53 ARS            Arabian-Sea
54 BOB          Bay-of-Bengal
55 EIO Equatorial.Indic-Ocean
56 SIO          S.Indic-Ocean
57 SOO         Southern-Ocean

[58 regions]
In [3]:
text_kws = dict(color="#67000d", fontsize=7, bbox=dict(pad=0.2, color="w"))

regionmask.defined_regions.ar6.all.plot(
    text_kws=text_kws, label_multipolygon="all"
)
Out[3]:
<GeoAxes: >
No description has been provided for this image
In [4]:
region = regionmask.defined_regions.ar6.all[47]
region
Out[4]:
<regionmask._OneRegion: N.Pacific-Ocean (NPO / 47)>
In [5]:
region.polygon
Out[5]:
No description has been provided for this image
In [6]:
region.coords
Out[6]:
array([[ 132.        ,    7.6       ],
       [ 132.        ,    8.035     ],
       [ 132.        ,    8.47      ],
       ...,
       [-179.12139303,    7.6       ],
       [-179.56069652,    7.6       ],
       [-180.        ,    7.6       ]], shape=(1027, 2))

Filter geodata w/ region mask¶

In [22]:
ar6_regions = regionmask.defined_regions.ar6.all

# dataset spanning the globe
globe_xr = xr.Dataset(
    {
        "lon": (["lon"], np.linspace(-179.99, 180, 360)),
        "lat": (["lat"], np.linspace(-90, 90, 180)),
    }
)

# create all possible masks over dataset
ar6_mask = ar6_regions.mask_3D(globe_xr)

# select desired region
ar6_mask.sel(region=47).plot()
Out[22]:
<matplotlib.collections.QuadMesh at 0x175500f80>
No description has been provided for this image
In [30]:
fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
ar6_mask.sel(region=47).plot(ax=ax, transform=ccrs.PlateCarree(), alpha=0.75)

ax.coastlines()
ax.add_feature(cfeature.BORDERS, linestyle=':')

plt.show()
No description has been provided for this image
In [8]:
# display xr dataset correlated to region mask
ar6_mask.sel(region=47)
Out[8]:
<xarray.DataArray 'mask' (lat: 180, lon: 360)> Size: 65kB
array([[False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       ...,
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False]], shape=(180, 360))
Coordinates:
  * lat      (lat) float64 1kB -90.0 -88.99 -87.99 -86.98 ... 87.99 88.99 90.0
  * lon      (lon) float64 3kB -180.0 -179.0 -178.0 -177.0 ... 178.0 179.0 180.0
    region   int64 8B 47
    abbrevs  <U4 16B 'NPO'
    names    <U25 100B 'N.Pacific-Ocean'
Attributes:
    standard_name:  region
xarray.DataArray
'mask'
  • lat: 180
  • lon: 360
  • False False False False False False ... False False False False False
    array([[False, False, False, ..., False, False, False],
           [False, False, False, ..., False, False, False],
           [False, False, False, ..., False, False, False],
           ...,
           [False, False, False, ..., False, False, False],
           [False, False, False, ..., False, False, False],
           [False, False, False, ..., False, False, False]], shape=(180, 360))
    • lat
      (lat)
      float64
      -90.0 -88.99 -87.99 ... 88.99 90.0
      array([-90.      , -88.994413, -87.988827, -86.98324 , -85.977654, -84.972067,
             -83.96648 , -82.960894, -81.955307, -80.949721, -79.944134, -78.938547,
             -77.932961, -76.927374, -75.921788, -74.916201, -73.910615, -72.905028,
             -71.899441, -70.893855, -69.888268, -68.882682, -67.877095, -66.871508,
             -65.865922, -64.860335, -63.854749, -62.849162, -61.843575, -60.837989,
             -59.832402, -58.826816, -57.821229, -56.815642, -55.810056, -54.804469,
             -53.798883, -52.793296, -51.787709, -50.782123, -49.776536, -48.77095 ,
             -47.765363, -46.759777, -45.75419 , -44.748603, -43.743017, -42.73743 ,
             -41.731844, -40.726257, -39.72067 , -38.715084, -37.709497, -36.703911,
             -35.698324, -34.692737, -33.687151, -32.681564, -31.675978, -30.670391,
             -29.664804, -28.659218, -27.653631, -26.648045, -25.642458, -24.636872,
             -23.631285, -22.625698, -21.620112, -20.614525, -19.608939, -18.603352,
             -17.597765, -16.592179, -15.586592, -14.581006, -13.575419, -12.569832,
             -11.564246, -10.558659,  -9.553073,  -8.547486,  -7.541899,  -6.536313,
              -5.530726,  -4.52514 ,  -3.519553,  -2.513966,  -1.50838 ,  -0.502793,
               0.502793,   1.50838 ,   2.513966,   3.519553,   4.52514 ,   5.530726,
               6.536313,   7.541899,   8.547486,   9.553073,  10.558659,  11.564246,
              12.569832,  13.575419,  14.581006,  15.586592,  16.592179,  17.597765,
              18.603352,  19.608939,  20.614525,  21.620112,  22.625698,  23.631285,
              24.636872,  25.642458,  26.648045,  27.653631,  28.659218,  29.664804,
              30.670391,  31.675978,  32.681564,  33.687151,  34.692737,  35.698324,
              36.703911,  37.709497,  38.715084,  39.72067 ,  40.726257,  41.731844,
              42.73743 ,  43.743017,  44.748603,  45.75419 ,  46.759777,  47.765363,
              48.77095 ,  49.776536,  50.782123,  51.787709,  52.793296,  53.798883,
              54.804469,  55.810056,  56.815642,  57.821229,  58.826816,  59.832402,
              60.837989,  61.843575,  62.849162,  63.854749,  64.860335,  65.865922,
              66.871508,  67.877095,  68.882682,  69.888268,  70.893855,  71.899441,
              72.905028,  73.910615,  74.916201,  75.921788,  76.927374,  77.932961,
              78.938547,  79.944134,  80.949721,  81.955307,  82.960894,  83.96648 ,
              84.972067,  85.977654,  86.98324 ,  87.988827,  88.994413,  90.      ])
    • lon
      (lon)
      float64
      -180.0 -179.0 ... 179.0 180.0
      array([-179.99    , -178.987242, -177.984485, ...,  177.994485,  178.997242,
              180.      ], shape=(360,))
    • region
      ()
      int64
      47
      array(47)
    • abbrevs
      ()
      <U4
      'NPO'
      array('NPO', dtype='<U4')
    • names
      ()
      <U25
      'N.Pacific-Ocean'
      array('N.Pacific-Ocean', dtype='<U25')
    • lat
      PandasIndex
      PandasIndex(Index([             -90.0, -88.99441340782123, -87.98882681564245,
             -86.98324022346368, -85.97765363128491, -84.97206703910615,
             -83.96648044692738,  -82.9608938547486, -81.95530726256983,
             -80.94972067039106,
             ...
              80.94972067039106,  81.95530726256985,   82.9608938547486,
              83.96648044692739,  84.97206703910615,  85.97765363128494,
               86.9832402234637,  87.98882681564245,  88.99441340782124,
                           90.0],
            dtype='float64', name='lat', length=180))
    • lon
      PandasIndex
      PandasIndex(Index([            -179.99, -178.98724233983287, -177.98448467966574,
              -176.9817270194986, -175.97896935933147, -174.97621169916437,
             -173.97345403899723,  -172.9706963788301, -171.96793871866296,
             -170.96518105849583,
             ...
              170.97518105849576,  171.97793871866293,  172.98069637883003,
               173.9834540389972,   174.9862116991643,  175.98896935933146,
              176.99172701949857,  177.99448467966573,  178.99724233983284,
                           180.0],
            dtype='float64', name='lon', length=360))
  • standard_name :
    region

earthkit data¶

Repeat steps above, but using the cached earthkit data as an xarray dataset.

Note: The data is cached from downloading in gis_intro.ipynb. When running this on your own, you'll need to redownload data from the API, and print/copy the path to the cached data.

In [13]:
ds_path = '/tmp/tmptacb1_eq/ads-retriever-f5c106c0db93736042f233ebbd5bf5ef5119c7a4c943338308f26655ccc3399e.cache'

ds_xr = xr.open_dataset(ds_path, engine='cfgrib')

ds_xr
Out[13]:
<xarray.Dataset> Size: 4MB
Dimensions:     (time: 8, latitude: 162, longitude: 187)
Coordinates:
    number      int64 8B ...
  * time        (time) datetime64[ns] 64B 2016-12-21 ... 2016-12-22T18:00:00
    step        timedelta64[ns] 8B ...
    surface     float64 8B ...
  * latitude    (latitude) float64 1kB 70.75 70.0 69.25 ... -48.5 -49.25 -50.0
  * longitude   (longitude) float64 1kB 150.0 150.8 151.5 ... 288.0 288.8 289.5
    valid_time  (time) datetime64[ns] 64B ...
Data variables:
    pm10        (time, latitude, longitude) float32 969kB ...
    t2m         (time, latitude, longitude) float32 969kB ...
    msl         (time, latitude, longitude) float32 969kB ...
    tcco        (time, latitude, longitude) float32 969kB ...
Attributes:
    GRIB_edition:            1
    GRIB_centre:             ecmf
    GRIB_centreDescription:  European Centre for Medium-Range Weather Forecasts
    GRIB_subCentre:          0
    Conventions:             CF-1.7
    institution:             European Centre for Medium-Range Weather Forecasts
    history:                 2025-01-01T16:27 GRIB to CDM+CF via cfgrib-0.9.1...
xarray.Dataset
    • time: 8
    • latitude: 162
    • longitude: 187
    • number
      ()
      int64
      ...
      long_name :
      ensemble member numerical id
      units :
      1
      standard_name :
      realization
      [1 values with dtype=int64]
    • time
      (time)
      datetime64[ns]
      2016-12-21 ... 2016-12-22T18:00:00
      long_name :
      initial time of forecast
      standard_name :
      forecast_reference_time
      array(['2016-12-21T00:00:00.000000000', '2016-12-21T06:00:00.000000000',
             '2016-12-21T12:00:00.000000000', '2016-12-21T18:00:00.000000000',
             '2016-12-22T00:00:00.000000000', '2016-12-22T06:00:00.000000000',
             '2016-12-22T12:00:00.000000000', '2016-12-22T18:00:00.000000000'],
            dtype='datetime64[ns]')
    • step
      ()
      timedelta64[ns]
      ...
      long_name :
      time since forecast_reference_time
      standard_name :
      forecast_period
      [1 values with dtype=timedelta64[ns]]
    • surface
      ()
      float64
      ...
      long_name :
      original GRIB coordinate for key: level(surface)
      units :
      1
      [1 values with dtype=float64]
    • latitude
      (latitude)
      float64
      70.75 70.0 69.25 ... -49.25 -50.0
      units :
      degrees_north
      standard_name :
      latitude
      long_name :
      latitude
      stored_direction :
      decreasing
      array([ 70.75,  70.  ,  69.25,  68.5 ,  67.75,  67.  ,  66.25,  65.5 ,  64.75,
              64.  ,  63.25,  62.5 ,  61.75,  61.  ,  60.25,  59.5 ,  58.75,  58.  ,
              57.25,  56.5 ,  55.75,  55.  ,  54.25,  53.5 ,  52.75,  52.  ,  51.25,
              50.5 ,  49.75,  49.  ,  48.25,  47.5 ,  46.75,  46.  ,  45.25,  44.5 ,
              43.75,  43.  ,  42.25,  41.5 ,  40.75,  40.  ,  39.25,  38.5 ,  37.75,
              37.  ,  36.25,  35.5 ,  34.75,  34.  ,  33.25,  32.5 ,  31.75,  31.  ,
              30.25,  29.5 ,  28.75,  28.  ,  27.25,  26.5 ,  25.75,  25.  ,  24.25,
              23.5 ,  22.75,  22.  ,  21.25,  20.5 ,  19.75,  19.  ,  18.25,  17.5 ,
              16.75,  16.  ,  15.25,  14.5 ,  13.75,  13.  ,  12.25,  11.5 ,  10.75,
              10.  ,   9.25,   8.5 ,   7.75,   7.  ,   6.25,   5.5 ,   4.75,   4.  ,
               3.25,   2.5 ,   1.75,   1.  ,   0.25,  -0.5 ,  -1.25,  -2.  ,  -2.75,
              -3.5 ,  -4.25,  -5.  ,  -5.75,  -6.5 ,  -7.25,  -8.  ,  -8.75,  -9.5 ,
             -10.25, -11.  , -11.75, -12.5 , -13.25, -14.  , -14.75, -15.5 , -16.25,
             -17.  , -17.75, -18.5 , -19.25, -20.  , -20.75, -21.5 , -22.25, -23.  ,
             -23.75, -24.5 , -25.25, -26.  , -26.75, -27.5 , -28.25, -29.  , -29.75,
             -30.5 , -31.25, -32.  , -32.75, -33.5 , -34.25, -35.  , -35.75, -36.5 ,
             -37.25, -38.  , -38.75, -39.5 , -40.25, -41.  , -41.75, -42.5 , -43.25,
             -44.  , -44.75, -45.5 , -46.25, -47.  , -47.75, -48.5 , -49.25, -50.  ])
    • longitude
      (longitude)
      float64
      150.0 150.8 151.5 ... 288.8 289.5
      units :
      degrees_east
      standard_name :
      longitude
      long_name :
      longitude
      array([150.  , 150.75, 151.5 , 152.25, 153.  , 153.75, 154.5 , 155.25, 156.  ,
             156.75, 157.5 , 158.25, 159.  , 159.75, 160.5 , 161.25, 162.  , 162.75,
             163.5 , 164.25, 165.  , 165.75, 166.5 , 167.25, 168.  , 168.75, 169.5 ,
             170.25, 171.  , 171.75, 172.5 , 173.25, 174.  , 174.75, 175.5 , 176.25,
             177.  , 177.75, 178.5 , 179.25, 180.  , 180.75, 181.5 , 182.25, 183.  ,
             183.75, 184.5 , 185.25, 186.  , 186.75, 187.5 , 188.25, 189.  , 189.75,
             190.5 , 191.25, 192.  , 192.75, 193.5 , 194.25, 195.  , 195.75, 196.5 ,
             197.25, 198.  , 198.75, 199.5 , 200.25, 201.  , 201.75, 202.5 , 203.25,
             204.  , 204.75, 205.5 , 206.25, 207.  , 207.75, 208.5 , 209.25, 210.  ,
             210.75, 211.5 , 212.25, 213.  , 213.75, 214.5 , 215.25, 216.  , 216.75,
             217.5 , 218.25, 219.  , 219.75, 220.5 , 221.25, 222.  , 222.75, 223.5 ,
             224.25, 225.  , 225.75, 226.5 , 227.25, 228.  , 228.75, 229.5 , 230.25,
             231.  , 231.75, 232.5 , 233.25, 234.  , 234.75, 235.5 , 236.25, 237.  ,
             237.75, 238.5 , 239.25, 240.  , 240.75, 241.5 , 242.25, 243.  , 243.75,
             244.5 , 245.25, 246.  , 246.75, 247.5 , 248.25, 249.  , 249.75, 250.5 ,
             251.25, 252.  , 252.75, 253.5 , 254.25, 255.  , 255.75, 256.5 , 257.25,
             258.  , 258.75, 259.5 , 260.25, 261.  , 261.75, 262.5 , 263.25, 264.  ,
             264.75, 265.5 , 266.25, 267.  , 267.75, 268.5 , 269.25, 270.  , 270.75,
             271.5 , 272.25, 273.  , 273.75, 274.5 , 275.25, 276.  , 276.75, 277.5 ,
             278.25, 279.  , 279.75, 280.5 , 281.25, 282.  , 282.75, 283.5 , 284.25,
             285.  , 285.75, 286.5 , 287.25, 288.  , 288.75, 289.5 ])
    • valid_time
      (time)
      datetime64[ns]
      ...
      standard_name :
      time
      long_name :
      time
      [8 values with dtype=datetime64[ns]]
    • pm10
      (time, latitude, longitude)
      float32
      ...
      GRIB_paramId :
      210074
      GRIB_dataType :
      an
      GRIB_numberOfPoints :
      30294
      GRIB_typeOfLevel :
      surface
      GRIB_stepUnits :
      1
      GRIB_stepType :
      instant
      GRIB_gridType :
      regular_ll
      GRIB_uvRelativeToGrid :
      0
      GRIB_NV :
      0
      GRIB_Nx :
      187
      GRIB_Ny :
      162
      GRIB_cfName :
      mass_concentration_of_pm10_ambient_aerosol_particles_in_air
      GRIB_cfVarName :
      pm10
      GRIB_gridDefinitionDescription :
      Latitude/Longitude Grid
      GRIB_iDirectionIncrementInDegrees :
      0.75
      GRIB_iScansNegatively :
      0
      GRIB_jDirectionIncrementInDegrees :
      0.75
      GRIB_jPointsAreConsecutive :
      0
      GRIB_jScansPositively :
      0
      GRIB_latitudeOfFirstGridPointInDegrees :
      70.75
      GRIB_latitudeOfLastGridPointInDegrees :
      -50.0
      GRIB_longitudeOfFirstGridPointInDegrees :
      150.0
      GRIB_longitudeOfLastGridPointInDegrees :
      289.5
      GRIB_missingValue :
      3.4028234663852886e+38
      GRIB_name :
      Particulate matter d <= 10 um
      GRIB_shortName :
      pm10
      GRIB_totalNumber :
      0
      GRIB_units :
      kg m**-3
      long_name :
      Particulate matter d <= 10 um
      units :
      kg m**-3
      standard_name :
      mass_concentration_of_pm10_ambient_aerosol_particles_in_air
      [242352 values with dtype=float32]
    • t2m
      (time, latitude, longitude)
      float32
      ...
      GRIB_paramId :
      167
      GRIB_dataType :
      an
      GRIB_numberOfPoints :
      30294
      GRIB_typeOfLevel :
      surface
      GRIB_stepUnits :
      1
      GRIB_stepType :
      instant
      GRIB_gridType :
      regular_ll
      GRIB_uvRelativeToGrid :
      0
      GRIB_NV :
      0
      GRIB_Nx :
      187
      GRIB_Ny :
      162
      GRIB_cfName :
      unknown
      GRIB_cfVarName :
      t2m
      GRIB_gridDefinitionDescription :
      Latitude/Longitude Grid
      GRIB_iDirectionIncrementInDegrees :
      0.75
      GRIB_iScansNegatively :
      0
      GRIB_jDirectionIncrementInDegrees :
      0.75
      GRIB_jPointsAreConsecutive :
      0
      GRIB_jScansPositively :
      0
      GRIB_latitudeOfFirstGridPointInDegrees :
      70.75
      GRIB_latitudeOfLastGridPointInDegrees :
      -50.0
      GRIB_longitudeOfFirstGridPointInDegrees :
      150.0
      GRIB_longitudeOfLastGridPointInDegrees :
      289.5
      GRIB_missingValue :
      3.4028234663852886e+38
      GRIB_name :
      2 metre temperature
      GRIB_shortName :
      2t
      GRIB_totalNumber :
      0
      GRIB_units :
      K
      long_name :
      2 metre temperature
      units :
      K
      standard_name :
      unknown
      [242352 values with dtype=float32]
    • msl
      (time, latitude, longitude)
      float32
      ...
      GRIB_paramId :
      151
      GRIB_dataType :
      an
      GRIB_numberOfPoints :
      30294
      GRIB_typeOfLevel :
      surface
      GRIB_stepUnits :
      1
      GRIB_stepType :
      instant
      GRIB_gridType :
      regular_ll
      GRIB_uvRelativeToGrid :
      0
      GRIB_NV :
      0
      GRIB_Nx :
      187
      GRIB_Ny :
      162
      GRIB_cfName :
      air_pressure_at_mean_sea_level
      GRIB_cfVarName :
      msl
      GRIB_gridDefinitionDescription :
      Latitude/Longitude Grid
      GRIB_iDirectionIncrementInDegrees :
      0.75
      GRIB_iScansNegatively :
      0
      GRIB_jDirectionIncrementInDegrees :
      0.75
      GRIB_jPointsAreConsecutive :
      0
      GRIB_jScansPositively :
      0
      GRIB_latitudeOfFirstGridPointInDegrees :
      70.75
      GRIB_latitudeOfLastGridPointInDegrees :
      -50.0
      GRIB_longitudeOfFirstGridPointInDegrees :
      150.0
      GRIB_longitudeOfLastGridPointInDegrees :
      289.5
      GRIB_missingValue :
      3.4028234663852886e+38
      GRIB_name :
      Mean sea level pressure
      GRIB_shortName :
      msl
      GRIB_totalNumber :
      0
      GRIB_units :
      Pa
      long_name :
      Mean sea level pressure
      units :
      Pa
      standard_name :
      air_pressure_at_mean_sea_level
      [242352 values with dtype=float32]
    • tcco
      (time, latitude, longitude)
      float32
      ...
      GRIB_paramId :
      210127
      GRIB_dataType :
      an
      GRIB_numberOfPoints :
      30294
      GRIB_typeOfLevel :
      surface
      GRIB_stepUnits :
      1
      GRIB_stepType :
      instant
      GRIB_gridType :
      regular_ll
      GRIB_uvRelativeToGrid :
      0
      GRIB_NV :
      0
      GRIB_Nx :
      187
      GRIB_Ny :
      162
      GRIB_cfName :
      atmosphere_mass_content_of_carbon_monoxide
      GRIB_cfVarName :
      tcco
      GRIB_gridDefinitionDescription :
      Latitude/Longitude Grid
      GRIB_iDirectionIncrementInDegrees :
      0.75
      GRIB_iScansNegatively :
      0
      GRIB_jDirectionIncrementInDegrees :
      0.75
      GRIB_jPointsAreConsecutive :
      0
      GRIB_jScansPositively :
      0
      GRIB_latitudeOfFirstGridPointInDegrees :
      70.75
      GRIB_latitudeOfLastGridPointInDegrees :
      -50.0
      GRIB_longitudeOfFirstGridPointInDegrees :
      150.0
      GRIB_longitudeOfLastGridPointInDegrees :
      289.5
      GRIB_missingValue :
      3.4028234663852886e+38
      GRIB_name :
      Total column Carbon monoxide
      GRIB_shortName :
      tcco
      GRIB_totalNumber :
      0
      GRIB_units :
      kg m**-2
      long_name :
      Total column Carbon monoxide
      units :
      kg m**-2
      standard_name :
      atmosphere_mass_content_of_carbon_monoxide
      [242352 values with dtype=float32]
    • time
      PandasIndex
      PandasIndex(DatetimeIndex(['2016-12-21 00:00:00', '2016-12-21 06:00:00',
                     '2016-12-21 12:00:00', '2016-12-21 18:00:00',
                     '2016-12-22 00:00:00', '2016-12-22 06:00:00',
                     '2016-12-22 12:00:00', '2016-12-22 18:00:00'],
                    dtype='datetime64[ns]', name='time', freq=None))
    • latitude
      PandasIndex
      PandasIndex(Index([ 70.75,   70.0,  69.25,   68.5,  67.75,   67.0,  66.25,   65.5,  64.75,
               64.0,
             ...
             -43.25,  -44.0, -44.75,  -45.5, -46.25,  -47.0, -47.75,  -48.5, -49.25,
              -50.0],
            dtype='float64', name='latitude', length=162))
    • longitude
      PandasIndex
      PandasIndex(Index([ 150.0, 150.75,  151.5, 152.25,  153.0, 153.75,  154.5, 155.25,  156.0,
             156.75,
             ...
             282.75,  283.5, 284.25,  285.0, 285.75,  286.5, 287.25,  288.0, 288.75,
              289.5],
            dtype='float64', name='longitude', length=187))
  • GRIB_edition :
    1
    GRIB_centre :
    ecmf
    GRIB_centreDescription :
    European Centre for Medium-Range Weather Forecasts
    GRIB_subCentre :
    0
    Conventions :
    CF-1.7
    institution :
    European Centre for Medium-Range Weather Forecasts
    history :
    2025-01-01T16:27 GRIB to CDM+CF via cfgrib-0.9.15.0/ecCodes-2.39.1 with {"source": "../../../../../tmp/tmptacb1_eq/ads-retriever-f5c106c0db93736042f233ebbd5bf5ef5119c7a4c943338308f26655ccc3399e.cache", "filter_by_keys": {}, "encode_cf": ["parameter", "time", "geography", "vertical"]}
In [9]:
# Apply the global mask to the climate data
masked_climate_data = ds_xr.isel(time=0).where(ar6_mask.sel(region=47))

# Plot the masked data
fig = masked_climate_data["pm10"].plot(figsize=(15, 5))
plt.title("PM10 concentration in region 47")
plt.show()
No description has been provided for this image
In [10]:
fig, ax = plt.subplots(1, 2, figsize=(15, 5))

masked_climate_data["tcco"].plot(ax=ax[0])
ax[0].set_title("Total column CO concentration in region 47")

masked_climate_data["msl"].plot(ax=ax[1])
ax[1].set_title("Mean sea level pressure in region 47")

fig.suptitle("Atmospheric data in region 47")

plt.show()
No description has been provided for this image

Iterate over interesting regions¶

In [ ]:
RELEVANT_LAND_REGIONS = [1, 3, 6, 7, 9, 13, 15]
RELEVANT_OCEAN_REGIONS = [47, 48, 49]

RELEVANT_REGIONS = RELEVANT_OCEAN_REGIONS # + RELEVANT_LAND_REGIONS

VARIABLE_NAMES = {
    "pm10": "PM10 concentration",
    "tcco": "Total column CO concentration",
    "msl": "Mean sea level pressure",
    "t2m": "2m temperature",
}

ds_path = '/tmp/tmptacb1_eq/ads-retriever-f5c106c0db93736042f233ebbd5bf5ef5119c7a4c943338308f26655ccc3399e.cache'
ds_xr = xr.open_dataset(ds_path, engine='cfgrib')

globe_xr = xr.Dataset(
    {
        "lon": (["lon"], np.linspace(-179.99, 180, 360)),
        "lat": (["lat"], np.linspace(-90, 90, 180)),
    }
)
ar6_mask = ar6_regions.mask_3D(globe_xr)


def plot_region_data(
    ds, 
    region_number, 
    variable,
    name=None,
    ax=None,
    global_mask=ar6_mask, 
):
    if ax is None:
        _, ax = plt.subplots()

    if name is None:
        name = variable
    
    region_mask = global_mask.sel(region=region_number)
    masked_ds = ds.where(region_mask)
    masked_ds[variable].plot(ax=ax)
    ax.set_title(f"{VARIABLE_NAMES[variable]} in region {region_number}")


time_idx = 0
for region_number in RELEVANT_REGIONS:
    # simliar to mosaic but with mixed projections
    fig = plt.figure(figsize=(10, 10))
    gs = fig.add_gridspec(3, 2)
    axs = {
        'A': fig.add_subplot(gs[0, :], projection=ccrs.PlateCarree()),
        'B': fig.add_subplot(gs[1, 0]),
        'C': fig.add_subplot(gs[1, 1]),
        'D': fig.add_subplot(gs[2, 0]),
        'E': fig.add_subplot(gs[2, 1]),
    }
    ax_keys = list(axs.keys())

    # draw mask region
    ar6_mask.sel(region=region_number).plot(ax=axs[ax_keys[0]], alpha=0.75)
    axs[ax_keys[0]].set_title(f"Region {region_number}")
    axs[ax_keys[0]].coastlines()
    axs[ax_keys[0]].add_feature(cfeature.BORDERS, linestyle=':')

    for i, (variable, name) in enumerate(VARIABLE_NAMES.items()):
        print(region_number, i, variable, ax_keys[i+1])
        plot_region_data(ds_xr.isel(time=time_idx), region_number, variable, name, axs[ax_keys[i+1]])
    
    plt.tight_layout()
    plt.show()
47 0 pm10 B
47 1 tcco C
47 2 msl D
47 3 t2m E
No description has been provided for this image
48 0 pm10 B
48 1 tcco C
48 2 msl D
48 3 t2m E
No description has been provided for this image
49 0 pm10 B
49 1 tcco C
49 2 msl D
49 3 t2m E
No description has been provided for this image