MPC_functions.cpp 24.5 KB
Newer Older
1
#include "MPC_functions.h"
2
#include <unsupported/Eigen/MatrixFunctions>
roangel's avatar
roangel committed
3
#include <unsupported/Eigen/KroneckerProduct>
4

5
6
7
8
9
extern "C"
{
#include <gurobi_c.h>
}

10
11
12
using namespace Eigen;
using namespace std;

13

14
void linearization_fast_euler_6_states(const VectorXtype x_vec, const VectorUtype u_vec, params_t params, MatrixAtype &A, MatrixBtype &B)
15
{
16
    double m = params.m;
17
    A = MatrixAtype::Zero();
18
    A.topRightCorner(3,3) = Matrix3d::Identity();
19

20
21
22
23
    double gamma = u_vec(0);
    double beta = u_vec(1);
    double alpha = u_vec(2);
    double ft = u_vec(3);
24

25
26
    double c_alpha = cos(alpha);
    double s_alpha = sin(alpha);
27

28
29
30
31
    double s_beta = sin(beta);
    double c_beta = cos(beta);
    double c_gamma = cos(gamma);
    double s_gamma = sin(gamma);
32
33

    B = MatrixBtype::Zero();
34
35
36
    B.row(3) << (ft*(c_gamma*s_alpha - c_alpha*s_beta*s_gamma))/m, (ft*c_alpha*c_beta*c_gamma)/m, (ft*(c_alpha*s_gamma - c_gamma*s_alpha*s_beta))/m,  (s_alpha*s_gamma + c_alpha*c_gamma*s_beta)/m;
    B.row(4) << -(ft*(c_alpha*c_gamma + s_alpha*s_beta*s_gamma))/m, (ft*c_beta*c_gamma*s_alpha)/m, (ft*(s_alpha*s_gamma + c_alpha*c_gamma*s_beta))/m, -(c_alpha*s_gamma - c_gamma*s_alpha*s_beta)/m;
    B.row(5) << -(ft*c_beta*s_gamma)/m,           -(ft*c_gamma*s_beta)/m,                                                                0,                                     (c_beta*c_gamma)/m;
37
38

}
39
40
41
42

void F_crazyflie_6_states(const VectorXtype x_vec, const VectorUtype u_vec, params_t params, VectorXtype &dx_vec)
{

43
44
    double m = params.m;
    double g = params.g;
45

46
47
48
49
50
51
    double c_alpha = cos(u_vec(2));
    double s_alpha = sin(u_vec(2));
    double s_beta = sin(u_vec(1));
    double c_beta = cos(u_vec(1));
    double c_gamma = cos(u_vec(0));
    double s_gamma = sin(u_vec(0));
52

53
    double c = u_vec(3)/m;
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

    dx_vec.head(3) = x_vec.tail(3);
    dx_vec.tail(3) << c*(c_alpha*s_beta*c_gamma + s_alpha*s_gamma),
                      c*(s_alpha*s_beta*c_gamma - c_alpha*s_gamma),
                      c*(c_beta*c_gamma) - g;

}


void discretization_affine(const MatrixAtype A, const MatrixBtype B, const VectorXtype x_tray, const VectorUtype u_tray, params_t params, MatrixAtype &A_d, MatrixBtype &B_d, VectorXtype &g_d)
{
    VectorXtype g;
    VectorXtype temp;

    F_crazyflie_6_states(x_tray,u_tray, params, temp);

    g = temp - A*x_tray - B*u_tray;

    int c_A = A.cols();
    int c_B = B.cols();

75
    MatrixXd M(c_A + c_B + 1, c_A + c_B + 1);
76
77
78


    M << A, B, g,
79
        MatrixXd::Zero(c_B+1, c_A), MatrixXd::Zero(c_B+1, c_B), MatrixXd::Zero(c_B+1,1);
80
81
82
83

    // std::cout << M << std::endl;

    // % discretization
84
    MatrixXd M_d;
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

    M = M*params.Ts;
    M_d = M.exp();


    A_d = M_d.topLeftCorner(c_A, c_A);
    B_d = M_d.block(0,c_A,c_A,c_B);
    g_d = M_d.topRightCorner(c_A, 1);


    // Eigen::IOFormat OctaveFmt(Eigen::StreamPrecision, 0, ", ", ";\n", "", "", "[", "]");
    // std::cout << A_d.format(OctaveFmt) << std::endl << std::endl;
    // std::cout << B_d.format(OctaveFmt) << std::endl << std::endl;
    // std::cout << g_d.format(OctaveFmt) << std::endl << std::endl;
}

