Subversion Repositories lagranto.ecmwf

Rev

Blame | Last modification | View Log | Download | RSS feed

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#################################################
#    Program calculate difference between       #
#    time interval. Calls the shell makeFile.sh #
#     to change file format                     #
#                                               #
#    by Lukas Langhamer                         #    
#    Innsbruck, Feb. 2017                       # 
#                                               #
#################################################


import sys
import numpy as np
import pandas as pd
import argparse
import copy 
import csv
import subprocess 

def main(argv):    
    
    
    filename = ""
    
    parser = argparse.ArgumentParser(description="Calculate difference between time interval")
    parser.add_argument("file", type=str, help="filename")
    parser.add_argument("-v", "--variable", type=str, help="Choose a variable [-v p]")
    parser.add_argument("-o", "--mean", type=str, help="Take mean between time interval of not choosen variable [-o mean]")
    args = parser.parse_args()

    
    filename = args.file
    
    # read lagranto ASCII File
    data = pd.read_csv(filename, sep=' ', skipfooter=0, skiprows=[0,3], skipinitialspace=True)
    
    
    if args.variable is None:
        print ("choose variable: -v [option]")
        return 0
    else:
        var = args.variable


    t_start = int(min(abs(data.time)))          # starting trajectory time 0.0
    t_end = int(max(abs(data.time)))            # ending trajectory time
    timestep = int(data.time[1]-data.time[0])   # timestep - new file will be shorter by one timestep
    timestep_min = timestep * 60                # in min
    
    
    # copy input data
    copy_a = copy.deepcopy(data)
    copy_b = copy.deepcopy(data)
    

    #drop end time
    copy_a.loc[copy_a['time'] == -t_end] = np.nan
    copy_a = copy_a.dropna()
    
    #drop starting time
    copy_b.loc[copy_b['time'] == t_start] = np.nan
    copy_b = copy_b.dropna()
    
    #change index
    copy_a.index = range(len(copy_a))
    copy_b.index = range(len(copy_b))
    
    # make difference of choosen variable (var) between each time step
    diff_var = copy.deepcopy(var)
    diff_var = copy_a[var] - copy_b[var]
    diff_var_name = "delta_%(1)s" %{'1': var} # assign new variable name

    
    
    # You can choose between two option:
    # 1.) all variables stay the same
    # 2.) mean between 2 time steps of all variables
    
    if args.mean is None:                                   # 1st option (default)
        print('Choosen option: None - unchanged variables')
        copy_a['diff_var'] = diff_var                       # add diff_var to copy
        copy_a.rename(columns={'diff_var' : diff_var_name},inplace=True)
        
        # Make Output
        output1 = "%s_diff_cp"% (filename)
        copy_a.to_csv(output1, sep=' ',index=None)
        
    else:                                                  # 2nd option 
        print('Choosen option: Calculate Mean betwen time steps')
        
        # create new DataFrame (df)
        columns = ['time']              # define 1st column time
        df = pd.DataFrame(columns=columns)
        df.time = copy_a.time 
        
        # make a loop arround all available fields in file. lon, lat, p etc.
        for x in range(1,data.shape[1]):
            
            add_fld = list(data[[x]])
            add_fld = str(add_fld[0])
            mean_cp = ( copy_a[add_fld]+copy_b[add_fld] ) / 2    # calculate mean
    
            # add to DataFrame
            df['mean_var'] = mean_cp
            df.rename(columns={'mean_var' : add_fld},inplace=True)
        
        # add diff_var to DataFrame
        df['diff_var'] = diff_var
        df.rename(columns={'diff_var' : diff_var_name},inplace=True)
        
        #output file
        output1 = "%s_diff_cp"% (filename)
        df.to_csv(output1, sep=' ',index=None)
    
 
    
    
    # Conver output file to 'LAGRANTO-File. This requires Shell-Skript makeFile.sh ' 
    print ('Produce  %(1)s_%(2)s' %{'1': filename, '2':diff_var_name})
    
    subprocess.call("./makeFile.sh %(1)s %(2)s %(3)i %(4)s" %{'1': filename, '2': output1, '3': timestep_min, '4':diff_var_name} , shell=True)
    subprocess.call("rm %(1)s" %{'1': output1} , shell=True)
    
    
    

if __name__ == '__main__':
    main(sys.argv[1:])