### Compile All Examples using Make Source: https://docs.mosek.com/latest/cxxfusion/install-interface Builds all example applications for the MOSEK Fusion API using the 'make all' command. This is typically run from the examples directory. ```shell make all ``` -------------------------------- ### Compile All Examples using NMake Source: https://docs.mosek.com/latest/cxxfusion/install-interface Builds all example applications for the MOSEK Fusion API using the 'nmake all' command. This command is used on Windows systems. ```shell nmake all ``` -------------------------------- ### Compile Single Example using Make Source: https://docs.mosek.com/latest/cxxfusion/install-interface Compiles a specific example file, such as 'lo1.cc', using the 'make' utility. This is useful for building individual examples in the MOSEK Fusion API distribution. ```shell make lo1 ``` -------------------------------- ### Compile Single Example using NMake Source: https://docs.mosek.com/latest/cxxfusion/install-interface Compiles a specific example file, such as 'lo1.cc', using the 'nmake' utility on Windows. The output executable is typically named 'lo1.exe'. ```shell nmake lo1.exe ``` -------------------------------- ### Basic Linear Programming Setup in C++ Source: https://docs.mosek.com/latest/cxxfusion/examples-list Demonstrates the initial setup for a linear programming problem in C++ using MOSEK Fusion. It defines the objective function and constraints, although the specific problem details are truncated in the provided snippet. ```cpp //// // Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved. // // File: lo1.cc // // Purpose: Demonstrates how to solve the problem // // maximize 3*x0 + 1*x1 + 5*x2 + x3 // such that ``` -------------------------------- ### Problem Setup for QCQP SDP Relaxation and Integer Least Squares Source: https://docs.mosek.com/latest/cxxfusion/examples-list This C++ code snippet sets up the problem dimensions and generates random data for matrices and vectors used in the QCQP SDP relaxation and integer least squares examples. It includes generating matrices A and P, vectors c, b, and q, and performing matrix operations like syrk and gemv. ```cpp int main(int argc, char ** argv) { std::default_random_engine generator; generator.seed(time(0)); std::uniform_real_distribution unif_distr(0., 1.); std::normal_distribution normal_distr(0., 1.); // problem dimensions int n = 20; int m = 2 * n; auto c = new_array_ptr(n); auto A = new_array_ptr(n * m); auto P = new_array_ptr(n * n); auto b = new_array_ptr(m); auto q = new_array_ptr(n); std::generate(A->begin(), A->end(), std::bind(normal_distr, generator)); std::generate(c->begin(), c->end(), std::bind(unif_distr, generator)); std::fill(b->begin(), b->end(), 0.0); std::fill(q->begin(), q->end(), 0.0); // P = A^T A syrk(MSK_UPLO_LO, MSK_TRANSPOSE_YES, n, m, 1.0, A, 0., P); for (int j = 0; j < n; j++) for (int i = j + 1; i < n; i++) (*P)[i * n + j] = (*P)[j * n + i]; // q = -P c, b = A c gemv(MSK_TRANSPOSE_NO, n, n, -1.0, P, c, 0., q); gemv(MSK_TRANSPOSE_NO, m, n, 1.0, A, c, 0., b); // Solve the problems { Model::t M = miqcqp_sdo_relaxation(n, Matrix::dense(n, n, P), q); Model::t Mint = int_least_squares(n, Matrix::dense(n, m, A)->transpose(), b); M->solve(); Mint->solve(); auto xRound = M->getVariable("Z")-/ slice(new_array_ptr({0, n}), new_array_ptr({n, n + 1}))->level(); for (int i = 0; i < n; i++) (*xRound)[i] = round((*xRound)[i]); auto yRound = new_array_ptr(m); auto xOpt = Mint->getVariable("x")->level(); auto yOpt = new_array_ptr(m); std::copy(b->begin(), b->end(), yRound->begin()); std::copy(b->begin(), b->end(), yOpt->begin()); gemv(MSK_TRANSPOSE_NO, m, n, 1.0, A, xRound, -1.0, yRound); // Ax_round-b ``` -------------------------------- ### Set and Get MOSEK Fusion Solver Parameters Source: https://docs.mosek.com/latest/cxxfusion/examples-list Illustrates how to configure MOSEK Fusion solver parameters, such as log level, optimizer type, and gap tolerance, using `setSolverParam`. It also shows how to retrieve solver information items like optimization time and iterations using `getSolverDoubleInfo` and `getSolverIntInfo`. The example includes error handling for invalid parameter values. ```cpp /* Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved. File : parameters.cc Purpose : Demonstrates a very simple example about how to set parameters and read information items with MOSEK Fusion */ #include #include "fusion.h" using namespace mosek::fusion; using namespace monty; int main(int argc, char ** argv) { Model::t M = new Model(""); auto _M = finally([&]() { M->dispose(); }); std::cout << "Test MOSEK parameter get/set functions\n"; // Set log level (integer parameter) M->setSolverParam("log", 1); // Select interior-point optimizer... (parameter with symbolic string values) M->setSolverParam("optimizer", "intpnt"); // ... without basis identification (parameter with symbolic string values) M->setSolverParam("intpntBasis", "never"); // Set relative gap tolerance (double parameter) M->setSolverParam("intpntCoTolRelGap", 1.0e-7); // The same in a different way M->setSolverParam("intpntCoTolRelGap", "1.0e-7"); // Incorrect value try { M->setSolverParam("intpntCoTolRelGap", -1); } catch (mosek::fusion::ParameterError) { std::cout << "Wrong parameter value\n"; } // Define and solve an optimization problem here // M->solve() // After optimization: std::cout << "Get MOSEK information items\n"; double tm = M->getSolverDoubleInfo("optimizerTime"); int it = M->getSolverIntInfo("intpntIter"); std::cout << "Time: " << tm << "\nIterations: " << it << "\n"; return 0; } ``` -------------------------------- ### Link C++ Application with MOSEK Fusion on Windows Source: https://docs.mosek.com/latest/cxxfusion/install-interface Compiles and links a C++ application using the MOSEK Fusion API on Windows. It specifies include directories for headers and library paths for static libraries. ```c++ cl /I file.cc /link /LIBPATH: fusion64_11_0.lib mosek64_11_0.lib ``` -------------------------------- ### C++ MOSEK Fusion Main Function Setup Source: https://docs.mosek.com/latest/cxxfusion/_downloads/4e09bd30a18cd36edb699f68c2d36a06/callback The `main` function in this C++ code initializes a MOSEK Fusion model, generates a random linear optimization problem, and sets up the optimizer (primal simplex, dual simplex, or interior-point) based on command-line arguments. It then assigns a custom callback handler to monitor the optimization process. ```cpp int main(int argc, char ** argv) { std::string slvr("intpnt"); if (argc <= 1) { std::cerr << "Usage: ( psim | dsim | intpnt ) \n"; } if (argc >= 2) slvr = argv[1]; /* Solve a big random linear optimization problem */ int n = 150, m = 700; std::default_random_engine generator; std::uniform_real_distribution unif_distr(0., 10.); auto c = new_array_ptr(n); auto b = new_array_ptr(m); auto A = new_array_ptr(m * n); std::generate(c->begin(), c->end(), std::bind(unif_distr, generator)); std::generate(b->begin(), b->end(), std::bind(unif_distr, generator)); std::generate(A->begin(), A->end(), std::bind(unif_distr, generator)); Model::t M = new Model(); auto x = M->variable(n, Domain::unbounded()); M->constraint(Expr::mul(Matrix::dense(m, n, A), x), Domain::lessThan(b)); M->objective(ObjectiveSense::Maximize, Expr::dot(c, x)); if ( slvr == "psim") M->setSolverParam("optimizer", "primalSimplex"); else if ( slvr == "dsim") M->setSolverParam("optimizer", "dualSimplex"); else if ( slvr == "intpnt") M->setSolverParam("optimizer", "intpnt"); double maxtime = 0.07; callbackHandler_t cllbck = [&](MSKcallbackcodee caller, const double * douinf, const int32_t* intinf, const int64_t* lintinf) { return usercallback(caller, douinf, intinf, lintinf, M, maxtime); }; // Note: The actual call to solve the model with the callback is missing in this snippet. // Typically, it would involve M->solve() or a similar method with the callback as an argument. return 0; } ``` -------------------------------- ### Compile Fusion API C++ on Windows Source: https://docs.mosek.com/latest/cxxfusion/install-interface Compiles the MOSEK Fusion API C++ source code using the 'nmake install' command. This command is used on Windows to build the C++ API libraries from source. ```shell cd /mosek/11.0/tools/platform//src/fusion_cxx nmake install ``` -------------------------------- ### Compile Fusion API C++ on Linux/macOS Source: https://docs.mosek.com/latest/cxxfusion/install-interface Compiles the MOSEK Fusion API C++ source code using the 'make install' command. This step is mandatory for Linux and macOS users to build the C++ API libraries. ```shell cd /mosek/11.0/tools/platform//src/fusion_cxx make install ``` -------------------------------- ### Visual Studio Project Configuration for Mosek Fusion Source: https://docs.mosek.com/latest/cxxfusion/install-interface Instructions for configuring a Visual Studio project to use the Mosek Fusion C++ library. This involves setting release and x64 configurations, adding include directories, specifying the runtime library, and linking necessary .lib files. It also includes setting the PATH environment variable for DLLs. ```text Project → Properties Configuration: Release Platform: x64 Configuration Manager: Active solution configuration: Release Active solution platform: x64 Configuration Properties → C/C++ → General → Additional Include Directories: Configuration Properties → C/C++ → Code Generation → Runtime library: /MD Configuration Properties → Linker → Input → Additional Dependencies: mosek64_11_0.lib, fusion64_11_0.lib Configuration Properties → Debugging → Environment: PATH=%PATH%; ``` -------------------------------- ### Link C++ Application with MOSEK Fusion on Linux Source: https://docs.mosek.com/latest/cxxfusion/install-interface Compiles and links a C++ application using the MOSEK Fusion API on Linux. It specifies include paths for headers and library paths for shared libraries, setting runtime paths for dynamic linking. ```c++ g++ -std=c++11 file.cc -o file -I -L -Wl,-rpath-link, -Wl,-rpath= -lmosek64 -lfusion64 ``` -------------------------------- ### Define Semidefinite Cone Problem with MOSEK Fusion (C++) Source: https://docs.mosek.com/latest/cxxfusion/examples-list This snippet demonstrates a basic setup for a semidefinite cone problem using the MOSEK Fusion C++ API. It initializes a model, defines a single semidefinite variable, sets up an objective function, and adds a constraint. The code includes setting a log handler and solving the problem. ```C++ Model::t M = new Model("sdo2"); auto _M = finally([&]() { M->dispose(); }); // Two semidefinite variables auto X1 = M->variable(Domain::inPSDCone(3)); auto X2 = M->variable(Domain::inPSDCone(4)); // Objective M->objective(ObjectiveSense::Minimize, Expr::add(Expr::dot(C1,X1), Expr::dot(C2,X2))); // Equality constraint M->constraint(Expr::add(Expr::dot(A1,X1), Expr::dot(A2,X2)), Domain::equalsTo(b)); // Inequality constraint M->constraint(X2->index(nint({0,1})), Domain::lessThan(k)); // Solve M->setLogHandler([ = ](const std::string & msg) { std::cout << msg << std::flush; } ); M->solve(); // Retrieve solution std::cout << "Solution (vectorized) : " << std::endl; std::cout << " X1 = " << *(X1->level()) << std::endl; std::cout << " X2 = " << *(X2->level()) << std::endl; return 0; } ``` -------------------------------- ### Main Function for Portfolio Optimization Example Source: https://docs.mosek.com/latest/cxxfusion/examples-list Sets up and runs the Markowitz portfolio optimization with cardinality constraints. This `main` function initializes input data such as expected returns, covariance matrix, initial holdings, and risk tolerance. It then calls the `MarkowitzWithCardinality` function to find optimal portfolios for different cardinality limits. ```cpp int main(int argc, char ** argv) { int n = 8; double w = 1.0; auto mu = new_array_ptr( {0.07197, 0.15518, 0.17535, 0.08981, 0.42896, 0.39292, 0.32171, 0.18379} ); auto x0 = new_array_ptr({0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}); auto GT = new_array_ptr({ {0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638}, {0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506}, {0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914}, {0. , 0. , 0. , 0.20876, 0.04933, 0.03651, 0.09381, 0.07742}, {0. , 0. , 0. , 0. , 0.36096, 0.12574, 0.10157, 0.0571 }, {0. , 0. , 0. , 0. , 0. , 0.21552, 0.05663, 0.06187}, {0. , 0. , 0. , 0. , 0. , 0. , 0.22514, 0.03327}, {0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.2202 } }); auto gamma = 0.25; std::vector kValues = { 1, 2, 3, 4, 5, 6, 7, 8 }; std::cout << std::endl << std::endl << "================================" << "Markowitz portfolio optimization" << "================================" << std::endl; std::cout << std::setprecision(4) << std::setiosflags(std::ios::scientific); // The actual call to the optimization function would go here, // followed by processing of the returned results. // std::vector> optimal_portfolios = MarkowitzWithCardinality(n, mu, GT, x0, w, gamma, kValues); return 0; } ``` -------------------------------- ### TSP Main Function Setup in C++ Source: https://docs.mosek.com/latest/cxxfusion/case-studies-tsp This snippet demonstrates the main function for setting up and running the TSP example. It initializes problem parameters like the number of nodes and creates sparse matrices for the adjacency and cost data, then calls the tsp function with different configurations. ```cpp int main() { auto A_i = new_array_ptr({0, 1, 2, 3, 1, 0, 2, 0}); auto A_j = new_array_ptr({1, 2, 3, 0, 0, 2, 1, 3}); auto C_v = new_array_ptr({1., 1., 1., 1., 0.1, 0.1, 0.1, 0.1}); int n = 4; tsp(n, Matrix::sparse(n, n, A_i, A_j, 1.), Matrix::sparse(n, n, A_i, A_j, C_v), true, false); tsp(n, Matrix::sparse(n, n, A_i, A_j, 1.), Matrix::sparse(n, n, A_i, A_j, C_v), true, true); return 0; } ``` -------------------------------- ### Solver Interaction Tutorials Source: https://docs.mosek.com/latest/cxxfusion/index Guides on interacting with MOSEK solvers, including accessing solutions, handling errors, and setting parameters. ```APIDOC ## Solver Interaction ### Description This section covers how to interact with the MOSEK solvers through the Fusion API, including retrieving results, managing errors, and configuring solver behavior. ### Topics * **Accessing the solution**: How to retrieve optimal solutions. * **Errors and exceptions**: Handling and understanding errors. * **Input/Output**: Data import and export capabilities. * **Setting solver parameters**: Customizing solver behavior. * **Retrieving information items**: Accessing diagnostic information. * **Stopping the solver**: Methods for interrupting the optimization process. * **Progress and data callback**: Monitoring solver progress. * **Optimizer API Task**: Understanding the core task object. * **MOSEK OptServer**: Interacting with the OptServer. ``` -------------------------------- ### Link C++ Application with MOSEK Fusion on macOS Source: https://docs.mosek.com/latest/cxxfusion/install-interface Compiles and links a C++ application using the MOSEK Fusion API on macOS. It includes standard library flags and uses 'install_name_tool' to correctly link shared libraries at runtime. ```c++ clang++ -std=c++11 -stdlib=libc++ file.cc -o file -I -L -Wl,-headerpad,128 -lmosek64 -lfusion64 install_name_tool -change libmosek64.11.0.dylib /libmosek64.11.0.dylib file install_name_tool -change libfusion64.11.0.dylib /libfusion64.11.0.dylib file ``` -------------------------------- ### Solve MILO Problem with MOSEK Fusion API (C++) Source: https://docs.mosek.com/latest/cxxfusion/tutorial-mio-shared Complete C++ example demonstrating the setup, solving, and retrieval of results for a mixed-integer linear optimization problem using MOSEK Fusion API. ```cpp #include #include #include "fusion.h" using namespace mosek::fusion; using namespace monty; int main(int argc, char ** argv) { auto a1 = new_array_ptr({ 50.0, 31.0 }); auto a2 = new_array_ptr({ 3.0, -2.0 }); auto c = new_array_ptr({ 1.0, 0.64 }); Model::t M = new Model("milo1"); auto _M = finally([&]() { M->dispose(); }); Variable::t x = M->variable("x", 2, Domain::integral(Domain::greaterThan(0.0))); // Create the constraints // 50.0 x[0] + 31.0 x[1] <= 250.0 // 3.0 x[0] - 2.0 x[1] >= -4.0 M->constraint("c1", Expr::dot(a1, x), Domain::lessThan(250.0)); M->constraint("c2", Expr::dot(a2, x), Domain::greaterThan(-4.0)); // Set max solution time M->setSolverParam("mioMaxTime", 60.0); // Set max relative gap (to its default value) M->setSolverParam("mioTolRelGap", 1e-4); // Set max absolute gap (to its default value) M->setSolverParam("mioTolAbsGap", 0.0); // Set the objective function to (c^T * x) M->objective("obj", ObjectiveSense::Maximize, Expr::dot(c, x)); // Solve the problem M->solve(); // Get the solution values auto sol = x->level(); std::cout << std::setiosflags(std::ios::scientific) << std::setprecision(2) << "x1 = " << (*sol)[0] << std::endl << "x2 = " << (*sol)[1] << std::endl << "MIP rel gap = " << M->getSolverDoubleInfo("mioObjRelGap") << " (" << M->getSolverDoubleInfo("mioObjAbsGap") << ")" << std::endl; } ``` -------------------------------- ### Synchronous OptServer Solution with C++ Fusion API Source: https://docs.mosek.com/latest/cxxfusion/_downloads/e031fc83dedf24a0a5be179b7383adb5/opt_server_sync This example demonstrates how to set up and solve an optimization problem using MOSEK's OptServer synchronously. It requires the OptServer address and an optional TLS certificate path as arguments. The code defines a simple linear problem, attaches a log handler, and connects to the OptServer to solve it. ```cpp // // Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved. // // File : opt_server_sync.cc // // Purpose : Demonstrates how to use MOSEK OptServer // to solve optimization problem synchronously // #include #include #include using namespace mosek::fusion; using namespace monty; int main(int argc, char ** argv) { if (argc<2) { std::cout << "Missing argument, syntax is:" << std::endl; std::cout << " opt_server_sync addr [certpath]" << std::endl; exit(0); } std::string serveraddr(argv[1]); std::string tlscert(argc==3 ? argv[2] : ""); // Setup a simple test problem Model::t M = new Model("testOptServer"); auto _M = finally([&]() { M->dispose(); } ); Variable::t x = M->variable("x", 3, Domain::greaterThan(0.0)); M->constraint("lc", Expr::dot(new_array_ptr({1.0, 1.0, 2.0}), x), Domain::equalsTo(1.0)); M->objective("obj", ObjectiveSense::Minimize, Expr::sum(x)); // Attach log handler M->setLogHandler([](const std::string & msg) { std::cout << msg << std::flush; } ); // Set OptServer URL M->optserverHost(serveraddr); // Path to certificate, if any M->setSolverParam("remoteTlsCertPath", tlscert); // Solve the problem on the OptServer M->solve(); // Get the solution std::cout << "x1,x2,x2 = " << *(x->level()) << std::endl; return 0; } ``` -------------------------------- ### Main execution for MOSEK C++ Fusion examples Source: https://docs.mosek.com/latest/cxxfusion/_downloads/f43fa53740ac985532a285570a84a498/portfolio_5_card The main function sets up parameters for a portfolio optimization problem and calls the `MarkowitzWithCardinality` function. It defines the number of assets, initial wealth, expected returns, covariance matrix, and initial holdings. ```cpp int main(int argc, char ** argv) { int n = 8; double w = 1.0; auto mu = new_array_ptr( {0.07197, 0.15518, 0.17535, 0.08981, 0.42896, 0.39292, 0.32171, 0.18379} ); auto x0 = new_array_ptr({0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}); auto GT = new_array_ptr({ {0.30758, 0.12146, 0.11341, 0.11327, 0.17625, 0.11973, 0.10435, 0.10638}, {0. , 0.25042, 0.09946, 0.09164, 0.06692, 0.08706, 0.09173, 0.08506}, {0. , 0. , 0.19914, 0.05867, 0.06453, 0.07367, 0.06468, 0.01914}, ``` -------------------------------- ### Install MOSEK Python API Source: https://docs.mosek.com/latest/cxxfusion/python-console Installs the MOSEK interface for Python using pip. This is a prerequisite for using the Python Console. ```bash pip install Mosek ``` -------------------------------- ### Elastic Net Linear Regression with Parameterization in C++ Source: https://docs.mosek.com/latest/cxxfusion/examples-list This C++ example demonstrates how to implement an elastic net linear regression model using the MOSEK Fusion API. It showcases model parameterization, allowing for dynamic updates of data (b) and regularization parameters (lambda1, lambda2) without rebuilding the entire model. The code defines a function to initialize the model and a main function to run a small example. ```C++ // Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved. // // File: elastic.cc // // Purpose: Demonstrates model parametrization on the example of an elastic net linear regression: // // min_x |Ax-b|_2 + lambda1*|x|_1 + lambda2*|x|_2 #include #include "fusion.h" using namespace mosek::fusion; using namespace monty; // Construct the model with parameters b, lambda1, lambda2 // and with prescribed matrix A Model::t initializeModel(int m, int n, std::shared_ptr> A) { Model::t M = new Model(); auto x = M->variable("x", n); // t >= |Ax-b|_2 where b is a parameter auto b = M->parameter("b", m); auto t = M->variable(); M->constraint(Expr::vstack(t, Expr::sub(Expr::mul(A, x), b)), Domain::inQCone()); // p_i >= |x_i|, i=1..n auto p = M->variable(n); M->constraint(Expr::hstack(p, x), Domain::inQCone()); // q >= |x|_2 auto q = M->variable(); M->constraint(Expr::vstack(q, x), Domain::inQCone()); // Objective, parametrized with lambda1, lambda2 // t + lambda1*sum(p) + lambda2*q auto lambda1 = M->parameter("lambda1"); auto lambda2 = M->parameter("lambda2"); auto obj = Expr::add(new_array_ptr({t, Expr::mul(lambda1, Expr::sum(p)), Expr::mul(lambda2, q)})); M->objective(ObjectiveSense::Minimize, obj); // Return the ready model return M; } int smallExample() { //Create a small example int m = 4; int n = 2; auto A = new_array_ptr( { {1.0, 2.0}, {3.0, 4.0}, {-2.0, -1.0}, {-4.0, -3.0} }); auto M = initializeModel(m, n, A); // For convenience retrieve some elements of the model auto b = M->getParameter("b"); auto lambda1 = M->getParameter("lambda1"); auto lambda2 = M->getParameter("lambda2"); auto x = M->getVariable("x"); // First solve b->setValue(new_array_ptr({0.1, 1.2, -1.1, 3.0})); lambda1->setValue(0.1); lambda2->setValue(0.01); M->solve(); auto sol = x->level(); std::cout << "Objective " << M->primalObjValue() << ", solution " << (*sol)[0] << ", " << (*sol)[1] << "\n"; // Increase lambda1 lambda1->setValue(0.5); M->solve(); sol = x->level(); std::cout << "Objective " << M->primalObjValue() << ", solution " << (*sol)[0] << ", " << (*sol)[1] << "\n"; // Now change the data completely b->setValue(new_array_ptr({1.0, 1.0, 1.0, 1.0})); lambda1->setValue(0.0); lambda2->setValue(0.0); M->solve(); sol = x->level(); std::cout << "Objective " << M->primalObjValue() << ", solution " << (*sol)[0] << ", " << (*sol)[1] << "\n"; // And increase lamda2 lambda2->setValue(1.4145); M->solve(); sol = x->level(); std::cout << "Objective " << M->primalObjValue() << ", solution " << (*sol)[0] << ", " << (*sol)[1] << "\n"; M->dispose(); return 0; } int main() { return smallExample(); } ``` -------------------------------- ### Set and Get MOSEK Fusion Parameters (C++) Source: https://docs.mosek.com/latest/cxxfusion/_downloads/347c449950fb737493736ef251f2ac1c/parameters Demonstrates setting integer, string, and double parameters for the MOSEK solver, as well as retrieving solver information items like optimization time and iterations. It uses the `setSolverParam` and `getSolverDoubleInfo`/`getSolverIntInfo` methods. ```cpp #include #include "fusion.h" using namespace mosek::fusion; using namespace monty; int main(int argc, char ** argv) { Model::t M = new Model(""); auto _M = finally([&]() { M->dispose(); }); std::cout << "Test MOSEK parameter get/set functions\n"; // Set log level (integer parameter) M->setSolverParam("log", 1); // Select interior-point optimizer... (parameter with symbolic string values) M->setSolverParam("optimizer", "intpnt"); // ... without basis identification (parameter with symbolic string values) M->setSolverParam("intpntBasis", "never"); // Set relative gap tolerance (double parameter) M->setSolverParam("intpntCoTolRelGap", 1.0e-7); // The same in a different way M->setSolverParam("intpntCoTolRelGap", "1.0e-7"); // Incorrect value try { M->setSolverParam("intpntCoTolRelGap", -1); } catch (mosek::fusion::ParameterError) { std::cout << "Wrong parameter value\n"; } // Define and solve an optimization problem here // M->solve() // After optimization: std::cout << "Get MOSEK information items\n"; double tm = M->getSolverDoubleInfo("optimizerTime"); int it = M->getSolverIntInfo("intpntIter"); std::cout << "Time: " << tm << "\nIterations: " << it << "\n"; return 0; } ``` -------------------------------- ### Break MOSEK Solver with Timeout in C++ Source: https://docs.mosek.com/latest/cxxfusion/examples-list This C++ code demonstrates how to set up and solve a binary optimization problem using the MOSEK Fusion API. It includes a mechanism to break the solver if it exceeds a specified timeout duration by using `M->breakSolver()`. The example requires the MOSEK library and the Fusion API. ```cpp // // Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved. // // File: breaksolver.cc // // Purpose: Show how to break a long-running task. // // Requires a parameter defining a timeout in seconds. // #include #include #include #include #include #include #include #include #include #include #include "assert.h" using namespace mosek::fusion; using namespace monty; template static std::ostream & operator<<(std::ostream & strm, const std::vector & arr) { strm << "["; if (arr.size() > 0) strm << arr[0]; for (auto iter = arr.begin() + 1; iter != arr.end(); ++iter) strm << " ," << *iter; strm << "]"; return strm; } int main(int argc, char ** argv) { int timeout = 5; int n = 200; // number of binary variables int m = n / 3; // number of constraints int p = n / 5; // Each constraint picks p variables and requires that exactly half of them are 1 std::cout << "Build problem...\n"; std::vector idxs(n); for (int i = 0; i < n; ++i) idxs[i] = i; std::shared_ptr< ndarray > cidxs(new ndarray(shape(p))); //auto rand = std::bind(std::uniform_int_distribution(0,n-1), std::mt19937(0)); Model::t M = new Model("SolveBinary"); auto _M = finally([&]() { M->dispose(); } ); M->setLogHandler([](const std::string & msg) { std::cout << msg << std::flush; } ); Variable::t x = M->variable("x", n, Domain::binary()); for (int i = 0; i < m; ++i) { std::random_shuffle(idxs.begin(), idxs.end(), [ = ](int i) { return std::rand() % i; }); std::copy(idxs.begin(), idxs.begin() + p, cidxs->begin()); M->constraint(Expr::sum(x->pick(cidxs)), Domain::equalsTo(p / 2)); } M->objective(ObjectiveSense::Minimize, Expr::sum(x)); std::cout << "Start thread...\n"; bool alive = true; std::thread T(std::function([&]() { M->solve(); alive = false; }) ); time_t T0 = time(NULL); while (true) { if (time(NULL) - T0 > timeout) { std::cout << "Solver terminated due to timeout!\n"; M->breakSolver(); T.join(); break; } if (! alive) { std::cout << "Solver terminated before anything happened!\n"; T.join(); break; } } return 0; } ``` -------------------------------- ### MOSEK C++ Quadratic Cone Constraint Example (cqo1.cc) Source: https://docs.mosek.com/latest/cxxfusion/examples-list This C++ example demonstrates how to solve a problem involving quadratic and rotated quadratic cone constraints using MOSEK Fusion. The problem minimizes y1 + y2 + y3 subject to a linear equality constraint and cone constraints. It illustrates the definition of variables, constraints, and objective, and how to retrieve solution details. ```cpp // // Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved. // // File: cqo1.cc // // Purpose: Demonstrates how to solve the problem // // minimize y1 + y2 + y3 // such that // x1 + x2 + 2.0 x3 = 1.0 // x1,x2,x3 >= 0.0 // and // (y1,x1,x2) in C_3, // (y2,y3,x3) in K_3 // // where C_3 and K_3 are respectively the quadratic and // rotated quadratic cone of size 3 defined as // C_3 = { z1,z2,z3 : z1 >= sqrt(z2^2 + z3^2) } // K_3 = { z1,z2,z3 : 2 z1 z2 >= z3^2 } // #include #include "fusion.h" using namespace mosek::fusion; using namespace monty; int main(int argc, char ** argv) { Model::t M = new Model("cqo1"); auto _M = finally([&]() { M->dispose(); }); Variable::t x = M->variable("x", 3, Domain::greaterThan(0.0)); ```