void get_matrices_linearization_affine(std::vector<VectorXtype> X_tray, std::vector<VectorUtype> U_tray, params_t params, std::vector<MatrixAtype> &A_tray, std::vector<MatrixBtype> &B_tray, std::vector<VectorXtype> &g_tray)
{
    int N = X_tray.size();

    A_tray.clear();
    B_tray.clear();
    g_tray.clear();

    for(int i = 0; i < N; i++)
    {
        MatrixAtype A_temp;
        MatrixBtype B_temp;
        VectorXtype g_temp;

        linearization_fast_euler_6_states(X_tray[i], U_tray[i], params, A_temp, B_temp);
        discretization_affine(A_temp, B_temp, X_tray[i], U_tray[i], params, A_temp, B_temp, g_temp);

        A_tray.push_back(A_temp);
        B_tray.push_back(B_temp);
        g_tray.push_back(g_temp);
    }
}
123
124
125



126
void euler_method_forward(F_callback_type pF, double t0, double h, double tfinal, VectorXtype y0, VectorUtype u, params_t params, std::vector<VectorXtype> &yout)
127
128
129
{
    VectorXtype y = y0;
    VectorXtype y_next;
roangel's avatar
roangel committed
130
131
    std::vector<VectorXtype> yout_temp;
    yout_temp.push_back(y);
132

133
    for(double t = t0; t < tfinal; t = t + h)
134
135
136
137
    {
        pF(y, u, params, y_next);

        y = y + h*y_next;
roangel's avatar
roangel committed
138
        yout_temp.push_back(y);
139
    }
roangel's avatar
roangel committed
140
141
142
    yout = yout_temp;
}

143
void funSxSuSg_varying_affine(std::vector<MatrixAtype> A_tray, std::vector<MatrixBtype> B_tray, int N, MatrixXd &Sx, MatrixXd &Su, MatrixXd &Sg)
roangel's avatar
roangel committed
144
145
146
147
148
{
    int N_A = A_tray.size();
    int N_B = B_tray.size();

    if(N_A != N)
149
        std::cout << "Error: number of A matrices hsould be equal to N, however it is equal to: "<< N_A <<endl << endl;
roangel's avatar
roangel committed
150
    if(N_B != N)
151
        std::cout << "Error: number of B matrices hsould be equal to N, however it is equal to: "<< N_B <<endl << endl;
roangel's avatar
roangel committed
152
153
154
155
156
157
158
159
160
161
162
163
    // int r_A = A_tray[0].rows();
    // int c_A = A_tray[0].cols();
    // int r_A = B_tray[0].rows();
    // int c_A = B_tray[0].cols();

    int r_A = N_x;
    int c_A = N_x;
    int r_B = N_x;
    int c_B = N_u;

    // S_x is the temporal, local variable that will in the end be the output, Sx

164
165
    MatrixXd S_x = MatrixXd::Zero(r_A*(N+1), c_A);
    MatrixAtype A_mult = MatrixXd::Identity(r_A, r_A);
roangel's avatar
roangel committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180

    // construct S_x:
    for(int i = 0; i < N+1; i++)
    {

        S_x.middleRows(i*r_A, r_A) << A_mult;
        if (i < N)              // we cannot access index N in A_tray, protect it
        {
            A_mult = A_tray[i]*A_mult;
        }
    }


    // construct Su

181
    MatrixXd S_u = MatrixXd::Zero(r_B*(N+1), c_B*N);
roangel's avatar
roangel committed
182
183
184

    // temporal variables:

185
    MatrixXd column_Su;
roangel's avatar
roangel committed
186
187
188
189


    for(int i = 0; i < N; i++)
    {
190
191
        column_Su = MatrixXd::Ones(r_B * (N+1), c_B);
        A_mult = MatrixXd::Identity(r_A, c_A);
roangel's avatar
roangel committed
192
193
194
195
196
197
198
199
200
201

        for(int j = 0; j < N+1; j++)
        {
            if (j == i+1)
            {

                column_Su.middleRows(r_B*j, r_B) << B_tray[i];
            }
            else if (j > i+1)
            {
roangel's avatar
roangel committed
202
203
                A_mult = A_tray[j-1]  * A_mult;
                column_Su.middleRows(r_B*j, r_B) << A_mult * B_tray[i];
roangel's avatar
roangel committed
204
205
206
207
208
209
210
211
212
213
214
215
216
            }
            else
            {
                // can possibly omit this else, just for clarity. Of course first we need to initizlize to zero instead of ones columns Su
                column_Su.middleRows(r_B*j, r_B).setZero();
            }
        }

        S_u.middleCols(c_B*i, c_B) << column_Su;
    }

    // build Sg matrix

217
    MatrixXd S_g = MatrixXd::Zero(r_A*(N+1), c_A*N);
roangel's avatar
roangel committed
218
219
220

    // temporal variables:

221
    MatrixXd column_Sg;
roangel's avatar
roangel committed
222
223
224
225


    for(int i = 0; i < N; i++)
    {
226
227
        column_Sg = MatrixXd::Ones(r_A * (N+1), c_A);
        A_mult = MatrixXd::Identity(r_A, c_A);
roangel's avatar
roangel committed
228
229
230
231
232
233
234
235
236
237

        for(int j = 0; j < N+1; j++)
        {
            if (j == i+1)
            {

                column_Sg.middleRows(r_A*j, r_A).setIdentity();
            }
            else if (j > i+1)
            {
roangel's avatar
roangel committed
238
239
                A_mult = A_tray[j-1]  * A_mult;
                column_Sg.middleRows(r_A*j, r_A) << A_mult;
roangel's avatar
roangel committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
            }
            else
            {
                // can possibly omit this else, just for clarity. Of course first we need to initizlize to zero instead of ones columns Su
                column_Sg.middleRows(r_A*j, r_A).setZero();
            }
        }

        S_g.middleCols(c_A*i, c_A) << column_Sg;
    }

    Sx = S_x;
    Su = S_u;
    Sg = S_g;
254
}
roangel's avatar
roangel committed
255
256


