#!/usr/bin/env python3




#===============================================================================
#   Options
#===============================================================================
period='10010101_10010130'
period_title='(year 1001 month 1)'
#period='10051201_10051230'
#period_title='(year 1005 month 12)'

file_type='avg'
freq='5d'

idxlat0 = 78    # transect grille mere
idxlat1 = 128   # transect grille fille

# map0 
lonmin_grid0, lonmax_grid0, latmin_grid0, latmax_grid0, lon_interv0, lat_interv0 = -34, -6, 5, 37, 8, 17
# map1 
lonmin_grid1, lonmax_grid1, latmin_grid1, latmax_grid1, lon_interv1, lat_interv1 = -28, -14, 10, 26, 8, 9
# map2 
lonmin_grid2, lonmax_grid2, latmin_grid2, latmax_grid2, lon_interv2, lat_interv2 = -20.5, -15.5, 11.5, 18.5, 6, 8

# transect 1 
lonmin_transect0, lonmax_transect0, depthmin_transect0, depthmax_transect0 = -20, -16, -500, 0


#===============================================================================
#   Var choice
#===============================================================================
### physic 2D
#var_list=['SST','zeta','hbl','usurf','vsurf','sustr','svstr','shflux','swflux','swrad']

### physic 3D
#var_list=['temp','usurf','vsurf']

### bio 3D
#var_list=['FER','NO3','DCHL','NCHL','CHL','MESO','ZOO','CACO3','O2','PO4','Si','NH4']


F_map0=True
F_map1=True
F_map2=True
#var_list_map_phy=['SST','zeta','hbl','usurf','vsurf','sustr','svstr','shflux','swflux','swrad']
#var_list_map_phy=['SST','salt','zeta','hbl','ubar','vbar','usurf','vsurf','sustr','svstr','shflux','swflux']
var_list_map_phy=['SST','salt','zeta','hbl','ubar','vbar','usurf','vsurf']  # Special Pierre
#var_list_map_phy=['SST','zeta','hbl','usurf','vsurf']
#var_list_map_phy=['zeta','ubar','vbar','usurf','vsurf','SST','salt','bostr','wstr','sustr','svstr','diff3d','AKv','AKt','AKs','hbl','shflux','swflux']
#var_list_map_phy=['zeta',                              'SST','salt','bostr','wstr',                'diff3d','AKv','AKt','AKs','hbl','shflux','swflux']

#var_list_map_bio=['FER','NO3','DCHL','NCHL','CHL','MESO','ZOO','O2']
#var_list_map_bio=['O2','PO4','Si','NANO','ZOO','DIA','MESO','FER','NCHL','DCHL','CHL','NO3','LGW']
#var_list_map_bio=['NO3','PO4','Si','FER','DCHL','NCHL','CHL','NH4','DIC','Alkalini','O2','MESO','NANO','ZOO','DIA','LGW']
var_list_map_bio=['NO3','PO4','Si','FER','DCHL','NCHL','CHL','O2','MESO','NANO','ZOO','DIA','LGW']

#var_list_map_phy=['ubar','vbar','usurf','vsurf']
var_list_map_phy=[]
var_list_map_bio=['FER']
#var_list_map_bio=[]

F_transect1=False
#var_list_transect_phy=['temp','usurf','vsurf']
var_list_transect_phy=['temp']
var_list_transect_bio=['FER','NO3','DCHL','NCHL','CHL','MESO','ZOO','O2']

#var_list_map=['usurf']
#var_list_transect=['usurf']

#===============================================================================
#   Exp choice
#===============================================================================
c11cp_climatoruns_021020={
#'root_path':'/ccc/scratch/cont005/gen1140/chabertp/can11sen2_croco/outputs',
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/can11sen2_croco/outputs',
'exp_name':'c11cp_climatoruns_021020',
'test_name':''
}

c11s2cp_climatoruns_151020={
#'root_path':'/ccc/scratch/cont005/gen1140/chabertp/can11sen2_croco/outputs',
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/can11sen2_croco/outputs',
'exp_name':'c11s2cp_climatoruns_151020',
'test_name':''
}

c11s2cp_climatoruns_051120={
#'root_path':'/ccc/scratch/cont005/gen1140/chabertp/can11sen2_croco/outputs',
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/can11sen2_croco/outputs',
'exp_name':'c11s2cp_climatoruns_051120',
'test_name':''
}

