# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
from netCDF4 import Dataset
import math
import warnings
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as t
from mpl_toolkits.basemap import Basemap,shiftgrid,addcyclic
from cdo import Cdo,CDOException,CdoTempfileStore
cdo=Cdo()

mpl.rc("text", usetex=False)
mpl.rc('axes',titlesize=20,labelsize=17,linewidth=1.2)
mpl.rc('xtick',labelsize=15)
mpl.rc('ytick',labelsize=15)
mpl.rcParams['xtick.major.size']=5.5
mpl.rcParams['xtick.minor.size']=3.5
mpl.rcParams['ytick.major.size']=5.5
mpl.rcParams['ytick.minor.size']=3.5
mpl.rcParams['legend.fontsize']=15
warnings.filterwarnings("ignore")


def graph_Antarctica(path_array,legend_array,name_files,var,year,mesi,\
                     title,ylabel,data172,temp,cost,position=(0.5,-0.16)):
    data_mean=np.zeros((len(path_array),12))

    for m in range(0,len(path_array)):
        if year[m]<10:
            string="000"+str(year[m])
        elif year[m]>=10 and year[m]<100:
            string="00"+str(year[m])
        elif year[m]>=100 and year[m]<1000:
            string="0"+str(year[m])
        else:
            string=str(year[m])

        
        if temp==True:
            data=[np.reshape([float(i)*cost for i in  " ".join(cdo.output(input="-addc,-273.15 -selmonth,"\
                    +str(j)+" -selname,"+var+" "+path_array[m]+"../"+name_files[m]+"_PLA."+string+".nc"))\
                              .split()],[nlat,nlon]) for j in range(1,13)]
        else:
            data=[np.reshape([float(i)*cost for i in  " ".join(cdo.output(input="-selmonth,"+str(j)\
                                            +" -selname,"+var+" "+path_array[m]+"../"+name_files[m]+"_PLA."\
                                            +string+".nc")).split()],[nlat,nlon]) for j in range(1,13)]
        lats=Dataset(path_array[m]+"../"+name_files[m]+"_PLA."+string+".nc","r").variables["lat"][::-1]
        data2=np.zeros((len(data),nlon*6*mul))
        #print(np.shape(data))
        
        for k in range(0,len(data)):
            count=0
            count_mean=0
            for i in range(0,len(data[k])):
                for j in range(0,len(data[k][i])):
                    if i>25*mul:
                        if data172[i][j]>=0.5:
                            #print(i,j)
                            #print(count)
                            data2[k][count]=data[k][i][j]*np.cos(np.pi*lats[i]/180)
                            count_mean+=np.cos(np.pi*lats[i]/180)
                            count+=1
        data_mean[m]=[np.sum(i)/count_mean for i in data2]
        #print(count)
    graph(mesi,data_mean,title+" Annual Antarctica Cycle",legend_array,"upper center","Time [month]",\
          ylabel,True,False,position=position)
    return data_mean

def graph_60N(path_array,legend_array,name_files,var,year,mesi,title,ylabel,data172,temp,cost):
    data_mean=np.zeros((len(path_array),12))

    for m in range(0,len(path_array)):
        if year[m]<10:
            string="000"+str(year[m])
        elif year[m]>=10 and year[m]<100:
            string="00"+str(year[m])
        elif year[m]>=100 and year[m]<1000:
            string="0"+str(year[m])
        else:
            string=str(year[m])

        if temp==True:
            data=[np.reshape([float(i)*cost for i in  " ".join(cdo.output(input="-addc,-273.15 -selmonth,"\
                        +str(j)+" -selname,"+var+" "+path_array[m]+"../"+name_files[m]+"_PLA."+string+".nc"))\
                              .split()],[nlat,nlon]) for j in range(1,13)]
        else:
            data=[np.reshape([float(i)*cost for i in  " ".join(cdo.output(input="-selmonth,"+str(j)\
                    +" -selname,"+var+" "+path_array[m]+"../"+name_files[m]+"_PLA."+string+".nc")).\
                              split()],[nlat,nlon]) for j in range(1,13)]
        lats=Dataset(path_array[m]+"../"+name_files[m]+"_PLA."+string+".nc","r").variables["lat"][::-1]
        data2=np.zeros((len(data),nlon*6*mul))
        #print(np.shape(data),lats)
        
        for k in range(0,len(data)):
            count=0
            count_mean=0
            for i in range(0,len(data[k])):
                for j in range(0,len(data[k][i])):
                    if i<6*mul:
                        if data172[i][j]>=0.5:
                            data2[k][count]=data[k][i][j]*data172[i][j]*np.cos(np.pi*lats[i]/180)
                            count_mean+=data172[i][j]*np.cos(np.pi*lats[i]/180)
                            count+=1
        data_mean[m]=[np.sum(i)/count_mean for i in data2]
        print(count)
    graph(mesi,data_mean,title+" Annual North Cycle",legend_array,"upper center","Time [month]"\
          ,ylabel,True,False)
    return data_mean


    