257
void funQbar(MatrixXd Q, MatrixXd P, int N, MatrixXd &Qbar)
roangel's avatar
roangel committed
258
{
259
260
    MatrixXd Q_bar;
    MatrixXd diag_mask = VectorXd::Ones(N+1).asDiagonal();
roangel's avatar
roangel committed
261
262
263
264
265
266
    Q_bar = kroneckerProduct(diag_mask, Q);
    Q_bar.bottomRightCorner(P.rows(), P.cols()) = P;

    Qbar = Q_bar;
}

267
void funRbar(MatrixXd R, int N, MatrixXd &Rbar)
roangel's avatar
roangel committed
268
{
269
270
    MatrixXd R_bar;
    MatrixXd diag_mask = VectorXd::Ones(N).asDiagonal();
roangel's avatar
roangel committed
271
272
273
274
    R_bar = kroneckerProduct(diag_mask, R);
    Rbar = R_bar;
}

275
VectorXd mympc_varying_another(std::vector<MatrixAtype> A_tray, std::vector<MatrixBtype> B_tray, std::vector<VectorXtype> g_tray, MatrixXd Q, MatrixXd R, MatrixXd P, int N, VectorXtype x0, VectorXd X_ref, VectorXd U_ref, double ft_min, double ft_max, double af)
276
{
277
278
279
    Eigen::MatrixXd Sx;
    Eigen::MatrixXd Su;
    Eigen::MatrixXd Sg;
280
281
282
283
284

    VectorUtype u_optimal;

    funSxSuSg_varying_affine(A_tray, B_tray, N, Sx, Su, Sg);

285
    VectorXd g_tray_col(N*N_x);
286
287
288
289
290
291
292
293
294

    for(int i = 0; i < g_tray.size(); i++)
    {
        g_tray_col.segment(i*N_x, N_x) = g_tray[i];
    }

    // std::cout << "g_tray_col" << std::endl;
    // std::cout << g_tray_col << std::endl;

295
296
    Eigen::MatrixXd Qbar;
    Eigen::MatrixXd Rbar;
297
298
299
300

    funQbar(Q, P, N, Qbar);
    funRbar(R,N, Rbar);

301
302
    Eigen::MatrixXd H;
    Eigen::MatrixXd F;
303
304
305
306
307

    H = Su.transpose()*Qbar*Su + Rbar;

    F = 2*(x0.transpose()*Sx.transpose()*Qbar*Su + g_tray_col.transpose()*Sg.transpose()*Qbar*Su - X_ref.transpose()*Qbar*Su - U_ref.transpose()*Rbar);

308
    Eigen::IOFormat CleanFmt(4, 0, ", ", "\n", "[", "]");
309

310
311
    // std::cout << "H test:" << std::endl << std::endl;
    // std::cout << H.format(CleanFmt) << std::endl;
312

roangel's avatar
roangel committed
313
    // ft_min and ft_max constraints:
roangel's avatar
roangel committed
314
    RowVectorXd pattern(4);
roangel's avatar
roangel committed
315
    pattern << 0, 0, 0, 1;
roangel's avatar
roangel committed
316
317
318
319

    // std::cout << "pattern test:" << std::endl << std::endl;
    // std::cout << pattern.format(CleanFmt) << std::endl;

roangel's avatar
roangel committed
320
321
322
    MatrixXd Au_kernel(2*N, N);
    Au_kernel.topRows(N) = MatrixXd::Identity(N,N);
    Au_kernel.bottomRows(N) = (-1)*MatrixXd::Identity(N,N);
roangel's avatar
roangel committed
323
324
325
326
327
328
329

    // std::cout << "Au_kernel test:" << std::endl << std::endl;
    // std::cout << Au_kernel.format(CleanFmt) << std::endl;




roangel's avatar
roangel committed
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
    MatrixXd Au = kroneckerProduct(Au_kernel, pattern);
    VectorXd bu(2*N);
    bu.topRows(N) = VectorXd::Ones(N)*ft_max;
    bu.bottomRows(N) = VectorXd::Ones(N)*(-ft_min);

    // std::cout << "Au test:" << std::endl << std::endl;
    // std::cout << Au.format(CleanFmt) << std::endl;

    // std::cout << "bu test:" << std::endl << std::endl;
    // std::cout << bu.format(CleanFmt) << std::endl;

    // Eigen::MatrixXd W = MatrixXd::Zero(4,4);

    // W(1,1) = 1/(af^2);
    // W(2,2) = 1/(af^2);

    Eigen::VectorXd U_0 = solve_QP(H, F, Au, bu, af);
    // Eigen::VectorXd U_0 = solve_QP(H, F, Au, bu);
    // Eigen::VectorXd U_0 = solve_QP(H, F);

    return U_0;
}


