Search code examples
netcdfmaskingcdo-climatedata-masking

CDO : Masking 3D and 4D variables within the same netcdf file


I have a netcdf file called data.nc and a masking file called mask.nc. The data.nc file has a 3D variable A with dimensions over (time,long,lat), and 4D variable B with dimensions over (time,depth,long,lat).

The mask.nc file has two masking variables mask_3d (time,long,lat) and mask_4d (time,depth,long,lat) with 0 and 1 values.

So far, I am masking each variable separately using:

cdo -div -selname,A data.nc -selname,mask_3d mask.nc out.nc

and

cdo -div -selname,B data.nc -selname,mask_4d mask.nc out2.nc

My question is:

How can I mask both variables A and B in data.nc using only one command ?


Solution

  • I'm not sure this really qualifies as an answer, perhaps it should be more of a comment, but I think this is not possible with cdo. If I understand correctly, you essentially want the output to be in the same file (cdo only allows one output file, so by definition your question implies this).

    The reason is that you would need to cat the two output files together in order to get what you want, but because cdo cat allows you to cat a variable number of files together, and even use wildcards (e.g. cdo cat *.nc out.nc) then it doesn't know how many input files to expect and thus cdo does not let you pipe such commands in combination with other commands as it can't interpret them safely.

    Thus you would need to keep this as three lines (at least for a cdo based solution, I think, but stand to be corrected):

    cdo -div -selname,A data.nc -selname,mask_3d mask.nc out1.nc
    cdo -div -selname,B data.nc -selname,mask_4d mask.nc out2.nc
    cdo cat out?.nc out.nc 
    

    sorry about that... That said, once commands start to get long, I think that keeping them separate as here aids legibility of the code.