Packages for linear programming

Một phần của tài liệu Financial risk modelling and portfolio optimization with r second edition (Trang 256 - 260)

In this subsectionRpackages for solving linear programs are presented. The focus is on package implementations based on freely available (i.e., open source) solvers, which are ordinarily covered by the GPL or a similar license. However, it should be noted thatR packages that interface to commercial optimizers are also hosted on CRAN and/or R-Forge. The packagesRcplexandcplexAPIprovide interfaces to the CPLEX solver package (see Bravo et al. 2014 and Gelius-Dietrich 2015a, respectively) and the package Rmosek provides an interface to the commercial MOSEK optimizer (see Friberg 2014).1For more information, consult the vendors’

internet sites: http://www-01.ibm.com/software/integration/

optimization/cplex-optimizer/ and http://www.mosek.com/, respectively. At the time of writing, both vendors offered free trial versions and/or free academic license agreements. Finally, it should be mentioned that theRpackage rneos(see Pfaff 2016) provides user access to the Network-Enabled Optimization System (NEOS; see Czyzyk et al. 1998; Dolan 2001; Gropp and Moré 1997) by means of the XML-RPC (eXtensible Markup Language remote procedure call) application programming interface (API). Incidentally, the MOSEK solver is available in NEOS. For more information about NEOS, see the project’s internet site athttps://neos-server.org/neos/.

The packages glpkAPI and Rglpk

The packages glpkAPI (see Gelius-Dietrich 2015b) and Rglpk (see Theussl and Hornik 2015) both provide access to the GPLK. This software package is organized in the form of a callable library written in ANSIC. With the GLPK, large-scale linear programs as well as mixed integer programs can be solved. As optimization tech- niques, primal/dual simplex, primal/dual interior-point, and branch-and-cut methods have been implemented. The GLPK software is shipped with an API and a standalone linear program / mixed integer linear program (LP/MILP) solver. Problems can be formulated in the GNU MathProg modelling language (GMPL) which is a subset of the AMPL language. More information about GLPK can be found on the project’s internet site,http://www.gnu.org/s/glpk/.

The twoRpackages differ in terms of how access betweenRand GLPK is es- tablished and the layer of abstraction. An implementation of the C API is made available in the packageglpkAPI. This package is hosted on CRAN. It requires a

1All three packages are only available as source packages.

k k GLPK installation, including libraries and header files. Directives for installing the

package are provided in anINSTALLfile, located in the root directory of the source package. The package is shipped with a vignette in which the usage of the cornerstone functions for setting up and solving a linear program are shown.

A different route is followed for accessing GLPK from R within the package Rglpk. Instead of offering the user a low-level entry point to theCAPI, as is the case with the previous package, the packageRglpkoffers high-level access. The package is hosted on CRAN and R-Forge. It is considered to be a core package in the CRAN

“Optimization” Task View. The package is shipped with aNAMESPACEfile in which the two main functionsRglpk_read_file()andRglpk_solve_LP()are ex- ported, as well as aprint()method for files that have been imported by the GLPK file reader. The package is dependent on the packageslamfor handling sparse arrays and matrices. Linear programs in either the fixed or free Mathematical Programming System (MPS) format or expressed in the CPLEX LP macro language can be im- ported and brought into memory with the functionRglpk_read_file(). This is accomplished with the GLPK file reader. The function is endowed with four argu- ments. The argumentfileexpects a character string which specifies the absolute or relative path to the model file. With the argumenttypethe format of the model file is selected. The remaining two arguments are of typelogicaland the user can indicate whether the first row should be ignored by settingignore_first_row toFALSE(the default) and whether additional solver output should be printed while the model file is parsed with theverboseargument (the default is set toFALSE).

The function returns alistobject of informal classMP_data_from_filefor which aprint()method is available. The relevant elements of this kind of object could then be used in the call ofRglpk_solve_LP(), the cornerstone function of the package. The arguments of this function are:

•objfor the coefficients of the objective function;

•matfor the constraint coefficients (either a vector or a matrix object);