354
VectorXd mympc_varying_another_ADP(std::vector<MatrixAtype> A_tray, std::vector<MatrixBtype> B_tray, std::vector<VectorXtype> g_tray, MatrixXd Q, MatrixXd R, MatrixXd P, int N, VectorXtype x0, VectorXd X_ref, VectorXd U_ref, double ft_min, double ft_max, double af)
roangel's avatar
roangel committed
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
{
    Eigen::MatrixXd Sx;
    Eigen::MatrixXd Su;
    Eigen::MatrixXd Sg;

    funSxSuSg_varying_affine(A_tray, B_tray, N, Sx, Su, Sg);

    VectorXd g_tray_col(N*N_x);

    for(int i = 0; i < g_tray.size(); i++)
    {
        g_tray_col.segment(i*N_x, N_x) = g_tray[i];
    }

    // std::cout << "g_tray_col" << std::endl;
    // std::cout << g_tray_col << std::endl;

    Eigen::MatrixXd Qbar_1;
    Eigen::MatrixXd Rbar;

    funQbar(Q, Q, N-1, Qbar_1);
    funRbar(R,N, Rbar);

    Eigen::MatrixXd H;
    Eigen::MatrixXd F;

    int size_1 = N_x*(N-1);

    Eigen::MatrixXd Su_1 = Su.topRows(size_1);
    Eigen::MatrixXd Sx_1 = Sx.topRows(size_1);
    Eigen::MatrixXd Sg_1 = Sg.topRows(size_1);

    Eigen::VectorXd X_ref_1 = X_ref.head(size_1);

    Eigen::MatrixXd Su_N = Su.bottomRows(N_x);
    Eigen::MatrixXd Sx_N = Sx.bottomRows(N_x);
    Eigen::MatrixXd Sg_N = Sg.bottomRows(N_x);

    VectorXtype X_ref_N = X_ref.tail(N_x);

    H = Su_1.transpose()*Qbar_1*Su_1 + Rbar;

    // in this case, F is a row vector
    F = 2*(x0.transpose()*Sx_1.transpose()*Qbar_1*Su_1 + g_tray_col.transpose()*Sg_1.transpose()*Qbar_1*Su_1 - X_ref_1.transpose()*Qbar_1*Su_1 - U_ref.transpose()*Rbar);

    // include epigraph in the matrices:
    Eigen::MatrixXd H_final = Eigen::MatrixXd::Zero(H.rows() + 1, H.cols() + 1);
    Eigen::MatrixXd F_final = Eigen::MatrixXd::Zero(F.rows(), F.cols() + 1);

    H_final.topLeftCorner(H.rows(),H.cols()) << H;

406
    F_final.leftCols(N*N_u) << F;
roangel's avatar
roangel committed
407
408
409
410
411
412
413
414
    F_final.rightCols(1) << 1.0;

    Eigen::IOFormat CleanFmt(4, 0, ", ", "\n", "[", "]");

    // std::cout << "H test:" << std::endl << std::endl;
    // std::cout << H.format(CleanFmt) << std::endl;

    // ft_min and ft_max constraints:
415

roangel's avatar
roangel committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
    RowVectorXd pattern(4);
    pattern << 0, 0, 0, 1;

    // std::cout << "pattern test:" << std::endl << std::endl;
    // std::cout << pattern.format(CleanFmt) << std::endl;

    MatrixXd Au_kernel(2*N, N);
    Au_kernel.topRows(N) = MatrixXd::Identity(N,N);
    Au_kernel.bottomRows(N) = (-1)*MatrixXd::Identity(N,N);

    // std::cout << "Au_kernel test:" << std::endl << std::endl;
    // std::cout << Au_kernel.format(CleanFmt) << std::endl;




roangel's avatar
roangel committed
432
433
434
435
436
    MatrixXd Au = kroneckerProduct(Au_kernel, pattern);
    VectorXd bu(2*N);
    bu.topRows(N) = VectorXd::Ones(N)*ft_max;
    bu.bottomRows(N) = VectorXd::Ones(N)*(-ft_min);

roangel's avatar
roangel committed
437
438
439
440
441
442
    // std::cout << "Au test:" << std::endl << std::endl;
    // std::cout << Au.format(CleanFmt) << std::endl;

    // std::cout << "bu test:" << std::endl << std::endl;
    // std::cout << bu.format(CleanFmt) << std::endl;

443
444
445
446
447
    // Eigen::MatrixXd W = MatrixXd::Zero(4,4);

    // W(1,1) = 1/(af^2);
    // W(2,2) = 1/(af^2);

448
449
450
    Eigen::VectorXd U_0 = solve_QP(H, F, Au, bu, af);
    // Eigen::VectorXd U_0 = solve_QP(H, F, Au, bu);
    // Eigen::VectorXd U_0 = solve_QP(H, F);
451

452
453
    return U_0;
}
454