def read_graph_file(name_file,path,month,title,mesi,column,bar_title,vmin,vmax,cbar_type):
    """name_file,path,month,title,mesi,column,bar_title,vmin,vmax,cbar_type """
    if month==True:
        with open(path+name_file,'r') as f:
            str_data=f.readline()
            f.seek(0)
            data=[[float(num) for num in line.split()] for line in f]
        for i in range(0,int(len(data)*column/tot)):
            data_res=np.reshape(data[i*int(tot/column)+1+i:(i+1)*int(tot/column)+1+i],[nlat,nlon])
            Title=title+" "+mesi[i]
            graphycs_v(data_res[::-1],Title,'cyl',cbar_type,False,bar_title,vmin,vmax)
        return data,str_data
    else: 
        
        with open(path+name_file,'r') as f:
            str_data=f.readline()
            data=[[float(num) for num in line.split()] for line in f]
        data_res=np.reshape(data,[nlat,nlon])
        graphycs_v(data_res[::-1],title,'cyl',cbar_type,False,bar_title,vmin,vmax)
        return data_res,str_data
    
def graphycs_v(data_array,title,proj,bar,savefig,bar_title,vmn,vmx):
    
    fig = plt.figure(figsize=(8,8))
    m = Basemap(projection=proj, llcrnrlat=-90, urcrnrlat=90,\
                llcrnrlon=0, urcrnrlon=360, resolution='c', lon_0=0)
    m.drawcoastlines()
    m.drawparallels(np.arange(-90,91,30),labels=[1,0,0,0])
    m.drawmeridians(np.arange(-180.,181.,60.),labels=[0,0,0,1])
    m.imshow(data_array,cmap=bar,vmax=vmx,vmin=vmn)
    cbar = plt.colorbar(orientation='vertical', shrink=0.5)
    cbar.set_label(bar_title,rotation=-90,fontsize=14,labelpad=25)
    plt.title(title+"\n",fontsize=17,fontweight="bold")
    if savefig==True :
        fig.savefig("grafici/"+title,bbox_inches='tight')

def graph(x,data_array,title,legend_array,loc_legend,xlabel,ylabel,save,zonal,position=(0.5,-0.16)):
    fig,ax=plt.subplots(figsize=(7,5))

    for i in range(0,len(data_array)):
        ax.plot(x[i],data_array[i],label=legend_array[i])
    legend=ax.legend(loc="best", shadow=True)
    ax.set_title(title+"\n",fontweight="bold")
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.yaxis.set_minor_locator(t.AutoMinorLocator())

    if zonal==True:
        ax.set_xlim(-90,90)
        ax.xaxis.set_minor_locator(t.MultipleLocator(10))
        ax.set_xticks((90,60,30,0,-30,-60,-90))
        ax.set_xticklabels(["90N","60N","30N","0","30S","60S","90S"])

        ax.grid(linestyle='--')   
    elif "Cycle" in title:
        ax.grid(axis='y',linestyle='--')
    else:
        ax.grid(axis='y',linestyle='--')
        #ax.xaxis.set_major_locator(t.MultipleLocator(20))
    plt.show()
    if save==True:
        fig.savefig("grafici/"+title,bbox_inches='tight')
    data=[]
              
def load_file1(cost,file_array,path_array):
    data=[]
              
        
        
    if "ZM" in file_array[0]:
        data=[[cost*i for i in np.reshape(Dataset(path_array[j]+file_array[j],"r").\
                    variables[file_array[j].split("_")[-1].replace(".nc","") ][:],[nlat])]\
              for j in range(0,len(file_array))]
        
    else:
        
        #print(np.shape(Dataset(path_array[0]+file_array[0],"r").variables[file_array[0].split("_")[-1].replace(".nc","") ][:]))
        data=[[cost*i for i in np.reshape(Dataset(path_array[j]+file_array[j],"r").variables[file_array[j]\
            .split("_")[-1].replace(".nc","") ][:],[int(file_array[j].split("_")[-2].replace("Y",""))])]\
              for j in range(0,len(file_array))]
        #print("1")
        
    return data

