Skip to content

Commit 74cca71

Browse files
authored
Use the same Dict type "Dict{Symbol,Any}" all over a 'd' is passed. (#1940)
This forces only one type in many functions and thus reduces the multiple compilations. Shelter grdimage.
1 parent 1361fc5 commit 74cca71

21 files changed

Lines changed: 162 additions & 156 deletions

src/GMT.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ const DEF_FIG_AXES = Ref{String}(DEF_FIG_AXES_BAK) # This one may be be changed
9696
const DEF_FIG_AXES3 = Ref{String}(DEF_FIG_AXES3_BAK)# ""
9797
const FIG_MARGIN = Ref{Int}(1) # Figure margin in points after convertion by 'psconvert'. Accessible 'margin' common option
9898
const global CTRL = CTRLstruct(zeros(13), zeros(6), [true], [false],
99-
[:arrows, :bubblechart, :basemap, :band, :clip, :coast, :colorbar, :grdcontour, :hband, :hlines, :inset, :logo, :lines, :grdvector, :plot, :plot3, :quiver, :scatter, :scatter3, :stairs, :text, :vlines, :vband], ["", "", ""], ["", "", "", " "], ["", ""], ["", ""], [false, true], [C_NULL], [Dict()])
99+
[:arrows, :bubblechart, :basemap, :band, :clip, :coast, :colorbar, :grdcontour, :hband, :hlines, :inset, :logo, :lines, :grdvector, :plot, :plot3, :quiver, :scatter, :scatter3, :stairs, :text, :vlines, :vband], ["", "", ""], ["", "", "", " "], ["", ""], ["", ""], [false, true], [C_NULL], [Dict{Symbol,Any}()])
100100
const pocket_call = Ref{Vector{Any}}(Any[nothing, nothing, nothing, nothing, nothing, nothing])# Extracted from CTRL to isolate type instability
101101
const CTRLshapes = CTRLstruct2(true, true, "") # Used in sub-module Drawing
102102
const prj4WGS84 = "+proj=longlat +datum=WGS84 +units=m +no_defs"# This is used in many places
@@ -387,7 +387,7 @@ using .Laszip
387387
gmtwrite(t, [0.0 0; 1 1])
388388
gmtread(t)
389389
gmtread(TESTSDIR * "assets/burro_cenora.jpg")
390-
coast(R=:g, proj=:guess, W=(level=1, pen=(2, :green)), savefig=tempname()*".ps")
390+
#coast(R=:g, proj=:guess, W=(level=1, pen=(2, :green)), savefig=tempname()*".ps")
391391
rm(t)
392392
D = mat2ds(rand(3, 3), colnames=["Time", "b", "c"])
393393
D.attrib = Dict("Timecol" => "1")

src/common_options.jl

Lines changed: 102 additions & 99 deletions
Large diffs are not rendered by default.