c11s2cp_climatoruns_sync_ASAP2020={
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/can11sen2_croco/outputs',
'exp_name':'c11s2cp_climatoruns_sync_ASAP2020',
'test_name':''
}

c11s2_climatoruns={
#'root_path':'/ccc/scratch/cont005/gen1140/chabertp/can11sen2_croco/outputs',
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/can11sen2_croco/outputs',
'exp_name':'c11s2_climatoruns',
'test_name':''
}

awa_v2_00={
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/AWA/outputs',
'exp_name':'awa_v2.00',
'test_name':''
}

c11s2cp_climatoruns_shading={
#'root_path':'/ccc/scratch/cont005/gen1140/chabertp/can11sen2_croco/outputs',
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/AWA/outputs',
'exp_name':'c11s2cp_climatoruns_shading',
'test_name':''
}

awa_v3_01_IRENE_frcbio_nc_1_pas_lu={
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/AWA/outputs',
'exp_name':'awa_v3.01_IRENE',
'test_name':'frcbio.nc.1_pas_lu'
}

awa_v3_01_IRENE={
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/AWA/outputs',
'exp_name':'awa_v3.01_IRENE',
'test_name':''
}

awa_v3_01_IRENE_AMD={
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/AWA/outputs',
'exp_name':'awa_v3.01_IRENE-AMD',
'test_name':''
}

awa_v3_01_JEANZAY={
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/AWA/outputs',
'exp_name':'awa_v3.01_JEANZAY',
'test_name':''
}

awa_v131={
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/croco/AWA/outputs',
'exp_name':'awa_v1.3.1',
'test_name':''
}

c11s2cp_climatoruns_shading={
'root_path':'/ccc/scratch/cont005/gen1140/hourdinc/croco/AWA/outputs',
'exp_name':'c11s2cp_climatoruns_shading',
'test_name':''
}

#  all
#exp_list=[c11cp_climatoruns_021020, c11s2cp_climatoruns_051120, c11s2cp_climatoruns_151020, c11s2cp_climatoruns_sync_ASAP2020, c11s2_climatoruns]

#exp_list=[c11cp_climatoruns_021020]
#exp_list=[c11s2cp_climatoruns_051120]
#exp_list=[c11s2cp_climatoruns_151020]
#exp_list=[c11s2cp_climatoruns_sync_ASAP2020]
#exp_list=[c11s2_climatoruns]
#exp_list=[awa_v2_00]
#exp_list=[awa_v3_01_IRENE]
#exp_list=[awa_v3_01_IRENE_frcbio_nc_1_pas_lu]
#exp_list=[awa_v3_01_IRENE_AMD]
#exp_list=[awa_v3_01_JEANZAY]
exp_list=[awa_v131]
#exp_list=[c11s2cp_climatoruns_shading]
#exp_list=[c11s2cp_climatoruns_shading, awa_v131]


exp2=awa_v131

#===============================================================================
#   Import
#===============================================================================
#  pour netcdf pour eviter pb opal
#import mpi4py
#mpi4py.rc.initialize=False
#mpi4py.rc.finalize=False

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
##from netCDF4 import Dataset
#import cmocean
import xarray
#import scipy
#import xcroco
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import matplotlib.ticker as mticker
from matplotlib.patches import Rectangle
##import cartopy.feature as cfeature
#from matplotlib.font_manager import FontProperties
import datetime

#  fonts
#plt.rc('font',size=10)
#mpl.rc('text', usetex=True)    #  False pour desactiver latex.
#mpl.rc('font', family='serif')


#===============================================================================
#   Functions
#===============================================================================
def var_choice(ds, var_str):
###   dynamique
    if var_str=='zeta':
        var = ds.zeta[0,:,:].values
#       cm = cmocean.cm.balance
        cm = 'jet'
        cbartitle = 'zeta [m]'
        vmin, vmax = -0.3, 0
    if var_str=='ubar':
        var = ds.ubar[0,:,:].values*100
#       cm = cmocean.cm.balance
        cm = 'bwr'
        cbartitle = 'ubar [cm/s]'
        vmin, vmax = -20, 20
    if var_str=='vbar':
        var = ds.vbar[0,:,:].values*100
#       cm = cmocean.cm.balance
        cm = 'bwr'
        cbartitle = 'vbar [cm/s]'
        vmin, vmax = -20, 20
    if var_str=='usurf':
        var = ds.u[0, -1, :, :].values*100
