Feature request : Passing additional parameters to cost and gradient function.
pirpyn opened this issue · 2 comments
pirpyn commented
Lets have the following example :
The cost function is f
and his gradient is g
. x
is the optimization variable, real array of size 2. Let y,z
be real array of same dimensions ( > 1 )
f = 0.5_wp*sum( ( x(1) + y*x(2) - z )**2 )
g(1) = sum( x(1) + y*x(2) - z )
g(2) = sum( y*(x(1) + y*x(2) - z ))
How can we pass y
and z
to f
and g
? Is it already implemented ?
jacobwilliams commented
Yes, you can do that in a couple of different ways. In the example slsqp_test.f90, you can see how the functions are contained within the calling routine. In that case, you could just declare your y
and z
in the calling routine and then the functions would have access to it.
Alternately, you can extend the slsqp_solver
class and add whatever data you want. Something like:
type,extends(slsqp_solver) :: mysolver
real(wp) :: y,z
end type mysolver
Then in your function:
subroutine func(me,x,f,c)
implicit none
class(slsqp_solver),intent(inout) :: me
real(wp),dimension(:),intent(in) :: x
real(wp),intent(out) :: f
real(wp),dimension(:),intent(out) :: c
select type (me)
class is (mysolver)
f = 0.5_wp*sum( ( x(1) + me%y*x(2) - me%z )**2 )
! ... etc
end select
end subroutine func
pirpyn commented
extends
is a nice way to do it. Thank you.