From 8431b3124dc68214211db519f142ad48ab6894cc Mon Sep 17 00:00:00 2001 From: Penelope Yong Date: Thu, 12 Sep 2024 10:44:11 +0100 Subject: [PATCH] Add error hint for MethodErrors on LogDensityModel (#146) --- Project.toml | 4 ++-- src/AbstractMCMC.jl | 14 ++++++++++++++ test/logdensityproblems.jl | 9 +++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/Project.toml b/Project.toml index 97c90709..60215cec 100644 --- a/Project.toml +++ b/Project.toml @@ -1,9 +1,9 @@ name = "AbstractMCMC" uuid = "80f14c24-f653-4e6a-9b94-39d6b0f70001" -keywords = ["markov chain monte carlo", "probablistic programming"] +keywords = ["markov chain monte carlo", "probabilistic programming"] license = "MIT" desc = "A lightweight interface for common MCMC methods." -version = "5.2.0" +version = "5.3.0" [deps] BangBang = "198e06fe-97b7-11e9-32a5-e1d131e6ad66" diff --git a/src/AbstractMCMC.jl b/src/AbstractMCMC.jl index dc464d42..d7374dd2 100644 --- a/src/AbstractMCMC.jl +++ b/src/AbstractMCMC.jl @@ -88,4 +88,18 @@ include("stepper.jl") include("transducer.jl") include("logdensityproblems.jl") +if isdefined(Base.Experimental, :register_error_hint) + function __init__() + Base.Experimental.register_error_hint(MethodError) do io, exc, argtypes, _ + if Base.parentmodule(exc.f) == LogDensityProblems && + any(a -> a <: LogDensityModel, argtypes) + print( + io, + "\n`AbstractMCMC.LogDensityModel` is a wrapper and does not itself implement the LogDensityProblems.jl interface. To use LogDensityProblems.jl methods, access the inner type with (e.g.) `logdensity(model.logdensity, params)` instead of `logdensity(model, params)`.", + ) + end + end + end +end + end # module AbstractMCMC diff --git a/test/logdensityproblems.jl b/test/logdensityproblems.jl index 181d2645..4a3a22d5 100644 --- a/test/logdensityproblems.jl +++ b/test/logdensityproblems.jl @@ -22,6 +22,15 @@ @test model.logdensity === ℓ @test_throws ArgumentError AbstractMCMC.LogDensityModel(mylogdensity) + + try + LogDensityProblems.logdensity(model, ones(10)) + catch exc + @test exc isa MethodError + if isdefined(Base.Experimental, :register_error_hint) + @test occursin("is a wrapper", sprint(showerror, exc)) + end + end end @testset "fallback for log densities" begin