source: TOOLS/CPLRESTART/FillOceRestart.py @ 6755

Last change on this file since 6755 was 6669, checked in by omamce, 7 months ago

O.M. : CPLRESTART

  • More comments
  • Python cleanup
  • More use of nemo.py functionalities
  • Property svn:keywords set to Author Date Revision Id HeadURL
File size: 6.6 KB
Line 
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'''
23 All documentation available at https://forge.ipsl.jussieu.fr/igcmg/wiki/IPSLCM6/CPLRESTART
24
25Extraction :
26> svn co http://forge.ipsl.jussieu.fr/igcmg/svn/TOOLS/CPLRESTART CPLRESTART
27'''
28
29## SVN information
30__SVN__ = ({
31    'Author'   : "$Author$",
32    'Date'     : "$Date$",
33    'Revision' : "$Revision$",
34    'Id'       : "$Id$",
35    'HeadURL'  : "$HeadURL$",
36    })
37##
38import shutil
39import getopt
40import sys
41import numpy.ma as np
42import netCDF4
43from scipy import ndimage
44import nemo
45
46def MyFill (InputData=None) :
47    """
48    Replace the value of masked 'InputData' cells by the value of the nearest valid data cell
49    From https://stackoverflow.com/questions/5551286/filling-gaps-in-a-numpy-array
50
51    Input:  InputData : numpy.ma array of any dimension.
52
53    Output: Return a filled array.
54    """
55
56    Invalid = np.where ( InputData[:,:].mask, True, False)
57    Indices = ndimage.distance_transform_bf(Invalid, metric='euclidean', sampling=None, return_distances=False,
58                                            return_indices=True, distances=None )
59    FilledData = InputData[tuple(Indices)]
60    return FilledData
61
62def usage () :
63    __help__ = """%(prog)s usage :
64python %(prog)s [-d] -i <sstoce file> [-n <perio>] [-v variables] [-o <output file>]
65 -d           | --debug                : debug
66 -i <file>    | --input=<file>         : input file  (default: none)
67 -o <file>    | --output=<file>        : output file (default : build a name form input file)
68 -r           | --replace              : replace input file by new file with filled variables
69 -v <varlist> | --variable=<variables> : list of variable to fill (default: all variable in file)
70 -x           | --exclude              : fills all variable in files, except those given in -v|--variable
71 -n <perio>   | --perio=<perio> : periodicity type (default: try to guess)
72    1, 4, 6 : Cyclic on i dimension (generaly longitudes)
73    2       : Obsolete (was symmetric condition at southern boundary ?)
74    3, 4    : North fold T-point pivot (legacy ORCA2)
75    5, 6    : North fold F-point pivot (ORCA1, ORCA025, ORCA2 with new grid for paleo)
76    If <perio> is not specified, %(prog)s will try to guess it from the grid dimensions
77example :
78    python %(prog)s -n 4 -i sstoce_ORCA2.3.nc
79    python %(prog)s -n 4 -i sstoce_ORCA2.3.nc -v O_SSTSST,OIceFrc
80    """
81    print ( __help__ % { 'prog':sys.argv[0] } )
82
83## Default input parameters
84InFile      = None
85OuFile      = None
86replace     = False
87ListVarName = None
88nperio      = None
89Debug       = False
90ListExclude = None
91Exclude     = False
92
93## Command line options
94try:
95    myopts, myargs = getopt.getopt ( sys.argv[1:], 'i:o:rv:xp:hd',
96                                [ 'input=', 'output=', 'replace', 'exclude', 'variable=', 'variables=', 'perio=', 'debug', 'help' ] )
97except getopt.GetoptError as cmdle :
98    print ( "Command line error : "+str(cmdle)+"\n" )
99    usage ()
100    sys.exit(1)
101
102for myopt, myval in myopts :
103    if   myopt in [ '-h', '--help'    ] : usage () ; sys.exit (0)
104    elif myopt in [ '-d', '--debug'   ] : Debug    = True
105    elif myopt in [ '-i', '--input'   ] : InFile   = myval
106    elif myopt in [ '-o', '--output'  ] :
107        if replace :
108            print ("Error : you can not specify both -r|--replace and -o|--output" )
109            usage ()
110            sys.exit(1)
111        else :
112            OuFile   = myval
113            if Debug : print ("Out file set to " + OuFile)
114    elif myopt in [ '-r', '--replace' ] :
115        if OuFile is not None :
116            print ("Error : you can not specify both -r|--replace and -o|--output" )
117            usage ()
118            sys.exit(1)
119        else :
120            if Debug : print ("Out file set to input file")
121            OuFile   = InFile
122    elif myopt in [ '-p', '--perio'     ] : nperio = int(myval)
123    elif myopt in [ '-v', '--variable', '--variables'  ] :
124        if Exclude : ListExclude = myval.split(',')
125        else :       ListVarName = myval.split(',')
126    elif myopt in [ '-x', '--exclude'  ] :
127        Exclude = True
128        if ListVarName is not None :
129            ListExclude = ListVarName
130            ListVarName  = None
131
132if OuFile is None :
133    print ( 'Definition OuFile' )
134    OuFile = InFile.replace ( ".nc", "_filled.nc" )
135    print ("Creates output file name: " + OuFile)
136
137# Copy the input file if needed
138if OuFile != InFile : shutil.copyfile ( InFile, OuFile )
139
140print ("Output file: " + OuFile )
141
142# Open file
143OuFile = netCDF4.Dataset ( OuFile , "r+" )
144
145# Try to guess periodicity type
146jpoi = OuFile.dimensions["x"].size
147jpoj = OuFile.dimensions["y"].size
148nperio = nemo.__guess_nperio__ (jpoj, jpoi, nperio=nperio, out='nperio')
149
150if nperio is None :
151    print ("%(prog)s couldn't guess the periodicity type of your file")
152    print ("Please specify -p|--perio")
153    usage ()
154    sys.exit(1)
155
156# Get variables from file is need
157if ListVarName is None : ListVarName = list ( OuFile.variables.keys() )
158
159# Exclude some var if needed
160for Var in ['time_centered', 'time_counter', 'time_centered_bounds', 'time_counter_bounds' ] :
161    if Var in ListVarName : ListVarName.remove(Var)
162if Exclude :
163    for Var in ListExclude :
164        if Var in ListVarName : ListVarName.remove(Var)
165
166# Loop on variables
167for VarName in ListVarName :
168    Var    = OuFile.variables[VarName]
169    if 'mask' in dir(Var[...]) :
170        print ( "Working on " + VarName )
171        NewVar = MyFill ( InputData = Var[...] )
172        NewVar = nemo.lbc (NewVar, nperio=nperio, cd_type='T', psgn=1.0)
173        OuFile.variables[VarName][:,:] = NewVar[:,:]
174    else :
175        print ( VarName + " is not masked" )
176
177# Close file : writes update variables.
178OuFile.close()
179
180## ===========================================================================
181##
182##                               That's all folk's !!!
183##
184## ===========================================================================
Note: See TracBrowser for help on using the repository browser.