#       var = xcroco.var2rho(ds, var).values
#       cm = cmocean.cm.balance
        cm = 'bwr'
        cbartitle = 'usurf [cm/s]'
        vmin, vmax = -20, 20
    if var_str=='vsurf':
        var = ds.v[0, -1, :, :].values*100
#       cm = cmocean.cm.balance
        cm = 'bwr'
        cbartitle = 'vsurf [cm/s]'
        vmin, vmax = -20, 20
    if var_str=='SST':
        var = ds.temp[0, -1, :, :].values
        cm = 'jet'
        cbartitle = 'SST [C]'
        vmin, vmax = 19, 27
    if var_str=='salt':
        var = ds.salt[0,-1,:,:].values
        cm = 'jet'
        cbartitle = 'salt [PSU]'
        vmin, vmax = 34, 38
    if var_str=='bostr':
        var = ds.bostr[0,:,:].values
        cm = cmocean.cm.algae
        cbartitle = 'bostr [N m-2]'
        vmin, vmax = 0,0.1 
    if var_str=='wstr':
        var = ds.wstr[0,:,:].values
        cm = cmocean.cm.algae
        cbartitle = 'wstr [N m-2]'
        vmin, vmax = 0,0.1 
    if var_str=='sustr':
        var = ds.sustr[0,:,:].values
#       cm = cmocean.cm.algae
        cm = 'bwr'
        cbartitle = 'sustr [N m-2]'
        vmin, vmax = -0.05,0.05
    if var_str=='svstr':
        var = ds.svstr[0,:,:].values
#       cm = cmocean.cm.algae
        cm = 'bwr'
        cbartitle = 'svstr [N m-2]'
        vmin, vmax = -0.05,0.05
    if var_str=='diff3d':
        var = ds.diff3d[0,-1,:,:].values
        cm = cmocean.cm.algae
        cbartitle = 'diff3d [N m-2]'
        vmin, vmax = 0,4e+10
    if var_str=='AKv':
        var = ds.AKv[0,-1,:,:].values
#       cm = cmocean.cm.algae
        cm = 'jet'
        cbartitle = 'AKv [m2s-1]'
        vmin, vmax = 0,0.1
    if var_str=='AKt':
        var = ds.AKt[0,-1,:,:].values
        cm = cmocean.cm.algae
        cbartitle = 'AKt [m2s-1]'
        vmin, vmax = 0,0.1
    if var_str=='AKs':
        var = ds.AKs[0,-1,:,:].values
        cm = cmocean.cm.algae
        cbartitle = 'AKs [m2s-1]'
        vmin, vmax = 0,0.1
    if var_str=='hbl':
        var = ds.hbl[0, :, :].values
#       cm = cmocean.cm.deep
        cm = 'jet'
        cbartitle = 'hbl [m]'
        vmin, vmax = 10, 120
    if var_str=='shflux':
        var = ds.shflux[0, :, :].values
#       cm = cmocean.cm.algae
        cm = 'bwr'
        cbartitle = 'shflux [W m-2]'
        vmin, vmax = -100,100
    if var_str=='swflux':
        var = ds.swflux[0, :, :].values
#       cm = cmocean.cm.algae
        cm = 'bwr'
        cbartitle = 'swflux [cm d-1]'
        vmin, vmax = -1,1 
    if var_str=='swrad':
        var = ds.swrad[0, :, :].values
        cm = cmocean.cm.algae
        cbartitle = 'swrad [W m-2]'
        vmin, vmax = 0, 2
###   BIO
    if var_str=='O2':
        var = ds.O2[0, -1, :, :].values
#       cm = cmocean.cm.oxy
        cm = 'jet'
        cbartitle = 'O2 [umol L-1]'
        vmin, vmax = 200, 300
    if var_str=='PO4':
        var = ds.PO4[0, -1, :, :].values
#       cm = cmocean.cm.matter
        cm = 'jet'
        cbartitle = 'PO4 [umol P L-1]'
        vmin, vmax = 0, 1
    if var_str=='Si':
        var = ds.Si[0, -1, :, :].values
#       cm = cmocean.cm.matter
        cm = 'jet'
        cbartitle = 'Si [umol Si L-1]'
        vmin, vmax = 0, 10
    if var_str=='NANO':
        var = ds.NANO[0, -1, :, :].values
#       cm = cmocean.cm.algae
        cm = 'jet'
        cbartitle = 'NANO [umol C L-1]'
        vmin, vmax = 0,10
    if var_str=='ZOO':
        var = ds.ZOO[0, -1, :, :].values