src/extras/mapsize2region.jl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,9 @@ function mapsize2region(; proj="", scale="", clon=NaN, clat=NaN, width=0, height
4545
@assert clon != NaN && clat != NaN "Center longitude and latitude must be specified"
4646
@assert width > 0 && height > 0 "Width and height must be positive"
4747
@assert contains(scale, ':') "Scale must be in the form of '1:xxxx'"
48-
(!isa(proj, StrSymb)) && (proj = parse_J(Dict(:J => proj, :scale => scale), "")[1][4:end]; scale="") # scale is now in J
49-
(bnds != "") && (bnds = parse_R(Dict(:R => bnds), "")[4:end]) # If bnds is not empty, parse it
50-
(!isa(scale, StrSymb)) && (scale = parse_Scale(Dict(:S => scale), "")) # If scale is not a StrSymb, parse it
48+
(!isa(proj, StrSymb)) && (proj = parse_J(Dict{Symbol,Any}(:J => proj, :scale => scale), "")[1][4:end]; scale="") # scale is now in J
49+
(bnds != "") && (bnds = parse_R(Dict{Symbol,Any}(:R => bnds), "")[4:end]) # If bnds is not empty, parse it
50+
(!isa(scale, StrSymb)) && (scale = parse_Scale(Dict{Symbol,Any}(:S => scale), "")) # If scale is not a StrSymb, parse it
5151
(bnds == "" && proj == "m" || startswith(proj, "merc") || startswith(proj, "Merc")) && (bnds="-180/180/-85/85") # Default bounds for Mercator
5252
opt_R, opt_J = mapsize2region(string(proj), scale, Float64(clon), Float64(clat), Float64(width), Float64(height), bnds)
5353
(plot != 0) && coast(R=opt_R, J=opt_J, shore=true, show=true, Vd=1)

src/extras/seismicity.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ function seismicity(; starttime::Union{DateTime, String}="", endtime::Union{Date
136136
plot!(D[:,1:4]; ml="faint", S=opt_S, C=C, show=see, Vd=Vd, d...)
137137
d = CTRL.pocket_d[1]
138138
d[:show] = show
139-
ms = (_size !== nothing) ? parse_opt_S(Dict(:size => _size), [3., 4, 5, 6, 7, 8, 9])[1] : [3., 4, 5, 6, 7, 8, 9] .* 0.02
139+
ms = (_size !== nothing) ? parse_opt_S(Dict{Symbol,Any}(:size => _size), [3., 4, 5, 6, 7, 8, 9])[1] : [3., 4, 5, 6, 7, 8, 9] .* 0.02
140140
st = (starttime != "") ? string(starttime) : string(Date(now() - Dates.Day(30)))
141141
et = (endtime != "") ? string(endtime) : string(Date(now()))
142142
legend && seislegend(; first=false, title="From "*st*" to "*et, cmap=C, mags=ms, pos="JBC+o0/1c+w12c/2.3c", d...)

src/extras/weather.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ function ecmwf(source::Symbol=:reanalysis; filename="", cb::Bool=false, dataset=
264264
last = (region == "") ? "\n" : ",\n" # Having an extra comma at the end of the line is a json syntax error
265265
params *= "\"download_format\": \"unarchived\"" * last
266266
if (region != "") # The region is provided by parse_R() as a string like " -R58/6/55/9" (N/W/S/E)
267-
optR = split(parse_R(Dict(:R => region), "")[1], '/')
267+
optR = split(parse_R(Dict{Symbol,Any}(:R => region), "")[1], '/')
268268
params *= "\"area\": [" * optR[1][4:end] * ", " * optR[4] * ", " * optR[2] * ", " * optR[3] * "]\n"
269269
end
270270
params = "{\"product_type\": [\"reanalysis\"],\n" * params * "}"

src/gdal/gdal_tools.jl

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -334,17 +334,19 @@ function gdalvectortranslate(indata, opts=String[]; dest="/vsimem/tmp", kwargs..
334334
helper_run_GDAL_fun(gdalvectortranslate, indata, dest, opts, "", KW(kwargs))
335335
end
336336

337-
function helper_run_GDAL_fun(f::Function, indata, dest::String, opts, method::String, d::Dict{Symbol, Any})::Union{GItype, GDtype, Gdal.AbstractDataset, Nothing}
337+
function helper_run_GDAL_fun(f::Function, indata, dest::String, opts, method::String, d::Dict{Symbol, Any})
338338
ressurectGDAL() # Another black-hole plug attempt.
339339
opts = gdal_opts2vec(opts) # Guarantied to return a Vector{String}
340-
#d = KW(kwargs)
340+
opts_vs = gdal_opts2vec(opts) # Guarantied to return a Vector{String}
341341
opts_vs, got_GMT_opts = GMT_opts_to_GDAL(f, opts, d)
342-
_helper_run_GDAL_fun(f, indata, dest, opts_vs, method, got_GMT_opts, d)
342+
d_fun = Dict{Symbol, Function}(:fun => f) # To avoid fck compilation for each different fuction
343+
_helper_run_GDAL_fun(d_fun, indata, dest, opts_vs, method, got_GMT_opts, d)
343344
end
344345

345346
# ---------------------------------------------------------------------------------------------------
346-
function _helper_run_GDAL_fun(f::Function, indata, dest::String, opts::Union{String, Vector{String}}, method, got_GMT_opts::Bool, d::Dict{Symbol, Any})::Union{GItype, GDtype, Gdal.AbstractDataset, Nothing}
347-
# This second level helper function reduces the number of multiple compiles. Here, only 'indata' may have different types.
347+
function _helper_run_GDAL_fun(d_fun::Dict{Symbol, Function}, @nospecialize(indata), dest::String, opts::Vector{String}, method::String, got_GMT_opts::Bool, d::Dict{Symbol, Any})
348+
# This second level helper function reduces the number of multiple compiles.
349+
f = d_fun[:fun] # Get back the function name
348350

349351
Vd::Int = ((val = find_in_dict(d, [:Vd])[1]) !== nothing) ? val : 0 # More gymns to avoid Anys
350352
(Vd > 0) && println(opts)
@@ -459,7 +461,6 @@ function GMT_opts_to_GDAL(f::Function, opts::Vector{String}, d::Dict{Symbol, Any
459461
end
460462
end
461463
f == gdalgrid ? append!(opts, ["-txe", s[1], s[2], "-tye", s[3], s[4]]) : append!(opts, op)
462-
#f == gdalgrid ? append!(opts, ["-txe", s[1], s[2], "-tye", s[3], s[4]]) : append!(opts, ["-projwin", split(opt_R[4:end], '/')[[1,4,2,3]]...]) # Ugly
463464
end
464465

465466
x_srs = (f == gdaltranslate) ? "-a_srs" : "-t_srs" # But don't know if there are others that take -a_srs instead of -t_srs
@@ -527,7 +528,7 @@ function default_gdopts!(f::Function, ds, opts::Vector{String}, dest::String)
527528
end
528529

529530
# ---------------------------------------------------------------------------------------------------
530-
function get_gdaldataset(data, opts, isVec::Bool=false)::Tuple{Gdal.AbstractDataset, Bool}
531+
function get_gdaldataset(data, opts::Vector{String}, isVec::Bool=false)::Tuple{Gdal.AbstractDataset, Bool}
531532
# Get a GDAL dataset from either a file name, a GMT grid or image, or a dataset itself
532533
# In case of a file name we must be careful and deal with possible "+b" band requests from GMT.
533534
# isVec tells us if the filename 'data' is to be opened as a Vector or a Raster.
@@ -540,11 +541,7 @@ function get_gdaldataset(data, opts, isVec::Bool=false)::Tuple{Gdal.AbstractData
540541
o = split(ext[ind[1]+2:end], ",") # But we must add 1 because GDAL band count is 1-based and GMT 0-based
541542
p = parse.(Int, o) .+ 1
542543
o = [string(c) for c in p]
543-
if (isa(opts, Vector{String}))
544-
for k = 1:lastindex(o) append!(opts, ["-b", o[k]]) end
545-
else
546-
opts *= " -b" * join(o, " -b ")
547-
end
544+
for k = 1:lastindex(o) append!(opts, ["-b", o[k]]) end
548545
end
549546
flags = isVec ? GDAL_OF_VECTOR | GDAL_OF_VERBOSE_ERROR : GDAL_OF_READONLY | GDAL_OF_VERBOSE_ERROR
550547
_ext = lowercase(ext[2:end]) # Drop the leading dot too
@@ -578,7 +575,7 @@ Convert a 24bit RGB image to 8bit paletted.
578575
"""
579576
function dither(indata, opts=String[]; n_colors::Integer=256, save::String="", gdataset::Bool=false)
580577
# ...
581-
src_ds, needclose = get_gdaldataset(indata, "", false)
578+
src_ds, needclose = get_gdaldataset(indata, String[], false)
582579
(nraster(src_ds) < 3) && error("Input image must have at least 3 bands")
583580
(isa(indata, GMTimage) && !startswith(indata.layout, "TRB")) &&
584581
error("Image memory layout must be `TRB` and not $(indata.layout). Load image with gdaltranslate()")

src/gdal_utils.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -957,7 +957,8 @@ Write a MxNxP `cube` object to disk as a multilayered file.
957957
"""
958958
function gdalwrite(fname::AbstractString, data, optsP=String[]; opts=String[], kw...)
959959
(fname == "") && error("Output file name is missing.")
960-
(isempty(optsP) && !isempty(opts)) && (optsP = opts) # Accept either Positional or KW argument
960+
(isempty(optsP) && !isempty(opts)) && (optsP = opts) # Accept either Positional or KW argument
961+
isa(optsP, AbstractString) && (optsP = gdal_opts2vec(optsP)) # Guarantied to return a Vector{String}
961962
ds = Gdal.get_gdaldataset(data, optsP)[1]
962963
if (Gdal.GDALGetRasterCount(ds.ptr) >= 1)
963964
gdaltranslate(ds, optsP; dest=fname, kw...)

src/gmt_types.jl

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -365,17 +365,20 @@ end
365365
mutable struct wrapGrids
366366
fname::String
367367
grd::GMTgrid
368+
img::GMTimage
368369
function wrapGrids(arg1, arg2)
369-
if (arg1 !== "") new(arg1, GMTgrid())
370-
elseif (isa(arg2, GMTgrid)) new("", arg2)
371-
elseif (isa(arg2, Matrix{<:Real})) new("", mat2grid(arg2))
372-
elseif (arg1 === "" && arg2 === nothing) new("", GMTgrid()) # Less usual case in grdlandmask where only kwargs are given
370+
tg, ti = GMTgrid(), GMTimage()
371+
if (arg1 !== "") new(arg1, tg, ti)
372+
elseif (isa(arg2, GMTgrid)) new("", arg2, ti)
373+
elseif (isa(arg2, GMTimage)) new("", tg, arg2)
374+
elseif (isa(arg2, Matrix{<:Real})) new("", mat2grid(arg2), ti)
375+
elseif (arg1 === "" && arg2 === nothing) new("", tg, ti) # Less usual case in grdlandmask where only kwargs are given
373376
else error("Unknown types ($(typeof(arg1)), $(typeof(arg2))) in wrapGrids")
374377
end
375378
end
376379
end
377380
function unwrapGrids(w::wrapGrids)
378-
return w.fname, !isempty(w.grd) ? w.grd : nothing
381+
return w.fname, !isempty(w.grd) ? w.grd : !isempty(w.img) ? w.img : nothing
379382
end
380383

381384
#=

src/grdimage.jl

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,14 @@ grdimage!(arg1, arg2=nothing, arg3=nothing; kw...) = grdimage_helper("", arg1, a
4949
function grdimage_helper(cmd0::String, arg1=nothing, arg2=nothing, arg3=nothing; first=true, kwargs...)
5050
d, K, O = init_module(first, kwargs...) # Also checks if the user wants ONLY the HELP mode
5151
(cmd0 != "" && arg1 === nothing && haskey(d, :inset)) && (arg1 = gmtread(cmd0); cmd0 = "")
52-
grdimage_helper(cmd0, arg1, arg2, arg3, K, O, d)
52+
(isa(arg1, Matrix{<:Real}) && isa(arg2, Matrix{<:Real}) && isa(arg3, Matrix{<:Real})) &&
53+
(arg2 = mat2grid(arg2); arg3 = mat2grid(arg3)) # Because than wrapGrids will convert arg1 to GMTgrid and other two must type agree
54+
grdimage_helper(wrapGrids(cmd0, arg1), arg2, arg3, K, O, d)
5355
end
5456

5557
# ---------------------------------------------------------------------------------------------------
56-
#function grdimage(cmd0::String="", arg1=nothing, arg2=nothing, arg3=nothing; first=true, kwargs...)
57-
function grdimage_helper(cmd0::String, arg1, arg2, arg3, K::Bool, O::Bool, d::Dict{Symbol, Any})
58+
function grdimage_helper(w::wrapGrids, arg2, arg3, K::Bool, O::Bool, d::Dict{Symbol, Any})
59+
cmd0, arg1 = unwrapGrids(w)
5860

5961
common_insert_R!(d, O, cmd0, arg1) # Set -R in 'd' out of grid/images (with coords) if limits was not used
6062

@@ -84,10 +86,11 @@ function grdimage_helper(cmd0::String, arg1, arg2, arg3, K::Bool, O::Bool, d::Di
8486
(haskey(d, :stretch) || haskey(d, :histo_bounds)) && delete!(d, [:histo_bounds, :stretch])
8587
end
8688

87-
_grdimage(cmd0, arg1, arg2, arg3, O, K, d)
89+
_grdimage(wrapGrids(cmd0, arg1), arg2, arg3, O, K, d)
8890
end
8991

90-
function _grdimage(cmd0::String, arg1, arg2, arg3, O::Bool, K::Bool, d::Dict)
92+
function _grdimage(w::wrapGrids, arg2, arg3, O::Bool, K::Bool, d::Dict{Symbol, Any})
93+
cmd0, arg1 = unwrapGrids(w)
9194

9295
arg4 = nothing # For the r,g,b + intensity case
9396

src/imshow.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ function imshow(arg1::GItype; kw...)
180180
# This is a (poor) pach for a GMT bug that screws when plotting CPTs on the sides.
181181
margin = "0"
182182
if ((val = find_in_dict(d, [:colorbar], false)[1]) !== nothing)
183-
tv = add_opt_module(Dict(:colorbar => val))
183+
tv = add_opt_module(Dict{Symbol,Any}(:colorbar => val))
184184
t2 = scan_opt(tv[1], "-D")
185185
t2 = replace(t2, "JMR" => "JMC")
186186
!contains(t2, "+o") && (t2 *= "+o$(_w/2 + 0.3)/0")

0 commit comments

Comments
 (0)