Skip to content
Snippets Groups Projects
Commit fc23eab9 authored by Marco Matthies's avatar Marco Matthies
Browse files

Fix averagefieldsize and simplify code

- When there are no fields `averagefieldsize` would return a unitless
  number.  This is now fixed.

- An unnecessary allocation was removed

- Fix unit tests, use approximate floating point comparison
parent a8280064
No related branches found
No related tags found
No related merge requests found
......@@ -96,11 +96,9 @@ end
Calculate the average field size in hectares for the model landscape.
"""
function averagefieldsize(model::SimulationModel)
sizes::Vector{Float64} = []
for fp in model.farmplots
push!(sizes, @areaof(length(fp.pixels)))
end
return sum(sizes)/length(sizes) |> ha
area_sum = sum(@areaof(length(fp.pixels)) for fp in model.farmplots; init=0.0u"m^2")
area_avg = area_sum / length(model.farmplots)
return area_avg |> ha
end
"""
......
......@@ -14,7 +14,7 @@
@test Ps.landcover((400,400), model) == Ps.grass
@test Ps.landcover((800,800), model) == Ps.agriculture
@test Ps.landcover((1100,1100), model) == Ps.builtup
@test Ps.averagefieldsize(model) == 5.37
@test isapprox(Ps.averagefieldsize(model), 5.374u"ha"; atol=1e-3u"ha")
@test count(f -> ismissing(f.fieldid), model.landscape) == 1685573
@test length(Ps.farmplot((800,800), model).pixels) == 4049
end
......
......@@ -20,7 +20,7 @@ const Ps = Persefone
const TESTPARAMETERS = joinpath(pkgdir(Persefone), "test/test_parameters.toml")
const TESTSETTINGS = Ps.getsettings(TESTPARAMETERS)
import Unitful: cm, m, km, ha, mg, g, kg, Length, Area, Mass
import Unitful: @u_str, cm, m, km, ha, mg, g, kg, Length, Area, Mass
const = m^2
const km² = km^2
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment