source: lmdz_wrf/trunk/tools/generic.py @ 1949

Last change on this file since 1949 was 1919, checked in by lfita, 7 years ago

Adding example and removing spurious printing test from 'ASCIIfile_stats'

File size: 16.6 KB
Line 
1# Wrapper for the generic functions written in python from 'generic_tools.py'
2# L. Fita, LMD. June 2016
3# Python to manage netCDF files.
4# From L. Fita work in different places: LMD (France)
5# More information at: http://www.xn--llusfb-5va.cat/python/PyNCplot
6#
7# pyNCplot and its component generic.py comes with ABSOLUTELY NO WARRANTY.
8# This work is licendes under a Creative Commons
9#   Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0)
10#
11
12from optparse import OptionParser
13import numpy as np
14import datetime as dt
15import generic_tools as gen
16
17main = 'generic.py'
18errormsg = 'ERROR -- error -- ERROR -- error'
19warnmsg = 'WARNING -- warning --WARNING -- warning'
20import os
21import re
22
23# ASCIIfile_stats: Function to provide the statistics of a series of values from an ASCII file
24# coincident_CFtimes: Function to make coincident times for two different sets of CFtimes
25# count_cond: Function to count values of a variable which attain a condition
26# datetimeStr_conversion: Function to transform a string date to an another date object
27# grid_combinations: Function to provide all the possible grid points combination for a given pair of values
28#   x,y= pair of grid points
29# interpolate_locs: Function to provide interpolate locations on a given axis
30# PolyArea: Function to compute the area of the polygon following 'Shoelace formula'
31# radial_points: Function to provide a number of grid point positions for a given angle
32# radius_dist: Function to generate a matrix with the distance at a given point
33# rmNOnum: Removing from a string all that characters which are not numbers
34# running_mean: Function to compute a running mean of a series of values
35# significant_decomposition: Function to decompose a given number by its signifcant potencies
36# squared_radial: Function to provide the series of radii as composite of pairs (x,y) of gid cells
37#   Npt= largest amount of grid points on x and y directions
38# table_tex_file: Function to write into a file a LaTeX tabular from a table of values
39# unitsDate: Function to know how many units of time are from a given pair of dates
40# variables_values: Function to provide values to plot the different variables values from ASCII file
41# wdismean: Function to compute the mean value weighted to its 4 distances
42# WRFsetup: Function to check the set-up of a series of model namelist
43
44# Character to split passed values
45cS = ','
46# Character to split a serie of values
47cV = '@'
48# Character for spaces
49cE = '!'
50
51# List of available operations
52operations=['ASCIIfile_stats', 'coincident_CFtimes', 'count_cond',                   \
53  'datetimeStr_conversion',                                                          \
54  'grid_combinations',                                                               \
55  'interpolate_locs', 'latex_fig_array', 'list_operations', 'PolyArea',              \
56  'radial_points', 'radius_dist',                                                    \
57  'rmNOnum', 'running_mean',                                                         \
58  'significant_decomposition', 'squared_radial',                                     \
59  'table_tex_file', 'unitsDate', 'variables_values', 'wdismean', 'WRFsetup']
60
61hundredvals = '0'
62for i in range(1,100): hundredvals = hundredvals + cV + str(i)
63
64vs100 = '0@1@2@3@4@5@6@7@8@9@10@11@12@13@14@15@16@17@18@19@20@21@22@23@24@25@26@27'
65vs100 = vs100 + '@28@29@30@31@32@33@34@35@36@37@38@39@40@41@42@43@44@45@46@47@48@49'
66vs100 = vs100 + '@50@51@52@53@54@55@56@57@58@59@60@61@62@63@64@65@66@67@68@69@70@71'
67va100 = vs100 + '@72@73@74@75@76@77@78@79@80@81@82@83@84@85@86@87@88@89@90@91@92@93'
68va100 = vs100 + '@94@95@96@97@98@99'
69
70## e.g. # generic.py -o 'coincident_CFtimes' -S '0@1@2@3@4@5@6@7@8@9,seconds since 1949-12-01 00:00:00,hours since 1949-12-01 00:00:00'
71## e.g. # generic.py -o count_cond -S 0@1@2@3@4@5@6@7@8@9,4,le
72## e.g. # generic.py -o datetimeStr_conversion -S '1976-02-17_08:32:05,Y-m-d_H:M:S,matYmdHMS'
73## e.g. # generic.py -o grid_combinations -S 1,2
74## e.g. # generic.py -o interpolate_locs -S -1.2@2.4@5.6@7.8@12.0,0.5@2.5,lin
75## e.g. # generic.py -o PolyArea -S -0.5@0.5@0.5@-0.5,0.5@0.5@-0.5@-0.5
76## e.g. # generic.py -o radial_points -S 0.785398163397,5
77## e.g. # generic.py -o radius_dist -S 3,5,2,2
78## e.g. # generic.py -o rmNOnum -S LMD123IPSL
79## e.g. # generic.py -o significant_decomposition -S 3.576,-2
80## e.g. # generic.py -o table_tex_file -S '5,3,0@5@10@1@6@11@2@7@12@3@8@13@4@9@14,!@a@b@c@d@e,i@ii@iii,table.tex'
81## e.g. # generic.py -o unitsDate -S '19490101000000,19760217082932,second'
82## e.g. # generic.py -o running_mean -S 0@1@2@3@4@5@6@7@8@9,10
83## e.g. # generic.py -o squared_radial -S 3
84## e.g. # generic.py -o variables_values -S 'hus'
85## e.g. # generic.py -o wdismean -S 0.005@0.005,0.@1.@2.@3.
86## e.g. # generic.py -o WRFsetup -S '/home/lluis/estudios/RELAMPAGO/SimCoor/UBA/namelist.input@/home/lluis/estudios/RELAMPAGO/SimCoor/SMN/namelist.input@/home/lluis/estudios/RELAMPAGO/SimCoor/NOA-IERSD/namelist.input@/home/lluis/estudios/RELAMPAGO/SimCoor/UBAmili/namelist.input,basic,textabrow'
87## e.g. # generic.py -o ASCIIfile_stats -S times_CDXWRF1.dat,#,R
88
89operationnames = "'" + gen.numVector_String(operations, "', '") + "'"
90valuesinf = "'" + cS + "' list of values to use according to the operation ('" + cV +\
91  "' for list of values)"
92
93parser = OptionParser()
94parser.add_option("-o", "--operation", type='choice', dest="operation", 
95  choices=operations, help="operation to make: " + operationnames, metavar="OPER")
96parser.add_option("-S", "--valueS (when applicable)", dest="values", 
97  help=valuesinf, metavar="VALUES")
98(opts, args) = parser.parse_args()
99
100#######    #######
101## MAIN
102    #######
103oper = opts.operation
104
105if oper == 'list_operations':
106# From: http://www.diveintopython.net/power_of_introspection/all_together.html
107    object = gen
108    for opern in operations:
109        if  opern != 'list_operations': 
110            print opern + '_______ ______ _____ ____ ___ __ _'
111            print getattr(object, opern).__doc__
112
113elif oper == 'coincident_CFtimes':
114    Nvals = 3
115    vals = opts.values.split(cS)
116    if vals[0] == 'h':
117        print gen.coincident_CFtimes.__doc__
118        quit(-1)
119    else:
120        if len(vals) != Nvals:
121            print errormsg
122            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
123              len(vals), ' has passed!!'
124            print gen.coincident_CFtimes.__doc__
125            quit(-1)
126        vals0 = np.array(vals[0].split(cV), dtype=np.float)
127        print gen.coincident_CFtimes(vals0, vals[1], vals[2])
128
129elif oper == 'count_cond':
130    Nvals = 3
131    vals = opts.values.split(cS)
132    if vals[0] == 'h':
133        print gen.count_cond.__doc__
134        quit(-1)
135    else:
136        if len(vals) != Nvals:
137            print errormsg
138            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
139              len(vals), ' has passed!!'
140            print gen.count_cond.__doc__
141            quit(-1)
142        vals0 = np.array(vals[0].split(cV), dtype=np.float)
143        print gen.count_cond(np.array(vals[0].split(cV), dtype=np.float),           \
144          np.float(vals[1]), vals[2])
145
146elif oper == 'datetimeStr_conversion':
147    Nvals = 3
148    vals = opts.values.split(cS)
149    newvals = []
150    if vals[1] == 'cfTime':
151        newvals.append(vals[0])
152        newvals.append(vals[1]+','+vals[2])
153        if vals[2] == 'cfTime': newvals.append(vals[3]+','+vals[4])
154        vals = list(newvals)
155    if vals[2] == 'cfTime':
156        newvals.append(vals[0])
157        newvals.append(vals[1])
158        newvals.append(vals[2]+','+vals[3])
159        vals = list(newvals)
160
161    if vals[0] == 'h':
162        print gen.datetimeStr_conversion.__doc__
163        quit(-1)
164    else:
165        if len(vals) != Nvals:
166            print errormsg
167            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
168              len(vals), ' has passed!!'
169            print gen.datetimeStr_conversion.__doc__
170            quit(-1)
171        print gen.datetimeStr_conversion(vals[0], vals[1], vals[2])
172
173#'days_period'
174
175elif oper == 'grid_combinations':
176    Nvals = 2
177    vals = opts.values.split(cS)
178    if vals[0] == 'h':
179        print gen.grid_combinations.__doc__
180        quit(-1)
181    else:
182        if len(vals) != Nvals:
183            print errormsg
184            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
185              len(vals), ' has passed!!'
186            print gen.grid_combinations.__doc__
187            quit(-1)
188
189        print gen.grid_combinations(np.int(vals[0]), np.int(vals[1]))
190
191elif oper == 'latex_fig_array':
192    vals = opts.values.split(cS)
193    if vals[0] == 'h':
194        print gen.latex_fig_array.__doc__
195        print "  NOTE: first argument as existing LaTeX file"
196        print "  figs: passing list of figures as '@' separated list"
197        print "  caption: using '!' for spaces"
198        quit(-1)
199    else:
200        expectargs = '[latexfile],[figs],[figcaption],[figlabel],[dist],[refsize],'+ \
201         '[width],[height],[dorest]'
202        gen.check_arguments(oper,opts.values,expectargs,cS)
203
204        objf = open(vals[0], 'a')
205
206        figs = vals[1].split('@')
207        caption = vals[2].replace('!',' ')
208        gen.latex_fig_array(figs, objf, caption, vals[3], dist=vals[4],              \
209          refsize=vals[5], width=vals[6], height=vals[7], dorest=vals[8])
210        objf.write('\\end{document}\n')
211        objf.close()
212 
213elif oper == 'interpolate_locs':
214    Nvals = 3
215    vals = opts.values.split(cS)
216    if vals[0] == 'h':
217        print gen.interpolate_locs.__doc__
218        quit(-1)
219    else:
220        if len(vals) != Nvals:
221            print errormsg
222            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
223              len(vals), ' has passed!!'
224            print gen.interpolate_locs.__doc__
225            quit(-1)
226        vals0 = np.array(vals[0].split(cV), dtype=np.float)
227        vals1 = np.array(vals[1].split(cV), dtype=np.float)
228
229        print gen.interpolate_locs(vals0, vals1, vals[2])
230
231elif oper == 'PolyArea':
232    Nvals = 2
233    vals = opts.values.split(cS)
234    if vals[0] == 'h':
235        print gen.PolyArea.__doc__
236        quit(-1)
237    else:
238        if len(vals) != Nvals:
239            print errormsg
240            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
241              len(vals), ' has passed!!'
242            print gen.PolyArea.__doc__
243            quit(-1)
244        xvals = np.array(vals[0].split(cV), dtype=np.float)
245        yvals = np.array(vals[1].split(cV), dtype=np.float)
246
247        print gen.PolyArea(xvals, yvals)
248
249elif oper == 'radial_points':
250    Nvals = 2
251    vals = opts.values.split(cS)
252    if vals[0] == 'h':
253        print gen.radial_points.__doc__
254        quit(-1)
255    else:
256        if len(vals) != Nvals:
257            print errormsg
258            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
259              len(vals), ' has passed!!'
260            print gen.radial_points.__doc__
261            quit(-1)
262        print gen.radial_points(np.float(vals[0]), int(vals[1]))
263
264elif oper == 'radius_dist':
265    Nvals = 1
266    vals = opts.values.split(cS)
267    if vals[0] == 'h':
268        print gen.radius_dist.__doc__
269        quit(-1)
270    else:
271        if len(vals) != Nvals:
272            print errormsg
273            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
274              len(vals), ' has passed!!'
275            print gen.radius_dist.__doc__
276            quit(-1)
277        print gen.radius_dist(int(vals[0]), int(vals[1]), int(vals[2]), int(vals[2]))
278
279elif oper == 'rmNOnum':
280    Nvals = 1
281    vals = opts.values.split(cS)
282    if vals[0] == 'h':
283        print gen.rmNOnum.__doc__
284        quit(-1)
285    else:
286        if len(vals) != Nvals:
287            print errormsg
288            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
289              len(vals), ' has passed!!'
290            print gen.rmNOnum.__doc__
291            quit(-1)
292        print gen.rmNOnum(vals[0])
293
294elif oper == 'running_mean':
295    Nvals = 2
296    vals = opts.values.split(cS)
297    if vals[0] == 'h':
298        print gen.running_mean.__doc__
299        quit(-1)
300    else:
301        if len(vals) != Nvals:
302            print errormsg
303            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
304              len(vals), ' has passed!!'
305            print gen.running_mean.__doc__
306            quit(-1)
307        print gen.running_mean(np.array(vals[0].split(cV), dtype=np.float), int(vals[1]))
308
309elif oper == 'significant_decomposition':
310    Nvals = 2
311    vals = opts.values.split(cS)
312    if vals[0] == 'h':
313        print gen.significant_decomposition.__doc__
314        quit(-1)
315    else:
316        if len(vals) != Nvals:
317            print errormsg
318            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
319              len(vals), ' has passed!!'
320            print gen.significant_decomposition.__doc__
321            quit(-1)
322        print gen.significant_decomposition(np.float(vals[0]), int(vals[1]))
323
324elif oper == 'squared_radial':
325    Nvals = 1
326    vals = opts.values.split(cS)
327    if vals[0] == 'h':
328        print gen.squared_radial.__doc__
329        quit(-1)
330    else:
331        if len(vals) != Nvals:
332            print errormsg
333            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
334              len(vals), ' has passed!!'
335            print gen.squared_radial.__doc__
336            quit(-1)
337        print gen.squared_radial(int(vals[0]))
338
339elif oper == 'table_tex_file':
340    Nvals = 6
341    vals = opts.values.split(cS)
342    if vals[0] == 'h':
343        print gen.table_tex_file.__doc__
344        quit(-1)
345    else:
346        if len(vals) != Nvals:
347            print errormsg
348            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
349              len(vals), ' has passed!!'
350            print gen.table_tex_file.__doc__
351            quit(-1)
352        vals2 = np.array(vals[2].split(cV),dtype=np.float).reshape(int(vals[0]),     \
353          int(vals[1]))
354        vals3 = vals[3].replace(cE,' ').split(cV)
355        vals4 = vals[4].replace(cE,' ').split(cV)
356
357        print gen.table_tex_file(int(vals[0]), int(vals[1]), vals2, vals3, vals4,    \
358          vals[5])
359
360elif oper == 'unitsDate':
361    Nvals = 3
362    vals = opts.values.split(cS)
363    if vals[0] == 'h':
364        print gen.unitsDate.__doc__
365        quit(-1)
366    else:
367        if len(vals) != Nvals:
368            print errormsg
369            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
370              len(vals), ' has passed!!'
371            print gen.unitsDate.__doc__
372            quit(-1)
373        print gen.unitsDate(vals[0], vals[1], vals[2])
374
375elif oper == 'variables_values':
376    Nvals = 1
377    vals = opts.values.split(cS)
378    if vals[0] == 'h':
379        print gen.variables_values.__doc__
380        quit(-1)
381    else:
382        if len(vals) != Nvals:
383            print errormsg
384            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
385              len(vals), ' has passed!!'
386            print gen.variables_values.__doc__
387            quit(-1)
388        result = gen.variables_values(vals[0])
389        print gen.numVector_String(result,':')
390
391elif oper == 'wdismean':
392    Nvals = 2
393    vals = opts.values.split(cS)
394    if vals[0] == 'h':
395        print gen.wdismean.__doc__
396        quit(-1)
397    else:
398        if len(vals) != Nvals:
399            print errormsg
400            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
401              len(vals), ' has passed!!'
402            print gen.wdismean.__doc__
403            quit(-1)
404        vals0 = np.array(vals[0].split(cV), dtype=np.float)
405        vals1 = np.array(vals[1].split(cV), dtype=np.float).reshape(2,2)
406
407        print gen.wdismean(vals0, vals1)
408
409elif oper == 'WRFsetup':
410    Nvals = 3
411    vals = opts.values.split(cS)
412    if vals[0] == 'h':
413        print gen.WRFsetup.__doc__
414        quit(-1)
415    else:
416        if len(vals) != Nvals:
417            print errormsg
418            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
419              len(vals), ' has passed!!'
420            print gen.WRFsetup.__doc__
421            quit(-1)
422        vals0 = vals[0].replace('@', ',')
423        vals1 = vals[1]
424        vals2 = vals[2]
425       
426        print gen.WRFsetup(vals0, vals1, vals2)
427
428elif oper == 'ASCIIfile_stats':
429    Nvals = 3
430    vals = opts.values.split(cS)
431    if vals[0] == 'h':
432        print gen.ASCIIfile_stats.__doc__
433        quit(-1)
434    else:
435        if len(vals) != Nvals:
436            print errormsg
437            print '  ' + main + ": operation '" + oper + "' requires", Nvals, 'and', \
438              len(vals), ' has passed!!'
439            print gen.ASCIIfile_stats.__doc__
440            quit(-1)
441        vals0 = vals[0]
442        vals1 = vals[1]
443        vals2 = vals[2]
444       
445        print gen.ASCIIfile_stats(vals0, vals1, vals2)
446
Note: See TracBrowser for help on using the repository browser.