#       cm = cmocean.cm.algae
        cm = 'jet'
        cbartitle = 'ZOO [umol C L-1]'
        vmin, vmax = 1e-2, 5
    if var_str=='DIA':
        var = ds.DIA[0, -1, :, :].values
#       cm = cmocean.cm.algae
        cm = 'jet'
        cbartitle = 'DIA [umol C L-1]'
        vmin, vmax = 1e-2,10 
    if var_str=='MESO':
        var = ds.MESO[0, -1, :, :].values
#       cm = cmocean.cm.algae
        cbartitle = 'MESO [umol C L-1]'
        cm = 'jet'
        vmin, vmax = 0, 2
    if var_str=='FER':
        var = ds.FER[0, -1, :, :].values*1000
#       cm = cmocean.cm.matter
        cm = 'jet'
#       cbartitle = 'FER [umol Fe L-1]'
        cbartitle = 'FER [nmol Fe L-1]'
#       vmin, vmax = 1e-4, 0.003
        vmin, vmax = 0.1, 4
    if var_str=='NCHL':
        var = ds.NCHL[0, -1, :, :].values
#       cm = cmocean.cm.algae
        cm = 'jet'
        cbartitle = 'NCHL [$mg.m^{-3}$]'
        vmin, vmax = 1e-2, 1e1
    if var_str=='DCHL':
        var = ds.DCHL[0, -1, :, :].values
#       cm = cmocean.cm.algae
        cm = 'jet'
        cbartitle = 'DCHL [$mg.m^{-3}$]'
        vmin, vmax = 1e-2, 1e1
    if var_str=='CHL':
        varA = ds.DCHL[0, -1, :, :].values
        varB = ds.NCHL[0, -1, :, :].values
        var = varA + varB
#       cm = cmocean.cm.algae
        cm = 'jet'
        cbartitle = 'DCHL+NCHL [$mg.m^{-3}$]'
        vmin, vmax = 1e-1, 1e1
    if var_str=='NO3':
        var = ds.NO3[0, -1, :, :].values
#       cm = cmocean.cm.matter
        cm = 'jet'
        cbartitle = 'NO3 [umol N L-1]'
        vmin, vmax = 0, 10
    if var_str=='LGW':
        var = ds.LGW[0,-1,:,:].values*1000
#       cm = cmocean.cm.matter
        cm = 'jet'
        cbartitle = 'LGW [nmol L-1]'
        vmin, vmax = 0, 5

###   pas utilisees?
    if var_str=='CACO3':
        var = ds.CACO3[0, -1, :, :].values
        cm = cmocean.cm.matter
        cbartitle = 'CACO3 [umol C L-1]'
        vmin, vmax = 0, 0.1
    if var_str=='NH4':
        var = ds.NH4[0, -1, :, :].values
        cm = cmocean.cm.matter
        cbartitle = 'NH4 [umol N L-1]'
        vmin, vmax = 0, 2

    return(var, cm, cbartitle, vmin, vmax)


def var_choice2(ds, var_str, idxlat):
    if var_str=='temp':
        var = ds.temp[0, :, idxlat, :].values
#       cm = cmocean.cm.solar
        cm = 'jet'
        cbartitle = 'Temp [°C]'
        vmin, vmax = 5, 25
    if var_str=='usurf':
        var = ds.u[0, :, idxlat, :].values
#       cm = cmocean.cm.balance
        cm = 'bwr'
#       cbartitle = 'u_{surf} [m/s]'
        cbartitle = 'usurf [m/s]'
        vmin, vmax = -0.1, 0.1
    if var_str=='vsurf':
        var = ds.v[0, :, idxlat, :].values
#       cm = cmocean.cm.balance
        cm = 'bwr'
