gener_perturbation.bash 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/bin/bash
  2. #
  3. # -- Author : François Massonnet, francois.massonnet@ic3.cat
  4. # -- Date : 30 Jan 2015
  5. # -- At : IC3, Barcelona
  6. # -- Modified : 19 Jan 2016, omar.bellprat@bsc.es
  7. #
  8. # -- Purpose: Generation of an arbitrary number of NEMO oceanic restarts that are copies of a reference, plus a perturbation
  9. #
  10. # -- Method : The reference file is duplicated in this script, then read by a R script. The perturbation is introduced and finally written to this latter file.
  11. # The script must be placed into the restart directory (e.g. NEMO_Restart_23). The generated restarts have to be renamed after generation. This
  12. # script has been tested on MareNostrum3.
  13. #
  14. # -- Input : NEMO ocean restart from an EC-Earth 3.1 run
  15. # -- Output : N restarts with the same name,but with an index fc0, fc1, ... fcN-1 appended
  16. #
  17. # -- Limitations: Only the surface conditions are perturbed (level index: 1) but this can be changed in the R script
  18. set -o errexit
  19. set -o nounset
  20. set -x
  21. if [ $# == 0 ] ; then
  22. echo "gener_perturbation.bash ocean_restart_file Nmembers"
  23. exit
  24. fi
  25. filein=$1
  26. nmemb=$2
  27. # ---------------------------------------------------------
  28. var=tn # Variable to be perturbed
  29. per=0.0001 # Standard deviation of gaussian perturbation to be applied,
  30. # in units of the variable (for tn: in K for example)
  31. for jmemb in `seq 0 $(( $nmemb -1 ))`
  32. do
  33. echo $jmemb
  34. # 1. Make a copy of the original file, with the new name
  35. filenew="${filein%.nc}_fc${jmemb}.nc"
  36. cp $filein ${filein}.backup
  37. cp $filein $filenew
  38. # 2. Prepare the R script
  39. echo "#!/usr/bin/env Rscript
  40. library(ncdf)
  41. # François Massonnet, 30 Jan 2015
  42. # Adds a gaussian perturbation at the first level of a 3D field
  43. # Tested only for NEMO restarts
  44. #
  45. # This script should be called by a bash script so that the variable and file names are specified, as well as the perturbation
  46. varname='$var'
  47. filein <- '$filenew'
  48. ex.nc <- open.ncdf(filein,write=TRUE)
  49. spert <- $per
  50. myvar <- get.var.ncdf(ex.nc, varname)
  51. myvarpert <- myvar
  52. for (i in seq(1,dim(myvar)[1])){
  53. for (j in seq(1,dim(myvar)[2])){
  54. if (myvar[i,j,1] != 0){
  55. myvarpert[i,j,1] = myvarpert[i,j,1] + rnorm(1,sd=spert)
  56. }
  57. }
  58. }
  59. put.var.ncdf(ex.nc,varname,myvarpert)
  60. close.ncdf(ex.nc)" > Rtmpfile.R
  61. chmod 744 Rtmpfile.R
  62. # 3. Run the R script, that produces the new NetCDF
  63. ./Rtmpfile.R
  64. done