diff --git a/src/solution.jl b/src/solution.jl index e51e90c6b..e776a72bb 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -42,17 +42,26 @@ function DataDrivenSolution( Y = get_implicit_data(prob) Ŷ = b(prob) T = eltype(p) - residuals = Y .- Ŷ - # Handle case where residuals may have element type Any - # (e.g., when basis has no equations due to all-zero coefficients) - if eltype(residuals) === Any - if isempty(residuals) - rss = zero(T) + if isempty(Ŷ) + # Strong sparsity can zero out every coefficient, leaving an empty + # basis whose prediction has no rows. The residual of "no model" is + # the data itself, so the rss is that of the data. This keeps empty + # models comparable (strictly worse than any fit) for rss-based + # selectors such as BIC instead of throwing a DimensionMismatch. + rss = sum(abs2, Y) + else + residuals = Y .- Ŷ + # Handle case where residuals may have element type Any + # (e.g., when basis has no equations due to all-zero coefficients) + if eltype(residuals) === Any + if isempty(residuals) + rss = zero(T) + else + rss = sum(abs2, T.(residuals)) + end else - rss = sum(abs2, T.(residuals)) + rss = sum(abs2, residuals) end - else - rss = sum(abs2, residuals) end return DataDrivenSolution{eltype(p)}( @@ -163,7 +172,11 @@ Returns the `summarystats` for each row of the error for the `DataDrivenSolution """ @views function StatsBase.summarystats(sol::DataDrivenSolution) p = getfield(sol, :prob) - map(summarystats, eachrow(get_implicit_data(p) .- sol(p))) + Y = get_implicit_data(p) + Ŷ = sol(p) + # Empty basis (see DataDrivenSolution): the residual is the data itself. + resids = isempty(Ŷ) ? Y : Y .- Ŷ + map(summarystats, eachrow(resids)) end """ diff --git a/test/Core/solution.jl b/test/Core/solution.jl index 1258c9a11..d689023df 100644 --- a/test/Core/solution.jl +++ b/test/Core/solution.jl @@ -77,3 +77,18 @@ sol_2 = DataDrivenSolution( @test r2(sol_2) ≈ 0.99998 atol = 1.0e-3 @test nobs(sol_2) == prod(size(y)) @test_nowarn summarystats(sol_2) + +# Regression test for #514: strong sparsity (e.g. SR3 with a large threshold) +# can zero out every coefficient, leaving an empty basis. Constructing the +# solution must not throw a DimensionMismatch; the residual is the data itself. +@variables x_empty[1:3] +b_empty = Basis(Num[], x_empty) +@test length(b_empty) == 0 +sol_empty = DataDrivenSolution( + b_empty, prob, DataDrivenDiffEq.ZeroDataDrivenAlgorithm(), + DataDrivenDiffEq.AbstractDataDrivenResult[dummy_sol], + internal_problem +) +@test dof(sol_empty) == 0 +@test rss(sol_empty) ≈ sum(abs2, ŷ) +@test_nowarn summarystats(sol_empty)