From ef520b87077b06e615fdeda17da36cc2917d035b Mon Sep 17 00:00:00 2001 From: Rose Crocker Date: Wed, 24 Jan 2024 10:24:19 +1000 Subject: [PATCH] Formatting --- ext/AvizExt/viz/location_selection.jl | 46 +++--- ext/AvizExt/viz/spatial.jl | 102 ++++++------ src/ADRIA.jl | 2 +- src/analysis/analysis.jl | 4 +- src/decision/CriteriaWeights.jl | 218 +++++++++++++------------- src/decision/dMCDA.jl | 40 ++--- src/ecosystem/connectivity.jl | 42 ++--- src/io/result_io.jl | 156 +++++++++--------- 8 files changed, 305 insertions(+), 305 deletions(-) diff --git a/ext/AvizExt/viz/location_selection.jl b/ext/AvizExt/viz/location_selection.jl index 5b38d0510a..b3207e573e 100644 --- a/ext/AvizExt/viz/location_selection.jl +++ b/ext/AvizExt/viz/location_selection.jl @@ -35,8 +35,8 @@ function ADRIA.viz.ranks_to_frequencies!( rs::ResultSet, frequencies::NamedDimsArray, rank_ids::Vector{Int64}; - opts::Dict = Dict(), - axis_opts::Dict = Dict(), + opts::Dict=Dict(), + axis_opts::Dict=Dict(), ) sym_rank_ids = Symbol.(rank_ids) rank_groups = Dict(rank_grp => rank_grp .== sym_rank_ids for rank_grp in sym_rank_ids) @@ -58,12 +58,12 @@ function ADRIA.viz.ranks_to_frequencies!( ADRIA.viz.map!( g, rs, - frequencies[ranks = rank_ids[1]]; - opts = opts, - axis_opts = axis_opts + frequencies[ranks=rank_ids[1]]; + opts=opts, + axis_opts=axis_opts, ) legend_els[1] = PolyElement(; - color = all_colormaps[Symbol(rank_ids[1])][2], strokecolor = :grey, strokewidth = 1 + color=all_colormaps[Symbol(rank_ids[1])][2], strokecolor=:grey, strokewidth=1 ) legend_labels[1] = string("Rank ", string(rank_ids[1])) ax = content(g[1, 1]) # get GeoAxis @@ -72,19 +72,19 @@ function ADRIA.viz.ranks_to_frequencies!( poly!( ax, geodata; - color = collect(frequencies[ranks = rr]), - colormap = all_colormaps[Symbol(rr)], - strokecolor = :grey, - strokewidth = 0.5, - linestyle = :solid, - overdraw = true, + color=collect(frequencies[ranks=rr]), + colormap=all_colormaps[Symbol(rr)], + strokecolor=:grey, + strokewidth=0.5, + linestyle=:solid, + overdraw=true, ) legend_els[rr] = PolyElement(; - color = all_colormaps[Symbol(rr)][2], strokecolor = :grey, strokewidth = 1 + color=all_colormaps[Symbol(rr)][2], strokecolor=:grey, strokewidth=1 ) legend_labels[rr] = string("Rank ", string(rr)) end - Legend(g[1, 2], legend_els, legend_labels; patchsize = (35, 35), rowgap = 10) + Legend(g[1, 2], legend_els, legend_labels; patchsize=(35, 35), rowgap=10) return g end function ADRIA.viz.ranks_to_frequencies!( @@ -92,8 +92,8 @@ function ADRIA.viz.ranks_to_frequencies!( rs::ResultSet, frequencies::NamedDimsArray, rank_id::Int64; - opts::Dict = Dict(), - axis_opts::Dict = Dict()) + opts::Dict=Dict(), + axis_opts::Dict=Dict()) opts[:colorbar_label] = get(opts, :colorbar_label, "Selection frequency") opts[:color_map] = get( opts, @@ -104,17 +104,17 @@ function ADRIA.viz.ranks_to_frequencies!( return ADRIA.viz.map!( g, rs, - AxisKeys.keyless(NamedDims.unname(frequencies[ranks = rank_id])); - opts = opts, - axis_opts = axis_opts, + AxisKeys.keyless(NamedDims.unname(frequencies[ranks=rank_id])); + opts=opts, + axis_opts=axis_opts, ) end function ADRIA.viz.ranks_to_frequencies( rs::ResultSet, frequencies::NamedDimsArray, rank_ids::Union{Int64, Vector{Int64}}; - opts::Dict = Dict(), - fig_opts::Dict = Dict(), axis_opts::Dict = Dict()) + opts::Dict=Dict(), + fig_opts::Dict=Dict(), axis_opts::Dict=Dict()) f = Figure(; fig_opts...) g = f[1, 1] = GridLayout() ADRIA.viz.ranks_to_frequencies!( @@ -122,8 +122,8 @@ function ADRIA.viz.ranks_to_frequencies( rs, frequencies, rank_ids; - opts = opts, - axis_opts = axis_opts + opts=opts, + axis_opts=axis_opts, ) return f diff --git a/ext/AvizExt/viz/spatial.jl b/ext/AvizExt/viz/spatial.jl index d8cf391e26..0440bfd536 100644 --- a/ext/AvizExt/viz/spatial.jl +++ b/ext/AvizExt/viz/spatial.jl @@ -34,12 +34,12 @@ function create_map!( data::Observable, highlight::Union{Vector, Tuple, Nothing}, centroids::Vector, - show_colorbar::Bool = true, - colorbar_label::String = "", - colorbar_limits::Tuple{Float64, Float64} = (0.0, maximum(data)), - color_map::Union{Symbol, Vector{Symbol}, RGBA{Float32}, Vector{RGBA{Float32}}} = :grayC, - legend_params::Union{Tuple, Nothing} = nothing, - axis_opts::Dict = Dict(), + show_colorbar::Bool=true, + colorbar_label::String="", + colorbar_limits::Tuple{Float64, Float64}=(0.0, maximum(data)), + color_map::Union{Symbol, Vector{Symbol}, RGBA{Float32}, Vector{RGBA{Float32}}}=:grayC, + legend_params::Union{Tuple, Nothing}=nothing, + axis_opts::Dict=Dict(), ) axis_opts[:title] = get(axis_opts, :title, "Study Area") axis_opts[:xlabel] = get(axis_opts, :xlabel, "Longitude") @@ -47,7 +47,7 @@ function create_map!( spatial = GeoAxis( f[1, 1]; - dest = "+proj=latlong +datum=WGS84", + dest="+proj=latlong +datum=WGS84", axis_opts..., ) # lon = first.(centroids) @@ -65,19 +65,19 @@ function create_map!( poly!( spatial, geodata; - color = data, - colormap = color_map, - strokecolor = (:black, 0.05), - strokewidth = 1.0, + color=data, + colormap=color_map, + strokecolor=(:black, 0.05), + strokewidth=1.0, ) if show_colorbar Colorbar( f[1, 2]; - colormap = color_map, - label = colorbar_label, - height = Relative(0.65), - limits = colorbar_limits, + colormap=color_map, + label=colorbar_label, + height=Relative(0.65), + limits=colorbar_limits, ) end @@ -89,34 +89,34 @@ function create_map!( poly!( spatial, geodata; - color = "transparent", - strokecolor = highlight, - strokewidth = 0.5, - linestyle = :solid, - overdraw = true, + color="transparent", + strokecolor=highlight, + strokewidth=0.5, + linestyle=:solid, + overdraw=true, ) else hl_groups = unique(highlight) for color in hl_groups m = findall(highlight .== [color]) - subset_feat = FC(; features = geodata[m]) + subset_feat = FC(; features=geodata[m]) poly!( spatial, subset_feat; - color = "transparent", - strokecolor = color, - strokewidth = 0.5, - linestyle = :solid, - overdraw = true, + color="transparent", + strokecolor=color, + strokewidth=0.5, + linestyle=:solid, + overdraw=true, ) end end if !isnothing(legend_params) # Plot Legend only if highlight colors are present - Legend(f[1, 3], legend_params...; framevisible = false) + Legend(f[1, 3], legend_params...; framevisible=false) end end @@ -162,9 +162,9 @@ GridPosition function ADRIA.viz.map( rs::Union{Domain, ResultSet}, y::NamedDimsArray; - opts::Dict = Dict(), - fig_opts::Dict = Dict(), - axis_opts::Dict = Dict(), + opts::Dict=Dict(), + fig_opts::Dict=Dict(), + axis_opts::Dict=Dict(), ) f = Figure(; fig_opts...) g = f[1, 1] = GridLayout() @@ -175,9 +175,9 @@ function ADRIA.viz.map( end function ADRIA.viz.map( rs::Union{Domain, ResultSet}; - opts::Dict{Symbol, <:Any} = Dict{Symbol, Any}(), - fig_opts::Dict{Symbol, <:Any} = Dict{Symbol, Any}(), - axis_opts::Dict{Symbol, <:Any} = Dict{Symbol, Any}(), + opts::Dict{Symbol, <:Any}=Dict{Symbol, Any}(), + fig_opts::Dict{Symbol, <:Any}=Dict{Symbol, Any}(), + axis_opts::Dict{Symbol, <:Any}=Dict{Symbol, Any}(), ) f = Figure(; fig_opts...) g = f[1, 1] = GridLayout() @@ -198,8 +198,8 @@ function ADRIA.viz.map!( g::Union{GridLayout, GridPosition}, rs::Union{Domain, ResultSet}, y::AbstractVector{<:Real}; - opts::Dict = Dict(), - axis_opts::Dict = Dict(), + opts::Dict=Dict(), + axis_opts::Dict=Dict(), ) geodata = get_geojson_copy(rs) data = Observable(collect(y)) @@ -228,15 +228,15 @@ function ADRIA.viz.map( rs::ResultSet, S::NamedDimsArray, scores::Vector{Float64}; - criteria::Vector{Symbol} = S.criteria, - opts::Dict = Dict(), - axis_opts::Dict = Dict(), - fig_opts::Dict = Dict(), + criteria::Vector{Symbol}=S.criteria, + opts::Dict=Dict(), + axis_opts::Dict=Dict(), + fig_opts::Dict=Dict(), ) f = Figure(; fig_opts...) g = f[1, 1] = GridLayout() ADRIA.viz.map!( - g, rs, S, scores; criteria = criteria, opts = opts, axis_opts = axis_opts + g, rs, S, scores; criteria=criteria, opts=opts, axis_opts=axis_opts ) return f end @@ -245,9 +245,9 @@ function ADRIA.viz.map!( rs::ResultSet, S::NamedDimsArray, scores::Vector{Float64}; - criteria::Vector{Symbol} = S.criteria, - opts::Dict = Dict(), - axis_opts::Dict = Dict(), + criteria::Vector{Symbol}=S.criteria, + opts::Dict=Dict(), + axis_opts::Dict=Dict(), ) if length(rs.site_data.site_id) != size(S, 1) error("Only unfiltered decision matrices can be plotted.") @@ -260,9 +260,9 @@ function ADRIA.viz.map!( criteria_names::Vector{String} = m_spec[ dropdims( any( - reshape(criteria, 1, length(criteria)) .== m_spec[:, "fieldname"]; dims = 2 + reshape(criteria, 1, length(criteria)) .== m_spec[:, "fieldname"]; dims=2 ); - dims = 2, + dims=2, ), "name"] n_criteria::Int64 = length(criteria) n_rows, n_cols = _calc_gridsize(n_criteria + 1) @@ -274,8 +274,8 @@ function ADRIA.viz.map!( g[row, col], rs, vec(scores); - opts = opts, - axis_opts = Dict(:title => "Aggregate criteria score"; axis_opts...), + opts=opts, + axis_opts=Dict(:title => "Aggregate criteria score"; axis_opts...), ) break end @@ -284,8 +284,8 @@ function ADRIA.viz.map!( g[row, col], rs, vec(S(criteria[step])); - opts = opts, - axis_opts = axis_opts_temp + opts=opts, + axis_opts=axis_opts_temp, ) step += 1 @@ -311,9 +311,9 @@ function make_geojson_copy(ds::Union{ResultSet, Domain})::String local geo_fn = joinpath(tmpdir, "Aviz_$(ds.name).geojson") if !isfile(geo_fn) try - GDF.write(geo_fn, ds.site_data; driver = "geojson") + GDF.write(geo_fn, ds.site_data; driver="geojson") catch - GDF.write(geo_fn, ds.site_data; geom_columns = (:geom,), driver = "geojson") + GDF.write(geo_fn, ds.site_data; geom_columns=(:geom,), driver="geojson") end end diff --git a/src/ADRIA.jl b/src/ADRIA.jl index c21cb66582..6027708a4f 100644 --- a/src/ADRIA.jl +++ b/src/ADRIA.jl @@ -259,7 +259,7 @@ if ccall(:jl_generating_output, Cint, ()) == 1 Matrix{Float64}, Matrix{Float64}, Float64, - }, + } ) # time: 0.1929096 Base.precompile( Tuple{ diff --git a/src/analysis/analysis.jl b/src/analysis/analysis.jl index 4de677e3fd..7ddedcee32 100644 --- a/src/analysis/analysis.jl +++ b/src/analysis/analysis.jl @@ -75,7 +75,7 @@ S := 1.0 - 0.9 S-1 := 0.9 - 0.8 etc """ -function discretize_outcomes(y; S = 20) +function discretize_outcomes(y; S=20) steps = 0.0:(1 / S):1.0 y_s_hat = col_normalize(y) @@ -101,7 +101,7 @@ Computes confidence interval for series of data. # Returns Confidence interval (lower bound, median and higher bound) for each series step """ -function series_confint(data::AbstractMatrix; agg_dim::Symbol = :scenarios)::Matrix{Float64} +function series_confint(data::AbstractMatrix; agg_dim::Symbol=:scenarios)::Matrix{Float64} slice_dim = data isa NamedDimsArray ? NamedDims.dim(data, agg_dim) : 2 return quantile.(Slices(data, slice_dim), [0.025 0.5 0.975]) end diff --git a/src/decision/CriteriaWeights.jl b/src/decision/CriteriaWeights.jl index cec0351c64..9804dff699 100644 --- a/src/decision/CriteriaWeights.jl +++ b/src/decision/CriteriaWeights.jl @@ -1,165 +1,165 @@ Base.@kwdef struct CriteriaWeights{U2, U3, DO} <: EcoModel seed_in_connectivity::U2 = Factor( 1.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:seed, :weight), - name = "Incoming Connectivity (Seed)", - description = "Higher values give preference to locations with high incoming connectivity (i.e., receives larvae from other sites) for enhanced coral deployments.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:seed, :weight), + name="Incoming Connectivity (Seed)", + description="Higher values give preference to locations with high incoming connectivity (i.e., receives larvae from other sites) for enhanced coral deployments.", ) seed_out_connectivity::U2 = Factor( 1.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:seed, :weight), - name = "Outgoing Connectivity (Seed)", - description = "Higher values give preference to locations with high outgoing connectivity (i.e., provides larvae to other sites) for enhanced coral deployments.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:seed, :weight), + name="Outgoing Connectivity (Seed)", + description="Higher values give preference to locations with high outgoing connectivity (i.e., provides larvae to other sites) for enhanced coral deployments.", ) seed_wave_stress::U2 = Factor( 1.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:seed, :weight), - name = "Seed Wave Stress", - description = "Importance of avoiding wave stress when seeding. Higher values places more weight on areas with low wave stress.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:seed, :weight), + name="Seed Wave Stress", + description="Importance of avoiding wave stress when seeding. Higher values places more weight on areas with low wave stress.", ) seed_heat_stress::U2 = Factor( 1.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:seed, :weight), - name = "Seed Heat Stress", - description = "Importance of avoiding heat stress when seeding. Higher values places more weight on areas with low heat stress.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:seed, :weight), + name="Seed Heat Stress", + description="Importance of avoiding heat stress when seeding. Higher values places more weight on areas with low heat stress.", ) seed_priority::U2 = Factor( 1.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:seed, :weight), - name = "Predecessor Priority (Seed)", - description = "Importance of seeding sites that provide larvae to priority reefs.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:seed, :weight), + name="Predecessor Priority (Seed)", + description="Importance of seeding sites that provide larvae to priority reefs.", ) seed_zone::U2 = Factor( 0.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:seed, :weight), - name = "Zone Predecessor (Seed)", - description = "Importance of seeding sites that provide larvae to priority (target) zones.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:seed, :weight), + name="Zone Predecessor (Seed)", + description="Importance of seeding sites that provide larvae to priority (target) zones.", ) seed_coral_cover_low::U2 = Factor( 0.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:seed, :weight), - name = "Low Coral Cover", - description = "Higher values give greater preference to sites with low coral cover for seeding deployments.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:seed, :weight), + name="Low Coral Cover", + description="Higher values give greater preference to sites with low coral cover for seeding deployments." ) seed_depth::U2 = Factor( 1.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:seed, :weight), - name = "Depth (Seed)", - description = "Higher values give preference to deeper locations for enhanced coral deployments.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:seed, :weight), + name="Depth (Seed)", + description="Higher values give preference to deeper locations for enhanced coral deployments.", ) fog_in_connectivity::U2 = Factor( 0.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:fog, :weight), - name = "Outgoing Connectivity (Fog)", - description = "Higher values give preference to locations with high incoming connectivity for foggining deployments.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:fog, :weight), + name="Outgoing Connectivity (Fog)", + description="Higher values give preference to locations with high incoming connectivity for foggining deployments.", ) fog_out_connectivity::U2 = Factor( 0.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:fog, :weight), - name = "Incoming Connectivity (Fog)", - description = "Higher values give preference to locations with high outgoing connectivity for fogging deployments.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:fog, :weight), + name="Incoming Connectivity (Fog)", + description="Higher values give preference to locations with high outgoing connectivity for fogging deployments." ) fog_wave_stress::U2 = Factor( 1.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:fog, :weight), - name = "Shade Wave Stress", - description = "Importance of avoiding wave stress when fogging. Higher values places more weight on areas with low wave stress.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:fog, :weight), + name="Shade Wave Stress", + description="Importance of avoiding wave stress when fogging. Higher values places more weight on areas with low wave stress.", ) fog_heat_stress::U2 = Factor( 1.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:fog, :weight), - name = "Shade Heat Stress", - description = "Importance of avoiding heat stress when fogging. Higher values places more weight on areas with low heat stress.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:fog, :weight), + name="Shade Heat Stress", + description="Importance of avoiding heat stress when fogging. Higher values places more weight on areas with low heat stress.", ) fog_priority::U2 = Factor( 0.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:fog, :weight), - name = "Predecessor Priority (Shade)", - description = "Importance of shading sites that provide larvae to priority reefs.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:fog, :weight), + name="Predecessor Priority (Shade)", + description="Importance of shading sites that provide larvae to priority reefs.", ) fog_zone::U2 = Factor( 0.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:fog, :weight), - name = "Zone Predecessor (Shade)", - description = "Importance of shading sites that provide larvae to priority (target) zones.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:fog, :weight), + name="Zone Predecessor (Shade)", + description="Importance of shading sites that provide larvae to priority (target) zones.", ) fog_coral_cover_high::U2 = Factor( 0.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:fog, :weight), - name = "High Coral Cover", - description = "Higher values give preference to sites with high coral cover for shading deployments.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:fog, :weight), + name="High Coral Cover", + description="Higher values give preference to sites with high coral cover for shading deployments." ) deployed_coral_risk_tol::U3 = Factor( 1.0; - ptype = "continuous", - dist = Uniform, - dist_params = (0.0, 1.0), - criteria_keywords = (:threshold, :seed, :fog), - name = "Risk Tolerance", - description = "Filters out sites with heat/wave stress above threshold.", + ptype="continuous", + dist=Uniform, + dist_params=(0.0, 1.0), + criteria_keywords=(:threshold, :seed, :fog), + name="Risk Tolerance", + description="Filters out sites with heat/wave stress above threshold.", ) depth_min::DO = Factor( 5.0; - ptype = "ordered categorical", - dist = DiscreteOrderedUniformDist, - dist_params = (3.0, 5.0, 0.5), # Half metre intervals - criteria_keywords = (:threshold,), - name = "Minimum Depth", - description = "Minimum depth for a site to be included for consideration.\nNote: This value will be replaced with the shallowest depth value found if all sites are found to be deeper than `depth_min + depth_offset`.", + ptype="ordered categorical", + dist=DiscreteOrderedUniformDist, + dist_params=(3.0, 5.0, 0.5), # Half metre intervals + criteria_keywords=(:threshold,), + name="Minimum Depth", + description="Minimum depth for a site to be included for consideration.\nNote: This value will be replaced with the shallowest depth value found if all sites are found to be deeper than `depth_min + depth_offset`.", ) depth_offset::DO = Factor( 10.0; - ptype = "ordered categorical", - dist = DiscreteOrderedUniformDist, - dist_params = (10.0, 25.0, 0.5), # Half metre intervals - criteria_keywords = (:threshold,), - name = "Depth Offset", - description = "Offset from minimum depth, used to indicate maximum depth.", + ptype="ordered categorical", + dist=DiscreteOrderedUniformDist, + dist_params=(10.0, 25.0, 0.5), # Half metre intervals + criteria_keywords=(:threshold,), + name="Depth Offset", + description="Offset from minimum depth, used to indicate maximum depth.", ) end @@ -179,7 +179,7 @@ function criteria_params( sel_crit = vec( all( hcat([in.(c_k, crit.criteria_keywords) for c_k in criteria_keywords]...); - dims = 2, + dims=2, ); ) return crit[sel_crit, :] diff --git a/src/decision/dMCDA.jl b/src/decision/dMCDA.jl index f75d6d5599..55b0407fc7 100644 --- a/src/decision/dMCDA.jl +++ b/src/decision/dMCDA.jl @@ -163,7 +163,7 @@ function DMCDA_vars( waves::AbstractArray, dhw::AbstractArray, )::DMCDA_vars - criteria_vec::NamedDimsArray = NamedDimsArray(collect(criteria); rows = names(criteria)) + criteria_vec::NamedDimsArray = NamedDimsArray(collect(criteria); rows=names(criteria)) return DMCDA_vars( domain, criteria_vec, site_ids, leftover_space, area_to_seed, waves, dhw ) @@ -175,7 +175,7 @@ function DMCDA_vars( leftover_space::AbstractArray, area_to_seed::Float64, )::DMCDA_vars - criteria_vec::NamedDimsArray = NamedDimsArray(collect(criteria); rows = names(criteria)) + criteria_vec::NamedDimsArray = NamedDimsArray(collect(criteria); rows=names(criteria)) return DMCDA_vars(domain, criteria_vec, site_ids, leftover_space, area_to_seed) end @@ -194,7 +194,7 @@ end Normalize a Matrix (SE/SH) for MCDA. """ function mcda_normalize(x::Matrix)::Matrix - return x ./ sqrt.(sum(x .^ 2; dims = 1)) + return x ./ sqrt.(sum(x .^ 2; dims=1)) end """ @@ -203,7 +203,7 @@ end Normalize weights for a set of scenarios (wse/wsh) for MCDA. """ function mcda_normalize(x::DataFrame)::DataFrame - return x ./ sum(Matrix(x); dims = 2) + return x ./ sum(Matrix(x); dims=2) end """ @@ -213,7 +213,7 @@ Filter all criteria which are zero for all sites from the decision matrix x. """ function _filter_preferred(x::Union{Matrix, NamedDimsArray})::BitVector # weights in order of: in_conn, out_conn, wave, heat, predecessors, low cover - return vec(.!all(x .== 0; dims = 1)) + return vec(.!all(x .== 0; dims=1)) end """ @@ -311,9 +311,9 @@ end function retrieve_ranks( site_ids::Vector{Float64}, scores::Vector, - maximize::Bool + maximize::Bool, )::Matrix{Union{Float64, Int64}} - s_order::Vector{Int64} = sortperm(scores; rev = maximize) + s_order::Vector{Int64} = sortperm(scores; rev=maximize) return Union{Float64, Int64}[Int64.(site_ids[s_order]) scores[s_order]] end @@ -357,7 +357,7 @@ function create_decision_matrix( site_depth::T, predec::Matrix{Float64}, zones_criteria::T, - risk_tol::Float64, + risk_tol::Float64 )::Tuple{Matrix{Float64}, BitVector} where {T <: Vector{Float64}} A = zeros(length(site_ids), 9) A[:, 1] .= site_ids # Column of site ids @@ -394,7 +394,7 @@ function create_decision_matrix( rule = (A[:, 4] .<= risk_tol) .& (A[:, 5] .> risk_tol) A[rule, 5] .= NaN - filtered = vec(.!any(isnan.(A); dims = 2)) + filtered = vec(.!any(isnan.(A); dims=2)) # Remove rows with NaNs A = A[filtered, :] @@ -451,7 +451,7 @@ function create_seed_matrix( wt_predec_zones_seed::T, wt_low_cover::T, wt_depth_seed::T; - filter_space::T = 0.0, + filter_space::T=0.0 )::Tuple{Matrix{Float64}, Vector{Float64}} where {T <: Float64} # Define seeding decision matrix, based on copy of A SE = copy(A) @@ -473,7 +473,7 @@ function create_seed_matrix( SE[SE[:, 8] .<= filter_space, 8] .= NaN # Filter out sites with no space # Filter out identified locations - SE = SE[vec(.!any(isnan.(SE); dims = 2)), :] + SE = SE[vec(.!any(isnan.(SE); dims=2)), :] return SE, wse end @@ -582,7 +582,7 @@ function guided_site_selection( in_conn::Vector{Float64}, out_conn::Vector{Float64}, strong_pred::Vector{Int64}; - methods_mcda = mcda_methods(), + methods_mcda=mcda_methods() )::Tuple{ Vector{T}, Vector{T}, Matrix{T} } where { @@ -779,7 +779,7 @@ function constrain_reef_cluster( area_to_seed::Float64, available_space::Vector{Float64}, n_iv_locs::Int64, - max_members::Int64, + max_members::Int64 )::Tuple{Vector{Int64}, Matrix{Int64}} # Get ordering of locations by their preferred ranks loc_ordered_ids = s_order[:, 1] @@ -806,7 +806,7 @@ function constrain_reef_cluster( pref_reefs = reefs[pref_locs] # Reefs that selected locations sit within # Number of times a reef appears within each location - reef_occurances = vec(sum(pref_reefs .== unique_reefs; dims = 1)) + reef_occurances = vec(sum(pref_reefs .== unique_reefs; dims=1)) # If more than n_reefs locations in a reef, swap out the worst locations reefs_swap = unique_reefs[(reef_occurances .> max_members)] @@ -822,7 +822,7 @@ function constrain_reef_cluster( locs_to_replace = vcat( [ pref_locs[pref_reefs .== reef][replace_start:end] for reef in reefs_swap - ]... + ]..., ) # Acceptable reefs to switch out for @@ -844,7 +844,7 @@ function constrain_reef_cluster( any( reshape(reefs[alternate_loc_ids], 1, length(reefs[alternate_loc_ids])) .== - reef_switch_ids; dims = 1); dims = 1), + reef_switch_ids; dims=1); dims=1), ) # New preferred location set @@ -910,14 +910,14 @@ function unguided_site_selection( if seed_years pref_seed_locs = zeros(Int64, n_site_int) pref_seed_locs[1:s_n_site_int] .= StatsBase.sample( - candidate_sites, s_n_site_int; replace = false + candidate_sites, s_n_site_int; replace=false ) end if fog_years pref_fog_locs = zeros(Int64, n_site_int) pref_fog_locs[1:s_n_site_int] .= StatsBase.sample( - candidate_sites, s_n_site_int; replace = false + candidate_sites, s_n_site_int; replace=false ) end @@ -942,10 +942,10 @@ conditions (e.g., DHWs, wave stress, etc): function summary_stat_env( env_layer::AbstractArray, dims::Union{Int64, Symbol, Tuple{Symbol, Symbol}}; - w = 0.5 + w=0.5, )::Vector{Float64} return vec( - (mean(env_layer; dims = dims) .* w) .+ (std(env_layer; dims = dims) .* (1.0 - w)) + (mean(env_layer; dims=dims) .* w) .+ (std(env_layer; dims=dims) .* (1.0 - w)) ) end diff --git a/src/ecosystem/connectivity.jl b/src/ecosystem/connectivity.jl index 67e9a9860b..b8abde1e42 100644 --- a/src/ecosystem/connectivity.jl +++ b/src/ecosystem/connectivity.jl @@ -33,9 +33,9 @@ NamedTuple: function site_connectivity( file_loc::String, unique_site_ids::Vector{String}; - con_cutoff::Float64 = 1e-6, - agg_func::Function = mean, - swap::Bool = false, + con_cutoff::Float64=1e-6, + agg_func::Function=mean, + swap::Bool=false, )::NamedTuple if !isdir(file_loc) && !isfile(file_loc) error("Could not find location: $(file_loc)") @@ -69,11 +69,11 @@ function site_connectivity( CSV.read( fn, DataFrame; - comment = "#", - missingstring = "NA", - transpose = swap, - types = Float64, - drop = [1], + comment="#", + missingstring="NA", + transpose=swap, + types=Float64, + drop=[1], ), ) for fn in year_conn_fns[yr] ] @@ -89,14 +89,14 @@ function site_connectivity( con_file1::DataFrame = CSV.read( con_files[1], DataFrame; - comment = "#", - missingstring = "NA", - transpose = swap, - types = Float64, - drop = [1], + comment="#", + missingstring="NA", + transpose=swap, + types=Float64, + drop=[1], ) con_site_ids::Vector{String} = String[ - x[1] for x in split.(names(con_file1), "_v"; limit = 2) + x[1] for x in split.(names(con_file1), "_v"; limit=2) ] if isfile(file_loc) @@ -133,18 +133,18 @@ function site_connectivity( end TP_base = NamedDimsArray( - extracted_TP; Source = unique_site_ids, Receiving = unique_site_ids + extracted_TP; Source=unique_site_ids, Receiving=unique_site_ids ) @assert all(0.0 .<= TP_base .<= 1.0) "Connectivity data not scaled between 0 - 1" - return (TP_base = TP_base, truncated = invalid_ids, site_ids = unique_site_ids) + return (TP_base=TP_base, truncated=invalid_ids, site_ids=unique_site_ids) end function site_connectivity( file_loc::String, unique_site_ids::Vector{Union{Missing, String}}; - con_cutoff::Float64 = 1e-6, - agg_func::Function = mean, - swap::Bool = false, + con_cutoff::Float64=1e-6, + agg_func::Function=mean, + swap::Bool=false, )::NamedTuple # Remove any row marked as missing @@ -157,7 +157,7 @@ function site_connectivity( end return site_connectivity( - file_loc, unique_site_ids; con_cutoff = con_cutoff, agg_func = agg_func, swap = swap + file_loc, unique_site_ids; con_cutoff=con_cutoff, agg_func=agg_func, swap=swap ) end @@ -208,7 +208,7 @@ function connectivity_strength( end end - return (in_conn = C1, out_conn = C2, strongest_predecessor = strong_pred) + return (in_conn=C1, out_conn=C2, strongest_predecessor=strong_pred) end function connectivity_strength( area_weighted_TP::AbstractMatrix{Float64}, diff --git a/src/io/result_io.jl b/src/io/result_io.jl index 471c1e1610..10ae8f7e8d 100644 --- a/src/io/result_io.jl +++ b/src/io/result_io.jl @@ -1,4 +1,4 @@ -const COMPRESSOR = Zarr.BloscCompressor(; cname = "zstd", clevel = 2, shuffle = true) +const COMPRESSOR = Zarr.BloscCompressor(; cname="zstd", clevel=2, shuffle=true) function get_geometry(df::DataFrame) if columnindex(df, :geometry) > 0 @@ -40,8 +40,8 @@ Matrix{Float64, 2}, of mean and standard deviation for each environmental scenar function summarize_env_data(data::AbstractArray)::Array{Float64} # TODO: Update once stats_store::Array{Float64} = zeros(2, size(data, 3), size(data, 2)) - stats_store[1, :, :] .= dropdims(mean(data; dims = 1); dims = 1)' - stats_store[2, :, :] .= dropdims(std(data; dims = 1); dims = 1)' + stats_store[1, :, :] .= dropdims(mean(data; dims=1); dims=1)' + stats_store[2, :, :] .= dropdims(std(data; dims=1); dims=1)' return stats_store end @@ -76,15 +76,15 @@ function store_env_summary( stats_store = zcreate( Float32, (2, size(stats, 2), size(stats, 3))...; - fill_value = nothing, fill_as_missing = false, - path = joinpath(file_loc, rcp), - attrs = Dict( + fill_value=nothing, fill_as_missing=false, + path=joinpath(file_loc, rcp), + attrs=Dict( :structure => ("stat", type, "locations"), :stats => ["mean", "std"], :scenarios => string.(1:size(stats, 2)), :locations => string.(1:size(stats, 3)), :rcp => rcp), - compressor = compressor) + compressor=compressor) stats_store[:, :, :] .= stats @@ -111,19 +111,19 @@ function store_conn( conn_data::NamedDimsArray, file_loc::String, rcp::String, - compressor::Zarr.Compressor + compressor::Zarr.Compressor, )::ZArray conn_store = zcreate( Float32, size(conn_data)...; - fill_value = nothing, fill_as_missing = false, - path = joinpath(file_loc, rcp), - attrs = Dict( + fill_value=nothing, fill_as_missing=false, + path=joinpath(file_loc, rcp), + attrs=Dict( :structure => ("Source", "Receiving"), :Source => conn_data.Source, :Receiving => conn_data.Receiving, :rcp => rcp), - compressor = compressor) + compressor=compressor) conn_store[:, :] .= Matrix(conn_data) return conn_store @@ -209,12 +209,12 @@ function setup_logs(z_store, unique_sites, n_scens, tf, n_sites) ranks = zcreate( Float32, rank_dims...; - name = "rankings", - fill_value = nothing, - fill_as_missing = false, - path = log_fn, - chunks = (rank_dims[1:3]..., 1), - attrs = attrs, + name="rankings", + fill_value=nothing, + fill_as_missing=false, + path=log_fn, + chunks=(rank_dims[1:3]..., 1), + attrs=attrs, ) attrs = Dict( @@ -224,37 +224,37 @@ function setup_logs(z_store, unique_sites, n_scens, tf, n_sites) seed_log = zcreate( Float32, seed_dims...; - name = "seed", - fill_value = nothing, - fill_as_missing = false, - path = log_fn, - chunks = (seed_dims[1:3]..., 1), - attrs = attrs, + name="seed", + fill_value=nothing, + fill_as_missing=false, + path=log_fn, + chunks=(seed_dims[1:3]..., 1), + attrs=attrs, ) attrs = Dict( :structure => ("timesteps", "sites", "scenarios"), - :unique_site_ids => unique_sites + :unique_site_ids => unique_sites, ) fog_log = zcreate( Float32, fog_dims...; - name = "fog", - fill_value = nothing, - fill_as_missing = false, - path = log_fn, - chunks = (fog_dims[1:2]..., 1), - attrs = attrs, + name="fog", + fill_value=nothing, + fill_as_missing=false, + path=log_fn, + chunks=(fog_dims[1:2]..., 1), + attrs=attrs, ) shade_log = zcreate( Float32, fog_dims...; - name = "shade", - fill_value = nothing, - fill_as_missing = false, - path = log_fn, - chunks = (fog_dims[1:2]..., 1), - attrs = attrs, + name="shade", + fill_value=nothing, + fill_as_missing=false, + path=log_fn, + chunks=(fog_dims[1:2]..., 1), + attrs=attrs, ) # TODO: Could log bleaching mortality @@ -279,12 +279,12 @@ function setup_logs(z_store, unique_sites, n_scens, tf, n_sites) 36, n_sites, n_scens; - name = "coral_dhw_log", - fill_value = nothing, - fill_as_missing = false, - path = log_fn, - chunks = (tf, 36, n_sites, 1), - attrs = attrs, + name="coral_dhw_log", + fill_value=nothing, + fill_as_missing=false, + path=log_fn, + chunks=(tf, 36, n_sites, 1), + attrs=attrs, ) else coral_dhw_log = zcreate( @@ -293,12 +293,12 @@ function setup_logs(z_store, unique_sites, n_scens, tf, n_sites) 36, 1, n_scens; - name = "coral_dhw_log", - fill_value = 0.0, - fill_as_missing = false, - path = log_fn, - chunks = (tf, 36, 1, 1), - attrs = attrs, + name="coral_dhw_log", + fill_value=0.0, + fill_as_missing=false, + path=log_fn, + chunks=(tf, 36, 1, 1), + attrs=attrs, ) end @@ -366,13 +366,13 @@ function setup_result_store!(domain::Domain, scen_spec::DataFrame)::Tuple mkdir(joinpath(log_location, "site_data")) geo_fn = joinpath(log_location, "site_data", basename(attrs[:name]) * ".gpkg") try - GDF.write(geo_fn, domain.site_data; driver = "geojson") + GDF.write(geo_fn, domain.site_data; driver="geojson") catch err if !isa(err, ArgumentError) rethrow(err) end - GDF.write(geo_fn, domain.site_data; geom_columns = (:geom,), driver = "geojson") + GDF.write(geo_fn, domain.site_data; geom_columns=(:geom,), driver="geojson") end # Store copy of model specification as CSV @@ -383,17 +383,17 @@ function setup_result_store!(domain::Domain, scen_spec::DataFrame)::Tuple inputs = zcreate( Float64, input_dims...; - fill_value = -9999.0, - fill_as_missing = false, - path = input_loc, - chunks = input_dims, - attrs = attrs, + fill_value=-9999.0, + fill_as_missing=false, + path=input_loc, + chunks=input_dims, + attrs=attrs, ) # Store table of factor values inputs[:, :] = Matrix(scen_spec) - tf, n_sites, _ = size(domain.dhw_scens) + tf, n_sites, _ = size(domain.dhw_scens) # Set up stores for each metric function dim_lengths(metric_structure) @@ -426,11 +426,11 @@ function setup_result_store!(domain::Domain, scen_spec::DataFrame)::Tuple # Create stores for each metric stores = [ zcreate(Float32, result_dims...; - fill_value = nothing, fill_as_missing = false, - path = joinpath(z_store.folder, RESULTS, string(m_name)), - chunks = (result_dims[1:(end - 1)]..., 1), - attrs = dim_struct, - compressor = COMPRESSOR) + fill_value=nothing, fill_as_missing=false, + path=joinpath(z_store.folder, RESULTS, string(m_name)), + chunks=(result_dims[1:(end - 1)]..., 1), + attrs=dim_struct, + compressor=COMPRESSOR) for m_name in met_names ] @@ -438,13 +438,13 @@ function setup_result_store!(domain::Domain, scen_spec::DataFrame)::Tuple push!( stores, zcreate(Float32, (result_dims[1], 6, result_dims[3])...; - fill_value = nothing, fill_as_missing = false, - path = joinpath(z_store.folder, RESULTS, "relative_taxa_cover"), - chunks = ((result_dims[1], 6)..., 1), - attrs = Dict( + fill_value=nothing, fill_as_missing=false, + path=joinpath(z_store.folder, RESULTS, "relative_taxa_cover"), + chunks=((result_dims[1], 6)..., 1), + attrs=Dict( :structure => string.(ADRIA.metrics.relative_taxa_cover.dims) ), - compressor = COMPRESSOR)) + compressor=COMPRESSOR)) push!(met_names, :relative_taxa_cover) # dhw and wave zarrays @@ -481,7 +481,7 @@ function setup_result_store!(domain::Domain, scen_spec::DataFrame)::Tuple domain.TP_data, joinpath(z_store.folder, "connectivity"), rcp, - COMPRESSOR + COMPRESSOR, ), ) @@ -529,7 +529,7 @@ function _recreate_stats_from_store(zarr_store_path::String)::Dict{String, Abstr stat_d = Dict{String, AbstractArray}() for (i, sd) in enumerate(rcp_stat_dirs) - store = zopen(sd; fill_as_missing = false) + store = zopen(sd; fill_as_missing=false) dim_names = Symbol.(store.attrs["structure"]) stats = string.(store.attrs["stats"]) @@ -537,7 +537,7 @@ function _recreate_stats_from_store(zarr_store_path::String)::Dict{String, Abstr loc_ids = string.(store.attrs["locations"]) stat_set = NamedDimsArray( store[:, :, :]; - zip(dim_names, [stats, scenario_ids, loc_ids])... + zip(dim_names, [stats, scenario_ids, loc_ids])..., ) stat_d[rcp_dirs[i]] = stat_set @@ -557,14 +557,14 @@ function _recreate_conn_from_store(zarr_store_path::String)::Dict{String, Abstra conn_d = Dict{String, AbstractArray}() for (i, sd) in enumerate(rcp_stat_dirs) - store = zopen(sd; fill_as_missing = false) + store = zopen(sd; fill_as_missing=false) dim_names = Symbol.(store.attrs["structure"]) source_ids = string.(store.attrs["Source"]) recieving_ids = string.(store.attrs["Receiving"]) conn_set = NamedDimsArray( store[:, :]; - zip(dim_names, [source_ids, recieving_ids])... + zip(dim_names, [source_ids, recieving_ids])..., ) conn_d[rcp_dirs[i]] = conn_set @@ -585,7 +585,7 @@ function load_results(result_loc::String)::ResultSet # Read in results local raw_set try - raw_set = zopen(joinpath(result_loc, RESULTS); fill_as_missing = false) + raw_set = zopen(joinpath(result_loc, RESULTS); fill_as_missing=false) catch err if !occursin("ArgumentError", sprint(showerror, err)) rethrow(err) @@ -593,8 +593,8 @@ function load_results(result_loc::String)::ResultSet end # Read in logs - log_set = zopen(joinpath(result_loc, LOG_GRP); fill_as_missing = false) - input_set = zopen(joinpath(result_loc, INPUTS); fill_as_missing = false) + log_set = zopen(joinpath(result_loc, LOG_GRP); fill_as_missing=false) + input_set = zopen(joinpath(result_loc, INPUTS); fill_as_missing=false) dhw_stat_set = _recreate_stats_from_store(joinpath(result_loc, ENV_STATS, "dhw")) wave_stat_set = _recreate_stats_from_store(joinpath(result_loc, ENV_STATS, "wave")) @@ -611,7 +611,7 @@ function load_results(result_loc::String)::ResultSet # Model specification model_spec = CSV.read( - joinpath(result_loc, MODEL_SPEC, "model_spec.csv"), DataFrame; comment = "#" + joinpath(result_loc, MODEL_SPEC, "model_spec.csv"), DataFrame; comment="#" ) # Standardize fieldnames to Symbol @@ -651,10 +651,10 @@ function load_results(result_loc::String)::ResultSet ) outcomes = Dict{Symbol, NamedDimsArray}() - subdirs = filter(isdir, readdir(joinpath(result_loc, RESULTS); join = true)) + subdirs = filter(isdir, readdir(joinpath(result_loc, RESULTS); join=true)) for sd in subdirs if !(occursin(LOG_GRP, sd)) && !(occursin(INPUTS, sd)) - res = zopen(sd; fill_as_missing = false) + res = zopen(sd; fill_as_missing=false) sz = size(res) # Construct dimension names and metadata