gener_perturb_restart.bash 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. module load R
  19. set -o errexit
  20. set -o nounset
  21. set -x
  22. if [ $# == 0 ] ; then
  23. echo "gener_perturbation.bash ocean_restart_file Nmembers"
  24. exit
  25. fi
  26. filein=$1
  27. nmemb=$2
  28. # ---------------------------------------------------------
  29. var=tn # Variable to be perturbed
  30. per=0.0001 # Standard deviation of gaussian perturbation to be applied,
  31. # in units of the variable (for tn: in K for example)
  32. cp $filein ${filein}.backup # Do a backup
  33. for jmemb in `seq 0 $(( $nmemb -1 ))`
  34. do
  35. echo $jmemb
  36. # 1. Make a copy of the original file, with the new name
  37. filenew="${filein%.nc}_fc${jmemb}.nc"
  38. cp $filein $filenew
  39. # 2. Prepare the R script
  40. echo "#!/usr/bin/env Rscript
  41. library(ncdf)
  42. # François Massonnet, 30 Jan 2015
  43. # Adds a gaussian perturbation at the first level of a 3D field
  44. # Tested only for NEMO restarts
  45. #
  46. # This script should be called by a bash script so that the variable and file names are specified, as well as the perturbation
  47. varname='$var'
  48. filein <- '$filenew'
  49. ex.nc <- open.ncdf(filein,write=TRUE)
  50. spert <- $per
  51. myvar <- get.var.ncdf(ex.nc, varname)
  52. myvarpert <- myvar
  53. for (i in seq(1,dim(myvar)[1])){
  54. for (j in seq(1,dim(myvar)[2])){
  55. if (myvar[i,j,1] != 0){
  56. myvarpert[i,j,1] = myvarpert[i,j,1] + rnorm(1,sd=spert)
  57. }
  58. }
  59. }
  60. put.var.ncdf(ex.nc,varname,myvarpert)
  61. close.ncdf(ex.nc)" > Rtmpfile.R
  62. chmod 744 Rtmpfile.R
  63. # 3. Run the R script, that produces the new NetCDF
  64. ./Rtmpfile.R
  65. rm -f Rtmpfile.R
  66. done