From e591f96be5a9a742e55c352cff7ff0c750bb4831 Mon Sep 17 00:00:00 2001 From: davidanthoff Date: Fri, 9 Feb 2024 03:31:14 +0000 Subject: [PATCH] Format files using DocumentFormat --- src/ciam.jl | 36 +-- src/ciamhelper.jl | 502 +++++++++++++++++++-------------------- src/main.jl | 14 +- src/slrcost.jl | 236 +++++++++--------- src/slrcost_GAMSmatch.jl | 238 +++++++++---------- test/runtests.jl | 4 +- test/test_utils.jl | 110 ++++----- 7 files changed, 570 insertions(+), 570 deletions(-) diff --git a/src/ciam.jl b/src/ciam.jl index 2b16b1c..bc512ee 100644 --- a/src/ciam.jl +++ b/src/ciam.jl @@ -6,14 +6,14 @@ using Mimi Initialize a CIAM model `m` with the given arguments. """ -function initciam(xsc, params, initparams, m::Model; fixed::Bool = true, t::Int = 20, - noRetreat::Bool = false, allowMaintain::Bool = false, popinput::Int = 0) +function initciam(xsc, params, initparams, m::Model; fixed::Bool=true, t::Int=20, + noRetreat::Bool=false, allowMaintain::Bool=false, popinput::Int=0) discountrate = 0.04 - if initparams["lslr"][1] !="lsl_rcp0_p50.csv" - rcp = parse(Int64,replace(replace(initparams["lslr"][1],r"^[^l]*lsl_rcp"=>s""),r"_.*"=>s"")) - pctl = parse(Int64,replace(replace(initparams["lslr"][1], r"^[^l]*lsl_rcp[0-9][0-9]_p"=>s""),r".csv"=>s"")) + if initparams["lslr"][1] != "lsl_rcp0_p50.csv" + rcp = parse(Int64, replace(replace(initparams["lslr"][1], r"^[^l]*lsl_rcp" => s""), r"_.*" => s"")) + pctl = parse(Int64, replace(replace(initparams["lslr"][1], r"^[^l]*lsl_rcp[0-9][0-9]_p" => s""), r".csv" => s"")) else rcp = 0 pctl = 50 @@ -22,17 +22,17 @@ function initciam(xsc, params, initparams, m::Model; fixed::Bool = true, t::Int if initparams["ssp"][1] == false ssp = 0 else - ssp = parse(Int64,replace(replace(initparams["ssp"][1],r"^[^l]*SSP"=>s""),r"_.*"=>s"")) + ssp = parse(Int64, replace(replace(initparams["ssp"][1], r"^[^l]*SSP" => s""), r"_.*" => s"")) end # Dynamically find indices corresponding to USA and CAN and manually set time steps # If the lengths are 0, then assume those segments are not used. Note that # if including Greenland, need Canada too as a reference for land appreciation - rgn_ind_canada = [k for (k,v) in xsc[4] if v=="CAN"] + rgn_ind_canada = [k for (k, v) in xsc[4] if v == "CAN"] rgn_ind_canada = (length(rgn_ind_canada) > 0) ? rgn_ind_canada[1] : 0 - rgn_ind_usa = [k for (k,v) in xsc[4] if v=="USA"] + rgn_ind_usa = [k for (k, v) in xsc[4] if v == "USA"] rgn_ind_usa = (length(rgn_ind_usa) > 0) ? rgn_ind_usa[1] : 0 # Add component: slrcost and set some parameters manually @@ -55,20 +55,20 @@ function initciam(xsc, params, initparams, m::Model; fixed::Bool = true, t::Int # Shorten some time-dependent parameters to correspond to the correct number of timesteps for k in keys(params) if ndims(params[k]) !== 0 && ndims(params[k]) == 2 && size(params[k])[1] > t && k != "surgeexposure" - params[k] = params[k][1:t,:] + params[k] = params[k][1:t, :] end end # set the VSL parameter to missings as a dummy and set vsl to be calculated # endogenously - dummy_vsl = Array{Union{Missing, Float64}}(missing, length(dim_keys(m, :time)), length(dim_keys(m, :ciam_country))) + dummy_vsl = Array{Union{Missing,Float64}}(missing, length(dim_keys(m, :time)), length(dim_keys(m, :ciam_country))) update_param!(m, :slrcost, :vsl_ciam_country, dummy_vsl) update_param!(m, :slrcost, :vsl_exogenous, false) # Set the rest of the parameters - to use update_leftover_params! we need To # specific the component as well as the parameter name params_dict = Dict() - for (k,v) in params + for (k, v) in params params_dict[(:slrcost, k)] = v end update_leftover_params!(m, params_dict) @@ -84,14 +84,14 @@ Return a initialized and built CIAM model with the given arguments. Note that the GAMSmatch optional argument uses a different slrcost component with the Hprev > H block commented out. This should only be used for testing! """ -function get_model(;initfile::Union{String, Nothing} = nothing, fixed::Bool=true, - t::Int = 20, noRetreat::Bool = false, allowMaintain::Bool = false, - popinput::Int = 0, GAMSmatch::Bool = false, surgeoption::Int = 0) +function get_model(; initfile::Union{String,Nothing}=nothing, fixed::Bool=true, + t::Int=20, noRetreat::Bool=false, allowMaintain::Bool=false, + popinput::Int=0, GAMSmatch::Bool=false, surgeoption::Int=0) - initparams = init(; f = initfile) + initparams = init(; f=initfile) params, xsc = import_model_data(initparams["lslr"][1], initparams["subset"][1], - initparams["ssp"][1], initparams["ssp_simplified"][1], - popinput, surgeoption) + initparams["ssp"][1], initparams["ssp_simplified"][1], + popinput, surgeoption) # clip the :at parameter based on t params["at"] = filter!(x -> x <= t, params["at"]) @@ -112,7 +112,7 @@ function get_model(;initfile::Union{String, Nothing} = nothing, fixed::Bool=true add_comp!(m, slrcost) end - initciam(xsc, params, initparams, m; fixed = fixed, t = t, noRetreat = noRetreat, allowMaintain = allowMaintain, popinput = popinput) + initciam(xsc, params, initparams, m; fixed=fixed, t=t, noRetreat=noRetreat, allowMaintain=allowMaintain, popinput=popinput) return m diff --git a/src/ciamhelper.jl b/src/ciamhelper.jl index 1a57f7f..be2132e 100644 --- a/src/ciamhelper.jl +++ b/src/ciamhelper.jl @@ -13,11 +13,11 @@ Load CIAM parameters from CSV to dictionary. """ function load_ciam_params() - data_dir = joinpath(@__DIR__, "..","data","input") + data_dir = joinpath(@__DIR__, "..", "data", "input") files = readdir(data_dir) - filter!(i->(i!="desktop.ini" && i!=".DS_Store" && i!="xsc.csv"), files) + filter!(i -> (i != "desktop.ini" && i != ".DS_Store" && i != "xsc.csv"), files) - params = Dict{Any, Any}(lowercase(splitext(m)[1]) => CSV.read(joinpath(data_dir,m),DataFrame) |> DataFrame for m in files) + params = Dict{Any,Any}(lowercase(splitext(m)[1]) => CSV.read(joinpath(data_dir, m), DataFrame) |> DataFrame for m in files) return params @@ -36,19 +36,19 @@ the input parameter dictionary `params`. The arguments are as fullows: """ function preplsl!(lslfile, subset, params, segnames) - data_dir = joinpath(@__DIR__,"..","data","lslr") - lsl_params = CSV.read(joinpath(data_dir,lslfile), DataFrame) |> DataFrame + data_dir = joinpath(@__DIR__, "..", "data", "lslr") + lsl_params = CSV.read(joinpath(data_dir, lslfile), DataFrame) |> DataFrame # Filter according to subset segments if subset != false col_names = [i for i in names(lsl_params) if string(i) in subset] - lsl_params = lsl_params[!,col_names] + lsl_params = lsl_params[!, col_names] end # Chomp off unrelated rows and sort alphabetically (do this regardless of whether there's a subset) - col_names = [i for i in names(lsl_params) if string(i) in segnames] + col_names = [i for i in names(lsl_params) if string(i) in segnames] col_names = sort(col_names) - lsl_params = lsl_params[!,col_names] + lsl_params = lsl_params[!, col_names] params["lslr"] = convert(Array{Float64,2}, Matrix(lsl_params)) @@ -70,7 +70,7 @@ the input parameter dictionary `params`. The arguments are as fullows: """ function prepssp!(ssp, ssp_simplified, params, rgnnames, segnames, popinput) - data_dir = joinpath(@__DIR__,"..","data","ssp") + data_dir = joinpath(@__DIR__, "..", "data", "ssp") # read and set population densities for Jones and Merkens data sets whether or not # we are using them, so they have some defaults. @@ -79,8 +79,8 @@ function prepssp!(ssp, ssp_simplified, params, rgnnames, segnames, popinput) error("The `popinput` argument values of 1 and 2 are not supported at this time. In the future they will indicate use of Jones and O'Neill 2016 or Merkens et al 2016 population data, respectively.") - popdens_seg_jones = CSV.read(joinpath(data_dir,string("popdens_seg_jones_ssp",ssp_simplified,".csv")), DataFrame) - popdens_seg_merkens=CSV.read(joinpath(data_dir,string("popdens_seg_merkens_ssp",ssp_simplified,".csv")), DataFrame) + popdens_seg_jones = CSV.read(joinpath(data_dir, string("popdens_seg_jones_ssp", ssp_simplified, ".csv")), DataFrame) + popdens_seg_merkens = CSV.read(joinpath(data_dir, string("popdens_seg_merkens_ssp", ssp_simplified, ".csv")), DataFrame) seg_col_names = [i for i in names(popdens_seg_jones) if string(i) in segnames] sort!(seg_col_names) @@ -90,24 +90,24 @@ function prepssp!(ssp, ssp_simplified, params, rgnnames, segnames, popinput) sort!(seg_col_names) popdens_seg_merkens = popdens_seg_merkens[!, seg_col_names] - params["popdens_seg_jones"] = Array{Float64,2}(popdens_seg_jones) - params["popdens_seg_merkens"] = Array{Float64,2}(popdens_seg_merkens) + params["popdens_seg_jones"] = Array{Float64,2}(popdens_seg_jones) + params["popdens_seg_merkens"] = Array{Float64,2}(popdens_seg_merkens) end if ssp == false # Do nothing, base ssp data already loaded return params else - pop = CSV.read(joinpath(data_dir,string("pop_",ssp,".csv")), DataFrame) - ypc = CSV.read(joinpath(data_dir, string("ypcc_",ssp,".csv")), DataFrame) + pop = CSV.read(joinpath(data_dir, string("pop_", ssp, ".csv")), DataFrame) + ypc = CSV.read(joinpath(data_dir, string("ypcc_", ssp, ".csv")), DataFrame) - col_names = [i for i in names(pop) if string(i) in rgnnames] + col_names = [i for i in names(pop) if string(i) in rgnnames] sort!(col_names) pop = pop[!, col_names] ypc = ypc[!, col_names] - params["pop"] = Array{Float64,2}(pop) - params["ypcc"] = Array{Float64,2}(ypc) + params["pop"] = Array{Float64,2}(pop) + params["ypcc"] = Array{Float64,2}(ypc) end return params end @@ -138,20 +138,20 @@ function parse_ciam_params!(params, rgn_order, seg_order, surgeoption) colnames = filter(f -> string(f) != "NA", names(p)) # Preserve column names # Filter segments to subset - segs = p[!,1] + segs = p[!, 1] seg_inds = filter_index(segs, seg_order) - p = p[seg_inds,:] + p = p[seg_inds, :] # Sort alphabetically - seg_alpha = sortperm(p[!,1]) - p = p[seg_alpha,:] + seg_alpha = sortperm(p[!, 1]) + p = p[seg_alpha, :] # Process all variables if length(seg_inds) >= 1 - for k in 2:(length(colnames) + 1) + for k in 2:(length(colnames)+1) varname = string(colnames[k-1]) - newvars = p[1:end,k] - newvars = [convert(Float64,v) for v in newvars] + newvars = p[1:end, k] + newvars = [convert(Float64, v) for v in newvars] params[varname] = newvars end delete!(params, "data") @@ -159,7 +159,7 @@ function parse_ciam_params!(params, rgn_order, seg_order, surgeoption) error("Segments in dictionary do not match supplied segments") end - # globalparams key case + # globalparams key case elseif k == "globalparams" for k in 1:nrow(p) @@ -168,20 +168,20 @@ function parse_ciam_params!(params, rgn_order, seg_order, surgeoption) newval = p[k, 2] if (varname == "ntsteps" || varname == "adaptPers") - newval = parse(Int64,newval) + newval = parse(Int64, newval) elseif lowercase(newval) == "true" newval = true elseif lowercase(newval) == "false" newval = false else - newval = parse(Float64,newval) + newval = parse(Float64, newval) end params[varname] = newval end delete!(params, "globalparams") - # surge exposure key case - elseif occursin("surgeexposure",k) # generalize for multiple possible surge data sets + # surge exposure key case + elseif occursin("surgeexposure", k) # generalize for multiple possible surge data sets p = @from i in p begin @where i.segments in seg_order @@ -191,9 +191,9 @@ function parse_ciam_params!(params, rgn_order, seg_order, surgeoption) # Sort alphabetically sort!(p, :segments) - params[k] = convert(Array{Float64,2}, Matrix(p[:,2:6])) + params[k] = convert(Array{Float64,2}, Matrix(p[:, 2:6])) - # refa key case + # refa key case elseif k == "refa_h" || k == "refa_r" p = @from i in p begin @@ -205,29 +205,29 @@ function parse_ciam_params!(params, rgn_order, seg_order, surgeoption) sort!(p, :segments) delete!(params, k) - if k=="refa_h" - params["refA_H"] = convert(Array{Float64}, p[!,:value]) + if k == "refa_h" + params["refA_H"] = convert(Array{Float64}, p[!, :value]) else - params["refA_R"] = convert(Array{Float64}, p[!,:value]) + params["refA_R"] = convert(Array{Float64}, p[!, :value]) end - # Country data matrices parameter case + # Country data matrices parameter case elseif size(p, 2) == 2 # Filter regions - r_inds = filter_index(p[!,1], rgn_order) - p = p[r_inds,:] + r_inds = filter_index(p[!, 1], rgn_order) + p = p[r_inds, :] # Alphabetize - p = p[sortperm(p[!,1]),:] - if p[!,1] != rgn_order + p = p[sortperm(p[!, 1]), :] + if p[!, 1] != rgn_order error("Regions in dictionary do not match supplied regions, ", k) else - newvals = p[!,2] + newvals = p[!, 2] params[k] = Array{Float64,1}(newvals) # Coerce to Array{Float64,1} end - # Time-country data matrices parameter case + # Time-country data matrices parameter case elseif size(p, 2) > 3 # Alphabetize @@ -235,9 +235,9 @@ function parse_ciam_params!(params, rgn_order, seg_order, surgeoption) p = p[!, sort(col_names)] params[k] = Array{Float64,2}(p) - # Single dimension parameter case - elseif size(p, 2)==1 - params[k] = Array{Float64,1}(p[!,1]) + # Single dimension parameter case + elseif size(p, 2) == 1 + params[k] = Array{Float64,1}(p[!, 1]) end end @@ -266,7 +266,7 @@ function filter_index(v1, v2) push!(out, i) end end - return(out) + return (out) end """ @@ -276,17 +276,17 @@ segments/regions """ function prepxsc(subset) - data_dir = joinpath(@__DIR__,"..","data","input") + data_dir = joinpath(@__DIR__, "..", "data", "input") xscfile = "xsc.csv" xsc_name = replace(xscfile, r".csv" => s"") # Strip ".csv" from file name # Read in csv and convert to dictionary format - xsc_params = Dict{Any, Any}(lowercase(splitext(xscfile)[1]) => CSV.read(joinpath(data_dir, xscfile), DataFrame)) - xsc_char = Dict{Any,Any}( xsc_params[xsc_name][i,1] => (xsc_params[xsc_name][i,2],xsc_params[xsc_name][i,3], xsc_params[xsc_name][i,4]) for i in 1:size(xsc_params[xsc_name],1)) + xsc_params = Dict{Any,Any}(lowercase(splitext(xscfile)[1]) => CSV.read(joinpath(data_dir, xscfile), DataFrame)) + xsc_char = Dict{Any,Any}(xsc_params[xsc_name][i, 1] => (xsc_params[xsc_name][i, 2], xsc_params[xsc_name][i, 3], xsc_params[xsc_name][i, 4]) for i in 1:size(xsc_params[xsc_name], 1)) # If only a subset of segments is used, filter down to relevant segments - if subset!=false - filter!(p-> (first(p) in subset), xsc_char) + if subset != false + filter!(p -> (first(p) in subset), xsc_char) end # Create region and segment indices @@ -331,22 +331,22 @@ function findind(val, vec) end function load_subset(subset=false) - dir = joinpath(@__DIR__,"..","data","subsets") + dir = joinpath(@__DIR__, "..", "data", "subsets") if subset != false - subs = readlines(joinpath(dir,subset)) + subs = readlines(joinpath(dir, subset)) return subs else return false end end -function init(; f::Union{String, Nothing} = nothing) +function init(; f::Union{String,Nothing}=nothing) if isnothing(f) - f = joinpath(@__DIR__,"..","data","batch","init.csv") + f = joinpath(@__DIR__, "..", "data", "batch", "init.csv") end - varnames=CSV.read(f, DataFrame) - vardict = Dict{Any,Any}( String(i) => varnames[!,i] for i in names(varnames)) - return(vardict) + varnames = CSV.read(f, DataFrame) + vardict = Dict{Any,Any}(String(i) => varnames[!, i] for i in names(varnames)) + return (vardict) end """ @@ -360,7 +360,7 @@ Wrapper for importing model data with the arguments: - popinput - population density data set to be used (0=original CIAM, 1=Jones and O'Neill 2016 (not supported), 2=Merkens et al 2016 (not supported)) - surgeoption - surge exposure data set to use (0=original CIAM/DINAS-COAST, 1=D-C corrected by GTSR/D-C bias, 2=GTSR nearest data point(s)) """ -function import_model_data(lslfile,sub,ssp,ssp_simplified,popinput,surgeoption) +function import_model_data(lslfile, sub, ssp, ssp_simplified, popinput, surgeoption) subset = (sub == "false") ? false : load_subset(sub) @@ -372,29 +372,29 @@ function import_model_data(lslfile,sub,ssp,ssp_simplified,popinput,surgeoption) # Process params using xsc and format lsl file parse_ciam_params!(params, xsc[2], xsc[3], surgeoption) - preplsl!(lslfile, subset, params,xsc[3]) - prepssp!(ssp,ssp_simplified,params,xsc[2],xsc[3],popinput) + preplsl!(lslfile, subset, params, xsc[3]) + prepssp!(ssp, ssp_simplified, params, xsc[2], xsc[3], popinput) - return(params, xsc) + return (params, xsc) end function load_meta() - metadir = joinpath(@__DIR__,"..","data","meta") + metadir = joinpath(@__DIR__, "..", "data", "meta") # Read header and mappings - header = read(open(joinpath(metadir,"header.txt")),String) + header = read(open(joinpath(metadir, "header.txt")), String) - varnames = readlines(open(joinpath(metadir,"variablenames.csv"))) - vardict = Dict{Any,Any}(split(varnames[i],',')[1] => (split(varnames[i],',')[2],split(varnames[i],',')[3]) for i in 1:length(varnames)) + varnames = readlines(open(joinpath(metadir, "variablenames.csv"))) + vardict = Dict{Any,Any}(split(varnames[i], ',')[1] => (split(varnames[i], ',')[2], split(varnames[i], ',')[3]) for i in 1:length(varnames)) protect = readlines(open(joinpath(metadir, "protectlevels.csv"))) - protectdict = Dict{Any,Any}(parse(Int,split(protect[i],',')[1]) => split(protect[i],',')[2] for i in 1:length(protect)) + protectdict = Dict{Any,Any}(parse(Int, split(protect[i], ',')[1]) => split(protect[i], ',')[2] for i in 1:length(protect)) retreat = readlines(open(joinpath(metadir, "retreatlevels.csv"))) - retreatdict = Dict{Any,Any}(parse(Int,split(retreat[i],',')[1]) => split(retreat[i],',')[2] for i in 1:length(retreat)) + retreatdict = Dict{Any,Any}(parse(Int, split(retreat[i], ',')[1]) => split(retreat[i], ',')[2] for i in 1:length(retreat)) - return(header,vardict, protectdict, retreatdict) + return (header, vardict, protectdict, retreatdict) end @@ -414,18 +414,18 @@ Write out model results to CSV file using arguments: - tag To do: possibly modify to work with DataVoyager() """ -function write_ciam(model; outputdir::String = joinpath(@__DIR__,"..","output"),runname::String = "base", sumsegs::String = "seg", varnames::Bool = false, tag::Bool = false) +function write_ciam(model; outputdir::String=joinpath(@__DIR__, "..", "output"), runname::String="base", sumsegs::String="seg", varnames::Bool=false, tag::Bool=false) meta_output = load_meta() - rcp = model[:slrcost,:rcp] - pctl = model[:slrcost,:percentile] - ssp = model[:slrcost,:ssp] - fixed = (model[:slrcost, :fixed]) ? "fixed" : "flex" - rcp_str = "$(rcp)p$(pctl)ssp$(ssp)$(fixed)" + rcp = model[:slrcost, :rcp] + pctl = model[:slrcost, :percentile] + ssp = model[:slrcost, :ssp] + fixed = (model[:slrcost, :fixed]) ? "fixed" : "flex" + rcp_str = "$(rcp)p$(pctl)ssp$(ssp)$(fixed)" - xsc = load_xsc() - segmap = load_segmap() - segRgnDict = Dict{Any,Any}(xsc[!,:seg][i] => xsc[!,:rgn][i] for i in 1:size(xsc,1)) + xsc = load_xsc() + segmap = load_segmap() + segRgnDict = Dict{Any,Any}(xsc[!, :seg][i] => xsc[!, :rgn][i] for i in 1:size(xsc, 1)) if varnames == false varnames = [k for k in keys(meta_output[2])] # to do change @@ -435,7 +435,7 @@ function write_ciam(model; outputdir::String = joinpath(@__DIR__,"..","output"), vargroup2 = [] # vars greater than 2D for v in varnames - if length(size(model[:slrcost,Symbol(v)])) > 2 + if length(size(model[:slrcost, Symbol(v)])) > 2 push!(vargroup2, Symbol(v)) else push!(vargroup1, Symbol(v)) @@ -452,16 +452,16 @@ function write_ciam(model; outputdir::String = joinpath(@__DIR__,"..","output"), if length(missing_names) >= 1 for name in missing_names - temp[!,name] = missings(size(temp)[1]) + temp[!, name] = missings(size(temp)[1]) end end if :ciam_country in missing_names && !(:segments in missing_names) - temp = temp |> @map(merge(_,{ciam_country=segRgnDict[_.segments]})) |> DataFrame + temp = temp |> @map(merge(_, {ciam_country = segRgnDict[_.segments]})) |> DataFrame end - temp[!,:variable] = fill(String(vargroup1[i]), nrow(temp)) - rename!(temp,vargroup1[i] => :value) + temp[!, :variable] = fill(String(vargroup1[i]), nrow(temp)) + rename!(temp, vargroup1[i] => :value) temp = temp[!, [:time, :ciam_country, :segments, :level, :variable, :value]] if i == 1 @@ -474,37 +474,37 @@ function write_ciam(model; outputdir::String = joinpath(@__DIR__,"..","output"), # Assign 3D variables to second data frame and join ntime = model[:slrcost, :ntsteps] segID = model[:slrcost, :segID] - colnames = Symbol.(segID_to_seg(Int64.(segID),segmap)) + colnames = Symbol.(segID_to_seg(Int64.(segID), segmap)) for j in 1:length(vargroup2) - ndim1 = size(model[:slrcost,vargroup2[j]])[3] + ndim1 = size(model[:slrcost, vargroup2[j]])[3] for k in 1:ndim1 - temp = DataFrame(model[:slrcost,vargroup2[j]][:,:,k], :auto) + temp = DataFrame(model[:slrcost, vargroup2[j]][:, :, k], :auto) - rename!(temp, colnames ) - temp[!,:time] = 1:ntime + rename!(temp, colnames) + temp[!, :time] = 1:ntime - if String(vargroup2[j])=="Construct" || occursin("Protect",String(vargroup2[j])) - dim1 = k+1 - adapt=model[:slrcost,:adaptoptions][dim1] + if String(vargroup2[j]) == "Construct" || occursin("Protect", String(vargroup2[j])) + dim1 = k + 1 + adapt = model[:slrcost, :adaptoptions][dim1] else - dim1=k - adapt=model[:slrcost,:adaptoptions][dim1] + dim1 = k + adapt = model[:slrcost, :adaptoptions][dim1] end - temp[!,:level] = fill(adapt, ntime) - temp = stack(temp,colnames) + temp[!, :level] = fill(adapt, ntime) + temp = stack(temp, colnames) - rename!(temp,:variable => :segments) + rename!(temp, :variable => :segments) - temp[!,:segments] = [String(i) for i in temp[!,:segments]] - temp[!,:variable]= fill(String(vargroup2[j]),nrow(temp)) + temp[!, :segments] = [String(i) for i in temp[!, :segments]] + temp[!, :variable] = fill(String(vargroup2[j]), nrow(temp)) - temp = temp |> @map(merge(_,{ciam_country=segRgnDict[_.segments]})) |> DataFrame - temp = temp[!,[:time,:ciam_country,:segments,:level,:variable,:value]] + temp = temp |> @map(merge(_, {ciam_country = segRgnDict[_.segments]})) |> DataFrame + temp = temp[!, [:time, :ciam_country, :segments, :level, :variable, :value]] if j == 1 && k == 1 global df2 = temp @@ -518,15 +518,15 @@ function write_ciam(model; outputdir::String = joinpath(@__DIR__,"..","output"), outdf = [df; df2] outfile = tag ? "$(runname)_$(sumsegs)_$(rcp_str)_$(tag).csv" : "$(runname)_$(sumsegs)_$(rcp_str).csv" - if sumsegs=="rgn" - rgndf = outdf |> @groupby({_.time,_.ciam_country, _.level, _.variable}) |> @map(merge(key(_),{value = sum(_.value)})) |> DataFrame - CSV.write(joinpath(outputdir,outfile),rgndf) - elseif sumsegs=="seg" - CSV.write(joinpath(outputdir,outfile),outdf) - elseif sumsegs=="global" + if sumsegs == "rgn" + rgndf = outdf |> @groupby({_.time, _.ciam_country, _.level, _.variable}) |> @map(merge(key(_), {value = sum(_.value)})) |> DataFrame + CSV.write(joinpath(outputdir, outfile), rgndf) + elseif sumsegs == "seg" + CSV.write(joinpath(outputdir, outfile), outdf) + elseif sumsegs == "global" globdf = outdf |> @groupby({_.time, _.level, _.variable}) |> - @map(merge(key(_),{value = sum(_.value)})) |> DataFrame - CSV.write(joinpath(outputdir,outfile),globdf) + @map(merge(key(_), {value = sum(_.value)})) |> DataFrame + CSV.write(joinpath(outputdir, outfile), globdf) end end @@ -535,24 +535,24 @@ end Streamline writing results for optimal adaptation costs. """ -function write_optimal_costs(model; outputdir::String = joinpath(@__DIR__,"..","output"), runname="base") +function write_optimal_costs(model; outputdir::String=joinpath(@__DIR__, "..", "output"), runname="base") # Output: Data Frame with segment,region,time,level,option, suboption # E.g. 'OptimalProtect', 'Construct' # Should output 2 CSVs: 1 with just the 3 main categories, 2nd with # detailed subcategories - rcp = model[:slrcost,:rcp] - pctl = model[:slrcost,:percentile] - ssp = model[:slrcost,:ssp] - fixed = (model[:slrcost, :fixed]) ? "fixed" : "flex" + rcp = model[:slrcost, :rcp] + pctl = model[:slrcost, :percentile] + ssp = model[:slrcost, :ssp] + fixed = (model[:slrcost, :fixed]) ? "fixed" : "flex" rcp_str = "$(rcp)p$(pctl)ssp$(ssp)$(fixed)" - xsc = load_xsc() - segRgnDict = Dict{Any,Any}( xsc[!,:seg][i] => xsc[!,:rgn][i] for i in 1:size(xsc,1)) + xsc = load_xsc() + segRgnDict = Dict{Any,Any}(xsc[!, :seg][i] => xsc[!, :rgn][i] for i in 1:size(xsc, 1)) # 1. Create aggregate adaptation decision DF temp1 = getdataframe(model, :slrcost => :OptimalCost) - temp1 = temp1 |> @map(merge(_,{ciam_country=segRgnDict[_.segments]})) |> DataFrame + temp1 = temp1 |> @map(merge(_, {ciam_country = segRgnDict[_.segments]})) |> DataFrame temp2 = getdataframe(model, :slrcost => :OptimalLevel) temp3 = getdataframe(model, :slrcost => :OptimalOption) @@ -560,86 +560,86 @@ function write_optimal_costs(model; outputdir::String = joinpath(@__DIR__,".."," # Join dataframes and reorganize # Inner join to restrict to only rows in both dataframes # (which should be all of time, because all segments should have values at all time steps) - out = innerjoin(temp1,temp2, on = [:time,:segments]) - out = innerjoin(out,temp3, on = [:time,:segments]) + out = innerjoin(temp1, temp2, on=[:time, :segments]) + out = innerjoin(out, temp3, on=[:time, :segments]) # Replace OptimalOption numeric value with string - lookup = Dict{Any,Any}(-2.0=> "RetreatCost", -1.0=> "ProtectCost",-3.0=>"NoAdaptCost") - out = out |> @map(merge(_,{variable=lookup[_.OptimalOption]})) |> DataFrame + lookup = Dict{Any,Any}(-2.0 => "RetreatCost", -1.0 => "ProtectCost", -3.0 => "NoAdaptCost") + out = out |> @map(merge(_, {variable = lookup[_.OptimalOption]})) |> DataFrame rename!(out, Dict(:OptimalLevel => :level)) - out = out[!,[:time, :ciam_country, :segments, :variable, :level, :OptimalCost]] + out = out[!, [:time, :ciam_country, :segments, :variable, :level, :OptimalCost]] # Write to file outfile = "$(runname)_seg_$(rcp_str)_optimal.csv" - CSV.write(joinpath(outputdir,outfile),out) + CSV.write(joinpath(outputdir, outfile), out) # Write Sub-Costs vars = [:OptimalStormCapital, :OptimalStormPop, :OptimalConstruct, - :OptimalFlood, :OptimalRelocate, :OptimalWetland] + :OptimalFlood, :OptimalRelocate, :OptimalWetland] for i in 1:length(vars) temp = getdataframe(model, :slrcost => vars[i]) - temp = temp |> @map(merge(_,{ciam_country=segRgnDict[_.segments]})) |> DataFrame + temp = temp |> @map(merge(_, {ciam_country = segRgnDict[_.segments]})) |> DataFrame - temp[!,:variable]= fill(String(vars[i]),nrow(temp)) + temp[!, :variable] = fill(String(vars[i]), nrow(temp)) temp2 = getdataframe(model, :slrcost => :OptimalLevel) temp3 = getdataframe(model, :slrcost => :OptimalOption) # Join dataframes and reorganize - out = innerjoin(temp,temp2, on=[:time,:segments]) - out = innerjoin(out,temp3, on=[:time,:segments]) + out = innerjoin(temp, temp2, on=[:time, :segments]) + out = innerjoin(out, temp3, on=[:time, :segments]) # Replace OptimalOption numeric value with string - lookup = Dict{Any,Any}(-2.0=> "RetreatCost", -1.0=> "ProtectCost",-3.0=>"NoAdaptCost") - out = out |> @map(merge(_,{AdaptCategory=lookup[_.OptimalOption]})) |> DataFrame + lookup = Dict{Any,Any}(-2.0 => "RetreatCost", -1.0 => "ProtectCost", -3.0 => "NoAdaptCost") + out = out |> @map(merge(_, {AdaptCategory = lookup[_.OptimalOption]})) |> DataFrame rename!(out, Dict(:OptimalLevel => :level)) - rename!(out,vars[i]=>:value) - out = out[!,[:time,:ciam_country,:segments,:AdaptCategory,:variable,:level,:value]] + rename!(out, vars[i] => :value) + out = out[!, [:time, :ciam_country, :segments, :AdaptCategory, :variable, :level, :value]] - if i==1 + if i == 1 global df = out else - df = [df;out] + df = [df; out] end end # Write to CSV outfile2 = "$(runname)_seg_$(rcp_str)_optimal_subcost.csv" - CSV.write(joinpath(outputdir,outfile2),df) + CSV.write(joinpath(outputdir, outfile2), df) end function write_optimal_protect_retreat(model; runname="base") - outputdir = joinpath(@__DIR__,"..","output") - rcp = model[:slrcost,:rcp] - pctl = model[:slrcost,:percentile] - ssp = model[:slrcost,:ssp] - fixed = (model[:slrcost,:fixed]) ? "fixed" : "flex" + outputdir = joinpath(@__DIR__, "..", "output") + rcp = model[:slrcost, :rcp] + pctl = model[:slrcost, :percentile] + ssp = model[:slrcost, :ssp] + fixed = (model[:slrcost, :fixed]) ? "fixed" : "flex" rcp_str = "$(rcp)p$(pctl)ssp$(ssp)$(fixed)" - xsc = load_xsc() + xsc = load_xsc() # segRgnDict = Dict{Any,Any}( xsc[!,:seg][i] => xsc[!,:rgn][i] for i in 1:size(xsc,1)) # note this isn't used # 1. Create aggregate adaptation decision DF pl = getdataframe(model, :slrcost => :OptimalProtectLevel) rl = getdataframe(model, :slrcost => :OptimalRetreatLevel) - out = innerjoin(pl,rl, on=[:time,:segments]) + out = innerjoin(pl, rl, on=[:time, :segments]) ## To do: read in protect, retreat variables and filter to optimal levels; add to out protect = model[:slrcost, :ProtectCost] retreat = model[:slrcost, :RetreatCost] for i in 1:5 - if i>1 - prot = DataFrame(model[:slrcost,:ProtectCost][:,:,i-1]) - ret = DataFrame(model[:slrcost,:RetreatCost][:,:,i]) + if i > 1 + prot = DataFrame(model[:slrcost, :ProtectCost][:, :, i-1]) + ret = DataFrame(model[:slrcost, :RetreatCost][:, :, i]) else - ret = DataFrame(model[:slrcost,:RetreatCost][:,:,i]) + ret = DataFrame(model[:slrcost, :RetreatCost][:, :, i]) end end outfile = "$(runname)_seg_$(rcp_str)_ProtectRetreat.csv" - CSV.write(joinpath(outputdir,outfile),out) + CSV.write(joinpath(outputdir, outfile), out) end @@ -648,14 +648,14 @@ end ## --------------------------------- function load_segmap() - segmap = CSV.read(joinpath(@__DIR__, "..", "data","meta", "segIDmap.csv"), DataFrame) |> DataFrame - segmap[!,:segID] = [Int64(i) for i in segmap[!,:segID]] - return(segmap) + segmap = CSV.read(joinpath(@__DIR__, "..", "data", "meta", "segIDmap.csv"), DataFrame) |> DataFrame + segmap[!, :segID] = [Int64(i) for i in segmap[!, :segID]] + return (segmap) end function load_xsc() - xsc = CSV.read(joinpath(@__DIR__,"..","data","input","xsc.csv"), DataFrame) |> DataFrame - return(xsc) + xsc = CSV.read(joinpath(@__DIR__, "..", "data", "input", "xsc.csv"), DataFrame) |> DataFrame + return (xsc) end """ @@ -668,8 +668,8 @@ ID entry as an array. The arguments are as follows: - segmap - output of load_rgnmap or load_segmap() (DataFrame) """ function segID_to_seg(segID, segmap) - seg = [String(segmap[!,:seg][segmap.segID.==i][1]) for i in segID] - return(seg) + seg = [String(segmap[!, :seg][segmap.segID.==i][1]) for i in segID] + return (seg) end """ @@ -678,8 +678,8 @@ end Get segID from string name of segment. Segstr must be an array of strings """ function segStr_to_segID(segstr) - ids = [parse(Int64,replace(i, r"[^0-9]"=> "")) for i in segstr] - return(ids) + ids = [parse(Int64, replace(i, r"[^0-9]" => "")) for i in segstr] + return (ids) end """ @@ -688,29 +688,29 @@ end Return time series of costs at global, regional and/or segment level scale and also compute cost as percent of regional or global gdp. """ -function getTimeSeries(model, ensnum; segIDs = false, rgns = false, sumsegs = "global") +function getTimeSeries(model, ensnum; segIDs=false, rgns=false, sumsegs="global") # If not using segment-level aggregation, segIDs refers to # individual segments to report in addition to global/regional if sumsegs == "seg" # Report all segments in model or those specified if segIDs == false - segIDs = model[:slrcost,:segID] + segIDs = model[:slrcost, :segID] end end xsc = MimiCIAM.load_xsc() - segRgnDict = Dict{Any,Any}( xsc[!,:seg][i] => (xsc[!,:rgn][i],xsc[!,:segID][i]) for i in 1:size(xsc,1)) + segRgnDict = Dict{Any,Any}(xsc[!, :seg][i] => (xsc[!, :rgn][i], xsc[!, :segID][i]) for i in 1:size(xsc, 1)) # Write Main and Sub-Costs - vars = [:OptimalCost,:OptimalStormCapital, :OptimalStormPop, :OptimalConstruct, + vars = [:OptimalCost, :OptimalStormCapital, :OptimalStormPop, :OptimalConstruct, :OptimalFlood, :OptimalRelocate, :OptimalWetland] global df = DataFrame() for i in 1:length(vars) temp = MimiCIAM.getdataframe(model, :slrcost => vars[i]) - temp = temp |> @map(merge(_,{ciam_country=segRgnDict[_.segments][1],segID=segRgnDict[_.segments][2]})) |> DataFrame + temp = temp |> @map(merge(_, {ciam_country = segRgnDict[_.segments][1], segID = segRgnDict[_.segments][2]})) |> DataFrame #temp[!,:costtype]= String(vars[i]) temp2 = MimiCIAM.getdataframe(model, :slrcost => :OptimalLevel) @@ -719,86 +719,86 @@ function getTimeSeries(model, ensnum; segIDs = false, rgns = false, sumsegs = "g temp5 = MimiCIAM.getdataframe(model, :slrcost => :pop) # Join dataframes and reorganize - out = innerjoin(temp,temp2, on=[:time,:segments]) - out = innerjoin(out,temp3, on=[:time,:segments]) - out = innerjoin(out,temp4, on=[:time,:ciam_country]) - out = innerjoin(out,temp5, on=[:time,:ciam_country]) + out = innerjoin(temp, temp2, on=[:time, :segments]) + out = innerjoin(out, temp3, on=[:time, :segments]) + out = innerjoin(out, temp4, on=[:time, :ciam_country]) + out = innerjoin(out, temp5, on=[:time, :ciam_country]) # Replace OptimalOption numeric value with string - lookup = Dict{Any,Any}(-2.0=> "Retreat", -1.0=> "Protection",-3.0=>"No Adaptation") - out = out |> @map(merge(_,{category=lookup[_.OptimalOption]})) |> DataFrame + lookup = Dict{Any,Any}(-2.0 => "Retreat", -1.0 => "Protection", -3.0 => "No Adaptation") + out = out |> @map(merge(_, {category = lookup[_.OptimalOption]})) |> DataFrame rename!(out, Dict(:OptimalLevel => :level)) - rename!(out,vars[i]=>:cost) + rename!(out, vars[i] => :cost) - out[!,:ens] = fill(ensnum, size(out)[1]) - col_order=[:ens,:time,:ciam_country,:segments,:segID,:category,:level,:cost,:ypcc,:pop] - out = out[!,col_order] + out[!, :ens] = fill(ensnum, size(out)[1]) + col_order = [:ens, :time, :ciam_country, :segments, :segID, :category, :level, :cost, :ypcc, :pop] + out = out[!, col_order] # Aggregate to geographic level - subset = filter(row -> row[:segID] in segIDs,out) + subset = filter(row -> row[:segID] in segIDs, out) - if sumsegs=="rgn" - rgndf = out |> @groupby({_.ens,_.time,_.ciam_country, _.level, _.category,_.ypcc,_.pop}) |> @map(merge(key(_),{cost = sum(_.cost)})) |> DataFrame - rgndf[!,:segID] = fill(0., size(rgndf)[1]) + if sumsegs == "rgn" + rgndf = out |> @groupby({_.ens, _.time, _.ciam_country, _.level, _.category, _.ypcc, _.pop}) |> @map(merge(key(_), {cost = sum(_.cost)})) |> DataFrame + rgndf[!, :segID] = fill(0., size(rgndf)[1]) rgndf[:segments] = fill("regional", size(rgndf)[1]) - rgndf = rgndf[!,col_order] - rgndf = [rgndf;subset] - - rgndf[!,:gdp]=rgndf[!,:ypcc].*rgndf[!,:pop]./1e3 # GDP is in $Billion (this will be regional for subset too) - rgndf[!,:pct_gdp]=rgndf[!,:cost]./rgndf[!,:gdp] # Annual cost / annual GDP - out=rgndf - - elseif sumsegs=="global" - - globdf = out |> @groupby({_.ens,_.time, _.level, _.category}) |> - @map(merge(key(_),{cost = sum(_.cost)})) |> DataFrame - - globsoc = innerjoin(temp4,temp5,on=[:time,:ciam_country]) - globsoc[!,:gdp] = globsoc[!,:ypcc].*globsoc[!,:pop]./1e3 - globsoc[!,:ens] = fill(ensnum, size(globsoc)[1]) - globsoc = globsoc |> @groupby({_.ens,_.time}) |> - @map(merge(key(_), {ypcc=sum(_.gdp), pop=sum(_.pop),gdp=sum(_.gdp)})) |> DataFrame - globsoc[!,:ypcc] = (globsoc[!,:gdp].*1e9)./(globsoc[!,:pop].*1e6) - - globdf = innerjoin(globdf,globsoc,on=[:ens,:time]) - globdf[!,:segID] = fill(0., size(globdf)[1]) - globdf[!,:ciam_country] = fill("global", size(globdf)[1]) - globdf[!,:segments] = fill("global", size(globdf)[1]) - globdf=globdf[!, [:ens,:time,:ciam_country,:segments,:segID,:category,:level,:cost,:ypcc,:pop,:gdp]] - subset[!,:gdp]=subset[!,:ypcc].*subset[!,:pop]./1e3 - globdf=[globdf;subset] - - globdf[!,:pct_gdp] = globdf[!,:cost] ./ globdf[!,:gdp] - - if rgns!=false - rgndf = filter(row -> row[:ciam_country] in rgns,out) - rgndf = rgndf |> @groupby({_.ens,_.time,_.ciam_country, _.level, _.category,_.ypcc,_.pop}) |> @map(merge(key(_),{cost = sum(_.cost)})) |> DataFrame - rgndf[!,:segID] = fill(0., size(rgndf)[1]) - rgndf[!,:segments] = fill("regional", size(rgndf)[1]) - rgndf = rgndf[!,col_order] - - rgndf[!,:gdp]=rgndf[!,:ypcc].*rgndf[!,:pop]./1e3 # GDP is in $Billion (this will be regional for subset too) - rgndf[!,:pct_gdp]=rgndf[!,:cost]./rgndf[!,:gdp] # Annual cost / annual GDP - - globdf=[globdf; rgndf] + rgndf = rgndf[!, col_order] + rgndf = [rgndf; subset] + + rgndf[!, :gdp] = rgndf[!, :ypcc] .* rgndf[!, :pop] ./ 1e3 # GDP is in $Billion (this will be regional for subset too) + rgndf[!, :pct_gdp] = rgndf[!, :cost] ./ rgndf[!, :gdp] # Annual cost / annual GDP + out = rgndf + + elseif sumsegs == "global" + + globdf = out |> @groupby({_.ens, _.time, _.level, _.category}) |> + @map(merge(key(_), {cost = sum(_.cost)})) |> DataFrame + + globsoc = innerjoin(temp4, temp5, on=[:time, :ciam_country]) + globsoc[!, :gdp] = globsoc[!, :ypcc] .* globsoc[!, :pop] ./ 1e3 + globsoc[!, :ens] = fill(ensnum, size(globsoc)[1]) + globsoc = globsoc |> @groupby({_.ens, _.time}) |> + @map(merge(key(_), {ypcc = sum(_.gdp), pop = sum(_.pop), gdp = sum(_.gdp)})) |> DataFrame + globsoc[!, :ypcc] = (globsoc[!, :gdp] .* 1e9) ./ (globsoc[!, :pop] .* 1e6) + + globdf = innerjoin(globdf, globsoc, on=[:ens, :time]) + globdf[!, :segID] = fill(0., size(globdf)[1]) + globdf[!, :ciam_country] = fill("global", size(globdf)[1]) + globdf[!, :segments] = fill("global", size(globdf)[1]) + globdf = globdf[!, [:ens, :time, :ciam_country, :segments, :segID, :category, :level, :cost, :ypcc, :pop, :gdp]] + subset[!, :gdp] = subset[!, :ypcc] .* subset[!, :pop] ./ 1e3 + globdf = [globdf; subset] + + globdf[!, :pct_gdp] = globdf[!, :cost] ./ globdf[!, :gdp] + + if rgns != false + rgndf = filter(row -> row[:ciam_country] in rgns, out) + rgndf = rgndf |> @groupby({_.ens, _.time, _.ciam_country, _.level, _.category, _.ypcc, _.pop}) |> @map(merge(key(_), {cost = sum(_.cost)})) |> DataFrame + rgndf[!, :segID] = fill(0., size(rgndf)[1]) + rgndf[!, :segments] = fill("regional", size(rgndf)[1]) + rgndf = rgndf[!, col_order] + + rgndf[!, :gdp] = rgndf[!, :ypcc] .* rgndf[!, :pop] ./ 1e3 # GDP is in $Billion (this will be regional for subset too) + rgndf[!, :pct_gdp] = rgndf[!, :cost] ./ rgndf[!, :gdp] # Annual cost / annual GDP + + globdf = [globdf; rgndf] end - out=globdf + out = globdf else - out[!,:gdp]= out[!,:ypcc] .* out[!,:pop] ./1e3 # Regional gdp by segment - out[!,:pct_gdp] = out[!,:cost] ./ out[!,:gdp] # Segment cost or subcost as % of regional gdp + out[!, :gdp] = out[!, :ypcc] .* out[!, :pop] ./ 1e3 # Regional gdp by segment + out[!, :pct_gdp] = out[!, :cost] ./ out[!, :gdp] # Segment cost or subcost as % of regional gdp end - if i==1 + if i == 1 global df = out else - df = [df;out] + df = [df; out] end end # Remove ypcc and pop from final df - df = df[!,[:ens,:time,:ciam_country,:segments,:segID,:category,:level,:cost,:gdp,:pct_gdp]] + df = df[!, [:ens, :time, :ciam_country, :segments, :segID, :category, :level, :cost, :gdp, :pct_gdp]] return df end @@ -814,11 +814,11 @@ IN PROGRESS - Create a writelog function to go with a wrapper for the run functi automatically produce a logfile """ function writelog() - dir=joinpath(@__DIR__,"..","data","batch","logs") + dir = joinpath(@__DIR__, "..", "data", "batch", "logs") d = init() run = d["run_name"] date = Dates.now() - cp("../data/batch/init.csv", joinpath(dir,"$(run)_$(date).csv")) + cp("../data/batch/init.csv", joinpath(dir, "$(run)_$(date).csv")) end using CSV @@ -834,11 +834,11 @@ Write the init.csv file for a specificied `run_name` into `outputdir` using init found in `init_settings`. """ function write_init_file(run_name::String, outputdir::String, init_settings::Dict) - textheader="run_name,lslr,subset,ssp,ssp_simplified\n" + textheader = "run_name,lslr,subset,ssp,ssp_simplified\n" textstr = "$(run_name),$(init_settings[:lslrfile]),$(init_settings[:subset]),$(init_settings[:ssp]),$(init_settings[:ssp_simplified])" - txtfile = open(joinpath(outputdir, init_settings[:init_filename]),"w") do io - write(io,textheader) - write(io,textstr) + txtfile = open(joinpath(outputdir, init_settings[:init_filename]), "w") do io + write(io, textheader) + write(io, textstr) end end @@ -855,11 +855,11 @@ function write_output_files(m, outputdir::String, run_name::String) # write out the results println("Writing out ciam `subsegs = seg` file for run $(run_name) to directory $(outputdir)") - MimiCIAM.write_ciam(m; outputdir = outputdir, runname = run_name, sumsegs="seg", varnames=false) + MimiCIAM.write_ciam(m; outputdir=outputdir, runname=run_name, sumsegs="seg", varnames=false) println("Writing out ciam `subsegs = global` file for run $(run_name) to directory $(outputdir)") - MimiCIAM.write_ciam(m; outputdir = outputdir, runname = run_name, sumsegs="global", varnames=false) + MimiCIAM.write_ciam(m; outputdir=outputdir, runname=run_name, sumsegs="global", varnames=false) println("Writing out optimal costs file for run $(run_name) to directory $(outputdir)") - MimiCIAM.write_optimal_costs(m; outputdir = outputdir, runname = run_name) + MimiCIAM.write_optimal_costs(m; outputdir=outputdir, runname=run_name) end @@ -874,34 +874,34 @@ end function calcCoastArea(areaparams, var) - area = (areaparams[1]*max(0,min(0.5,var-0)) - +(areaparams[1]+areaparams[2])/2*max(0,min(1,var-0.5)) - +areaparams[2]*max(0,min(0.5,var-1.5)) - +areaparams[3]*max(0,min(1,var-2)) - +areaparams[4]*max(0,min(1,var-3)) - +areaparams[5]*max(0,min(1,var-4)) - +areaparams[6]*max(0,min(1,var-5)) - +areaparams[7]*max(0,min(1,var-6)) - +areaparams[8]*max(0,min(1,var-7)) - +areaparams[9]*max(0,min(1,var-8)) - +areaparams[10]*max(0,min(1,var-9)) - +areaparams[11]*max(0,min(1,var-10)) - +areaparams[12]*max(0,min(1,var-11)) - +areaparams[13]*max(0,min(1,var-12)) - +areaparams[14]*max(0,min(1,var-13)) - +areaparams[15]*max(0,var-14)) + area = (areaparams[1] * max(0, min(0.5, var - 0)) + + (areaparams[1] + areaparams[2]) / 2 * max(0, min(1, var - 0.5)) + + areaparams[2] * max(0, min(0.5, var - 1.5)) + + areaparams[3] * max(0, min(1, var - 2)) + + areaparams[4] * max(0, min(1, var - 3)) + + areaparams[5] * max(0, min(1, var - 4)) + + areaparams[6] * max(0, min(1, var - 5)) + + areaparams[7] * max(0, min(1, var - 6)) + + areaparams[8] * max(0, min(1, var - 7)) + + areaparams[9] * max(0, min(1, var - 8)) + + areaparams[10] * max(0, min(1, var - 9)) + + areaparams[11] * max(0, min(1, var - 10)) + + areaparams[12] * max(0, min(1, var - 11)) + + areaparams[13] * max(0, min(1, var - 12)) + + areaparams[14] * max(0, min(1, var - 13)) + + areaparams[15] * max(0, var - 14)) return area end function localrate(lslr1, lslr2, tstep) - return max(0, (lslr2 - lslr1))/tstep + return max(0, (lslr2 - lslr1)) / tstep end function getsegments(rgn_name, xsc) - segs = collect(keys(filter( (k,v) -> v[1]==rgn_name,xsc))) + segs = collect(keys(filter((k, v) -> v[1] == rgn_name, xsc))) return segs end @@ -926,12 +926,12 @@ function calcHorR(option, level, lslrPlan, surgeExpLevels, adaptOptions) ind = findind(level, adaptOptions) - if option==-1 && level ==10 + if option == -1 && level == 10 # Protect height differs from retreat radius only in case of 10 yr surge exposure H = max(0, lslrPlan + surgeExpLevels[ind] / 2) return H - elseif level==0 # Maintain existing defenses - H_R=0 + elseif level == 0 # Maintain existing defenses + H_R = 0 return H_R else H_R = max(0, lslrPlan + surgeExpLevels[ind]) @@ -940,5 +940,5 @@ function calcHorR(option, level, lslrPlan, surgeExpLevels, adaptOptions) end function pos(x) - return max(0,x) + return max(0, x) end diff --git a/src/main.jl b/src/main.jl index 75acf29..2f45ab6 100644 --- a/src/main.jl +++ b/src/main.jl @@ -33,18 +33,18 @@ for file in lsl_files isdir(run_outputdir) || mkpath(run_outputdir) init_settings = Dict( - :init_filename => string("$run_name", "_init.csv"), - :lslrfile => file, - :subset => false, - :ssp => "IIASAGDP_SSP5_v9_130219", - :ssp_simplified => 5 + :init_filename => string("$run_name", "_init.csv"), + :lslrfile => file, + :subset => false, + :ssp => "IIASAGDP_SSP5_v9_130219", + :ssp_simplified => 5 ) MimiCIAM.write_init_file(run_name, run_outputdir, init_settings) - m = MimiCIAM.get_model(initfile = joinpath(run_outputdir, init_settings[:init_filename])) + m = MimiCIAM.get_model(initfile=joinpath(run_outputdir, init_settings[:init_filename])) run(m) - MimiCIAM.write_optimal_costs(m; outputdir = run_outputdir, runname = run_name) + MimiCIAM.write_optimal_costs(m; outputdir=run_outputdir, runname=run_name) # MimiCIAM.write_output_files(m; outputdir = outputdir, run_name = run_name) # writes three files end diff --git a/src/slrcost.jl b/src/slrcost.jl index 596b669..fc7b8f8 100644 --- a/src/slrcost.jl +++ b/src/slrcost.jl @@ -9,7 +9,7 @@ using Mimi adaptPers = Index() # --- Region / segment mapping --- - segID = Parameter(index = [segments]) # Unique segment numeric identifier + segID = Parameter(index=[segments]) # Unique segment numeric identifier xsc = Parameter{Dict{Int,Tuple{Int,Int,Int}}}() # Region to segment mapping (dictionary) to keep track of which segments belong to each region rcp = Parameter{Int}() # RCP being run (metadata; not used in run) percentile = Parameter{Int}() # Percentile of RCP being run (metadata; not used in run) @@ -17,7 +17,7 @@ using Mimi # ---Time-related Parameters--- tstep = Parameter() # Length of individual time-step (years) - at = Parameter(index = [adaptPers]) # Array of time indices that mark starts of adaptation periods + at = Parameter(index=[adaptPers]) # Array of time indices that mark starts of adaptation periods ntsteps = Parameter{Int}() # Number of time-steps # ---Model Parameters --- @@ -27,51 +27,51 @@ using Mimi # ---Socioeconomic Parameters--- popinput = Parameter{Int}() # Input for population data source: 0 (default), 1 (Jones & O'Neill, 2016), 2 (Merkens et al, 2016) - pop = Parameter(index = [time, ciam_country], unit = "million") # Population of region (million people) (from MERGE or SSPs) - refpopdens = Parameter(index = [ciam_country], unit = "persons/km2") # Reference population density of region (people / km^2) + pop = Parameter(index=[time, ciam_country], unit="million") # Population of region (million people) (from MERGE or SSPs) + refpopdens = Parameter(index=[ciam_country], unit="persons/km2") # Reference population density of region (people / km^2) rgn_ind_usa = Parameter{Int}() # Lookup parameter for USA region index, used in refpopdens and ypc # for USA benchmark in vsl, rho and fundland calculations - popdens = Parameter(index = [segments], unit = "persons/km2") # Pop density of segment in time t = 1 (people/km^2) - ypcc = Parameter(index = [time, ciam_country], unit = "US\$2010/yr/person") # GDP per capita per region ($2010 per capita) + popdens = Parameter(index=[segments], unit="persons/km2") # Pop density of segment in time t = 1 (people/km^2) + ypcc = Parameter(index=[time, ciam_country], unit="US\$2010/yr/person") # GDP per capita per region ($2010 per capita) - popdens_seg = Variable(index = [time, segments], unit = "persons/km2") # Population density of segment extrapolated forward in time (people / km^2) + popdens_seg = Variable(index=[time, segments], unit="persons/km2") # Population density of segment extrapolated forward in time (people / km^2) #popdens_seg_jones = Parameter(index=[time,segments], unit = "persons/km2") # Holder for Jones and O'Neill population density (not currently supported) #popdens_seg_merkens = Parameter(index=[time,segments], unit = "persons/km2") # Holder for Merkens et al population density (not currently supported) - ypc_seg = Variable(index = [time, segments], unit = "US\$2010/yr/person") # GDP per capita by segment ($2010 per capita) (multiplied by scaling factor) - refA_R = Parameter(index = [segments]) # Reference retreat level of adaptation in 0 period - refA_H = Parameter(index = [segments]) # Reference height for adaptation in 0 period + ypc_seg = Variable(index=[time, segments], unit="US\$2010/yr/person") # GDP per capita by segment ($2010 per capita) (multiplied by scaling factor) + refA_R = Parameter(index=[segments]) # Reference retreat level of adaptation in 0 period + refA_H = Parameter(index=[segments]) # Reference height for adaptation in 0 period # ---Land Parameters--- landinput = Parameter{Bool}() # Set to T for FUND or F for GTAP - gtapland = Parameter(index = [ciam_country], unit = "million US\$2010/km2") # GTAP land value in 2007 (million 2010$ / km^2) - dvbm = Parameter(unit = "million US\$2010/km2") # FUND value of OECD dryland per Darwin et al 1995 converted from $1995 ($2010M per sqkm) (5.376) + gtapland = Parameter(index=[ciam_country], unit="million US\$2010/km2") # GTAP land value in 2007 (million 2010$ / km^2) + dvbm = Parameter(unit="million US\$2010/km2") # FUND value of OECD dryland per Darwin et al 1995 converted from $1995 ($2010M per sqkm) (5.376) kgdp = Parameter() # Capital output ratio (per MERGE) (3 by default) discountrate = Parameter() # Discount rate (0.04 by default) depr = Parameter() # Fraction of capital that has not been depreciated over adaptation period (retreat cases) - landdata = Variable(index = [ciam_country], unit = "million US\$2010/km2") # Takes on value of either fundland or gtapland - fundland = Variable(index = [ciam_country], unit = "million US\$2010/km2") # FUND land value in 1995 (calculated in run_timestep) (million 2010$ / km^2), + landdata = Variable(index=[ciam_country], unit="million US\$2010/km2") # Takes on value of either fundland or gtapland + fundland = Variable(index=[ciam_country], unit="million US\$2010/km2") # FUND land value in 1995 (calculated in run_timestep) (million 2010$ / km^2), rgn_ind_canada = Parameter{Int}() # Region index for Canada (Used as reference for Greenland land appreciation) - land_appr = Variable(index = [time, ciam_country]) # Land appreciation rate (calculated as regression by Yohe ref Abraham and Hendershott) - coastland = Variable(index = [time, segments], unit = "million US\$2010/km2") # Coastal land value (function of interior land value * scaling factor) ($2010M per sqkm) - landvalue = Variable(index = [time, segments], unit = "million US\$2010/km2") # Total endowment value of land ($2010M per sqkm) - landrent = Variable(index = [time, segments], unit = "million US\$2010/km2/yr") # Annual rental value of land ($2010M/sqkm/year) + land_appr = Variable(index=[time, ciam_country]) # Land appreciation rate (calculated as regression by Yohe ref Abraham and Hendershott) + coastland = Variable(index=[time, segments], unit="million US\$2010/km2") # Coastal land value (function of interior land value * scaling factor) ($2010M per sqkm) + landvalue = Variable(index=[time, segments], unit="million US\$2010/km2") # Total endowment value of land ($2010M per sqkm) + landrent = Variable(index=[time, segments], unit="million US\$2010/km2/yr") # Annual rental value of land ($2010M/sqkm/year) - ρ = Variable(index = [time, ciam_country]) # Country-wide resilience parameter (logistic function related to GDP) - capital = Variable(index = [time, segments], unit = "million US\$2010/km2") # Total endowment value of capital stock (million $2010 / km^2) - discountfactor = Variable(index = [time]) # Discount factor (derived from discount rate) + ρ = Variable(index=[time, ciam_country]) # Country-wide resilience parameter (logistic function related to GDP) + capital = Variable(index=[time, segments], unit="million US\$2010/km2") # Total endowment value of capital stock (million $2010 / km^2) + discountfactor = Variable(index=[time]) # Discount factor (derived from discount rate) # ---Coastal Parameters--- - length = Parameter(index = [segments], unit = "km") # Segment length (km) + length = Parameter(index=[segments], unit="km") # Segment length (km) # ---Protection Parameters--- - cci = Parameter(index = [ciam_country]) + cci = Parameter(index=[ciam_country]) pcfixed = Parameter() # Fraction of protection cost that is fixed (not variable in height) (0.3) mc = Parameter() # Maintenance cost (Hillen et al, 2010) (2%/yr) - pc0 = Parameter(unit = "million US\$2010/km/m2") # Reference cost of protection (million 2010$ / km / vert m^2) (6.02 by default) + pc0 = Parameter(unit="million US\$2010/km/m2") # Reference cost of protection (million 2010$ / km / vert m^2) (6.02 by default) # ---Retreat / No Adapt Parameters--- mobcapfrac = Parameter() # Fraction of capital that is mobile (0.25) @@ -81,129 +81,129 @@ using Mimi # # ---Surge Exposure Parameters--- # Protection case - psig0 = Parameter(index = [segments]) - psig0coef = Parameter(index = [segments]) - psigA = Parameter(index = [segments]) # psigA in GAMS code - psigB = Parameter(index = [segments]) # psigB in GAMS code + psig0 = Parameter(index=[segments]) + psig0coef = Parameter(index=[segments]) + psigA = Parameter(index=[segments]) # psigA in GAMS code + psigB = Parameter(index=[segments]) # psigB in GAMS code # Retreat / No Adapt Cases - rsig0 = Parameter(index = [segments]) - rsigA = Parameter(index = [segments]) # rsigA in GAMS code - rsigB = Parameter(index = [segments]) # rsigB in GAMS code + rsig0 = Parameter(index=[segments]) + rsigA = Parameter(index=[segments]) # rsigA in GAMS code + rsigB = Parameter(index=[segments]) # rsigB in GAMS code # ---Storm damage parameters--- floodmortality = Parameter() # Flood deaths as percent of exposed population; (Jonkman Vrijling 2008) (0.01) # if TRUE, then VSL is exogenously calculated for each country and set in vsl_ciam_country, then each segment is set by looking up its country # if FALSE, then VSL is endogenously calculated using vslel and vslmult as well as other endogenous socioeconomics for each segment - vsl_exogenous = Parameter{Bool}(default=true) + vsl_exogenous = Parameter{Bool}(default=true) - vsl_ciam_country = Parameter(index = [time, ciam_country], unit = "million US\$2010/yr") # Value of statistical life (million 2010$) (only used for exogenous calculation of vsl) - vslel = Parameter(default = 0.5) # Elasticity of vsl (0.5) (only used for endogenous calculation of vsl) - vslmult = Parameter(default = 216) # multiplier on USA GDP (216)(only used for endogenous calculation of vsl) + vsl_ciam_country = Parameter(index=[time, ciam_country], unit="million US\$2010/yr") # Value of statistical life (million 2010$) (only used for exogenous calculation of vsl) + vslel = Parameter(default=0.5) # Elasticity of vsl (0.5) (only used for endogenous calculation of vsl) + vslmult = Parameter(default=216) # multiplier on USA GDP (216)(only used for endogenous calculation of vsl) - vsl = Variable(index = [time, segments], unit = "million US\$2010/yr") # Value of statistical life (million 2010$) + vsl = Variable(index=[time, segments], unit="million US\$2010/yr") # Value of statistical life (million 2010$) # ---Wetland Loss Parameters--- - wvbm = Parameter(default = 0.376, unit = "million US\$2010/km2/yr") # Annual value of wetland services (million 2010$ / km^2 / yr); (Brander et al 2006) (0.376) - wetland = Parameter(index = [segments], unit = "km2") # Initial wetland area in coastal segment (km^2) - wmaxrate = Parameter(default = 0.01, unit = "m/yr") # Maximum rate of wetland accretion (m per yr) per Kirwan et al 2010 (0.01) - wvel = Parameter(default = 1.16) # income elasticity of wetland value (1.16) (Brander et al, 2006) - wvpdl = Parameter(default = 0.47) # Population density elasticity of wetland value (0.47) (Brander et al, 2006) + wvbm = Parameter(default=0.376, unit="million US\$2010/km2/yr") # Annual value of wetland services (million 2010$ / km^2 / yr); (Brander et al 2006) (0.376) + wetland = Parameter(index=[segments], unit="km2") # Initial wetland area in coastal segment (km^2) + wmaxrate = Parameter(default=0.01, unit="m/yr") # Maximum rate of wetland accretion (m per yr) per Kirwan et al 2010 (0.01) + wvel = Parameter(default=1.16) # income elasticity of wetland value (1.16) (Brander et al, 2006) + wvpdl = Parameter(default=0.47) # Population density elasticity of wetland value (0.47) (Brander et al, 2006) - wetlandservice = Variable(index = [time, ciam_country]) # Annual value of wetland services adjusted for income and density (Brander et al 2006) ($2010M/km^2/year) - wetlandloss = Variable(index = [time, segments]) # Fractional loss of wetland due to slr + wetlandservice = Variable(index=[time, ciam_country]) # Annual value of wetland services adjusted for income and density (Brander et al 2006) ($2010M/km^2/year) + wetlandloss = Variable(index=[time, segments]) # Fractional loss of wetland due to slr # ---Sea Level Rise Parameters--- - lslr = Parameter(index = [time, segments], unit = "m") # Local sea level rise (m) - adaptoptions = Parameter(index = [6]) # Index of available adaptation levels for protect and retreat (0 is no adaptation) - surgeexposure = Parameter{Float64}(index = [segments, 5])# Storm surge exposure levels (corresponding to each designated adaptation option) + lslr = Parameter(index=[time, segments], unit="m") # Local sea level rise (m) + adaptoptions = Parameter(index=[6]) # Index of available adaptation levels for protect and retreat (0 is no adaptation) + surgeexposure = Parameter{Float64}(index=[segments, 5])# Storm surge exposure levels (corresponding to each designated adaptation option) # ---Coastal Area Parameters--- - area1 = Parameter(index = [segments]) - area2 = Parameter(index = [segments]) - area3 = Parameter(index = [segments]) - area4 = Parameter(index = [segments]) - area5 = Parameter(index = [segments]) - area6 = Parameter(index = [segments]) - area7 = Parameter(index = [segments]) - area8 = Parameter(index = [segments]) - area9 = Parameter(index = [segments]) - area10 = Parameter(index = [segments]) - area11 = Parameter(index = [segments]) - area12 = Parameter(index = [segments]) - area13 = Parameter(index = [segments]) - area14 = Parameter(index = [segments]) - area15 = Parameter(index = [segments]) - areaparams = Variable(index = [segments, 15]) # Nothing is computed; this is just a convenient container for area params - - coastArea = Variable(index = [time, segments], unit = "km2") # Coast area inundated (km^2) + area1 = Parameter(index=[segments]) + area2 = Parameter(index=[segments]) + area3 = Parameter(index=[segments]) + area4 = Parameter(index=[segments]) + area5 = Parameter(index=[segments]) + area6 = Parameter(index=[segments]) + area7 = Parameter(index=[segments]) + area8 = Parameter(index=[segments]) + area9 = Parameter(index=[segments]) + area10 = Parameter(index=[segments]) + area11 = Parameter(index=[segments]) + area12 = Parameter(index=[segments]) + area13 = Parameter(index=[segments]) + area14 = Parameter(index=[segments]) + area15 = Parameter(index=[segments]) + areaparams = Variable(index=[segments, 15]) # Nothing is computed; this is just a convenient container for area params + + coastArea = Variable(index=[time, segments], unit="km2") # Coast area inundated (km^2) # ---Intermediate Variables--- - WetlandNoAdapt = Variable(index = [time, segments]) - FloodNoAdapt = Variable(index = [time, segments]) - StormCapitalNoAdapt = Variable(index = [time, segments]) - StormPopNoAdapt = Variable(index = [time, segments]) - RelocateNoAdapt = Variable(index = [time, segments]) - StormLossNoAdapt = Variable(index = [time, segments]) - DryLandLossNoAdapt = Variable(index = [time, segments]) - - Construct = Variable(index = [time, segments, 5]) - WetlandProtect = Variable(index = [time, segments]) - StormCapitalProtect = Variable(index = [time, segments, 5]) - StormPopProtect = Variable(index = [time, segments, 5]) - StormLossProtect = Variable(index = [time, segments, 5]) - FloodProtect = Variable(index = [time, segments]) - - WetlandRetreat = Variable(index = [time, segments]) - StormCapitalRetreat = Variable(index = [time, segments, 6]) - StormPopRetreat = Variable(index = [time, segments, 6]) - StormLossRetreat = Variable(index = [time, segments, 6]) - FloodRetreat = Variable(index = [time, segments, 6]) - RelocateRetreat = Variable(index = [time, segments, 6]) - DryLandLossRetreat = Variable(index = [time, segments, 6]) - coastAreaRetreat = Variable(index = [time, segments, 6]) - coastAreaNoAdapt = Variable(index = [time, segments]) + WetlandNoAdapt = Variable(index=[time, segments]) + FloodNoAdapt = Variable(index=[time, segments]) + StormCapitalNoAdapt = Variable(index=[time, segments]) + StormPopNoAdapt = Variable(index=[time, segments]) + RelocateNoAdapt = Variable(index=[time, segments]) + StormLossNoAdapt = Variable(index=[time, segments]) + DryLandLossNoAdapt = Variable(index=[time, segments]) + + Construct = Variable(index=[time, segments, 5]) + WetlandProtect = Variable(index=[time, segments]) + StormCapitalProtect = Variable(index=[time, segments, 5]) + StormPopProtect = Variable(index=[time, segments, 5]) + StormLossProtect = Variable(index=[time, segments, 5]) + FloodProtect = Variable(index=[time, segments]) + + WetlandRetreat = Variable(index=[time, segments]) + StormCapitalRetreat = Variable(index=[time, segments, 6]) + StormPopRetreat = Variable(index=[time, segments, 6]) + StormLossRetreat = Variable(index=[time, segments, 6]) + FloodRetreat = Variable(index=[time, segments, 6]) + RelocateRetreat = Variable(index=[time, segments, 6]) + DryLandLossRetreat = Variable(index=[time, segments, 6]) + coastAreaRetreat = Variable(index=[time, segments, 6]) + coastAreaNoAdapt = Variable(index=[time, segments]) # --- Decision Variables --- (evaluated brute force) - H = Variable(index = [time, segments, 5], unit = "m") # Height of current sea wall, no retreat (m) - R = Variable(index = [time, segments, 6], unit = "m") # Retreat perimeter (m) - SIGMA = Variable(index = [time, segments, 12]) # Expected value of effective exposure area for over-topping surge (all cases) + H = Variable(index=[time, segments, 5], unit="m") # Height of current sea wall, no retreat (m) + R = Variable(index=[time, segments, 6], unit="m") # Retreat perimeter (m) + SIGMA = Variable(index=[time, segments, 12]) # Expected value of effective exposure area for over-topping surge (all cases) # Order of sigma values: 1 no adapt case, 6 retreat cases, 5 protect cases in ascending order # ---Outcome Variables--- - OptimalH = Variable(index = [time, segments], unit = "m") # m; Holder to track height built across timesteps (cumulative) - OptimalR = Variable(index = [time, segments], unit = "m") # m; Holder to track retreat radius across timesteps (cumulative) - WetlandLossOptimal = Variable(index = [time, segments], unit = "km2") # km2; Cumulative wetland loss from optimal decision - DryLandLossOptimal = Variable(index = [time, segments], unit = "km2") # km2; Cumulative loss of dry land from optimal decision + OptimalH = Variable(index=[time, segments], unit="m") # m; Holder to track height built across timesteps (cumulative) + OptimalR = Variable(index=[time, segments], unit="m") # m; Holder to track retreat radius across timesteps (cumulative) + WetlandLossOptimal = Variable(index=[time, segments], unit="km2") # km2; Cumulative wetland loss from optimal decision + DryLandLossOptimal = Variable(index=[time, segments], unit="km2") # km2; Cumulative loss of dry land from optimal decision # DrylandLost = Variable(index=[time,segments]) # km2; container to track cumulative lost dryland - WetlandLost = Variable(index = [time, segments], unit = "km2") # km2; container to track cumulative lost wetland - - NoAdaptCost = Variable(index = [time, segments], unit = "billion US\$2010/yr") # Cost of not adapting (e.g. reactive retreat) (2010$) - ProtectCost = Variable(index = [time, segments, 5], unit = "billion US\$2010/yr") # Total cost of protection at each level - RetreatCost = Variable(index = [time, segments, 6], unit = "billion US\$2010/yr") # Total cost of retreat at each level - OptimalRetreatLevel = Variable(index = [time, segments]) - OptimalProtectLevel = Variable(index = [time, segments]) - OptimalCost = Variable(index = [time, segments], unit = "billion US\$2010/yr") # Optimal cost based on NPV relative to start of adaptation period - OptimalLevel = Variable(index = [time, segments]) # Fixed optimal level (1,10,100,1000,10000) - OptimalOption = Variable(index = [time, segments]) # Fixed adaptation decision (-1 - protect, -2 - retreat, -3 - no adapt) - NPVRetreat = Variable(index = [time, segments, 6]) - NPVProtect = Variable(index = [time, segments, 5]) - NPVNoAdapt = Variable(index = [time, segments]) - NPVOptimal = Variable(index = [segments]) # NPV of cost of optimal decisions relative to t=1 + WetlandLost = Variable(index=[time, segments], unit="km2") # km2; container to track cumulative lost wetland + + NoAdaptCost = Variable(index=[time, segments], unit="billion US\$2010/yr") # Cost of not adapting (e.g. reactive retreat) (2010$) + ProtectCost = Variable(index=[time, segments, 5], unit="billion US\$2010/yr") # Total cost of protection at each level + RetreatCost = Variable(index=[time, segments, 6], unit="billion US\$2010/yr") # Total cost of retreat at each level + OptimalRetreatLevel = Variable(index=[time, segments]) + OptimalProtectLevel = Variable(index=[time, segments]) + OptimalCost = Variable(index=[time, segments], unit="billion US\$2010/yr") # Optimal cost based on NPV relative to start of adaptation period + OptimalLevel = Variable(index=[time, segments]) # Fixed optimal level (1,10,100,1000,10000) + OptimalOption = Variable(index=[time, segments]) # Fixed adaptation decision (-1 - protect, -2 - retreat, -3 - no adapt) + NPVRetreat = Variable(index=[time, segments, 6]) + NPVProtect = Variable(index=[time, segments, 5]) + NPVNoAdapt = Variable(index=[time, segments]) + NPVOptimal = Variable(index=[segments]) # NPV of cost of optimal decisions relative to t=1 NPVOptimalTotal = Variable() # Total NPV of all segments from optimal decision - StormLossOptimal = Variable(index = [time, segments], unit = "persons") # Cumulative expected loss of life (num people) from storm surges from optimal decision + StormLossOptimal = Variable(index=[time, segments], unit="persons") # Cumulative expected loss of life (num people) from storm surges from optimal decision # ---Subcategories of Optimal Choice---- - OptimalStormCapital = Variable(index = [time, segments]) - OptimalStormPop = Variable(index = [time, segments]) - OptimalConstruct = Variable(index = [time, segments]) - OptimalWetland = Variable(index = [time, segments]) - OptimalFlood = Variable(index = [time, segments]) - OptimalRelocate = Variable(index = [time, segments]) + OptimalStormCapital = Variable(index=[time, segments]) + OptimalStormPop = Variable(index=[time, segments]) + OptimalConstruct = Variable(index=[time, segments]) + OptimalWetland = Variable(index=[time, segments]) + OptimalFlood = Variable(index=[time, segments]) + OptimalRelocate = Variable(index=[time, segments]) function run_timestep(p, v, d, t) @@ -330,9 +330,9 @@ using Mimi v.vsl[ti, m] = p.vsl_ciam_country[ti, rgn_ind] else # endogenously calculate VSL if isgreenland(m, p.xsc)::Int == 1 # Special treatment for Greenland segments - v.vsl[ti, m] = 1e-6 * p.vslmult * p.ypcc[ti, p.rgn_ind_usa] * (v.ypc_seg[ti, m] / p.ypcc[ti, p.rgn_ind_usa])^p.vslel + v.vsl[ti, m] = 1e-6 * p.vslmult * p.ypcc[ti, p.rgn_ind_usa] * (v.ypc_seg[ti, m] / p.ypcc[ti, p.rgn_ind_usa])^p.vslel else - v.vsl[ti, m] = 1e-6 * p.vslmult * p.ypcc[ti, p.rgn_ind_usa] * (p.ypcc[ti, rgn_ind] / p.ypcc[ti, p.rgn_ind_usa])^p.vslel + v.vsl[ti, m] = 1e-6 * p.vslmult * p.ypcc[ti, p.rgn_ind_usa] * (p.ypcc[ti, rgn_ind] / p.ypcc[ti, p.rgn_ind_usa])^p.vslel end end diff --git a/src/slrcost_GAMSmatch.jl b/src/slrcost_GAMSmatch.jl index b549e6e..726087e 100644 --- a/src/slrcost_GAMSmatch.jl +++ b/src/slrcost_GAMSmatch.jl @@ -11,7 +11,7 @@ using Mimi # end @defcomp slrcost_GAMSmatch begin - # Define all variables, parameters and indices used by this module + # Define all variables, parameters and indices used by this module # --- Indices --- ciam_country = Index() @@ -19,7 +19,7 @@ using Mimi adaptPers = Index() # --- Region / segment mapping --- - segID = Parameter(index = [segments]) # Unique segment numeric identifier + segID = Parameter(index=[segments]) # Unique segment numeric identifier xsc = Parameter{Dict{Int,Tuple{Int,Int,Int}}}() # Region to segment mapping (dictionary) to keep track of which segments belong to each region rcp = Parameter{Int}() # RCP being run (metadata; not used in run) percentile = Parameter{Int}() # Percentile of RCP being run (metadata; not used in run) @@ -27,7 +27,7 @@ using Mimi # ---Time-related Parameters--- tstep = Parameter() # Length of individual time-step (years) - at = Parameter(index = [adaptPers]) # Array of time indices that mark starts of adaptation periods + at = Parameter(index=[adaptPers]) # Array of time indices that mark starts of adaptation periods ntsteps = Parameter{Int}() # Number of time-steps # ---Model Parameters --- @@ -37,51 +37,51 @@ using Mimi # ---Socioeconomic Parameters--- popinput = Parameter{Int}() # Input for population data source: 0 (default), 1 (Jones & O'Neill, 2016), 2 (Merkens et al, 2016) - pop = Parameter(index = [time, ciam_country], unit = "million") # Population of region (million people) (from MERGE or SSPs) - refpopdens = Parameter(index = [ciam_country], unit = "persons/km2") # Reference population density of region (people / km^2) + pop = Parameter(index=[time, ciam_country], unit="million") # Population of region (million people) (from MERGE or SSPs) + refpopdens = Parameter(index=[ciam_country], unit="persons/km2") # Reference population density of region (people / km^2) rgn_ind_usa = Parameter{Int}() # Lookup parameter for USA region index, used in refpopdens and ypc # for USA benchmark in vsl, rho and fundland calculations - popdens = Parameter(index = [segments], unit = "persons/km2") # Pop density of segment in time t = 1 (people/km^2) - ypcc = Parameter(index = [time, ciam_country], unit = "US\$2010/yr/person") # GDP per capita per region ($2010 per capita) + popdens = Parameter(index=[segments], unit="persons/km2") # Pop density of segment in time t = 1 (people/km^2) + ypcc = Parameter(index=[time, ciam_country], unit="US\$2010/yr/person") # GDP per capita per region ($2010 per capita) - popdens_seg = Variable(index = [time, segments], unit = "persons/km2") # Population density of segment extrapolated forward in time (people / km^2) + popdens_seg = Variable(index=[time, segments], unit="persons/km2") # Population density of segment extrapolated forward in time (people / km^2) #popdens_seg_jones = Parameter(index=[time,segments], unit = "persons/km2") # Holder for Jones and O'Neill population density (not currently supported) #popdens_seg_merkens = Parameter(index=[time,segments], unit = "persons/km2") # Holder for Merkens et al population density (not currently supported) - ypc_seg = Variable(index = [time, segments], unit = "US\$2010/yr/person") # GDP per capita by segment ($2010 per capita) (multiplied by scaling factor) - refA_R = Parameter(index = [segments]) # Reference retreat level of adaptation in 0 period - refA_H = Parameter(index = [segments]) # Reference height for adaptation in 0 period + ypc_seg = Variable(index=[time, segments], unit="US\$2010/yr/person") # GDP per capita by segment ($2010 per capita) (multiplied by scaling factor) + refA_R = Parameter(index=[segments]) # Reference retreat level of adaptation in 0 period + refA_H = Parameter(index=[segments]) # Reference height for adaptation in 0 period # ---Land Parameters--- landinput = Parameter{Bool}() # Set to T for FUND or F for GTAP - gtapland = Parameter(index = [ciam_country], unit = "million US\$2010/km2") # GTAP land value in 2007 (million 2010$ / km^2) - dvbm = Parameter(unit = "million US\$2010/km2") # FUND value of OECD dryland per Darwin et al 1995 converted from $1995 ($2010M per sqkm) (5.376) + gtapland = Parameter(index=[ciam_country], unit="million US\$2010/km2") # GTAP land value in 2007 (million 2010$ / km^2) + dvbm = Parameter(unit="million US\$2010/km2") # FUND value of OECD dryland per Darwin et al 1995 converted from $1995 ($2010M per sqkm) (5.376) kgdp = Parameter() # Capital output ratio (per MERGE) (3 by default) discountrate = Parameter() # Discount rate (0.04 by default) depr = Parameter() # Fraction of capital that has not been depreciated over adaptation period (retreat cases) - landdata = Variable(index = [ciam_country], unit = "million US\$2010/km2") # Takes on value of either fundland or gtapland - fundland = Variable(index = [ciam_country], unit = "million US\$2010/km2") # FUND land value in 1995 (calculated in run_timestep) (million 2010$ / km^2), + landdata = Variable(index=[ciam_country], unit="million US\$2010/km2") # Takes on value of either fundland or gtapland + fundland = Variable(index=[ciam_country], unit="million US\$2010/km2") # FUND land value in 1995 (calculated in run_timestep) (million 2010$ / km^2), rgn_ind_canada = Parameter{Int}() # Region index for Canada (Used as reference for Greenland land appreciation) - land_appr = Variable(index = [time, ciam_country]) # Land appreciation rate (calculated as regression by Yohe ref Abraham and Hendershott) - coastland = Variable(index = [time, segments], unit = "million US\$2010/km2") # Coastal land value (function of interior land value * scaling factor) ($2010M per sqkm) - landvalue = Variable(index = [time, segments], unit = "million US\$2010/km2") # Total endowment value of land ($2010M per sqkm) - landrent = Variable(index = [time, segments], unit = "million US\$2010/km2/yr") # Annual rental value of land ($2010M/sqkm/year) + land_appr = Variable(index=[time, ciam_country]) # Land appreciation rate (calculated as regression by Yohe ref Abraham and Hendershott) + coastland = Variable(index=[time, segments], unit="million US\$2010/km2") # Coastal land value (function of interior land value * scaling factor) ($2010M per sqkm) + landvalue = Variable(index=[time, segments], unit="million US\$2010/km2") # Total endowment value of land ($2010M per sqkm) + landrent = Variable(index=[time, segments], unit="million US\$2010/km2/yr") # Annual rental value of land ($2010M/sqkm/year) - ρ = Variable(index = [time, ciam_country]) # Country-wide resilience parameter (logistic function related to GDP) - capital = Variable(index = [time, segments], unit = "million US\$2010/km2") # Total endowment value of capital stock (million $2010 / km^2) - discountfactor = Variable(index = [time]) # Discount factor (derived from discount rate) + ρ = Variable(index=[time, ciam_country]) # Country-wide resilience parameter (logistic function related to GDP) + capital = Variable(index=[time, segments], unit="million US\$2010/km2") # Total endowment value of capital stock (million $2010 / km^2) + discountfactor = Variable(index=[time]) # Discount factor (derived from discount rate) # ---Coastal Parameters--- - length = Parameter(index = [segments], unit = "km") # Segment length (km) + length = Parameter(index=[segments], unit="km") # Segment length (km) # ---Protection Parameters--- - cci = Parameter(index = [ciam_country]) + cci = Parameter(index=[ciam_country]) pcfixed = Parameter() # Fraction of protection cost that is fixed (not variable in height) (0.3) mc = Parameter() # Maintenance cost (Hillen et al, 2010) (2%/yr) - pc0 = Parameter(unit = "million US\$2010/km/m2") # Reference cost of protection (million 2010$ / km / vert m^2) (6.02 by default) + pc0 = Parameter(unit="million US\$2010/km/m2") # Reference cost of protection (million 2010$ / km / vert m^2) (6.02 by default) # ---Retreat / No Adapt Parameters--- mobcapfrac = Parameter() # Fraction of capital that is mobile (0.25) @@ -91,129 +91,129 @@ using Mimi # # ---Surge Exposure Parameters--- # Protection case - psig0 = Parameter(index = [segments]) - psig0coef = Parameter(index = [segments]) - psigA = Parameter(index = [segments]) # psigA in GAMS code - psigB = Parameter(index = [segments]) # psigB in GAMS code + psig0 = Parameter(index=[segments]) + psig0coef = Parameter(index=[segments]) + psigA = Parameter(index=[segments]) # psigA in GAMS code + psigB = Parameter(index=[segments]) # psigB in GAMS code # Retreat / No Adapt Cases - rsig0 = Parameter(index = [segments]) - rsigA = Parameter(index = [segments]) # rsigA in GAMS code - rsigB = Parameter(index = [segments]) # rsigB in GAMS code + rsig0 = Parameter(index=[segments]) + rsigA = Parameter(index=[segments]) # rsigA in GAMS code + rsigB = Parameter(index=[segments]) # rsigB in GAMS code # ---Storm damage parameters--- floodmortality = Parameter() # Flood deaths as percent of exposed population; (Jonkman Vrijling 2008) (0.01) # if TRUE, then VSL is exogenously calculated for each country and set in vsl_ciam_country, then each segment is set by looking up its country # if FALSE, then VSL is endogenously calculated using vslel and vslmult as well as other endogenous socioeconomics for each segment - vsl_exogenous = Parameter{Bool}(default=true) + vsl_exogenous = Parameter{Bool}(default=true) - vsl_ciam_country = Parameter(index = [time, ciam_country], unit = "million US\$2010/yr") # Value of statistical life (million 2010$) (only used for exogenous calculation of vsl) - vslel = Parameter(default = 0.5) # Elasticity of vsl (0.5) (only used for endogenous calculation of vsl) - vslmult = Parameter(default = 216) # multiplier on USA GDP (216)(only used for endogenous calculation of vsl) + vsl_ciam_country = Parameter(index=[time, ciam_country], unit="million US\$2010/yr") # Value of statistical life (million 2010$) (only used for exogenous calculation of vsl) + vslel = Parameter(default=0.5) # Elasticity of vsl (0.5) (only used for endogenous calculation of vsl) + vslmult = Parameter(default=216) # multiplier on USA GDP (216)(only used for endogenous calculation of vsl) - vsl = Variable(index = [time, segments], unit = "million US\$2010/yr") # Value of statistical life (million 2010$) + vsl = Variable(index=[time, segments], unit="million US\$2010/yr") # Value of statistical life (million 2010$) # ---Wetland Loss Parameters--- - wvbm = Parameter(default = 0.376, unit = "million US\$2010/km2/yr") # Annual value of wetland services (million 2010$ / km^2 / yr); (Brander et al 2006) (0.376) - wetland = Parameter(index = [segments], unit = "km2") # Initial wetland area in coastal segment (km^2) - wmaxrate = Parameter(default = 0.01, unit = "m/yr") # Maximum rate of wetland accretion (m per yr) per Kirwan et al 2010 (0.01) - wvel = Parameter(default = 1.16) # income elasticity of wetland value (1.16) (Brander et al, 2006) - wvpdl = Parameter(default = 0.47) # Population density elasticity of wetland value (0.47) (Brander et al, 2006) + wvbm = Parameter(default=0.376, unit="million US\$2010/km2/yr") # Annual value of wetland services (million 2010$ / km^2 / yr); (Brander et al 2006) (0.376) + wetland = Parameter(index=[segments], unit="km2") # Initial wetland area in coastal segment (km^2) + wmaxrate = Parameter(default=0.01, unit="m/yr") # Maximum rate of wetland accretion (m per yr) per Kirwan et al 2010 (0.01) + wvel = Parameter(default=1.16) # income elasticity of wetland value (1.16) (Brander et al, 2006) + wvpdl = Parameter(default=0.47) # Population density elasticity of wetland value (0.47) (Brander et al, 2006) - wetlandservice = Variable(index = [time, ciam_country]) # Annual value of wetland services adjusted for income and density (Brander et al 2006) ($2010M/km^2/year) - wetlandloss = Variable(index = [time, segments]) # Fractional loss of wetland due to slr + wetlandservice = Variable(index=[time, ciam_country]) # Annual value of wetland services adjusted for income and density (Brander et al 2006) ($2010M/km^2/year) + wetlandloss = Variable(index=[time, segments]) # Fractional loss of wetland due to slr # ---Sea Level Rise Parameters--- - lslr = Parameter(index = [time, segments], unit = "m") # Local sea level rise (m) - adaptoptions = Parameter(index = [6]) # Index of available adaptation levels for protect and retreat (0 is no adaptation) - surgeexposure = Parameter{Float64}(index = [segments, 5])# Storm surge exposure levels (corresponding to each designated adaptation option) + lslr = Parameter(index=[time, segments], unit="m") # Local sea level rise (m) + adaptoptions = Parameter(index=[6]) # Index of available adaptation levels for protect and retreat (0 is no adaptation) + surgeexposure = Parameter{Float64}(index=[segments, 5])# Storm surge exposure levels (corresponding to each designated adaptation option) # ---Coastal Area Parameters--- - area1 = Parameter(index = [segments]) - area2 = Parameter(index = [segments]) - area3 = Parameter(index = [segments]) - area4 = Parameter(index = [segments]) - area5 = Parameter(index = [segments]) - area6 = Parameter(index = [segments]) - area7 = Parameter(index = [segments]) - area8 = Parameter(index = [segments]) - area9 = Parameter(index = [segments]) - area10 = Parameter(index = [segments]) - area11 = Parameter(index = [segments]) - area12 = Parameter(index = [segments]) - area13 = Parameter(index = [segments]) - area14 = Parameter(index = [segments]) - area15 = Parameter(index = [segments]) - areaparams = Variable(index = [segments, 15]) # Nothing is computed; this is just a convenient container for area params - - coastArea = Variable(index = [time, segments], unit = "km2") # Coast area inundated (km^2) + area1 = Parameter(index=[segments]) + area2 = Parameter(index=[segments]) + area3 = Parameter(index=[segments]) + area4 = Parameter(index=[segments]) + area5 = Parameter(index=[segments]) + area6 = Parameter(index=[segments]) + area7 = Parameter(index=[segments]) + area8 = Parameter(index=[segments]) + area9 = Parameter(index=[segments]) + area10 = Parameter(index=[segments]) + area11 = Parameter(index=[segments]) + area12 = Parameter(index=[segments]) + area13 = Parameter(index=[segments]) + area14 = Parameter(index=[segments]) + area15 = Parameter(index=[segments]) + areaparams = Variable(index=[segments, 15]) # Nothing is computed; this is just a convenient container for area params + + coastArea = Variable(index=[time, segments], unit="km2") # Coast area inundated (km^2) # ---Intermediate Variables--- - WetlandNoAdapt = Variable(index = [time, segments]) - FloodNoAdapt = Variable(index = [time, segments]) - StormCapitalNoAdapt = Variable(index = [time, segments]) - StormPopNoAdapt = Variable(index = [time, segments]) - RelocateNoAdapt = Variable(index = [time, segments]) - StormLossNoAdapt = Variable(index = [time, segments]) - DryLandLossNoAdapt = Variable(index = [time, segments]) - - Construct = Variable(index = [time, segments, 5]) - WetlandProtect = Variable(index = [time, segments]) - StormCapitalProtect = Variable(index = [time, segments, 5]) - StormPopProtect = Variable(index = [time, segments, 5]) - StormLossProtect = Variable(index = [time, segments, 5]) - FloodProtect = Variable(index = [time, segments]) - - WetlandRetreat = Variable(index = [time, segments]) - StormCapitalRetreat = Variable(index = [time, segments, 6]) - StormPopRetreat = Variable(index = [time, segments, 6]) - StormLossRetreat = Variable(index = [time, segments, 6]) - FloodRetreat = Variable(index = [time, segments, 6]) - RelocateRetreat = Variable(index = [time, segments, 6]) - DryLandLossRetreat = Variable(index = [time, segments, 6]) - coastAreaRetreat = Variable(index = [time, segments, 6]) - coastAreaNoAdapt = Variable(index = [time, segments]) + WetlandNoAdapt = Variable(index=[time, segments]) + FloodNoAdapt = Variable(index=[time, segments]) + StormCapitalNoAdapt = Variable(index=[time, segments]) + StormPopNoAdapt = Variable(index=[time, segments]) + RelocateNoAdapt = Variable(index=[time, segments]) + StormLossNoAdapt = Variable(index=[time, segments]) + DryLandLossNoAdapt = Variable(index=[time, segments]) + + Construct = Variable(index=[time, segments, 5]) + WetlandProtect = Variable(index=[time, segments]) + StormCapitalProtect = Variable(index=[time, segments, 5]) + StormPopProtect = Variable(index=[time, segments, 5]) + StormLossProtect = Variable(index=[time, segments, 5]) + FloodProtect = Variable(index=[time, segments]) + + WetlandRetreat = Variable(index=[time, segments]) + StormCapitalRetreat = Variable(index=[time, segments, 6]) + StormPopRetreat = Variable(index=[time, segments, 6]) + StormLossRetreat = Variable(index=[time, segments, 6]) + FloodRetreat = Variable(index=[time, segments, 6]) + RelocateRetreat = Variable(index=[time, segments, 6]) + DryLandLossRetreat = Variable(index=[time, segments, 6]) + coastAreaRetreat = Variable(index=[time, segments, 6]) + coastAreaNoAdapt = Variable(index=[time, segments]) # --- Decision Variables --- (evaluated brute force) - H = Variable(index = [time, segments, 5], unit = "m") # Height of current sea wall, no retreat (m) - R = Variable(index = [time, segments, 6], unit = "m") # Retreat perimeter (m) - SIGMA = Variable(index = [time, segments, 12]) # Expected value of effective exposure area for over-topping surge (all cases) + H = Variable(index=[time, segments, 5], unit="m") # Height of current sea wall, no retreat (m) + R = Variable(index=[time, segments, 6], unit="m") # Retreat perimeter (m) + SIGMA = Variable(index=[time, segments, 12]) # Expected value of effective exposure area for over-topping surge (all cases) # Order of sigma values: 1 no adapt case, 6 retreat cases, 5 protect cases in ascending order # ---Outcome Variables--- - OptimalH = Variable(index = [time, segments], unit = "m") # m; Holder to track height built across timesteps (cumulative) - OptimalR = Variable(index = [time, segments], unit = "m") # m; Holder to track retreat radius across timesteps (cumulative) - WetlandLossOptimal = Variable(index = [time, segments], unit = "km2") # km2; Cumulative wetland loss from optimal decision - DryLandLossOptimal = Variable(index = [time, segments], unit = "km2") # km2; Cumulative loss of dry land from optimal decision + OptimalH = Variable(index=[time, segments], unit="m") # m; Holder to track height built across timesteps (cumulative) + OptimalR = Variable(index=[time, segments], unit="m") # m; Holder to track retreat radius across timesteps (cumulative) + WetlandLossOptimal = Variable(index=[time, segments], unit="km2") # km2; Cumulative wetland loss from optimal decision + DryLandLossOptimal = Variable(index=[time, segments], unit="km2") # km2; Cumulative loss of dry land from optimal decision # DrylandLost = Variable(index=[time,segments]) # km2; container to track cumulative lost dryland - WetlandLost = Variable(index = [time, segments], unit = "km2") # km2; container to track cumulative lost wetland - - NoAdaptCost = Variable(index = [time, segments], unit = "billion US\$2010/yr") # Cost of not adapting (e.g. reactive retreat) (2010$) - ProtectCost = Variable(index = [time, segments, 5], unit = "billion US\$2010/yr") # Total cost of protection at each level - RetreatCost = Variable(index = [time, segments, 6], unit = "billion US\$2010/yr") # Total cost of retreat at each level - OptimalRetreatLevel = Variable(index = [time, segments]) - OptimalProtectLevel = Variable(index = [time, segments]) - OptimalCost = Variable(index = [time, segments], unit = "billion US\$2010/yr") # Optimal cost based on NPV relative to start of adaptation period - OptimalLevel = Variable(index = [time, segments]) # Fixed optimal level (1,10,100,1000,10000) - OptimalOption = Variable(index = [time, segments]) # Fixed adaptation decision (-1 - protect, -2 - retreat, -3 - no adapt) - NPVRetreat = Variable(index = [time, segments, 6]) - NPVProtect = Variable(index = [time, segments, 5]) - NPVNoAdapt = Variable(index = [time, segments]) - NPVOptimal = Variable(index = [segments]) # NPV of cost of optimal decisions relative to t=1 + WetlandLost = Variable(index=[time, segments], unit="km2") # km2; container to track cumulative lost wetland + + NoAdaptCost = Variable(index=[time, segments], unit="billion US\$2010/yr") # Cost of not adapting (e.g. reactive retreat) (2010$) + ProtectCost = Variable(index=[time, segments, 5], unit="billion US\$2010/yr") # Total cost of protection at each level + RetreatCost = Variable(index=[time, segments, 6], unit="billion US\$2010/yr") # Total cost of retreat at each level + OptimalRetreatLevel = Variable(index=[time, segments]) + OptimalProtectLevel = Variable(index=[time, segments]) + OptimalCost = Variable(index=[time, segments], unit="billion US\$2010/yr") # Optimal cost based on NPV relative to start of adaptation period + OptimalLevel = Variable(index=[time, segments]) # Fixed optimal level (1,10,100,1000,10000) + OptimalOption = Variable(index=[time, segments]) # Fixed adaptation decision (-1 - protect, -2 - retreat, -3 - no adapt) + NPVRetreat = Variable(index=[time, segments, 6]) + NPVProtect = Variable(index=[time, segments, 5]) + NPVNoAdapt = Variable(index=[time, segments]) + NPVOptimal = Variable(index=[segments]) # NPV of cost of optimal decisions relative to t=1 NPVOptimalTotal = Variable() # Total NPV of all segments from optimal decision - StormLossOptimal = Variable(index = [time, segments], unit = "persons") # Cumulative expected loss of life (num people) from storm surges from optimal decision + StormLossOptimal = Variable(index=[time, segments], unit="persons") # Cumulative expected loss of life (num people) from storm surges from optimal decision # ---Subcategories of Optimal Choice---- - OptimalStormCapital = Variable(index = [time, segments]) - OptimalStormPop = Variable(index = [time, segments]) - OptimalConstruct = Variable(index = [time, segments]) - OptimalWetland = Variable(index = [time, segments]) - OptimalFlood = Variable(index = [time, segments]) - OptimalRelocate = Variable(index = [time, segments]) + OptimalStormCapital = Variable(index=[time, segments]) + OptimalStormPop = Variable(index=[time, segments]) + OptimalConstruct = Variable(index=[time, segments]) + OptimalWetland = Variable(index=[time, segments]) + OptimalFlood = Variable(index=[time, segments]) + OptimalRelocate = Variable(index=[time, segments]) function run_timestep(p, v, d, t) @@ -326,9 +326,9 @@ using Mimi v.vsl[ti, m] = p.vsl_ciam_country[ti, rgn_ind] else # endogenously calculate VSL if isgreenland(m, p.xsc)::Int == 1 # Special treatment for Greenland segments - v.vsl[ti, m] = 1e-6 * p.vslmult * p.ypcc[ti, p.rgn_ind_usa] * (v.ypc_seg[ti, m] / p.ypcc[ti, p.rgn_ind_usa])^p.vslel + v.vsl[ti, m] = 1e-6 * p.vslmult * p.ypcc[ti, p.rgn_ind_usa] * (v.ypc_seg[ti, m] / p.ypcc[ti, p.rgn_ind_usa])^p.vslel else - v.vsl[ti, m] = 1e-6 * p.vslmult * p.ypcc[ti, p.rgn_ind_usa] * (p.ypcc[ti, rgn_ind] / p.ypcc[ti, p.rgn_ind_usa])^p.vslel + v.vsl[ti, m] = 1e-6 * p.vslmult * p.ypcc[ti, p.rgn_ind_usa] * (p.ypcc[ti, rgn_ind] / p.ypcc[ti, p.rgn_ind_usa])^p.vslel end end diff --git a/test/runtests.jl b/test/runtests.jl index 0d5ac62..6149d5e 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -21,7 +21,7 @@ jl_outputdir = joinpath(@__DIR__, "..", "output", "BaselineComparisonTests") # write out the current results using the same random subset of segments used # for the validation data -write_MimiCIAM_comparison_files(jl_outputdir, subset = "random10.csv") +write_MimiCIAM_comparison_files(jl_outputdir, subset="random10.csv") ##============================================================================== ## Baseline Comparison Tests: MimiCIAM dev to MimICIAM stable @@ -32,7 +32,7 @@ write_MimiCIAM_comparison_files(jl_outputdir, subset = "random10.csv") jl_validation_outputdir = joinpath(@__DIR__, "..", "data", "validation_data", "julia") files = readdir(jl_validation_outputdir) - filter!(i->(i!="desktop.ini" && i!=".DS_Store" && i!="xsc.csv"), files) + filter!(i -> (i != "desktop.ini" && i != ".DS_Store" && i != "xsc.csv"), files) for (i, file) in enumerate(files) diff --git a/test/test_utils.jl b/test/test_utils.jl index 59975cf..e47e4c3 100644 --- a/test/test_utils.jl +++ b/test/test_utils.jl @@ -3,7 +3,7 @@ using CSV ##============================================================================== ## Write Comparison Files -function write_MimiCIAM_comparison_files(outputdir; subset = false) +function write_MimiCIAM_comparison_files(outputdir; subset=false) isdir(outputdir) || mkpath(outputdir) @@ -15,33 +15,33 @@ function write_MimiCIAM_comparison_files(outputdir; subset = false) run_name = "ctrl+noConstrFix" init_settings = Dict( - :init_filename => string("$run_name", "_init.csv"), - :lslrfile => "lsl_rcp85_p50.csv", - :subset => subset, - :ssp => 0, - :ssp_simplified => 2 # won't matter, just to get defaults for the popdens_seg_jones and _merkens arrays. + :init_filename => string("$run_name", "_init.csv"), + :lslrfile => "lsl_rcp85_p50.csv", + :subset => subset, + :ssp => 0, + :ssp_simplified => 2 # won't matter, just to get defaults for the popdens_seg_jones and _merkens arrays. ) model_settings = Dict( - :fixed => true, - :t => 20, - :noRetreat => false, - :allowMaintain => false, - :popinput => 0, - :GAMSmatch => true + :fixed => true, + :t => 20, + :noRetreat => false, + :allowMaintain => false, + :popinput => 0, + :GAMSmatch => true ) # write files MimiCIAM.write_init_file(run_name, outputdir, init_settings) m = MimiCIAM.get_model( - initfile = joinpath(outputdir, init_settings[:init_filename]), - fixed = model_settings[:fixed], - t = model_settings[:t], - noRetreat = model_settings[:noRetreat], - allowMaintain = model_settings[:allowMaintain], - popinput = model_settings[:popinput], - GAMSmatch = model_settings[:GAMSmatch] + initfile=joinpath(outputdir, init_settings[:init_filename]), + fixed=model_settings[:fixed], + t=model_settings[:t], + noRetreat=model_settings[:noRetreat], + allowMaintain=model_settings[:allowMaintain], + popinput=model_settings[:popinput], + GAMSmatch=model_settings[:GAMSmatch] ) run(m) @@ -53,32 +53,32 @@ function write_MimiCIAM_comparison_files(outputdir; subset = false) run_name = "ctrl" init_settings = Dict( - :init_filename => string("$run_name", "_init.csv"), - :lslrfile => "lsl_rcp85_p50.csv", - :subset => subset, - :ssp => 0, - :ssp_simplified => 2 # won't matter, just to get defaults for the popdens_seg_jones and _merkens arrays. + :init_filename => string("$run_name", "_init.csv"), + :lslrfile => "lsl_rcp85_p50.csv", + :subset => subset, + :ssp => 0, + :ssp_simplified => 2 # won't matter, just to get defaults for the popdens_seg_jones and _merkens arrays. ) model_settings = Dict( - :fixed => true, - :t => 15, - :noRetreat => false, - :allowMaintain => false, - :popinput => 0, - :GAMSmatch => false + :fixed => true, + :t => 15, + :noRetreat => false, + :allowMaintain => false, + :popinput => 0, + :GAMSmatch => false ) MimiCIAM.write_init_file(run_name, outputdir, init_settings) m = MimiCIAM.get_model( - initfile = joinpath(outputdir, init_settings[:init_filename]), - fixed = model_settings[:fixed], - t = model_settings[:t], - noRetreat = model_settings[:noRetreat], - allowMaintain = model_settings[:allowMaintain], - popinput = model_settings[:popinput], - GAMSmatch = model_settings[:GAMSmatch] + initfile=joinpath(outputdir, init_settings[:init_filename]), + fixed=model_settings[:fixed], + t=model_settings[:t], + noRetreat=model_settings[:noRetreat], + allowMaintain=model_settings[:allowMaintain], + popinput=model_settings[:popinput], + GAMSmatch=model_settings[:GAMSmatch] ) run(m) @@ -90,32 +90,32 @@ function write_MimiCIAM_comparison_files(outputdir; subset = false) run_name = "ctrl+SSP5" init_settings = Dict( - :init_filename => string("$run_name", "_init.csv"), - :lslrfile => "lsl_rcp85_p50.csv", - :subset => subset, - :ssp => "IIASAGDP_SSP5_v9_130219", - :ssp_simplified => 5 + :init_filename => string("$run_name", "_init.csv"), + :lslrfile => "lsl_rcp85_p50.csv", + :subset => subset, + :ssp => "IIASAGDP_SSP5_v9_130219", + :ssp_simplified => 5 ) model_settings = Dict( - :fixed => true, - :t => 15, - :noRetreat => false, - :allowMaintain => false, - :popinput => 0, - :GAMSmatch => false + :fixed => true, + :t => 15, + :noRetreat => false, + :allowMaintain => false, + :popinput => 0, + :GAMSmatch => false ) MimiCIAM.write_init_file(run_name, outputdir, init_settings) m = MimiCIAM.get_model( - initfile = joinpath(outputdir, init_settings[:init_filename]), - fixed = model_settings[:fixed], - t = model_settings[:t], - noRetreat = model_settings[:noRetreat], - allowMaintain = model_settings[:allowMaintain], - popinput = model_settings[:popinput], - GAMSmatch = model_settings[:GAMSmatch] + initfile=joinpath(outputdir, init_settings[:init_filename]), + fixed=model_settings[:fixed], + t=model_settings[:t], + noRetreat=model_settings[:noRetreat], + allowMaintain=model_settings[:allowMaintain], + popinput=model_settings[:popinput], + GAMSmatch=model_settings[:GAMSmatch] ) run(m)