def load_file2(cost,file_array,path_array,typology,temp,step,start):
                 
    if typology=="global":
        data=[[cost*float(j) for j in np.reshape([cdo.output(input="-timselmean,"+str(step[k])+","\
                                                             +str(start[k])+" -selmonth,"+str(i)\
                                                        +" "+path_array[k]+file_array[k]) for i in\
                                                  range(1,13)],[12])] for k in range(0,len(file_array))]
    
    elif typology=="south":
        if temp==True:
            data0=[[cdo.output(input="-gridboxmean,nlon,16 -timselmean,"+str(step[k])+\
                                                  ","+str(start[k])+" -addc,-273.15 -selmonth,"+str(i)+" "+\
                                                  path_array[k]+file_array[k])[0].split() for i in \
                    range(1,13)]\
                                                   for k in range(0,len(file_array))]
        else:
            data0=[[cdo.output(input="-gridboxmean,nlon,16 -timselmean,"+str(step[k])+\
                                        ","+str(start[k])+" -selmonth,"+str(i)+" "+\
                                            path_array[k]+file_array[k])[0].split() for i in range(1,13)]\
                                            for k in range(0,len(file_array))]

        data=[[cost*float(data0[k][i][1]) for i in range(0,len(data0[k]))] for k in range(0,len(data0))]
    elif typology=="north":
        if temp==True:
            data0=[[cdo.output(input="-gridboxmean,nlon,16 -timselmean,"+str(step[k])+\
                                                  ","+str(start[k])+" -addc,-273.15 -selmonth,"+str(i)+" "+\
                                                  path_array[k]+file_array[k])[0].split() for i \
                    in range(1,13)]\
                                                   for k in range(0,len(file_array))]
        else:
            data0=[[cdo.output(input="-gridboxmean,nlon,16 -timselmean,"+str(step[k])+\
                                        ","+str(start[k])+" -selmonth,"+str(i)+" "+\
                                            path_array[k]+file_array[k])[0].split() for i in range(1,13)]\
                                            for k in range(0,len(file_array))]

        data=[[cost*float(data0[k][i][0]) for i in range(0,len(data0[k]))] for k in range(0,len(data0))]
    else:
        print("input sbagliato")
        
    return data



def graph_globe(data,lons,lats,proj,save,title,cbar_title,vmn,vmx,step_bar,cmap=plt.cm.jet_r):
    fig = plt.figure(figsize=(10,10))
    m = Basemap(projection=proj, llcrnrlat=-90, urcrnrlat=90,\
            llcrnrlon=0, urcrnrlon=360, resolution='c', lon_0=0)
    m.drawcoastlines()
    if proj=="cyl":
        m.drawparallels(np.arange(-90,91,30),labels=[1,0,0,0])
        m.drawmeridians(np.arange(-180.,181.,60.),labels=[0,0,0,1])
        m.imshow(data[::-1],cmap=cmap,vmin=vmn,vmax=vmx)
        cbar = plt.colorbar(orientation='vertical', shrink=0.5,ticks=np.linspace(vmn,vmx,step_bar))
    else:
        m.drawmapboundary()
        m.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
        m.drawmeridians(np.arange(m.lonmin,m.lonmax+30,60),labels=[0,0,0,1])
        var_cyclic, lons_cyclic = addcyclic(data,lons)
        var_cyclic, lons_cyclic = shiftgrid(180.,var_cyclic,lons_cyclic,start=False)
        lon2d, lat2d = np.meshgrid(lons_cyclic, lats)
        x,y = m(lon2d, lat2d)
        
        cs = m.contourf(x,y,var_cyclic, cmap=cmap,levels=t.MaxNLocator(nbins=step_bar)\
                        .tick_values(vmn,vmx),extend="both")
        cbar = plt.colorbar(cs,orientation='vertical', shrink=0.5,ticks=t.MaxNLocator\
                            (nbins=step_bar).tick_values(vmn,vmx))

       
    cbar.set_label(cbar_title,rotation=-90,labelpad=25)
    plt.title(title+"\n",fontweight="bold")
    if save==True:
        fig.savefig("grafici/"+title,bbox_inches='tight')

def print_value(data,starts,ends):
   
    for i in range(0,len(data)):
          print("Mean "+str(starts[i])+"-"+str(ends[i])+": "+str(np.mean(data[i][starts[i]:ends[i]]))\
              +" dev.std: "+str(np.std(data[i][starts[i]:ends[i]])))

            
