subtracting variables within two different netcdf files

12.6k views Asked by At

I have two netcdf files: downwelling radiation named rsds.nc and confined radiation named rsns.nc. rsds.nc contains a variable named rsds and rsns.nc contains a variable named rsns. Now I would like to have the upwelling radiation rsus.nc by subtracting the variables within rsds.nc and rsns.nc, respectively.

I tried the following methods:

ncdiff rsds.nc rsns.nc rsus.nc
ncbo op_typ=diff rsds.nc rsns.nc rsus.nc

All of them produced a rsus.nc but the variable rsus, within this file is missing. Any idea of why this is so?

3

There are 3 answers

0
N1B4 On BEST ANSWER

As an alternative to @RichSignell's answer, you can combine variables into a single file and use ncap2 to perform the subtraction without renaming variables.

ncks -A rsns.nc rsds.nc 
ncap2 -s 'rsus=(rsds-rsns)' rsds.nc rsus.nc
1
Rich Signell On

Only variables with the same name are operated on when you ncdiff two files. So one solution would be to simply rename the variable in one of the files so it is the same. For example, try this:

ncrename -v rsds,rsns rsds.nc
ncdiff rsds.nc rsns.nc rsus.nc
0
ClimateUnboxed On

Two alternative CDO solutions.

1. The sledgehammer approach

The cdo sub command can do this on one line:

cdo sub rsds.nc rsns.nc rsus.nc

You will get the warning

cdo sub (Warning): Input streams have different parameters!

But you can ignore that. Note that you may want to change the variable name to something more appropriate, so you can do this on one line as:

cdo setname,rsus -sub rsds.nc rsns.nc rsus.nc

2. The expr approach

This just mimics the accepted answer but in cdo equivalent commands

cdo cat rsds.nc rsns.nc tmp.nc
cdo expr,"rsus=rsds-rsns" temp.nc rsus.nc

By the way, with all solutions on Thurs page you might want to use cdo chgattr or the nco equivalent to ensure the meta data is correct for your new field, especially if you intend to keep the files long term or pass them to other people.