•dirfor indicating the kind of inequality/equality constraint specified as a char- acter vector (possible directions are"<","<=",">",">=", or"==";

•rhsfor the right-hand-side values of the constraints;

•typesfor determining whether the variables of the objective function can take continuous ("C"), integer ("I"), or binary ("B") values (the default setting is that all variables are defined as continuous variables);

•maxfor indicating whether the objective is to be maximized or minimized (the default value isFALSE, which means that the objective will be minimized);

•boundsfor defining allowable ranges of the variables;

•verbosewhich serves as a logical switch for controlling the printing of ad- ditional output from the solver.

k k The function returns a list object with the elements"solution","objval",

and"status". The first list element contains the solution found for the variables, the second element is the value of the objective function, and the last element is a status flag indicating whether an optimal solution was determined (0) or not.

The package linprog

For solving linear programs, in the packagelinprog(see Henningsen 2012) the func- tionlp()contained in the packagelpSolvecan be employed; otherwise, the linear program is solved by the simplex algorithm which is directly implemented asRcode.

The packagelpSolveis discussed below. The packagelinprogis hosted on CRAN and contained in the “Optimization” Task View. It is shipped with aNAMESPACE file, andS3classes and methods are employed.

Linear programs in the MPS format can be brought into memory with the func- tionreadMps(). In contrast to the packageRglpkin which the GLPK file reader is employed, the parsing of the MPS file is accomplished entirely inR. In addition to the argumentfile, which points to the MPS file to be read, the user can spec- ify whether the linear program should immediately be solved by setting the logical switchsolvetoTRUE(the default value isFALSE), and whether the objective func- tion should be maximized or minimized by the argumentmaximum(the default value isFALSE, which means that the objective function will be minimized). The function readMps()will return alistof named objects with elements containing the rele- vant information such that these can be employed in a call tosolveLP(). These are namefor carrying the name of the problem and the elementscvec,bvec, andAmat which refer to coefficients of the objective function, the right-hand-side variables, and the left-hand-side constraint matrix, respectively. In the case of direct optimiza- tion, wheresolve=TRUEhas been used, the function will return an additional list element,res, which is an object of informal classsolveLP.

The user can specify the direction of the inequality constraints by means of the argument const.dir. The default value is to treat all constraints as less-than-or-equal-to constraints. At the time of writing, equality constraints are not implemented. The next group of arguments are intended for controlling the algorithm. The maximum number of iterations can be set with the argument maxiter, a threshold value for floating point numbers to be considered as equal is determined by the argumentzero, and the convergence tolerances for the primal and dual specification of the linear program can be specified with the arguments tolanddualtol, respectively. Whether the problem is solved by means of the simplex algorithm or by callinglp()is controlled by the logical switchlpsolve.

The default islpsolve=FALSE. With the last two arguments the user can also specify whether the linear program in its dual form is solved (the default isFALSE) and/or whether any intermediate results are returned to the console (and, if so, in how much detail) by assigning an integer value between 0 and 4 to the argument verbose. The function returns a namedlistobject ofS3 classsolveLPfor whichprint()andsummary()methods are available.

k k Finally, the functionwriteMps()enables the user to save a linear program in

MPS format. In addition to the argumentscvec,bvec, andAmatfor specifying the coefficient, anameargument is used to assign a name to the linear program (the default is set to"LP"). The main purpose of this function is to cross-compare results between different solvers, given that these can digest MPS files.

The packages lpSolve and lpSolveAPI

Akin to GLPK, the software lp_solve is in the public domain and its purpose is to provide routines for solving linear (integer) programs. This suite supports not only LP and MILP, but also binary, semi-continuous, and special ordered set problems. These routines are collected into a library that can be accessed through an API written in ANSIC. The project is hosted on the Sourceforge platform, and more information is available on the project’s internet site athttp://lpsolve .sourceforge.net/.

Two R packages are available that give users access to lp_solve: lpSolve (see Berkelaar 2015) and lpSolveAPI (see Konis 2016). They differ from each other with respect to the level of interfacing with lp_solve. In the former package a rather high-level interface is implemented in the form of a driver routine, whereas the latter package provides low-level access by means of theCAPI functions.

The packagelpSolveis hosted on CRAN and is considered to be a core package in the “Optimization” Task View.S3classes and methods have been employed, and the package ships with aNAMESPACEfile with export directives for the functions and methods defined. The cornerstone function for solving LP or MILP islp(). The function returns a namedlistobject of informal classlp, for which aprint() method has been defined. The elements consist of the elements that have been passed to the solver whenlp()has been called—the direction of the optimization, the co- efficients of the objective function, the right-hand-side matrix, and the left-hand-side constraints. In addition, objects of class lp contain as list elements the value of the objective function and the associated solution vector. Furthermore, the number of (integer) variables, their positions in the vector of variables, and the number of constraints are returned. Finally, the list elementstatusindicates successful com- pletion of the algorithm if it takes the value 0; if no feasible solution is found, a 2 is returned instead. Incidentally, the packagelimSolve(see Soetaert et al. 2009;

Van den Meersche et al. 2009) provides the wrapper function linp(), in which the constraints are separated according to their direction. The remaining functions lp.assign()andlp.transport()contained in the packagelpSolveare in- tended for specific types of linear program, namely assignment and transportation problems, respectively.

Hosted on CRAN and R-Forge, the packagelpSolveAPIis contained in the CRAN

“Optimization” Task View. Development versions of the package can be obtained fromhttp://lpsolve.r-forge.r-project.org. A vignette is available in which the definition, handling, solving, and solution retrieval of a linear program model object (LPMO) are elucidated by a worked-through example linear program.

Therefore, a typical workflow would consist of first defining a linear program with

k k respect to its dimension by the function make.lp()and then filling the LPMO

object (an external pointer to a Cstructure) with data and specifying the type of variables and the directions of the constraints. When this is accomplished, the model can be solved by a call to the functionsolve(). The results can then be retrieved by means of access methods. Methods for LPMO printing and plotting (two-dimensional only) are available, as well asRfunctions for reading a linear program specification (read.lp()) that has been expressed in either LP (a macro language pertinent to lp_solve) or fixed/free MPS format. Finally, a linear program specification can be written to a file in the same formats with the functionwrite.lp().

The package Rsymphony

The packageRsymphonyprovides a high-level interface to the MILP solver SYM- PHONY (see Harter et al. 2016). The package is hosted on CRAN and R-Forge. It is contained in the “Optimization” Task View and has the status of a core package. The solver SYMPHONY is part of the COIN-OR project (seehttp://www.coin-or .org/SYMPHONY/index.htmfor more information). The solver implements the branch, cut, and price approach for solving MILP problems. As such the approach taken is more powerful than using the branch and bound method for solving linear programs alone. The solver itself is written in theClanguage.

The package exports the functionRysmphony_solve_LP()for solving MILP problems. The target vector of the objective function has to be provided as argument objto this function. The coefficient matrix, the relation operator between this and the right-hand-side variables, and the right-hand-side variables themselves have to be specified as argumentsmat,dir, andrhs, respectively. The following relation operators can be used as characters fordir:"<","<","<=",">",">=","==", and"!=". Bounds for the target variables can be specified as alistobject with elementslowerandupperfor the respective lower and upper bounds. The type of target variables is determined by the argumenttype. Here, the user can specify whether a target variable is treated as continuous ("C"), integer ("I"), or binary ("B"). If this argument is leftNULLthen all targets are taken as continuous vari- ables. Finally, the logical argumentmaxcontrols whether the objective function is maximized or minimized (the default). The functionRysmphony_solve_LP() returns a listobject with elementssolution,objval, andstatusfor the solved target variables, the value of the objective function, and an integer that indi- cates the status of the solver’s execution, respectively.

The package is further endowed with functions that convert the coefficient matrix into the sparse column major order used by SYMPHONY as well as for preparing and checking the specified bounds. These functions are not exported via directives in the NAMESPACE file of the package.

Một phần của tài liệu Financial risk modelling and portfolio optimization with r second edition (Trang 256 - 260)

Tải bản đầy đủ (PDF)

(436 trang)