def Net_Flux_Sup(nome_file,type_file,path_arrays,lenght,load_file,typology,temp,step,start):
    var=["rls","rss","hfss","hfls","prsn"]
    path_array=[path_arrays for i in range(0,len(var))]
    if load_file==1:
        data=load_file1(1,[nome_file+type_file+i+".nc" for i in var],path_array)
    else:
        data=load_file2(1,[nome_file+type_file+i+".nc" for i in var],path_array,typology,temp,\
                        [step for i in range(0,len(var))],[start for i in range(0,len(var))] )
       
    data0=np.reshape(data[0],[lenght])+np.reshape(data[1],[lenght])+np.reshape(data[2],[lenght])+\
    np.reshape(data[3],[lenght])-1000*334000*np.reshape(data[4],[lenght])
    return np.reshape(data0,[lenght])

def all_graph(var,title_var,ylabel,name_files,path_array,legend_array,starts,ends,step,lats,lons,mesi\
              ,cost,temp,string="ab",position=(0.5,-0.16)):
    if "a" in string:
        #Global Annual Cycle
        in_global=[name_files[i]+"_YM_FM_"+str(ends[i])+"Y_"+var+".nc" for i in range(0,len(name_files))]
        data_global=load_file1(cost,in_global,path_array)
        graph(time,data_global,title_var+" Global Annual Mean",legend_array,"upper center","Time [year]"\
              ,ylabel,True,False,position)
        print_value(data_global,starts,ends)
    else: 
        data_global=0
    if "b" in string:
        #Zonal
        in_zonal=[name_files[i]+"_YM_"+str(step[i])+"YM_ZM_"+str(ends[i])+"Y_"+var+".nc" for i in \
                  range(0,len(name_files))]
        data_zonal=load_file1(cost,in_zonal,path_array)
        graph(lats,data_zonal,title_var+" Zonal Mean",legend_array,"upper center","Latitude [°]",ylabel,\
              True,True,position)
    else:
        data_zonal=0
    if "c" in string:
        #1 year cycle
        #Global
        in_global_cycle=[name_files[i]+"_FM_"+str(ends[i])+"Y_"+var+".nc" for i in range(0,len(name_files))]
        data_global_cycle=load_file2(cost,in_global_cycle,path_array,"global",temp,step,starts)
        graph(mesi,data_global_cycle,title_var+" Global Annual Cycle",legend_array,"upper center","Time [month]",\
              ylabel,True,False,position)
    else:
        data_global_cycle=0
    if "n" in string:
        #North
        in_north_cycle=[i+"_all_"+var+".nc" for i in name_files]
        data_north_cycle=load_file2(cost,in_north_cycle,path_array,"north",temp,step,starts)
        graph(mesi,data_north_cycle,title_var+" North Annual Cycle",legend_array,"upper center","Time [month]",\
              ylabel,True,False,position)
    else:
        data_north_cycle=0
    if "s" in string:
        #South
        in_south_cycle=[i+"_all_"+var+".nc" for i in name_files]
        data_south_cycle=load_file2(cost,in_south_cycle,path_array,"south",temp,step,starts)
        graph(mesi,data_south_cycle,title_var+" South Annual Cycle",legend_array,"upper center","Time [month]",\
          ylabel,True,False,position)
    else:
        data_south_cycle=0
    
    return data_global,data_zonal,data_global_cycle,data_north_cycle,data_south_cycle



def all_graph_res(var,title_var,ylabel,name_files,path_array,legend_array,starts,ends,step,lats,lons,mesi,cost,\
                  temp):
    #Global Annual Cycle
    in_global=[name_files[i]+"_YM_FM_"+str(ends[i])+"Y_"+var+".nc" for i in range(0,len(name_files))]
    data_global=load_file1(cost,in_global,path_array)
    graph(time,data_global,title_var+" Global Annual Mean",legend_array,"upper center","Time [year]",ylabel,\
          True,False)
    print_value(data_global,starts,ends)               
    #Zonal
    in_zonal=[name_files[i]+"_YM_"+str(step[i])+"YM_ZM_"+str(ends[i])+"Y_"+var+".nc" for i in range(0,len(name_files))]
    data_zonal=load_file1(cost,in_zonal,path_array)
    graph(lats,data_zonal,title_var+" Zonal Mean",legend_array,"upper left","Latitude [°]",ylabel,True,True)
 
    return data_global,data_zonal

