source: TOOLS/CPLRESTART/FillOceRestart.py @ 4603

Last change on this file since 4603 was 4289, checked in by omamce, 5 years ago

O.M. : CPLRESTART

  • Add filling of ocean variable on continents
  • Add more parameters to increase versability
  • Property svn:keywords set to Author Date Revision Id HeadURL
File size: 7.3 KB
RevLine 
[3738]1### ===========================================================================
2###
3### Fill a coupler restart, ocean side
4###
5### ===========================================================================
6##
7##  Warning, to install, configure, run, use any of Olivier Marti's
8##  software or to read the associated documentation you'll need at least
9##  one (1) brain in a reasonably working order. Lack of this implement
10##  will void any warranties (either express or implied).
11##  O. Marti assumes no responsability for errors, omissions,
12##  data loss, or any other consequences caused directly or indirectly by
13##  the usage of his software by incorrectly or partially configured
14##  personal.
15##
16## SVN information
17__Author__   = "$Author$"
18__Date__     = "$Date$"
19__Revision__ = "$Revision$"
20__Id__       = "$Id$"
21__HeadURL    = "$HeadURL$"
22##
23import netCDF4
24import numpy.ma as np
25from scipy import ndimage
26import nemo
27import shutil, getopt, sys
28
29def MyFill (InputData=None) :
30    """
31    Replace the value of masked 'InputData' cells by the value of the nearest valid data cell
32    From https://stackoverflow.com/questions/5551286/filling-gaps-in-a-numpy-array
33   
[3741]34    Input:  InputData : numpy.ma array of any dimension.
[3738]35
36    Output: Return a filled array.
37    """   
38
39    Invalid = np.where ( InputData[:,:].mask, True, False)
40    Indices = ndimage.distance_transform_bf(Invalid, metric='euclidean', sampling=None, return_distances=False,
41                                            return_indices=True, distances=None )
42    FilledData = InputData[tuple(Indices)]
43    return FilledData
44
45def usage () :
[3741]46    __help__ = """%(prog)s usage :
47python %(prog)s [-d] -i <sstoce file> [-n <perio>] [-v variables] [-o <output file>]
[3738]48 -d           | --debug                : debug
49 -i <file>    | --input=<file>         : input file  (default: none)
[3741]50 -o <file>    | --output=<file>        : output file (default : build a name form input file)
51 -r           | --replace              : replace input file by new file with filled variables
[4289]52 -v <varlist> | --variable=<variables> : list of variable to fill (default: all variable in file)
[3741]53 -x           | --exclude              : fills all variable in files, except those given in -v|--variable
[3738]54 -n <perio>   | --perio=<perio> : periodicity type (default: try to guess)
[3741]55    1, 4, 6 : Cyclic on i dimension (generaly longitudes)
56    2       : Obsolete (was symmetric condition at southern boundary ?)
57    3, 4    : North fold T-point pivot (legacy ORCA2)
58    5, 6    : North fold F-point pivot (ORCA1, ORCA025, ORCA2 with new grid for paleo)
[3738]59    If <perio> is not specified, %(prog)s will try to guess it from the grid dimensions
60example :
61    python %(prog)s -n 4 -i sstoce_ORCA2.3.nc
62    python %(prog)s -n 4 -i sstoce_ORCA2.3.nc -v O_SSTSST,OIceFrc
63    """
[3741]64    print ( __help__ % { 'prog':sys.argv[0] } )
[3738]65
66## Default input parameters
67InFile      = None
68OuFile      = None
69replace     = False
70ListVarName = None
71nperio      = None
72Debug       = False
73ListExclude = None ; Exclude=False
74
75## Command line options
76try:
[3741]77    myopts, myargs = getopt.getopt ( sys.argv[1:], 'i:o:rv:xp:hd',
78                                         [ 'input=', 'output=', 'replace', 'exclude', 'variable=', 'variables=', 'perio=', 'debug', 'help' ] )
[3738]79except getopt.GetoptError as cmdle :
80    print ( "Command line error : "+str(cmdle)+"\n" )
81    usage ()
82    sys.exit(1)
83
84for myopt, myval in myopts :
85    if   myopt in [ '-h', '--help'    ] : usage () ; sys.exit (0) ;
86    elif myopt in [ '-d', '--debug'   ] : Debug    = True  ;
87    elif myopt in [ '-i', '--input'   ] : InFile   = myval ;
88    elif myopt in [ '-o', '--output'  ] :
89        if replace :
90            print ("Error : you can not specify both -r|--replace and -o|--output" )
91            usage ()
92            sys.exit(1)
93        else :
94            OuFile   = myval ;
[4289]95            if Debug : print ("Out file set to " + OuFile)
[3738]96    elif myopt in [ '-r', '--replace' ] :
97        if OuFile != None :
98            print ("Error : you can not specify both -r|--replace and -o|--output" )
99            usage ()
100            sys.exit(1)
101        else :
102            if Debug : print ("Out file set to input file")
[3741]103            OuFile   = InFile ;
[3738]104    elif myopt in [ '-p', '--perio'     ] : nperio = int(myval) ;
[3741]105    elif myopt in [ '-v', '--variable', '--variables'  ] :
106        if Exclude : ListExclude = myval.split(',')         
107        else :       ListVarName = myval.split(',')
[3738]108    elif myopt in [ '-x', '--exclude'  ] :
109        Exclude = True
110        if ListVarName != None :
111            ListExclude = ListVarName
112            ListVarName  = None
[4289]113
[3738]114if OuFile == None :
[4289]115    print ( 'Definition OuFile' )
[3738]116    OuFile = InFile.replace ( ".nc", "_filled.nc" )
[4289]117    print ("Creates output file name: " + OuFile)
[3738]118
119# Copy the input file if needed
120if OuFile != InFile : shutil.copyfile ( InFile, OuFile )
121
122print ("Output file: " + OuFile )
123
124# Open file
125OuFile = netCDF4.Dataset ( OuFile , "r+" )
126
127# Try to guess periodicity type
128if nperio == None :
[3741]129    print ( "Trying to guess nperio parameter" )
[3738]130    jpoi = OuFile.dimensions["x"].size
131    jpoj = OuFile.dimensions["y"].size
132    print ("Grid dimensions: ("+str(jpoj)+", "+str(jpoi)+")")
[3741]133    if   'ORCA2' in InFile :
[4289]134        nperio=4
[3741]135        print ("ORCA 2 grid found from file name: nperio may vary for this configuration")
[4289]136        print ("Choosen nperio=" + str(nperio) )
[3741]137    elif 'ORCA1' in InFile :
[4289]138        if 'eORCA1' in InFile :
139            nperio=6
140            print ("eORCA 1 grid found from file name, nperio=" + str(nperio))
[3741]141        else :
[4289]142            nperio=6
143            print ("ORCA 1 grid found from file name, nperio=" + str(nperio))
[3741]144    elif (jpoj, jpoi) == (149, 182) :
[4289]145        nperio = 4
[3741]146        print ("ORCA 2 grid found from dimension: nperio may vary for this configuration")
[4289]147        print ("Choosen nperio=" + str(nperio))
[3741]148    elif (jpoj, jpoi) == (332, 292) :
[3738]149        nperio = 6
[4289]150        print ("ORCA1 grid found from dimensions, nperio" + str(nperio) )
[3741]151    elif (jpoj, jpoi) == (332, 362) :
[3738]152        nperio = 6
[4289]153        print ("eORCA1 grid found from dimensions, nperio" + str(nperio) )
[4249]154    elif (jpoj, jpoi) == (1021, 1442) :
[4289]155        nperio = 6
156        print ("ORCA025 grid found from dimensions, nperio" + str(nperio) )
[4249]157    elif (jpoj, jpoi) == (1207, 1442) :
[4289]158        nperio = 6
159        print ("eORCA025 grid found from dimensions, nperio=" + str(nperio) )
[3741]160       
[3738]161if nperio == None :
[3741]162    print ("%(prog)s couldn't guess the periodicity type of your file")
163    print ("Please specify -p|--perio")
[3738]164    usage ()
165    sys.exit(1)
166   
167# Get variables from file is need
168if ListVarName == None : ListVarName = list ( OuFile.variables.keys() )
169
170# Exclude some var if needed
[3741]171if Exclude : 
[3738]172    for Var in ListExclude : 
173        if Var in ListVarName : ListVarName.remove(Var)
174
175# Loop on variables
176for VarName in ListVarName :
177    Var    = OuFile.variables[VarName]
[3741]178    if 'mask' in dir(Var[...]) :
[3738]179        print ( "Working on " + VarName )
[3741]180        NewVar = MyFill ( InputData = Var[...] )
[3738]181        NewVar = nemo.lbc (NewVar, nperio=nperio, cd_type='T', psgn=1.0)
182        OuFile.variables[VarName][:,:] = NewVar[:,:]
183    else :
184        print ( VarName + " is not masked" )
185       
186# Close file : writes update variables.   
[3741]187OuFile.close()
[3738]188
189## ===========================================================================
190##
191##                               That's all folk's !!!
192##
193## ===========================================================================
Note: See TracBrowser for help on using the repository browser.