source: lmdz_wrf/trunk/tools/nc_var.py @ 2358

Last change on this file since 2358 was 2352, checked in by lfita, 6 years ago

Adding:

  • `usefile_compute_slices_stats_areaweighted': Function to compute stats of variables of a file splitting variables by slices along sets of ranges for a series of variables weighting by the area covered by each grid (defined as polygon) within the slice using pre-calculated area-weights from an existing file
  • Property svn:executable set to *
File size: 39.4 KB
Line 
1#!/usr/bin/python
2# Python to manage netCDF files.
3# From L. Fita work in different places: CCRC (Australia), LMD (France)
4# More information at: http://www.xn--llusfb-5va.cat/python/PyNCplot
5#
6# pyNCplot and its component nc_var.py comes with ABSOLUTELY NO WARRANTY.
7# This work is licendes under a Creative Commons
8#   Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0)
9#
10
11## e.g. # nc_var.py -o lonlat_polygon -f wrfout_d01_1995-01-01_00:00:00 -S star.dat -v XLONG,XLAT
12## e.g. # nc_var.py -o maskvar -f SouthAm_Climzones_masked.nc -S 'geo_em.d01.nc:LANDMASK:Time|0:0' -v region:lon,lat
13## e.g. # nc_var.py -o addDim -S 128 -f SouthAm_Climzones.nc -v Lstring
14## e.g. # nc_var.py -o addVar -S 'reg,Lstring|region_name@name!of!the!regions@-|c' -f SouthAm_Climzones.nc -v regionn
15## e.g. # nc_var.py -o varaddattr -f SouthAm_Climzones.nc -S 'grid_mapping_name|Mercator' -v Mercator
16## e.g. # nc_var.py -o varaddattrk -f SouthAm_Climzones.nc -S 'longitude_of_central_meridian|-60.0|R' -v Mercator
17## e.g. # nc_var.py -o setvar_asciivalues -S 'nombres_zonas.dat' -f SouthAm_Climzones.nc -v regionn
18## e.g. # nc_var.py -o WRF_to_newCF -f wrfout_d01_1995-01-01_00\:00\:00 -S 'XLONG:XLAT:Times:19491201000000:minutes' -v QVAPOR,T2,Q2
19## e.g. # nc_var.py -o reconstruct_matrix_from_vector -f cruncep_halfdeg_1958.nc -S 'nav_lon:nav_lat:-90.:-7.:-67.:15.:latlon:0.5:0.5:0.05' -v all
20## e.g. # nc_var.py -o nc_var.py -o CFmorzization -S 'X|west_east|XLONG,Y|south_north|XLAT,T|Time|WRFtime,Z|bottom_top|ZNU:GlobalAttr1995.inf:proj1995.inf' -f ~/PY/wrfout_d01_1995-01-01_00\:00\:00 -v QFX@instantaneous@None
21## e.g.# nc_var.py -o CFmorzization -S 'X|west_east|XLONG,Y|south_north|XLAT,T|Time|WRFtime,Z|bottom_top|ZNU:GlobalAttr1995.inf:proj1995.inf' -f ~/PY/wrfout_d01_1995-01-01_00\:00\:00 -v 'RAINC@time:!accumulation@WRFtime_bnds|h|3'
22## e.g. # nc_var.py -o dimrm -S removevar -f wrfout_d01_1995-01-01_00:00:00 -v west_east
23## e.g. # nc_var.py -o ifile -f ../PY/wrfout_d01_1995-01-01_00:00:00
24## e.g. # nc_var.py -o splitfile_dim -S bottom_top:ZNU:QVAPOR_ZNU:.4f -v QVAPOR,XLONG,XLAT,Times -f ~/PY/wrfout_d01_1995-01-01_00:00:00
25## e.g. # nc_var.py -o itime -S WRFtime -f ../PY/wrfout_d01_1995-01-01_00:00:00 -v Times
26## e.g. # nc_var.py -o get_point -S 'XLONG:XLAT:Time|0' -f /home/lluis/PY/wrfout_d01_1995-01-01_00:00:00 -v -45.,-30.
27## e.g. # nc_var.py -o get_time -S '1422759600;seconds!since!1949-12-01!00:00:00' -f /home/lluis/PY/wrfout_d01_1995-01-01_00:00:00 -v WRFtime
28## e.g. # nc_var.py -o join_singlestation_obsfiles -S 'obs/sfc_CAM:OBSnetcdf' -v all
29## e.g. # nc_var.py -o join_sounding_obsfiles -S .:UWyoming_snd_1 -v all
30## e.g. # nc_var.py -o timemean -f selvar_new.nc -S 2:XLONG,XLAT -v T2
31
32## e.g. ccrc468-17 # ./nc_var.py -v time -f 123/CCRC_NARCliM_Sydney_All_1990-1999_pr10max.nc -o out -S 1:-1
33## e.g. ccrc468-17 # ./nc_var.py -v prac -f xyz/CCRC_NARCliM_Sydney_DAM_1990-1999_prac.nc -o mname -S pluja
34## e.g. ccrc468-17 # ./nc_var.py -v lluis -f CCRC_NARCliM_Sydney_MOM_1990-1999_prac.nc -o addref -S 'prac:standard_name@lluis_variable:long_name@test variable lluis:units@m s-1:0.'
35## e.g. ccrc468-17 # ./nc_var.py -v lluis66 -f ~/UNSW-CCRC-WRF/tools/python/CCRC_NARCliM_Sydney_MOM_1990-1999_prac.nc -o addattr -S 'comment|Lluis Fita-123456'
36## e.g. ccrc468-17 # ./nc_var.py -v lluis66 -f ~/UNSW-CCRC-WRF/tools/python/CCRC_NARCliM_Sydney_MOM_1990-1999_prac.nc -o rmvattr -S 'comment'
37## e.g. acuna # ./nc_var.py -f /d4/lflmd/etudes/WRF_LMDZ/WaquaL/WRF/control/wrfout/wrfout_d01_1979-12-01_00:00:00 -o checkallvars -S 'DateStrLen,Time,soil_layers_stag,bottom_top_stag,bottom_top,west_east_stag,west_east,south_north,south_north_stag:-3,1,2,2,2,-2,-2,-2,-2'
38## e.g. foudre # nc_var.py -f ~/etudes/WRF_LMDZ/tests/wrf_input/AR40.0/wrfout_d01_1979-01-01_00\:00\:00 -o checkallvars -S 'bottom_top_plus1,num_orchidee_soil_levels,lmdz_ksoil_types,DIM0009,DateStrLen,Time,soil_layers_stag,bottom_top_stag,bottom_top,west_east_stag,west_east,south_north,south_north_stag:2,0,0,1,-3,1,2,2,2,-2,-2,-2,-2'
39## e.g. # nc_var.py -o field_stats -f ~/etudes/domains/Polynesie/geo_em.d03.nc -S full -v HGT_M
40## e.g. # nc_var.py -o filter_2dim -S '80,y,x,lon,lat' -f 'tahiti_5m_ll.grd' -v 'z'
41## e.g. # nc_var.py -o selvar -f /home/lluis/PY/met_em.d01.1979-01-01_00:00:00.nc -S 'west_east@XLONG_M,south_north@XLAT_M,num_metgrid_levels@int,Time@Times' -v TT,UU,VV,SKINTEMP
42## e.g. # nc_var.py -o 'Partialmap_Entiremap' -f carteveg5km.nc -S 'longitude,latitude,std,5000.,Goode,Goode_5km.nc' -v vegetation_map
43## e.g. # nc_var.py -o subbasin -f routing.nc -S Caceres,-57.75,-16.25,left
44## e.g. # nc_var.py -o computevar_model -f ~/PY/wrfout_d01_2001-11-11_00:00:00 -S hurs
45## e.g. # nc_var.py -o model_characteristics -f ~/PY/wrfout_d01_2001-11-11_00:00:00 -S WRF
46## e.g. # nc_var.py -o WRF_toCF -f ~/PY/wrfout_d01_2001-11-11_00:00:00 -S XLONG:XLAT:19491201000000:minutes
47## e.g. # nc_var.py -o cleaning_varsfile -f ~/PY/wrfout_d01_2001-11-11_00:00:00 -S T2,XLONG,XLAT,Times
48## e.g. # nc_var.py -o LMDZ_toCF -f LMDZ/AR40/vas_histins_1-1.nc -S 'minutes!since!1949-12-01!00:00:00'
49## e.g. # nc_var.py -o CDO_toCF -f LMDZ/AR40/hfss_reproj-histins.nc
50## e.g. # nc_var.py -o pinterp -f wrfout_d01_2001-11-11_00\:00\:00 -S 100000.:97500.:95000.:92500.:90000.:85000.:80000.:75000.:70000.:65000.:60000.:55000.:50000.:45000.:40000.:35000.:30000.:25000.:20000.:15000.:10000.:5000.:2500.:1000.:500.:250.,1,0 -v WRFt,WRFrh
51## e.g. # nc_var.py -o pinterp -f /media/ExtDiskC_ext4/DATA/etudes/WRF_LMDZ/WaquaL_highres/short_copies/LMDZ/AR40/histins_19790101000000-19790304000000_short.nc -S 100000.:97500.:95000.:92500.:90000.:85000.:80000.:75000.:70000.:65000.:60000.:55000.:50000.:45000.:40000.:35000.:30000.:25000.:20000.:15000.:10000.:5000.:2500.:1000.:500.:250.,1,0 -v temp,ovap
52## e.g. # nc_var.py -o reproject -f analysis/LMDZ/AR40/hurs_histins.nc -S 'lon,lat,analysis/WRF/current/hurs_wrfout.nc,lon,lat,npp,time@time' -v hurs
53## e.g. # nc_var.py -o field_stats_dim -f /home/lluis/PY/wrfout_d01_2001-11-11_00:00:00 -S 'full,None,None,west_east,XLONG,False' -v 'T2'
54## e.g. # nc_var.py -o compute_opersvarsfiles -S 'west_east|XLONG|-1;south_north|XLAT|-1;Time|Times|3@add|wrfout_d01_2001-11-11_00:00:00|T2%west_east|XLONG|-1;south_north|XLAT|-1;Time|Times|3@subc,273.15|wrfout_d01_2001-11-11_00:00:00|None' -v 'tempC,air!temperature,C'
55## e.g. # nc_var.py -o compute_opersvarsfiles -S 'lon|lon|-1;lat|lat|-1;time_counter|time_counter|-1@forwrdderiv,1,1,2|/ccc/store/cont003/gen7593/fitaborl/etudes/DynamicoESM/aquaplanet/AR40/19800101000000-19810101000000/histday.nc|t2m' -v 'tasderiv,x-derivative|of|air|temperature,K
56## e.g. # nc_var.py -o getvars_tofile -S soils_param_Zobler_textXIOS.nc -f soils_param_colorXIOS.nc -v 'soiltext,soiltexttypes'
57## e.g. # nc_var.py -o addVar -S 'lon,lat|mask@mask@1|f' -f new_ORCHIDEE_13PFTmap_2010_cmpi6_LUH2v2h.nc -v mask
58## e.g. # nc_var.py -o setvar_nc -S 'new_ORCHIDEE_13PFTmap_2010_cmpi6_LUH2v2h.nc,maxvegetfrac,veget;0' -f new_ORCHIDEE_13PFTmap_2010_cmpi6_LUH2v2h.nc -v mask
59## e.g. $ nc_var.py -o VarVal_FillValue -S '0.,eq,std' -f new_lai2D.nc -v LAI
60## e.g. # nc_var.py -o rm_FillValue -f new_ORCHIDEE_13PFTmap_2010_cmpi6_LUH2v2h.nc -S 0 -v mask
61## e.g. # nc_var.py -o curve_section -f /home/lluis/PY/test.nc -S 'gridline,x,y,8.,8.,16.,16.,32' -v all
62## e.g. # nc_var.py -o merge_files -S 'plev|plev,time|time:merged.nc' -f 'ncobs/AliceSprings/snd_94326_198201-198201.nc,ncobs/AliceSprings/snd_94326_198202-198202.nc' -v 'plev,time'
63## e.g. # nc_var.py -o temporal_stats -S 'Time:WRFtime:day@1@min,LTday@-3@1@min:bottom_top@ZNU,south_north@XLAT,west_east@XLONG' -f wrfout_d01_1995-01-01_00:00:00 -v T2,Q2
64## e.g. # nc_var.py -o retrieve_stations -f wrfout_d01_1995-01-01_00:00:00 -S 'tmin_percentiles.nc:stname:None:stlon:stlat:None:nearest:west_east:XLONG:south_north:XLAT:HGT:Time:WRFtime' -v T2,QVAPOR
65## e.g. # nc_var.py -o compute_slice2Dstats -S 'XLAT,-63.,19.,2.,HGT,250.,7000.,500.,Time|Times:west_east|XLONG:south_north|XLAT' -f wrfout_d01_1995-01-01_00:00:00 -v T2,Q2
66## e.g. # nc_var.py -o same_deltasign -f wrfout_d01_1995-01-01_00:00:00 -S 'Time:0|south_north:60|west_east:-1' -v T2,Q2,XLAT,XLONG
67## e.g. # nc_var.py -o compute_slices_stats -S 'XLONG,-74.,-36.,4.;XLAT,-62.,18.,2.;HGT,500.,7000.,500.@Time|Times:west_east|XLONG:south_north|XLAT@Time' -f wrfout_d01_1995-01-01_00:00:00 -v T2,Q2
68## e.g. # nc_var.py -o dimrename -f /media/lluis/ExtDiskC_ext3/DATA/estudios/FPS_Alps/additional/IOP/select/out_irene/simcdx_vars_cape_120lev_cdxwrf2.nc -S Time -v time0
69## e.g. # nc_var.py -o area_weighted -f 'reference_data.nc:lon;lon;lon_bnds;-1;lat;lat;lat_bnds;-1,get_data.nc:lon;lon;lon_bnds;-1;lat;lat;lat_bnds;-1' -S 'yes:min,max,mean,stddev,count' -v ct_values,xband_values,box_values,mosaic_values
70## e.g. # nc_var.py -o area_weighted -f '/media/lluis/ExtDiskC_ext4/bkup/llamp/estudios/dominios/SA150k/geo_em.d01.nc:west_east;XLONG_M;WRFxbnds;-1;south_north;XLAT_M;WRFybnds;-1,/media/lluis/ExtDiskC_ext4/bkup/llamp/estudios/dominios/SA50k/geo_em.d01.nc:west_east;XLONG_M;WRFxbnds;-1;south_north;XLAT_M;WRFybnds;-1' -S 'no:mean' -v HGT_M
71## e.g. # nc_var.py -o compute_slices_stats_areaweighted -S 'XLONG,-74.,-36.4,4.;XLAT,-63.,19.,4.;HGT,500.,7000.,500.@Time|WRFtime:west_east|XLONG:south_north|XLAT@Time@west_east|lon_bnds,south_north|lat_bnds@XLONG|lat_bnds;lon_bnds,XLAT|lat_bnds;lon_bnds@Time' -f wrfout_bnds.nc -v T2,U10,V10,Q2
72## e.g. # nc_var.py -o compute_slices_stats_areaweighted -S 'lat,-63.,19.,2.;orog,500.,7000.,500.;rangefaces,fixed,-2.5|-0.5,-0.5|0.5,0.5|2.5@time|time:lon|lon:lat|lat@time@lon|lon_bnds,lat|lat_bnds@lon|lon_bnds,lat|lat_bnds@lat,lon@time' -f /media/lluis/ExtDiskC_ext3/DATA/estudios/Andes/DATA/concatenated/historical/tasmin/tasmin_Amon_ACCESS1-0_historical_r1i1p1_185001-200512_Andes_19600101000000-19900101000000.nc -v tasmin
73## e.g. # nc_var.py -o except_fillValue -S 'orog:range,500.,7000.:None' -f /home/lluis/estudios/Andes/cmip_data/fx/orog_fx_ACCESS1-0_historical_r0i0p0.nc -v 'all'
74## e.g. # nc_var.py -o usefile_compute_slices_stats_areaweighted -S 'compute_slices_stats_areaweighted.nc@XLAT_M-HGT_M-rangefaces@Time|WRFtime:west_east|XLONG_M:south_north|XLAT_M:land_cat|INTrange@Time,land_cat' -f 'geo_em.d01.nc' -v 'LANDUSEF'
75
76from optparse import OptionParser
77import numpy as np
78from netCDF4 import Dataset as NetCDFFile
79import os
80import re
81import nc_var_tools as ncvar
82# Using 'generic_tools.py'
83import generic_tools as gen
84
85# addDim: Operation to add a new dimension in a file
86# addVar: Operation to add a new variable in a file using exisintg dimensions
87# addvals: Function to add values to a given variable at a given dimension
88# area_weighted: Function to provide an area weighted statistics within two different values
89#   of matrices assuming regular lon/lat projections without taking into account Earth's curvature
90# CDO_toCF: Function to pass a CDO output file to CF-conventions
91# CFmorzization: Function to provide a CF-compilation version of a variable within a file
92# chdimname: Changing the name of the dimension
93# changevartype: Function to change the type of a variable (when possible)
94# checkallvars: Function to check all variables of a file
95# checkAllValues: Function to check for variables with along all their dimensions with the same value in a file
96# checkNaNs: Function to check for NaN values over all variables in a file
97# chgtimestep: Function to change the values of a given time-step of a variable inside a netCDF for values from a nother file
98# chvarname: Changing the name of the variable
99# cleaning_varsfile: Function to keep a list of varibales from a file
100# compute_deaccum: Function to compute deaccum: deaccumulation of a variable (VAR[t+1]-VAR[t])
101# compute_opersvarsfiles: Function to compute opersvarfiles: operation of variables from different files
102# compute_opervaralltime: Function to compute opervaralltime: operation of variable successible allover the time-steps
103# compute_opervartimes: Function to compute opervartimes: operation of variable for a given sub-set of time-steps
104# compute_slices_stats: Function to compute stats of variables of a file splitting variables by
105#   slices along sets of ranges for a series of variables
106# compute_slices_stats_areaweighted: Function to compute stats of variables of a file splitting variables by
107#   slices along sets of ranges for a series of variables weighting by the area
108#   covered by each grid (defined as polygon) within the slice
109# compute_slice2Dstats: Function to compute stats of variables of a file following slices along 2 variables
110# compute_tevolboxtraj: Function to compute tevolboxtraj: temporal evolution at a given point along a box following a trajectory
111# computevar_model: Function to provide the way to compute a CF-variable providing its name
112# curve_section: Function to provide a section of a file following a given curve
113# DatesFiles: Function to find different time values on a series of WRF files in a folder
114# DataSetSection: Function to get a section (values along a dimension) of a given data-set
115# DataSetSection_multidims: Function to get a section (values along multiple dimensions) of a given data-set
116# DataSetSection_multivars: Function to get a section (values along multiple variables) of a given data-set
117# DYNAMICO_toCF: Function to pass a DYNAMICO original file to CF-conventions
118# dimrename: Renaming a dimension from a file
119# dimrm: Removing a dimension from a file
120# dimToUnlimited: Operation to create an unlimited dimension from an existing one
121# dimVar_creation: Function to add a 1D variable with the size of a given dimension in a file
122# except_fillValue: Function to fill a file with fill_Value except a given value of a variable
123# fattradd: Adding attributes from a reference file
124# fdimadd: Adding dimension from another reference file
125# fgaddattr: Adding global attributes from a reference file
126# field_stats: Function to retrieve statistics from a field
127# field_stats_dim: Function to retrieve statistics from a field along dimensions
128# file_creation: Operation to create a file with one variable with a given set of dimensions
129# file_oper_alongdims: Function to operate a file along different dimensions of a variable
130# filter_2dim: Function to filter along 2 dimensions (moving grid-box means of a given size) values of the netCDF file
131# flipdim: flips the value following one dimension
132# fvaradd: Adding variable (and all its attributes and dimensions) from a reference file to a file
133# gaddattrk: Add a global attribute to a netCDF caring about the type. Removes previous attribute if it exist
134# gaddattr: Add a global attribute to a netCDF. Removes previous attribute if it exist
135# get_attribute: Function to get an attribute from a netCDF file
136# get_point: Function to provide the closest grid point to a given lat,lon
137# get_time: Function to provide the closest time-step to a given time
138# get_namelist_vars: Function to get namelist-like  values ([varname] = [value])
139# get_Variables: Function to get a list of variables from an existing file
140# getvalues_lonlat: Function to retrieve the values from the closest grid point to a set of longitude, latitude values
141# getvars_tofile: Function to get variables from a file and pass them to another one
142# grattr: Function to read a global atribute
143# grmattr: Removing a global attribute
144# idims: Give all the dimensions names of a file
145# ifile: Function to provide some information from a given file
146# igattrs: Give all the global attributes of a file
147# increaseDimvar: Function to increase with 1 dimension an existing variable within a netcdf file. Values of
148#   the variable will be repeated along the new dimension
149# isgattrs: Give a single global attribute of a file and its type
150# isvattrs: Give a single attribute of a variable
151# itime: Function to provide information of the time from a netCDF file
152# ivars: Give all the variable names of a file
153# ivattrs: Give all the attributes of a variable and its type
154# join_singlestation_obsfiles: Function to join files from 'single-station'
155#   `create_OBSnetcdf.py' script to create a single file
156# join_sounding_obsfiles: Function to join 1D variables from files generated by
157#   `UWyoming_snd_nc.py' script to create a single file
158# LMDZ_toCF: Function to pass a LMDZ original file to CF-conventions
159# lonlat_polygon: Function to define a lon/lat region giving the coordinates of the vertexs of a given polygon
160# maskvar: Function to mask a variable using another variable to mask it. Only need to share at least 1 dimension with the same size (no need same name)
161# merge_files: Function to merge variables from two files
162# model_characteristics: Function to provide major characterisitcs of a given model output
163# mthDYNAMICO_toCF: Function to pass a mthDYNAMICO original file to CF-conventions
164# ncreplace: Function to replace something from a netCDF file
165# ncstepdiff: Function to compute differencies between time-steps (deacumulate) a netCDF file
166# netcdf_concatenation: Function to concatenate netCDF files for a given set of variables
167# netcdf_fold_concatenation: Function to concatenate netCDF files in a given folder for a given set of variables
168# netcdf_fold_concatenation_HMT: Function to concatenate netCDF files in a given folder for a given set of variables
169#   giving Header, Middle, Tail for the name files
170# reconstruct_matrix_from_vector: Function to reconstruct a 2D matrix from a pair of syncronized vectors with the positions on x and y coordinates
171# reproject: Function to reproject values to another one
172# rm_FillValue: Operation to remove the _FillValue from a variable inside a netCDF file
173# Partialmap_Entiremap: Function to transform from a partial global map (e.g.: only land points) to an entire one
174#   Coincidence of points is done throughout a first guess from fractions of the total domain of search
175# Partialmap_EntiremapFor: Function to transform from a partial global map (e.g.: only land points) to an entire one
176#   using Fortran code Coincidence of points is done throughout a first guess from fractions of the total domain of search
177# Partialmap_EntiremapForExact: Function to transform from a partial global map (e.g.: only land points) to an entire
178#   one using Fortran code with exact location Coincidence of points is done throughout a first guess from fractions of
179#   the total domain of search
180# pinterp: Function to vertically interpolate using subroutines from the p_interp.F90 NCAR program
181# remapnn: Function to remap to the nearest neightbor a variable using projection from another file
182# retrieve_stations: Function to retrieve temporal values at given stations provided by a secondary netcdf
183# same_deltasign: Function to determine if a given series of 1D values share the same sign of
184#   increase/decrease between consecutive values
185# seasmean: Function to compute the seasonal mean of a variable
186# sellonlatbox: Function to select a lotlan box from a data-set
187# sellonlatlevbox: Function to select a lotlan box and a given level from a data-set
188# selvar: Function to select a series of variables from a netcdf file. Variables with
189# setvar_asciivalues: Function to set de values of a variable with an ASCII file (common Fortran-like format)
190# setvar_nc: Operation to set values of a variable from values of an other one
191# sorttimesmat: Function to sort the time values of a given file
192# spacemean: Function to retrieve a space mean series from a multidimensional variable of a file
193# SpatialWeightedMean: Function to compute the spatial mean using weights from a netCDF file
194# splitfile_dim: Function to split a file along a given dimension with a new file for each different value along the dimension (assuming resultant vardim of rank-1)
195# statcompare_files: Python script to statistically compare two different files
196# subbasin: Function to retrieve the subbasin (all the sub-flows untila a given lon,lat)
197# submns: Function to retrieve a series of months from a file
198# subyrs: Function to retrieve a series of years from a file
199# temporal_stats: Function to compute temporal statistics. Rank of the variables are
200#   preserved along other non-temporal dimensions
201# TimeInf: Function to print all the information from the variable time
202# time_reset: Function to re-set the time axis of a file
203# TimeSplitmat: Function to transform a file with CFtimes to a matrix [Nyear,Nmonth,Nday,Nhour,Nminute,Nsecond]
204# timemean: Function to retrieve a time mean series from a multidimensional variable of a file
205# usefile_compute_slices_stats_areaweighted: Function to compute stats of variables of
206#   a file splitting variables by slices along sets of ranges for a series of
207#   variables weighting by the area covered by each grid (defined as polygon) within
208#   the slice using pre-calculated area-weights from an existing file
209# valmod: Function to modify the value of a variable
210# valmod_dim: Function to modify the value of a variable at a given dimension and value
211# varaddattrk: Add an attribute to a variable caring about the type
212# varaddattr: Add an attribute to a variable. Removes previous attribute if it exists
213# varaddref: Function to add a variable in an existing file copying characteristics from an existing one
214# var_creation: Operation to create a new variable in a file with a given set of dimensions
215# varout: Function when we want to output variable values
216# varrmattr: Removing an attribute from a variable
217# varrm: Removing a variable from a file
218# VarVal_FillValue: Function to transform a given value from a given variable to _FillValue in a netCDF file
219# vrattr: Function to remove an atribute from a variable
220# WRF_d0Nref: Function for the generation of an extra WRF domain from a given one
221# WRF_CFlonlat_creation: Function to add a CF-convention longitude/latitude variables in a WRF file
222# WRF_CFtime_creation: Function to add a CF-convention time unit in a WRF file
223# WRF_CFxtime_creation: Function to add a CF-convention time unit in a WRF file using variable 'XTIME'
224# WRF_toCF: Function to pass a WRF original file to CF-conventions
225# WRF_to_newCF: Function to pass a WRF original file to new CF-conventions file
226
227operations=['addDim', 'addVar', 'addvals', 'area_weighted', 'CDO_toCF',              \
228  'CFmorzization', 'chdimname', 'changevartype',                                     \
229  'checkallvars', 'checkAllValues', 'checkNaNs',                                     \
230  'chgtimestep', 'chvarname', 'cleaning_varsfile', 'compute_deaccum',                \
231  'compute_opersvarsfiles',                                                          \
232  'compute_opervaralltime', 'compute_opervartimes', 'compute_slices_stats',          \
233  'compute_slices_stats_areaweighted', 'compute_slice2Dstats',                       \
234  'compute_tevolboxtraj',                                                            \
235  'computevar_model', 'curve_section', 'DatesFiles',                                 \
236  'DataSetSection', 'DataSetSection_multidims', 'DataSetSection_multivars',          \
237  'DYNAMICO_toCF', 'dimrename', 'dimrm', 'dimToUnlimited', 'dimVar_creation',        \
238  'except_fillValue', 'fattradd',                                                    \
239  'fdimadd', 'fgaddattr', 'field_stats', 'field_stats_dim', 'file_creation',         \
240  'file_oper_alongdims', 'filter_2dim',                                              \
241  'flipdim', 'fvaradd', 'gaddattrk', 'gaddattr', 'get_attribute',                    \
242  'get_point', 'get_time', 'get_namelist_vars', 'get_Variables',                     \
243  'getvalues_lonlat', 'getvars_tofile', 'grattr',                                    \
244  'grmattr', 'idims', 'ifile', 'igattrs', 'increaseDimvar', 'isgattrs',              \
245  'isvattrs', 'itime', 'ivars', 'ivattrs', 'join_singlestation_obsfiles',            \
246  'join_sounding_obsfiles', 'LMDZ_toCF', 'lonlat_polygon', 'maskvar',                \
247  'merge_files', 'model_characteristics',                                            \
248  'mthDYNAMICO_toCF', 'ncreplace', 'ncstepdiff', 'netcdf_concatenation',             \
249  'netcdf_fold_concatenation',                                                       \
250  'netcdf_fold_concatenation_HMT', 'reproject', 'Partialmap_Entiremap',              \
251  'Partialmap_EntiremapFor', 'Partialmap_EntiremapForExact',                         \
252  'pinterp', 'reconstruct_matrix_from_vector', 'remapnn', 'retrieve_stations',       \
253  'rm_FillValue', 'same_deltasign',                                                  \
254  'seasmean', 'sellonlatbox', 'sellonlatlevbox', 'selvar', 'setvar_asciivalues',     \
255  'setvar_nc', 'sorttimesmat', 'spacemean', 'SpatialWeightedMean',                   \
256  'splitfile_dim', 'statcompare_files',                                              \
257  'subbasin', 'submns', 'subyrs', 'temporal_stats', 'TimeInf', 'time_reset',         \
258  'TimeSplitmat', 'timemean', 'usefile_compute_slices_stats_areaweighted',           \
259  'valmod', 'valmod_dim','varaddattrk', 'varaddattr',                                \
260  'varaddref',                                                                       \
261  'var_creation', 'varout', 'varoutold', 'varrmattr', 'varrm', 'VarVal_FillValue',   \
262  'vrattr', 'WRF_d0Nref',                                                            \
263  'WRF_CFlonlat_creation', 'WRF_CFtime_creation', 'WRF_CFxtime_creation',            \
264  'list_operations', 'WRF_toCF', 'WRF_to_newCF']
265
266### Options
267##string_operation="operation to make: " + '\n' + " out, output values -S inidim1,[inidim2,...]:enddim1,[enddim2,...]"
268string_operation="""operation to make:
269  addgattr, add a new global attribute: addatr -S [attrname]|[attrvalue]
270  addvattr, add a new attribute to any given variable: addatr -S [attrname]|[attrvalue]
271  addref, add a new variable with dimension and attributes from an already existing 'variable ref' in the file and -S [variable ref]:[attr name]@[value]:[[attr2]@[value2], ...]:[value/file with values]  mname, modify name -S newname
272  checkallvalrs: Function to check all variables of a file: -S [dimn1],[[dimn2],...,[dimnN]]:[dim1],[[dim2],...,[dimN]]
273  mname, modify name -S newname
274  out, output values -S inidim1,[inidim2,...]:enddim1,[enddim2,...]
275  valmod, modifiy values of variable -S [modification]:
276     sumc,[constant]: add [constant] to variables values
277     subc,[constant]: substract [constant] to variables values
278     mulc,[constant]: multipy by [constant] to variables values
279     divc,[constant]: divide by [constant] to variables values
280  rmgattr, remove a global attribute: rmgattr -S [attrname]
281  rmvattr, remove an attribute to any given variable: rmvattr -S [attrname]
282"""
283
284#print string_operation
285
286operationnames = "'" + gen.numVector_String(operations, "', '") + "'"
287
288parser = OptionParser()
289parser.add_option("-f", "--netCDF_file", dest="ncfile", help="file to use", 
290  metavar="FILE")
291parser.add_option("-o", "--operation", type='choice', dest="operation", 
292  choices=operations, help="operation to make: " + operationnames, metavar="OPER")
293parser.add_option("-S", "--valueS", dest="values", 
294  help="values to use according to the operation (when applicable); '-h' specific help of the operation", metavar="VALUES")
295parser.add_option("-v", "--variable", dest="varname",
296  help="variable to use (when applicable)", metavar="VAR")
297
298(opts, args) = parser.parse_args()
299
300#if opts.help:
301#  parser.print_help()
302#  print string_operation
303#  sys.exit()
304
305#######    #######
306## MAIN
307    #######
308
309# Operations which file name is not a real file
310NotCheckingFile = ['area_weighted', 'DatesFiles', 'compute_opersvarsfiles',          \
311  'file_creation',                                                                   \
312  'join_singlestation_obsfiles', 'join_sounding_obsfiles', 'list_operations',        \
313  'merge_files',                                                                     \
314  'model_characteristics', 'netcdf_concatenation', 'netcdf_fold_concatenation',      \
315  'netcdf_fold_concatenation_HMT']
316
317####### ###### ##### #### ### ## #
318errormsg='ERROR -- error -- ERROR -- error'
319
320varn=opts.varname
321oper=opts.operation
322
323if opts.operation is None:
324    print errormsg
325    print '  No operation provided !!'
326    print "  an operation must be provided as '-o [operationname]' "
327    quit(-1)
328
329if opts.ncfile is not None and not os.path.isfile(opts.ncfile) and                   \
330  not gen.searchInlist(NotCheckingFile,oper) and opts.ncfile != 'h':
331    print errormsg
332    print "  File '" + opts.ncfile + "' does not exist !!"
333    quit(-1)
334elif opts.ncfile is None and not gen.searchInlist(NotCheckingFile,oper) and          \
335  opts.values != 'h':
336    print errormsg
337    print '  No file provided !!'
338    print "  a file must be provided as '-f [filename]' "
339    quit(-1)
340
341if oper == 'addDim':
342    ncvar.addDim(opts.values, opts.ncfile, opts.varname)
343elif oper == 'addVar':
344    ncvar.addVar(opts.values, opts.ncfile, opts.varname)
345elif oper == 'addvals':
346    ncvar.addvals(opts.values, opts.ncfile, opts.varname)
347elif oper == 'area_weighted':
348    ncvar.area_weighted(opts.values, opts.ncfile, opts.varname)
349elif oper == 'CDO_toCF':
350    ncvar.CDO_toCF(opts.ncfile)
351elif oper == 'CFmorzization':
352    ncvar.CFmorzization(opts.values, opts.ncfile, opts.varname)
353elif oper == 'chdimname':
354    ncvar.chdimname(opts.values, opts.ncfile)
355elif oper == 'changevartype':
356    ncvar.changevartype(opts.values, opts.ncfile, opts.varname)
357elif oper == 'checkallvars':
358    ncvar.checkallvars(opts.values, opts.ncfile)
359elif oper == 'checkAllValues':
360    ncvar.checkAllValues(opts.values, opts.ncfile)
361elif oper == 'checkNaNs':
362    ncvar.checkNaNs(opts.values, opts.ncfile)
363elif oper == 'chgtimestep':
364    ncvar.chgtimestep(opts.values, opts.ncfile, opts.varname)
365elif oper == 'chvarname':
366    ncvar.chvarname(opts.values, opts.ncfile, opts.varname)
367elif oper == 'cleaning_varsfile':
368    ncvar.cleaning_varsfile(opts.values, opts.ncfile)
369elif oper == 'compute_deaccum':
370    ncvar.compute_deaccum(opts.values, opts.ncfile, opts.varname)
371elif oper == 'compute_opersvarsfiles':
372    ncvar.compute_opersvarsfiles(opts.values, opts.varname)
373elif oper == 'compute_opervaralltime':
374    ncvar.compute_opervaralltime(opts.values, opts.ncfile, opts.varname)
375elif oper == 'compute_opervartimes':
376    ncvar.compute_opervartimes(opts.values, opts.ncfile, opts.varname)
377elif oper == 'compute_slices_stats':
378    ncvar.compute_slices_stats(opts.values, opts.ncfile, opts.varname)
379elif oper == 'compute_slices_stats_areaweighted':
380    ncvar.compute_slices_stats_areaweighted(opts.values, opts.ncfile, opts.varname)
381elif oper == 'compute_slice2Dstats':
382    ncvar.compute_slice2Dstats(opts.values, opts.ncfile, opts.varname)
383elif oper == 'compute_tevolboxtraj':
384    ncvar.compute_tevolboxtraj(opts.values, opts.ncfile, opts.varname)
385elif oper == 'computevar_model':
386    ncvar.computevar_model(opts.values, opts.ncfile)
387elif oper == 'curve_section':
388    ncvar.curve_section(opts.values, opts.ncfile, opts.varname)
389elif oper == 'DataSetSection':
390    ncvar.DataSetSection(opts.values, opts.ncfile)
391elif oper == 'DataSetSection_multidims':
392    ncvar.DataSetSection_multidims(opts.values, opts.ncfile, opts.varname)
393elif oper == 'DataSetSection_multivars':
394    ncvar.DataSetSection_multivars(opts.values, opts.ncfile, opts.varname)
395elif oper == 'DatesFiles':
396    ncvar.DatesFiles(opts.values, opts.ncfile, opts.varname)
397elif oper == 'DYNAMICO_toCF':
398    ncvar.DYNAMICO_toCF(opts.values, opts.ncfile)
399elif oper == 'dimrename':
400    ncvar.dimrename(opts.ncfile, opts.values, opts.varname)
401elif oper == 'dimrm':
402    ncvar.dimrm(opts.ncfile, opts.values, opts.varname)
403elif oper == 'dimToUnlimited':
404    ncvar.dimToUnlimited(opts.values, opts.ncfile)
405elif oper == 'dimVar_creation':
406    ncvar.dimVar_creation(opts.values, opts.ncfile)
407elif oper == 'except_fillValue':
408    ncvar.except_fillValue(opts.values, opts.ncfile, opts.varname)
409elif oper == 'fattradd':
410    ncvar.fattradd(var, opts.values, opts.ncfile)
411elif oper == 'fdimadd':
412    ncvar.fdimadd(opts.values, opts.ncfile)
413elif oper == 'fgaddattr':
414    ncvar.fgaddattr(opts.values, opts.ncfile)
415elif oper == 'file_creation':
416    ncvar.file_creation(opts.values, opts.ncfile, opts.varname)
417elif oper == 'file_oper_alongdims':
418    ncvar.file_oper_alongdims(opts.values, opts.ncfile, opts.varname)
419elif oper == 'field_stats':
420    ncvar.field_stats(opts.values, opts.ncfile, opts.varname)
421elif oper == 'field_stats_dim':
422    ncvar.field_stats_dim(opts.values, opts.ncfile, opts.varname)
423elif oper == 'filter_2dim':
424    ncvar.filter_2dim(opts.values, opts.ncfile, opts.varname)
425elif oper == 'flipdim':
426    ncvar.flipdim(opts.values, opts.ncfile, opts.varname)
427elif oper == 'fvaradd':
428    ncvar.fvaradd(opts.values, opts.ncfile)
429elif oper == 'gaddattrk':
430    ncvar.gaddattrk(opts.values, opts.ncfile)
431elif oper == 'gaddattr':
432    ncvar.gaddattr(opts.values, opts.ncfile)
433elif oper == 'get_attribute':
434    ncvar.get_attribute(opts.values, opts.ncfile, opts.varname)
435elif oper == 'get_namelist_vars':
436    ncvar.get_namelist_vars(opts.values, opts.ncfile)
437elif oper == 'get_point':
438    ncvar.get_point(opts.values, opts.ncfile, opts.varname)
439elif oper == 'get_time':
440    ncvar.get_time(opts.values, opts.ncfile, opts.varname)
441elif oper == 'get_Variables':
442    ncvar.get_Variables(opts.values, opts.ncfile, opts.varname)
443elif oper == 'getvalues_lonlat':
444    ncvar.getvalues_lonlat(opts.values, opts.ncfile)
445elif oper == 'getvars_tofile':
446    ncvar.getvars_tofile(opts.values, opts.ncfile, opts.varname)
447elif oper == 'grattr':
448    ncvar.grattr(opts.values, opts.ncfile)
449elif oper == 'grmattr':
450    ncvar.grmattr(opts.values, opts.ncfile)
451elif oper == 'idims':
452    ncvar.idims(opts.ncfile)
453elif oper == 'ifile':
454    ncvar.ifile(opts.ncfile)
455elif oper == 'igattrs':
456    ncvar.igattrs(opts.ncfile)
457elif oper == 'increaseDimvar':
458    ncvar.increaseDimvar(opts.values, opts.ncfile, opts.varname)
459elif oper == 'isgattrs':
460    ncvar.isgattrs(opts.values, opts.ncfile)
461elif oper == 'isvattrs':
462    ncvar.isvattrs(opts.values, opts.ncfile, opts.varname)
463elif oper == 'itime':
464    ncvar.itime(opts.values, opts.ncfile, opts.varname)
465elif oper == 'ivars':
466    ncvar.ivars(opts.ncfile)
467elif oper == 'ivattrs':
468    ncvar.ivattrs(opts.ncfile, opts.varname)
469elif oper == 'join_singlestation_obsfiles':
470    ncvar.join_singlestation_obsfiles(opts.values, opts.varname)
471elif oper == 'join_sounding_obsfiles':
472    ncvar.join_sounding_obsfiles(opts.values, opts.varname)
473elif oper == 'list_operations':
474# From: http://www.diveintopython.net/power_of_introspection/all_together.html
475    object = ncvar
476    for opern in operations:
477        if  opern != 'list_operations': 
478            print opern + '_______ ______ _____ ____ ___ __ _'
479            print getattr(object, opern).__doc__
480elif oper == 'LMDZ_toCF':
481    ncvar.LMDZ_toCF(opts.values, opts.ncfile)
482elif oper == 'lonlat_polygon':
483    ncvar.lonlat_polygon(opts.values, opts.ncfile, opts.varname)
484elif oper == 'maskvar':
485    ncvar.maskvar(opts.values, opts.ncfile, opts.varname)
486elif oper == 'merge_files':
487    ncvar.merge_files(opts.values, opts.ncfile, opts.varname)
488elif oper == 'model_characteristics':
489    ncvar.model_characteristics(opts.values, opts.ncfile)
490elif oper == 'mthDYNAMICO_toCF':
491    ncvar.mthDYNAMICO_toCF(opts.values, opts.ncfile)
492elif oper == 'ncreplace':
493    ncvar.ncreplace(opts.values, opts.ncfile, opts.varname)
494elif oper == 'ncstepdiff':
495    ncvar.ncstepdiff(opts.values, opts.ncfile, opts.varname)
496elif oper == 'netcdf_concatenation':
497    ncvar.netcdf_concatenation(opts.ncfile)
498elif oper == 'netcdf_fold_concatenation':
499    ncvar.netcdf_fold_concatenation(opts.values, opts.ncfile, opts.varname)
500elif oper == 'netcdf_fold_concatenation_HMT':
501    ncvar.netcdf_fold_concatenation_HMT(opts.values, opts.ncfile, opts.varname)
502elif oper == 'opersvarsfiles':
503    ncvar.compute_opersvarsfiles(opts.values, opts.varname)
504elif oper == 'pinterp':
505    ncvar.pinterp(opts.values, opts.ncfile, opts.varname)
506elif oper == 'remapnn':
507    ncvar.remapnn(opts.values, opts.ncfile, opts.varname)
508elif oper == 'Partialmap_Entiremap':
509    ncvar.Partialmap_Entiremap(opts.values, opts.ncfile, opts.varname)
510elif oper == 'Partialmap_EntiremapFor':
511    ncvar.Partialmap_EntiremapFor(opts.values, opts.ncfile, opts.varname)
512elif oper == 'Partialmap_EntiremapForExact':
513    ncvar.Partialmap_EntiremapForExact(opts.values, opts.ncfile, opts.varname)
514elif oper == 'reconstruct_matrix_from_vector':
515    ncvar.reconstruct_matrix_from_vector(opts.values, opts.ncfile, opts.varname)
516elif oper == 'reproject':
517    ncvar.reproject(opts.values, opts.ncfile, opts.varname)
518elif oper == 'retrieve_stations':
519    ncvar.retrieve_stations(opts.values, opts.ncfile, opts.varname)
520elif oper == 'rm_FillValue':
521    ncvar.rm_FillValue(opts.values, opts.ncfile, opts.varname)
522elif oper == 'same_deltasign':
523    ncvar.same_deltasign(opts.values, opts.ncfile, opts.varname)
524elif oper == 'seasmean':
525    ncvar.seasmean(timename, opts.ncfile, opts.varname)
526elif oper == 'sellonlatbox':
527    ncvar.sellonlatbox(opts.values, opts.ncfile, opts.varname)
528elif oper == 'sellonlatlevbox':
529    ncvar.sellonlatlevbox(opts.values, opts.ncfile, opts.varname)
530elif oper == 'selvar':
531    ncvar.selvar(opts.values, opts.ncfile, opts.varname)
532elif oper == 'setvar_asciivalues':
533    ncvar.setvar_asciivalues(opts.values, opts.ncfile, opts.varname)
534elif oper == 'setvar_nc':
535    ncvar.setvar_nc(opts.values, opts.ncfile, opts.varname)
536elif oper == 'sorttimesmat':
537    ncvar.sorttimesmat(opts.ncfile, opts.varname)
538elif oper == 'spacemean':
539    ncvar.spacemean(opts.ncfile, opts.varname)
540elif oper == 'SpatialWeightedMean':
541    ncvar.SpatialWeightedMean(opts.values, opts.ncfile, opts.varname)
542elif oper == 'splitfile_dim':
543    ncvar.splitfile_dim(opts.values, opts.ncfile, opts.varname)
544elif oper == 'statcompare_files':
545    ncvar.statcompare_files(opts.values)
546elif oper == 'subbasin':
547    ncvar.subbasin(opts.values, opts.ncfile)
548elif oper == 'submns':
549    ncvar.submns(opts.values, opts.ncfile, opts.varname)
550elif oper == 'subyrs':
551    ncvar.subyrs(opts.values, opts.ncfile, opts.varname)
552elif oper == 'temporal_stats':
553    ncvar.temporal_stats(opts.values, opts.ncfile, opts.varname)
554elif oper == 'TimeInf':
555    ncvar.TimeInf(opts.ncfile, opts.varname)
556elif oper == 'time_reset':
557    ncvar.time_reset(opts.values, opts.ncfile, opts.varname)
558elif oper == 'TimeSplitmat':
559    ncvar.TimeSplitmat(opts.values, opts.ncfile, opts.varname)
560elif oper == 'timemean':
561    ncvar.timemean(opts.values, opts.ncfile, opts.varname)
562elif oper == 'usefile_compute_slices_stats_areaweighted':
563    ncvar.usefile_compute_slices_stats_areaweighted(opts.values, opts.ncfile,        \
564      opts.varname)
565elif oper == 'valmod':
566    ncvar.valmod(opts.values, opts.ncfile, opts.varname)
567elif oper == 'valmod_dim':
568    ncvar.valmod_dim(opts.values, opts.ncfile, opts.varname)
569elif oper == 'varaddattrk':
570    ncvar.varaddattrk(opts.values, opts.ncfile, opts.varname)
571elif oper == 'varaddattr':
572    ncvar.varaddattr(opts.values, opts.ncfile, opts.varname)
573elif oper == 'varaddref':
574    ncvar.varaddref(opts.values, opts.ncfile, opts.varname)
575elif oper == 'var_creation':
576    ncvar.var_creation(opts.values, opts.ncfile, opts.varname)
577elif oper == 'varout':
578    ncvar.varout(opts.values, opts.ncfile, opts.varname)
579elif oper == 'varoutold':
580    ncvar.varoutold(opts.values, opts.ncfile, opts.varname)
581elif oper == 'varrmattr':
582    ncvar.varrmattr(opts.values, opts.ncfile, opts.varname)
583elif oper == 'varrm':
584    ncvar.varrm(opts.ncfile, opts.varname)
585elif oper == 'VarVal_FillValue':
586    ncvar.VarVal_FillValue(opts.values, opts.ncfile, opts.varname)
587elif oper == 'vrattr':
588    ncvar.vrattr(opts.values, opts.ncfile, opts.varname)
589elif oper == 'WRF_d0Nref':
590    ncvar.WRF_d0Nref(opts.values, opts.ncfile)
591elif oper == 'WRF_CFlonlat_creation':
592    ncvar.WRF_CFlonlat_creation(opts.values, opts.ncfile, opts.varname)
593elif oper == 'WRF_CFtime_creation':
594    ncvar.WRF_CFtime_creation(opts.values, opts.ncfile, opts.varname)
595elif oper == 'WRF_CFxtime_creation':
596    ncvar.WRF_CFxtime_creation(opts.values, opts.ncfile, opts.varname)
597elif oper == 'WRF_toCF':
598    ncvar.WRF_toCF(opts.values, opts.ncfile)
599elif oper == 'WRF_to_newCF':
600    ncvar.WRF_to_newCF(opts.values, opts.ncfile, opts.varname)
601else:
602    print errormsg
603    print '   The operation ' + oper + ' is not ready !!'
604    print errormsg
605    quit()
Note: See TracBrowser for help on using the repository browser.