#Contains the functions needed to process both chords and regularized beards
# proc_chords is used for chords
#proc_beard_regularize for generating beards
#proc_pdf saves pdfs of a variable below cloud base
#Both have a large overlap, but I split them in two to keep the one script from getting to confusing. 

import numpy as np
import math
from netCDF4 import Dataset
import os
import time as ttiimmee
from scipy.interpolate import interp1d
from scipy.interpolate import interp2d
#from scipy.interpolate import griddata
#from mpl_toolkits.axes_grid1 import make_axes_locatable
import pickle
import sys
#sys.path.insert(0, "/home/pgriewank/code/2019-chords-plumes/")


#from unionfind import UnionFind
from cusize_functions import *
#import matplotlib.pyplot as plt
import pandas as pd
import gc
import glob
import xarray as xr

#turned into a function
#removed the possibility to loop over multiple dates, if you want to do that call the function repeatedly 
#Full list of variables to analyze is unclear, I will try to include everything available, but this might break the memory bank
#want to keep the automatic x and y calculation
#Scaling shouldn't be needed, as all chord properties should be indepenent of wind direction (right?)
#Similarly, no basedefinition is needed, all values are relative to cloud base

#Should be able to work for any variable in the column output, or for any 3D variable as long as it is named the same as the file. 
#Changing 3D output
#Default is now to always go over x and y directions

#TODO
#plot_flag disabled for the mean time

def proc_chords(          date_str='20160611',
                          directory_input='/data/testbed/lasso/sims/',
                          directory_output='/data/testbed/lasso/chords/',
                          data_dim_flag=1,
                          base_percentile = 25,
                          special_name='',
                          chord_times = 0,
                          N_it_min=0,
                          N_it_max=1e9):

    # plot_curtains_flag: 0 nothing, 1 plots pre regularization plots, currently dissabled
    # data_dim_flag: 1 = column, 3 = 3D snapshot
    # chord_times: 0 use Neils values, use values that fit model output exactly with not gap possible
    # directory_input         = '/data/testbed/lasso/sims/' #+date
    # N_it_max = maximum number of iterables, 3D timesteps or column files. Used for testing things quickly
    # N_it_min = start number of iterables, 3D timesteps or column files. Only reall makes sense for 3D to avoid some weird initial fields. 
    
    time_begin = ttiimmee.time()
    

    dz = 25.0 #39.0625 #should be overwritten after the profile data is loaded
    dx = 25.0

    date = date_str

    n_percentiles = 7 #Number of percentiles
    percentiles = np.array([5,10,35,50,65,90,95])

    
    #1D clustering parameters in seconds, taken to agree with Lareau
    if chord_times == 0:
        t_gap = 20
        t_min = 30
        t_max = 1200*100 #Made a 100 times longer
        cell_min = 3 #Minimal number of cells needed per chord

    # #1D clustering parameters, 
    #set super strict, but goes on for a loooong time as well
    if chord_times == 1:
        t_gap = 0. #should be pretty strict, no gaps allowed!
        t_min = 0.0
        t_max = 1e9
        cell_min = 3 #Minimal number of cells needed per chord
        
   


    ql_min = 1e-5 #value used to determine existence of cloud
    z_min  = 10 #Index of minimum  z_vlvl of the cbl



 
    
    print('looking into date: ',date)
    if data_dim_flag==1:
        filename_column = []
        #uses glob to get all files which contain column.
        column_files =     glob.glob(directory_input+date+'/*column*.nc')
         
        for c_file in column_files:
            filename_column.append(c_file)
            print('filename column included:',c_file)
    if data_dim_flag==3:
        filename_w   = directory_input+date+'/w.nc'
        filename_l   = directory_input+date+'/ql.nc'
        filename_qt  = directory_input+date+'/qt.nc'
        filename_thl = directory_input+date+'/thl.nc'
        file_w       = Dataset(filename_w,read='r')
        file_ql      = Dataset(filename_l,read='r')
        file_thl     = Dataset(filename_thl,read='r')
        file_qt      = Dataset(filename_qt,read='r')
        [nz, nx, ny] = get_zxy_dimension(filename_l,'ql')
        
        





    filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0]
    
    #if date=='bomex':
    #    filename_prof=directory_input+date+'/bomex.default.0000000.nc'
        

    file_prof  =  Dataset(filename_prof,read='r')


    
    

    n_chords = 0
    #I will try lists first, which I will then convert to arrays in the end before saving in pandas
    chord_timesteps           = []
    chord_length              = []
    chord_duration            = []
    chord_time                = []
    chord_height              = [] #percentile of cloud base
    chord_w                   = []
    chord_w_up                = [] #mean over updrafts
    chord_w_base              = []
    chord_w_star              = []
    chord_thl_star            = []
    chord_qt_star             = []
    chord_thl                 = []
    chord_thl_25              = []
    chord_thl_75              = []
    chord_qt                  = []
    chord_qt_25               = []
    chord_qt_75               = []
    chord_w_flux              = [] #Sum of w below
    #Coming next
    chord_w_per               = np.zeros([0,n_percentiles])
    chord_w_per_up            = np.zeros([0,n_percentiles])
    


    #This now a bit trickier then for the 3D version. Will have to calculate a vector for the lower time resolution of the profile,
    #Then latter apply the nearest value to the full 1d time vec
    #First loading surface variables from default profile

    print('calculating cbl height from profile file')
    T = file_prof['thl'][:,0]
    p = file_prof['p'][:,0]*0.0+99709
    qt = file_prof['qt'][:,0]
    w2 = file_prof['w2'][:,:]
    thl_prof = file_prof['thl'][:,:]
    qt_prof = file_prof['qt'][:,:]
    nz_prof = w2.shape[1]
    z_prof = file_prof['z'][:]
    dz = z_prof[1]-z_prof[0]
    total_surf_buoy_flux = file_prof['bflux'][:,1]
    total_surf_thl_flux = file_prof['thlflux'][:,1]
    total_surf_qt_flux = file_prof['qtflux'][:,1]
    print('dz: ',dz)
    
    
    time_prof = file_prof['time'][:]
    cbl_1d_prof = time_prof*0.0

    #Hack together the Lifting condensation level LCL
    qt_pressure = p*qt
    sat_qv = 6.112*100 * np.exp(17.67 * (T - 273.15) / (T - 29.65 ))
    #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0]
    rel_hum = qt_pressure/sat_qv
    #Dewpoint
    A = 17.27
    B = 237.7
    alpha = ((A * (T- 273.15)) / (B + (T-273.15)))
    alpha = alpha + np.log(rel_hum)
    dewpoint = (B * alpha) / (A - alpha)
    dewpoint = dewpoint + 273.15
    LCL = 125.*(T-dewpoint)
    LCL_index = np.floor(LCL/dz)

    #now calculate the cbl top for each profile time
    for tt in range(len(time_prof)):
        w_var = 1.0
        z=z_min
        while w_var > 0.08:
            z += 1
            w_var = w2[tt,z]
            #w_var = np.var(w_1d[z,:])

        #Mimimum of LCL +100 or variance plus 300 m 
        cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt])
        #To avoid issues later on I set the maximum cbl height to 60 % of the domain height, but spit out a warning if it happens
        if cbl_1d_prof[tt]>0.6*nz_prof:
            print('warning, cbl height heigher than 0.6 domain height, could crash regularization later on, timestep: ',tt)
            cbl_1d_prof[tt] = math.floor(nz*0.6)
    print('resulting indexes of cbl over time: ',cbl_1d_prof)
    print('calculated LCL: ',LCL_index)


    #Now we either iterate over columns or timesteps
    if data_dim_flag==1:
        n_iter =len(filename_column)
    if data_dim_flag==3:
        n_iter =len(time_prof)





    #for col in filename_column:
    n_iter = min(n_iter,N_it_max)
    for it in range(N_it_min,n_iter):
        print('n_chords: ',n_chords)
        

        time1 = ttiimmee.time()
        if data_dim_flag ==1:
            print('loading column: ',filename_column[it])
            file_col = Dataset(filename_column[it],read='r')

            w_2d = file_col.variables['w'][:]
            w_2d = w_2d.transpose()
            ql_2d = file_col.variables['ql'][:]
            ql_2d = ql_2d.transpose()
            t_1d = file_col.variables['time'][:]
            print('t_1d',t_1d)
            thl_2d = file_col.variables['thl'][:]
            thl_2d = thl_2d.transpose()
            qt_2d  = file_col.variables['qt'][:]
            qt_2d  = qt_2d.transpose()
            u_2d  = file_col.variables['u'][:]
            u_2d  = u_2d.transpose()
            v_2d  = file_col.variables['v'][:]
            v_2d  = v_2d.transpose()
           
            #lets try saving memory by closing files
            #file_col.close()
            
            #The needed cbl height
            cbl_1d = t_1d*0
            #The needed surface_bouyancy_flux
            bflux_s_1d = t_1d*0
            qtflux_s_1d = t_1d*0
            thlflux_s_1d = t_1d*0


            #Now we go through profile time snapshots and allocate the closest full time values to the profile values
            dt_2 = (time_prof[1]-time_prof[0])/2
            for tt in range(len(time_prof)):
                cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt]
                bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_buoy_flux[tt]
                qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2]  = total_surf_qt_flux[tt]
                thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt]
                
                
                
            #to get anomalies of thl and qt we subtract the closet mean profile
            for tt in range(len(time_prof)):
                
                #globals().update(locals())                
                tmp_matrix =  thl_2d[:,abs(t_1d-time_prof[tt])<dt_2]
                tmp_vector =  thl_prof[tt,:]
                #because the vectors don't perfectly align
                thl_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose()

                tmp_matrix =  qt_2d[:,abs(t_1d-time_prof[tt])<dt_2]
                tmp_vector =  qt_prof[tt,:]
                #because the vectors don't perfectly align
                qt_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose()

                # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:]
                
                


        if data_dim_flag ==3:


            if sum(file_prof['ql'][it,:])>0.0:

                print('loading timestep: ',it)

                ql_3d   = grab_3d_field(file_ql  ,it,'ql')
                w_3d    = grab_3d_field(file_w   ,it,'w')
                qt_3d   = grab_3d_field(file_qt  ,it,'qt')
                thl_3d  = grab_3d_field(file_thl  ,it,'thl')

                #Here we have to do all the fuckery to turn the 3D fields into 2d slices with an imaginary time vector
                w_2d   = np.array(w_3d.reshape((nz,nx*ny)))
                ql_2d  = np.array(ql_3d.reshape((nz,nx*ny)))
                qt_2d  = np.array(qt_3d.reshape((nz,nx*ny)))
                thl_2d = np.array(thl_3d.reshape((nz,nx*ny)))
                
                #Now we do the same thing with the transposed field, use to be an either or, now just add it on
                w_3d   = np.transpose( w_3d,  (0, 2, 1))
                ql_3d  = np.transpose(ql_3d,  (0, 2, 1))
                qt_3d  = np.transpose(qt_3d,  (0, 2, 1))
                thl_3d = np.transpose(thl_3d, (0, 2, 1))
                
                w_2d     = np.hstack([w_2d   ,np.array(w_3d.reshape((nz,nx*ny)))])
                ql_2d    = np.hstack([ql_2d  ,np.array(ql_3d.reshape((nz,nx*ny)))])
                thl_2d   = np.hstack([thl_2d ,np.array(thl_3d.reshape((nz,nx*ny)))])
                qt_2d    = np.hstack([qt_2d  ,np.array(qt_3d.reshape((nz,nx*ny)))])
                
                
                
                
                #Should now be able to delete 3d fields as they aren't needed anymore, not sure if that helps save any memory though
                del w_3d
                del ql_3d
                del thl_3d
                del qt_3d
                #hopefully this helps
                gc.collect()
                
                #Getting anomalies of thl and qt
                qt_2d[:,:]  = (qt_2d.transpose()  - qt_prof[it,:]).transpose()
                thl_2d[:,:] = (thl_2d.transpose() - thl_prof[it,:]).transpose()
                
                
                #to get the fake time vector we load the wind from the profile data, which devided by the grid spacing gives us a fake time resolution
                #we use the calculated cbl+300 meter or lcl as reference height 
                ref_lvl = cbl_1d_prof[it]

                u_ref = file_prof['u'][it,ref_lvl]
                v_ref = file_prof['v'][it,ref_lvl]

                V_ref = np.sqrt(u_ref**2+v_ref**2) 

                time_resolution = dx/V_ref

                print('time iterative, V_ref, time_resolution',it, str(V_ref)[:4], str(time_resolution)[:4] )
                #fake t vector, 
                t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it
                #dt_1d   = t_1d*0
                #dt_1d[1:] = t_1d[1:]-t_1d[:-1]   
                



            else:
                #If no clouds are present we pass a very short empty fields over to the chord searcher
                print('skipping timestep: ',it,' cause no clouds')
                ql_2d    = np.zeros((nz,1))
                w_2d     = np.zeros((nz,1))
                thl_2d   = np.zeros((nz,1))
                qt_2d    = np.zeros((nz,1))
                t_1d     = np.zeros(1)

            #The needed cbl height, which constant everywhere
            cbl_1d = t_1d*0
            cbl_1d[:] = cbl_1d_prof[it]
            #The needed surface buoyancy flux, which is constant everywhere
            bflux_s_1d = t_1d*0 + total_surf_buoy_flux[it]
            qtflux_s_1d = t_1d*0  + total_surf_qt_flux[it]
            thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it]






        time2 = ttiimmee.time()
        print('loading time:',(time2-time1)*1.0,)



        ### Detecting lowest cloud cell is within 300 m of CBL

        nt = len(cbl_1d)
        cl_base = np.zeros(nt)

        #Detecting all cloudy cells
        #Use to have a different method using nans that doesn:t work anymore somehow. Now I just set it really high where there is no cloud. 
        for t in range(nt):
            if np.max(ql_2d[:,t])>ql_min :
                cl_base[t]=np.argmax(ql_2d[:,t]>1e-6)
            else:
                cl_base[t]=10000000

        cl_base=cl_base.astype(int)

        #Now find c base lower than the max height
        cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0]

        cbl_cl_binary = cl_base*0
        cbl_cl_binary[cbl_cl_idx]=1
        t_cbl_cl=t_1d[cbl_cl_idx]


        ### Clustering 1D

        #Now we simply go through all cloudy timesteps and detect chords
        #If they fulful chord time requirements and have a number of values which fulfills cell_min they are counted as a chord
        #and their properties are calculatted immediately
        t_cloudy_idx = 0
        #n_chords = 0
        chord_idx_list = []

        print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns')


        chord_idx_list = []

        while t_cloudy_idx < len(cbl_cl_idx)-1:# and n_curtain<100*it:      ####################################GO HERE TO SET MAXIMUM CURTAIN
            #print(t_chord_begin)
            t_chord_begin = t_cloudy_idx
            #now connecting all cloudy indexes
            #Originally only cared if they fulfilled cloud criteria, but now I also hard coded that neighboring cells always count
            ##Check if the index of the next cloudy cell is the same as the next index in total, if so the cells are connected
                
            
            while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap):
                t_cloudy_idx += 1 
            t_chord_end = t_cloudy_idx


            #Checking if it fulfils chord criteria regaring time
            #we also added a minimum height of 100 m to screen out fog/dew stuff at the surface
            if t_chord_end-t_chord_begin>cell_min:
                chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]])
                ch_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin]
            else:
                chord_z_min = 0
                ch_duration = 0
            if ch_duration>t_min and ch_duration<t_max and chord_z_min > 4:


                if t_chord_end-t_chord_begin>cell_min-1:
                    n_chords += 1
                    
                    #Getting the chord beginning and end
                    idx_beg_chord = cbl_cl_idx[t_chord_begin]
                    idx_end_chord = cbl_cl_idx[t_chord_end]
                    time_beg_chord = t_1d[idx_beg_chord]
                    time_end_chord = t_1d[idx_end_chord]
                    #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_chord_end]))
                    #list of relevant chord indexes
                    ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end])
                    
                    
                    #getting V_ref if data_dim_flag==1. Is calculated directly from the cloud base speeds
                    if data_dim_flag==1:
                        u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l])
                        v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l])
                        V_ref=np.sqrt(u_ref**2+v_ref**2) 
                     ### Now appending chord properties
                
                    chord_timesteps.append(t_chord_end-t_chord_begin)
                    chord_duration.append(ch_duration)
                    chord_length.append(ch_duration*V_ref)
                    tmp_base_height = np.percentile(cl_base[ch_idx_l],base_percentile)*dz
                    chord_height.append(tmp_base_height) #25th percentile of cloud base
                    
                    surf_b_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord])
                    w_star = (tmp_base_height*surf_b_flux)**(1./3.)
                    surf_qt_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord])
                    qt_star = surf_qt_flux/w_star
                    surf_thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord])
                    thl_star = surf_thl_flux/w_star
                    
                    chord_w_star.append(w_star )
                    chord_thl_star.append(thl_star )
                    chord_qt_star.append(qt_star )
                    
                    
                    chord_w_base.append(np.mean(w_2d[cl_base[ch_idx_l],ch_idx_l]))
                    chord_w.append(np.mean(w_2d[cl_base[ch_idx_l]-1,ch_idx_l]))
                    chord_thl.append(np.mean(thl_2d[cl_base[ch_idx_l]-1,ch_idx_l]))
                    
                    #get a fourth and 3/4 of the cloud base
                    cl_base_25_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)/4.)
                    cl_base_75_idx = cl_base[ch_idx_l]*0 + int(np.percentile(cl_base[ch_idx_l],base_percentile)*3./4.)
                    #print ('cl base idx:',np.percentile(cl_base[ch_idx_l],base_percentile),'clbase/4:',cl_base_25_idx[0],'clbase3/4:',cl_base_75_idx[0])
                    chord_thl_25.append(np.mean(thl_2d[cl_base_25_idx,ch_idx_l]))
                    chord_thl_75.append(np.mean(thl_2d[cl_base_75_idx,ch_idx_l]))
                    chord_qt.append(np.mean(qt_2d[cl_base[ch_idx_l]-1,ch_idx_l]))
                    chord_qt_75.append(np.mean(qt_2d[cl_base_75_idx,ch_idx_l]))
                    chord_qt_25.append(np.mean(qt_2d[cl_base_25_idx,ch_idx_l]))
                    chord_w_flux.append(np.sum(w_2d[cl_base[ch_idx_l]-1,ch_idx_l]))

                    w_base_vec = w_2d[cl_base[ch_idx_l]-1,ch_idx_l]
                    chord_w_up.append(np.mean(w_base_vec[w_base_vec>0.0]))
                    tmp_w_per    = np.percentile(w_base_vec,percentiles)
                    
                    if len(w_base_vec[w_base_vec>0.0])>0:
                        tmp_w_per_up = np.percentile(w_base_vec[w_base_vec>0.0],percentiles)
                    else:
                        tmp_w_per_up = np.zeros(n_percentiles)
                        tmp_w_per_up[:] = 'nan'
                        
                    
                    
                    chord_w_per               = np.vstack([chord_w_per,tmp_w_per])
                    chord_w_per_up            = np.vstack([chord_w_per,tmp_w_per_up])


                    if data_dim_flag==1:
                        chord_time.append(np.mean(t_1d[ch_idx_l]))
                    if data_dim_flag==3:
                        chord_time.append(time_prof[it])


            t_cloudy_idx += 1
        time3 = ttiimmee.time()
        
        print('iterable: ',it)
        print('n_chords: ',n_chords)
        print('number of time points included: ',len(cbl_cl_idx))

       
                
            

       
    
    
    #Does it matter if I turn these from lists to arrays? Fuck it, will do it anyway
    
    chord_timesteps=np.asarray(chord_timesteps)
    chord_duration =np.asarray(chord_duration)
    chord_length   =np.asarray(chord_length)
    chord_height   =np.asarray(chord_height)
    chord_w_base   =np.asarray(chord_w_base)
    chord_w_star   =np.asarray(chord_w_star)
    chord_thl_star =np.asarray(chord_thl_star)
    chord_qt_star  =np.asarray(chord_qt_star)
    chord_w        =np.asarray(chord_w)
    chord_w_up     =np.asarray(chord_w_up)
    chord_w_flux   =np.asarray(chord_w_flux)
    chord_thl      =np.asarray(chord_thl)
    chord_thl_25   =np.asarray(chord_thl_25)
    chord_thl_75   =np.asarray(chord_thl_75)
    chord_qt       =np.asarray(chord_qt)
    chord_qt_25    =np.asarray(chord_qt_25)
    chord_qt_75    =np.asarray(chord_qt_75)
    chord_time     =np.asarray(chord_time)
    
    
    #Saving
    
    print('all chords: ',len(chord_duration))
        
    save_string_base = 'chord_prop_'+date+'_d'+str(data_dim_flag)+'_ct'+str(chord_times)
    if N_it_min>0:
        save_string_base = save_string_base+'_Nmin'+str(N_it_min)
    if N_it_max<1e9:
        save_string_base = save_string_base+'_Nmax'+str(n_iter)
    save_string_base = save_string_base+'_'+special_name+'_N'+str(n_chords)

                   
    filename_chord_panda = directory_output+save_string_base+'.pkl'
    
    
    data_for_panda = list(zip(chord_timesteps,chord_duration,chord_length,chord_height,chord_w_base,chord_w,chord_w_flux,chord_time,chord_w_up,chord_w_per,chord_w_per_up,
                             chord_w_star,chord_thl_star,chord_qt_star,
                             chord_thl,chord_thl_25,chord_thl_75,chord_qt,chord_qt_25,chord_qt_75))
    df = pd.DataFrame(data = data_for_panda, columns=['timesteps','duration','length','height','w_base','w','w_flux','time','w up','w per','w per up',
                                                     'w star','thl star','qt star',
                                                     'thl','thl 25','thl 75','qt','qt 25','qt 75'])
    df.to_pickle(filename_chord_panda)
    time_end = ttiimmee.time()
    print('total run time of proc_chords in minutes: ',(time_end-time_begin)/60.)
    print(':')
    print(':')
    print('chordlength properties saved as panda in ',filename_chord_panda)
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')


    return



