Skip to content

Commit

Permalink
Merge pull request #18 from fernandopalafox/feature/jacobian_error_ha…
Browse files Browse the repository at this point in the history
…ndling

Add error handling for missing Jacobian
  • Loading branch information
lassepe authored Oct 14, 2023
2 parents b76df14 + 2fd05da commit 30ec200
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
2 changes: 2 additions & 0 deletions src/autodiff.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ function _solve_jacobian_θ(problem, solution, θ; active_tolerance = 1e-3)
(; jacobian_z!, jacobian_θ!, lower_bounds, upper_bounds) = problem
z_star = solution.z

!isnothing(jacobian_θ!) || throw(ArgumentError("Missing sensitivities. Set `compute_sensitivities = true` when constructing the ParametricMCP."))

inactive_indices = let
lower_inactive = z_star .>= (lower_bounds .+ active_tolerance)
upper_inactive = z_star .<= (upper_bounds .- active_tolerance)
Expand Down
14 changes: 12 additions & 2 deletions test/runtests.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using ParametricMCPs
using Test: @testset, @test
using Test: @testset, @test, @test_throws
using Random: Random
using LinearAlgebra: norm
using Zygote: Zygote
Expand All @@ -15,6 +15,7 @@ using FiniteDiff: FiniteDiff
lower_bounds = [-Inf, -Inf, 0, 0]
upper_bounds = [Inf, Inf, Inf, Inf]
problem = ParametricMCPs.ParametricMCP(f, lower_bounds, upper_bounds, parameter_dimension)
problem_no_jacobian = ParametricMCPs.ParametricMCP(f, lower_bounds, upper_bounds, parameter_dimension; compute_sensitivities = false)

feasible_parameters = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [rand(rng, 2) for _ in 1:10]...]
infeasible_parameters = -feasible_parameters
Expand Down Expand Up @@ -44,5 +45,14 @@ using FiniteDiff: FiniteDiff
@test isapprox(∇_autodiff_reverse, ∇_finitediff; atol = 1e-4)
@test isapprox(∇_autodiff_reverse, ∇_autodiff_forward; atol = 1e-4)
end
end
end

@testset "missing jacobian" begin
function dummy_pipeline(θ, problem)
solution = ParametricMCPs.solve(problem, θ)
sum(solution.z .^ 2)
end

@test_throws ArgumentError Zygote.gradient-> dummy_pipeline(θ, problem_no_jacobian), feasible_parameters[1])
end
end

0 comments on commit 30ec200

Please sign in to comment.