455
VectorXd solve_QP(Eigen::MatrixXd H, Eigen::MatrixXd F, Eigen::MatrixXd A, Eigen::VectorXd b, double af)
456
{
roangel's avatar
roangel committed
457
458
459
    // H is assumed to be symmetric. There is NO 0.5 factor anywhere, with this we solve:
    // min(x'Hx + F'x)

460
    int size_H = H.cols();
roangel's avatar
roangel committed
461
462
    int cols_A = A.cols();
    int rows_A = A.rows();
463

464
465
466
467
    std::vector<int> q_row;
    std::vector<int> q_col;
    std::vector<double> q_val;
    std::vector<double> l_obj_coeff;
468

469
470
471
472
    for(int i = 0; i < size_H; i++)
    {
        for(int j = i; j < size_H; j++)
        {
473
            // std::cout << "i,j -->" << i << "," << j << std::endl;
474
475
476
477
478
479
480
481
            if(H(i,j) != 0)
            {
                q_row.push_back(i);
                q_col.push_back(j);

                if(i == j)
                {
                    q_val.push_back(H(i,j));
482
                    // std::cout << "H(i,j)" << H(i,j) << endl;
483
484
485
486
                }
                else
                {
                    q_val.push_back(2*H(i,j));
487
                    // std::cout << "2H(i,j)" << 2*H(i,j) << endl;
488
489
490
491
492
                }
            }
        }
        l_obj_coeff.push_back(F(i));
    }
493
494
495



496
    int N_vars = size_H;
497
    int N_q_coeffs = q_val.size();
498

499
    // BEGINNING C INTERFACE:
500

501
502
503
504
505
506
507
508
509
510
511
    GRBenv   *env   = NULL;
    GRBmodel *model = NULL;
    int       error = 0;
    double    sol[N_vars];
    int       ind[N_vars];
    double    val[N_vars];
    int*       qrow = q_row.data();
    int*       qcol = q_col.data();
    double*    qval = q_val.data();
    int       optimstatus;
    double    objval;
512

513
514
    std::vector<double> ub(N_vars, GRB_INFINITY);
    std::vector<double> lb(N_vars, -GRB_INFINITY);
515

roangel's avatar
roangel committed
516
517
518
    std::vector<int> l_ind;
    std::vector<double> l_coeff;

519
520
521
522
523
524
525
526
    int quad_row[2];
    int quad_col[2];
    double quad_coeff[2];

    int N_horizon = size_H/N_u;



roangel's avatar
roangel committed
527

528
529
530
    /* Create environment */
    error = GRBloadenv(&env, "qp.log");
    if (error) goto QUIT;
531

532
    /* Create a model */
533
534
    error = GRBnewmodel(env, &model, "qp", N_vars, l_obj_coeff.data(),lb.data(), ub.data(), NULL, NULL);
    if (error) goto QUIT;
535

536
    /* Quadratic objective terms */
537

538
539
    error = GRBaddqpterms(model, N_q_coeffs, qrow, qcol, qval);
    if (error) goto QUIT;
540

541
542
543
    error = GRBsetintparam(GRBgetenv(model), "OutputFlag", 0);
    if (error) goto QUIT;

roangel's avatar
roangel committed
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
    for(int i = 0; i < rows_A; i++)
    {
        l_ind.clear();
        l_coeff.clear();
        for(int j = 0; j < cols_A; j++)
        {
            if(A(i,j) != 0)
            {
                l_ind.push_back(j);
                l_coeff.push_back(A(i,j));
            }
        }
        error = GRBaddconstr(model, l_ind.size(), l_ind.data(), l_coeff.data(), GRB_LESS_EQUAL, b(i), NULL);
        if (error) goto QUIT;
    }

560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578


    // Quadratic constraints.

    for(int i = 0; i < N_horizon; i++)
    {
        quad_row[0] = N_u*i;
        quad_col[0] = N_u*i;
        quad_row[1] = N_u*i + 1;
        quad_col[1] = N_u*i + 1;
        quad_coeff[0] = 1/(af*af);
        quad_coeff[1] = 1/(af*af);

        error = GRBaddqconstr(model, 0, NULL, NULL, 2, quad_row, quad_col, quad_coeff,
                        GRB_LESS_EQUAL, 1.0, NULL);
        if (error) goto QUIT;
    }


579
    // Optimize model
580

581
582
    error = GRBoptimize(model);
    if (error) goto QUIT;
583

584
585
586
    /* Write model to 'qp.lp' */
    error = GRBwrite(model, "qp.lp");
    if (error) goto QUIT;
587

588
589
590
    /* Capture solution information */
    error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
    if (error) goto QUIT;
591

592
593
    error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
    if (error) goto QUIT;
594

595
596
    error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, N_vars, sol);
    if (error) goto QUIT;
