Skip to content

Commit 5f14b27

Browse files
authored
Allow that users set the file names in ecmwf. (#1732)
1 parent ba7c9d0 commit 5f14b27

File tree

3 files changed

+36
-19
lines changed

3 files changed

+36
-19
lines changed

src/common_options.jl

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5080,14 +5080,14 @@ macro var"?"(name)
50805080
getfield(Main, sym)
50815081
dir = "modules/"
50825082
if sym in [:ablines,:append2fig,:blendimg,:cart2pol,:cart2sph,:colorzones,:cpt4dcw,:crop,:cubeplot,:coastlinesproj,
5083-
:cubeslice,:date2doy,:delrows!,:doy2date,:era5,:gadm,:geocoder,:geodetic2enu,:getbyattrib,:gmtread,:gmtwrite,
5084-
:graticules,:gridit,:gunique,hampel,:imagesc,:inwhichpolygon,:image_alpha!,:image_cpt!,:imshow,:ind2rgb,
5085-
:info,:isnodata,:isoutlier,:lelandshade,:linearfitxy,:lowess,:magic,:mat2ds,:mat2grid,:mat2img,:mosaic,
5086-
:ODE2ds,:orbits,:pca,:plotgrid!,:plotyy,:pol2cart,:polygonlevels,:rasterzones!,:regiongeog,:rescale,
5087-
:slicecube,:sph2cart,:stackgrids,:ter2cart,:theme,:uniqueind,:vecangles,:weather,:whereami,:wmsinfo,
5088-
:wmsread,:wmstest,:worldrectgrid,:worldrectcoast,:worldrectangular,:xyzw2cube,:yeardecimal,:zonal_stats,
5089-
:cube,:cylinder,:dodecahedron,:ellipse3D,:flatfv,:fv2fv,:icosahedron,:loft,:sphere,
5090-
:octahedron,:tetrahedron,:torus,:replicant,:revolve,
5083+
:cubeslice,:date2doy,:delrows!,:doy2date,:ecmwf,:era5time,era5vars,:gadm,:geocoder,:geodetic2enu,
5084+
:getbyattrib,:gmtread,:gmtwrite, :graticules,:gridit,:gunique,hampel,:imagesc,:inwhichpolygon,:image_alpha!,
5085+
:image_cpt!,:imshow,:ind2rgb, :info,:isnodata,:isoutlier,:lelandshade,:linearfitxy,:listecmwfvars,
5086+
:lowess,:magic,:mat2ds,:mat2grid,:mat2img, :mosaic,:ODE2ds,:orbits,:pca,:plotgrid!,:plotyy,:pol2cart,
5087+
:polygonlevels,:rasterzones!,:regiongeog,:rescale, :slicecube,:sph2cart,:stackgrids,:ter2cart,:theme,
5088+
:uniqueind,:vecangles,:weather,:whereami,:wmsinfo, :wmsread,:wmstest,:worldrectgrid,:worldrectcoast,
5089+
:worldrectangular,:xyzw2cube,:yeardecimal,:zonal_stats, :cube,:cylinder,:dodecahedron,:ellipse3D,
5090+
:flatfv,:fv2fv,:icosahedron,:loft,:sphere, :octahedron,:tetrahedron,:torus,:replicant,:revolve,
50915091
:binarize,:bwareaopen,:bwhitmiss,:bwperim,:bwskell,:fillsinks,:imbothat,:imclose,:imcomplement,:imdilate,
50925092
:imerode,:imfill,:imfilter,:imhdome,:imhmin,:imhmax,:immorphgrad,:imopen,:imrankfilter,:imreconstruct,
50935093
:imsegment,:imsobel,:imtophat,:isodata, :padarray,:strel,:rgb2gray,:rgb2lab,:rgb2ycbcr

src/extras/weather.jl

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ Download a forecast dataset from the ECMWF.
155155
Where the Int is the number of days to go back from today. If the Int is greater than 3, an error is raised.
156156
If the date is a string, it must be in the form YYYYMMDD or YYYY-MM-DD.
157157
- `dryrun`: Print the URL of the requested data and return without trying to download anything.
158+
- `filename`: The name of the file to save the data to. If not provided, you still have two options: (1) the function
159+
will generate a name based on the on the variables and the date. (2) Use the `prefix` option to provide a prefix for the file name.
158160
- `format`: The format in which to save the downloaded data. It can be "grib" or "netcdf". Default is "netcdf".
159161
- `levlist`: The pressure levels to select. It can be a string to select a unique pressure level,
160162
or a vector of strings or Ints to select multiple pressure levels.
@@ -163,7 +165,10 @@ Download a forecast dataset from the ECMWF.
163165
of strings or Ints to select multiple variables. When variable(s) is requested, we download only those
164166
variables as separate files. The names of those files are the same as the variable names with the .grib2 extension.
165167
NOTE: Not specifying a variable will download the entire forecast grib file for each forecast step selected with the `step` option.
168+
- `prefix`: A string with the prefix to use for the file name. The file name will be the prefix followed by the variable name.
166169
- `root`: The root URL of the CDS ERA5 dataset. Default is "https://data.ecmwf.int/forecasts".
170+
- `region`: Specify a region of a specific geographic area. It can be provided as a string with form "N/W/S/E"
171+
or a 4-element vector or tuple with numeric data, or all a earthregion name.
167172
- `step`: An Int with the forecast step to select.
168173
- `stream`: The stream to select. It can be one of: "oper", "enfo", "waef", "wave", "scda", "scwv", "mmsf". Default is "oper".
169174
- `time`: The time in hours to select. It can be a string a ``Time`` object, or a Int. What ever it is,
@@ -172,15 +177,16 @@ Download a forecast dataset from the ECMWF.
172177
- `type`: A string with the type of forecast to select, it must be one of: "fc", "ef", "ep", "tf". Default is "fc".
173178
174179
### Example
175-
Try to get the latest 10m wind and 2m temperature forecast for today. It probably will fail because
176-
the data is likely not available yet. Adding a good `date` will make it work.
177-
```julia
180+
181+
Get the latest 10m wind and 2m temperature forecast for today.
182+
183+
```julia
178184
ecmwf(:forecast, vars=["10u", "2t"])
179185
```
180186
"""
181187
function ecmwf(source::Symbol=:reanalysis; filename="", cb::Bool=false, dataset="", params::Union{AbstractString, Vector{String}}="", key::String="", url::String="", wait=1.0, levlist="", region="", format="netcdf", dryrun=false, verbose::Bool=true, kw...)
182188

183-
(source == :forecast) && return ecmwf_fc(; levlist=levlist, dryrun=dryrun, kw...)
189+
(source == :forecast) && return ecmwf_fc(; filename=filename, levlist=levlist, dryrun=dryrun, kw...)
184190

185191
function cdsapikey()::Tuple{String, String}
186192
# Get the API key and URL from the ~/.cdsapirc file
@@ -306,9 +312,17 @@ function ecmwf(source::Symbol=:reanalysis; filename="", cb::Bool=false, dataset=
306312
end
307313

308314
# ---------------------------------------------------------------------------------------------------------------
309-
function ecmwf_fc(; levlist="", kw...)
315+
function ecmwf_fc(; filename="", levlist="", kw...)
310316

311317
d = KW(kw)
318+
319+
function which_name(d::Dict, thisvar::String, name::String, filename::AbstractString, EXT::String)::String
320+
# Select which name to use for saving the file. NAME is the composed (long) name. The others are user choices.
321+
(filename != "") && return filename # This one takes priority
322+
fname_prefix::String = ((val = find_in_dict(d, [:prefix], false)[1]) !== nothing) ? string(val)::String * "_$(thisvar)$(EXT)" : ""
323+
return (fname_prefix != "") ? fname_prefix : name # 'fname_prefix' takes priority if exists.
324+
end
325+
312326
root = "https://data.ecmwf.int/forecasts"
313327
if ((val = find_in_dict(d, [:root])[1]) !== nothing) #
314328
root = string(val)::String
@@ -399,10 +413,9 @@ function ecmwf_fc(; levlist="", kw...)
399413
grdclip_cmd = opt_R * " -Sr1/1 -G" # Not always used. To be replaced when grdconvert GMT bug is fixed
400414
(opt_R != "") && (opt_R = opt_R[4:end])
401415
EXT = (((val = find_in_dict(d, [:format])[1]) !== nothing) && val == "grib") ? ".grib" : ".grd"
402-
fmt_info = (EXT == ".grib") ? "GRIB" : "netCDF" # For printing info
403416

404417
local mat, G::GMTgrid{Float32,2}, x, y, range, inc
405-
tmp = tempname()
418+
tmp = tempname() # Temporary to store the index file
406419
for ns = 1:numel(step) # Loop over the steps
407420
thisFile = root * "/$(date)/$(tim)z/$(model)/0p25/$(stream)/$(date)$(tim)0000-$(step[ns])h-$(stream)-$(type)."
408421
dryrun && (println(thisFile * "grib2"); continue) # Dry run
@@ -431,6 +444,7 @@ function ecmwf_fc(; levlist="", kw...)
431444
mat[:,:,nl] .= G.z
432445
else # Just save the single level
433446
fname = vars[k] * "_step$(step[ns])_level$(levels[nl])_$(model)_$(stream)_$(type)_$(date)_$(tim)$(EXT)" # This var fname
447+
fname = which_name(d, vars[k], fname, filename, EXT) # Decide the final name
434448
@info "Downloading $(vars[k]) and saving to $fname"
435449
(EXT == ".grd") ? gmt("grdclip /vsisubfile/$(start)_$(len)" * ",/vsicurl/" * url * grdclip_cmd * fname) :
436450
run(`curl --show-error --range $(start)-$(stop) $url -o $fname`)
@@ -439,13 +453,15 @@ function ecmwf_fc(; levlist="", kw...)
439453

440454
if (cubeit && n_levels > 1) # Save the cube (implied by 'cubeit') on a 3D file
441455
fname = vars[k] * "_step$(step[ns])_$(model)_$(stream)_$(type)_$(date)_$(tim).nc" # This cube fname
456+
fname = which_name(d, vars[k], fname, filename, ".nc")
442457
@info "Downloading $(vars[k]) and saving cube to $fname"
443458
make_cube_ecmwf(G, mat, x, y, range, inc, levels, "millibars", levels, "Pressure", vars[1], fname)
444459
end
445460

446461
else # A surface variable
447462
start, len, stop = off_len[k,1,1], off_len[k,2,1], off_len[k,1,1] + off_len[k,2,1] - 1 # This var byte range
448463
fname = vars[k] * "_step$(step[ns])_$(model)_$(stream)_$(type)_$(date)_$(tim)$(EXT)" # This var fname
464+
fname = which_name(d, vars[k], fname, filename, EXT)
449465
@info "Downloading $(vars[k]) and saving to $fname"
450466
(EXT == ".grd") ? gmt("grdclip /vsisubfile/$(start)_$(len),/vsicurl/" * url * grdclip_cmd * fname) :
451467
run(`curl --show-error --range $(start)-$(stop) $url -o $fname`)
@@ -467,6 +483,7 @@ function ecmwf_fc(; levlist="", kw...)
467483

468484
if (cubeit && multi_steps)
469485
fname = vars[1] * "_step$(step[1])-$(step[end])_$(model)_$(stream)_$(type)_$(date)_$(tim).nc" # This cube fname
486+
fname = which_name(d, vars[1], fname, filename, ".nc")
470487
@info "Saving multi-step cube of $(vars[1]) to $fname"
471488
make_cube_ecmwf(G, mat, x, y, range, inc, step, "hour", step, "time", vars[1], fname)
472489
end

src/windbarbs/windbarbs.jl

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ Plot wind barbs in either 2D or 3D, from table data or two u,v grids.
2525
windbarbs(cmd0::String=""; first=true, kwargs...) = windbarbs(gmtread(cmd0, data=true); first=first, kwargs...)
2626
function windbarbs(arg1; first=true, kwargs...)
2727

28-
gmt_proggy = (IamModern[1]) ? "barb " : "psbarb "
28+
gmt_proggy = (IamModern[1]) ? "barb " : "psbarb "
2929
d, K, O = init_module(first, kwargs...) # Also checks if the user wants ONLY the HELP mode
3030

3131
cmd, opt_B, opt_J, opt_R = parse_BJR(d, "", "", O)
@@ -49,8 +49,8 @@ end
4949
function windbarbs(arg1::Union{String, GMTgrid}, arg2::Union{String, GMTgrid}; first=true, kwargs...)
5050
d, cmd, arg1, arg2, arg3 = grdvector(arg1, arg2; first=first, barbs=true, kwargs...) # arg3 is a possible CPT
5151
cmd[1] = replace(cmd[1], "grdvector" => "grdbarb")
52-
cmd[1] = add_opt(d, cmd[1], "Q", [:Q :barbs], (len=("", arg2str, 1), length=("", arg2str, 1), angle="+a", fill="+g", pen="+p", just="+j", speed="+s", width="+w"))
53-
cmd[1] = parse_these_opts(cmd[1], d, [[:A :polar], [:T :signs], [:Z :azim :azimuth :azimuths]])
52+
cmd[1] = add_opt(d, cmd[1], "Q", [:Q :barbs], (len=("", arg2str, 1), length=("", arg2str, 1), angle="+a", fill="+g", pen="+p", just="+j", justify="+j", speed="+s", width="+w"))
53+
cmd[1] = parse_these_opts(cmd[1], d, [[:A :polar], [:T :signs :sign_scale], [:Z :azim :azimuth :azimuths]])
5454

55-
finish_PS_module(d, cmd, "", first, !first, true, arg1, arg2, arg3)
55+
finish_PS_module(d, cmd, "", first, !first, true, arg1, arg2, arg3)
5656
end

0 commit comments

Comments
 (0)