#       cbartitle = 'v_{surf} [m/s]'
        cbartitle = 'vsurf [m/s]'
        vmin, vmax = -0.1, 0.1
    if var_str=='FER':
        var = ds.FER[0, :, idxlat, :].values
        cm = cmocean.cm.matter
        cbartitle = 'FER [umol Fe L-1]'
        vmin, vmax = 1e-4, 0.003
    if var_str=='NO3':
        var = ds.NO3[0, :, idxlat, :].values
        cm = cmocean.cm.matter
        cbartitle = 'NO3 [umol N L-1]'
        vmin, vmax = 0, 35
    if var_str=='DCHL':
        var = ds.DCHL[0, :, idxlat, :].values
        cm = cmocean.cm.algae
        cbartitle = 'DCHL [$mg.m^{-3}$]'
        vmin, vmax = 1e-2, 1
    if var_str=='NCHL':
        var = ds.NCHL[0, :, idxlat, :].values
        cm = cmocean.cm.algae
        cbartitle = 'NCHL [$mg.m^{-3}$]'
        vmin, vmax = 1e-2, 1
    if var_str=='CHL':
        varA = ds.DCHL[0, :, idxlat, :].values
        varB = ds.NCHL[0, :, idxlat, :].values
        var = varA + varB
        cm = cmocean.cm.algae
        cbartitle = 'DCHL+NCHL [$mg.m^{-3}$]'
        vmin, vmax = 1e-1, 1e1
    if var_str=='MESO':
        var = ds.MESO[0, :, idxlat, :].values
        cm = cmocean.cm.algae
        cbartitle = 'MESO [umol C L-1]'
        vmin, vmax = 0, 2
    if var_str=='ZOO':
        var = ds.ZOO[0, :, idxlat, :].values
        cm = cmocean.cm.algae
        cbartitle = 'ZOO [umol C L-1]'
        vmin, vmax = 1e-2, 2
    if var_str=='CACO3':
        var = ds.CACO3[0, :, idxlat, :].values
        cm = cmocean.cm.matter
        cbartitle = 'CACO3 [umol C L-1]'
        vmin, vmax = 0, 0.3
    if var_str=='O2':
        var = ds.O2[0, :, idxlat, :].values
        cm = cmocean.cm.oxy
        cbartitle = 'O2 [umol L-1]'
        vmin, vmax = 0, 250
    if var_str=='PO4':
        var = ds.PO4[0, :, idxlat, :].values
        cm = cmocean.cm.matter
        cbartitle = 'PO4 [umol P L-1]'
        vmin, vmax = 0, 2
    if var_str=='Si':
        var = ds.Si[0, :, idxlat, :].values
        cm = cmocean.cm.matter
        cbartitle = 'Si [umol Si L-1]'
        vmin, vmax = 0, 40
    if var_str=='NH4':
        var = ds.NH4[0, :, idxlat, :].values
        cm = cmocean.cm.matter
        cbartitle = 'NH4 [umol N L-1]'
        vmin, vmax = 0, 2

    return(var, cm, cbartitle, vmin, vmax)

local_time1=datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')    #  '2018-09-26'
local_time2=datetime.datetime.strftime(datetime.datetime.now(), '%d-%b-%Y')    #  '2018-09-26'
local_time3=datetime.datetime.strftime(datetime.datetime.now(), '%Y_%m_%d-%H-%M-%S') # '2018_09_26-16-38-04'
local_time4=datetime.datetime.strftime(datetime.datetime.now(), '%d-%b-%Y')    #  '19-Sep-2018'

def plot_map(ii, agrif, idxlat, exp_name, test_name, ds, var_str, lonmin, lonmax, latmin, latmax, lon_interv, lat_interv, lon_zoom, lat_zoom):
   if agrif == 0 : ext1=''; ext2=''
   elif agrif == 1 : ext1='CHILD'; ext2='_CHILD'

   print ('\n   ',var_str,' plot map '+ext1+'  (lon : '+str(lonmin)+' '+str(lonmax)+'    lat : '+str(latmin)+' '+str(latmax)+')')
#  lons = np.linspace(lonmin-1, lonmax+1, lonmax - lonmin + 3)
#  lats = np.linspace(latmin-1, latmax+1, latmax - latmin + 3)
   lons = np.linspace(lonmin, lonmax, lon_interv)
   lats = np.linspace(latmin, latmax, lat_interv)

   if (var_str == 'usurf') | (var_str == 'sustr') | (var_str == 'ubar') :
      lon, lat = ds.lon_u.values, ds.lat_u.values
   elif (var_str == 'vsurf') | (var_str == 'svstr') | (var_str == 'vbar'):
      lon, lat = ds.lon_v.values, ds.lat_v.values
   else :
      lon, lat = ds.lon_rho.values, ds.lat_rho.values

   landmask = ds.mask_rho.values[:,:]

   var, cm, cbartitle, vmin, vmax = var_choice(ds, var_str)
