Skip to content

Instantly share code, notes, and snippets.

@Grace-Amondi
Last active October 1, 2021 12:28
Show Gist options
  • Save Grace-Amondi/8e9b949d0face3c17d54e56080e6827a to your computer and use it in GitHub Desktop.
Save Grace-Amondi/8e9b949d0face3c17d54e56080e6827a to your computer and use it in GitHub Desktop.
Bil to NetCDF Conversion
import numpy as np
import datetime as dt
import os
import gdal
import netCDF4
# Open .bil dataset
ds = gdal.Open('../Download/v2p0chirps201401.bil') # Data location
a = ds.ReadAsArray()
# Define shape
nlat,nlon = np.shape(a)
b = ds.GetGeoTransform() #bbox, interval
lon = np.arange(nlon)*b[1]+b[0]
lat = np.arange(nlat)*b[5]+b[3]
# start time for netcdf
basedate = dt.datetime(2014,1,1,0,0,0)
# initialize output netcdf file
nco = netCDF4.Dataset('../Output_nc/chirps_2014.nc','w',clobber=True) # Output name
# Create dimensions, variables and attributes:
nco.createDimension('lon',nlon)
nco.createDimension('lat',nlat)
nco.createDimension('time',None)
timeo = nco.createVariable('time','f4',('time'))
timeo.units = f'days since {basedate}'
timeo.standard_name = 'time'
timeo.calendar = 'gregorian'
timeo.axis = 'T'
lono = nco.createVariable('lon','f4',('lon'))
lono.units = 'degrees_east'
lono.standard_name = 'longitude'
lono.long_name = 'longitude'
lono.axis = 'X'
lato = nco.createVariable('lat','f4',('lat'))
lato.units = 'degrees_north'
lato.standard_name = 'latitude'
lato.long_name = 'latitude'
lato.axis = 'Y'
# Create container variable for CRS: lon/lat WGS84 datum
crso = nco.createVariable('crs','i4')
crso.long_name = 'Lon/Lat Coords in WGS84'
crso.grid_mapping_name='latitude_longitude'
crso.longitude_of_prime_meridian = 0.0
crso.semi_major_axis = 6378137.0
crso.inverse_flattening = 298.257223563
# Create float variable for precipitation data, with chunking
pcpo = nco.createVariable('precip', 'f4', ('time', 'lat', 'lon'),zlib=True,fill_value=-9999.)
pcpo.units = 'mm'
pcpo.standard_name = 'convective precipitation rate'
pcpo.long_name = 'Climate Hazards group InfraRed Precipitation with Stations'
pcpo.time_step = 'month'
pcpo.missing_value = -9999.
pcpo.geospatial_lat_min = -13.0
pcpo.geospatial_lat_max = 24.0
pcpo.geospatial_lon_min = 21.0
pcpo.geospatial_lon_max = 52.0
pcpo.grid_mapping = 'crs'
pcpo.set_auto_maskandscale(False)
# Additional attributes
nco.Conventions='CF-1.6'
nco.title = "CHIRPS v2.0"
nco.history = "created by Climate Hazards Group. University of California at Santa Barbara"
nco.version = "Version 2.0"
nco.comments = "time variable denotes the first day of the given dekad."
nco.website = "https://www.chc.ucsb.edu/data/chirps"
nco.date_created = "2021-09-25"
nco.creator_name = "Grace"
nco.creator_email = "gmiswa@icpac.net"
nco.institution = "UN World Food Programme"
nco.note = "The data is developed to support regular updating procedure for SPI analysis (https://github.com/wfpidn/SPI). This activities will support EADW to assess extreme dry and wet periods as part of ICPAC's Seasonal Monitoring"
# Write lon,lat
lono[:]=lon
lato[:]=lat
# Generate time
itime = 0
date=dt.datetime(2014,1,1,0,0,0)
dtime=(date-basedate).total_seconds()/86400.
timeo[itime]=dtime
# copy .bil array to .netcdf
pcpo[itime,:,:]=a
nco.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment