More NetCDF commands

1. NetCDF file compression

ncks -L 2    # 2 is the compression ratio, could be 2-9

2. Split file by dimension (e.g. time, lat, lon)

ncks -d time,0,30     
ncks -F -d time,1,31  (equivalent)

3. Merge time using NCO

ncks --mk_rec_dmn time
ncrcat *.nc

Handling NetCDF

1. See data

ncdump -h or -c  #see the dimension and data info

2. Manipulating data
Extract data by timestep

cdo -O seltimestep,1,32,61 #extract the timestep 1, 32, and 61 from

Extract data by variable

cdo -O selname,storage #extract the storage variable


ncks -A -v storage

Delete data by timestep

cdo -O delete,timestep=13 # delete the 13th time frame

Rename a variable

ncrename -v OldVarName,NewVarName #change variable name

3. Math
Add/subtract/multiply/divide two nc files

cdo -O add/sub/mul/div #add two nc files and output

Multiply by a constant (e.g. 0)

cdo -O mulc,0

Create new variable by adding others

ncap -O -s "storage=SoilMoist_1+SoilMoist_2+SoilMoist_3+SWE" #add all storage terms together and create a new variable "storage"
cdo expr,'runoff=srfrun+subrun;'

Add the field

cdo -O fldsum #add the value at each field

4. I/O
Output to ascii

cdo output > out.txt

5. ncview
Output frame as .png file when using ncview

 ncview -frame

Clip a basin in NetCDF

Problem: I want to clip a basin (e.g. Nena) from a global netcdf file (e.g. and output a new .nc file ( What I have is a shapefile of this basin.

Step1: Generate a set of coordinates of the basin boundary.
In ArcGIS, use “Feature Vertices To Points” and then “Export Feature Attribute to ASCII” to output the coordinates file (lena.txt), which looks like

 113.25000000 52.25000000 1
 113.25000000 52.50000000 2
 113.00000000 52.50000000 3
 113.00000000 52.25000000 4
 112.75000000 52.25000000 5
 112.75000000 52.50000000 6
 112.50000000 52.50000000 7
 112.50000000 52.25000000 8

then use “cut” in shell to cut the last column.

Step2: Using cdo to clip the basin.

cdo maskregion,lena.txt