#turned into a function
#removed the possibility to loop over multiple dates, if you want to do that call the function repeatedly 
#Should be able to work for any variable in the column output, or for any 3D variable as long as it is named the same as the file. 
#If the input data is a 3D field it will always go over x and y directions
#Two different scale_flags added to rotate the curtain to point upwind. 



#TODO
#plot_flag disabled for the mean time

def proc_beard_regularize(reg_var = 'w',
                          date_str='20160611',
                          directory_input='/data/testbed/lasso/sims/',
                          directory_output = 'data_curtains/',
                          data_dim_flag=1,
                          base_smoothing_flag=2,
                          plot_curtains_flag = 0,
                          base_percentile = 25,
                          special_name='',
                          scale_flag=2,
                          chord_times = 0,
                          anomaly_flag = 0,
                          N_it_max=1e9,
                          N_it_min=0,
                          size_bin_flag=0,
                          N_bins=12,
                          bin_size = 250,
                          curtain_extra = 1.0,
                          chord_max = 1e9,
                          boundary_scaling_flag = 0
                         ):

    # reg_var = variable that will be regularized
    # plot_curtains_flag: 0 nothing, 1 plots pre and post regularization plots of reg_var
    # data_dim_flag: 1 = column, 3 = 3D snapshot
    # time_slice_curtain: 0 only puts out the total sums, 1: adds a seperate output for each time slice, is needed for scale_flag
    # scale_flag: If 0, nothing, if 1, it scales the output by u/sqrt(u^2+v^2) and flips the vector if u>0. Is set to 0 if data_dim_flag==1
    #             1 the ref_lvl used is determined from the mean cloud base height 
    #             2, similar to 1 but now using a profile
    #
    # base_smoothing_flag: 0 use mix of percentile and cloud base as done my Neil, 1: smooth out base after setting it with running average 2: just use percentile defined by base_percentile
    # base_percentile: percentile used to find chordlength bottom
    # chord_times: 0 use Neils values, use values that fit model output exactly with not gap possible
    # anomaly_flag: 0 use reg_var as it is. 1 use reg_var - profile. Works easiest for 3d output, 1d_flag needs to use the closet mean profile
    # directory_input         = '/data/testbed/lasso/sims/' #+date
    # N_it_max = maximum number of iterables, 3D timesteps or column files. Used for testing things quickly
    # size_bin_flag bins the beards by their chord_lenth. Currently using 8 bins of 250 meters length to get started. The lowest bin should be empty, because we only calculate curtains when at least curtain_min is used
    # curtain_extra: Regularized chord length before and after in the curtain, default is 1
    # chord_max: Maximum number of chords. If data_dim_flag=3 it will jump to the y direction when chord_max/2 is reached
    # boundary_scaling_flag: 0 nothing, 1 uses the surface fluxes and cloud base height to calculate either w/w*, thl'/thl*, or qt'/qt*
    time_begin = ttiimmee.time()



    dz = 25.0 #39.0625 #Is recalculated from the profile file later on
    dx = 25.0

    date = date_str

    #1D clustering parameters in seconds, taken to agree with Lareau
    if chord_times == 0:
        t_gap = 20
        t_min = 30
        t_max = 120000
        cell_min = 3 #Minimal number of cells needed per chord
        curtain_min = 10 #Minimal number of cells needed to convert into a curtain

    # #1D clustering parameters, 
    #set super strict 
    if chord_times == 1:
        t_gap = 0.#No gaps allowed!
        t_min = 0
        t_max = 1e9
        cell_min = 10 #Minimal number of cells needed per chord
        curtain_min = 10 #Minimal number of cells needed per curtain


    #value used to determine existence of cloud
    ql_min = 1e-5

    z_min  = 10 #Index of minimum  z_vlvl of the cbl
    #z_min  = 0 #Index of minimum  z_vlvl of the cbl


    #Flag clean up
    if data_dim_flag==1:
        scale_flag=0


    

    
    
    #Creating dictionary to save all properties
    settings_dict = {
    'reg_var': reg_var,
    'date_str':date_str,
    'directory_input':directory_input,
    'data_dim_flag':data_dim_flag,
    'base_smoothing_flag':base_smoothing_flag,
    'plot_curtains_flag' :plot_curtains_flag,
    'base_percentile':base_percentile,
    'special_name':special_name,
    'scale_flag':scale_flag,
    'chord_times':chord_times,
    'anomaly_flag':anomaly_flag,
    'N_it_max':N_it_max,
    'N_it_min':N_it_min,
    'size_bin_flag':size_bin_flag,
    'bin_size':bin_size,
    'N_bins':N_bins,
    'curtain_extra':curtain_extra
    }
    
    #moved to an inner function to avoid issues with global and local variables 
    def func_curtain_reg(input_2d_field):
        #function regularizes to cloud base
        #2019-03-20: added smoother to hopefully avoid impact of harsch jumps
        #2019-03-28: Added simplified version for base_smoothing_flag == 2 which gets rid of 1D pre interpolation 
        #I originally used interp2d, tried griddata but it was a lot slower
        
        #Calculating the regularized t axis but for original resolution
        #It is expected to go a bit beyond -1.5 and 1.5, total width defined by curtain_extra
        #takes the original time vector, subtracts it by mean time, then scales it by 1/(time_end_chord-time_beg_chord)
        t_reg_orig = t_1d[idx_beg_curtain:idx_end_curtain]-(time_beg_chord+time_end_chord)/2.
        t_reg_orig = t_reg_orig/(time_end_chord-time_beg_chord)
    
        #Now we calculate the new regularized grid with the correct vertical but low/original horizontal/time resolution
        #mesh_t_low_z_high_x,mesh_t_low_z_high_z = np.meshgrid(t_reg_orig,z_reg_mid) #seems not to be needed
        var_t_low_z_high = np.zeros([curtain_cells,n_z_reg])
    
    
        #introducing z_idx_base vector
        #Assigning reference cloud base where no cloud present
        z_idx_base=cl_base*1.0+0.0
        z_idx_base[:] = z_idx_base_default
        for i in range(idx_beg_chord,idx_end_chord):
            if i>idx_beg_chord-1 and i<idx_end_chord and cl_base[i]<cbl_1d[i]:
                    z_idx_base[i] = cl_base[i]
                
        
    
        #Here the smoother comes into play:
        #We started with a simple 5 cell running mean, 
        #But now we are making it a function of the chordlength, using a 0.1 running mean
        
        if base_smoothing_flag ==1:
            z_idx_base_smooth = z_idx_base*1.0
            N = int(np.floor(idx_end_chord-idx_beg_chord)*0.1)
            for i in range(idx_beg_chord-N,idx_end_chord+N):
                z_idx_base_smooth[i] = sum(z_idx_base[i-N:i+N])/(2*N)
            z_idx_base[:] = z_idx_base_smooth[:]
            
        if base_smoothing_flag==2:
            #just put the percentile back
    
            z_idx_base[:] = z_idx_base_default
            
            
        
        
            
            
        #default version for variable base height    
        if base_smoothing_flag<2:
            #Now for each of the columns of the original curtain a vertical interpolation is done
            for i in range(idx_beg_curtain,idx_end_curtain):
    
                #assigining column value
    
                var_orig_col = input_2d_field[:,i]
    
    
    
    
    
                #Regularizing the z axes so that cloud base is at 1
                d_z_tmp = 1.0/z_idx_base[i]
                nz = var_orig_col.shape[0]
                z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2
                z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz)
    
                #HAve to add 0  to the z_reg_orig to enable interpolation 
                z_reg_orig = np.hstack([[0],z_reg_orig])
                var_orig_col   = np.hstack([var_orig_col[0],var_orig_col])
    
    
                #1D vertical interpolation to get the right columns and asign them one by one to w_x_low_z_high
                #f = interp1d(z_reg_orig, var_orig_col, kind='next')
                f = interp1d(z_reg_orig, var_orig_col, kind='nearest')
                try:
    
                    var_reg_inter = f(z_reg_mid)
                except:
                    print(z_idx_base[i])
                    print(z_reg_orig)
                    print(z_reg_mid)
    
                var_t_low_z_high[i-idx_beg_curtain,:] = var_reg_inter
    
            #Now that w_x_low_z_high we have to interpolate 2D onto the rull regularized grid
            #print(t_reg_orig.shape,z_reg_mid.shape)
            f = interp2d(t_reg_orig, z_reg_mid, var_t_low_z_high.transpose(), kind='linear')
            var_curtain = f(t_reg_mid,z_reg_mid)
        
        
        #constant base height version
        if base_smoothing_flag==2:
            #Regularizing the z axes so that cloud base is at 1, since z_idx_base is the same everywhere I just use idx_beg_curtain as one. 
            i=idx_beg_curtain
            d_z_tmp = 1.0/z_idx_base[i]
            var_orig_2d = input_2d_field[:,idx_beg_curtain:idx_end_curtain]
    
            nz = var_orig_2d.shape[0]
            z_reg_orig_top = d_z_tmp*nz- d_z_tmp/2
            z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz)
            
            #Have to add 0  to the z_reg_orig to enable interpolation 
            z_reg_orig    = np.hstack([[0],z_reg_orig])
            var_orig_2d   = np.vstack([var_orig_2d[0,:],var_orig_2d])
    
            
            f = interp2d(t_reg_orig, z_reg_orig,var_orig_2d, kind='linear')
            var_curtain = f(t_reg_mid,z_reg_mid)
    
            
        
        
        
        
        
        return var_curtain

    
    
    #Creating regularized grid.
    d_reg = 0.005
    n_z_reg = int(1.5/d_reg)
    n_t_reg = int((1+2*curtain_extra)/d_reg)


    t_reg_bound      = np.linspace(-0.5-curtain_extra,0.5+curtain_extra ,n_t_reg+1)
    t_reg_mid        = np.linspace(-0.5-curtain_extra+d_reg/2,0.5+curtain_extra-d_reg/2  ,n_t_reg)
    z_reg_bound      = np.linspace(0,1.5                     ,n_z_reg+1)
    z_reg_mid        = np.linspace(0+d_reg/2,1.5-d_reg/2     ,n_z_reg)

    mesh_curtain_t,mesh_curtain_z = np.meshgrid(t_reg_mid,z_reg_mid)
    var_curtain     = np.zeros([n_t_reg,n_z_reg])
    var_curtain_sum = np.zeros([n_t_reg,n_z_reg])
    
    var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg])
    var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg])

    n_curtain        = 0
    n_curtain_up     = 0
    n_curtain_dw     = 0

    if size_bin_flag==1:
        N_bins = 12
        n_curtain_bin          = np.zeros([N_bins])
        n_curtain_bin_up       = np.zeros([N_bins])
        n_curtain_bin_dw       = np.zeros([N_bins])
        var_curtain_bin_sum    = np.zeros([N_bins,n_t_reg,n_z_reg])
        var_curtain_bin_up_sum = np.zeros([N_bins,n_t_reg,n_z_reg])
        var_curtain_bin_dw_sum = np.zeros([N_bins,n_t_reg,n_z_reg])
        
        mid_bin_size = np.linspace(125,-125+N_bins*250,N_bins)
        print('mid_bin_size',mid_bin_size)



    
    print('looking into date: ',date)
    if data_dim_flag==1:
        filename_column = []
        #uses glob to get all files which contain column.
        column_files =     glob.glob(directory_input+date+'/*column*.nc')
         
        for c_file in column_files:
            filename_column.append(c_file)
            print('filename column included:',c_file)
    if data_dim_flag==3:
        filename_w   = directory_input+date+'/w.nc'
        filename_l   = directory_input+date+'/ql.nc'
        file_w       = Dataset(filename_w,read='r')
        file_ql      = Dataset(filename_l,read='r')
        [nz, nx, ny] = get_zxy_dimension(filename_l,'ql')
        
        
        #getting variable to be regularized
        filename_var = directory_input+date+'/'+reg_var+'.nc'
        file_var     = Dataset(filename_var,read='r')





    filename_prof=glob.glob(directory_input+date+'/*default?0*.nc')[0]
    #if date=='bomex':
    #    filename_prof=directory_input+date+'/bomex.default.0000000.nc'

    file_prof  =  Dataset(filename_prof,read='r')


    extra_string = ''

    

    n_chords = 0


    #This now a bit trickier then for the 3D version. Will have to calculate a vector for the lower time resolution of the profile,
    #Then latter apply the nearest value to the full 1d time vec
    #First loading surface variables from default profile

    print('calculating cbl height from profile file')
    T = file_prof['thl'][:,0]
    p = file_prof['p'][:,0]*0.0+99709
    qt = file_prof['qt'][:,0]
    w2 = file_prof['w2'][:,:]
    nz_prof = w2.shape[1]
    var_prof =  file_prof[reg_var][:,:] #needed for anomaly processing
    #Just grabbing this to calculate dz
    z_prof = file_prof['z'][:]
    dz = z_prof[1]-z_prof[0]
    print('dz: ',dz)
    
    #for boundary scaling
    total_surf_buoy_flux = file_prof['bflux'][:,1]
    total_surf_thl_flux = file_prof['thlflux'][:,1]
    total_surf_qt_flux = file_prof['qtflux'][:,1]
    

    time_prof = file_prof['time'][:]
    cbl_1d_prof = time_prof*0.0

    #Hack together the Lifting condensation level LCL
    qt_pressure = p*qt
    sat_qv = 6.112*100 * np.exp(17.67 * (T - 273.15) / (T - 29.65 ))
    #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0]
    rel_hum = qt_pressure/sat_qv
    #Dewpoint
    A = 17.27
    B = 237.7
    alpha = ((A * (T- 273.15)) / (B + (T-273.15)))
    alpha = alpha + np.log(rel_hum)
    dewpoint = (B * alpha) / (A - alpha)
    dewpoint = dewpoint + 273.15
    LCL = 125.*(T-dewpoint)
    LCL_index = np.floor(LCL/dz)

    #now calculate the cbl top for each profile time
    for tt in range(len(time_prof)):
        w_var = 1.0
        z=z_min
        while w_var > 0.08:
            z += 1
            w_var = w2[tt,z]
            #w_var = np.var(w_1d[z,:])

        #Mimimum of LCL +100 or variance plus 300 m 
        cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt])
        #To avoid issues later on I set the maximum cbl height to 60 % of the domain height, but spit out a warning if it happens
        if cbl_1d_prof[tt]>0.6*nz_prof:
            print('warning, cbl height heigher than 0.6 domain height, could crash regularization later on, timestep: ',tt)
            cbl_1d_prof[tt] = math.floor(nz*0.6)
    print('resulting indexes of cbl over time: ',cbl_1d_prof)
    print('calculated LCL: ',LCL_index)


    #Now we either iterate over columns or timesteps
    if data_dim_flag==1:
        n_iter =len(filename_column)
    if data_dim_flag==3:
        n_iter =len(time_prof)


    #Setting curtains for var
    var_curtain_sum = np.zeros([n_t_reg,n_z_reg])
    var_curtain_up_sum = np.zeros([n_t_reg,n_z_reg])
    var_curtain_dw_sum = np.zeros([n_t_reg,n_z_reg])

    n_curtain        = 0
    n_chord        = 0
    n_curtain_up     = 0
    n_curtain_dw     = 0




    #for col in filename_column:
    n_iter = min(n_iter,N_it_max)
    for it in range(N_it_min,n_iter):
        print('n_chords: ',n_chords)
        print('n_curtain: ',n_curtain)




        time1 = ttiimmee.time()
        if data_dim_flag ==1:
            print('loading column: ',filename_column[it])
            file_col = Dataset(filename_column[it],read='r')

            w_2d = file_col.variables['w'][:]
            w_2d = w_2d.transpose()
            ql_2d = file_col.variables['ql'][:]
            ql_2d = ql_2d.transpose()
            t_1d = file_col.variables['time'][:]
            u_2d  = file_col.variables['u'][:]
            u_2d  = u_2d.transpose()
            v_2d  = file_col.variables['v'][:]
            v_2d  = v_2d.transpose()
            print('t_1d',t_1d)
            #Load the var file, even if means that we doable load w_2d or ql_2d
            var_2d = file_col.variables[reg_var][:]
            
            
            var_2d = var_2d.transpose()
            
            
            #The needed cbl height
            cbl_1d = t_1d*0
            bflux_s_1d  = t_1d*0 
            qtflux_s_1d = t_1d*0 
            thlflux_s_1d= t_1d*0 

            #Now we go through profile time snapshots and allocate the closest full time values to the profile values
            dt_2 = (time_prof[1]-time_prof[0])/2
            for tt in range(len(time_prof)):
                cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt]
                bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2]   = total_surf_buoy_flux[tt]
                qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2]  = total_surf_qt_flux[tt]
                thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt]
                
            #to get anomalies we subtract the closet mean profile
            if anomaly_flag==1:
                for tt in range(len(time_prof)):
                    tmp_matrix =  var_2d[:,abs(t_1d-time_prof[tt])<dt_2]
                    tmp_vector =  var_prof[tt,:]
                    #because the vectors don't perfectly align
                    var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose()

                    # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:]
                
                


        if data_dim_flag ==3:


            if sum(file_prof['ql'][it,:])>0.0:

                print('loading timestep: ',it)

                ql_3d   = grab_3d_field(file_ql  ,it,'ql')
                w_3d    = grab_3d_field(file_w   ,it,'w')
                var_3d  = grab_3d_field(file_var ,it,reg_var)

                #Here we have to do all the fuckery to turn the 3D fields into 2d slices with an imaginary time vector
                w_2d   = np.array(w_3d.reshape((nz,nx*ny)))
                ql_2d  = np.array(ql_3d.reshape((nz,nx*ny)))
                var_2d = np.array(var_3d.reshape((nz,nx*ny)))
                
                #Now we do the same thing with the transposed field, use to be an either or, now just add it on
                w_3d   = np.transpose( w_3d,  (0, 2, 1))
                ql_3d  = np.transpose(ql_3d,  (0, 2, 1))
                var_3d = np.transpose(var_3d, (0, 2, 1))
                
                #globals().update(locals())                
                w_2d     = np.hstack([w_2d   ,np.array(w_3d.reshape((nz,nx*ny)))])
                ql_2d    = np.hstack([ql_2d  ,np.array(ql_3d.reshape((nz,nx*ny)))])
                var_2d   = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))])
                
                
                
                
                #Should now be able to delete 3d fields as they aren't needed anymore, not sure if that helps save any memory though
                del w_3d
                del ql_3d
                del var_3d
                
                gc.collect()
                
                
                #Switching to anomalies if anomaly flag is used
                if anomaly_flag==1:
                    #because the vectors don't perfectly align
                    var_2d[:,:] = (var_2d.transpose() - var_prof[it,:]).transpose()
                
                
                #to get the fake time vector we load the wind from the profile data, which devided by the grid spacing gives us a fake time resolution
                #we use the calculated cbl+300 meter or lcl as reference height 
                ref_lvl = cbl_1d_prof[it]

                u_ref = file_prof['u'][it,ref_lvl]
                v_ref = file_prof['v'][it,ref_lvl]

                V_ref = np.sqrt(u_ref**2+v_ref**2) 

                time_resolution = dx/V_ref

                print('time iterative, V_ref, time_resolution',it, V_ref, time_resolution )
                print('ref_lvl used to determine reference winds',ref_lvl )
                #fake t vector, 
                t_1d = np.linspace(0,2*nx*ny*time_resolution,2*nx*ny)#+nx*ny*time_resolution*it
                
                
                
            else:
                #If no clouds are present we pass a very short empty fields over to the chord searcher
                print('skipping timestep: ',it,' cause no clouds')
                ql_2d  = np.zeros((nz,1))
                w_2d   = np.zeros((nz,1))
                var_2d = np.zeros((nz,1))
                t_1d   = np.zeros(1)

            #The needed cbl height, which constant everywhere
            cbl_1d = t_1d*0
            cbl_1d[:] = cbl_1d_prof[it]
            #The needed surface buoyancy flux, which is constant everywhere
            bflux_s_1d = t_1d*0   + total_surf_buoy_flux[it]
            qtflux_s_1d = t_1d*0  + total_surf_qt_flux[it]
            thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it]






        time2 = ttiimmee.time()
        print('loading time:',(time2-time1)*1.0,)



        ### Detecting lowest cloud cell is within 300 m of CBL

        nt = len(cbl_1d)
        cl_base = np.zeros(nt)

        #Detecting all cloudy cells
        #Use to have a different method using nans that doesn:t work anymore somehow. Now I just set it really high where there is no cloud. 
        for t in range(nt):
            if np.max(ql_2d[:,t])>ql_min :
                cl_base[t]=np.argmax(ql_2d[:,t]>ql_min)
            else:
                cl_base[t]=10000000

        cl_base=cl_base.astype(int)

        #Now find c base lower than the max height
        cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0]

        cbl_cl_binary = cl_base*0
        cbl_cl_binary[cbl_cl_idx]=1
        t_cbl_cl=t_1d[cbl_cl_idx]
        
        
        #Scaling between x and y is calculated here if required. Is skipped if there are less than 2 timesteps, which is what is assigned when no clouds are present  
        
        if scale_flag > 0 and t_1d.shape[0]>3:
            #calculate the profiles of u and v and their scaling
            u_ref_prof = file_prof['u'][it,:]
            v_ref_prof = file_prof['v'][it,:]
            V_ref_prof = np.sqrt(u_ref_prof**2+v_ref_prof**2) 
            scaling_factor_x_prof = u_ref_prof/V_ref_prof
            scaling_factor_y_prof = v_ref_prof/V_ref_prof
            
            #Using the mean cloud base height as the reference lvl
            ref_idx = np.mean(cl_base[cbl_cl_idx])
            
            if scale_flag == 1:
                #a new reference level is com

                scaling_factor_x = scaling_factor_x_prof[int(ref_idx)]
                scaling_factor_y = scaling_factor_y_prof[int(ref_idx)]

                print('Scaling flag 1:  scaling factor_x: ',scaling_factor_x,' scaling factor_y: ',scaling_factor_y, ' int(ref_idx): ',int(ref_idx))

            if scale_flag == 2:
            
                #Regularizing the scaling profiles and interpolation them onto the regularized z axis 
                d_z_tmp = 1.0/ref_idx
                nz = scaling_factor_x_prof.shape[0]
                z_reg_orig_top = d_z_tmp*nz-d_z_tmp/2
                z_reg_orig = np.linspace(0+d_z_tmp/2,z_reg_orig_top,nz)

                #HAve to add 0  to the z_reg_orig to enable interpolation 
                z_reg_orig = np.hstack([[0],z_reg_orig])
                scaling_factor_x_prof_ext   = np.hstack([scaling_factor_x_prof[0],scaling_factor_x_prof])
                scaling_factor_y_prof_ext   = np.hstack([scaling_factor_y_prof[0],scaling_factor_y_prof])


                #1D vertical interpolation to get the right columns and asign them one by one to w_x_low_z_high
                f_x = interp1d(z_reg_orig, scaling_factor_x_prof_ext, kind='nearest')
                f_y = interp1d(z_reg_orig, scaling_factor_y_prof_ext, kind='nearest')
                scaling_factor_x_inter = f_x(z_reg_mid)
                scaling_factor_y_inter = f_y(z_reg_mid)

                print('Scaling flag 2:, mean scaling_factor_x_inter: ',np.mean(scaling_factor_x_inter),
                      ' mean scaling_factor_y_inter: ',np.mean(scaling_factor_y_inter))


        ### Clustering 1D

        #Now we simply go through all cloudy timesteps
        #As long as the difference to the next cloudy timestep is lower than t_gap it counts as the same cloud
        #As an additional contraint, if the cloudy cells are right next to each other they are always counted as consecutive, not matter the time distance between them. 
        #if the difference is larger than 20s the cloud is over, and a chordlength is created which is a list of all timesteps that below to that chordlength
        #However if the duration of the chordlength is lower than t_min  or higher than t_max seconds it isn't
        #I added an additional constraint that each chord must include at least cell_min cells, because it is possible to get 
        #Small chord lengths with more than t_min which are mostly gaps. 


        t_cloudy_idx = 0
        #n_chords = 0
        chord_idx_list = []

        print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns')


        while t_cloudy_idx < len(cbl_cl_idx)-1 and n_chords<chord_max: 
                
            #print('t_chord_begin',t_chord_begin)
            t_chord_begin = t_cloudy_idx
            #now connecting all cloudy indexes
            while t_cloudy_idx < len(cbl_cl_idx)-1 and (cbl_cl_idx[t_cloudy_idx+1]==cbl_cl_idx[t_cloudy_idx]+1 or t_cbl_cl[t_cloudy_idx+1]-t_cbl_cl[t_cloudy_idx]<t_gap):
                t_cloudy_idx += 1 
            t_chord_end = t_cloudy_idx
            #print('t_chord_end',t_chord_end)


            #Checking if it fulfils chord criteria regaring time
            #we also added a minimum height of 100 m to screen out fog/dew stuff at the surface
            if t_chord_end-t_chord_begin>cell_min:
                chord_z_min = np.min(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]])
                chord_duration = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin]
            else:
                chord_z_min = 0
                chord_duration = 0
                
                
            
            
            
            if chord_duration>t_min and chord_duration<t_max and chord_z_min > 4:


                if t_chord_end-t_chord_begin>cell_min-1:
                    n_chords += 1
                    #chord_idx_list.append(list(cbl_cl_idx[t_chord_begin:t_cloudy_idx]))

                    #Here we start the interpolation stuff
                    #Getting the chord beginning and end
                    idx_beg_chord = cbl_cl_idx[t_chord_begin]
                    idx_end_chord = cbl_cl_idx[t_chord_end]
                    time_beg_chord = t_1d[idx_beg_chord]
                    time_end_chord = t_1d[idx_end_chord]

                    #Calculate the beginning and end of the curtain, we add a bit to to each side to make interpolation easy
                    idx_beg_curtain = (np.abs(t_1d - (time_beg_chord-curtain_extra*(time_end_chord-time_beg_chord)))).argmin()-1
                    idx_end_curtain = (np.abs(t_1d - (time_end_chord+curtain_extra*(time_end_chord-time_beg_chord)))).argmin()+2
                    idx_end_curtain = min(idx_end_curtain,nt-1)
                    time_beg_curtain = t_1d[idx_beg_curtain]
                    time_end_curtain = t_1d[idx_end_curtain]


                    chord_cells = t_chord_end-t_chord_begin
                    curtain_cells = idx_end_curtain-idx_beg_curtain

                    #If curtain has more than curtain_min cells and curtain tail noes not extend beyond end of 2d field or the beginning extend before 
                    #I added 2 cells buffer at the beginning and end, because for the interpolation a bit of overlap is used. 
                    if idx_end_curtain<nt-2 and idx_beg_curtain>2 and len(cbl_cl_idx[t_chord_begin:t_chord_end])>curtain_min-1:
                        n_curtain += 1

                            
                        #First thing to do is calculate the chord base using the 25 percentile in agreement with Neil
                        z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]],base_percentile))

                        #Regularized curtains, I am too lazy to pass on all my variables to func_curtain_reg so I instead made it a nested function
                        var_curtain_tmp = (func_curtain_reg(var_2d)).transpose()
                 
                        if boundary_scaling_flag == 1:
                            #Now adding the boundary scaling using w*
                            surf_flux = np.mean(bflux_s_1d[idx_beg_chord:idx_end_chord])
                            base_height = z_idx_base_default*dz

                            w_star=(base_height*surf_flux)**(1/3) 
                            if reg_var=='w': 
                                boundary_scaling = w_star
                            if reg_var=='qt': 
                                surf_flux = np.mean(qtflux_s_1d[idx_beg_chord:idx_end_chord])
                                boundary_scaling = surf_flux/w_star
                            if reg_var=='thl': 
                                thl_flux = np.mean(thlflux_s_1d[idx_beg_chord:idx_end_chord])
                                boundary_scaling = surf_flux/w_star

                            var_curtain_tmp = var_curtain_tmp/boundary_scaling

                        #Finally add it to the mean one and track one more curtain
                        #detecting if chord base has a positive or negative w, then adds to the sum of up or downdraft chords
                        w_tmp = w_2d[cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]-1,cbl_cl_idx[t_chord_begin:t_chord_end]]
                        #print(w_tmp)
                            
                        
                        #Scaling is now added here, 
                        #Things are applied twice so that deviding by n it comes out fin
                        #We assume here that n_x and n_y are roughly same
                        #Could be made cleaner later on
                        if scale_flag>0 and data_dim_flag==3:
    
                            if scale_flag==1:
                                #find out if we need scaling_factor_x or y by seeing if we are in the first or second half
                                if idx_end_curtain<nt/2:
                                    scaling_factor = 2*scaling_factor_x
                                else:
                                    scaling_factor = 2*scaling_factor_y

                                if scaling_factor>0:
                                    var_curtain_tmp = var_curtain_tmp[::-1,:]

                                var_curtain_tmp = abs(scaling_factor) * var_curtain_tmp

                            if scale_flag==2:
                                if idx_end_curtain<nt/2:
                                    scaling_factor_prof = 2*scaling_factor_x_inter
                                else:
                                    scaling_factor_prof = 2*scaling_factor_y_inter

                                for n_prof in range(scaling_factor_prof.shape[0]):
                                    if scaling_factor_prof[n_prof]>0:
                                        var_curtain_tmp[:,n_prof] = var_curtain_tmp[::-1,n_prof]
                                    var_curtain_tmp [:,n_prof]= abs(scaling_factor_prof[n_prof])*var_curtain_tmp[:,n_prof]

                        #Now adding the var_curtain_tmp to the sums
                        var_curtain_sum    = var_curtain_sum+var_curtain_tmp
                        if np.mean(w_tmp)>0.:
                            n_curtain_up += 1
                            var_curtain_up_sum +=  var_curtain_tmp
                        elif np.mean(w_tmp)<0.:
                            n_curtain_dw += 1
                            var_curtain_dw_sum +=  var_curtain_tmp
                        else:
                            print('wtf how is this zero: ',np.mean(w_tmp),w_tmp)

                        
                        #globals().update(locals())
                        
                        ###############################################################################################################################################
                        ################## SIZE BINNING  ##############################################################################################################
                        ###############################################################################################################################################
                        
                        if size_bin_flag:
                            
                            #getting V_ref if data_dim_flag==1. Is calculated directly from the cloud base speeds
                            if data_dim_flag==1:
                                ch_idx_l = list(cbl_cl_idx[t_chord_begin:t_chord_end])
                                u_ref=np.mean(u_2d[cl_base[ch_idx_l],ch_idx_l])
                                v_ref=np.mean(v_2d[cl_base[ch_idx_l],ch_idx_l])
                                V_ref=np.sqrt(u_ref**2+v_ref**2)
                                
                            ch_duration  = t_cbl_cl[t_chord_end]-t_cbl_cl[t_chord_begin]
                            chord_length = ch_duration*V_ref

                            #if scale_flag==0:
                            #    scaling_factor=1.
                            
                                
                            #find index of bin close to mid size bin
                            bin_idx = np.where(np.abs(chord_length-mid_bin_size)<125)[0]
                            if bin_idx.size>0:
                                #print('bin_idx,chord_length',bin_idx,chord_length)
                                n_curtain_bin[bin_idx] += 1                                                   
                                var_curtain_bin_sum[bin_idx,:,:]    = var_curtain_bin_sum[bin_idx,:,:] + var_curtain_tmp

                                if np.mean(w_tmp)>0.:
                                    n_curtain_bin_up[bin_idx] += 1
                                    var_curtain_bin_up_sum[bin_idx,:,:] +=  var_curtain_tmp
                                elif np.mean(w_tmp)<0.:
                                    n_curtain_bin_dw[bin_idx] += 1
                                    var_curtain_bin_dw_sum[bin_idx,:,:] +=  var_curtain_tmp
                                else:
                                    print('wtf how is this zero: ',np.mean(w_tmp),w_tmp)
                            
                            
                        

                        


                        ##############################################################################################################################
                        #PLOTS
                        ##############################################################################################################################
                        #If the plot flag is set the pre regularization curtains are plotted. 
                        if plot_curtains_flag ==1:
                            print('plotting not implemented yet')
                    
                    ##############################################################################################################################
                    #switching to y direction if half of max chords reached
                    ##############################################################################################################################
                    if n_chords == int(chord_max/2):
                        t_cloudy_idx = int(len(cbl_cl_idx)/2)
                        
            






            t_cloudy_idx += 1
        time3 = ttiimmee.time()

        print('curtain processing:',(time3-time2)/60.0,'minutes')
    

   
    print(':')
    print(':')
    print(':')
    time_end = ttiimmee.time()
    print('total run time of proc_beard_regularize in minutes: ',(time_end-time_begin)/60.)
    print(':')
    print(':')
    print(':')
    
    #Replacing saving with xarray
    xr_dataset = xr.Dataset(
        data_vars = {reg_var   :(('regularized height', 'regularized time'), var_curtain_sum.transpose()/n_curtain),
                     reg_var+'_up':(('regularized height', 'regularized time'), var_curtain_up_sum.transpose()/n_curtain_up),
                     reg_var+'_dw':(('regularized height', 'regularized time'), var_curtain_dw_sum.transpose()/n_curtain_dw)},
        coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid})
    xr_dataset[reg_var].attrs['n']=n_curtain
    xr_dataset[reg_var+'_up'].attrs['n']=n_curtain_up
    xr_dataset[reg_var+'_dw'].attrs['n']=n_curtain_dw
    xr_dataset.attrs = settings_dict

    #Making save string
    save_string_base = '_beard_'+date+'_d'+str(data_dim_flag)+'_cb'+str(base_smoothing_flag)+'_an'+str(anomaly_flag)+'_ct'+str(chord_times)+'_ce'+str(int(curtain_extra))
    if data_dim_flag==3:
        save_string_base = save_string_base+'_sf'+str(scale_flag)
    if N_it_min>0:
        save_string_base = save_string_base+'_Nmin'+str(N_it_min)
    if N_it_max<1e9:
        save_string_base = save_string_base+'_Nmax'+str(n_iter)
    if boundary_scaling_flag==1:
        save_string_base = 'star'+save_string_base
    save_string_base = save_string_base+'_'+special_name+'_N'+str(n_curtain)
    save_string = directory_output+ reg_var+save_string_base +'.nc'
    xr_dataset.to_netcdf(save_string)
    print('saved beard data to '+save_string)



    if size_bin_flag==1: 
        xr_dataset = xr.Dataset(
            data_vars = {reg_var      :(('regularized height', 'regularized time','length'), var_curtain_bin_sum.transpose()/n_curtain_bin),
                         reg_var+'_up':(('regularized height', 'regularized time','length'), var_curtain_bin_up_sum.transpose()/n_curtain_bin_up),
                         reg_var+'_dw':(('regularized height', 'regularized time','length'), var_curtain_bin_dw_sum.transpose()/n_curtain_bin_dw)},
            coords={'regularized time':t_reg_mid, 'regularized height':z_reg_mid, 'length':mid_bin_size})
        xr_dataset[reg_var].attrs['n']        =n_curtain_bin
        xr_dataset[reg_var+'_up'].attrs['n']  =n_curtain_bin_up
        xr_dataset[reg_var+'_dw'].attrs['n']  =n_curtain_bin_dw
        xr_dataset.attrs = settings_dict
        save_string = directory_output+ reg_var+save_string_base+'_sizebin.nc'
        xr_dataset.to_netcdf(save_string)
        print('saved size binned beards to '+save_string)
    
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    
        

        


            
    return








   
    

