我将 [LikelihoodProfiler]: https://github.com/insysbio/LikelihoodProfiler.jl从 Julia 重写为 Python。我需要为[非线性约束]编写约束函数: https ://nlopt.readthedocs.io/en/latest/NLopt_Python_Reference/#nonlinear-constraints ,就好像我们得到一些我们抛出的值[强制停止异常]:https://nlopt .readthedocs.io/en/latest/NLopt_Python_Reference/# exc Nlopt 必须处理异常并使用特殊代码返回结果。
在 [Julia 它看起来]:https ://github.com/insysbio/LikelihoodProfiler.jl/blob/master/src/cico_one_pass.jl
function constraints_func(x, g)
loss = loss_func(x)
if (loss < 0.) && (scan_func(x) > scan_bound)
throw(ForcedStop("Out of the scan bound but in ll constraint."))
#elseif isapprox(loss, 0., atol=loss_tol)
# @warn "loss_tol reached... but..."
# return loss
else
return loss
end
end
opt = Opt(:LN_AUGLAG, n_theta)
ftol_abs!(opt, scan_tol)
max_objective!(
opt,
(x, g) -> scan_func(x)
)
lb = [theta_bounds[i][1] for i in 1:n_theta] # minimum.(theta_bounds)
ub = [theta_bounds[i][2] for i in 1:n_theta] # maximum.(theta_bounds)
lower_bounds!(opt, lb)
upper_bounds!(opt, ub)
local_optimizer!(opt, local_opt)
maxeval!(opt, max_iter)
# inequality constraints
inequality_constraint!(
opt,
constraints_func,
loss_tol
)
# start optimization
(optf, optx, ret) = optimize(opt, theta_init)
我尝试将其重写为 python:
# Constraints function
def constraints_func(x, g, opt):
loss = loss_func(x)
if (loss < 0) and (scan_func(x) > scan_bound):
opt.force_stop()
#raise nlopt.ForcedStop("Out of the scan bound but in ll constraint.")
else:
return loss
# constrain optimizer
opt = nlopt.opt(nlopt.LN_AUGLAG, n_theta)
opt.set_ftol_abs(scan_tol)
opt.set_max_objective(lambda x, g: scan_func(x))
lb = [theta_bounds[i][0] for i in range(n_theta)] # minimum.(theta_bounds)
ub = [theta_bounds[i][1] for i in range(n_theta)] # maximum.(theta_bounds)
opt.set_lower_bounds(lb)
opt.set_upper_bounds(ub)
opt.set_local_optimizer(local_opt)
opt.set_maxeval(max_iter)
# print(max_iter)
# inequality constraints
opt.add_inequality_constraint(lambda x, g: constraints_func(x, g, opt), loss_tol)
# start optimization
optx = opt.optimize(theta_init)
optf = opt.last_optimum_value()
ret = opt.last_optimize_result()
但是当我运行它时,我得到nlopt invalid argument,如果相反
opt.force_stop()
我用
raise nlopt.ForcedStop("Out of the scan bound but in ll constraint.")
我得到nlopt.ForcedStop: Out of the scan bound but in ll 约束
但我预计,Nlopt 会使用特殊代码处理异常并返回优化结果。