Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions src/solution.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)}(
Expand Down Expand Up @@ -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

"""
Expand Down
15 changes: 15 additions & 0 deletions test/Core/solution.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading