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

#!/usr/bin/env python
"``naginterfaces.library.mip.sqp`` Python Example."

# NAG Copyright 2017-2019.

# pylint: disable=invalid-name,too-many-locals

import numpy as np

from naginterfaces.library import mip

[docs]def main(): """ Example for :func:`naginterfaces.library.mip.sqp`. Nonlinear programming with some integer constraints. >>> main() naginterfaces.library.mip.sqp Python Example Results. Solve a portfolio selection problem. Final objective value is 2.9250000e+00 """ print('naginterfaces.library.mip.sqp Python Example Results.') print('Solve a portfolio selection problem.') # The portfolio parameters: rho = 10. p = 3 def cb_confun(mode, varcon, x, cjac, _nstate): """The constraint function.""" if mode == 0: c = [ 8.*x[0] + 9.*x[1] + 12.*x[2] + 7.*x[3] - rho, p - x[4] - x[5] - x[6] - x[7], ] cjac = np.empty(cjac.shape) else: c = np.empty(cjac.shape[0]) cjac = [ [8., 9., 12., 7., 0., 0., 0., 0], [0.]*cjac.shape[1], ] return c, cjac def cb_objfun(mode, varcon, x, objgrd, _nstate): """The objective function.""" if mode == 0: objmip = ( 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]) ) objgrd = np.empty(len(x)) else: objmip = 0. objgrd = [ 8.*x[0] + 6.*x[1] - 2.*x[2], 6.*x[0] + 12.*x[1] + 2.*x[2], 2.*(x[1]-x[0]) + 20.*x[2], 0., 0., 0., 0., 0., ] return objmip, objgrd # Initialize the solver: comm = {} mip.optset('Initialize = sqp', comm) # The initial guess: x = [1., 1., 1., 1., 0., 0., 0., 0.] # There are two nonlinear constraints defined by cb_confun: ncnln = 2 # The linear constraints: a = np.array([ [1., 1., 1., 1., 0., 0., 0., 0.], [-1., 0., 0., 0., 1., 0., 0., 0.], [0., -1., 0., 0., 0., 1., 0., 0.], [0., 0., -1., 0., 0., 0., 1., 0.], [0., 0., 0., -1., 0., 0., 0., 1.], ]) # The linear-constraint constants: d = [1., 0., 0., 0., 0.] # The bounds: bl = [0.]*len(x) bu = [1000., 1000., 1000., 1000., 1., 1., 1., 1.] # The types of the variables: varcon = [ 0, 0, 0, 0, 1, 1, 1, 1, 3, 4, 4, 4, 4, 3, 4, ] # Accuracy parameter: acc = 1.e-6 objmip = mip.sqp( ncnln, bl, bu, varcon, x, cb_objfun, comm, a=a, d=d, confun=cb_confun, acc=acc, ).objmip print('Final objective value is {:.7e}'.format(objmip))
if __name__ == '__main__': import doctest import sys sys.exit( doctest.testmod( None, verbose=True, report=False, optionflags=doctest.REPORT_NDIFF, ).failed )