- Timestamp:
- 09/14/23 15:08:35 (8 months ago)
- Location:
- TOOLS/WATER_BUDGET
- Files:
-
- 1 added
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
TOOLS/WATER_BUDGET/ATM_waterbudget.py
r6518 r6620 23 23 ### 24 24 ## Import system modules 25 import sys, os, shutil, subprocess, platform 26 import numpy as np 25 import sys, os, shutil#, subprocess, platform 27 26 import configparser, re 27 28 ## Import needed scientific modules 29 import numpy as np, xarray as xr 28 30 29 31 # Check python version … … 34 36 ## Import local module 35 37 import WaterUtils as wu 38 import libIGCM_sys 39 import nemo, lmdz 36 40 37 41 ## Creates parser for reading .ini input file 42 ## ------------------------------------------- 38 43 config = configparser.ConfigParser ( interpolation=configparser.ExtendedInterpolation() ) 39 44 config.optionxform = str # To keep capitals 40 45 41 46 ## Experiment parameters 47 ## --------------------- 42 48 ATM=None ; ATM_HIS='latlon' ; SRF_HIS='latlon' ; RUN_HIS='latlon' ; ORCA=None ; NEMO=None ; OCE_relax=False 43 49 OCE_icb=False ; Coupled=False ; Routing=None … … 45 51 46 52 ## 47 ARCHIVE=None ; STORAGE=None ; SCRATCHDIR=None ; R_IN=None ; rebuild=None 48 TmpDir=None ; RunDir=None ; FileOut=None53 ARCHIVE=None ; STORAGE=None ; SCRATCHDIR=None ; R_IN=None ; rebuild=None ; TmpDir=None 54 FileDir=None ; FileOut=None 49 55 dir_ATM_his=None ; dir_SRF_his=None ; dir_OCE_his=None ; dir_ICE_his=None 50 56 FileCommon=None ; file_ATM_his=None ; file_SRF_his=None ; file_RUN_his=None … … 61 67 ContinueOnError=False ; ErrorCount=0 ; SortIco = False 62 68 63 # Read command line arguments 69 ## Read command line arguments 70 ## --------------------------- 64 71 print ( "Name of Python script:", sys.argv[0] ) 65 72 IniFile = sys.argv[1] 66 # Text existence of IniFile 73 74 # Test existence of IniFile 67 75 if not os.path.exists (IniFile ) : 68 76 raise FileExistsError ( f"File not found : {IniFile = }" ) … … 75 83 FullIniFile = 'full_' + IniFile 76 84 85 ## Reading config.card if possible 86 ## ------------------------------- 87 ConfigCard = None 88 89 if 'Experiment' in config.keys () : ## Read Experiment on Config file if possible 90 if 'ConfigCard' in config['Experiment'].keys () : 91 ConfigCard = config['Experiment']['ConfigCard'] 92 print ( f'{ConfigCard=}' ) 93 94 if ConfigCard : ## Read config card if it exists 95 # Text existence of ConfigCard 96 if os.path.exists ( ConfigCard ) : 97 print ( f'Reading Config Card : {ConfigCard}' ) 98 ## Creates parser for reading .ini input file 99 MyReader = configparser.ConfigParser (interpolation=configparser.ExtendedInterpolation() ) 100 MyReader.optionxform = str # To keep capitals 101 102 MyReader.read (ConfigCard) 103 104 for VarName in ['JobName', 'ExperimentName', 'SpaceName', 'LongName', 'ModelName', 'TagName'] : 105 if VarName in MyReader['UserChoices'].keys() : 106 locals()[VarName] = MyReader['UserChoices'][VarName] 107 exec ( f'{VarName} = wu.setBool ({VarName})' ) 108 exec ( f'{VarName} = wu.setNum ({VarName})' ) 109 exec ( f'{VarName} = wu.setNone ({VarName})' ) 110 exec ( f'wu.{VarName} = {VarName}' ) 111 print ( f' {VarName:21} set to : {locals()[VarName]:}' ) 112 113 for VarName in ['PackFrequency'] : 114 if VarName in MyReader['Post'].keys() : 115 locals()[VarName] = MyReader['Post'][VarName] 116 exec ( f'{VarName} = wu.setBool ({VarName})' ) 117 exec ( f'{VarName} = wu.setNum ({VarName})' ) 118 exec ( f'{VarName} = wu.setNone ({VarName})' ) 119 exec ( f'wu.{VarName} = {VarName}' ) 120 print ( f' {VarName:21} set to : {locals()[VarName]:}' ) 121 else : 122 raise FileExistsError ( f"File not found : {ConfigCard = }" ) 123 77 124 ## Reading config file 125 ## ------------------- 78 126 for Section in ['Config', 'Experiment', 'libIGCM', 'Files', 'Physics' ] : 79 127 if Section in config.keys () : … … 85 133 exec ( f'{VarName} = wu.setNone ({VarName})' ) 86 134 exec ( f'wu.{VarName} = {VarName}' ) 87 print ( f' {VarName:21} set to : {locals()[VarName] :}' )135 print ( f' {VarName:21} set to : {locals()[VarName]}' ) 88 136 #exec ( f'del {VarName}' ) 89 137 90 138 print ( f'\nConfig file readed : {IniFile} ' ) 91 92 ##-- Some physical constants 93 if wu.unDefined ( 'Ra' ) : Ra = 6366197.7236758135 #-- Earth Radius (m) 94 if wu.unDefined ( 'Grav' ) : Grav = 9.81 #-- Gravity (m^2/s) 95 if wu.unDefined ( 'ICE_rho_ice' ) : ICE_rho_ice = 917.0 #-- Ice volumic mass (kg/m3) in LIM3 or SI3 96 if wu.unDefined ( 'ICE_rho_sno') : ICE_rho_sno = 330.0 #-- Snow volumic mass (kg/m3) in LIM3 or SI3 97 if wu.unDefined ( 'OCE_rho_liq' ) : OCE_rho_liq = 1026.0 #-- Ocean water volumic mass (kg/m3) in NEMO 98 if wu.unDefined ( 'ATM_rho' ) : ATM_rho = 1000.0 #-- Water volumic mass in atmosphere (kg/m^3) 99 if wu.unDefined ( 'SRF_rho' ) : SRF_rho = 1000.0 #-- Water volumic mass in surface reservoir (kg/m^3) 100 if wu.unDefined ( 'RUN_rho' ) : RUN_rho = 1000.0 #-- Water volumic mass of rivers (kg/m^3) 101 if wu.unDefined ( 'ICE_rho_pnd' ) : ICE_rho_pnd = 1000. #-- Water volumic mass in ice ponds (kg/m^3) 102 if wu.unDefined ( 'YearLength' ) : YearLength = 365.25 * 86400. #-- Year length (s) - Use only to compute drif in approximate unit 103 104 ##-- Set libIGCM and machine dependant values 139 140 ## Some physical constants 141 ## ======================= 142 if wu.unDefined ( 'Ra' ) : Ra = wu.Ra #-- Earth Radius (m) 143 if wu.unDefined ( 'Grav' ) : Grav = wu.Grav #-- Gravity (m^2/s 144 if wu.unDefined ( 'ICE_rho_ice' ) : ICE_rho_ice = wu.ICE_rho_ice #-- Ice volumic mass (kg/m3) in LIM3 145 if wu.unDefined ( 'ICE_rho_sno') : ICE_rho_sno = wu.ICE_rho_sno #-- Snow volumic mass (kg/m3) in LIM3 146 if wu.unDefined ( 'OCE_rho_liq' ) : OCE_rho_liq = wu.OCE_rho_liq #-- Ocean water volumic mass (kg/m3) in NEMO 147 if wu.unDefined ( 'ATM_rho' ) : ATM_rho = wu.ATM_rho #-- Water volumic mass in atmosphere (kg/m^3) 148 if wu.unDefined ( 'SRF_rho' ) : SRF_rho = wu.SRF_rho #-- Water volumic mass in surface reservoir (kg/m^3) 149 if wu.unDefined ( 'RUN_rho' ) : RUN_rho = wu.RUN_rho #-- Water volumic mass of rivers (kg/m^3) 150 if wu.unDefined ( 'ICE_rho_pnd' ) : ICE_rho_pnd = wu.ICE_rho_pnd #-- Water volumic mass in ice ponds (kg/m^3) 151 if wu.unDefined ( 'YearLength' ) : YearLength = wu.YearLength #-- Year length (s) 152 153 ## Set libIGCM and machine dependant values 154 ## ---------------------------------------- 105 155 if not 'Files' in config.keys () : config['Files'] = {} 106 156 … … 113 163 ICO = ( 'ICO' in wu.ATM ) 114 164 LMDZ = ( 'LMD' in wu.ATM ) 115 116 with open ('SetLibIGCM.py') as f: exec ( f.read() ) 165 166 mm = libIGCM_sys.config ( TagName=TagName, SpaceName=SpaceName, ExperimentName=ExperimentName, JobName=JobName, User=User, Group=Group, 167 ARCHIVE=None, SCRATCHDIR=None, STORAGE=None, R_IN=None, R_OUT=None, R_FIG=None, rebuild=None, TmpDir=None, 168 R_SAVE=None, R_FIGR=None, R_BUFR=None, R_BUF_KSH=None, REBUILD_DIR=None, POST_DIR=None ) 169 globals().update(mm) 170 117 171 config['Files']['TmpDir'] = TmpDir 118 119 if libIGCM : 120 config['libIGCM'] = { 'ARCHIVE':ARCHIVE, 'STORAGE':STORAGE, 'SCRATCHDIR':SCRATCHDIR, 'R_IN':R_IN, 'rebuild':rebuild } 121 122 ##-- Import specific module 123 import nemo, lmdz 124 ##-- Now import needed scientific modules 125 import xarray as xr 126 127 ##- Output file with water budget diagnostics 128 if wu.unDefined ( 'FileOut' ) : FileOut = f'ATM_waterbudget_{JobName}_{YearBegin}_{YearEnd}.out' 172 config['libIGCM'] = { 'ARCHIVE':ARCHIVE, 'STORAGE':STORAGE, 'TmpDir':TmpDir, 'R_IN':R_IN, 'rebuild':rebuild } 173 174 ## Defines begining and end of experiment 175 ## -------------------------------------- 176 if wu.unDefined ( 'DateBegin' ) : 177 DateBegin = f'{YearBegin}0101' 178 config['Experiment']['DateBegin'] = DateBegin 179 else : 180 YearBegin, MonthBegin, DayBegin = wu.DateSplit ( DateBegin ) 181 DateBegin = wu.FormatToGregorian ( DateBegin) 182 config['Experiment']['YearBegin'] = YearBegin 183 184 if wu.unDefined ( 'DateEnd' ) : 185 DateEnd = f'{YearEnd}1231' 186 config['Experiment']['DateEnd'] = DateEnd 187 else : 188 YearEnd, MonthEnd, DayEnd = wu.DateSplit ( DateEnd ) 189 DateEnd = wu.FormatToGregorian ( DateEnd) 190 191 if wu.unDefined ( 'PackFrequency' ) : 192 PackFrequency = YearEnd - YearBegin + 1 193 config['Experiment']['PackFrequency'] = f'{PackFrequency}' 194 195 if type ( PackFrequency ) == str : 196 if 'Y' in PackFrequency : PackFrequency = PackFrequency.replace ( 'Y', '') 197 if 'M' in PackFrequency : PackFrequency = PackFrequency.replace ( 'M', '') 198 PackFrequency = int ( PackFrequency ) 199 200 ## Output file with water budget diagnostics 201 ## ----------------------------------------- 202 if wu.unDefined ( 'FileOut' ) : FileOut = f'ATM_waterbudget_{JobName}_{DateBegin}_{DateEnd}.out' 129 203 config['Files']['FileOut'] = FileOut 130 204 131 205 f_out = open ( FileOut, mode = 'w' ) 132 206 133 ##- Useful functions 207 ## Useful functions 208 ## ---------------- 134 209 def kg2Sv (val, rho=ATM_rho) : 135 210 '''From kg to Sverdrup''' … … 141 216 142 217 def var2prt (var, small=False, rho=ATM_rho) : 143 if small : return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*100 0.218 if small : return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*100# 144 219 else : return var , kg2Sv(var, rho=rho) , kg2myear(var, rho=rho) 145 220 146 221 def prtFlux (Desc, var, Form='F', small=False, rho=ATM_rho, width=15) : 147 222 if small : 148 if Form in ['f', 'F'] : ff=" {:1 2.4e} kg | {:12.4f} mSv | {:12.4f} mm/year "149 if Form in ['e', 'E'] : ff=" {:1 2.4e} kg | {:12.4e} mSv | {:12.4e} mm/year "223 if Form in ['f', 'F'] : ff=" {:14.6e} kg | {:12.4f} mSv | {:12.4f} mm/year " 224 if Form in ['e', 'E'] : ff=" {:14.6e} kg | {:12.4e} mSv | {:12.4e} mm/year " 150 225 else : 151 if Form in ['f', 'F'] : ff=" {:1 2.4e} kg | {:12.4f} Sv | {:12.4f} m/year "152 if Form in ['e', 'E'] : ff=" {:1 2.4e} kg | {:12.4e} Sv | {:12.4e} m/year "153 echo ( (' {:>{width}} = ' +ff).format (Desc, *var2prt(var, small , rho=rho), width=width ) )226 if Form in ['f', 'F'] : ff=" {:14.6e} kg | {:12.4f} Sv | {:12.4f} m/year " 227 if Form in ['e', 'E'] : ff=" {:14.6e} kg | {:12.4e} Sv | {:12.4e} m/year " 228 echo ( (' {:>{width}} = ' +ff).format (Desc, *var2prt(var, small=small, rho=rho), width=width ) ) 154 229 return None 155 230 … … 162 237 return None 163 238 164 ##- Set libIGCM directories 239 ## Set libIGCM directories 240 ## ----------------------- 165 241 if wu.unDefined ('R_OUT' ) : R_OUT = os.path.join ( ARCHIVE , 'IGCM_OUT' ) 166 242 if wu.unDefined ('R_BUF' ) : R_BUF = os.path.join ( SCRATCHDIR, 'IGCM_OUT' ) … … 173 249 if wu.unDefined ('R_FIGR' ) : R_FIGR = os.path.join ( STORAGE, 'IGCM_OUT', L_EXP ) 174 250 175 config['libIGCM'] = { 'R_OUT':R_OUT, 'R_BUF':R_BUF, 'L_EXP':L_EXP, 'R_BUFR':R_BUFR, 'POST_DIR':POST_DIR, 176 'REBUILD_DIR':REBUILD_DIR, 'R_BUF_KSH':R_BUF_KSH, 'R_FIGR':R_FIGR } 177 178 ##- Set directory to extract files 179 if wu.unDefined ( 'RunDir' ) : RunDir = os.path.join ( TmpDir, f'WATER_{JobName}_{YearBegin}_{YearEnd}' ) 180 config['Files']['RunDir'] = RunDir 181 182 if not os.path.isdir ( RunDir ) : os.makedirs ( RunDir ) 251 config['libIGCM'].update ( { 'R_OUT':R_OUT, 'R_BUF':R_BUF, 'L_EXP':L_EXP, 'R_BUFR':R_BUFR, 'POST_DIR':POST_DIR, 252 'REBUILD_DIR':REBUILD_DIR, 'R_BUF_KSH':R_BUF_KSH, 'R_FIGR':R_FIGR, 'rebuild':rebuild } ) 253 254 ## Set directory to extract files 255 ## ------------------------------ 256 if wu.unDefined ( 'FileDir' ) : FileDir = os.path.join ( TmpDir, f'WATER_{JobName}' ) 257 config['Files']['FileDir'] = FileDir 258 259 if not os.path.isdir ( FileDir ) : os.makedirs ( FileDir ) 183 260 184 261 ##- Set directories to rebuild ocean and ice restart files 185 if wu.unDefined ( ' RunDirOCE' ) : RunDirOCE = os.path.join ( RunDir, 'OCE' )186 if wu.unDefined ( ' RunDirICE' ) : RunDirICE = os.path.join ( RunDir, 'ICE' )187 if not os.path.exists ( RunDirOCE ) : os.mkdir ( RunDirOCE )188 if not os.path.exists ( RunDirICE ) : os.mkdir ( RunDirICE )262 if wu.unDefined ( 'FileDirOCE' ) : FileDirOCE = os.path.join ( FileDir, 'OCE' ) 263 if wu.unDefined ( 'FileDirICE' ) : FileDirICE = os.path.join ( FileDir, 'ICE' ) 264 if not os.path.exists ( FileDirOCE ) : os.mkdir ( FileDirOCE ) 265 if not os.path.exists ( FileDirICE ) : os.mkdir ( FileDirICE ) 189 266 190 267 echo (' ') 191 echo ( f'JobName : {JobName}' )192 echo ( f'Comment : {Comment}' )193 echo ( f'TmpDir : {TmpDir}' )194 echo ( f' RunDir : {RunDir}' )195 echo ( f' RunDirOCE : {RunDirOCE}' )196 echo ( f' RunDirICE : {RunDirICE}' )268 echo ( f'JobName : {JobName}' ) 269 echo ( f'Comment : {Comment}' ) 270 echo ( f'TmpDir : {TmpDir}' ) 271 echo ( f'FileDir : {FileDir}' ) 272 echo ( f'FileDirOCE : {FileDirOCE}' ) 273 echo ( f'FileDirICE : {FileDirICE}' ) 197 274 198 275 echo ( f'\nDealing with {L_EXP}' ) 199 276 200 ##-- Creates model output directory names 277 ## Creates model output directory names 278 ## ------------------------------------ 201 279 if Freq == "MO" : FreqDir = os.path.join ('Output' , 'MO' ) 202 280 if Freq == "SE" : FreqDir = os.path.join ('Analyse', 'SE' ) … … 214 292 ##-- Creates files names 215 293 if wu.unDefined ( 'Period' ) : 216 if Freq == 'MO' : Period = f'{ YearBegin}0101_{YearEnd}1231_1M'217 if Freq == 'SE' : Period = f'SE_{ YearBegin}0101_{YearEnd}1231_1M'294 if Freq == 'MO' : Period = f'{DateBegin}_{DateEnd}_1M' 295 if Freq == 'SE' : Period = f'SE_{DateBegin}_{DateEnd}_1M' 218 296 config['Files']['Period'] = Period 297 298 config['Files']['DateBegin'] = DateBegin 299 config['Files']['DateBegin'] = DateEnd 300 301 echo ( f'Period : {Period}' ) 302 219 303 if wu.unDefined ( 'FileCommon' ) : 220 304 FileCommon = f'{JobName}_{Period}' … … 222 306 223 307 if wu.unDefined ( 'Title' ) : 224 Title = f'{JobName} : {Freq} : { YearBegin}-01-01 - {YearEnd}-12-31'308 Title = f'{JobName} : {Freq} : {DateBegin} - {DateEnd}' 225 309 config['Files']['Title'] = Title 226 310 … … 256 340 if Routing == 'SIMPLE' : echo ( f'{file_RUN_his = }' ) 257 341 258 ##-- Compute run length 342 ## Compute run length 343 ## ------------------ 259 344 dtime = ( d_ATM_his.time_counter_bounds.max() - d_ATM_his.time_counter_bounds.min() ) 260 345 echo ('\nRun length : {:8.2f} days'.format ( (dtime/np.timedelta64(1, "D")).values ) ) … … 272 357 273 358 ##-- Extract restart files from tar 274 YearRes = YearBegin - 1 # Year of the restart of beginning of simulation 275 YearPre = YearBegin - PackFrequency # Year to find the tarfile of the restart of beginning of simulation 276 277 config['Files']['YearPre'] = f'{YearBegin}' 278 279 if wu.unDefined ( 'TarRestartPeriod_beg' ) : 280 echo (f'Restart dates - Start : {YearRes}-12-31 / End : {YearEnd}-12-31 ') 281 TarRestartPeriod_beg = f'{YearPre}0101_{YearRes}1231' 359 360 if wu.unDefined ('TarRestartDate_beg' ) : TarRestartDate_beg = wu.DateMinusOneDay ( DateBegin ) 361 if wu.unDefined ('TarRestartDate_end' ) : TarRestartDate_end = wu.FormatToGregorian ( DateEnd ) 362 363 if wu.unDefined ( 'TarRestartPeriod_beg' ) : 364 365 TarRestartPeriod_beg_DateEnd = TarRestartDate_beg 366 TarRestartPeriod_beg_DateBeg = wu.DateAddYear ( TarRestartPeriod_beg_DateEnd, -PackFrequency ) 367 TarRestartPeriod_beg_DateBeg = wu.DatePlusOneDay ( TarRestartPeriod_beg_DateBeg ) 368 369 TarRestartPeriod_beg = f'{TarRestartPeriod_beg_DateBeg}_{TarRestartPeriod_beg_DateEnd}' 370 echo (f'Tar period for initial restart : {TarRestartPeriod_beg}') 282 371 config['Files']['TarRestartPeriod_beg'] = TarRestartPeriod_beg 283 372 284 if wu.unDefined ( 'TarRestartPeriod_end ' ) : 285 YearPre = YearBegin - PackFrequency # Year to find the tarfile of the restart of beginning of simulation 286 echo (f'Restart dates - Start : {YearRes}-12-31 / End : {YearEnd}-12-31 ') 287 TarRestartPeriod_end = f'{YearBegin}0101_{YearEnd}1231' 373 if wu.unDefined ( 'TarRestartPeriod_end' ) : 374 375 TarRestartPeriod_end_DateEnd = TarRestartDate_end 376 TarRestartPeriod_end_DateBeg = wu.DateAddYear ( TarRestartPeriod_end_DateEnd, -PackFrequency ) 377 TarRestartPeriod_end_DateBeg = wu.DatePlusOneDay ( TarRestartPeriod_end_DateBeg ) 378 379 TarRestartPeriod_end = f'{TarRestartPeriod_end_DateBeg}_{TarRestartPeriod_end_DateEnd}' 380 echo (f'Tar period for final restart : {TarRestartPeriod_end}') 288 381 config['Files']['TarRestartPeriod_end'] = TarRestartPeriod_end 382 383 echo (f'Restart dates - Start : {TarRestartPeriod_beg} / End : {TarRestartPeriod_end}') 289 384 290 385 if wu.unDefined ( 'tar_restart_beg' ) : … … 316 411 317 412 if wu.unDefined ( 'file_ATM_beg' ) : 318 file_ATM_beg = f'{ RunDir}/ATM_{JobName}_{YearRes}1231_restartphy.nc'413 file_ATM_beg = f'{FileDir}/ATM_{JobName}_{TarRestartDate_beg}_restartphy.nc' 319 414 config['Files']['file_ATM_beg'] = file_ATM_beg 320 415 if wu.unDefined ( 'file_ATM_end' ) : 321 file_ATM_end = f'{ RunDir}/ATM_{JobName}_{YearEnd}1231_restartphy.nc'416 file_ATM_end = f'{FileDir}/ATM_{JobName}_{TarRestartDate_end}_restartphy.nc' 322 417 config['Files']['file_ATM_end'] = file_ATM_end 323 418 … … 326 421 327 422 if wu.unDefined ( 'file_DYN_beg' ) : 328 if LMDZ : file_DYN_beg = f'{ RunDir}/ATM_{JobName}_{YearRes}1231_restart.nc'329 if ICO : file_DYN_beg = f'{ RunDir}/ICO_{JobName}_{YearRes}1231_restart.nc'423 if LMDZ : file_DYN_beg = f'{FileDir}/ATM_{JobName}_{TarRestartDate_beg}_restart.nc' 424 if ICO : file_DYN_beg = f'{FileDir}/ICO_{JobName}_{TarRestartDate_beg}_restart.nc' 330 425 liste_beg.append (file_DYN_beg) 331 426 config['Files']['file_DYN_beg'] = file_DYN_beg 332 427 333 428 if wu.unDefined ( 'file_DYN_end' ) : 334 if LMDZ : file_DYN_end = f'{ RunDir}/ATM_{JobName}_{YearEnd}1231_restart.nc'335 if ICO : file_DYN_end = f'{ RunDir}/ICO_{JobName}_{YearEnd}1231_restart.nc'429 if LMDZ : file_DYN_end = f'{FileDir}/ATM_{JobName}_{TarRestartDate_end}_restart.nc' 430 if ICO : file_DYN_end = f'{FileDir}/ICO_{JobName}_{TarRestartDate_end}_restart.nc' 336 431 liste_end.append ( file_DYN_end ) 337 432 config['Files']['file_DYN_end'] = file_DYN_end 338 433 339 434 if wu.unDefined ( 'file_SRF_beg' ) : 340 file_SRF_beg = f'{ RunDir}/SRF_{JobName}_{YearRes}1231_sechiba_rest.nc'435 file_SRF_beg = f'{FileDir}/SRF_{JobName}_{TarRestartDate_beg}_sechiba_rest.nc' 341 436 config['Files']['file_SRF_beg'] = file_SRF_beg 342 437 if wu.unDefined ( 'file_SRF_end' ) : 343 file_SRF_end = f'{ RunDir}/SRF_{JobName}_{YearEnd}1231_sechiba_rest.nc'438 file_SRF_end = f'{FileDir}/SRF_{JobName}_{TarRestartDate_end}_sechiba_rest.nc' 344 439 config['Files']['file_SRF_end'] = file_SRF_end 345 440 … … 356 451 if ICO : 357 452 if wu.unDefined ('file_DYN_aire') : file_DYN_aire = os.path.join ( R_IN, 'ATM', 'GRID', ATM+'_grid.nc' ) 358 config['Files'] 453 config['Files']['file_DYN_aire'] = file_DYN_aire 359 454 360 455 if Routing == 'SIMPLE' : 361 456 if wu.unDefined ( 'file_RUN_beg' ) : 362 file_RUN_beg = f'{ RunDir}/SRF_{JobName}_{YearRes}1231_routing_restart.nc'457 file_RUN_beg = f'{FileDir}/SRF_{JobName}_{TarRestartDate_beg}_routing_restart.nc' 363 458 config['Files']['file_RUN_beg'] = file_RUN_beg 364 459 if wu.unDefined ( 'file_RUN_end' ) : 365 file_RUN_end = f'{ RunDir}/SRF_{JobName}_{YearEnd}1231_routing_restart.nc'460 file_RUN_end = f'{FileDir}/SRF_{JobName}_{TarRestartDate_end}_routing_restart.nc' 366 461 config['Files']['file_RUN_end'] = file_RUN_end 367 462 … … 373 468 echo ('\nExtract restart files from tar : ATM, ICO and SRF') 374 469 375 def extract_and_rebuild ( file_name=file_ATM_beg, tar_restart=tar_restart_end, RunDirComp=RunDir, ErrorCount=ErrorCount ) :470 def extract_and_rebuild ( file_name=file_ATM_beg, tar_restart=tar_restart_end, FileDirComp=FileDir, ErrorCount=ErrorCount ) : 376 471 echo ( f'----------') 377 472 echo ( f'file to extract : {file_name = }' ) 378 if os.path.exists ( os.path.join ( RunDir, file_name) ) :473 if os.path.exists ( os.path.join (FileDir, file_name) ) : 379 474 echo ( f'file found : {file_name = }' ) 380 475 else : … … 382 477 base_resFile = os.path.basename (file_name) 383 478 if os.path.exists ( tar_restart ) : 384 command = f'cd { RunDir} ; tar xf {tar_restart} {base_resFile}'479 command = f'cd {FileDir} ; tar xf {tar_restart} {base_resFile}' 385 480 echo ( f'{command = }' ) 386 try : 387 os.system ( command ) 481 try : os.system ( command ) 388 482 except : 389 483 if ContinueOnError : … … 404 498 return ErrorCount 405 499 406 ErrorCount += extract_and_rebuild ( file_name=file_ATM_beg, tar_restart=tar_restart_beg_ATM, RunDirComp=RunDir )407 ErrorCount += extract_and_rebuild ( file_name=file_DYN_beg, tar_restart=tar_restart_beg_DYN, RunDirComp=RunDir )408 ErrorCount += extract_and_rebuild ( file_name=file_SRF_beg, tar_restart=tar_restart_beg_SRF, RunDirComp=RunDir )409 410 ErrorCount += extract_and_rebuild ( file_name=file_ATM_end, tar_restart=tar_restart_end_ATM, RunDirComp=RunDir )411 ErrorCount += extract_and_rebuild ( file_name=file_DYN_end, tar_restart=tar_restart_end_DYN, RunDirComp=RunDir )412 ErrorCount += extract_and_rebuild ( file_name=file_SRF_end, tar_restart=tar_restart_end_SRF, RunDirComp=RunDir )500 ErrorCount += extract_and_rebuild ( file_name=file_ATM_beg, tar_restart=tar_restart_beg_ATM, FileDirComp=FileDir ) 501 ErrorCount += extract_and_rebuild ( file_name=file_DYN_beg, tar_restart=tar_restart_beg_DYN, FileDirComp=FileDir ) 502 ErrorCount += extract_and_rebuild ( file_name=file_SRF_beg, tar_restart=tar_restart_beg_SRF, FileDirComp=FileDir ) 503 504 ErrorCount += extract_and_rebuild ( file_name=file_ATM_end, tar_restart=tar_restart_end_ATM, FileDirComp=FileDir ) 505 ErrorCount += extract_and_rebuild ( file_name=file_DYN_end, tar_restart=tar_restart_end_DYN, FileDirComp=FileDir ) 506 ErrorCount += extract_and_rebuild ( file_name=file_SRF_end, tar_restart=tar_restart_end_SRF, FileDirComp=FileDir ) 413 507 414 508 if Routing == 'SIMPLE' : 415 ErrorCount += extract_and_rebuild ( file_name=file_RUN_beg, tar_restart=tar_restart_beg_RUN, RunDirComp=RunDir )416 ErrorCount += extract_and_rebuild ( file_name=file_RUN_end, tar_restart=tar_restart_end_RUN, RunDirComp=RunDir )509 ErrorCount += extract_and_rebuild ( file_name=file_RUN_beg, tar_restart=tar_restart_beg_RUN, FileDirComp=FileDir ) 510 ErrorCount += extract_and_rebuild ( file_name=file_RUN_end, tar_restart=tar_restart_end_RUN, FileDirComp=FileDir ) 417 511 418 512 ##-- Exit in case of error in the opening file phase … … 423 517 ## 424 518 echo ('\nOpening ATM SRF and ICO restart files') 425 d_ATM_beg = xr.open_dataset ( os.path.join ( RunDir, file_ATM_beg), decode_times=False, decode_cf=True ).squeeze()426 d_ATM_end = xr.open_dataset ( os.path.join ( RunDir, file_ATM_end), decode_times=False, decode_cf=True ).squeeze()427 d_SRF_beg = xr.open_dataset ( os.path.join ( RunDir, file_SRF_beg), decode_times=False, decode_cf=True ).squeeze()428 d_SRF_end = xr.open_dataset ( os.path.join ( RunDir, file_SRF_end), decode_times=False, decode_cf=True ).squeeze()429 d_DYN_beg = xr.open_dataset ( os.path.join ( RunDir, file_DYN_beg), decode_times=False, decode_cf=True ).squeeze()430 d_DYN_end = xr.open_dataset ( os.path.join ( RunDir, file_DYN_end), decode_times=False, decode_cf=True ).squeeze()519 d_ATM_beg = xr.open_dataset ( os.path.join (FileDir, file_ATM_beg), decode_times=False, decode_cf=True ).squeeze() 520 d_ATM_end = xr.open_dataset ( os.path.join (FileDir, file_ATM_end), decode_times=False, decode_cf=True ).squeeze() 521 d_SRF_beg = xr.open_dataset ( os.path.join (FileDir, file_SRF_beg), decode_times=False, decode_cf=True ).squeeze() 522 d_SRF_end = xr.open_dataset ( os.path.join (FileDir, file_SRF_end), decode_times=False, decode_cf=True ).squeeze() 523 d_DYN_beg = xr.open_dataset ( os.path.join (FileDir, file_DYN_beg), decode_times=False, decode_cf=True ).squeeze() 524 d_DYN_end = xr.open_dataset ( os.path.join (FileDir, file_DYN_end), decode_times=False, decode_cf=True ).squeeze() 431 525 432 526 for var in d_SRF_beg.variables : … … 435 529 436 530 if Routing == 'SIMPLE' : 437 d_RUN_beg = xr.open_dataset ( os.path.join ( RunDir, file_RUN_beg), decode_times=False, decode_cf=True ).squeeze()438 d_RUN_end = xr.open_dataset ( os.path.join ( RunDir, file_RUN_end), decode_times=False, decode_cf=True ).squeeze()531 d_RUN_beg = xr.open_dataset ( os.path.join (FileDir, file_RUN_beg), decode_times=False, decode_cf=True ).squeeze() 532 d_RUN_end = xr.open_dataset ( os.path.join (FileDir, file_RUN_end), decode_times=False, decode_cf=True ).squeeze() 439 533 440 534 def to_cell ( dd, newname='cell' ) : … … 470 564 471 565 ## Write the full configuration 472 #config_out = open (FullIniFile, 'w')473 #config.write ( config_out )474 #config_out.close ()566 config_out = open (FullIniFile, 'w') 567 config.write ( config_out ) 568 config_out.close () 475 569 476 570 if ICO : … … 554 648 SRF_areas = xr.DataArray ( SRF_areas , coords=d_SRF_his ['Contfrac'].coords, dims=d_SRF_his ['Contfrac'].dims) 555 649 SRF_areafrac = xr.DataArray ( SRF_areafrac, coords=d_SRF_his ['Contfrac'].coords, dims=d_SRF_his ['Contfrac'].dims) 556 SRF_contfrac = SRF_areafrac / SRF_areas 557 #SRF_aire = lmdz.geo2point (SRF_areas * SRF_contfrac, dim1D='cell_latlon', cumulPoles=True ) 558 #SRF_aire = lmdz.geo2point (SRF_areas, dim1D='cell_latlon', cumulPoles=True ) 559 #SRF_aire = lmdz.geo2point (d_ATM_aire ['aire'].squeeze().values * SRF_contfrac, dim1D='cell_latlon', cumulPoles=True ) 650 560 651 SRF_areas = lmdz.geo2point ( SRF_areas , dim1D='cell_latlon', cumulPoles=True ) 561 652 SRF_areafrac = lmdz.geo2point ( SRF_areafrac, dim1D='cell_latlon', cumulPoles=True ) 562 SRF_contfrac = lmdz.geo2point ( SRF_contfrac, dim1D='cell_latlon' )653 SRF_contfrac = SRF_areafrac / SRF_areas 563 654 SRF_aire = SRF_areafrac 564 655 … … 574 665 575 666 if SRF_HIS == 'ico' : 576 SRF_lat = d_SRF_his ['lat'] [SRF_his_keysort]577 SRF_lon = d_SRF_his ['lon'] [SRF_his_keysort]578 SRF_a ire = d_SRF_his ['Areas'][SRF_his_keysort] * d_SRF_his ['Contfrac'][SRF_his_keysort]579 SRF_areas = d_SRF_his ['Areas'][SRF_his_keysort]667 SRF_lat = d_SRF_his ['lat'] [SRF_his_keysort] 668 SRF_lon = d_SRF_his ['lon'] [SRF_his_keysort] 669 SRF_areas = d_SRF_his ['Areas'] [SRF_his_keysort] 670 #SRF_areafrac = d_SRF_his ['AreaFrac'] [SRF_his_keysort] 580 671 SRF_contfrac = d_SRF_his ['Contfrac'][SRF_his_keysort] 672 SRF_aire = SRF_areas * SRF_contfrac 581 673 582 674 ATM_fsea = ATM_foce + ATM_fsic … … 589 681 ATM_aire_fsea = ATM_aire * ATM_fsea 590 682 591 SRF_aire = SRF_aire.where ( np.abs (SRF_aire) < 1E15, 0. )683 SRF_aire = SRF_aire.where ( np.abs (SRF_aire) < 1E15, 0. ) 592 684 593 685 ## Write the full configuration … … 1023 1115 echo ( f'-- ATM Fluxes -- {Title} ' ) 1024 1116 1025 print ( 'Step 1', end='' ) 1117 Step=1 1118 print ( 'Step {Step}', end='' ) ; Step += 1 1026 1119 if ATM_HIS == 'latlon' : 1027 1120 ATM_wbilo_oce = lmdz.geo2point ( d_ATM_his ['wbilo_oce'], dim1D='cell_latlon' ) … … 1039 1132 ATM_wevap_lic = lmdz.geo2point ( d_ATM_his ['wevap_lic'], dim1D='cell_latlon' ) 1040 1133 ATM_wevap_sic = lmdz.geo2point ( d_ATM_his ['wevap_sic'], dim1D='cell_latlon' ) 1134 1135 ATM_wrain_ter = lmdz.geo2point ( d_ATM_his ['wrain_ter'], dim1D='cell_latlon' ) 1136 ATM_wrain_oce = lmdz.geo2point ( d_ATM_his ['wrain_oce'], dim1D='cell_latlon' ) 1137 ATM_wrain_lic = lmdz.geo2point ( d_ATM_his ['wrain_lic'], dim1D='cell_latlon' ) 1138 ATM_wrain_sic = lmdz.geo2point ( d_ATM_his ['wrain_sic'], dim1D='cell_latlon' ) 1139 1140 ATM_wsnow_ter = lmdz.geo2point ( d_ATM_his ['wsnow_ter'], dim1D='cell_latlon' ) 1141 ATM_wsnow_oce = lmdz.geo2point ( d_ATM_his ['wsnow_oce'], dim1D='cell_latlon' ) 1142 ATM_wsnow_lic = lmdz.geo2point ( d_ATM_his ['wsnow_lic'], dim1D='cell_latlon' ) 1143 ATM_wsnow_sic = lmdz.geo2point ( d_ATM_his ['wsnow_sic'], dim1D='cell_latlon' ) 1144 1145 ATM_wevap_ter = lmdz.geo2point ( d_ATM_his ['wevap_ter'], dim1D='cell_latlon' ) 1146 ATM_wevap_oce = lmdz.geo2point ( d_ATM_his ['wevap_oce'], dim1D='cell_latlon' ) 1147 ATM_wevap_lic = lmdz.geo2point ( d_ATM_his ['wevap_lic'], dim1D='cell_latlon' ) 1148 ATM_wevap_sic = lmdz.geo2point ( d_ATM_his ['wevap_sic'], dim1D='cell_latlon' ) 1149 1041 1150 ATM_runofflic = lmdz.geo2point ( d_ATM_his ['runofflic'], dim1D='cell_latlon' ) 1042 1151 1043 print ( ' - Step 2', end='' )1152 print ( 'Step {Step}', end='' ) ; Step += 1 1044 1153 if ATM_HIS == 'ico' : 1045 1154 ATM_wbilo_oce = d_ATM_his ['wbilo_oce'][..., ATM_his_keysort] … … 1059 1168 ATM_runofflic = d_ATM_his ['runofflic'][..., ATM_his_keysort] 1060 1169 1061 print ( ' - Step 3', end='' ) 1170 ATM_wevap_ter = d_ATM_his ['wevap_ter'][..., ATM_his_keysort] 1171 ATM_wevap_oce = d_ATM_his ['wevap_oce'][..., ATM_his_keysort] 1172 ATM_wevap_lic = d_ATM_his ['wevap_lic'][..., ATM_his_keysort] 1173 ATM_wevap_sic = d_ATM_his ['wevap_sic'][..., ATM_his_keysort] 1174 1175 ATM_wrain_ter = d_ATM_his ['wrain_ter'][..., ATM_his_keysort] 1176 ATM_wrain_oce = d_ATM_his ['wrain_oce'][..., ATM_his_keysort] 1177 ATM_wrain_lic = d_ATM_his ['wrain_lic'][..., ATM_his_keysort] 1178 ATM_wrain_sic = d_ATM_his ['wrain_sic'][..., ATM_his_keysort] 1179 1180 ATM_wsnow_ter = d_ATM_his ['wsnow_ter'][..., ATM_his_keysort] 1181 ATM_wsnow_oce = d_ATM_his ['wsnow_oce'][..., ATM_his_keysort] 1182 ATM_wsnow_lic = d_ATM_his ['wsnow_lic'][..., ATM_his_keysort] 1183 ATM_wsnow_sic = d_ATM_his ['wsnow_sic'][..., ATM_his_keysort] 1184 1185 print ( 'Step {Step}', end='' ) ; Step += 1 1186 1187 ATM_wprecip_oce = ATM_wrain_oce + ATM_wsnow_oce 1188 ATM_wprecip_ter = ATM_wrain_ter + ATM_wsnow_ter 1189 ATM_wprecip_sic = ATM_wrain_sic + ATM_wsnow_sic 1190 ATM_wprecip_lic = ATM_wrain_lic + ATM_wsnow_lic 1191 1062 1192 ATM_wbilo = ATM_wbilo_oce + ATM_wbilo_sic + ATM_wbilo_ter + ATM_wbilo_lic 1063 1193 ATM_emp = ATM_evap - ATM_precip 1064 ATM_wbilo_sea = ATM_wbilo_oce + ATM_wbilo_sic 1065 ATM_wevap_sea = ATM_wevap_sic + ATM_wevap_oce 1066 1067 ATM_wemp_ter = ATM_wevap_ter - ATM_precip * ATM_fter 1068 ATM_wemp_oce = ATM_wevap_oce - ATM_precip * ATM_foce 1069 ATM_wemp_sic = ATM_wevap_sic - ATM_precip * ATM_fsic 1070 ATM_wemp_lic = ATM_wevap_lic - ATM_precip * ATM_flic 1071 ATM_wemp_sea = ATM_wevap_sic + ATM_wevap_oce - ATM_precip * ATM_fsea 1072 1073 print ( ' - Step 4', end='' ) 1194 ATM_wprecip_sea = ATM_wprecip_oce + ATM_wprecip_sic 1195 ATM_wsnow_sea = ATM_wsnow_oce + ATM_wsnow_sic 1196 ATM_wrain_sea = ATM_wrain_oce + ATM_wrain_sic 1197 ATM_wbilo_sea = ATM_wbilo_oce + ATM_wbilo_sic 1198 ATM_wevap_sea = ATM_wevap_sic + ATM_wevap_oce 1199 1200 #ATM_wemp_ter = ATM_wevap_ter - ATM_precip * ATM_fter 1201 #ATM_wemp_oce = ATM_wevap_oce - ATM_precip * ATM_foce 1202 #ATM_wemp_sic = ATM_wevap_sic - ATM_precip * ATM_fsic 1203 #ATM_wemp_lic = ATM_wevap_lic - ATM_precip * ATM_flic 1204 #ATM_wemp_sea = ATM_wevap_sic + ATM_wevap_oce - ATM_precip * ATM_fsea 1205 1206 ATM_wemp_ter = ATM_wevap_ter - ATM_wprecip_ter 1207 ATM_wemp_oce = ATM_wevap_oce - ATM_wprecip_oce 1208 ATM_wemp_sic = ATM_wevap_sic - ATM_wprecip_sic 1209 ATM_wemp_lic = ATM_wevap_lic - ATM_wprecip_lic 1210 ATM_wemp_sea = ATM_wevap_sic - ATM_wprecip_oce 1211 1212 print ( 'Step {Step}', end='' ) ; Step += 1 1074 1213 if RUN_HIS == 'latlon' : 1075 1214 RUN_coastalflow = lmdz.geo2point ( d_RUN_his ['coastalflow'], dim1D='cell_latlon' ) … … 1082 1221 RUN_riverflow_cpl = lmdz.geo2point ( d_RUN_his ['riverflow_cpl'] , dim1D='cell_latlon' ) 1083 1222 1084 print ( ' - Step 5', end='' )1223 print ( 'Step {Step}', end='' ) ; Step += 1 1085 1224 if RUN_HIS == 'ico' : 1086 1225 RUN_coastalflow = d_RUN_his ['coastalflow'][..., RUN_his_keysort] … … 1093 1232 RUN_riverflow_cpl = d_RUN_his ['riverflow_cpl'] [..., RUN_his_keysort] 1094 1233 1095 print ( ' - Step 6', end='' )1234 print ( 'Step {Step}', end='' ) ; Step += 1 1096 1235 if SRF_HIS == 'latlon' : 1097 1236 SRF_rain = lmdz.geo2point ( d_SRF_his ['rain'] , dim1D='cell_latlon') … … 1101 1240 SRF_transpir = lmdz.geo2point ( np.sum (d_SRF_his ['transpir'], axis=1), dim1D='cell_latlon' ) 1102 1241 1103 print ( ' - Step 7', end='' )1242 print ( 'Step {Step}', end='' ) ; Step += 1 1104 1243 if SRF_HIS == 'ico' : 1105 1244 SRF_rain = d_SRF_his ['rain'] [..., SRF_his_keysort] … … 1109 1248 SRF_transpir = np.sum (d_SRF_his ['transpir'], axis=1)[..., SRF_his_keysort] 1110 1249 1111 print ( ' - Step 8', end='' )1250 print ( 'Step {Step}', end='' ) ; Step += 1 1112 1251 SRF_transpir.attrs['units'] = d_SRF_his ['transpir'].attrs['units'] 1113 1252 SRF_emp = SRF_evap - SRF_rain - SRF_snowf ; SRF_emp.attrs['units'] = SRF_rain.attrs['units'] … … 1132 1271 mmd2SI (VarT) 1133 1272 1134 print ( ' - Step 9', end='' )1273 print ( 'Step {Step}', end='' ) ; Step += 1 1135 1274 RUN_input = RUN_runoff + RUN_drainage 1136 1275 RUN_output = RUN_coastalflow + RUN_riverflow 1137 1276 1138 print ( ' - Step 10', end='' )1277 print ( 'Step {Step}', end='' ) ; Step += 1 1139 1278 ATM_flx_wbilo = ATM_flux_int ( ATM_wbilo ) 1279 ATM_flx_wbilo_lic = ATM_flux_int ( ATM_wbilo_lic ) 1140 1280 ATM_flx_wbilo_oce = ATM_flux_int ( ATM_wbilo_oce ) 1281 ATM_flx_wbilo_sea = ATM_flux_int ( ATM_wbilo_sea ) 1141 1282 ATM_flx_wbilo_sic = ATM_flux_int ( ATM_wbilo_sic ) 1142 ATM_flx_wbilo_sea = ATM_flux_int ( ATM_wbilo_sea )1143 1283 ATM_flx_wbilo_ter = ATM_flux_int ( ATM_wbilo_ter ) 1144 ATM_flx_wbilo_lic = ATM_flux_int ( ATM_wbilo_lic )1145 1284 ATM_flx_calving = ATM_flux_int ( ATM_fqcalving ) 1146 1285 ATM_flx_fqfonte = ATM_flux_int ( ATM_fqfonte ) 1147 1286 1148 print ( ' - Step 11', end='' )1287 print ( 'Step {Step}', end='' ) ; Step += 1 1149 1288 ATM_flx_precip = ATM_flux_int ( ATM_precip ) 1150 1289 ATM_flx_snowf = ATM_flux_int ( ATM_snowf ) … … 1152 1291 ATM_flx_runlic = ATM_flux_int ( ATM_runofflic ) 1153 1292 1154 print ( '- Step 12', end='' ) 1155 ATM_flx_wevap_ter = ATM_flux_int ( ATM_wevap_ter ) 1156 ATM_flx_wevap_sea = ATM_flux_int ( ATM_wevap_sea ) 1157 ATM_flx_precip_ter = ATM_flux_int ( ATM_precip * ATM_fter ) 1158 ATM_flx_precip_sea = ATM_flux_int ( ATM_precip * ATM_fsea ) 1159 ATM_flx_emp = ATM_flux_int ( ATM_emp) 1160 ATM_flx_wemp_ter = ATM_flux_int ( ATM_wemp_ter ) 1161 ATM_flx_wemp_oce = ATM_flux_int ( ATM_wemp_oce ) 1162 ATM_flx_wemp_lic = ATM_flux_int ( ATM_wemp_lic ) 1163 ATM_flx_wemp_sea = ATM_flux_int ( ATM_wemp_sea ) 1164 1165 print ( '- Step 13', end='' ) 1293 print ( 'Step {Step}', end='' ) ; Step += 1 1294 ATM_flx_wrain_ter = ATM_flux_int ( ATM_wrain_ter ) 1295 ATM_flx_wrain_oce = ATM_flux_int ( ATM_wrain_oce ) 1296 ATM_flx_wrain_lic = ATM_flux_int ( ATM_wrain_lic ) 1297 ATM_flx_wrain_sic = ATM_flux_int ( ATM_wrain_sic ) 1298 ATM_flx_wrain_sea = ATM_flux_int ( ATM_wrain_sea ) 1299 1300 ATM_flx_wsnow_ter = ATM_flux_int ( ATM_wsnow_ter ) 1301 ATM_flx_wsnow_oce = ATM_flux_int ( ATM_wsnow_oce ) 1302 ATM_flx_wsnow_lic = ATM_flux_int ( ATM_wsnow_lic ) 1303 ATM_flx_wsnow_sic = ATM_flux_int ( ATM_wsnow_sic ) 1304 ATM_flx_wsnow_sea = ATM_flux_int ( ATM_wsnow_sea ) 1305 print ( 'Step {Step}', end='' ) ; Step += 1 1306 ATM_flx_wrain_ter = ATM_flux_int ( ATM_wrain_ter ) 1307 ATM_flx_wrain_oce = ATM_flux_int ( ATM_wrain_oce ) 1308 ATM_flx_wrain_lic = ATM_flux_int ( ATM_wrain_lic ) 1309 ATM_flx_wrain_sic = ATM_flux_int ( ATM_wrain_sic ) 1310 ATM_flx_wrain_sea = ATM_flux_int ( ATM_wrain_sea ) 1311 ATM_flx_wevap_ter = ATM_flux_int ( ATM_wevap_ter ) 1312 ATM_flx_wevap_oce = ATM_flux_int ( ATM_wevap_oce ) 1313 ATM_flx_wevap_lic = ATM_flux_int ( ATM_wevap_lic ) 1314 ATM_flx_wevap_sic = ATM_flux_int ( ATM_wevap_sic ) 1315 ATM_flx_wevap_sea = ATM_flux_int ( ATM_wevap_sea ) 1316 ATM_flx_wprecip_lic = ATM_flux_int ( ATM_wprecip_lic ) 1317 ATM_flx_wprecip_oce = ATM_flux_int ( ATM_wprecip_oce ) 1318 ATM_flx_wprecip_sic = ATM_flux_int ( ATM_wprecip_sic ) 1319 ATM_flx_wprecip_ter = ATM_flux_int ( ATM_wprecip_ter ) 1320 ATM_flx_wprecip_sea = ATM_flux_int ( ATM_wprecip_sea ) 1321 ATM_flx_wemp_lic = ATM_flux_int ( ATM_wemp_lic ) 1322 ATM_flx_wemp_oce = ATM_flux_int ( ATM_wemp_oce ) 1323 ATM_flx_wemp_sic = ATM_flux_int ( ATM_wemp_sic ) 1324 ATM_flx_wemp_ter = ATM_flux_int ( ATM_wemp_ter ) 1325 ATM_flx_wemp_sea = ATM_flux_int ( ATM_wemp_sea ) 1326 1327 ATM_flx_emp = ATM_flux_int ( ATM_emp) 1328 1329 print ( 'Step {Step}', end='' ) ; Step += 1 1166 1330 RUN_flx_coastal = ONE_flux_int ( RUN_coastalflow) 1167 1331 RUN_flx_river = ONE_flux_int ( RUN_riverflow ) … … 1174 1338 RUN_flx_output = ONE_flux_int ( RUN_output ) 1175 1339 1176 print ( ' - Step 14' )1340 print ( 'Step {Step}', end='' ) ; Step += 1 1177 1341 RUN_flx_bil = RUN_flx_input - RUN_flx_output 1178 1342 RUN_flx_rivcoa = RUN_flx_coastal + RUN_flx_river … … 1190 1354 prtFlux ('snowf ', ATM_flx_snowf , 'f' ) 1191 1355 prtFlux ('evap ', ATM_flx_evap , 'f' ) 1192 prtFlux ('runoff lic ', ATM_flx_runlic , 'f' ) 1356 prtFlux ('runoff lic ', ATM_flx_runlic , 'f' ) 1357 1358 prtFlux ('ATM_flx_wemp_lic ', ATM_flx_wemp_lic , 'f' ) 1359 prtFlux ('ATM_flx_wemp_oce ', ATM_flx_wemp_oce , 'f' ) 1360 prtFlux ('ATM_flx_wemp_sic ', ATM_flx_wemp_sic , 'f' ) 1361 prtFlux ('ATM_flx_wemp_ter ', ATM_flx_wemp_ter , 'f' ) 1362 1363 prtFlux ('ATM_flx_wprecip_lic ', ATM_flx_wprecip_lic , 'f' ) 1364 prtFlux ('ATM_flx_wprecip_oce ', ATM_flx_wprecip_oce , 'f' ) 1365 prtFlux ('ATM_flx_wprecip_sic ', ATM_flx_wprecip_sic , 'f' ) 1366 prtFlux ('ATM_flx_wprecip_ter ', ATM_flx_wprecip_ter , 'f' ) 1367 1368 prtFlux ('ATM_flx_wrain_lic ', ATM_flx_wrain_lic , 'f' ) 1369 prtFlux ('ATM_flx_wrain_oce ', ATM_flx_wrain_oce , 'f' ) 1370 prtFlux ('ATM_flx_wrain_sic ', ATM_flx_wrain_sic , 'f' ) 1371 prtFlux ('ATM_flx_wrain_ter ', ATM_flx_wrain_ter , 'f' ) 1372 1373 prtFlux ('ATM_flx_wsnow_lic ', ATM_flx_wsnow_lic , 'f' ) 1374 prtFlux ('ATM_flx_wsnow_oce ', ATM_flx_wsnow_oce , 'f' ) 1375 prtFlux ('ATM_flx_wsnow_sic ', ATM_flx_wsnow_sic , 'f' ) 1376 prtFlux ('ATM_flx_wsnow_ter ', ATM_flx_wsnow_ter , 'f' ) 1377 1378 prtFlux ('ATM_flx_wevap_lic ', ATM_flx_wevap_lic , 'f' ) 1379 prtFlux ('ATM_flx_wevap_oce ', ATM_flx_wevap_oce , 'f' ) 1380 prtFlux ('ATM_flx_wevap_sic ', ATM_flx_wevap_sic , 'f' ) 1381 prtFlux ('ATM_flx_wevap_ter ', ATM_flx_wevap_ter , 'f' ) 1382 1383 prtFlux ('ATM_flx_wevap_lic ', ATM_flx_wevap_lic , 'f' ) 1384 prtFlux ('ATM_flx_wevap_oce ', ATM_flx_wevap_oce , 'f' ) 1385 prtFlux ('ATM_flx_wevap_sic ', ATM_flx_wevap_sic , 'f' ) 1386 prtFlux ('ATM_flx_wevap_ter ', ATM_flx_wevap_ter , 'f' ) 1193 1387 1194 1388 echo ( '\n====================================================================================' ) -
TOOLS/WATER_BUDGET/OCE_waterbudget.py
r6519 r6620 22 22 ### 23 23 ## Import system modules 24 import sys, os, shutil, subprocess, platform 25 import numpy as np 24 import sys, os, shutil#, subprocess, platform 26 25 import configparser, re 27 26 from pathlib import Path 28 27 29 ## Import local module30 import WaterUtils as wu28 ## Import needed scientific modules 29 import numpy as np, xarray as xr 31 30 32 31 # Check python version … … 35 34 raise Exception ( "Minimum Python version is 3.8" ) 36 35 36 ## Import local module 37 import WaterUtils as wu 38 import libIGCM_sys 39 import nemo, lmdz 40 37 41 ## Creates parser for reading .ini input file 38 config = configparser.ConfigParser() 42 ## ------------------------------------------- 43 config = configparser.ConfigParser ( interpolation=configparser.ExtendedInterpolation() ) 39 44 config.optionxform = str # To keep capitals 40 45 41 ## Read experiment parameters 42 ATM=None ; ATM_HIS='latlon' ; SRF_HIS='latlon' ; RUN_HIS='latlon' ; ORCA=None ; NEMO=None ; OCE_relax=False ; OCE_icb=False ; Coupled=False ; Routing=None ; TarRestartPeriod_beg=None ; TarRestartPeriod_end=None ; Comment=None ; Period=None ; Title=None 46 ## Experiment parameters 47 ## --------------------- 48 ATM=None ; ATM_HIS='latlon' ; SRF_HIS='latlon' ; RUN_HIS='latlon' ; ORCA=None ; NEMO=None ; OCE_relax=False 49 OCE_icb=False ; Coupled=False ; Routing=None 50 TarRestartPeriod_beg=None ; TarRestartPeriod_end=None ; Comment=None ; Period=None ; Title=None 51 43 52 ## 44 ARCHIVE=None ; STORAGE=None ; SCRATCHDIR=None ; R_IN=None ; rebuild=None 45 TmpDir=None ; RunDir=None ; FileOut=None ; dir_ATM_his=None ; dir_SRF_his=None ; dir_OCE_his=None ; dir_ICE_his=None ; FileCommon=None 46 file_ATM_his=None ; file_SRF_his=None ; file_RUN_his=None ; file_OCE_his=None ; file_ICE_his=None ; file_OCE_sca=None 47 tar_restart_beg=None ; tar_restart_end=None ; file_ATM_beg=None ; file_ATM_end=None ; file_DYN_beg=None ; file_DYN_end=None ; file_SRF_beg=None ; file_SRF_end=None 48 file_RUN_beg=None ; file_RUN_end=None ; file_RUN_end=None ; file_OCE_beg=None ; file_ICE_beg=None ; file_OCE_beg=None ; file_OCE_end=None ; file_ICE_beg=None ; file_OCE_end=None ; file_ICE_end=None ; ContinueOnError=False ; ErrorCount=0 49 tar_restart_beg_ATM=None ; tar_restart_beg_DYN=None ; tar_restart_beg_SRF=None ; tar_restart_beg_RUN=None ; tar_restart_beg_OCE=None ; tar_restart_beg_ICE=None 50 tar_restart_end_ATM=None ; tar_restart_end_DYN=None ; tar_restart_end_SRF=None ; tar_restart_end_RUN=None ; tar_restart_end_OCE=None ; tar_restart_end_ICE=None 51 52 # Read command line arguments 53 ARCHIVE=None ; STORAGE=None ; SCRATCHDIR=None ; R_IN=None ; rebuild=None ; TmpDir=None 54 FileDir=None ; FileOut=None 55 dir_ATM_his=None ; dir_SRF_his=None ; dir_OCE_his=None ; dir_ICE_his=None 56 FileCommon=None ; file_ATM_his=None ; file_SRF_his=None ; file_RUN_his=None 57 file_OCE_his=None ; file_ICE_his=None ; file_OCE_sca=None 58 tar_restart_beg=None ; tar_restart_end=None ; file_ATM_beg=None ; file_ATM_end=None ; file_DYN_beg=None 59 file_DYN_end=None ; file_SRF_beg=None ; file_SRF_end=None 60 file_RUN_beg=None ; file_RUN_end=None ; file_RUN_end=None ; file_OCE_beg=None 61 file_ICE_beg=None ; file_OCE_beg=None 62 file_OCE_end=None ; file_ICE_beg=None ; file_OCE_end=None ; file_ICE_end=None 63 tar_restart_beg_ATM=None ; tar_restart_beg_DYN=None ; tar_restart_beg_SRF=None 64 tar_restart_beg_RUN=None ; tar_restart_beg_OCE=None ; tar_restart_beg_ICE=None 65 tar_restart_end_ATM=None ; tar_restart_end_DYN=None ; tar_restart_end_SRF=None 66 tar_restart_end_RUN=None ; tar_restart_end_OCE=None ; tar_restart_end_ICE=None 67 ContinueOnError=False ; ErrorCount=0 ; SortIco = False 68 69 ## Read command line arguments 70 ## --------------------------- 53 71 print ( "Name of Python script:", sys.argv[0] ) 54 72 IniFile = sys.argv[1] 55 # Text existence of IniFile 73 74 # Test existence of IniFile 56 75 if not os.path.exists (IniFile ) : 57 76 raise FileExistsError ( f"File not found : {IniFile = }" ) … … 63 82 config.read (IniFile) 64 83 FullIniFile = 'full_' + IniFile 65 84 85 # Reading config.card if possible 86 ## ------------------------------- 87 ConfigCard = None 88 89 if 'Experiment' in config.keys () : ## Read Experiment on Config file if possible 90 if 'ConfigCard' in config['Experiment'].keys () : 91 ConfigCard = config['Experiment']['ConfigCard'] 92 print ( f'{ConfigCard=}' ) 93 94 if ConfigCard : ## Read config card if it exists 95 # Text existence of ConfigCard 96 if os.path.exists ( ConfigCard ) : 97 print ( f'Reading Config Card : {ConfigCard}' ) 98 ## Creates parser for reading .ini input file 99 MyReader = configparser.ConfigParser (interpolation=configparser.ExtendedInterpolation() ) 100 MyReader.optionxform = str # To keep capitals 101 102 MyReader.read (ConfigCard) 103 104 for VarName in ['JobName', 'ExperimentName', 'SpaceName', 'LongName', 'ModelName', 'TagName'] : 105 if VarName in MyReader['UserChoices'].keys() : 106 locals()[VarName] = MyReader['UserChoices'][VarName] 107 exec ( f'{VarName} = wu.setBool ({VarName})' ) 108 exec ( f'{VarName} = wu.setNum ({VarName})' ) 109 exec ( f'{VarName} = wu.setNone ({VarName})' ) 110 exec ( f'wu.{VarName} = {VarName}' ) 111 print ( f' {VarName:21} set to : {locals()[VarName]:}' ) 112 113 for VarName in ['PackFrequency'] : 114 if VarName in MyReader['Post'].keys() : 115 locals()[VarName] = MyReader['Post'][VarName] 116 exec ( f'{VarName} = wu.setBool ({VarName})' ) 117 exec ( f'{VarName} = wu.setNum ({VarName})' ) 118 exec ( f'{VarName} = wu.setNone ({VarName})' ) 119 exec ( f'wu.{VarName} = {VarName}' ) 120 print ( f' {VarName:21} set to : {locals()[VarName]:}' ) 121 else : 122 raise FileExistsError ( f"File not found : {ConfigCard = }" ) 123 66 124 ## Reading config file 67 for Section in ['Experiment', 'libIGCM', 'Files', 'Physics' ] : 125 ## ------------------- 126 for Section in ['Config', 'Experiment', 'libIGCM', 'Files', 'Physics' ] : 68 127 if Section in config.keys () : 69 print ( f' Reading [{Section}]' )128 print ( f'\nReading [{Section}]' ) 70 129 for VarName in config[Section].keys() : 71 130 locals()[VarName] = config[Section][VarName] … … 74 133 exec ( f'{VarName} = wu.setNone ({VarName})' ) 75 134 exec ( f'wu.{VarName} = {VarName}' ) 76 print ( f' {VarName:25} set to : {locals()[VarName])}' )135 print ( f' {VarName:21} set to : {locals()[VarName]}' ) 77 136 #exec ( f'del {VarName}' ) 78 137 79 138 print ( f'\nConfig file readed : {IniFile} ' ) 80 139 81 #-- Some physical constants 82 if wu.unDefined ( 'Ra' ) : Ra = 6366197.7236758135 #-- Earth Radius (m) 83 if wu.unDefined ( 'Grav' ) : Grav = 9.81 #-- Gravity (m^2/s 84 if wu.unDefined ( 'ICE_rho_ice' ) : ICE_rho_ice = 917.0 #-- Ice volumic mass (kg/m3) in LIM3 85 if wu.unDefined ( 'ICE_rho_sno') : ICE_rho_sno = 330.0 #-- Snow volumic mass (kg/m3) in LIM3 86 if wu.unDefined ( 'OCE_rho_liq' ) : OCE_rho_liq = 1026.0 #-- Ocean water volumic mass (kg/m3) in NEMO 87 if wu.unDefined ( 'ATM_rho' ) : ATM_rho = 1000.0 #-- Water volumic mass in atmosphere (kg/m^3) 88 if wu.unDefined ( 'SRF_rho' ) : SRF_rho = 1000.0 #-- Water volumic mass in surface reservoir (kg/m^3) 89 if wu.unDefined ( 'RUN_rho' ) : RUN_rho = 1000.0 #-- Water volumic mass of rivers (kg/m^3) 90 if wu.unDefined ( 'ICE_rho_pnd' ) : ICE_rho_pnd = 1000. #-- Water volumic mass in ice ponds (kg/m^3) 91 if wu.unDefined ( 'YearLength' ) : YearLength = 365.25 * 24. * 60. * 60. #-- Year length (s) 92 93 # Set libIGCM and machine dependant values 94 if not 'Files' in config.keys() : config['Files'] = {} 95 96 config['Physics'] = { 'Ra':Ra, 'Grav':Grav, 'ICE_rho_ice':ICE_rho_ice, 'ICE_rho_sno':ICE_rho_sno, 'OCE_rho_liq':OCE_rho_liq, 'ATM_rho':ATM_rho, 'SRF_rho':SRF_rho, 'RUN_rho':RUN_rho} 97 98 config['Config'] = { 'ContinueOnError':ContinueOnError, 'SortIco':SortIco} 99 100 with open ('SetLibIGCM.py') as f: exec ( f.read() ) 140 ## Some physical constants 141 ## ======================= 142 if wu.unDefined ( 'Ra' ) : Ra = wu.Ra #-- Earth Radius (m) 143 if wu.unDefined ( 'Grav' ) : Grav = wu.Grav #-- Gravity (m^2/s 144 if wu.unDefined ( 'ICE_rho_ice' ) : ICE_rho_ice = wu.ICE_rho_ice #-- Ice volumic mass (kg/m3) in LIM3 145 if wu.unDefined ( 'ICE_rho_sno') : ICE_rho_sno = wu.ICE_rho_sno #-- Snow volumic mass (kg/m3) in LIM3 146 if wu.unDefined ( 'OCE_rho_liq' ) : OCE_rho_liq = wu.OCE_rho_liq #-- Ocean water volumic mass (kg/m3) in NEMO 147 if wu.unDefined ( 'ATM_rho' ) : ATM_rho = wu.ATM_rho #-- Water volumic mass in atmosphere (kg/m^3) 148 if wu.unDefined ( 'SRF_rho' ) : SRF_rho = wu.SRF_rho #-- Water volumic mass in surface reservoir (kg/m^3) 149 if wu.unDefined ( 'RUN_rho' ) : RUN_rho = wu.RUN_rho #-- Water volumic mass of rivers (kg/m^3) 150 if wu.unDefined ( 'ICE_rho_pnd' ) : ICE_rho_pnd = wu.ICE_rho_pnd #-- Water volumic mass in ice ponds (kg/m^3) 151 if wu.unDefined ( 'YearLength' ) : YearLength = wu.YearLength #-- Year length (s) 152 153 ## Set libIGCM and machine dependant values 154 ## ---------------------------------------- 155 if not 'Files' in config.keys () : config['Files'] = {} 156 157 config['Physics'] = { 'Ra':Ra, 'Grav':Grav, 'ICE_rho_ice':ICE_rho_ice, 'ICE_rho_sno':ICE_rho_sno, 158 'OCE_rho_liq':OCE_rho_liq, 'ATM_rho':ATM_rho, 'SRF_rho':SRF_rho, 'RUN_rho':RUN_rho} 159 160 config['Config'] = { 'ContinueOnError':ContinueOnError, 'SortIco':SortIco } 161 162 ## -------------------------- 163 ICO = ( 'ICO' in wu.ATM ) 164 LMDZ = ( 'LMD' in wu.ATM ) 165 166 mm = libIGCM_sys.config ( TagName=TagName, SpaceName=SpaceName, ExperimentName=ExperimentName, JobName=JobName, User=User, Group=Group, 167 ARCHIVE=None, SCRATCHDIR=None, STORAGE=None, R_IN=None, R_OUT=None, R_FIG=None, rebuild=None, TmpDir=None, 168 R_SAVE=None, R_FIGR=None, R_BUFR=None, R_BUF_KSH=None, REBUILD_DIR=None, POST_DIR=None ) 169 globals().update(mm) 170 101 171 config['Files']['TmpDir'] = TmpDir 102 103 if libIGCM : 104 config['libIGCM'] = {'ARCHIVE':ARCHIVE, 'STORAGE':STORAGE, 'SCRATCHDIR':SCRATCHDIR, 'R_IN':R_IN, 'rebuild':rebuild } 105 106 ## Import specific module 107 import nemo 108 ## Now import needed scientific modules 109 import xarray as xr 110 111 # Output file with water budget diagnostics 112 if wu.unDefined ( 'FileOut' ) : FileOut = f'OCE_waterbudget_{JobName}_{YearBegin}_{YearEnd}.out' 172 config['libIGCM'] = { 'ARCHIVE':ARCHIVE, 'STORAGE':STORAGE, 'TmpDir':TmpDir, 'R_IN':R_IN, 'rebuild':rebuild } 173 174 ## Defines begining and end of experiment 175 ## -------------------------------------- 176 if wu.unDefined ( 'DateBegin' ) : 177 DateBegin = f'{YearBegin}0101' 178 config['Experiment']['DateBegin'] = DateBegin 179 else : 180 YearBegin, MonthBegin, DayBegin = wu.DateSplit ( DateBegin ) 181 DateBegin = wu.FormatToGregorian ( DateBegin) 182 config['Experiment']['YearBegin'] = YearBegin 183 184 if wu.unDefined ( 'DateEnd' ) : 185 DateEnd = f'{YearEnd}1231' 186 config['Experiment']['DateEnd'] = DateEnd 187 else : 188 YearEnd, MonthEnd, DayEnd = wu.DateSplit ( DateEnd ) 189 DateEnd = wu.FormatToGregorian ( DateEnd) 190 191 if wu.unDefined ( 'PackFrequency' ) : 192 PackFrequency = YearEnd - YearBegin +1 193 config['Experiment']['PackFrequency'] = f'{PackFrequency}' 194 195 if type ( PackFrequency ) == str : 196 if 'Y' in PackFrequency : PackFrequency = PackFrequency.replace ( 'Y', '') 197 if 'M' in PackFrequency : PackFrequency = PackFrequency.replace ( 'M', '') 198 PackFrequency = int ( PackFrequency ) 199 200 print ( f'{YearBegin=} {DateBegin=}' ) 201 print ( f'{YearEnd =} {DateEnd =}' ) 202 print ( f'{PackFrequency=}' ) 203 204 ## Output file with water budget diagnostics 205 ## ----------------------------------------- 206 if wu.unDefined ( 'FileOut' ) : FileOut = f'ATM_waterbudget_{JobName}_{DateBegin}_{DateEnd}.out' 113 207 config['Files']['FileOut'] = FileOut 114 208 115 209 f_out = open ( FileOut, mode = 'w' ) 116 210 117 # Useful functions 118 def kg2Sv (val, rho=ATM_rho) : 211 ## Useful functions 212 ## ---------------- 213 def kg2Sv (val, rho=OCE_rho_liq) : 119 214 '''From kg to Sverdrup''' 120 215 return val/dtime_sec*1.0e-6/rho 121 216 122 def kg2myear (val, rho= ATM_rho) :217 def kg2myear (val, rho=OCE_rho_liq) : 123 218 '''From kg to m/year''' 124 return val/ ATM_aire_sea_tot/rho/NbYear125 126 def var2prt (var, small=False, rho= ATM_rho) :219 return val/OCE_aire_tot/rho/NbYear 220 221 def var2prt (var, small=False, rho=OCE_rho_liq) : 127 222 if small : return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*1000. 128 223 else : return var , kg2Sv(var, rho=rho) , kg2myear(var, rho=rho) 129 224 130 def prtFlux (Desc, var, Form='F', small=False, rho= ATM_rho, width=15) :225 def prtFlux (Desc, var, Form='F', small=False, rho=OCE_rho_liq, width=15) : 131 226 if small : 132 if Form in ['f', 'F'] : ff=" {:1 2.4e} kg | {:12.4f} mSv | {:12.4f} mm/year "133 if Form in ['e', 'E'] : ff=" {:1 2.4e} kg | {:12.4e} mSv | {:12.4e} mm/year "227 if Form in ['f', 'F'] : ff=" {:14.6e} kg | {:12.4f} mSv | {:12.4f} mm/year " 228 if Form in ['e', 'E'] : ff=" {:14.6e} kg | {:12.4e} mSv | {:12.4e} mm/year " 134 229 else : 135 if Form in ['f', 'F'] : ff=" {:1 2.4e} kg | {:12.4f} Sv | {:12.4f} m/year "136 if Form in ['e', 'E'] : ff=" {:1 2.4e} kg | {:12.4e} Sv | {:12.4e} m/year "230 if Form in ['f', 'F'] : ff=" {:14.6e} kg | {:12.4f} Sv | {:12.4f} m/year " 231 if Form in ['e', 'E'] : ff=" {:14.6e} kg | {:12.4e} Sv | {:12.4e} m/year " 137 232 echo ( (' {:>{width}} = ' +ff).format (Desc, *var2prt(var, small, rho=rho), width=width ) ) 138 233 return None … … 146 241 return None 147 242 148 ### Set libIGCM directories 243 244 ## Set libIGCM directories 245 ## ----------------------- 149 246 if wu.unDefined ('R_OUT' ) : R_OUT = os.path.join ( ARCHIVE , 'IGCM_OUT' ) 150 247 if wu.unDefined ('R_BUF' ) : R_BUF = os.path.join ( SCRATCHDIR, 'IGCM_OUT' ) … … 157 254 if wu.unDefined ('R_FIGR' ) : R_FIGR = os.path.join ( STORAGE, 'IGCM_OUT', L_EXP ) 158 255 159 config['libIGCM'] = { 'R_OUT':R_OUT, 'R_BUF':R_BUF, 'L_EXP':L_EXP, 'R_BUFR':R_BUFR, 'POST_DIR':POST_DIR, 'REBUILD_DIR':REBUILD_DIR, 'R_BUF_KSH':R_BUF_KSH, 'R_FIGR':R_FIGR } 160 161 # Set directory to extract files 162 if wu.unDefined ( 'RunDir' ) : RunDir = os.path.join ( TmpDir, f'WATER_{JobName}_{YearBegin}_{YearEnd}' ) 163 config['Files']['RunDir'] = RunDir 164 165 if not os.path.isdir (RunDir) : os.makedirs (RunDir) 166 167 # Set directories to rebuild ocean and ice restart files 168 RunDirOCE = os.path.join (RunDir, 'OCE') 169 RunDirICE = os.path.join (RunDir, 'ICE') 170 if not os.path.exists (RunDirOCE) : os.mkdir (RunDirOCE ) 171 if not os.path.exists (RunDirICE) : os.mkdir (RunDirICE ) 256 config['libIGCM'].update ( { 'R_OUT':R_OUT, 'R_BUF':R_BUF, 'L_EXP':L_EXP, 'R_BUFR':R_BUFR, 'POST_DIR':POST_DIR, 257 'REBUILD_DIR':REBUILD_DIR, 'R_BUF_KSH':R_BUF_KSH, 'R_FIGR':R_FIGR, 'rebuild':rebuild } ) 258 259 ## Set directory to extract files 260 ## ------------------------------ 261 if wu.unDefined ( 'FileDir' ) : FileDir = os.path.join ( TmpDir, f'WATER_{JobName}' ) 262 config['Files']['FileDir'] = FileDir 263 264 if not os.path.isdir ( FileDir ) : os.makedirs ( FileDir ) 265 266 ##- Set directories to rebuild ocean and ice restart files 267 if wu.unDefined ( 'FileDirOCE' ) : FileDirOCE = os.path.join ( FileDir, 'OCE' ) 268 if wu.unDefined ( 'FileDirICE' ) : FileDirICE = os.path.join ( FileDir, 'ICE' ) 269 if not os.path.exists ( FileDirOCE ) : os.mkdir ( FileDirOCE ) 270 if not os.path.exists ( FileDirICE ) : os.mkdir ( FileDirICE ) 172 271 173 272 echo (' ') 174 echo ( f'JobName : {JobName}' ) 175 echo ( f'Comment : {Comment}' ) 176 echo ( f'TmpDir : {TmpDir}' ) 177 echo ( f'RunDirOCE : {RunDirOCE}' ) 178 echo ( f'RunDirICE : {RunDirICE}' ) 273 echo ( f'JobName : {JobName}' ) 274 echo ( f'Comment : {Comment}' ) 275 echo ( f'TmpDir : {TmpDir}' ) 276 echo ( f'FileDir : {FileDir}' ) 277 echo ( f'FileDirOCE : {FileDirOCE}' ) 278 echo ( f'FileDirICE : {FileDirICE}' ) 179 279 180 280 echo ( f'\nDealing with {L_EXP}' ) 181 281 182 #-- Creates model output directory names 282 ## Creates model output directory names 283 ## ------------------------------------ 183 284 if Freq == "MO" : FreqDir = os.path.join ( 'Output' , 'MO' ) 184 285 if Freq == "SE" : FreqDir = os.path.join ( 'Analyse', 'SE' ) … … 196 297 #-- Creates files names 197 298 if wu.unDefined ( 'Period ' ) : 198 if Freq == 'MO' : Period = f'{ YearBegin}0101_{YearEnd}1231_1M'199 if Freq == 'SE' : Period = f'SE_{ YearBegin}0101_{YearEnd}1231_1M'299 if Freq == 'MO' : Period = f'{DateBegin}_{DateEnd}_1M' 300 if Freq == 'SE' : Period = f'SE_{DateBegin}_{DateEnd}_1M' 200 301 config['Files']['Period'] = Period 302 303 config['Files']['DateBegin'] = DateBegin 304 config['Files']['DateBegin'] = DateEnd 305 306 echo ( f'Period : {Period}' ) 307 201 308 if wu.unDefined ( 'FileCommon' ) : 202 309 FileCommon = f'{JobName}_{Period}' … … 204 311 205 312 if wu.unDefined ( 'Title' ) : 206 Title = f'{JobName} : {Freq} : { YearBegin}-01-01 - {YearEnd}-12-31'313 Title = f'{JobName} : {Freq} : {DateBegin} - {DateEnd}' 207 314 config['Files']['Title'] = Title 208 315 … … 228 335 229 336 ## Compute run length 337 ## ------------------ 230 338 dtime = ( d_OCE_his.time_counter_bounds.max() - d_OCE_his.time_counter_bounds.min() ) 231 339 echo ( f'\nRun length : {(dtime/np.timedelta64(1, "D")).values:8.2f} days' ) … … 233 341 234 342 ## Compute length of each period 343 ## ----------------------------- 235 344 dtime_per = ( d_OCE_his.time_counter_bounds[:,-1] - d_OCE_his.time_counter_bounds[:,0] ) 236 345 echo ( f'\nPeriods lengths (days) : ') … … 243 352 NbYear = dtime_sec / YearLength 244 353 245 #-- Open restart files 246 YearRes = YearBegin - 1 # Year of the restart of beginning of simulation 247 YearPre = YearBegin - PackFrequency # Year to find the tarfile of the restart of beginning of simulation 248 249 echo (f'Restart dates - Start : {YearRes}-12-31 / End : {YearEnd}-12-31 ') 250 251 if wu.unDefined ( 'TarRestartPeriod_beg' ) : 252 echo (f'Restart dates - Start : {YearRes}-12-31 / End : {YearEnd}-12-31 ') 253 TarRestartPeriod_beg = f'{YearPre}0101_{YearRes}1231' 354 ##-- Extract restart files from tar 355 356 if wu.unDefined ('TarRestartDate_beg' ) : TarRestartDate_beg = wu.DateMinusOneDay ( DateBegin ) 357 if wu.unDefined ('TarRestartDate_end' ) : TarRestartDate_end = wu.FormatToGregorian ( DateEnd ) 358 359 if wu.unDefined ( 'TarRestartPeriod_beg' ) : 360 361 TarRestartPeriod_beg_DateEnd = TarRestartDate_beg 362 TarRestartPeriod_beg_DateBeg = wu.DateAddYear ( TarRestartPeriod_beg_DateEnd, -PackFrequency ) 363 TarRestartPeriod_beg_DateBeg = wu.DatePlusOneDay ( TarRestartPeriod_beg_DateBeg ) 364 365 TarRestartPeriod_beg = f'{TarRestartPeriod_beg_DateBeg}_{TarRestartPeriod_beg_DateEnd}' 366 echo (f'Tar period for initial restart : {TarRestartPeriod_beg}') 254 367 config['Files']['TarRestartPeriod_beg'] = TarRestartPeriod_beg 255 368 256 if wu.unDefined ( 'TarRestartPeriod_end' ) : 257 YearPre = YearBegin - PackFrequency # Year to find the tarfile of the restart of beginning of simulation 258 echo (f'Restart dates - Start : {YearRes}-12-31 / End : {YearEnd}-12-31 ') 259 TarRestartPeriod_end = f'{YearBegin}0101_{YearEnd}1231' 369 if wu.unDefined ( 'TarRestartPeriod_end' ) : 370 371 TarRestartPeriod_end_DateEnd = TarRestartDate_end 372 TarRestartPeriod_end_DateBeg = wu.DateAddYear ( TarRestartPeriod_end_DateEnd, -PackFrequency ) 373 TarRestartPeriod_end_DateBeg = wu.DatePlusOneDay ( TarRestartPeriod_end_DateBeg ) 374 375 TarRestartPeriod_end = f'{TarRestartPeriod_end_DateBeg}_{TarRestartPeriod_end_DateEnd}' 376 echo (f'Tar period for final restart : {TarRestartPeriod_end}') 260 377 config['Files']['TarRestartPeriod_end'] = TarRestartPeriod_end 378 379 echo (f'Restart dates - Start : {TarRestartPeriod_beg} / End : {TarRestartPeriod_end}') 261 380 262 381 if wu.unDefined ( 'tar_restart_beg' ) : … … 267 386 config['Files']['tar_restart_end'] = tar_restart_end 268 387 269 echo ( f'{tar_restart_beg }' )270 echo ( f'{tar_restart_end }' )271 388 echo ( f'{tar_restart_beg = }' ) 389 echo ( f'{tar_restart_end = }' ) 390 272 391 # 273 392 if wu.unDefined ('tar_restart_beg_ATM' ) : tar_restart_beg_ATM = tar_restart_beg … … 286 405 287 406 if wu.unDefined ( 'file_OCE_beg' ) : 288 file_OCE_beg = f'{ RunDir}/OCE_{JobName}_{YearRes}1231_restart.nc'407 file_OCE_beg = f'{FileDir}/OCE_{JobName}_{TarRestartDate_beg}_restart.nc' 289 408 config['Files']['file_OCE_beg'] = file_OCE_beg 290 409 if wu.unDefined ( 'file_OCE_end' ) : 291 file_OCE_end = f'{ RunDir}/OCE_{JobName}_{YearEnd}1231_restart.nc'410 file_OCE_end = f'{FileDir}/OCE_{JobName}_{TarRestartDate_end}_restart.nc' 292 411 config['Files']['file_OCE_end'] = file_OCE_end 293 412 if wu.unDefined ( 'file_ICE_beg' ) : 294 file_ICE_beg = f'{ RunDir}/ICE_{JobName}_{YearRes}1231_restart_icemod.nc'413 file_ICE_beg = f'{FileDir}/ICE_{JobName}_{TarRestartDate_beg}_restart_icemod.nc' 295 414 config['Files']['file_ICE_beg'] = file_ICE_beg 296 415 if wu.unDefined ( 'file_ICE_end' ) : 297 file_ICE_end = f'{ RunDir}/ICE_{JobName}_{YearEnd}1231_restart_icemod.nc'416 file_ICE_end = f'{FileDir}/ICE_{JobName}_{TarRestartDate_end}_restart_icemod.nc' 298 417 config['Files']['file_ICE_end'] = file_ICE_end 299 418 … … 302 421 echo ( f'{file_ICE_beg}' ) 303 422 echo ( f'{file_ICE_end}' ) 423 424 liste_beg = [file_OCE_beg, file_ICE_beg ] 425 liste_end = [file_ATM_end, file_ICE_end ] 304 426 305 427 echo ('\nExtract and rebuild OCE and ICE restarts') … … 311 433 return int (ndomain_opa) 312 434 313 def extract_and_rebuild ( file_name=file_OCE_beg, tar_restart=tar_restart_end, RunDirComp=RunDirOCE, ErrorCount=ErrorCount ) :435 def extract_and_rebuild ( file_name=file_OCE_beg, tar_restart=tar_restart_end, FileDirComp=FileDirOCE, ErrorCount=ErrorCount ) : 314 436 '''Extract restart file from tar. Rebuild ocean files if needed''' 315 437 echo ( f'----------') … … 321 443 # Try to extract the rebuilded file 322 444 if os.path.exists ( tar_restart ) : 323 command = f'cd { RunDirComp} ; tar xf {tar_restart} {base_resFile}.nc'445 command = f'cd {FileDirComp} ; tar xf {tar_restart} {base_resFile}.nc' 324 446 echo ( command ) 325 447 try : 326 448 os.system ( command ) 327 449 except : 328 if not os.path.exists ( os.path.join ( RunDir, f'{base_resFile}_0000.nc') ):329 command = f'cd { RunDirComp} ; tar xf {tar_restart_end} {base_file}_*.nc'450 if not os.path.exists ( os.path.join (FileDir, f'{base_resFile}_0000.nc') ): 451 command = f'cd {FileDirComp} ; tar xf {tar_restart_end} {base_file}_*.nc' 330 452 echo ( command ) 331 453 ierr = os.system ( command ) … … 333 455 else : raise Exception ( f'command failed : {command}' ) 334 456 echo ( f'extract ndomain' ) 335 ndomain_opa = get_ndomain ( os.path.join ( RunDir, f'{base_file}') )336 command = f'cd { RunDirComp} ; {rebuild} {base_resFile} {ndomain_opa} ; mv {base_resFile}.nc {RunDir}'457 ndomain_opa = get_ndomain ( os.path.join (FileDir, f'{base_file}') ) 458 command = f'cd {FileDirComp} ; {rebuild} {base_resFile} {ndomain_opa} ; mv {base_resFile}.nc {FileDir}' 337 459 echo ( command ) 338 460 ierr = os.system ( command ) … … 341 463 else : 342 464 echo ( f'tar done : {base_resFile}') 343 command = f'cd { RunDirComp} ; mv {base_resFile}.nc {RunDir}'465 command = f'cd {FileDirComp} ; mv {base_resFile}.nc {FileDir}' 344 466 ierr = os.system ( command ) 345 467 if ierr == 0 : echo ( f'command done : {command}' ) … … 354 476 355 477 356 ErrorCount += extract_and_rebuild ( file_name=file_OCE_beg, tar_restart=tar_restart_beg, RunDirComp=RunDirOCE )357 ErrorCount += extract_and_rebuild ( file_name=file_OCE_end, tar_restart=tar_restart_end, RunDirComp=RunDirOCE )358 ErrorCount += extract_and_rebuild ( file_name=file_ICE_beg, tar_restart=tar_restart_beg, RunDirComp=RunDirICE )359 ErrorCount += extract_and_rebuild ( file_name=file_ICE_end, tar_restart=tar_restart_end, RunDirComp=RunDirICE )478 ErrorCount += extract_and_rebuild ( file_name=file_OCE_beg, tar_restart=tar_restart_beg, FileDirComp=FileDirOCE ) 479 ErrorCount += extract_and_rebuild ( file_name=file_OCE_end, tar_restart=tar_restart_end, FileDirComp=FileDirOCE ) 480 ErrorCount += extract_and_rebuild ( file_name=file_ICE_beg, tar_restart=tar_restart_beg, FileDirComp=FileDirICE ) 481 ErrorCount += extract_and_rebuild ( file_name=file_ICE_end, tar_restart=tar_restart_end, FileDirComp=FileDirICE ) 360 482 361 483 echo ('Opening OCE and ICE restart files') 362 484 if NEMO == 3.6 : 363 d_OCE_beg = xr.open_dataset ( os.path.join ( RunDir, file_OCE_beg), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze()364 d_OCE_end = xr.open_dataset ( os.path.join ( RunDir, file_OCE_end), decode_times=False, decode_cf=True).squeeze()365 d_ICE_beg = xr.open_dataset ( os.path.join ( RunDir, file_ICE_beg), decode_times=False, decode_cf=True).squeeze()366 d_ICE_end = xr.open_dataset ( os.path.join ( RunDir, file_ICE_end), decode_times=False, decode_cf=True).squeeze()485 d_OCE_beg = xr.open_dataset ( os.path.join (FileDir, file_OCE_beg), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze() 486 d_OCE_end = xr.open_dataset ( os.path.join (FileDir, file_OCE_end), decode_times=False, decode_cf=True).squeeze() 487 d_ICE_beg = xr.open_dataset ( os.path.join (FileDir, file_ICE_beg), decode_times=False, decode_cf=True).squeeze() 488 d_ICE_end = xr.open_dataset ( os.path.join (FileDir, file_ICE_end), decode_times=False, decode_cf=True).squeeze() 367 489 if NEMO == 4.0 or NEMO == 4.2 : 368 d_OCE_beg = xr.open_dataset ( os.path.join ( RunDir, file_OCE_beg), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze()369 d_OCE_end = xr.open_dataset ( os.path.join ( RunDir, file_OCE_end), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze()370 d_ICE_beg = xr.open_dataset ( os.path.join ( RunDir, file_ICE_beg), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze()371 d_ICE_end = xr.open_dataset ( os.path.join ( RunDir, file_ICE_end), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze()490 d_OCE_beg = xr.open_dataset ( os.path.join (FileDir, file_OCE_beg), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze() 491 d_OCE_end = xr.open_dataset ( os.path.join (FileDir, file_OCE_end), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze() 492 d_ICE_beg = xr.open_dataset ( os.path.join (FileDir, file_ICE_beg), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze() 493 d_ICE_end = xr.open_dataset ( os.path.join (FileDir, file_ICE_end), decode_times=False, decode_cf=True, drop_variables=['y', 'x']).squeeze() 372 494 373 495 ## Write the full configuration … … 377 499 378 500 379 def kg2Sv (val, rho=OCE_rho_liq) :380 '''From kg to Sverdrup'''381 return val/dtime_sec*1.0e-6/rho382 383 def kg2myear (val, rho=OCE_rho_liq) :384 '''From kg to m/year'''385 return val/OCE_aire_tot/rho/NbYear386 387 def var2prt (var, small=False) :388 if small : return var , kg2Sv(var)*1000., kg2myear(var)*1000.389 else : return var , kg2Sv(var) , kg2myear(var)390 391 def prtFlux (Desc, var, Form='F', small=False) :392 if small :393 if Form in ['f', 'F'] : ff=" {:12.4e} kg | {:12.4f} mSv | {:12.4f} mm/year "394 if Form in ['e', 'E'] : ff=" {:12.4e} kg | {:12.4e} mSv | {:12.4e} mm/year "395 else :396 if Form in ['f', 'F'] : ff=" {:12.4e} kg | {:12.4f} Sv | {:12.4f} m/year "397 if Form in ['e', 'E'] : ff=" {:12.4e} kg | {:12.4e} Sv | {:12.4e} m/year "398 echo ( (' {:>15} = ' +ff).format (Desc, *var2prt(var, small) ) )399 return None400 401 501 # Get mask and surfaces 402 502 sos = d_OCE_his ['sos'][0].squeeze() … … 670 770 echo (' = (dSEA_mas_wat + emp_oce + emp_ice - runoffs - iceshelf)*/abs(dSEA_mas_wat) = {:12.1e} (-) '.format ( (dSEA_mas_wat + OCE_mas_emp_oce + OCE_mas_emp_ice - OCE_mas_runoffs - OCE_mas_iceshelf)/abs(dSEA_mas_wat) ) ) 671 771 772 prtFlux (' Leak OCE ', ( dOCE_mas_wat + OCE_mas_empmr - OCE_mas_iceshelf) , 'e' ) 773 prtFlux (' Leak ICE+SNW+PND ', ( dICE_mas_wat + OCE_mas_emp_ice + OCE_mas_wfxice + OCE_mas_wfxsnw + ICE_mas_wfxpnd + ICE_mas_wfxsub_err ) , 'e' ) 774 prtFlux (' Leak OCE+ICE+SNW+PND ', ( dSEA_mas_wat + OCE_mas_emp_oce +OCE_mas_emp_ice - OCE_mas_runoffs - OCE_mas_iceshelf ) , 'e' ) 775 776 777 672 778 673 779 # check if emp = emp_ice + emp_oce - calving -
TOOLS/WATER_BUDGET/WaterUtils.py
r6518 r6620 1 1 #!/usr/bin/env python3 2 ### 3 ### Script to check water conservation in the IPSL coupled model 4 ### 5 ## Here, some common utilities to all scripts 6 ## 7 ## Warning, to install, configure, run, use any of included software or 8 ## to read the associated documentation you'll need at least one (1) 9 ## brain in a reasonably working order. Lack of this implement will 10 ## void any warranties (either express or implied). Authors assumes 11 ## no responsability for errors, omissions, data loss, or any other 12 ## consequences caused directly or indirectly by the usage of his 13 ## software by incorrectly or partially configured personal 14 ## 15 ## 16 ## SVN information 17 # $Author$ 18 # $Date$ 19 # $Revision$ 20 # $Id: ATM_waterbudget.py 6277 2022-12-08 09:24:05Z omamce $ 21 # $HeadURL$ 22 23 ## Import system modules 24 #import sys, os, shutil, subprocess, platform 2 ''' 3 Script to check water conservation in the IPSL coupled model 4 5 Here, some common utilities to all scripts 6 7 Warning, to install, configure, run, use any of included software or 8 to read the associated documentation you'll need at least one (1) 9 brain in a reasonably working order. Lack of this implement will 10 void any warranties (either express or implied). Authors assumes 11 no responsability for errors, omissions, data loss, or any other 12 consequences caused directly or indirectly by the usage of his 13 software by incorrectly or partially configured personal 14 15 16 SVN information 17 $Author$ 18 $Date$ 19 $Revision$ 20 $Id: ATM_waterbudget.py 6277 2022-12-08 09:24:05Z omamce $ 21 $HeadURL$ 22 ''' 23 25 24 import numpy as np 26 25 import configparser, re 27 26 28 VarInt = 10 29 Ra = None 30 31 def ftest () : 32 print ( toto ) 27 VarInt = 10 28 Rho = 1000.0 29 Ra = 6366197.7236758135 #-- Earth Radius (m) 30 Grav = 9.81 #-- Gravity (m^2/s 31 ICE_rho_ice = 917.0 #-- Ice volumic mass (kg/m3) in LIM3 32 ICE_rho_sno = 330.0 #-- Snow volumic mass (kg/m3) in LIM3 33 OCE_rho_liq = 1026.0 #-- Ocean water volumic mass (kg/m3) in NEMO 34 ATM_rho = 1000.0 #-- Water volumic mass in atmosphere (kg/m^3) 35 SRF_rho = 1000.0 #-- Water volumic mass in surface reservoir (kg/m^3) 36 RUN_rho = 1000.0 #-- Water volumic mass of rivers (kg/m^3) 37 ICE_rho_pnd = 1000. #-- Water volumic mass in ice ponds (kg/m^3) 38 YearLength = 365.25 * 24. * 60. * 60. #-- Year length (s) 33 39 34 40 def setBool (chars) : … … 43 49 '''Convert specific char string in integer or real if possible''' 44 50 if type (chars) == str : 45 realnum = re.compile ("^[-+]?[0-9]*\.?[0-9]+(e[-+]?[0-9]+)?$")51 realnum = re.compile ("^[-+]?[0-9]*\.?[0-9]+(e[-+]?[0-9]+)?$") 46 52 isNumber = realnum.match(chars.strip()) != None 47 53 isInt = chars.strip().isdigit() … … 63 69 64 70 def unDefined (char) : 65 if char in globals () : 66 if globals()[char] == None : unDefined = True 71 '''True if a variable is not defined, or set to None''' 72 if char in locals () : 73 if locals()[char] == None : unDefined = True 67 74 else : unDefined = False 68 75 else : unDefined = True 69 76 return unDefined 77 78 def Defined (char) : 79 '''True if a variable is defined and not equal to None''' 80 if char in globals () : 81 if globals()[char] == None : Defined = False 82 else : Defined = True 83 else : Defined = False 84 return Defined 70 85 71 86 def Ksum (tab) : … … 87 102 def Ssum (tab) : 88 103 ''' 89 Precision summation by sorting by absolute value 104 Precision summation by sorting by absolute values 90 105 ''' 91 106 Ssum = np.sum ( tab[np.argsort(np.abs(tab))] ) … … 102 117 Psum = KSsum 103 118 104 105 106 119 def IsLeapYear ( Year, CalendarType="Gregorian" ) : 120 ''' True is Year is a leap year ''' 121 122 # What is the calendar : 123 if CalendarType in [ '360d', '360_day', 'noleap', '365_day'] : 124 IsLeapYear = False 125 return IsLeapYear 126 127 if CalendarType in [ 'all_leap', '366_day' ] : 128 IsLeapYear = True 129 return IsLeapYear 130 131 Year = int ( Year ) 132 133 # a year is a leap year if it is even divisible by 4 134 # but not evenly divisible by 100 135 # unless it is evenly divisible by 400 136 137 # if it is evenly divisible by 400 it must be a leap year 138 if np.mod ( Year, 400 ) == 0 : 139 IsLeapYear = True 140 return IsLeapYear 141 142 # if it is evenly divisible by 100 it must not be a leap year 143 if np.mod ( Year, 100 ) == 0 : 144 IsLeapYear = False 145 return IsLeapYear 146 147 # if it is evenly divisible by 4 it must be a leap year 148 if np.mod ( Year, 4 ) == 0 : 149 IsLeapYear = True 150 return IsLeapYear 151 152 IsLeapYear = False 153 return IsLeapYear 154 155 def DateFormat ( Date ) : 156 ''' 157 Get date format : 158 [yy]yymmdd is Gregorian 159 [yy]yy-mm-dd is Human 160 ''' 161 if type (Date) == str : 162 if '-' in Date : 163 DateFormat = 'Human' 164 else : 165 DateFormat = 'Gregorian' 166 if type (Date) == int : DateFormat = 'Gregorian' 167 return DateFormat 168 169 def PrintDate ( YE, MO, DA, Format ) : 170 '''Return a date in the requested format''' 171 if Format == 'Human' : PrintDate = f'{YE:04d}-{MO:02d}-{DA:02d}' 172 if Format == 'Gregorian' : PrintDate = f'{YE:04d}{MO:02d}{DA:02d}' 173 return PrintDate 174 175 def FormatToGregorian ( Date ) : 176 ''' from a yyyy-mm-dd or yyymmdd date format returns 177 a yyymmdd date format 178 ''' 179 YE, MO, DA = SplitDate ( Date ) 180 FormatToGregorian = f'{YE:04d}{MO:02d}{DA:02d}' 181 return FormatToGregorian 182 183 def FormatToHuman ( Date ) : 184 ''' From a yyyymmdd or yyymmdd date format returns 185 a yyy-mm-dd date format 186 ''' 187 YE, MO, DA = SplitDate ( Date ) 188 FormatToHuman = f'{YE_new:04d}-{MO:02d}-{DA:02d}' 189 return FormatToHuman 190 191 def SplitDate ( Date, Out='int' ) : 192 ''' Split Date in format [yy]yymmdd or [yy]yy-mm-dd 193 to yy, mm, dd ''' 194 if type (Date) == str : 195 if '-' in Date : 196 Dash = True 197 YE, MO, DA = Date.split ('-') 198 else : 199 Dash = False 200 YE = Date[:-4] ; MO = Date[-4:-2] ; DA = Date[-2:] 201 YearDigits = len (YE) 202 if type (Date) == int : 203 DA = np.mod ( Date, 100) 204 MO = np.mod ( Date//100, 100) 205 YE = Date // 10000 206 207 YE = int(YE) ; MO = int(MO) ; DA=int(DA) 208 return YE, MO, DA 209 210 def DateAddYear ( Date, YearInc=1 ) : 211 ''' Add on year to date in format [yy]yymmdd or [yy]yy-mm-dd''' 212 Format = DateFormat ( Date ) 213 YE, MO, DA = SplitDate ( Date ) 214 YE_new = YE + YearInc 215 DateAddYear = PrintDate ( YE_new, MO, DA, Format) 216 return DateAddYear 217 218 def DateMinusOneDay ( Date ) : 219 ''' Substracts one day to date in format [yy]yymmdd or [yy]yy-mm-dd''' 220 Format = DateFormat ( Date ) 221 mth_length = np.array ( [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ) 222 YE, MO, DA = SplitDate ( Date ) 223 if IsLeapYear ( YE) : mth_length[1] += 1 224 225 YE = int(YE) ; MO = int(MO) ; DA=int(DA) 226 if DA == 1 : 227 if MO == 1 : DA_new = mth_length[-1] ; MO_new = 12 ; YE_new = YE - 1 228 else : DA_new = mth_length[MO-2] ; MO_new = MO - 1 ; YE_new = YE 229 else : DA_new = DA - 1 ; MO_new = MO ; YE_new = YE 230 231 DateMinusOneDay = PrintDate ( YE_new, MO_new, DA_new, Format) 232 return DateMinusOneDay 233 234 def DatePlusOneDay ( Date ) : 235 ''' Add one day to date in format [yy]yymmdd or [yy]yy-mm-dd''' 236 Format = DateFormat ( Date ) 237 mth_length = np.array ( [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ) 238 YE, MO, DA = SplitDate ( Date ) 239 if IsLeapYear ( YE ) : mth_length[1] += 1 240 241 YE_new = YE ; MO_new=MO ; DA_new=DA+1 242 if DA_new > mth_length [MO_new-1] : 243 DA_new = 1 ; MO_new = MO_new + 1 244 if MO_new == 13 : 245 MO_new = 1 ; YE_new = YE_new+1 246 247 DatePlusOneDay = PrintDate ( YE_new, MO_new, DA_new, Format ) 248 return DatePlusOneDay
Note: See TracChangeset
for help on using the changeset viewer.