def all_graph_sum(var1,var2,title_var,ylabel,name_files,path_array,legend_array,starts,\
                  ends,step,lats,lons,mesi,cost,temp,string="ab",position=(0.5,-0.16)):
    if "a" in string:
        #Global Annual Cycle
        in_global1=[name_files[i]+"_YM_FM_"+str(ends[i])+"Y_"+var1+".nc" for i in range(0,len(name_files))]
        in_global2=[name_files[i]+"_YM_FM_"+str(ends[i])+"Y_"+var2+".nc" for i in range(0,len(name_files))]
        data_global=[np.add(load_file1(cost,in_global1,path_array)[i],load_file1(cost,in_global2,path_array)\
                            [i]) for i in range(0,len(name_files))]
   
        graph(time,data_global,title_var+" Global Annual Mean",legend_array,"upper center","Time [year]",\
          ylabel,True,False,position)
        print_value(data_global,starts,ends) 
    else:
        data_global=0
    if "b" in string:
        
        #Zonal
        in_zonal1=[name_files[i]+"_YM_"+str(step[i])+"YM_ZM_"+str(ends[i])+"Y_"+var1+".nc" for i in range(0,len(name_files))]
        in_zonal2=[name_files[i]+"_YM_"+str(step[i])+"YM_ZM_"+str(ends[i])+"Y_"+var2+".nc" for i in range(0,len(name_files))]
        data_zonal=[np.add(load_file1(cost,in_zonal1,path_array)[i],load_file1(cost,in_zonal2,path_array)[i])\
                    for i in range(0,len(name_files))]
        #print(np.shape(data_zonal))
        graph(lats,data_zonal,title_var+" Zonal Mean",legend_array,"upper center","Latitude [°]",ylabel,\
              True,True,position)
    else:
        data_zonal=0
    if "c" in string:
        
        #1 year cycle
        #Global
        in_global_cycle1=[name_files[i]+"_FM_"+str(ends[i])+"Y_"+var1+".nc" for i in range(0,len(name_files))]
        in_global_cycle2=[name_files[i]+"_FM_"+str(ends[i])+"Y_"+var2+".nc" for i in range(0,len(name_files))]
        data_global_cycle=[np.add(load_file2(cost,in_global_cycle1,path_array,"global",temp,step,starts)[i],\
                                  load_file2(cost,in_global_cycle2,path_array,"global",temp,step,starts)[i])\
                       for i in range(0,len(name_files))]
        graph(mesi,data_global_cycle,title_var+" Global Annual Cycle",legend_array,"upper center","Time [month]",\
              ylabel,True,False,position)
    else:
        data_global_cycle=0
    if "n" in string:
        #North
        in_north_cycle1=[i+"_all_"+var1+".nc" for i in name_files]
        in_north_cycle2=[i+"_all_"+var2+".nc" for i in name_files]
        data_north_cycle=[np.add(load_file2(cost,in_north_cycle1,path_array,"north",\
                                        temp,step,starts)[i],load_file2(cost,in_north_cycle2,path_array,\
                                                                      "north",temp,step,starts)[i]) \
                          for i in range(0,len(name_files))]
        graph(mesi,data_north_cycle,title_var+" North Annual Cycle",legend_array,\
              "upper center","Time [month]",ylabel,True,False,position)
    else:
        data_north_cycle=0
    if "s" in string:
        #South
        in_south_cycle1=[i+"_all_"+var1+".nc" for i in name_files]
        in_south_cycle2=[i+"_all_"+var2+".nc" for i in name_files]
        data_south_cycle=[np.add(load_file2(cost,in_south_cycle1,path_array,"south",\
                                        temp,step,starts)[i],load_file2(cost,in_south_cycle2,path_array,\
                                                                      "south",temp,step,starts)[i]) \
                      for i in range(0,len(name_files))]
        graph(mesi,data_south_cycle,title_var+" South Annual Cycle",legend_array,\
              "upper center","Time [month]",ylabel,True,False,position)
    else:
        data_south_cycle=0
    
    return data_global,data_zonal,data_global_cycle,data_north_cycle,data_south_cycle

def graph_level(var,title_var,ylabel,name_files,path_array,ends,steps,z_press,lat,cost,var_min,var_max):
    data_globe=[[cost*i for i in Dataset(path_array[j]+name_files[j]+"_YM_"+str(steps[j])+"YM_ZM_"+str(ends[j])+"Y_"+var+".nc").\
                 variables[var][:]]for j in range(0,len(name_files))]


    for i in range(0,len(name_files)):
        for j in range(i+1,len(name_files)):
            fig,ax=plt.subplots(figsize=(8,6))
            x,y=np.meshgrid(lat,z_press)
            cs=ax.contourf(x,y,np.reshape(data_globe[i],(13,nlat))-np.reshape(data_globe[j],(13,nlat)),\
                           cmap=plt.cm.jet,levels=np.linspace(var_min,var_max,21),extend="both")
            #ax.xaxis.set_major_locator(plt.MultipleLocator(10))
            ax.yaxis.set_ticks([1000,850,700,500,400,300,200,100,30])
            ax.set_ylim(1000,30)
            ax.set_xlabel("Latitude [°]")
            ax.set_ylabel(" Pressure [hPa]")
            ax.set_xlim(-86,86)
            ax.set_xticks((80,60,40,20,0,-20,-40,-60,-80))
            ax.set_xticklabels(["80N","60N","40N","20N","0","20S","40S","60S","80S"])
            ax.grid()
            cbar = plt.colorbar(cs,orientation='vertical', shrink=0.9,ticks=np.linspace(var_min,var_max,15))
            cbar.set_label(ylabel,rotation=-90,labelpad=25)
            #plt.gca().invert_yaxis()
            plt.title(title_var+" ("+name_files[i]+"-"+name_files[j]+") \n",fontweight="bold")
            plt.savefig("grafici/"+title_var+" ("+name_files[i]+"-"+name_files[j]+")")




def all_graph_globe(var,title_var,ylabel,name_files,path_array,lon,lat,cost,proj_type,end,step,color=plt.cm.jet):
    data_globe=[[cost*i for i in Dataset(path_array[j]+name_files[j]+"_YM_"+str(step[j])+"YM_"+\
                                         str(end[j])+"Y_"+var+".nc").variables[var][0]]for j in \
                range(0,len(name_files))]
    #print(math.factorial(len(name_files))/(math.factorial(len(name_files)-2)*math.factorial(2)))
    min_max=np.zeros((int(math.factorial(len(name_files))/(math.factorial(len(name_files)-2)*\
                                                           math.factorial(2))),2))
    #print(np.shape(data_globe))
    #print(np.reshape(data_globe[0],[nlat,nlon])[0])
    count=0
    for i in range(0,len(name_files)):
        for j in range(i+1,len(name_files)):
            min_max[count]=[np.min(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon])),\
                            np.max(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon]))]
            count+=1
    #print(min_max)
    max_lim=int(np.max(min_max)+1)
    min_lim=int(np.min(min_max)-1)
    lim=np.max([np.abs(min_lim),np.abs(max_lim)])
    for i in range(0,len(name_files)):
        for j in range(i+1,len(name_files)):
            max_lim=int(np.max(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon]))+1)
            min_lim=int(np.min(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon]))-1)
            lim=np.max([np.abs(min_lim),np.abs(max_lim)])
            graph_globe(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon]),lons[i],\
                        lats[i],proj_type,True,title_var+" ("+name_files[i]+"-"+name_files[j]+")",ylabel,\
                        -lim,lim,15,cmap=color)
            #print(np.max(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon])),np.min(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon])))
    return data_globe

def all_graph_globe2(data_globe,title_var,ylabel,lon,lat,proj_type):
    min_max=np.zeros((int(math.factorial(len(name_files))/(math.factorial(len(name_files)-2)\
                                                           *math.factorial(2))),2))
    count=0
    for i in range(0,len(data_globe)):
        for j in range(i+1,len(data_globe)):
            min_max[count]=[np.min(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon])),\
                            np.max(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon]))]
            count+=1
    #print(min_max)
    max_lim=int(np.max(min_max)+1)
    min_lim=int(np.min(min_max)-1)
    lim=np.max([np.abs(min_lim),np.abs(max_lim)])
    for i in range(0,len(data_globe)):
        for j in range(i+1,len(data_globe)):
            max_lim=int(np.max(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon]))+1)
            min_lim=int(np.min(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon]))-1)
            lim=np.max([np.abs(min_lim),np.abs(max_lim)])
            graph_globe(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon]),lons[i],lats[i]\
                        ,proj_type,True,title_var+" ("+name_files[i]+"-"+name_files[j]+")",ylabel,-lim,\
                        lim,15)
            #print(np.max(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon])),np.min(np.reshape(data_globe[i],[nlat,nlon])-np.reshape(data_globe[j],[nlat,nlon])))
# -



StarcoderdataJupyterScriptsDedupFiltered