More NetCDF commands

1. NetCDF file compression

ncks -L 2 in.nc out.nc    # 2 is the compression ratio, could be 2-9

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

ncks -d time,0,30 in.nc out.nc     
ncks -F -d time,1,31 in.nc out.nc  (equivalent)

3. Merge time using NCO

ncks --mk_rec_dmn time in.nc out.nc
ncrcat *.nc out.nc
Advertisements

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 in.nc out.nc #extract the timestep 1, 32, and 61 from in.nc

Extract data by variable

cdo -O selname,storage in.nc out.nc #extract the storage variable

or

ncks -A -v storage in.nc out.nc

Delete data by timestep

cdo -O delete,timestep=13 temp.nc temp1.nc # delete the 13th time frame

Rename a variable

ncrename -v OldVarName,NewVarName in.nc #change variable name

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

cdo -O add/sub/mul/div in1.nc in2.nc out.nc #add two nc files and output

Multiply by a constant (e.g. 0)

cdo -O mulc,0 in1.nc out.nc

Create new variable by adding others

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

Add the field

cdo -O fldsum in.nc out.nc #add the value at each field

4. I/O
Output to ascii

cdo output in.nc > out.txt

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

 ncview -frame in.nc

Clip a basin in NetCDF

Problem: I want to clip a basin (e.g. Nena) from a global netcdf file (e.g. global.nc) and output a new .nc file (nena.nc). 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 global.nc lena.nc