From fc23eab9f345e46b16fdcdb7d2a0b7c0607489bd Mon Sep 17 00:00:00 2001 From: Marco Matthies <71844+marcom@users.noreply.github.com> Date: Mon, 19 Aug 2024 06:34:48 +0200 Subject: [PATCH] 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 --- src/crop/farmplot.jl | 8 +++----- test/landscape_tests.jl | 2 +- test/runtests.jl | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/crop/farmplot.jl b/src/crop/farmplot.jl index c100306..ecd4baf 100644 --- a/src/crop/farmplot.jl +++ b/src/crop/farmplot.jl @@ -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 """ diff --git a/test/landscape_tests.jl b/test/landscape_tests.jl index d80afb2..9aa3cb3 100644 --- a/test/landscape_tests.jl +++ b/test/landscape_tests.jl @@ -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 diff --git a/test/runtests.jl b/test/runtests.jl index 4ee512e..7fb635a 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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² = m^2 const km² = km^2 -- GitLab