#A simple script which calculates a histogram below the cloud base and saves it
#I will try to keep it at least somewhat general with a flexible variable

def proc_pdf(reg_var = 'w',
                        date_str='20160611',
                        directory_input  ='/data/testbed/lasso/sims/',
                        directory_output ='data_pdfs/',
                        data_dim_flag=3,
                        special_name='',
                        N_it_max=1e9,
                        N_it_min=0,
                        anomaly_flag =0,                   
                        N_bins=400,
                        base_percentile = 25,
                        boundary_scaling_flag = 1,
                        range_var = [-10,10] ):

    


    #We are starting out with histograms of w from -10 to 10 and a 0.1 spacing
    var_hist_sum=np.zeros(N_bins)

    date = date_str

    #value used to determine existence of cloud
    ql_min = 1e-5

    z_min  = 10 #Index of minimum  z_vlvl of the cbl


    print('looking into date: ',date)
    if data_dim_flag==1:
        filename_column = []
        #uses glob to get all files which contain column.
        column_files =     glob.glob(directory_input+date+'/*.column.*.*.*.nc')

        for c_file in column_files:
            filename_column.append(c_file)
            print('filename column included:',c_file)
    if data_dim_flag==3:
        filename_w   = directory_input+date+'/w.nc'
        filename_l   = directory_input+date+'/ql.nc'
        file_w       = Dataset(filename_w,read='r')
        file_ql      = Dataset(filename_l,read='r')
        [nz, nx, ny] = get_zxy_dimension(filename_l,'ql')


        #getting variable to be regularized
        filename_var = directory_input+date+'/'+reg_var+'.nc'
        file_var     = Dataset(filename_var,read='r')





    filename_prof=glob.glob(directory_input+date+'/testbed?default?0*.nc')[0]
    #filename_prof=directory_input+date+'/testbed.default.0000000.nc'

    if date=='bomex':
        filename_prof=directory_input+date+'/bomex.default.0000000.nc'

    file_prof  =  Dataset(filename_prof,read='r')


    extra_string = ''





    #This now a bit trickier then for the 3D version. Will have to calculate a vector for the lower time resolution of the profile,
    #Then latter apply the nearest value to the full 1d time vec
    #First loading surface variables from default profile

    print('calculating cbl height from profile file')
    T = file_prof['thl'][:,0]
    p = file_prof['p'][:,0]*0.0+99709
    qt = file_prof['qt'][:,0]
    w2 = file_prof['w2'][:,:]
    nz_prof = w2.shape[1]
    var_prof =  file_prof[reg_var][:,:] #needed for anomaly processing
    #Just grabbing this to calculate dz
    z_prof = file_prof['z'][:]
    dz = z_prof[1]-z_prof[0]
    print('dz: ',dz)
    
    #for boundary scaling
    total_surf_buoy_flux = file_prof['bflux'][:,1]
    total_surf_thl_flux = file_prof['thlflux'][:,1]
    total_surf_qt_flux = file_prof['qtflux'][:,1]


    time_prof = file_prof['time'][:]
    cbl_1d_prof = time_prof*0.0

    #Hack together the Lifting condensation level LCL
    qt_pressure = p*qt
    sat_qv = 6.112*100 * np.exp(17.67 * (T - 273.15) / (T - 29.65 ))
    #rel_hum = np.asmatrix(qt_pressure/sat_qv)[0]
    rel_hum = qt_pressure/sat_qv
    #Dewpoint
    A = 17.27
    B = 237.7
    alpha = ((A * (T- 273.15)) / (B + (T-273.15)))
    alpha = alpha + np.log(rel_hum)
    dewpoint = (B * alpha) / (A - alpha)
    dewpoint = dewpoint + 273.15
    LCL = 125.*(T-dewpoint)
    LCL_index = np.floor(LCL/dz)

    #now calculate the cbl top for each profile time
    for tt in range(len(time_prof)):
        w_var = 1.0
        z=z_min
        while w_var > 0.08:
            z += 1
            w_var = w2[tt,z]
            #w_var = np.var(w_1d[z,:])

        #Mimimum of LCL +100 or variance plus 300 m 
        cbl_1d_prof[tt] = min(z+300/dz,LCL_index[tt])
        #To avoid issues later on I set the maximum cbl height to 60 % of the domain height, but spit out a warning if it happens
        if cbl_1d_prof[tt]>0.6*nz_prof:
            print('warning, cbl height heigher than 0.6 domain height, could crash regularization later on, timestep: ',tt)
            cbl_1d_prof[tt] = math.floor(nz*0.6)
    print('resulting indexes of cbl over time: ',cbl_1d_prof)
    print('calculated LCL: ',LCL_index)


    #Now we either iterate over columns or timesteps
    if data_dim_flag==1:
        n_iter =len(filename_column)
    if data_dim_flag==3:
        n_iter =len(time_prof)


    #for col in filename_column:
    n_iter = min(n_iter,N_it_max)
    for it in range(N_it_min,n_iter):
        time1 = ttiimmee.time()
        if data_dim_flag ==1:
            print('loading column: ',filename_column[it])
            file_col = Dataset(filename_column[it],read='r')

            w_2d = file_col.variables['w'][:]
            w_2d = w_2d.transpose()
            ql_2d = file_col.variables['ql'][:]
            ql_2d = ql_2d.transpose()
            t_1d = file_col.variables['time'][:]
            print('t_1d',t_1d)
            #Load the var file, even if means that we doable load w_2d or ql_2d
            var_2d = file_col.variables[reg_var][:]


            var_2d = var_2d.transpose()


            #The needed cbl height
            cbl_1d = t_1d*0
            bflux_s_1d  = t_1d*0 
            qtflux_s_1d = t_1d*0 
            thlflux_s_1d= t_1d*0 

            #Now we go through profile time snapshots and allocate the closest full time values to the profile values
            dt_2 = (time_prof[1]-time_prof[0])/2
            for tt in range(len(time_prof)):
                cbl_1d[abs(t_1d-time_prof[tt])<dt_2] = cbl_1d_prof[tt]
                bflux_s_1d[abs(t_1d-time_prof[tt])<dt_2]   = total_surf_buoy_flux[tt]
                qtflux_s_1d[abs(t_1d-time_prof[tt])<dt_2]  = total_surf_qt_flux[tt]
                thlflux_s_1d[abs(t_1d-time_prof[tt])<dt_2] = total_surf_thl_flux[tt]

            #to get anomalies we subtract the closet mean profile
            if anomaly_flag==1:
                for tt in range(len(time_prof)):
                    tmp_matrix =  var_2d[:,abs(t_1d-time_prof[tt])<dt_2]
                    tmp_vector =  var_prof[tt,:]
                    #because the vectors don't perfectly align
                    var_2d[:,abs(t_1d-time_prof[tt])<dt_2] = (tmp_matrix.transpose() - tmp_vector).transpose()

                    # = var_2d[:,abs(t_1d-time_prof[tt])<dt_2]-var_prof[tt,:]




        if data_dim_flag ==3:


            if sum(file_prof['ql'][it,:])>0.0:

                print('loading timestep: ',it)

                ql_3d   = grab_3d_field(file_ql  ,it,'ql')
                w_3d    = grab_3d_field(file_w   ,it,'w')
                var_3d  = grab_3d_field(file_var ,it,reg_var)

                #Here we have to do all the fuckery to turn the 3D fields into 2d slices with an imaginary time vector
                w_2d   = np.array(w_3d.reshape((nz,nx*ny)))
                ql_2d  = np.array(ql_3d.reshape((nz,nx*ny)))
                var_2d = np.array(var_3d.reshape((nz,nx*ny)))

                #Now we do the same thing with the transposed field, use to be an either or, now just add it on
                w_3d   = np.transpose( w_3d,  (0, 2, 1))
                ql_3d  = np.transpose(ql_3d,  (0, 2, 1))
                var_3d = np.transpose(var_3d, (0, 2, 1))

                #globals().update(locals())                
                w_2d     = np.hstack([w_2d   ,np.array(w_3d.reshape((nz,nx*ny)))])
                ql_2d    = np.hstack([ql_2d  ,np.array(ql_3d.reshape((nz,nx*ny)))])
                var_2d   = np.hstack([var_2d ,np.array(var_3d.reshape((nz,nx*ny)))])
                
                #This might save a bit of memory
                if reg_var == 'w':
                    var_2d = w_2d
                if reg_var == 'ql':
                    var_2d = ql_2d
                    




                #Should now be able to delete 3d fields as they aren't needed anymore, not sure if that helps save any memory though
                del w_3d
                del ql_3d
                del var_3d

                gc.collect()

                 #fake t vector,   
                t_1d = np.linspace(0,2*nx*ny,2*nx*ny)
                
                #Switching to anomalies if anomaly flag is used
                if anomaly_flag==1:
                    #because the vectors don't perfectly align
                    var_2d[:,:] = (var_2d.transpose() - var_prof[it,:]).transpose()


                #to get the fake time vector we load the wind from the profile data, which devided by the grid spacing gives us a fake time resolution
                #we use the calculated cbl+300 meter or lcl as reference height 
                ref_lvl = cbl_1d_prof[it]





            else:
                #If no clouds are present we pass a very short empty fields over to the chord searcher
                print('skipping timestep: ',it,' cause no clouds')
                ql_2d  = np.zeros((nz,1))
                w_2d   = np.zeros((nz,1))
                var_2d = np.zeros((nz,1))
                t_1d   = np.zeros(1)

            #The needed cbl height, which constant everywhere
            cbl_1d = t_1d*0
            cbl_1d[:] = cbl_1d_prof[it]
            #The needed surface buoyancy flux, which is constant everywhere
            bflux_s_1d = t_1d*0   + total_surf_buoy_flux[it]
            qtflux_s_1d = t_1d*0  + total_surf_qt_flux[it]
            thlflux_s_1d = t_1d*0 + total_surf_thl_flux[it]






        time2 = ttiimmee.time()
        print('loading time:',(time2-time1)*1.0,)



        ### Detecting lowest cloud cell is within 300 m of CBL

        nt = len(cbl_1d)
        cl_base = np.zeros(nt)

        #Detecting all cloudy cells
        #Use to have a different method using nans that doesn:t work anymore somehow. Now I just set it really high where there is no cloud. 
        for t in range(nt):
            if np.max(ql_2d[:,t])>ql_min :
                cl_base[t]=np.argmax(ql_2d[:,t]>ql_min)
            else:
                cl_base[t]=10000000

        cl_base=cl_base.astype(int)

        #Now find c base lower than the max height
        cbl_cl_idx = np.where((cl_base-cbl_1d[:nt])*dz<0)[0]

        cbl_cl_binary = cl_base*0
        cbl_cl_binary[cbl_cl_idx]=1


        print('iterating through step ',it,'which contains ',len(cbl_cl_idx),'cloudy columns')


        if len(cbl_cl_idx)>0:
            #Now calculating the var at cloud base
            var_cl_base=var_2d[cl_base[cbl_cl_idx]-1,cbl_cl_idx]
            
            #If boundary scaling is used, the variable is scaled accordingly
            #Only called if there are any clouds
            if boundary_scaling_flag == 1 and len(cbl_cl_idx)>1:
                
                #First thing to do is calculate the chord base using the 25 percentile in agreement with Neil
                
                if data_dim_flag==3:
                    z_idx_base_default = math.floor(np.percentile(cl_base[cbl_cl_idx],base_percentile))
                # Can't think of a good way to do this, will throw up an error for the mean time. 
                if data_dim_flag==1:
                    print('sorry, but I havent implemented star scaling for 1d data')
                    sys.exit()



                
                #Now adding the boundary scaling using w*
                #Is a bit overcooked currently as it only works with 3D data and thus all surface fluxes are the same everywhere. 
                surf_flux = np.mean(bflux_s_1d)
                base_height = z_idx_base_default*dz

                w_star=(base_height*surf_flux)**(1/3) 
                if reg_var=='w': 
                    boundary_scaling = w_star
                if reg_var=='qt': 
                    surf_flux = np.mean(qtflux_s_1d)
                    boundary_scaling = surf_flux/w_star
                if reg_var=='thl': 
                    thl_flux = np.mean(thlflux_s_1d)
                    boundary_scaling = surf_flux/w_star

                var_cl_base = var_cl_base/boundary_scaling

            #Calculating the histogram, and adding it to the total histogram
            var_hist,bin_edges = np.histogram(var_cl_base,range=range_var,bins=N_bins)

            var_hist_sum = var_hist_sum+var_hist

        else:
            print('no cloudy columns apparently')


    var_pdf = var_hist_sum


    save_string_base = '_pdf_'+date+'_d'+str(data_dim_flag)+'_an'+str(anomaly_flag)

    if N_it_min>0:
        save_string_base = save_string_base+'_Nmin'+str(N_it_min)
    if N_it_max<1e9:
        save_string_base = save_string_base+'_Nmax'+str(n_iter)
    if boundary_scaling_flag==1:
        save_string_base = 'star'+save_string_base


    save_string = directory_output+ reg_var+save_string_base

    save_string = save_string+'.npz'

    np.savez(save_string,var_pdf=var_pdf,range_var=range_var)
    print('saved pdf with ', sum(var_pdf), 'points to '+save_string)

    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
    print(':')
                
    return

