Changeset 6620 for TOOLS


Ignore:
Timestamp:
09/14/23 15:08:35 (8 months ago)
Author:
omamce
Message:

WATER_BUDET (by OM) : OK for SECHIBA on LMD grid. Still need improvment for ICO.

Location:
TOOLS/WATER_BUDGET
Files:
1 added
3 edited

Legend:

Unmodified
Added
Removed
  • TOOLS/WATER_BUDGET/ATM_waterbudget.py

    r6518 r6620  
    2323### 
    2424## Import system modules 
    25 import sys, os, shutil, subprocess, platform 
    26 import numpy as np 
     25import sys, os, shutil#, subprocess, platform 
    2726import configparser, re 
     27 
     28## Import needed scientific modules 
     29import numpy as np, xarray as xr 
    2830 
    2931# Check python version 
     
    3436## Import local module 
    3537import WaterUtils as wu 
     38import libIGCM_sys 
     39import nemo, lmdz 
    3640 
    3741## Creates parser for reading .ini input file 
     42## ------------------------------------------- 
    3843config = configparser.ConfigParser ( interpolation=configparser.ExtendedInterpolation() ) 
    3944config.optionxform = str # To keep capitals 
    4045 
    4146## Experiment parameters 
     47## --------------------- 
    4248ATM=None ; ATM_HIS='latlon' ; SRF_HIS='latlon' ; RUN_HIS='latlon' ; ORCA=None ; NEMO=None ; OCE_relax=False 
    4349OCE_icb=False ; Coupled=False ; Routing=None 
     
    4551 
    4652## 
    47 ARCHIVE=None ; STORAGE=None ; SCRATCHDIR=None ; R_IN=None ; rebuild=None 
    48 TmpDir=None ; RunDir=None ; FileOut=None 
     53ARCHIVE=None ; STORAGE=None ; SCRATCHDIR=None ; R_IN=None ; rebuild=None ; TmpDir=None 
     54FileDir=None ; FileOut=None 
    4955dir_ATM_his=None ; dir_SRF_his=None ; dir_OCE_his=None ; dir_ICE_his=None 
    5056FileCommon=None ; file_ATM_his=None ; file_SRF_his=None ; file_RUN_his=None 
     
    6167ContinueOnError=False ; ErrorCount=0 ; SortIco = False 
    6268 
    63 # Read command line arguments 
     69## Read command line arguments 
     70## --------------------------- 
    6471print ( "Name of Python script:", sys.argv[0] ) 
    6572IniFile = sys.argv[1] 
    66 # Text existence of IniFile 
     73 
     74# Test existence of IniFile 
    6775if not os.path.exists (IniFile ) : 
    6876    raise FileExistsError ( f"File not found : {IniFile = }" ) 
     
    7583FullIniFile = 'full_' + IniFile 
    7684 
     85## Reading config.card if possible 
     86## ------------------------------- 
     87ConfigCard = None 
     88 
     89if '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 
     94if 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                 
    77124## Reading config file 
     125## ------------------- 
    78126for Section in ['Config', 'Experiment', 'libIGCM', 'Files', 'Physics' ] : 
    79127   if Section in config.keys () :  
     
    85133            exec  ( f'{VarName} = wu.setNone ({VarName})' ) 
    86134            exec  ( f'wu.{VarName} = {VarName}' ) 
    87             print ( f'    {VarName:21} set to : {locals()[VarName]:}' ) 
     135            print ( f'    {VarName:21} set to : {locals()[VarName]}' ) 
    88136            #exec ( f'del {VarName}' ) 
    89137 
    90138print ( 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## ======================= 
     142if wu.unDefined ( 'Ra' )           : Ra          = wu.Ra           #-- Earth Radius (m) 
     143if wu.unDefined ( 'Grav' )         : Grav        = wu.Grav         #-- Gravity (m^2/s 
     144if wu.unDefined ( 'ICE_rho_ice' )  : ICE_rho_ice = wu.ICE_rho_ice  #-- Ice volumic mass (kg/m3) in LIM3 
     145if wu.unDefined ( 'ICE_rho_sno')   : ICE_rho_sno = wu.ICE_rho_sno  #-- Snow volumic mass (kg/m3) in LIM3 
     146if wu.unDefined ( 'OCE_rho_liq' )  : OCE_rho_liq = wu.OCE_rho_liq  #-- Ocean water volumic mass (kg/m3) in NEMO 
     147if wu.unDefined ( 'ATM_rho' )      : ATM_rho     = wu.ATM_rho      #-- Water volumic mass in atmosphere (kg/m^3) 
     148if wu.unDefined ( 'SRF_rho' )      : SRF_rho     = wu.SRF_rho      #-- Water volumic mass in surface reservoir (kg/m^3) 
     149if wu.unDefined ( 'RUN_rho' )      : RUN_rho     = wu.RUN_rho      #-- Water volumic mass of rivers (kg/m^3) 
     150if wu.unDefined ( 'ICE_rho_pnd' )  : ICE_rho_pnd = wu.ICE_rho_pnd  #-- Water volumic mass in ice ponds (kg/m^3) 
     151if wu.unDefined ( 'YearLength' )   : YearLength  = wu.YearLength   #-- Year length (s) 
     152     
     153## Set libIGCM and machine dependant values 
     154## ---------------------------------------- 
    105155if not 'Files' in config.keys () : config['Files'] = {} 
    106156 
     
    113163ICO  = ( 'ICO' in wu.ATM ) 
    114164LMDZ = ( 'LMD' in wu.ATM ) 
    115      
    116 with open ('SetLibIGCM.py') as f: exec ( f.read() ) 
     165 
     166mm = 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 ) 
     169globals().update(mm) 
     170 
    117171config['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' 
     172config['libIGCM'] = { 'ARCHIVE':ARCHIVE, 'STORAGE':STORAGE, 'TmpDir':TmpDir, 'R_IN':R_IN, 'rebuild':rebuild } 
     173 
     174## Defines begining and end of experiment 
     175## -------------------------------------- 
     176if wu.unDefined ( 'DateBegin' ) : 
     177    DateBegin = f'{YearBegin}0101' 
     178    config['Experiment']['DateBegin'] = DateBegin 
     179else : 
     180    YearBegin, MonthBegin, DayBegin = wu.DateSplit ( DateBegin ) 
     181    DateBegin = wu.FormatToGregorian ( DateBegin) 
     182    config['Experiment']['YearBegin'] = YearBegin 
     183 
     184if wu.unDefined ( 'DateEnd' )   : 
     185    DateEnd   = f'{YearEnd}1231' 
     186    config['Experiment']['DateEnd']   = DateEnd 
     187else : 
     188    YearEnd, MonthEnd, DayEnd = wu.DateSplit ( DateEnd ) 
     189    DateEnd   = wu.FormatToGregorian ( DateEnd) 
     190 
     191if wu.unDefined ( 'PackFrequency' ) : 
     192    PackFrequency = YearEnd - YearBegin + 1 
     193    config['Experiment']['PackFrequency']   = f'{PackFrequency}' 
     194 
     195if 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## ----------------------------------------- 
     202if wu.unDefined ( 'FileOut' ) : FileOut = f'ATM_waterbudget_{JobName}_{DateBegin}_{DateEnd}.out' 
    129203config['Files']['FileOut'] = FileOut 
    130204 
    131205f_out = open ( FileOut, mode = 'w' ) 
    132206 
    133 ##- Useful functions 
     207## Useful functions 
     208## ---------------- 
    134209def kg2Sv    (val, rho=ATM_rho) : 
    135210    '''From kg to Sverdrup''' 
     
    141216 
    142217def var2prt (var, small=False, rho=ATM_rho) : 
    143     if small :  return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*1000. 
     218    if small :  return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*100# 
    144219    else     :  return var , kg2Sv(var, rho=rho)      , kg2myear(var, rho=rho) 
    145220 
    146221def prtFlux (Desc, var, Form='F', small=False, rho=ATM_rho, width=15) : 
    147222    if small : 
    148         if Form in ['f', 'F'] : ff=" {:12.4e} kg | {:12.4f} mSv | {:12.4f} mm/year " 
    149         if Form in ['e', 'E'] : ff=" {:12.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 " 
    150225    else : 
    151         if Form in ['f', 'F'] : ff=" {:12.4e} kg | {:12.4f} Sv  | {:12.4f} m/year  " 
    152         if Form in ['e', 'E'] : ff=" {:12.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 ) ) 
    154229    return None 
    155230 
     
    162237    return None 
    163238     
    164 ##- Set libIGCM directories 
     239## Set libIGCM directories 
     240## ----------------------- 
    165241if wu.unDefined ('R_OUT'      ) : R_OUT       = os.path.join ( ARCHIVE   , 'IGCM_OUT' ) 
    166242if wu.unDefined ('R_BUF'      ) : R_BUF       = os.path.join ( SCRATCHDIR, 'IGCM_OUT' ) 
     
    173249if wu.unDefined ('R_FIGR'     ) : R_FIGR      = os.path.join ( STORAGE, 'IGCM_OUT', L_EXP ) 
    174250 
    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 ) 
     251config['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## ------------------------------ 
     256if wu.unDefined ( 'FileDir' ) : FileDir = os.path.join ( TmpDir, f'WATER_{JobName}' ) 
     257config['Files']['FileDir'] = FileDir 
     258 
     259if not os.path.isdir ( FileDir ) : os.makedirs ( FileDir ) 
    183260 
    184261##- 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 ) 
     262if wu.unDefined ( 'FileDirOCE' ) : FileDirOCE = os.path.join ( FileDir, 'OCE' ) 
     263if wu.unDefined ( 'FileDirICE' ) : FileDirICE = os.path.join ( FileDir, 'ICE' ) 
     264if not os.path.exists ( FileDirOCE ) : os.mkdir ( FileDirOCE ) 
     265if not os.path.exists ( FileDirICE ) : os.mkdir ( FileDirICE ) 
    189266 
    190267echo (' ') 
    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}' ) 
     268echo ( f'JobName    : {JobName}'   ) 
     269echo ( f'Comment    : {Comment}'   ) 
     270echo ( f'TmpDir     : {TmpDir}'    ) 
     271echo ( f'FileDir     : {FileDir}'    ) 
     272echo ( f'FileDirOCE  : {FileDirOCE}' ) 
     273echo ( f'FileDirICE  : {FileDirICE}' ) 
    197274 
    198275echo ( f'\nDealing with {L_EXP}'  ) 
    199276 
    200 ##-- Creates model output directory names 
     277## Creates model output directory names 
     278## ------------------------------------ 
    201279if Freq == "MO" : FreqDir = os.path.join ('Output' , 'MO' ) 
    202280if Freq == "SE" : FreqDir = os.path.join ('Analyse', 'SE' ) 
     
    214292##-- Creates files names 
    215293if 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' 
    218296    config['Files']['Period'] = Period 
     297 
     298config['Files']['DateBegin'] = DateBegin 
     299config['Files']['DateBegin'] = DateEnd 
     300        
     301echo ( f'Period   : {Period}' ) 
     302     
    219303if wu.unDefined ( 'FileCommon' ) : 
    220304    FileCommon = f'{JobName}_{Period}' 
     
    222306 
    223307if wu.unDefined ( 'Title' ) : 
    224     Title = f'{JobName} : {Freq} : {YearBegin}-01-01 - {YearEnd}-12-31' 
     308    Title = f'{JobName} : {Freq} : {DateBegin} - {DateEnd}' 
    225309    config['Files']['Title'] = Title 
    226310      
     
    256340if Routing == 'SIMPLE' : echo ( f'{file_RUN_his = }' ) 
    257341 
    258 ##-- Compute run length 
     342## Compute run length 
     343## ------------------ 
    259344dtime = ( d_ATM_his.time_counter_bounds.max() - d_ATM_his.time_counter_bounds.min() ) 
    260345echo ('\nRun length : {:8.2f} days'.format ( (dtime/np.timedelta64(1, "D")).values ) ) 
     
    272357 
    273358##-- 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 
     360if wu.unDefined ('TarRestartDate_beg' ) : TarRestartDate_beg = wu.DateMinusOneDay ( DateBegin ) 
     361if wu.unDefined ('TarRestartDate_end' ) : TarRestartDate_end = wu.FormatToGregorian ( DateEnd ) 
     362 
     363if 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}') 
    282371    config['Files']['TarRestartPeriod_beg'] = TarRestartPeriod_beg 
    283372 
    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' 
     373if 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}') 
    288381    config['Files']['TarRestartPeriod_end'] = TarRestartPeriod_end 
     382 
     383echo (f'Restart dates - Start : {TarRestartPeriod_beg}  /  End : {TarRestartPeriod_end}') 
    289384 
    290385if wu.unDefined ( 'tar_restart_beg' ) : 
     
    316411 
    317412if 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' 
    319414    config['Files']['file_ATM_beg'] = file_ATM_beg 
    320415if 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' 
    322417    config['Files']['file_ATM_end'] = file_ATM_end 
    323418 
     
    326421 
    327422if 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' 
    330425    liste_beg.append (file_DYN_beg) 
    331426    config['Files']['file_DYN_beg'] = file_DYN_beg 
    332427     
    333428if 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' 
    336431    liste_end.append ( file_DYN_end ) 
    337432    config['Files']['file_DYN_end'] = file_DYN_end 
    338433 
    339434if 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' 
    341436    config['Files']['file_SRF_beg'] = file_SRF_beg 
    342437if 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' 
    344439    config['Files']['file_SRF_end'] = file_SRF_end 
    345440     
     
    356451if ICO : 
    357452    if wu.unDefined ('file_DYN_aire') : file_DYN_aire = os.path.join ( R_IN, 'ATM', 'GRID', ATM+'_grid.nc' ) 
    358     config['Files'] ['file_DYN_aire'] = file_DYN_aire 
     453    config['Files']['file_DYN_aire'] = file_DYN_aire 
    359454 
    360455if Routing == 'SIMPLE' : 
    361456    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' 
    363458        config['Files']['file_RUN_beg'] = file_RUN_beg 
    364459    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' 
    366461        config['Files']['file_RUN_end'] = file_RUN_end 
    367462         
     
    373468echo ('\nExtract restart files from tar : ATM, ICO and SRF') 
    374469 
    375 def extract_and_rebuild ( file_name=file_ATM_beg, tar_restart=tar_restart_end, RunDirComp=RunDir, ErrorCount=ErrorCount ) : 
     470def extract_and_rebuild ( file_name=file_ATM_beg, tar_restart=tar_restart_end, FileDirComp=FileDir, ErrorCount=ErrorCount ) : 
    376471    echo ( f'----------') 
    377472    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) ) : 
    379474        echo ( f'file found : {file_name = }' ) 
    380475    else : 
     
    382477        base_resFile = os.path.basename (file_name) 
    383478        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}' 
    385480            echo ( f'{command = }' ) 
    386             try :  
    387                 os.system ( command ) 
     481            try : os.system ( command ) 
    388482            except : 
    389483                if ContinueOnError : 
     
    404498    return ErrorCount 
    405499  
    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 ) 
     500ErrorCount += extract_and_rebuild ( file_name=file_ATM_beg, tar_restart=tar_restart_beg_ATM, FileDirComp=FileDir ) 
     501ErrorCount += extract_and_rebuild ( file_name=file_DYN_beg, tar_restart=tar_restart_beg_DYN, FileDirComp=FileDir ) 
     502ErrorCount += extract_and_rebuild ( file_name=file_SRF_beg, tar_restart=tar_restart_beg_SRF, FileDirComp=FileDir ) 
     503 
     504ErrorCount += extract_and_rebuild ( file_name=file_ATM_end, tar_restart=tar_restart_end_ATM, FileDirComp=FileDir ) 
     505ErrorCount += extract_and_rebuild ( file_name=file_DYN_end, tar_restart=tar_restart_end_DYN, FileDirComp=FileDir ) 
     506ErrorCount += extract_and_rebuild ( file_name=file_SRF_end, tar_restart=tar_restart_end_SRF, FileDirComp=FileDir ) 
    413507 
    414508if 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 ) 
    417511 
    418512##-- Exit in case of error in the opening file phase 
     
    423517##  
    424518echo ('\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() 
     519d_ATM_beg = xr.open_dataset ( os.path.join (FileDir, file_ATM_beg), decode_times=False, decode_cf=True ).squeeze() 
     520d_ATM_end = xr.open_dataset ( os.path.join (FileDir, file_ATM_end), decode_times=False, decode_cf=True ).squeeze() 
     521d_SRF_beg = xr.open_dataset ( os.path.join (FileDir, file_SRF_beg), decode_times=False, decode_cf=True ).squeeze() 
     522d_SRF_end = xr.open_dataset ( os.path.join (FileDir, file_SRF_end), decode_times=False, decode_cf=True ).squeeze() 
     523d_DYN_beg = xr.open_dataset ( os.path.join (FileDir, file_DYN_beg), decode_times=False, decode_cf=True ).squeeze() 
     524d_DYN_end = xr.open_dataset ( os.path.join (FileDir, file_DYN_end), decode_times=False, decode_cf=True ).squeeze() 
    431525 
    432526for var in d_SRF_beg.variables : 
     
    435529 
    436530if 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() 
    439533 
    440534def to_cell ( dd, newname='cell' ) : 
     
    470564 
    471565## Write the full configuration 
    472 #config_out = open (FullIniFile, 'w') 
    473 #config.write ( config_out ) 
    474 #config_out.close () 
     566config_out = open (FullIniFile, 'w') 
     567config.write ( config_out ) 
     568config_out.close () 
    475569 
    476570if ICO : 
     
    554648        SRF_areas    = xr.DataArray ( SRF_areas   , coords=d_SRF_his ['Contfrac'].coords, dims=d_SRF_his ['Contfrac'].dims) 
    555649        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 
    560651        SRF_areas     = lmdz.geo2point ( SRF_areas   , dim1D='cell_latlon', cumulPoles=True ) 
    561652        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 
    563654        SRF_aire      = SRF_areafrac 
    564655 
     
    574665         
    575666    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_aire      =  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]  
    580671        SRF_contfrac  =  d_SRF_his ['Contfrac'][SRF_his_keysort] 
     672        SRF_aire      =  SRF_areas * SRF_contfrac 
    581673 
    582674ATM_fsea      = ATM_foce + ATM_fsic 
     
    589681ATM_aire_fsea = ATM_aire * ATM_fsea 
    590682 
    591 SRF_aire = SRF_aire.where ( np.abs (SRF_aire) < 1E15, 0.) 
     683SRF_aire = SRF_aire.where ( np.abs (SRF_aire) < 1E15, 0. ) 
    592684 
    593685## Write the full configuration 
     
    10231115echo ( f'-- ATM Fluxes  -- {Title} ' ) 
    10241116 
    1025 print ( 'Step 1', end='' ) 
     1117Step=1 
     1118print ( 'Step {Step}', end='' ) ; Step += 1 
    10261119if ATM_HIS == 'latlon' : 
    10271120    ATM_wbilo_oce   = lmdz.geo2point ( d_ATM_his ['wbilo_oce'], dim1D='cell_latlon' ) 
     
    10391132    ATM_wevap_lic   = lmdz.geo2point ( d_ATM_his ['wevap_lic'], dim1D='cell_latlon' ) 
    10401133    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     
    10411150    ATM_runofflic   = lmdz.geo2point ( d_ATM_his ['runofflic'], dim1D='cell_latlon' ) 
    10421151     
    1043 print ( ' - Step 2', end='' ) 
     1152print ( 'Step {Step}', end='' ) ; Step += 1 
    10441153if ATM_HIS == 'ico' : 
    10451154    ATM_wbilo_oce   = d_ATM_his ['wbilo_oce'][..., ATM_his_keysort] 
     
    10591168    ATM_runofflic   = d_ATM_his ['runofflic'][..., ATM_his_keysort] 
    10601169 
    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 
     1185print ( 'Step {Step}', end='' ) ; Step += 1 
     1186 
     1187ATM_wprecip_oce = ATM_wrain_oce + ATM_wsnow_oce 
     1188ATM_wprecip_ter = ATM_wrain_ter + ATM_wsnow_ter 
     1189ATM_wprecip_sic = ATM_wrain_sic + ATM_wsnow_sic 
     1190ATM_wprecip_lic = ATM_wrain_lic + ATM_wsnow_lic 
     1191 
    10621192ATM_wbilo       = ATM_wbilo_oce + ATM_wbilo_sic + ATM_wbilo_ter + ATM_wbilo_lic 
    10631193ATM_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='' ) 
     1194ATM_wprecip_sea = ATM_wprecip_oce + ATM_wprecip_sic 
     1195ATM_wsnow_sea   = ATM_wsnow_oce   + ATM_wsnow_sic 
     1196ATM_wrain_sea   = ATM_wrain_oce   + ATM_wrain_sic 
     1197ATM_wbilo_sea   = ATM_wbilo_oce   + ATM_wbilo_sic 
     1198ATM_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 
     1206ATM_wemp_ter = ATM_wevap_ter - ATM_wprecip_ter  
     1207ATM_wemp_oce = ATM_wevap_oce - ATM_wprecip_oce 
     1208ATM_wemp_sic = ATM_wevap_sic - ATM_wprecip_sic 
     1209ATM_wemp_lic = ATM_wevap_lic - ATM_wprecip_lic 
     1210ATM_wemp_sea = ATM_wevap_sic - ATM_wprecip_oce 
     1211 
     1212print ( 'Step {Step}', end='' ) ; Step += 1 
    10741213if RUN_HIS == 'latlon' :  
    10751214    RUN_coastalflow = lmdz.geo2point ( d_RUN_his ['coastalflow'], dim1D='cell_latlon' )  
     
    10821221    RUN_riverflow_cpl   = lmdz.geo2point ( d_RUN_his ['riverflow_cpl']  , dim1D='cell_latlon' ) 
    10831222 
    1084 print ( ' - Step 5', end='' ) 
     1223print ( 'Step {Step}', end='' ) ; Step += 1 
    10851224if RUN_HIS == 'ico' : 
    10861225    RUN_coastalflow =  d_RUN_his ['coastalflow'][..., RUN_his_keysort] 
     
    10931232    RUN_riverflow_cpl   = d_RUN_his ['riverflow_cpl']  [..., RUN_his_keysort] 
    10941233 
    1095 print ( ' - Step 6', end='' ) 
     1234print ( 'Step {Step}', end='' ) ; Step += 1 
    10961235if SRF_HIS == 'latlon' : 
    10971236    SRF_rain     = lmdz.geo2point ( d_SRF_his ['rain']  , dim1D='cell_latlon') 
     
    11011240    SRF_transpir = lmdz.geo2point ( np.sum (d_SRF_his ['transpir'], axis=1), dim1D='cell_latlon' ) 
    11021241 
    1103 print ( '- Step 7', end='' ) 
     1242print ( 'Step {Step}', end='' ) ; Step += 1 
    11041243if SRF_HIS == 'ico' : 
    11051244    SRF_rain     = d_SRF_his ['rain'] [..., SRF_his_keysort] 
     
    11091248    SRF_transpir = np.sum (d_SRF_his ['transpir'], axis=1)[..., SRF_his_keysort] 
    11101249 
    1111 print ( '- Step 8', end='' ) 
     1250print ( 'Step {Step}', end='' ) ; Step += 1 
    11121251SRF_transpir.attrs['units'] = d_SRF_his ['transpir'].attrs['units'] 
    11131252SRF_emp      = SRF_evap - SRF_rain - SRF_snowf ; SRF_emp.attrs['units'] = SRF_rain.attrs['units'] 
     
    11321271    mmd2SI (VarT) 
    11331272 
    1134 print ( '- Step 9', end='' ) 
     1273print ( 'Step {Step}', end='' ) ; Step += 1 
    11351274RUN_input  = RUN_runoff      + RUN_drainage 
    11361275RUN_output = RUN_coastalflow + RUN_riverflow 
    11371276 
    1138 print ( '- Step 10', end='' ) 
     1277print ( 'Step {Step}', end='' ) ; Step += 1 
    11391278ATM_flx_wbilo       = ATM_flux_int ( ATM_wbilo      ) 
     1279ATM_flx_wbilo_lic   = ATM_flux_int ( ATM_wbilo_lic  ) 
    11401280ATM_flx_wbilo_oce   = ATM_flux_int ( ATM_wbilo_oce  ) 
     1281ATM_flx_wbilo_sea   = ATM_flux_int ( ATM_wbilo_sea  ) 
    11411282ATM_flx_wbilo_sic   = ATM_flux_int ( ATM_wbilo_sic  ) 
    1142 ATM_flx_wbilo_sea   = ATM_flux_int ( ATM_wbilo_sea  ) 
    11431283ATM_flx_wbilo_ter   = ATM_flux_int ( ATM_wbilo_ter  ) 
    1144 ATM_flx_wbilo_lic   = ATM_flux_int ( ATM_wbilo_lic  ) 
    11451284ATM_flx_calving     = ATM_flux_int ( ATM_fqcalving  ) 
    11461285ATM_flx_fqfonte     = ATM_flux_int ( ATM_fqfonte    ) 
    11471286 
    1148 print ( '- Step 11', end='' ) 
     1287print ( 'Step {Step}', end='' ) ; Step += 1 
    11491288ATM_flx_precip      = ATM_flux_int ( ATM_precip     ) 
    11501289ATM_flx_snowf       = ATM_flux_int ( ATM_snowf      ) 
     
    11521291ATM_flx_runlic      = ATM_flux_int ( ATM_runofflic  ) 
    11531292 
    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='' ) 
     1293print ( 'Step {Step}', end='' ) ; Step += 1 
     1294ATM_flx_wrain_ter    = ATM_flux_int ( ATM_wrain_ter ) 
     1295ATM_flx_wrain_oce    = ATM_flux_int ( ATM_wrain_oce ) 
     1296ATM_flx_wrain_lic    = ATM_flux_int ( ATM_wrain_lic ) 
     1297ATM_flx_wrain_sic    = ATM_flux_int ( ATM_wrain_sic ) 
     1298ATM_flx_wrain_sea    = ATM_flux_int ( ATM_wrain_sea ) 
     1299 
     1300ATM_flx_wsnow_ter    = ATM_flux_int ( ATM_wsnow_ter ) 
     1301ATM_flx_wsnow_oce    = ATM_flux_int ( ATM_wsnow_oce ) 
     1302ATM_flx_wsnow_lic    = ATM_flux_int ( ATM_wsnow_lic ) 
     1303ATM_flx_wsnow_sic    = ATM_flux_int ( ATM_wsnow_sic ) 
     1304ATM_flx_wsnow_sea    = ATM_flux_int ( ATM_wsnow_sea ) 
     1305print ( 'Step {Step}', end='' ) ; Step += 1 
     1306ATM_flx_wrain_ter    = ATM_flux_int ( ATM_wrain_ter ) 
     1307ATM_flx_wrain_oce    = ATM_flux_int ( ATM_wrain_oce ) 
     1308ATM_flx_wrain_lic    = ATM_flux_int ( ATM_wrain_lic ) 
     1309ATM_flx_wrain_sic    = ATM_flux_int ( ATM_wrain_sic ) 
     1310ATM_flx_wrain_sea    = ATM_flux_int ( ATM_wrain_sea ) 
     1311ATM_flx_wevap_ter    = ATM_flux_int ( ATM_wevap_ter ) 
     1312ATM_flx_wevap_oce    = ATM_flux_int ( ATM_wevap_oce ) 
     1313ATM_flx_wevap_lic    = ATM_flux_int ( ATM_wevap_lic ) 
     1314ATM_flx_wevap_sic    = ATM_flux_int ( ATM_wevap_sic ) 
     1315ATM_flx_wevap_sea    = ATM_flux_int ( ATM_wevap_sea ) 
     1316ATM_flx_wprecip_lic  = ATM_flux_int ( ATM_wprecip_lic ) 
     1317ATM_flx_wprecip_oce  = ATM_flux_int ( ATM_wprecip_oce ) 
     1318ATM_flx_wprecip_sic  = ATM_flux_int ( ATM_wprecip_sic ) 
     1319ATM_flx_wprecip_ter  = ATM_flux_int ( ATM_wprecip_ter ) 
     1320ATM_flx_wprecip_sea  = ATM_flux_int ( ATM_wprecip_sea ) 
     1321ATM_flx_wemp_lic     = ATM_flux_int ( ATM_wemp_lic ) 
     1322ATM_flx_wemp_oce     = ATM_flux_int ( ATM_wemp_oce ) 
     1323ATM_flx_wemp_sic     = ATM_flux_int ( ATM_wemp_sic ) 
     1324ATM_flx_wemp_ter     = ATM_flux_int ( ATM_wemp_ter ) 
     1325ATM_flx_wemp_sea     = ATM_flux_int ( ATM_wemp_sea ) 
     1326 
     1327ATM_flx_emp          = ATM_flux_int ( ATM_emp) 
     1328 
     1329print ( 'Step {Step}', end='' ) ; Step += 1 
    11661330RUN_flx_coastal     = ONE_flux_int ( RUN_coastalflow) 
    11671331RUN_flx_river       = ONE_flux_int ( RUN_riverflow  ) 
     
    11741338RUN_flx_output      = ONE_flux_int ( RUN_output     ) 
    11751339 
    1176 print ( '- Step 14' ) 
     1340print ( 'Step {Step}', end='' ) ; Step += 1 
    11771341RUN_flx_bil    = RUN_flx_input   - RUN_flx_output 
    11781342RUN_flx_rivcoa = RUN_flx_coastal + RUN_flx_river 
     
    11901354prtFlux ('snowf         ', ATM_flx_snowf      , 'f' )         
    11911355prtFlux ('evap          ', ATM_flx_evap       , 'f' ) 
    1192 prtFlux ('runoff lic    ', ATM_flx_runlic     , 'f' )    
     1356prtFlux ('runoff lic    ', ATM_flx_runlic     , 'f' ) 
     1357 
     1358prtFlux ('ATM_flx_wemp_lic     ', ATM_flx_wemp_lic      , 'f' ) 
     1359prtFlux ('ATM_flx_wemp_oce     ', ATM_flx_wemp_oce      , 'f' ) 
     1360prtFlux ('ATM_flx_wemp_sic     ', ATM_flx_wemp_sic      , 'f' ) 
     1361prtFlux ('ATM_flx_wemp_ter     ', ATM_flx_wemp_ter      , 'f' ) 
     1362 
     1363prtFlux ('ATM_flx_wprecip_lic  ', ATM_flx_wprecip_lic   , 'f' ) 
     1364prtFlux ('ATM_flx_wprecip_oce  ', ATM_flx_wprecip_oce   , 'f' ) 
     1365prtFlux ('ATM_flx_wprecip_sic  ', ATM_flx_wprecip_sic   , 'f' ) 
     1366prtFlux ('ATM_flx_wprecip_ter  ', ATM_flx_wprecip_ter   , 'f' ) 
     1367 
     1368prtFlux ('ATM_flx_wrain_lic    ', ATM_flx_wrain_lic     , 'f' ) 
     1369prtFlux ('ATM_flx_wrain_oce    ', ATM_flx_wrain_oce     , 'f' ) 
     1370prtFlux ('ATM_flx_wrain_sic    ', ATM_flx_wrain_sic     , 'f' ) 
     1371prtFlux ('ATM_flx_wrain_ter    ', ATM_flx_wrain_ter     , 'f' ) 
     1372 
     1373prtFlux ('ATM_flx_wsnow_lic    ', ATM_flx_wsnow_lic     , 'f' ) 
     1374prtFlux ('ATM_flx_wsnow_oce    ', ATM_flx_wsnow_oce     , 'f' ) 
     1375prtFlux ('ATM_flx_wsnow_sic    ', ATM_flx_wsnow_sic     , 'f' ) 
     1376prtFlux ('ATM_flx_wsnow_ter    ', ATM_flx_wsnow_ter     , 'f' ) 
     1377 
     1378prtFlux ('ATM_flx_wevap_lic    ', ATM_flx_wevap_lic     , 'f' ) 
     1379prtFlux ('ATM_flx_wevap_oce    ', ATM_flx_wevap_oce     , 'f' ) 
     1380prtFlux ('ATM_flx_wevap_sic    ', ATM_flx_wevap_sic     , 'f' ) 
     1381prtFlux ('ATM_flx_wevap_ter    ', ATM_flx_wevap_ter     , 'f' ) 
     1382 
     1383prtFlux ('ATM_flx_wevap_lic    ', ATM_flx_wevap_lic     , 'f' ) 
     1384prtFlux ('ATM_flx_wevap_oce    ', ATM_flx_wevap_oce     , 'f' ) 
     1385prtFlux ('ATM_flx_wevap_sic    ', ATM_flx_wevap_sic     , 'f' ) 
     1386prtFlux ('ATM_flx_wevap_ter    ', ATM_flx_wevap_ter     , 'f' ) 
    11931387 
    11941388echo ( '\n====================================================================================' ) 
  • TOOLS/WATER_BUDGET/OCE_waterbudget.py

    r6519 r6620  
    2222### 
    2323## Import system modules 
    24 import sys, os, shutil, subprocess, platform 
    25 import numpy as np 
     24import sys, os, shutil#, subprocess, platform 
    2625import configparser, re 
    2726from pathlib import Path 
    2827 
    29 ## Import local module 
    30 import WaterUtils as wu 
     28## Import needed scientific modules 
     29import numpy as np, xarray as xr 
    3130 
    3231# Check python version 
     
    3534    raise Exception ( "Minimum Python version is 3.8" ) 
    3635 
     36## Import local module 
     37import WaterUtils as wu 
     38import libIGCM_sys 
     39import nemo, lmdz 
     40 
    3741## Creates parser for reading .ini input file 
    38 config = configparser.ConfigParser() 
     42## ------------------------------------------- 
     43config = configparser.ConfigParser ( interpolation=configparser.ExtendedInterpolation() ) 
    3944config.optionxform = str # To keep capitals 
    4045 
    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## --------------------- 
     48ATM=None ; ATM_HIS='latlon' ; SRF_HIS='latlon' ; RUN_HIS='latlon' ; ORCA=None ; NEMO=None ; OCE_relax=False 
     49OCE_icb=False ; Coupled=False ; Routing=None 
     50TarRestartPeriod_beg=None ; TarRestartPeriod_end=None ; Comment=None ; Period=None ; Title=None 
     51 
    4352## 
    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 
     53ARCHIVE=None ; STORAGE=None ; SCRATCHDIR=None ; R_IN=None ; rebuild=None ; TmpDir=None 
     54FileDir=None ; FileOut=None 
     55dir_ATM_his=None ; dir_SRF_his=None ; dir_OCE_his=None ; dir_ICE_his=None 
     56FileCommon=None ; file_ATM_his=None ; file_SRF_his=None ; file_RUN_his=None 
     57file_OCE_his=None ;  file_ICE_his=None ; file_OCE_sca=None 
     58tar_restart_beg=None ; tar_restart_end=None ; file_ATM_beg=None ; file_ATM_end=None ; file_DYN_beg=None 
     59file_DYN_end=None ; file_SRF_beg=None ; file_SRF_end=None 
     60file_RUN_beg=None ; file_RUN_end=None ; file_RUN_end=None ; file_OCE_beg=None 
     61file_ICE_beg=None ; file_OCE_beg=None 
     62file_OCE_end=None ; file_ICE_beg=None ; file_OCE_end=None ; file_ICE_end=None 
     63tar_restart_beg_ATM=None ; tar_restart_beg_DYN=None ; tar_restart_beg_SRF=None 
     64tar_restart_beg_RUN=None ; tar_restart_beg_OCE=None ; tar_restart_beg_ICE=None 
     65tar_restart_end_ATM=None ; tar_restart_end_DYN=None ; tar_restart_end_SRF=None 
     66tar_restart_end_RUN=None ; tar_restart_end_OCE=None ; tar_restart_end_ICE=None 
     67ContinueOnError=False ; ErrorCount=0 ; SortIco = False 
     68 
     69## Read command line arguments 
     70## --------------------------- 
    5371print ( "Name of Python script:", sys.argv[0] ) 
    5472IniFile = sys.argv[1] 
    55 # Text existence of IniFile 
     73 
     74# Test existence of IniFile 
    5675if not os.path.exists (IniFile ) : 
    5776    raise FileExistsError ( f"File not found : {IniFile = }" ) 
     
    6382config.read (IniFile) 
    6483FullIniFile = 'full_' + IniFile 
    65      
     84 
     85# Reading config.card if possible 
     86## ------------------------------- 
     87ConfigCard = None 
     88 
     89if '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 
     94if 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 
    66124## Reading config file 
    67 for Section in ['Experiment', 'libIGCM', 'Files', 'Physics' ] : 
     125## ------------------- 
     126for Section in ['Config', 'Experiment', 'libIGCM', 'Files', 'Physics' ] : 
    68127   if Section in config.keys () :  
    69         print ( f'Reading [{Section}]' ) 
     128        print ( f'\nReading [{Section}]' ) 
    70129        for VarName in config[Section].keys() : 
    71130            locals()[VarName] = config[Section][VarName] 
     
    74133            exec ( f'{VarName} = wu.setNone ({VarName})' ) 
    75134            exec ( f'wu.{VarName} = {VarName}' ) 
    76             print ( f'{VarName:25} set to : {locals()[VarName])}' ) 
     135            print ( f'    {VarName:21} set to : {locals()[VarName]}' ) 
    77136            #exec ( f'del {VarName}' ) 
    78137 
    79138print ( f'\nConfig file readed : {IniFile} ' ) 
    80139             
    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## ======================= 
     142if wu.unDefined ( 'Ra' )           : Ra          = wu.Ra           #-- Earth Radius (m) 
     143if wu.unDefined ( 'Grav' )         : Grav        = wu.Grav         #-- Gravity (m^2/s 
     144if wu.unDefined ( 'ICE_rho_ice' )  : ICE_rho_ice = wu.ICE_rho_ice  #-- Ice volumic mass (kg/m3) in LIM3 
     145if wu.unDefined ( 'ICE_rho_sno')   : ICE_rho_sno = wu.ICE_rho_sno  #-- Snow volumic mass (kg/m3) in LIM3 
     146if wu.unDefined ( 'OCE_rho_liq' )  : OCE_rho_liq = wu.OCE_rho_liq  #-- Ocean water volumic mass (kg/m3) in NEMO 
     147if wu.unDefined ( 'ATM_rho' )      : ATM_rho     = wu.ATM_rho      #-- Water volumic mass in atmosphere (kg/m^3) 
     148if wu.unDefined ( 'SRF_rho' )      : SRF_rho     = wu.SRF_rho      #-- Water volumic mass in surface reservoir (kg/m^3) 
     149if wu.unDefined ( 'RUN_rho' )      : RUN_rho     = wu.RUN_rho      #-- Water volumic mass of rivers (kg/m^3) 
     150if wu.unDefined ( 'ICE_rho_pnd' )  : ICE_rho_pnd = wu.ICE_rho_pnd  #-- Water volumic mass in ice ponds (kg/m^3) 
     151if wu.unDefined ( 'YearLength' )   : YearLength  = wu.YearLength   #-- Year length (s) 
     152 
     153## Set libIGCM and machine dependant values 
     154## ---------------------------------------- 
     155if not 'Files' in config.keys () : config['Files'] = {} 
     156 
     157config['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 
     160config['Config'] = { 'ContinueOnError':ContinueOnError, 'SortIco':SortIco } 
     161 
     162## -------------------------- 
     163ICO  = ( 'ICO' in wu.ATM ) 
     164LMDZ = ( 'LMD' in wu.ATM ) 
     165 
     166mm = 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 ) 
     169globals().update(mm) 
     170 
    101171config['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' 
     172config['libIGCM'] = { 'ARCHIVE':ARCHIVE, 'STORAGE':STORAGE, 'TmpDir':TmpDir, 'R_IN':R_IN, 'rebuild':rebuild } 
     173 
     174## Defines begining and end of experiment 
     175## -------------------------------------- 
     176if wu.unDefined ( 'DateBegin' ) : 
     177    DateBegin = f'{YearBegin}0101' 
     178    config['Experiment']['DateBegin'] = DateBegin 
     179else : 
     180    YearBegin, MonthBegin, DayBegin = wu.DateSplit ( DateBegin ) 
     181    DateBegin = wu.FormatToGregorian ( DateBegin) 
     182    config['Experiment']['YearBegin'] = YearBegin 
     183 
     184if wu.unDefined ( 'DateEnd' )   : 
     185    DateEnd   = f'{YearEnd}1231' 
     186    config['Experiment']['DateEnd']   = DateEnd 
     187else : 
     188    YearEnd, MonthEnd, DayEnd = wu.DateSplit ( DateEnd ) 
     189    DateEnd   = wu.FormatToGregorian ( DateEnd) 
     190 
     191if wu.unDefined ( 'PackFrequency' ) : 
     192    PackFrequency = YearEnd - YearBegin +1 
     193    config['Experiment']['PackFrequency']   = f'{PackFrequency}' 
     194 
     195if 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 
     200print ( f'{YearBegin=} {DateBegin=}' ) 
     201print ( f'{YearEnd  =} {DateEnd  =}' ) 
     202print ( f'{PackFrequency=}' ) 
     203     
     204## Output file with water budget diagnostics 
     205## ----------------------------------------- 
     206if wu.unDefined ( 'FileOut' ) : FileOut = f'ATM_waterbudget_{JobName}_{DateBegin}_{DateEnd}.out' 
    113207config['Files']['FileOut'] = FileOut 
    114208 
    115209f_out = open ( FileOut, mode = 'w' ) 
    116210 
    117 # Useful functions 
    118 def kg2Sv    (val, rho=ATM_rho) : 
     211## Useful functions 
     212## ---------------- 
     213def kg2Sv  (val, rho=OCE_rho_liq) : 
    119214    '''From kg to Sverdrup''' 
    120215    return val/dtime_sec*1.0e-6/rho 
    121216 
    122 def kg2myear (val, rho=ATM_rho) : 
     217def kg2myear (val, rho=OCE_rho_liq) : 
    123218    '''From kg to m/year''' 
    124     return val/ATM_aire_sea_tot/rho/NbYear 
    125  
    126 def var2prt (var, small=False, rho=ATM_rho) : 
     219    return val/OCE_aire_tot/rho/NbYear 
     220 
     221def var2prt (var, small=False, rho=OCE_rho_liq) : 
    127222    if small :  return var , kg2Sv(var, rho=rho)*1000., kg2myear(var, rho=rho)*1000. 
    128223    else     :  return var , kg2Sv(var, rho=rho)      , kg2myear(var, rho=rho) 
    129224 
    130 def prtFlux (Desc, var, Form='F', small=False, rho=ATM_rho, width=15) : 
     225def prtFlux (Desc, var, Form='F', small=False, rho=OCE_rho_liq, width=15) : 
    131226    if small : 
    132         if Form in ['f', 'F'] : ff=" {:12.4e} kg | {:12.4f} mSv | {:12.4f} mm/year " 
    133         if Form in ['e', 'E'] : ff=" {:12.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 " 
    134229    else : 
    135         if Form in ['f', 'F'] : ff=" {:12.4e} kg | {:12.4f} Sv  | {:12.4f} m/year  " 
    136         if Form in ['e', 'E'] : ff=" {:12.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  " 
    137232    echo ( (' {:>{width}} = ' +ff).format (Desc, *var2prt(var, small, rho=rho), width=width ) ) 
    138233    return None 
     
    146241    return None 
    147242     
    148 ### Set libIGCM directories 
     243    
     244## Set libIGCM directories 
     245## ----------------------- 
    149246if wu.unDefined ('R_OUT'      ) : R_OUT       = os.path.join ( ARCHIVE   , 'IGCM_OUT' ) 
    150247if wu.unDefined ('R_BUF'      ) : R_BUF       = os.path.join ( SCRATCHDIR, 'IGCM_OUT' ) 
     
    157254if wu.unDefined ('R_FIGR'     ) : R_FIGR      = os.path.join ( STORAGE, 'IGCM_OUT', L_EXP ) 
    158255 
    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 ) 
     256config['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## ------------------------------ 
     261if wu.unDefined ( 'FileDir' ) : FileDir = os.path.join ( TmpDir, f'WATER_{JobName}' ) 
     262config['Files']['FileDir'] = FileDir 
     263 
     264if not os.path.isdir ( FileDir ) : os.makedirs ( FileDir ) 
     265 
     266##- Set directories to rebuild ocean and ice restart files 
     267if wu.unDefined ( 'FileDirOCE' ) : FileDirOCE = os.path.join ( FileDir, 'OCE' ) 
     268if wu.unDefined ( 'FileDirICE' ) : FileDirICE = os.path.join ( FileDir, 'ICE' ) 
     269if not os.path.exists ( FileDirOCE ) : os.mkdir ( FileDirOCE ) 
     270if not os.path.exists ( FileDirICE ) : os.mkdir ( FileDirICE ) 
    172271 
    173272echo (' ') 
    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}' ) 
     273echo ( f'JobName    : {JobName}'   ) 
     274echo ( f'Comment    : {Comment}'   ) 
     275echo ( f'TmpDir     : {TmpDir}'    ) 
     276echo ( f'FileDir    : {FileDir}'    ) 
     277echo ( f'FileDirOCE : {FileDirOCE}' ) 
     278echo ( f'FileDirICE : {FileDirICE}' ) 
    179279 
    180280echo ( f'\nDealing with {L_EXP}'  ) 
    181281 
    182 #-- Creates model output directory names 
     282## Creates model output directory names 
     283## ------------------------------------ 
    183284if Freq == "MO" : FreqDir = os.path.join ( 'Output' , 'MO' ) 
    184285if Freq == "SE" : FreqDir = os.path.join ( 'Analyse', 'SE' ) 
     
    196297#-- Creates files names 
    197298if 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' 
    200301    config['Files']['Period'] = Period 
     302 
     303config['Files']['DateBegin'] = DateBegin 
     304config['Files']['DateBegin'] = DateEnd 
     305        
     306echo ( f'Period   : {Period}' ) 
     307 
    201308if wu.unDefined ( 'FileCommon' ) : 
    202309    FileCommon = f'{JobName}_{Period}' 
     
    204311 
    205312if wu.unDefined ( 'Title' ) : 
    206     Title = f'{JobName} : {Freq} : {YearBegin}-01-01 - {YearEnd}-12-31' 
     313    Title = f'{JobName} : {Freq} : {DateBegin} - {DateEnd}' 
    207314    config['Files']['Title'] = Title 
    208315         
     
    228335 
    229336## Compute run length 
     337## ------------------ 
    230338dtime = ( d_OCE_his.time_counter_bounds.max() - d_OCE_his.time_counter_bounds.min() ) 
    231339echo ( f'\nRun length : {(dtime/np.timedelta64(1, "D")).values:8.2f} days' ) 
     
    233341 
    234342## Compute length of each period 
     343## ----------------------------- 
    235344dtime_per = ( d_OCE_his.time_counter_bounds[:,-1] - d_OCE_his.time_counter_bounds[:,0] ) 
    236345echo ( f'\nPeriods lengths (days) : ') 
     
    243352NbYear = dtime_sec / YearLength 
    244353 
    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 
     356if wu.unDefined ('TarRestartDate_beg' ) : TarRestartDate_beg = wu.DateMinusOneDay ( DateBegin ) 
     357if wu.unDefined ('TarRestartDate_end' ) : TarRestartDate_end = wu.FormatToGregorian ( DateEnd ) 
     358 
     359if 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}') 
    254367    config['Files']['TarRestartPeriod_beg'] = TarRestartPeriod_beg 
    255368 
    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' 
     369if 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}') 
    260377    config['Files']['TarRestartPeriod_end'] = TarRestartPeriod_end 
     378 
     379echo (f'Restart dates - Start : {TarRestartPeriod_beg}  /  End : {TarRestartPeriod_end}') 
    261380 
    262381if wu.unDefined ( 'tar_restart_beg' ) : 
     
    267386    config['Files']['tar_restart_end'] = tar_restart_end 
    268387 
    269 echo ( f'{tar_restart_beg}' ) 
    270 echo ( f'{tar_restart_end}' ) 
    271  
     388echo ( f'{tar_restart_beg = }' ) 
     389echo ( f'{tar_restart_end = }' ) 
     390     
    272391# 
    273392if wu.unDefined ('tar_restart_beg_ATM' ) : tar_restart_beg_ATM = tar_restart_beg 
     
    286405 
    287406if 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' 
    289408    config['Files']['file_OCE_beg'] = file_OCE_beg 
    290409if 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' 
    292411    config['Files']['file_OCE_end'] = file_OCE_end 
    293412if 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' 
    295414    config['Files']['file_ICE_beg'] = file_ICE_beg 
    296415if 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' 
    298417    config['Files']['file_ICE_end'] = file_ICE_end 
    299418 
     
    302421echo ( f'{file_ICE_beg}' ) 
    303422echo ( f'{file_ICE_end}' ) 
     423 
     424liste_beg = [file_OCE_beg, file_ICE_beg ] 
     425liste_end = [file_ATM_end, file_ICE_end ] 
    304426 
    305427echo ('\nExtract and rebuild OCE and ICE restarts') 
     
    311433    return int (ndomain_opa) 
    312434 
    313 def extract_and_rebuild ( file_name=file_OCE_beg, tar_restart=tar_restart_end, RunDirComp=RunDirOCE, ErrorCount=ErrorCount ) : 
     435def extract_and_rebuild ( file_name=file_OCE_beg, tar_restart=tar_restart_end, FileDirComp=FileDirOCE, ErrorCount=ErrorCount ) : 
    314436    '''Extract restart file from tar. Rebuild ocean files if needed''' 
    315437    echo ( f'----------') 
     
    321443        # Try to extract the rebuilded file 
    322444        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' 
    324446            echo ( command ) 
    325447            try :  
    326448                os.system ( command ) 
    327449            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' 
    330452                    echo ( command ) 
    331453                    ierr = os.system ( command ) 
     
    333455                    else         : raise Exception ( f'command failed : {command}' ) 
    334456                    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}' 
    337459                echo ( command ) 
    338460                ierr = os.system ( command ) 
     
    341463            else :  
    342464                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}' 
    344466                ierr = os.system ( command ) 
    345467                if ierr == 0 : echo ( f'command done : {command}' ) 
     
    354476 
    355477             
    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 ) 
     478ErrorCount += extract_and_rebuild ( file_name=file_OCE_beg, tar_restart=tar_restart_beg, FileDirComp=FileDirOCE ) 
     479ErrorCount += extract_and_rebuild ( file_name=file_OCE_end, tar_restart=tar_restart_end, FileDirComp=FileDirOCE ) 
     480ErrorCount += extract_and_rebuild ( file_name=file_ICE_beg, tar_restart=tar_restart_beg, FileDirComp=FileDirICE ) 
     481ErrorCount += extract_and_rebuild ( file_name=file_ICE_end, tar_restart=tar_restart_end, FileDirComp=FileDirICE ) 
    360482 
    361483echo ('Opening OCE and ICE restart files') 
    362484if 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() 
    367489if 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() 
    372494 
    373495## Write the full configuration 
     
    377499 
    378500     
    379 def kg2Sv  (val, rho=OCE_rho_liq) : 
    380     '''From kg to Sverdrup''' 
    381     return val/dtime_sec*1.0e-6/rho 
    382  
    383 def kg2myear (val, rho=OCE_rho_liq) : 
    384     '''From kg to m/year''' 
    385     return val/OCE_aire_tot/rho/NbYear 
    386  
    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 None 
    400  
    401501# Get mask and surfaces 
    402502sos = d_OCE_his ['sos'][0].squeeze() 
     
    670770echo ('                        = (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) ) ) 
    671771 
     772prtFlux ('   Leak OCE             ', ( dOCE_mas_wat + OCE_mas_empmr - OCE_mas_iceshelf) , 'e' ) 
     773prtFlux ('   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' ) 
     774prtFlux ('   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 
    672778 
    673779# check if emp     = emp_ice + emp_oce - calving 
  • TOOLS/WATER_BUDGET/WaterUtils.py

    r6518 r6620  
    11#!/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 
    2524import numpy as np 
    2625import configparser, re 
    2726 
    28 VarInt = 10 
    29 Ra     = None 
    30  
    31 def ftest () : 
    32     print ( toto ) 
     27VarInt      = 10 
     28Rho         = 1000.0 
     29Ra          = 6366197.7236758135 #-- Earth Radius (m) 
     30Grav        = 9.81               #-- Gravity (m^2/s 
     31ICE_rho_ice = 917.0              #-- Ice volumic mass (kg/m3) in LIM3 
     32ICE_rho_sno = 330.0              #-- Snow volumic mass (kg/m3) in LIM3 
     33OCE_rho_liq = 1026.0             #-- Ocean water volumic mass (kg/m3) in NEMO 
     34ATM_rho     = 1000.0             #-- Water volumic mass in atmosphere (kg/m^3) 
     35SRF_rho     = 1000.0             #-- Water volumic mass in surface reservoir (kg/m^3) 
     36RUN_rho     = 1000.0             #-- Water volumic mass of rivers (kg/m^3) 
     37ICE_rho_pnd = 1000.              #-- Water volumic mass in ice ponds (kg/m^3) 
     38YearLength  = 365.25 * 24. * 60. * 60. #-- Year length (s) 
    3339 
    3440def setBool (chars) : 
     
    4349    '''Convert specific char string in integer or real if possible''' 
    4450    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]+)?$") 
    4652        isNumber = realnum.match(chars.strip()) != None 
    4753        isInt    = chars.strip().isdigit() 
     
    6369 
    6470def 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 
    6774        else            : unDefined = False 
    6875    else                : unDefined = True 
    6976    return unDefined 
     77 
     78def 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 
    7085 
    7186def Ksum (tab) : 
     
    87102def Ssum (tab) : 
    88103    ''' 
    89     Precision summation by sorting by absolute value 
     104    Precision summation by sorting by absolute values 
    90105    ''' 
    91106    Ssum = np.sum ( tab[np.argsort(np.abs(tab))] ) 
     
    102117Psum = KSsum 
    103118 
    104  
    105  
    106  
     119def 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 
     155def 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 
     169def 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         
     175def 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   
     183def 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 
     191def 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 
     210def 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 
     218def 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 
     234def 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.