Source code for naginterfaces.library.examples.mip.handle_solve_minlp_ex

#!/usr/bin/env python3
"``naginterfaces.library.mip.handle_solve_minlp`` Python Example."

# NAG Copyright 2018-2020.

# pylint: disable=invalid-name

from naginterfaces.base import utils
from naginterfaces.library import opt, mip

[docs]def main(): """ Example for :func:`naginterfaces.library.mip.handle_solve_minlp`. Nonlinear programming with some integer constraints. >>> main() naginterfaces.library.mip.handle_solve_minlp Python Example Results. Solve a portfolio selection problem. Final objective value is 2.9250000e+00 """ print( 'naginterfaces.library.mip.handle_solve_minlp Python Example Results.' ) print('Solve a portfolio selection problem.') # The portfolio parameters: rho = 10. p = 3 # The nonlinear objective: cb_objfun = lambda x, inform: ( ( x[0]*(4.*x[0]+3.*x[1]-x[2]) + x[1]*(3.*x[0]+6.*x[1]+x[2]) + x[2]*(x[1]-x[0]+10.*x[2]) ), 0, ) def cb_objgrd(x, fdx, inform): """The gradient of the objective.""" fdx[0] = 8.*x[0] + 6.*x[1] - 2.*x[2] fdx[1] = 6.*x[0] + 12.*x[1] + 2.*x[2] fdx[2] = 2.*(x[1]-x[0]) + 20.*x[2] fdx[3] = 0. return 0 # The nonlinear constraints function: cb_confun = lambda x, _ncnln, inform: ( [ 8.*x[0] + 9.*x[1] + 12.*x[2] + 7.*x[3] - rho, p - x[4] - x[5] - x[6] - x[7], ], 0, ) def cb_congrd(x, gdx, inform): """The Jacobian of the nonlinear constraints.""" gdx[:4] = [8., 9., 12., 7.] return inform # The problem size: n = 8 # The initial guess: x = [1., 1., 1., 1., 0., 0., 0., 0.] # Create a handle for the problem: handle = opt.handle_init(nvar=n) # Define the bounds: opt.handle_set_simplebounds( handle, bl=[0.]*n, bu=[1000., 1000., 1000., 1000., 1., 1., 1., 1.], ) # Define the non-linear objective: opt.handle_set_nlnobj( handle, idxfd=[1, 2, 3, 4], ) # Define the linear constraints: opt.handle_set_linconstr( handle, bl=[1.] + [0.]*4, bu=[1.] + [1.e20]*4, irowb=[ 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, ], icolb=[ 1, 2, 3, 4, 1, 5, 2, 6, 3, 7, 4, 8 ], b=[ 1., 1., 1., 1., -1., 1, -1., 1, -1., 1, -1., 1 ], ) # Define the nonlinear constraints: opt.handle_set_nlnconstr( handle, bl=[0., 0.], bu=[0., 1.e20], irowgd=[1, 1, 1, 1], icolgd=[1, 2, 3, 4], ) # Set integer variables opt.handle_set_property(handle=handle, ptype='Bin', idx=[5, 6, 7, 8]) # Set some algorithmic options. for option in [ 'Verify Derivatives = Yes', 'Print Level = 0', ]: opt.handle_opt_set(handle, option) # Use an explicit I/O manager for abbreviated iteration output: iom = utils.FileObjManager(locus_in_output=False) # Solve the problem. soln = mip.handle_solve_minlp( handle, x, objfun=cb_objfun, objgrd=cb_objgrd, confun=cb_confun, congrd=cb_congrd, io_manager=iom) print('Final objective value is {:.7e}'.format(soln.rinfo[0])) # Destroy the handle: opt.handle_free(handle)
if __name__ == '__main__': import doctest import sys sys.exit( doctest.testmod( None, verbose=True, report=False, optionflags=doctest.ELLIPSIS | doctest.REPORT_NDIFF, ).failed )