#  mmvar="\\Large (min:%.1e  max:%.1e)" %(var.min(),var.max())
   if var.max() < 0.1 : 
      mmvar="(min:%.1e  max:%.1e)" %(var.min(),var.max())
   else :
      mmvar="(min:%.2f  max:%.2f)" %(var.min(),var.max())

   if (var_str == 'usurf') | (var_str == 'sustr') | (var_str == 'ubar') | (var_str == 'vsurf') | (var_str == 'svstr') | (var_str == 'vbar') :
      var[var==0] = np.nan
   else :
#     pas de mask pour u et v dans le  fichier netcdf
      var[landmask==0] = np.nan

   plt.figure(ii,figsize=(8,8));
   plt.subplot(1,1,1, projection=ccrs.PlateCarree()) 
   ax = plt.gca()
   pcm = ax.pcolormesh(lon, lat, var, cmap=cm, vmin=vmin, vmax=vmax)
   if var_str=='DCHL' or var_str=='NCHL' or var_str=='CHL' or var_str=='FER':
      pcm = ax.pcolormesh(lon, lat, var, cmap=cm, norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax))
   plt.colorbar(pcm, label=cbartitle)
   plt.suptitle(exp_name+' '+test_name+' '+ext1+'  '+period_title)
   plt.text(lonmin+0.2,latmin+0.2,mmvar,verticalalignment='bottom',horizontalalignment='left',bbox=dict(facecolor='white', edgecolor='white',alpha=0.5))
   plt.text(lonmax-0.2,latmin+0.2,local_time4,verticalalignment='bottom',horizontalalignment='right',color='black',bbox=dict(facecolor='white', edgecolor='white', alpha=0.5))
#  plt.text(lonmax-0.2,latmin+0.2,'\\large \\textbf{\\it{'+local_time4+'}}',verticalalignment='bottom',horizontalalignment='right',color='black',bbox=dict(facecolor='white', edgecolor='white', alpha=0.5))
   gl = ax.gridlines(draw_labels=True, linestyle='--', alpha=.5, color='gray', linewidth=1)
   gl.xlocator = mticker.FixedLocator(lons)
   gl.ylocator = mticker.FixedLocator(lats)
   gl.xformatter = LONGITUDE_FORMATTER
   gl.xformatter = LONGITUDE_FORMATTER
   gl.yformatter = LATITUDE_FORMATTER
   gl.top_labels = False
   gl.right_labels = False
   plt.xlim(lonmin, lonmax);plt.ylim(latmin,latmax)
   plt.xlabel('Longitude (°)'); plt.ylabel('Latitude (°)')
# if agrif : plot zoom boundaries 
   if ('c11s2' in exp_name)  | ('awa' in exp_name) :
      plt.plot(lon_zoom,lat_zoom,'m-')
      plt.text(lon_zoom[3],lat_zoom[3],'AGRIF',verticalalignment='bottom',horizontalalignment='left',color='magenta',bbox=dict(facecolor='white', edgecolor='white', alpha=0.5))
# plot zoom map0, map1...
   ax.add_patch(Rectangle((lonmin_grid1, latmin_grid1), lonmax_grid1-lonmin_grid1, latmax_grid1-latmin_grid1,alpha=1,edgecolor='black',facecolor='none',linestyle='-.',lw=1)) 
   plt.text(lonmax_grid1, latmax_grid1 ,'zoom1',verticalalignment='bottom',horizontalalignment='left',color='black',bbox=dict(facecolor='white', edgecolor='white', alpha=0.5))
   ax.add_patch(Rectangle((lonmin_grid2, latmin_grid2), lonmax_grid2-lonmin_grid2, latmax_grid2-latmin_grid2,alpha=1,edgecolor='black',facecolor='none',linestyle='-.',lw=1)) 
   plt.text(lonmax_grid2, latmax_grid2 ,'zoom2',verticalalignment='bottom',horizontalalignment='left',color='black',bbox=dict(facecolor='white', edgecolor='white', alpha=0.5))
# plot transect line
   iimin=0; iimax=0
   while (lon[idxlat,iimin] < lonmin_transect0) : iimin=iimin+1
   while (lon[idxlat,iimax] < lonmax_transect0) : iimax=iimax+1
   plt.plot (lon[idxlat,iimin:iimax],lat[idxlat,iimin:iimax], color='black', linestyle='-.')
   plt.text(lon[idxlat,iimax], lat[idxlat,iimax],'transect',verticalalignment='bottom',horizontalalignment='left',color='black',bbox=dict(facecolor='white', edgecolor='white', alpha=0.5))