[((60, 17, 60, 32), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((69, 18, 69, 49), 'numpy.array', 'np.array', ({(69, 27, 69, 48): '[5, 10, 35, 50, 65, 90, 95]'}, {}), '([5, 10, 35, 50, 65, 90, 95])', True, 'import numpy as np\n'), ((129, 18, 129, 49), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((156, 32, 156, 59), 'numpy.zeros', 'np.zeros', ({(156, 41, 156, 58): '[0, n_percentiles]'}, {}), '([0, n_percentiles])', True, 'import numpy as np\n'), ((157, 32, 157, 59), 'numpy.zeros', 'np.zeros', ({(157, 41, 157, 58): '[0, n_percentiles]'}, {}), '([0, n_percentiles])', True, 'import numpy as np\n'), ((197, 16, 197, 32), 'numpy.floor', 'np.floor', ({(197, 25, 197, 31): 'LCL / dz'}, {}), '(LCL / dz)', True, 'import numpy as np\n'), ((538, 20, 538, 47), 'numpy.asarray', 'np.asarray', ({(538, 31, 538, 46): 'chord_timesteps'}, {}), '(chord_timesteps)', True, 'import numpy as np\n'), ((539, 20, 539, 46), 'numpy.asarray', 'np.asarray', ({(539, 31, 539, 45): 'chord_duration'}, {}), '(chord_duration)', True, 'import numpy as np\n'), ((540, 20, 540, 44), 'numpy.asarray', 'np.asarray', ({(540, 31, 540, 43): 'chord_length'}, {}), '(chord_length)', True, 'import numpy as np\n'), ((541, 20, 541, 44), 'numpy.asarray', 'np.asarray', ({(541, 31, 541, 43): 'chord_height'}, {}), '(chord_height)', True, 'import numpy as np\n'), ((542, 20, 542, 44), 'numpy.asarray', 'np.asarray', ({(542, 31, 542, 43): 'chord_w_base'}, {}), '(chord_w_base)', True, 'import numpy as np\n'), ((543, 20, 543, 44), 'numpy.asarray', 'np.asarray', ({(543, 31, 543, 43): 'chord_w_star'}, {}), '(chord_w_star)', True, 'import numpy as np\n'), ((544, 20, 544, 46), 'numpy.asarray', 'np.asarray', ({(544, 31, 544, 45): 'chord_thl_star'}, {}), '(chord_thl_star)', True, 'import numpy as np\n'), ((545, 20, 545, 45), 'numpy.asarray', 'np.asarray', ({(545, 31, 545, 44): 'chord_qt_star'}, {}), '(chord_qt_star)', True, 'import numpy as np\n'), ((546, 20, 546, 39), 'numpy.asarray', 'np.asarray', ({(546, 31, 546, 38): 'chord_w'}, {}), '(chord_w)', True, 'import numpy as np\n'), ((547, 20, 547, 42), 'numpy.asarray', 'np.asarray', ({(547, 31, 547, 41): 'chord_w_up'}, {}), '(chord_w_up)', True, 'import numpy as np\n'), ((548, 20, 548, 44), 'numpy.asarray', 'np.asarray', ({(548, 31, 548, 43): 'chord_w_flux'}, {}), '(chord_w_flux)', True, 'import numpy as np\n'), ((549, 20, 549, 41), 'numpy.asarray', 'np.asarray', ({(549, 31, 549, 40): 'chord_thl'}, {}), '(chord_thl)', True, 'import numpy as np\n'), ((550, 20, 550, 44), 'numpy.asarray', 'np.asarray', ({(550, 31, 550, 43): 'chord_thl_25'}, {}), '(chord_thl_25)', True, 'import numpy as np\n'), ((551, 20, 551, 44), 'numpy.asarray', 'np.asarray', ({(551, 31, 551, 43): 'chord_thl_75'}, {}), '(chord_thl_75)', True, 'import numpy as np\n'), ((552, 20, 552, 40), 'numpy.asarray', 'np.asarray', ({(552, 31, 552, 39): 'chord_qt'}, {}), '(chord_qt)', True, 'import numpy as np\n'), ((553, 20, 553, 43), 'numpy.asarray', 'np.asarray', ({(553, 31, 553, 42): 'chord_qt_25'}, {}), '(chord_qt_25)', True, 'import numpy as np\n'), ((554, 20, 554, 43), 'numpy.asarray', 'np.asarray', ({(554, 31, 554, 42): 'chord_qt_75'}, {}), '(chord_qt_75)', True, 'import numpy as np\n'), ((555, 20, 555, 42), 'numpy.asarray', 'np.asarray', ({(555, 31, 555, 41): 'chord_time'}, {}), '(chord_time)', True, 'import numpy as np\n'), ((576, 9, 578, 99), 'pandas.DataFrame', 'pd.DataFrame', (), '', True, 'import pandas as pd\n'), ((580, 15, 580, 30), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((653, 17, 653, 32), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((844, 23, 844, 83), 'numpy.linspace', 'np.linspace', ({(844, 35, 844, 53): '-0.5 - curtain_extra', (844, 54, 844, 71): '0.5 + curtain_extra', (844, 73, 844, 82): 'n_t_reg + 1'}, {}), '(-0.5 - curtain_extra, 0.5 + curtain_extra, n_t_reg + 1)', True, 'import numpy as np\n'), ((845, 23, 845, 98), 'numpy.linspace', 'np.linspace', ({(845, 35, 845, 61): '-0.5 - curtain_extra + d_reg / 2', (845, 62, 845, 87): '0.5 + curtain_extra - d_reg / 2', (845, 90, 845, 97): 'n_t_reg'}, {}), '(-0.5 - curtain_extra + d_reg / 2, 0.5 + curtain_extra - d_reg /\n    2, n_t_reg)', True, 'import numpy as np\n'), ((846, 23, 846, 72), 'numpy.linspace', 'np.linspace', ({(846, 35, 846, 36): '0', (846, 37, 846, 40): '1.5', (846, 62, 846, 71): 'n_z_reg + 1'}, {}), '(0, 1.5, n_z_reg + 1)', True, 'import numpy as np\n'), ((847, 23, 847, 70), 'numpy.linspace', 'np.linspace', ({(847, 35, 847, 44): '0 + d_reg / 2', (847, 45, 847, 56): '1.5 - d_reg / 2', (847, 62, 847, 69): 'n_z_reg'}, {}), '(0 + d_reg / 2, 1.5 - d_reg / 2, n_z_reg)', True, 'import numpy as np\n'), ((849, 36, 849, 68), 'numpy.meshgrid', 'np.meshgrid', ({(849, 48, 849, 57): 't_reg_mid', (849, 58, 849, 67): 'z_reg_mid'}, {}), '(t_reg_mid, z_reg_mid)', True, 'import numpy as np\n'), ((850, 22, 850, 49), 'numpy.zeros', 'np.zeros', ({(850, 31, 850, 48): '[n_t_reg, n_z_reg]'}, {}), '([n_t_reg, n_z_reg])', True, 'import numpy as np\n'), ((851, 22, 851, 49), 'numpy.zeros', 'np.zeros', ({(851, 31, 851, 48): '[n_t_reg, n_z_reg]'}, {}), '([n_t_reg, n_z_reg])', True, 'import numpy as np\n'), ((853, 25, 853, 52), 'numpy.zeros', 'np.zeros', ({(853, 34, 853, 51): '[n_t_reg, n_z_reg]'}, {}), '([n_t_reg, n_z_reg])', True, 'import numpy as np\n'), ((854, 25, 854, 52), 'numpy.zeros', 'np.zeros', ({(854, 34, 854, 51): '[n_t_reg, n_z_reg]'}, {}), '([n_t_reg, n_z_reg])', True, 'import numpy as np\n'), ((904, 18, 904, 49), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((952, 16, 952, 32), 'numpy.floor', 'np.floor', ({(952, 25, 952, 31): 'LCL / dz'}, {}), '(LCL / dz)', True, 'import numpy as np\n'), ((981, 22, 981, 49), 'numpy.zeros', 'np.zeros', ({(981, 31, 981, 48): '[n_t_reg, n_z_reg]'}, {}), '([n_t_reg, n_z_reg])', True, 'import numpy as np\n'), ((982, 25, 982, 52), 'numpy.zeros', 'np.zeros', ({(982, 34, 982, 51): '[n_t_reg, n_z_reg]'}, {}), '([n_t_reg, n_z_reg])', True, 'import numpy as np\n'), ((983, 25, 983, 52), 'numpy.zeros', 'np.zeros', ({(983, 34, 983, 51): '[n_t_reg, n_z_reg]'}, {}), '([n_t_reg, n_z_reg])', True, 'import numpy as np\n'), ((1423, 15, 1423, 30), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((1516, 17, 1516, 33), 'numpy.zeros', 'np.zeros', ({(1516, 26, 1516, 32): 'N_bins'}, {}), '(N_bins)', True, 'import numpy as np\n'), ((1557, 18, 1557, 49), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((1604, 16, 1604, 32), 'numpy.floor', 'np.floor', ({(1604, 25, 1604, 31): 'LCL / dz'}, {}), '(LCL / dz)', True, 'import numpy as np\n'), ((1854, 4, 1854, 61), 'numpy.savez', 'np.savez', (), '', True, 'import numpy as np\n'), ((101, 27, 101, 73), 'glob.glob', 'glob.glob', ({(101, 37, 101, 72): "directory_input + date + '/*column*.nc'"}, {}), "(directory_input + date + '/*column*.nc')", False, 'import glob\n'), ((111, 23, 111, 51), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((112, 23, 112, 51), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((113, 23, 113, 53), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((114, 23, 114, 52), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((123, 18, 123, 67), 'glob.glob', 'glob.glob', ({(123, 28, 123, 66): "(directory_input + date + '/*default?0*.nc')"}, {}), "(directory_input + date + '/*default?0*.nc')", False, 'import glob\n'), ((186, 25, 186, 68), 'numpy.exp', 'np.exp', ({(186, 32, 186, 67): '(17.67 * (T - 273.15) / (T - 29.65))'}, {}), '(17.67 * (T - 273.15) / (T - 29.65))', True, 'import numpy as np\n'), ((193, 20, 193, 35), 'numpy.log', 'np.log', ({(193, 27, 193, 34): 'rel_hum'}, {}), '(rel_hum)', True, 'import numpy as np\n'), ((234, 16, 234, 31), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((381, 16, 381, 31), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((389, 18, 389, 30), 'numpy.zeros', 'np.zeros', ({(389, 27, 389, 29): 'nt'}, {}), '(nt)', True, 'import numpy as np\n'), ((523, 16, 523, 31), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((732, 27, 732, 60), 'numpy.zeros', 'np.zeros', ({(732, 36, 732, 59): '[curtain_cells, n_z_reg]'}, {}), '([curtain_cells, n_z_reg])', True, 'import numpy as np\n'), ((862, 33, 862, 51), 'numpy.zeros', 'np.zeros', ({(862, 42, 862, 50): '[N_bins]'}, {}), '([N_bins])', True, 'import numpy as np\n'), ((863, 33, 863, 51), 'numpy.zeros', 'np.zeros', ({(863, 42, 863, 50): '[N_bins]'}, {}), '([N_bins])', True, 'import numpy as np\n'), ((864, 33, 864, 51), 'numpy.zeros', 'np.zeros', ({(864, 42, 864, 50): '[N_bins]'}, {}), '([N_bins])', True, 'import numpy as np\n'), ((865, 33, 865, 67), 'numpy.zeros', 'np.zeros', ({(865, 42, 865, 66): '[N_bins, n_t_reg, n_z_reg]'}, {}), '([N_bins, n_t_reg, n_z_reg])', True, 'import numpy as np\n'), ((866, 33, 866, 67), 'numpy.zeros', 'np.zeros', ({(866, 42, 866, 66): '[N_bins, n_t_reg, n_z_reg]'}, {}), '([N_bins, n_t_reg, n_z_reg])', True, 'import numpy as np\n'), ((867, 33, 867, 67), 'numpy.zeros', 'np.zeros', ({(867, 42, 867, 66): '[N_bins, n_t_reg, n_z_reg]'}, {}), '([N_bins, n_t_reg, n_z_reg])', True, 'import numpy as np\n'), ((869, 23, 869, 62), 'numpy.linspace', 'np.linspace', ({(869, 35, 869, 38): '125', (869, 39, 869, 54): '-125 + N_bins * 250', (869, 55, 869, 61): 'N_bins'}, {}), '(125, -125 + N_bins * 250, N_bins)', True, 'import numpy as np\n'), ((879, 27, 879, 73), 'glob.glob', 'glob.glob', ({(879, 37, 879, 72): "directory_input + date + '/*column*.nc'"}, {}), "(directory_input + date + '/*column*.nc')", False, 'import glob\n'), ((887, 23, 887, 51), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((888, 23, 888, 51), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((894, 23, 894, 53), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((900, 18, 900, 67), 'glob.glob', 'glob.glob', ({(900, 28, 900, 66): "(directory_input + date + '/*default?0*.nc')"}, {}), "(directory_input + date + '/*default?0*.nc')", False, 'import glob\n'), ((941, 25, 941, 68), 'numpy.exp', 'np.exp', ({(941, 32, 941, 67): '(17.67 * (T - 273.15) / (T - 29.65))'}, {}), '(17.67 * (T - 273.15) / (T - 29.65))', True, 'import numpy as np\n'), ((948, 20, 948, 35), 'numpy.log', 'np.log', ({(948, 27, 948, 34): 'rel_hum'}, {}), '(rel_hum)', True, 'import numpy as np\n'), ((1002, 16, 1002, 31), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((1133, 16, 1133, 31), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((1141, 18, 1141, 30), 'numpy.zeros', 'np.zeros', ({(1141, 27, 1141, 29): 'nt'}, {}), '(nt)', True, 'import numpy as np\n'), ((1414, 16, 1414, 31), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((1530, 27, 1530, 79), 'glob.glob', 'glob.glob', ({(1530, 37, 1530, 78): "directory_input + date + '/*.column.*.*.*.nc'"}, {}), "(directory_input + date + '/*.column.*.*.*.nc')", False, 'import glob\n'), ((1538, 23, 1538, 51), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((1539, 23, 1539, 51), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((1545, 23, 1545, 53), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((1551, 18, 1551, 74), 'glob.glob', 'glob.glob', ({(1551, 28, 1551, 73): "(directory_input + date + '/testbed?default?0*.nc')"}, {}), "(directory_input + date + '/testbed?default?0*.nc')", False, 'import glob\n'), ((1593, 25, 1593, 68), 'numpy.exp', 'np.exp', ({(1593, 32, 1593, 67): '(17.67 * (T - 273.15) / (T - 29.65))'}, {}), '(17.67 * (T - 273.15) / (T - 29.65))', True, 'import numpy as np\n'), ((1600, 20, 1600, 35), 'numpy.log', 'np.log', ({(1600, 27, 1600, 34): 'rel_hum'}, {}), '(rel_hum)', True, 'import numpy as np\n'), ((1635, 16, 1635, 31), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((1761, 16, 1761, 31), 'time.time', 'ttiimmee.time', ({}, {}), '()', True, 'import time as ttiimmee\n'), ((1769, 18, 1769, 30), 'numpy.zeros', 'np.zeros', ({(1769, 27, 1769, 29): 'nt'}, {}), '(nt)', True, 'import numpy as np\n'), ((213, 30, 213, 48), 'math.floor', 'math.floor', ({(213, 41, 213, 47): 'nz * 0.6'}, {}), '(nz * 0.6)', False, 'import math\n'), ((237, 23, 237, 60), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((402, 21, 402, 57), 'numpy.where', 'np.where', ({(402, 30, 402, 56): '((cl_base - cbl_1d[:nt]) * dz < 0)'}, {}), '((cl_base - cbl_1d[:nt]) * dz < 0)', True, 'import numpy as np\n'), ((818, 25, 818, 67), 'numpy.linspace', 'np.linspace', ({(818, 37, 818, 48): '0 + d_z_tmp / 2', (818, 49, 818, 63): 'z_reg_orig_top', (818, 64, 818, 66): 'nz'}, {}), '(0 + d_z_tmp / 2, z_reg_orig_top, nz)', True, 'import numpy as np\n'), ((821, 28, 821, 55), 'numpy.hstack', 'np.hstack', ({(821, 38, 821, 54): '[[0], z_reg_orig]'}, {}), '([[0], z_reg_orig])', True, 'import numpy as np\n'), ((822, 28, 822, 69), 'numpy.vstack', 'np.vstack', ({(822, 38, 822, 68): '[var_orig_2d[(0), :], var_orig_2d]'}, {}), '([var_orig_2d[(0), :], var_orig_2d])', True, 'import numpy as np\n'), ((825, 16, 825, 75), 'scipy.interpolate.interp2d', 'interp2d', (), '', False, 'from scipy.interpolate import interp2d\n'), ((968, 30, 968, 48), 'math.floor', 'math.floor', ({(968, 41, 968, 47): 'nz * 0.6'}, {}), '(nz * 0.6)', False, 'import math\n'), ((1005, 23, 1005, 60), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((1154, 21, 1154, 57), 'numpy.where', 'np.where', ({(1154, 30, 1154, 56): '((cl_base - cbl_1d[:nt]) * dz < 0)'}, {}), '((cl_base - cbl_1d[:nt]) * dz < 0)', True, 'import numpy as np\n'), ((1167, 25, 1167, 61), 'numpy.sqrt', 'np.sqrt', ({(1167, 33, 1167, 60): 'u_ref_prof ** 2 + v_ref_prof ** 2'}, {}), '(u_ref_prof ** 2 + v_ref_prof ** 2)', True, 'import numpy as np\n'), ((1172, 22, 1172, 50), 'numpy.mean', 'np.mean', ({(1172, 30, 1172, 49): 'cl_base[cbl_cl_idx]'}, {}), '(cl_base[cbl_cl_idx])', True, 'import numpy as np\n'), ((1620, 30, 1620, 48), 'math.floor', 'math.floor', ({(1620, 41, 1620, 47): 'nz * 0.6'}, {}), '(nz * 0.6)', False, 'import math\n'), ((1638, 23, 1638, 60), 'netCDF4.Dataset', 'Dataset', (), '', False, 'from netCDF4 import Dataset\n'), ((1782, 21, 1782, 57), 'numpy.where', 'np.where', ({(1782, 30, 1782, 56): '((cl_base - cbl_1d[:nt]) * dz < 0)'}, {}), '((cl_base - cbl_1d[:nt]) * dz < 0)', True, 'import numpy as np\n'), ((1829, 33, 1829, 86), 'numpy.histogram', 'np.histogram', (), '', True, 'import numpy as np\n'), ((313, 25, 313, 56), 'numpy.transpose', 'np.transpose', ({(313, 39, 313, 43): 'w_3d', (313, 46, 313, 55): '(0, 2, 1)'}, {}), '(w_3d, (0, 2, 1))', True, 'import numpy as np\n'), ((314, 25, 314, 56), 'numpy.transpose', 'np.transpose', ({(314, 38, 314, 43): 'ql_3d', (314, 46, 314, 55): '(0, 2, 1)'}, {}), '(ql_3d, (0, 2, 1))', True, 'import numpy as np\n'), ((315, 25, 315, 56), 'numpy.transpose', 'np.transpose', ({(315, 38, 315, 43): 'qt_3d', (315, 46, 315, 55): '(0, 2, 1)'}, {}), '(qt_3d, (0, 2, 1))', True, 'import numpy as np\n'), ((316, 25, 316, 56), 'numpy.transpose', 'np.transpose', ({(316, 38, 316, 44): 'thl_3d', (316, 46, 316, 55): '(0, 2, 1)'}, {}), '(thl_3d, (0, 2, 1))', True, 'import numpy as np\n'), ((332, 16, 332, 28), 'gc.collect', 'gc.collect', ({}, {}), '()', False, 'import gc\n'), ((346, 24, 346, 50), 'numpy.sqrt', 'np.sqrt', ({(346, 32, 346, 49): 'u_ref ** 2 + v_ref ** 2'}, {}), '(u_ref ** 2 + v_ref ** 2)', True, 'import numpy as np\n'), ((352, 23, 352, 69), 'numpy.linspace', 'np.linspace', ({(352, 35, 352, 36): '0', (352, 37, 352, 60): '2 * nx * ny * time_resolution', (352, 61, 352, 68): '2 * nx * ny'}, {}), '(0, 2 * nx * ny * time_resolution, 2 * nx * ny)', True, 'import numpy as np\n'), ((362, 27, 362, 43), 'numpy.zeros', 'np.zeros', ({(362, 36, 362, 42): '(nz, 1)'}, {}), '((nz, 1))', True, 'import numpy as np\n'), ((363, 27, 363, 43), 'numpy.zeros', 'np.zeros', ({(363, 36, 363, 42): '(nz, 1)'}, {}), '((nz, 1))', True, 'import numpy as np\n'), ((364, 27, 364, 43), 'numpy.zeros', 'np.zeros', ({(364, 36, 364, 42): '(nz, 1)'}, {}), '((nz, 1))', True, 'import numpy as np\n'), ((365, 27, 365, 43), 'numpy.zeros', 'np.zeros', ({(365, 36, 365, 42): '(nz, 1)'}, {}), '((nz, 1))', True, 'import numpy as np\n'), ((366, 27, 366, 38), 'numpy.zeros', 'np.zeros', ({(366, 36, 366, 37): '1'}, {}), '(1)', True, 'import numpy as np\n'), ((394, 15, 394, 33), 'numpy.max', 'np.max', ({(394, 22, 394, 32): 'ql_2d[:, (t)]'}, {}), '(ql_2d[:, (t)])', True, 'import numpy as np\n'), ((395, 27, 395, 53), 'numpy.argmax', 'np.argmax', ({(395, 37, 395, 52): 'ql_2d[:, (t)] > 1e-06'}, {}), '(ql_2d[:, (t)] > 1e-06)', True, 'import numpy as np\n'), ((439, 30, 439, 84), 'numpy.min', 'np.min', ({(439, 37, 439, 83): 'cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]'}, {}), '(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]])', True, 'import numpy as np\n'), ((783, 29, 783, 71), 'numpy.linspace', 'np.linspace', ({(783, 41, 783, 52): '0 + d_z_tmp / 2', (783, 53, 783, 67): 'z_reg_orig_top', (783, 68, 783, 70): 'nz'}, {}), '(0 + d_z_tmp / 2, z_reg_orig_top, nz)', True, 'import numpy as np\n'), ((786, 29, 786, 56), 'numpy.hstack', 'np.hstack', ({(786, 39, 786, 55): '[[0], z_reg_orig]'}, {}), '([[0], z_reg_orig])', True, 'import numpy as np\n'), ((787, 33, 787, 74), 'numpy.hstack', 'np.hstack', ({(787, 43, 787, 73): '[var_orig_col[0], var_orig_col]'}, {}), '([var_orig_col[0], var_orig_col])', True, 'import numpy as np\n'), ((792, 20, 792, 70), 'scipy.interpolate.interp1d', 'interp1d', (), '', False, 'from scipy.interpolate import interp1d\n'), ((1068, 25, 1068, 56), 'numpy.transpose', 'np.transpose', ({(1068, 39, 1068, 43): 'w_3d', (1068, 46, 1068, 55): '(0, 2, 1)'}, {}), '(w_3d, (0, 2, 1))', True, 'import numpy as np\n'), ((1069, 25, 1069, 56), 'numpy.transpose', 'np.transpose', ({(1069, 38, 1069, 43): 'ql_3d', (1069, 46, 1069, 55): '(0, 2, 1)'}, {}), '(ql_3d, (0, 2, 1))', True, 'import numpy as np\n'), ((1070, 25, 1070, 56), 'numpy.transpose', 'np.transpose', ({(1070, 38, 1070, 44): 'var_3d', (1070, 46, 1070, 55): '(0, 2, 1)'}, {}), '(var_3d, (0, 2, 1))', True, 'import numpy as np\n'), ((1085, 16, 1085, 28), 'gc.collect', 'gc.collect', ({}, {}), '()', False, 'import gc\n'), ((1101, 24, 1101, 50), 'numpy.sqrt', 'np.sqrt', ({(1101, 32, 1101, 49): 'u_ref ** 2 + v_ref ** 2'}, {}), '(u_ref ** 2 + v_ref ** 2)', True, 'import numpy as np\n'), ((1108, 23, 1108, 69), 'numpy.linspace', 'np.linspace', ({(1108, 35, 1108, 36): '0', (1108, 37, 1108, 60): '2 * nx * ny * time_resolution', (1108, 61, 1108, 68): '2 * nx * ny'}, {}), '(0, 2 * nx * ny * time_resolution, 2 * nx * ny)', True, 'import numpy as np\n'), ((1115, 25, 1115, 41), 'numpy.zeros', 'np.zeros', ({(1115, 34, 1115, 40): '(nz, 1)'}, {}), '((nz, 1))', True, 'import numpy as np\n'), ((1116, 25, 1116, 41), 'numpy.zeros', 'np.zeros', ({(1116, 34, 1116, 40): '(nz, 1)'}, {}), '((nz, 1))', True, 'import numpy as np\n'), ((1117, 25, 1117, 41), 'numpy.zeros', 'np.zeros', ({(1117, 34, 1117, 40): '(nz, 1)'}, {}), '((nz, 1))', True, 'import numpy as np\n'), ((1118, 25, 1118, 36), 'numpy.zeros', 'np.zeros', ({(1118, 34, 1118, 35): '1'}, {}), '(1)', True, 'import numpy as np\n'), ((1146, 15, 1146, 33), 'numpy.max', 'np.max', ({(1146, 22, 1146, 32): 'ql_2d[:, (t)]'}, {}), '(ql_2d[:, (t)])', True, 'import numpy as np\n'), ((1147, 27, 1147, 55), 'numpy.argmax', 'np.argmax', ({(1147, 37, 1147, 54): 'ql_2d[:, (t)] > ql_min'}, {}), '(ql_2d[:, (t)] > ql_min)', True, 'import numpy as np\n'), ((1188, 29, 1188, 71), 'numpy.linspace', 'np.linspace', ({(1188, 41, 1188, 52): '0 + d_z_tmp / 2', (1188, 53, 1188, 67): 'z_reg_orig_top', (1188, 68, 1188, 70): 'nz'}, {}), '(0 + d_z_tmp / 2, z_reg_orig_top, nz)', True, 'import numpy as np\n'), ((1191, 29, 1191, 56), 'numpy.hstack', 'np.hstack', ({(1191, 39, 1191, 55): '[[0], z_reg_orig]'}, {}), '([[0], z_reg_orig])', True, 'import numpy as np\n'), ((1192, 46, 1192, 105), 'numpy.hstack', 'np.hstack', ({(1192, 56, 1192, 104): '[scaling_factor_x_prof[0], scaling_factor_x_prof]'}, {}), '([scaling_factor_x_prof[0], scaling_factor_x_prof])', True, 'import numpy as np\n'), ((1193, 46, 1193, 105), 'numpy.hstack', 'np.hstack', ({(1193, 56, 1193, 104): '[scaling_factor_y_prof[0], scaling_factor_y_prof]'}, {}), '([scaling_factor_y_prof[0], scaling_factor_y_prof])', True, 'import numpy as np\n'), ((1197, 22, 1197, 85), 'scipy.interpolate.interp1d', 'interp1d', (), '', False, 'from scipy.interpolate import interp1d\n'), ((1198, 22, 1198, 85), 'scipy.interpolate.interp1d', 'interp1d', (), '', False, 'from scipy.interpolate import interp1d\n'), ((1238, 30, 1238, 84), 'numpy.min', 'np.min', ({(1238, 37, 1238, 83): 'cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]]'}, {}), '(cl_base[cbl_cl_idx[t_chord_begin:t_chord_end]])', True, 'import numpy as np\n'), ((1697, 25, 1697, 56), 'numpy.transpose', 'np.transpose', ({(1697, 39, 1697, 43): 'w_3d', (1697, 46, 1697, 55): '(0, 2, 1)'}, {}), '(w_3d, (0, 2, 1))', True, 'import numpy as np\n'), ((1698, 25, 1698, 56), 'numpy.transpose', 'np.transpose', ({(1698, 38, 1698, 43): 'ql_3d', (1698, 46, 1698, 55): '(0, 2, 1)'}, {}), '(ql_3d, (0, 2, 1))', True, 'import numpy as np\n'), ((1699, 25, 1699, 56), 'numpy.transpose', 'np.transpose', ({(1699, 38, 1699, 44): 'var_3d', (1699, 46, 1699, 55): '(0, 2, 1)'}, {}), '(var_3d, (0, 2, 1))', True, 'import numpy as np\n'), ((1721, 16, 1721, 28), 'gc.collect', 'gc.collect', ({}, {}), '()', False, 'import gc\n'), ((1724, 23, 1724, 53), 'numpy.linspace', 'np.linspace', ({(1724, 35, 1724, 36): '0', (1724, 37, 1724, 44): '2 * nx * ny', (1724, 45, 1724, 52): '2 * nx * ny'}, {}), '(0, 2 * nx * ny, 2 * nx * ny)', True, 'import numpy as np\n'), ((1743, 25, 1743, 41), 'numpy.zeros', 'np.zeros', ({(1743, 34, 1743, 40): '(nz, 1)'}, {}), '((nz, 1))', True, 'import numpy as np\n'), ((1744, 25, 1744, 41), 'numpy.zeros', 'np.zeros', ({(1744, 34, 1744, 40): '(nz, 1)'}, {}), '((nz, 1))', True, 'import numpy as np\n'), ((1745, 25, 1745, 41), 'numpy.zeros', 'np.zeros', ({(1745, 34, 1745, 40): '(nz, 1)'}, {}), '((nz, 1))', True, 'import numpy as np\n'), ((1746, 25, 1746, 36), 'numpy.zeros', 'np.zeros', ({(1746, 34, 1746, 35): '1'}, {}), '(1)', True, 'import numpy as np\n'), ((1774, 15, 1774, 33), 'numpy.max', 'np.max', ({(1774, 22, 1774, 32): 'ql_2d[:, (t)]'}, {}), '(ql_2d[:, (t)])', True, 'import numpy as np\n'), ((1775, 27, 1775, 55), 'numpy.argmax', 'np.argmax', ({(1775, 37, 1775, 54): 'ql_2d[:, (t)] > ql_min'}, {}), '(ql_2d[:, (t)] > ql_min)', True, 'import numpy as np\n'), ((1813, 28, 1813, 47), 'numpy.mean', 'np.mean', ({(1813, 36, 1813, 46): 'bflux_s_1d'}, {}), '(bflux_s_1d)', True, 'import numpy as np\n'), ((473, 34, 473, 82), 'numpy.mean', 'np.mean', ({(473, 42, 473, 81): 'bflux_s_1d[idx_beg_chord:idx_end_chord]'}, {}), '(bflux_s_1d[idx_beg_chord:idx_end_chord])', True, 'import numpy as np\n'), ((475, 35, 475, 84), 'numpy.mean', 'np.mean', ({(475, 43, 475, 83): 'qtflux_s_1d[idx_beg_chord:idx_end_chord]'}, {}), '(qtflux_s_1d[idx_beg_chord:idx_end_chord])', True, 'import numpy as np\n'), ((477, 36, 477, 86), 'numpy.mean', 'np.mean', ({(477, 44, 477, 85): 'thlflux_s_1d[idx_beg_chord:idx_end_chord]'}, {}), '(thlflux_s_1d[idx_beg_chord:idx_end_chord])', True, 'import numpy as np\n'), ((502, 35, 502, 72), 'numpy.percentile', 'np.percentile', ({(502, 49, 502, 59): 'w_base_vec', (502, 60, 502, 71): 'percentiles'}, {}), '(w_base_vec, percentiles)', True, 'import numpy as np\n'), ((512, 48, 512, 82), 'numpy.vstack', 'np.vstack', ({(512, 58, 512, 81): '[chord_w_per, tmp_w_per]'}, {}), '([chord_w_per, tmp_w_per])', True, 'import numpy as np\n'), ((513, 48, 513, 85), 'numpy.vstack', 'np.vstack', ({(513, 58, 513, 84): '[chord_w_per, tmp_w_per_up]'}, {}), '([chord_w_per, tmp_w_per_up])', True, 'import numpy as np\n'), ((751, 20, 751, 57), 'numpy.floor', 'np.floor', ({(751, 29, 751, 56): 'idx_end_chord - idx_beg_chord'}, {}), '(idx_end_chord - idx_beg_chord)', True, 'import numpy as np\n'), ((1202, 71, 1202, 102), 'numpy.mean', 'np.mean', ({(1202, 79, 1202, 101): 'scaling_factor_x_inter'}, {}), '(scaling_factor_x_inter)', True, 'import numpy as np\n'), ((1203, 55, 1203, 86), 'numpy.mean', 'np.mean', ({(1203, 63, 1203, 85): 'scaling_factor_y_inter'}, {}), '(scaling_factor_y_inter)', True, 'import numpy as np\n'), ((1806, 20, 1806, 30), 'sys.exit', 'sys.exit', ({}, {}), '()', False, 'import sys\n'), ((1820, 32, 1820, 52), 'numpy.mean', 'np.mean', ({(1820, 40, 1820, 51): 'qtflux_s_1d'}, {}), '(qtflux_s_1d)', True, 'import numpy as np\n'), ((1823, 31, 1823, 52), 'numpy.mean', 'np.mean', ({(1823, 39, 1823, 51): 'thlflux_s_1d'}, {}), '(thlflux_s_1d)', True, 'import numpy as np\n'), ((462, 30, 462, 71), 'numpy.mean', 'np.mean', ({(462, 38, 462, 70): 'u_2d[cl_base[ch_idx_l], ch_idx_l]'}, {}), '(u_2d[cl_base[ch_idx_l], ch_idx_l])', True, 'import numpy as np\n'), ((463, 30, 463, 71), 'numpy.mean', 'np.mean', ({(463, 38, 463, 70): 'v_2d[cl_base[ch_idx_l], ch_idx_l]'}, {}), '(v_2d[cl_base[ch_idx_l], ch_idx_l])', True, 'import numpy as np\n'), ((464, 30, 464, 56), 'numpy.sqrt', 'np.sqrt', ({(464, 38, 464, 55): 'u_ref ** 2 + v_ref ** 2'}, {}), '(u_ref ** 2 + v_ref ** 2)', True, 'import numpy as np\n'), ((470, 38, 470, 86), 'numpy.percentile', 'np.percentile', ({(470, 52, 470, 69): 'cl_base[ch_idx_l]', (470, 70, 470, 85): 'base_percentile'}, {}), '(cl_base[ch_idx_l], base_percentile)', True, 'import numpy as np\n'), ((485, 40, 485, 81), 'numpy.mean', 'np.mean', ({(485, 48, 485, 80): 'w_2d[cl_base[ch_idx_l], ch_idx_l]'}, {}), '(w_2d[cl_base[ch_idx_l], ch_idx_l])', True, 'import numpy as np\n'), ((486, 35, 486, 78), 'numpy.mean', 'np.mean', ({(486, 43, 486, 77): 'w_2d[cl_base[ch_idx_l] - 1, ch_idx_l]'}, {}), '(w_2d[cl_base[ch_idx_l] - 1, ch_idx_l])', True, 'import numpy as np\n'), ((487, 37, 487, 82), 'numpy.mean', 'np.mean', ({(487, 45, 487, 81): 'thl_2d[cl_base[ch_idx_l] - 1, ch_idx_l]'}, {}), '(thl_2d[cl_base[ch_idx_l] - 1, ch_idx_l])', True, 'import numpy as np\n'), ((493, 40, 493, 80), 'numpy.mean', 'np.mean', ({(493, 48, 493, 79): 'thl_2d[cl_base_25_idx, ch_idx_l]'}, {}), '(thl_2d[cl_base_25_idx, ch_idx_l])', True, 'import numpy as np\n'), ((494, 40, 494, 80), 'numpy.mean', 'np.mean', ({(494, 48, 494, 79): 'thl_2d[cl_base_75_idx, ch_idx_l]'}, {}), '(thl_2d[cl_base_75_idx, ch_idx_l])', True, 'import numpy as np\n'), ((495, 36, 495, 80), 'numpy.mean', 'np.mean', ({(495, 44, 495, 79): 'qt_2d[cl_base[ch_idx_l] - 1, ch_idx_l]'}, {}), '(qt_2d[cl_base[ch_idx_l] - 1, ch_idx_l])', True, 'import numpy as np\n'), ((496, 39, 496, 78), 'numpy.mean', 'np.mean', ({(496, 47, 496, 77): 'qt_2d[cl_base_75_idx, ch_idx_l]'}, {}), '(qt_2d[cl_base_75_idx, ch_idx_l])', True, 'import numpy as np\n'), ((497, 39, 497, 78), 'numpy.mean', 'np.mean', ({(497, 47, 497, 77): 'qt_2d[cl_base_25_idx, ch_idx_l]'}, {}), '(qt_2d[cl_base_25_idx, ch_idx_l])', True, 'import numpy as np\n'), ((498, 40, 498, 82), 'numpy.sum', 'np.sum', ({(498, 47, 498, 81): 'w_2d[cl_base[ch_idx_l] - 1, ch_idx_l]'}, {}), '(w_2d[cl_base[ch_idx_l] - 1, ch_idx_l])', True, 'import numpy as np\n'), ((501, 38, 501, 73), 'numpy.mean', 'np.mean', ({(501, 46, 501, 72): 'w_base_vec[w_base_vec > 0.0]'}, {}), '(w_base_vec[w_base_vec > 0.0])', True, 'import numpy as np\n'), ((505, 39, 505, 92), 'numpy.percentile', 'np.percentile', ({(505, 53, 505, 79): 'w_base_vec[w_base_vec > 0.0]', (505, 80, 505, 91): 'percentiles'}, {}), '(w_base_vec[w_base_vec > 0.0], percentiles)', True, 'import numpy as np\n'), ((507, 39, 507, 62), 'numpy.zeros', 'np.zeros', ({(507, 48, 507, 61): 'n_percentiles'}, {}), '(n_percentiles)', True, 'import numpy as np\n'), ((1802, 52, 1802, 102), 'numpy.percentile', 'np.percentile', ({(1802, 66, 1802, 85): 'cl_base[cbl_cl_idx]', (1802, 86, 1802, 101): 'base_percentile'}, {}), '(cl_base[cbl_cl_idx], base_percentile)', True, 'import numpy as np\n'), ((517, 42, 517, 65), 'numpy.mean', 'np.mean', ({(517, 50, 517, 64): 't_1d[ch_idx_l]'}, {}), '(t_1d[ch_idx_l])', True, 'import numpy as np\n'), ((1280, 56, 1280, 134), 'numpy.percentile', 'np.percentile', ({(1280, 70, 1280, 117): 'cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]]', (1280, 118, 1280, 133): 'base_percentile'}, {}), '(cl_base[cbl_cl_idx[t_chord_begin:t_cloudy_idx]], base_percentile)', True, 'import numpy as np\n'), ((1287, 40, 1287, 88), 'numpy.mean', 'np.mean', ({(1287, 48, 1287, 87): 'bflux_s_1d[idx_beg_chord:idx_end_chord]'}, {}), '(bflux_s_1d[idx_beg_chord:idx_end_chord])', True, 'import numpy as np\n'), ((1339, 27, 1339, 41), 'numpy.mean', 'np.mean', ({(1339, 35, 1339, 40): 'w_tmp'}, {}), '(w_tmp)', True, 'import numpy as np\n'), ((490, 63, 490, 111), 'numpy.percentile', 'np.percentile', ({(490, 77, 490, 94): 'cl_base[ch_idx_l]', (490, 95, 490, 110): 'base_percentile'}, {}), '(cl_base[ch_idx_l], base_percentile)', True, 'import numpy as np\n'), ((1263, 39, 1263, 116), 'numpy.abs', 'np.abs', ({(1263, 46, 1263, 115): '(t_1d - (time_beg_chord - curtain_extra * (time_end_chord - time_beg_chord)))'}, {}), '(t_1d - (time_beg_chord - curtain_extra * (time_end_chord -\n    time_beg_chord)))', True, 'import numpy as np\n'), ((1264, 39, 1264, 116), 'numpy.abs', 'np.abs', ({(1264, 46, 1264, 115): '(t_1d - (time_end_chord + curtain_extra * (time_end_chord - time_beg_chord)))'}, {}), '(t_1d - (time_end_chord + curtain_extra * (time_end_chord -\n    time_beg_chord)))', True, 'import numpy as np\n'), ((1294, 44, 1294, 93), 'numpy.mean', 'np.mean', ({(1294, 52, 1294, 92): 'qtflux_s_1d[idx_beg_chord:idx_end_chord]'}, {}), '(qtflux_s_1d[idx_beg_chord:idx_end_chord])', True, 'import numpy as np\n'), ((1297, 43, 1297, 93), 'numpy.mean', 'np.mean', ({(1297, 51, 1297, 92): 'thlflux_s_1d[idx_beg_chord:idx_end_chord]'}, {}), '(thlflux_s_1d[idx_beg_chord:idx_end_chord])', True, 'import numpy as np\n'), ((1342, 29, 1342, 43), 'numpy.mean', 'np.mean', ({(1342, 37, 1342, 42): 'w_tmp'}, {}), '(w_tmp)', True, 'import numpy as np\n'), ((1360, 38, 1360, 79), 'numpy.mean', 'np.mean', ({(1360, 46, 1360, 78): 'u_2d[cl_base[ch_idx_l], ch_idx_l]'}, {}), '(u_2d[cl_base[ch_idx_l], ch_idx_l])', True, 'import numpy as np\n'), ((1361, 38, 1361, 79), 'numpy.mean', 'np.mean', ({(1361, 46, 1361, 78): 'v_2d[cl_base[ch_idx_l], ch_idx_l]'}, {}), '(v_2d[cl_base[ch_idx_l], ch_idx_l])', True, 'import numpy as np\n'), ((1362, 38, 1362, 64), 'numpy.sqrt', 'np.sqrt', ({(1362, 46, 1362, 63): 'u_ref ** 2 + v_ref ** 2'}, {}), '(u_ref ** 2 + v_ref ** 2)', True, 'import numpy as np\n'), ((491, 63, 491, 111), 'numpy.percentile', 'np.percentile', ({(491, 77, 491, 94): 'cl_base[ch_idx_l]', (491, 95, 491, 110): 'base_percentile'}, {}), '(cl_base[ch_idx_l], base_percentile)', True, 'import numpy as np\n'), ((1346, 59, 1346, 73), 'numpy.mean', 'np.mean', ({(1346, 67, 1346, 72): 'w_tmp'}, {}), '(w_tmp)', True, 'import numpy as np\n'), ((1378, 35, 1378, 49), 'numpy.mean', 'np.mean', ({(1378, 43, 1378, 48): 'w_tmp'}, {}), '(w_tmp)', True, 'import numpy as np\n'), ((1372, 47, 1372, 80), 'numpy.abs', 'np.abs', ({(1372, 54, 1372, 79): '(chord_length - mid_bin_size)'}, {}), '(chord_length - mid_bin_size)', True, 'import numpy as np\n'), ((1381, 37, 1381, 51), 'numpy.mean', 'np.mean', ({(1381, 45, 1381, 50): 'w_tmp'}, {}), '(w_tmp)', True, 'import numpy as np\n'), ((1385, 67, 1385, 81), 'numpy.mean', 'np.mean', ({(1385, 75, 1385, 80): 'w_tmp'}, {}), '(w_tmp)', True, 'import numpy as np\n')]