597

598
    // printf("\nOptimization complete\n");
599
    if (optimstatus == GRB_OPTIMAL) {
600
        // printf("Optimal objective: %.4e\n", objval);
601
602
603
604
        // for(int i = 0; i < N_vars; i++)
        // {
        //     printf("sol[i] = %.4f\n", sol[i]);
        // }
605
606
607
608
609
    } else if (optimstatus == GRB_INF_OR_UNBD) {
        printf("Model is infeasible or unbounded\n");
    } else {
        printf("Optimization was stopped early\n");
    }
610
611


612
QUIT:
613

614
    /* Error reporting */
615

616
617
618
619
    if (error) {
        printf("ERROR: %s\n", GRBgeterrormsg(env));
        exit(1);
    }
620

621
    /* Free model */
622

623
624
625
626
627
    GRBfreemodel(model);

    /* Free environment */

    GRBfreeenv(env);
628

629
    // END C INTERFACE
630

631
    Map<VectorXd> U_0(sol,N_vars);
632
    // Eigen::IOFormat CleanFmt(4, 0, ", ", "\n", "[", "]");
633
    // cout << "The mapped vector U_0 is: \n" << U_0.format(CleanFmt) << "\n";
634
    return U_0;
635
}
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786

VectorXd solve_QP(Eigen::MatrixXd H, Eigen::MatrixXd F, Eigen::MatrixXd A, Eigen::VectorXd b)
{
    // H is assumed to be symmetric. There is NO 0.5 factor anywhere, with this we solve:
    // min(x'Hx + F'x)

    int size_H = H.cols();
    int cols_A = A.cols();
    int rows_A = A.rows();

    std::vector<int> q_row;
    std::vector<int> q_col;
    std::vector<double> q_val;
    std::vector<double> l_obj_coeff;

    for(int i = 0; i < size_H; i++)
    {
        for(int j = i; j < size_H; j++)
        {
            // std::cout << "i,j -->" << i << "," << j << std::endl;
            if(H(i,j) != 0)
            {
                q_row.push_back(i);
                q_col.push_back(j);

                if(i == j)
                {
                    q_val.push_back(H(i,j));
                    // std::cout << "H(i,j)" << H(i,j) << endl;
                }
                else
                {
                    q_val.push_back(2*H(i,j));
                    // std::cout << "2H(i,j)" << 2*H(i,j) << endl;
                }
            }
        }
        l_obj_coeff.push_back(F(i));
    }



    int N_vars = size_H;
    int N_q_coeffs = q_val.size();

    // BEGINNING C INTERFACE:

    GRBenv   *env   = NULL;
    GRBmodel *model = NULL;
    int       error = 0;
    double    sol[N_vars];
    int       ind[N_vars];
    double    val[N_vars];
    int*       qrow = q_row.data();
    int*       qcol = q_col.data();
    double*    qval = q_val.data();
    int       optimstatus;
    double    objval;

    std::vector<double> ub(N_vars, GRB_INFINITY);
    std::vector<double> lb(N_vars, -GRB_INFINITY);

    std::vector<int> l_ind;
    std::vector<double> l_coeff;


    /* Create environment */
    error = GRBloadenv(&env, "qp.log");
    if (error) goto QUIT;

    /* Create a model */
    error = GRBnewmodel(env, &model, "qp", N_vars, l_obj_coeff.data(),lb.data(), ub.data(), NULL, NULL);
    if (error) goto QUIT;

    /* Quadratic objective terms */

    error = GRBaddqpterms(model, N_q_coeffs, qrow, qcol, qval);
    if (error) goto QUIT;

    error = GRBsetintparam(GRBgetenv(model), "OutputFlag", 0);
    if (error) goto QUIT;

    for(int i = 0; i < rows_A; i++)
    {
        l_ind.clear();
        l_coeff.clear();
        for(int j = 0; j < cols_A; j++)
        {
            if(A(i,j) != 0)
            {
                l_ind.push_back(j);
                l_coeff.push_back(A(i,j));
            }
        }
        error = GRBaddconstr(model, l_ind.size(), l_ind.data(), l_coeff.data(), GRB_LESS_EQUAL, b(i), NULL);
        if (error) goto QUIT;
    }

    // Optimize model

    error = GRBoptimize(model);
    if (error) goto QUIT;

    /* Write model to 'qp.lp' */
    error = GRBwrite(model, "qp.lp");
    if (error) goto QUIT;

    /* Capture solution information */
    error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
    if (error) goto QUIT;

    error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
    if (error) goto QUIT;

    error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, N_vars, sol);
    if (error) goto QUIT;

    // printf("\nOptimization complete\n");
    if (optimstatus == GRB_OPTIMAL) {
        // printf("Optimal objective: %.4e\n", objval);
        // for(int i = 0; i < N_vars; i++)
        // {
        //     printf("sol[i] = %.4f\n", sol[i]);
        // }
    } else if (optimstatus == GRB_INF_OR_UNBD) {
        printf("Model is infeasible or unbounded\n");
    } else {
        printf("Optimization was stopped early\n");
    }


