0

I have to use a .nc file as input in a model and such model requires projection_x_coordinate and projection_y_coordinate as variables but I don't have them. Is it possible to create them using pyproj, for instance? (file available here). My projparams are:

{'a': 6371229,
 'b': 6371229,
 'proj': 'stere',
 'lat_ts': 60.0,
 'lat_0': 90.0,
 'lon_0': 264.0}

My first idea was to use the information of the number of points (Nx in the file), the horizontal resolution (Dx) and the first points (e.g. latitudeOfFirstGridPointInDegrees) to create the desired variables but I don't know if it is the right thing to do.

0

You may be interested in rioxarray.

Due to https://github.com/mapbox/rasterio/issues/1248, you cannot use rioxarray.open_rasterio to generate CRS/coordinate info.

So, you will have to do it manually:

from rioxarray.rioxarray import affine_to_coords
import rasterio

with rasterio.Env(), rasterio.open("CMC_caps_HGT_ISBL_0050_ps3km_2018090900_P005.grib2") as rrr:
    riocrs = rrr.crs
    coords = affine_to_coords(rrr.transform, rrr.width, rrr.height)

Then, you can use rioxarray to read in the data, add attrs, and write to netcdf:

from pyproj.crs import CRS
import rioxarray

rds = rioxarray.open_rasterio("CMC_caps_HGT_ISBL_0050_ps3km_2018090900_P005.grib2", parse_coordinates=False)
rds = rds.assign_coords(coords)
rds.rio.write_crs(riocrs, inplace=True)
rds.spatial_ref.attrs.update(CRS.from_user_input(riocrs).to_cf())
rds.x.attrs["long_name"] = "x coordinate of projection"
rds.x.attrs["standard_name"] = "projection_x_coordinate"
rds.y.attrs["long_name"] = "y coordinate of projection"
rds.y.attrs["standard_name"] = "projection_y_coordinate"
rds.to_netcdf("CMC_caps_HGT_ISBL_0050_ps3km_2018090900_P005_coord.nc")
| improve this answer | |
  • it worked like a dream! Thank you, @snowman2 – Victor Aguiar Apr 9 at 11:56
  • I am glad to hear that it worked 👍 – snowman2 Apr 9 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.