qiaoxu123
1/6/2020 - 7:24 AM

OOQP官方实例代码

OOQP的官方示例代码,程序运行和具体分析具体请参考Ubuntu下OOQP库的安装, Ubuntu环境下OOQP优化库的基本使用 [//]: # (Uploading ma27-1.0.0.tar.gz)

/* OOQP                                                               *
 * Authors: E. Michael Gertz, Stephen J. Wright                       *
 * (C) 2001 University of Chicago. See Copyright Notification in OOQP */

#include "GondzioSolver.h"
#include "QpGenData.h"
#include "QpGenResiduals.h"
#include "QpGenSparseMa27.h"
#include "QpGenVars.h"

#include <iostream>
#include <string.h>

using namespace std;

const int nx = 2;
double c[] = {1.5, -2}; // 目标函数中的线性项,长度为nx的向量

double xupp[] = {20, 0};
char ixupp[] = {1, 0};

double xlow[] = {0, 0};
char ixlow[] = {1, 1};

const int nnzQ = 3;      // 数目与矩阵的下三角矩阵的个数相对应
int irowQ[] = {0, 1, 1}; // 对称矩阵Q,仅在irowQ,jcolQ和dQ中指定
int jcolQ[] = {0, 0, 1}; // 矩阵的下三角元素
double dQ[] = {8, 2, 10};

int my = 0;     // 线性等式约束的个数
double *b = 0;  // 线性等式约束的右侧向量b
int nnzA = 0;   // nonze-ros总数
int *irowA = 0; // 等式约束中的A
int *jcolA = 0;
double *dA = 0;

const int mz = 2; // 不等式约束的个数
double clow[] = {2, 0};
char iclow[] = {1, 0};

double cupp[] = {0, 6};
char icupp[] = {0, 1};

const int nnzC = 4; // 多项式不等式约束的个数
int irowC[] = {0, 0, 1, 1};
int jcolC[] = {0, 1, 0, 1};
double dC[] = {2, 1, -1, 2};

int main(int argc, char *argv[]) {
  int usage_ok = 1, quiet = 0;

  if (argc > 2)
    usage_ok = 0;
  if (argc == 2) {
    if (0 == strcmp("--quiet", argv[1])) {
      quiet = 1;
    } else {
      usage_ok = 0;
    }
  }
  if (!usage_ok) {
    cerr << "Usage: " << argv[0] << " [ --quiet ]\n";
    return 1;
  }

  QpGenSparseMa27 *qp = new QpGenSparseMa27(nx, my, mz, nnzQ, nnzA, nnzC);

  QpGenData *prob = (QpGenData *)qp->copyDataFromSparseTriple(
      c, irowQ, nnzQ, jcolQ, dQ, xlow, ixlow, xupp, ixupp, irowA, nnzA, jcolA,
      dA, b, irowC, nnzC, jcolC, dC, clow, iclow, cupp, icupp);

  QpGenVars *vars = (QpGenVars *)qp->makeVariables(prob);
  QpGenResiduals *resid = (QpGenResiduals *)qp->makeResiduals(prob);

  GondzioSolver *s = new GondzioSolver(qp, prob);

  if (!quiet)
    s->monitorSelf();
  int ierr = s->solve(prob, vars, resid);

  if (ierr == 0) {
    cout.precision(4);
    cout << "Solution: \n";
    vars->x->writefToStream(cout, "x[%{index}] = %{value}");
  } else {
    cout << "Could not solve the problem.\n";
  }
  return ierr;
}
SHELL = /bin/sh

OOQP=../../..
OOQPINCLUDEDIR=$(OOQP)/include
OOQPLIBDIR=$(OOQP)/lib


CXX      = c++

CXXFLAGS =-O 
CPPFLAGS =-I$(OOQPINCLUDEDIR)
LDFLAGS  =-L$(OOQPLIBDIR)
BLAS     = -lblas
MA27LIB  = $(OOQP)/extras/MA27/libMA27.a
FLIBS    = -lgfortran
LIBS     = -looqpgensparse -looqpsparse  -looqpgondzio -looqpbase \
                $(BLAS) $(MA27LIB) $(FLIBS)

cxx_example.exe : example.o
	$(CXX) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LIBS)

clean:
	rm -f *.o

veryclean: clean
	rm -f *.exe

distclean: veryclean

.C.o:
	$(CXX) -c $(CPPFLAGS) $(CXXFLAGS) -o $@ $<