Subversion Repositories lagranto.ecmwf

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
42 michaesp 1
#!/usr/bin/env python
2
# -*- coding:utf-8 -*-
3
 
4
#################################################
5
#    Program calculate difference between       #
6
#    time interval. Calls the shell makeFile.sh #
7
#     to change file format                     #
8
#                                               #
9
#    by Lukas Langhamer                         #    
10
#    Innsbruck, Feb. 2017                       # 
11
#                                               #
12
#################################################
13
 
14
 
15
import sys
16
import numpy as np
17
import pandas as pd
18
import argparse
19
import copy 
20
import csv
21
import subprocess 
22
 
23
def main(argv):    
24
 
25
 
26
    filename = ""
27
 
28
    parser = argparse.ArgumentParser(description="Calculate difference between time interval")
29
    parser.add_argument("file", type=str, help="filename")
30
    parser.add_argument("-v", "--variable", type=str, help="Choose a variable [-v p]")
31
    parser.add_argument("-o", "--mean", type=str, help="Take mean between time interval of not choosen variable [-o mean]")
32
    args = parser.parse_args()
33
 
34
 
35
    filename = args.file
36
 
37
    # read lagranto ASCII File
38
    data = pd.read_csv(filename, sep=' ', skipfooter=0, skiprows=[0,3], skipinitialspace=True)
39
 
40
 
41
    if args.variable is None:
42
        print ("choose variable: -v [option]")
43
        return 0
44
    else:
45
        var = args.variable
46
 
47
 
48
    t_start = int(min(abs(data.time)))          # starting trajectory time 0.0
49
    t_end = int(max(abs(data.time)))            # ending trajectory time
50
    timestep = int(data.time[1]-data.time[0])   # timestep - new file will be shorter by one timestep
51
    timestep_min = timestep * 60                # in min
52
 
53
 
54
    # copy input data
55
    copy_a = copy.deepcopy(data)
56
    copy_b = copy.deepcopy(data)
57
 
58
 
59
    #drop end time
60
    copy_a.loc[copy_a['time'] == -t_end] = np.nan
61
    copy_a = copy_a.dropna()
62
 
63
    #drop starting time
64
    copy_b.loc[copy_b['time'] == t_start] = np.nan
65
    copy_b = copy_b.dropna()
66
 
67
    #change index
68
    copy_a.index = range(len(copy_a))
69
    copy_b.index = range(len(copy_b))
70
 
71
    # make difference of choosen variable (var) between each time step
72
    diff_var = copy.deepcopy(var)
73
    diff_var = copy_a[var] - copy_b[var]
74
    diff_var_name = "delta_%(1)s" %{'1': var} # assign new variable name
75
 
76
 
77
 
78
    # You can choose between two option:
79
    # 1.) all variables stay the same
80
    # 2.) mean between 2 time steps of all variables
81
 
82
    if args.mean is None:                                   # 1st option (default)
83
        print('Choosen option: None - unchanged variables')
84
        copy_a['diff_var'] = diff_var                       # add diff_var to copy
85
        copy_a.rename(columns={'diff_var' : diff_var_name},inplace=True)
86
 
87
        # Make Output
88
        output1 = "%s_diff_cp"% (filename)
89
        copy_a.to_csv(output1, sep=' ',index=None)
90
 
91
    else:                                                  # 2nd option 
92
        print('Choosen option: Calculate Mean betwen time steps')
93
 
94
        # create new DataFrame (df)
95
        columns = ['time']              # define 1st column time
96
        df = pd.DataFrame(columns=columns)
97
        df.time = copy_a.time 
98
 
99
        # make a loop arround all available fields in file. lon, lat, p etc.
100
        for x in range(1,data.shape[1]):
101
 
102
            add_fld = list(data[[x]])
103
            add_fld = str(add_fld[0])
104
            mean_cp = ( copy_a[add_fld]+copy_b[add_fld] ) / 2    # calculate mean
105
 
106
            # add to DataFrame
107
            df['mean_var'] = mean_cp
108
            df.rename(columns={'mean_var' : add_fld},inplace=True)
109
 
110
        # add diff_var to DataFrame
111
        df['diff_var'] = diff_var
112
        df.rename(columns={'diff_var' : diff_var_name},inplace=True)
113
 
114
        #output file
115
        output1 = "%s_diff_cp"% (filename)
116
        df.to_csv(output1, sep=' ',index=None)
117
 
118
 
119
 
120
 
121
    # Conver output file to 'LAGRANTO-File. This requires Shell-Skript makeFile.sh ' 
122
    print ('Produce  %(1)s_%(2)s' %{'1': filename, '2':diff_var_name})
123
 
124
    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)
125
    subprocess.call("rm %(1)s" %{'1': output1} , shell=True)
126
 
127
 
128
 
129
 
130
if __name__ == '__main__':
131
    main(sys.argv[1:])