#  plt.show()
   sav_name=exp_name+'_'+test_name+'_'+var_str+'_'+period+'_lon_'+str(lonmin)+'_'+str(lonmax)+'_lat_'+str(latmin)+'_'+str(latmax)+ext2+'.png'
   plt.savefig(sav_name)
   plt.close()
   return()


#plot_transect(ii1, 0, idxlat0, exp_name1, ds1, var1_str, lonmin_transect0, lonmax_transect0, depthmin_transect0, depthmax_transect0); ii1=ii1+1
#ii=ii1
#agrif=0
#idxlat=idxlat0
#exp_name=exp_name1
#ds=ds1
#var_str=var1_str
#lonmin=lonmin_transect0
#lonmax=lonmax_transect0
#depthmin=depthmin_transect0
#depthmax=depthmax_transect0

def plot_transect(ii, agrif, idxlat, exp_name, ds, var_str, lonmin, lonmax, depthmin, depthmax):
   if agrif == 0 : ext1=''; ext2=''
   elif agrif == 1 : ext1='CHILD'; ext2='_CHILD'

   print ('\n   ',var_str,' plot transect '+ext1+'  (lon : '+str(lonmin)+' '+str(lonmax)+'    depth : '+str(depthmin)+' '+str(depthmax)+')')
   var, cm, cbartitle, vmin, vmax = var_choice2(ds, var_str, idxlat)
#  mmvar="\\Large (min:%.1e  max:%.1e)" %(var.min(),var.max())
   if var.max() < 0.1 : 
      mmvar="(min:%.1e  max:%.1e)" %(var.min(),var.max())
   else :
      mmvar="(min:%.2f  max:%.2f)" %(var.min(),var.max())
   z_rho = ds.z_rho[0].values
   z_rho = z_rho[:,idxlat,:]
   lon = ds.lon_rho[idxlat, :].values
   x = np.empty(z_rho.shape)
   for i in range(x.shape[0]):
       x[i,:] = lon

   plt.figure(ii, figsize=(14,8))
   plt.suptitle(exp_name+' '+ext1+'  '+period_title)
   plt.text(lonmin+0.2,depthmin+10,mmvar,verticalalignment='bottom',horizontalalignment='left',bbox=dict(facecolor='white', edgecolor='white',alpha=0.5))
   plt.text(lonmax-0.2,depthmin+10,local_time4,verticalalignment='bottom',horizontalalignment='right',color='black',bbox=dict(facecolor='white', edgecolor='white', alpha=0.5))
#  plt.text(lonmax-0.2,latmin+0.2,'\\large \\textbf{\\it{'+local_time4+'}}',verticalalignment='bottom',horizontalalignment='right',color='black',bbox=dict(facecolor='white', edgecolor='white', alpha=0.5))
   plt.subplot(1,1,1)
   ax = plt.gca()
   pcm = ax.pcolormesh(x, z_rho, var, cmap=cm, vmin=vmin, vmax=vmax)
   if var_str=='DCHL' or var_str=='NCHL' or var_str=='CHL' or var_str=='FER':
       pcm = ax.pcolormesh(x, z_rho, var, cmap=cm, norm=mpl.colors.LogNorm(vmin=vmin, vmax=vmax))
   plt.colorbar(pcm, label=cbartitle)
   plt.xlim(lonmin, lonmax);plt.ylim(depthmin,depthmax)
   plt.xlabel('Longitude (°)'); plt.ylabel('Depth (m)')
#  plt.show()
   sav_name=exp_name+'_'+var_str+'_'+period+'_lon_'+str(lonmin)+'_'+str(lonmax)+'_depth_'+str(depthmin)+'_'+str(depthmax)+ext2+'.png'
   plt.savefig(sav_name)
   plt.close()
   return()


#===============================================================================
#   Execute
#===============================================================================

# pour plotter la grille zoom dans la grille mere
file_zoom='/ccc/work/cont005/gen1140/chabertp/CONFIGS/CAN11_NEW/chab_agrif_idealwind/run/can11_grd.nc.1'
ds_zoom=xarray.open_dataset(file_zoom)

lon_zoom=[ds_zoom.lon_rho.values[0,0], ds_zoom.lon_rho.values[-1,0], ds_zoom.lon_rho.values[-1,-1], ds_zoom.lon_rho.values[0,-1], ds_zoom.lon_rho.values[0,0]]
lat_zoom=[ds_zoom.lat_rho.values[0,0], ds_zoom.lat_rho.values[-1,0], ds_zoom.lat_rho.values[-1,-1], ds_zoom.lat_rho.values[0,-1], ds_zoom.lat_rho.values[0,0]]