QUIT:

    /* Error reporting */

    if (error) {
        printf("ERROR: %s\n", GRBgeterrormsg(env));
        exit(1);
    }

    /* Free model */

    GRBfreemodel(model);

    /* Free environment */

    GRBfreeenv(env);

    // END C INTERFACE

    // Eigen::IOFormat CleanFmt(4, 0, ", ", "\n", "[", "]");
787
    Map<VectorXd> U_0(sol,N_vars);
788
789
790
791
    // cout << "The mapped vector U_0 is: \n" << U_0.format(CleanFmt) << "\n";
    return U_0;
}

792
793


794
795
796
797
798
799
800
801
802
803
804
805
VectorXd solve_QP(Eigen::MatrixXd H, Eigen::MatrixXd F)
{
    // H is assumed to be symmetric. There is NO 0.5 factor anywhere, with this we solve:
    // min(x'Hx + F'x)

    int size_H = H.cols();

    std::vector<int> q_row;
    std::vector<int> q_col;
    std::vector<double> q_val;
    std::vector<double> l_obj_coeff;

806
    for(int i = 0; i < size_H; i++)
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
    {
        for(int j = i; j < size_H; j++)
        {
            // std::cout << "i,j -->" << i << "," << j << std::endl;
            if(H(i,j) != 0)
            {
                q_row.push_back(i);
                q_col.push_back(j);

                if(i == j)
                {
                    q_val.push_back(H(i,j));
                    // std::cout << "H(i,j)" << H(i,j) << endl;
                }
                else
                {
                    q_val.push_back(2*H(i,j));
                    // std::cout << "2H(i,j)" << 2*H(i,j) << endl;
                }
            }
        }
        l_obj_coeff.push_back(F(i));
    }


832
833
834
835

    int N_vars = size_H;
    int N_q_coeffs = q_val.size();

836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
    // BEGINNING C INTERFACE:

    GRBenv   *env   = NULL;
    GRBmodel *model = NULL;
    int       error = 0;
    double    sol[N_vars];
    int       ind[N_vars];
    double    val[N_vars];
    int*       qrow = q_row.data();
    int*       qcol = q_col.data();
    double*    qval = q_val.data();
    int       optimstatus;
    double    objval;

    std::vector<double> ub(N_vars, GRB_INFINITY);
    std::vector<double> lb(N_vars, -GRB_INFINITY);

    /* Create environment */
    error = GRBloadenv(&env, "qp.log");
    if (error) goto QUIT;

    /* Create a model */
    error = GRBnewmodel(env, &model, "qp", N_vars, l_obj_coeff.data(),lb.data(), ub.data(), NULL, NULL);
    if (error) goto QUIT;

    /* Quadratic objective terms */

    error = GRBaddqpterms(model, N_q_coeffs, qrow, qcol, qval);
    if (error) goto QUIT;

    error = GRBsetintparam(GRBgetenv(model), "OutputFlag", 0);
    if (error) goto QUIT;

    // Optimize model

    error = GRBoptimize(model);
    if (error) goto QUIT;

    /* Write model to 'qp.lp' */
    error = GRBwrite(model, "qp.lp");
    if (error) goto QUIT;

    /* Capture solution information */
    error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
    if (error) goto QUIT;

    error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
    if (error) goto QUIT;

    error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, N_vars, sol);
    if (error) goto QUIT;

    // printf("\nOptimization complete\n");
    if (optimstatus == GRB_OPTIMAL) {
        // printf("Optimal objective: %.4e\n", objval);
        // for(int i = 0; i < N_vars; i++)
        // {
        //     printf("sol[i] = %.4f\n", sol[i]);
        // }
    } else if (optimstatus == GRB_INF_OR_UNBD) {
        printf("Model is infeasible or unbounded\n");
    } else {
        printf("Optimization was stopped early\n");
    }


QUIT:

    /* Error reporting */

    if (error) {
        printf("ERROR: %s\n", GRBgeterrormsg(env));
        exit(1);
    }

    /* Free model */

    GRBfreemodel(model);

    /* Free environment */

    GRBfreeenv(env);

    // END C INTERFACE

    // Eigen::IOFormat CleanFmt(4, 0, ", ", "\n", "[", "]");
922
    Map<VectorXd> U_0(sol,N_vars);
923
924
925
926
    // cout << "The mapped vector U_0 is: \n" << U_0.format(CleanFmt) << "\n";
    return U_0;
}

927