Friday, March 12, 2010

NCO example III

#!/bin/bash  
#  add a new row for the north pole with an average value of the last row
#  Usage: 
#        NorthPole.sh ori_file.nc [ncvar mod_file.nc]
#        NetCdf Operator (NCO) package is required
#
GuessVar(){
if [ -e $1 ]; then 
      ncvar=`ncdump -h $1 | grep "(time, lat, lon)" | awk '{print $2}' | awk -F\( '{print $1}'`
      if [ ${#ncvar} -eq 0 ]; then
          echo "Failed in guessing the variable name" 
          exit 
      else 
          echo "   I guess the potential variable in the $1 is $ncvar"      
      fi
 else
      echo "$1 can not be found!!!" 
      exit   
fi
} 
CheckLength()
{ 
  NL=`echo $1 | awk -F\. '{print NF}'`   return $NL
}
#------------------------------------------------------------------------------------------------  
if [ $# -lt 1 ]; then 
    sed -n '2,7p' NorthPole.sh    
    exit
 else
     if [ $# -eq 1 ]; then 
        if [ -e $1 ]; then 
           ncfile_ori=$1 
          ncfile_mod="mod_"${ncfile_ori} 
          GuessVar $ncfile_ori 
        else
           echo "$1 can not be found!!!" 
           exit
         fi
     elif [ $# -eq 2 ]; then
         ncfile_ori=$1
        CheckLength $2 
        if [ $? -eq 1 ]; then
           ncvar=$2 
           ncfile_mod="mod_"${ncfile_ori} 
       else 
          ncfile_mod=$2 
          GuessVar $ncfile_ori
        fi
     elif [ $# -eq 3 ]; then 
        ncfile_ori=$1 
        ncvar=$2 
        ncfile_mod=$3 
    fi 
 fi
 echo "original nc file: $ncfile_ori, output ncfile: $ncfile_mod, variable: $ncvar"
 myaddstr=" -s 'defdim(\"new_lat\",\$lat.size+1)' \
                       -s 'new_var[\$time,\$new_lat,\$lon]=0.0f'\ 
                       -s 'new_lat[\$new_lat]=0.0d'\ 
                      -s 'new_lat(0:\$lat.size-1)=lat'\
                      -s 'new_lat(\$lat.size)=90.0d' \ 
                      -s 'new_var(:,0:\$lat.size-1,0:\$lon.size-1)=${ncvar}' \
                      -s '*nnt=\$time.size; *nny=\$lat.size-1; *nnx=\$lon.size-1; *indt=0;' \ 
                     -s 'for (indt==0; indt<nnt; indt++)  new_var(indt,nny+1,:)=${ncvar}(indt,nny,0:nnx).avg();'"
 eval "ncap2 -O -v  ${myaddstr} ${ncfile_ori} ${ncfile_mod}" 

#rename variables 
ncwa -O -a lat ${ncfile_mod} tmp_${ncfile_mod} 
ncks -O -x -v lat tmp_${ncfile_mod} ${ncfile_mod} 
ncrename -d new_lat,lat -v new_var,${ncvar} -v new_lat,lat ${ncfile_mod} &&  rm -f tmp_${ncfile_mod} 
ncatted -a standard_name,lat,o,c,"latitude" ${ncfile_mod} 
ncatted -a long_name,lat,o,c,"latitude" ${ncfile_mod} 
ncatted -a units,lat,o,c,"degrees_north" ${ncfile_mod} 
ncatted -a axis,lat,o,c,"Y" ${ncfile_mod}

No comments:

ShowCalendar