ii1=1

#-------------------------------------------------------------------------------
for exp1 in exp_list :
#-------------------------------------------------------------------------------
### exp1
   root_path1=exp1['root_path']
   exp_name1=exp1['exp_name']
   test_name1=exp1['test_name']

   exp_path1=root_path1+'/'+exp_name1+'/'+period

   if test_name1 != '' :
      exp_path1=exp_path1+'_'+test_name1

   file1=exp_path1+'/'+exp_name1+'_'+file_type+'_'+freq+'_'+period+'_mean.nc'

#  ds1=xarray.open_dataset(file1)
# ouverture via xcroco pour pouvoir passer de la grille u ou v a la grille rho
# necessite d'interpoller les grilles au préalable avec xgcm appele par xcroco.croco_dataset
#  globals()['exp1']=xcroco.croco_dataset(file1)
#  ds1 =  xarray.concat([globals()['exp1']],'time')
#  ds1=xcroco.croco_dataset(file1)
   ds1=xarray.open_dataset(file1)

#  if 'c11s2' in exp_name1 : 
   file1z=file1+'.1'
   ds1z=xarray.open_dataset(file1z)

### transect :
#  climato_v1 = '/ccc/work/cont005/gen1140/chabertp/CONFIGS/CAN11_NEW/RESTARTS_pisces/creation_rst/can11_avg.mean.2000-2006.can11bio1.nc'
#  ds_climv1 = xcroco.croco_dataset(climato_v1)
#  z_rho = ds_climv1.z_rho[0].values
#  z_rho = z_rho[:,idxlat,:]

   print ('\n\n',80*'=','\n   ',exp_name1,' \n',80*'=')
   print (exp_path1)
   print (file1)

   #-------------------------------------------------------------------------------
   
#  if 'cp' in exp_name1 :
   var_list_map=var_list_map_phy + var_list_map_bio
   var_list_transect=var_list_transect_phy + var_list_transect_bio
#  else : 
#     var_list_map=var_list_map_phy
#     var_list_transect=var_list_transect_phy
   
   for var1_str in var_list_map :
      if F_map0 : plot_map(ii1, 0, idxlat0,  exp_name1, test_name1, ds1, var1_str, lonmin_grid0, lonmax_grid0, latmin_grid0, latmax_grid0, lon_interv0, lat_interv0, lon_zoom, lat_zoom); ii1=ii1+1
      if F_map1 : plot_map(ii1, 0, idxlat0,  exp_name1, test_name1, ds1, var1_str, lonmin_grid1, lonmax_grid1, latmin_grid1, latmax_grid1, lon_interv1, lat_interv1, lon_zoom, lat_zoom); ii1=ii1+1
      if F_map2 :
         plot_map(ii1, 0, idxlat0,  exp_name1, test_name1, ds1, var1_str, lonmin_grid2, lonmax_grid2, latmin_grid2, latmax_grid2, lon_interv2, lat_interv2, lon_zoom, lat_zoom); ii1=ii1+1
#        if 'c11s2' in exp_name1 : plot_map(ii1, 1, idxlat1,  exp_name1, ds1z, var1_str, lonmin_grid2, lonmax_grid2, latmin_grid2, latmax_grid2, lon_interv2, lat_interv2, lon_zoom, lat_zoom); ii1=ii1+1
         plot_map(ii1, 1, idxlat1,  exp_name1, test_name1, ds1z, var1_str, lonmin_grid2, lonmax_grid2, latmin_grid2, latmax_grid2, lon_interv2, lat_interv2, lon_zoom, lat_zoom); ii1=ii1+1


   #-------------------------------------------------------------------------------
   for var1_str in var_list_transect :
      if F_transect1 :
         plot_transect(ii1, 0, idxlat0, exp_name1, ds1, var1_str, lonmin_transect0, lonmax_transect0, depthmin_transect0, depthmax_transect0); ii1=ii1+1
         if 'c11s2' in exp_name1 : plot_transect(ii1, 1, idxlat1, exp_name1, ds1z, var1_str, lonmin_transect0, lonmax_transect0, depthmin_transect0, depthmax_transect0); ii1=ii1+1

#  ds1.close()




plt.show()







