-
Notifications
You must be signed in to change notification settings - Fork 0
/
Example3_ASAi_Rev.cpp
1132 lines (822 loc) · 33.2 KB
/
Example3_ASAi_Rev.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
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
832
833
834
835
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -----------------------------------------------------------------
* Last Modified by Yulan Zhang
* 2023/04/27
* Example 5 for CACE paper
* Adjoint subgradient evaluation system with reverse-mode subgradient AD
* -----------------------------------------------------------------*/
/* Include header files for both MC++ and CVODES*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <chrono>
#include <cvodes/cvodes.h> /* prototypes for CVODE fcts., consts. */
#include <nvector/nvector_serial.h> /* access to serial N_Vector */
#include <sunmatrix/sunmatrix_dense.h> /* access to dense SUNMatrix */
#include <sunlinsol/sunlinsol_dense.h> /* access to dense SUNLinearSolver */
#include <sundials/sundials_types.h> /* defs. of realtype, sunindextype */
#include <sundials/sundials_math.h> /* definition of ABS */
#include <iostream>
#include <fstream>
#include "interval.hpp"
#include "mccormick.hpp"
#include "reverseMC3.hpp"
using namespace std;
/* Accessor macros */
#define Ith(v,i) NV_Ith_S(v,i-1) /* i-th vector component i=1..NEQ */
#define IJth(A,i,j) SM_ELEMENT_D(A,i-1,j-1) /* (i,j)-th matrix component i,j=1..NEQ */
/* Problem Constants */
#define RTOL RCONST(1e-7) /* scalar relative tolerance */
#define ATOL RCONST(1e-7) /* vector absolute tolerance components */
#define ATOLl RCONST(1e-9) /* absolute tolerance for adjoint vars. */
#define ATOLq RCONST(1e-9) /* absolute tolerance for quadratures */
#define T0 RCONST(0.0) /* initial time */
#define TOUT RCONST(2.0) /* final time */
#define TB1 RCONST(2.0) /* starting point for adjoint problem */
#define STEPS 150 /* number of steps between check points */
#define NP 8 /* number of problem parameters */
#define NX 5 /* number of state variables */
#define NS 2*NP /* number of subgradient of each yi */
#define NEQ NX + NX*4 /* number of equations: original solution, state relaxation, subgradient */
#define ZERO RCONST(0.0)
#define xi 4
#define Xi 10
/* Type : UserData */
/* problem parameters */
typedef mc::Interval I;
typedef mc::McCormick<I> MC;
/* define the values of parameters */
double pL[NP] = { 22.14, 80, 238, 30.6, 313.6, 423, 4.28, 0.84 }; /* lower bound of parameters*/
double pU[NP] = { 62.14, 146.5, 298, 70.6, 373.6, 483, 14.28, 1.16 };/* upper bound of parameters */
double fixedp[NP] = { 42.14,116.5,268,50.6,343.6,450, 10.78, 1.0}; /* fixed value of parameters*/
typedef struct {
I pI[NP];
realtype p[NP];
} *UserData;
/* Prototypes of functions by CVODES */
template <typename T, typename U> T Original_RHS(T x[NX], U p[NP], int n);
template <typename T> T Original_initial(T p[NP], int n);
static N_Vector x_initial(N_Vector x, void* user_data);
static int f(realtype t, N_Vector x_Re, N_Vector dx_Re, void* user_data);
static int fB(realtype t, N_Vector x, N_Vector xB, N_Vector xBdot, void* user_dataB);
static int fQB(realtype t, N_Vector x, N_Vector xB, N_Vector qBdot, void* user_dataB);
static N_Vector S_initial(N_Vector xB, N_Vector S_init,void* user_data);
static int ewt(N_Vector x_Re, N_Vector w, void* user_data);
/* Prototypes of private functions */
static void PrintHead(realtype tB0);
static void PrintOutput(realtype tfinal, N_Vector x, N_Vector xB, N_Vector qB, N_Vector S_0);
static void PrintOutput1(realtype time, realtype t, N_Vector x);
static void PrintOutput2(void* cvode_mem, realtype t, N_Vector u);
static int check_retval(void* returnvalue, const char* funcname, int opt);
/*
*--------------------------------------------------------------------
* MAIN PROGRAM
*--------------------------------------------------------------------
*/
int main()
{
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::duration<float> fsec;
auto tstart = Time::now();
SUNContext sunctx;
SUNMatrix A, AB;
SUNLinearSolver LS, LSB;
void* cvode_mem;
UserData data;
long int nst, nstB;
realtype time;
N_Vector x;
N_Vector xB, qB;
N_Vector S0;
int retval, ncheck;
int steps;
int indexB;
MC pMC[NP];
CVadjCheckPointRec* ckpnt;
realtype reltolQ, abstolQ;
realtype reltolB, abstolB, abstolQB;
data = NULL;
A = AB = NULL;
LS = LSB = NULL;
cvode_mem = NULL;
ckpnt = NULL;
x = xB = qB = NULL;
S0 = NULL;
/* Initialize user data structure sclar p and interval PI*/
data = (UserData)malloc(sizeof * data);
if (check_retval((void*)data, "malloc", 2)) return(1);
for (int j = 0; j < NP; j++) {
data->p[j] = fixedp[j];
data->pI[j] = I(pL[j], pU[j]);
}
/* Create the SUNDIALS context that all SUNDIALS objects require */
retval = SUNContext_Create(NULL, &sunctx);
if (check_retval(&retval, "SUNContext_Create", 1)) return(1);
/* Initialize state variables */
x = N_VNew_Serial(NEQ,sunctx);
if (check_retval((void*)x, "N_VNew_Serial", 0)) return(1);
x = x_initial(x, data);
/* Set the scalar relative and absolute tolerances reltolQ and abstolQ */
reltolQ = RTOL;
abstolQ = ATOLq;
/* Create and allocate CVODES memory for forward run */
printf("Create and allocate CVODES memory for forward runs\n");
/* Call CVodeCreate to create the solver memory and specify the
Backward Differentiation Formula */
cvode_mem = CVodeCreate(CV_BDF,sunctx);
if (check_retval((void*)cvode_mem, "CVodeCreate", 0)) return(1);
/* Call CVodeInit to initialize the integrator memory and specify the
user's right-hand side function in y'=f(t,y), the initial time T0, and
the initial dependent variable vector y. */
//// The first bug, failing to allocate memory.
//// Solution: check the dimensional of y and dy
retval = CVodeInit(cvode_mem, f, T0, x);
if (check_retval(&retval, "CVodeInit", 1)) return(1);
/* Call CVodeWFtolerances to specify a user-supplied function ewt that sets
the multiplicative error weights w_i for use in the weighted RMS norm */
retval = CVodeWFtolerances(cvode_mem, ewt);
if (check_retval(&retval, "CVodeSetEwtFn", 1)) return(1);
/* Attach user data */
retval = CVodeSetUserData(cvode_mem, data);
if (check_retval(&retval, "CVodeSetUserData", 1)) return(1);
/* Create dense SUNMatrix */
A = SUNDenseMatrix(NEQ, NEQ,sunctx);
if (check_retval((void*)A, "SUNDenseMatrix", 0)) return(1);
/* Create dense SUNLinearSolver */
LS = SUNLinSol_Dense(x, A,sunctx);
if (check_retval((void*)LS, "SUNLinSol_Dense", 0)) return(1);
/* Attach the matrix and linear solver */
retval = CVodeSetLinearSolver(cvode_mem, LS, A);
if (check_retval(&retval, "CVodeSetLinearSolver", 1)) return(1);
/* Set the maximum number of step size */
retval = CVodeSetMaxNumSteps(cvode_mem, 2000);
if (check_retval(&retval, "CVodeSetMaxNumSteps", 1)) return(1);
/* Allocate global memory */
/* Call CVodeAdjInit to update CVODES memory block by allocting the internal
memory needed for backward integration.*/
steps = STEPS; /* no. of integration steps between two consecutive ckeckpoints*/
retval = CVodeAdjInit(cvode_mem, steps, CV_HERMITE);
/*
retval = CVodeAdjInit(cvode_mem, steps, CV_POLYNOMIAL);
*/
if (check_retval(&retval, "CVodeAdjInit", 1)) return(1);
/* Perform forward run */
printf("Forward integration ... ");
/* Call CVodeF to integrate the forward problem over an interval in time and
saves checkpointing data */
retval = CVodeF(cvode_mem, TOUT, x, &time, CV_NORMAL, &ncheck);
if (check_retval(&retval, "CVodeF", 1)) return(1);
//retval = CVodeF(cvode_mem, TOUT, y, &time, CV_ONE_STEP, &ncheck);
//if (check_retval(&retval, "CVodeF", 1)) return(1);
retval = CVodeGetNumSteps(cvode_mem, &nst);
if (check_retval(&retval, "CVodeGetNumSteps", 1)) return(1);
printf("done ( nst = %ld )\n", nst);
printf("\nncheck = %d\n\n", ncheck); // (int)the number of(internal) checkpoints stored so far.
printf("-------------------------------------------------\n\n");
// Print the solutions of forward sensitivity analysis
// This could be compared to the results obtained by running Example1.cpp
printf("Solutions to forward sensitivity analysis\n");
std::cout << "p7: " << fixedp[6] << std::endl;
printf("===========================================");
printf("============================\n");
printf(" T Q H NST x\n");
printf("===========================================");
printf("============================\n");
PrintOutput2(cvode_mem, time, x);
/* Initialize xB */
/* xB = dg/dx_Re for i = 1,..,NX at T*/
/* where x_Re = xicv, xicc*/
xB = N_VNew_Serial(2 * NX,sunctx);
if (check_retval((void*)xB, "N_VNew_Serial", 0)) return(1);
for (int i = 0; i < 2 * NX; i++) {
Ith(xB, i + 1) = ZERO;
}
/* Define function g*/
/* In this case, g is set to x5^cv*/
Ith(xB, Xi) = RCONST(1.0);
/* Initialize qB */
/* qB = 0 at T */
qB = N_VNew_Serial(NP,sunctx);
if (check_retval((void*)qB, "N_VNew", 0)) return(1);
for (int i = 0; i < NP; i++) {
Ith(qB, i + 1) = ZERO;
}
/* Set the scalar relative tolerance reltolB */
reltolB = RTOL;
/* Set the scalar absolute tolerance abstolB */
abstolB = ATOLl;
/* Set the scalar absolute tolerance abstolQB */
abstolQB = ATOLq;
/* Create and allocate CVODES memory for backward run */
printf("-------------------------------------------------\n");
printf("Create and allocate CVODES memory for backward run\n");
/* Call CVodeCreateB to specify the solution method for the backward
problem. */
retval = CVodeCreateB(cvode_mem, CV_BDF, &indexB);
if (check_retval(&retval, "CVodeCreateB", 1)) return(1);
/* Call CVodeInitB to allocate internal memory and initialize the
backward problem. */
retval = CVodeInitB(cvode_mem, indexB, fB, TB1, xB);
if (check_retval(&retval, "CVodeInitB", 1)) return(1);
/* Set the scalar relative and absolute tolerances. */
retval = CVodeSStolerancesB(cvode_mem, indexB, reltolB, abstolB);
if (check_retval(&retval, "CVodeSStolerancesB", 1)) return(1);
/* Attach the user data for backward problem. */
retval = CVodeSetUserDataB(cvode_mem, indexB, data);
if (check_retval(&retval, "CVodeSetUserDataB", 1)) return(1);
/* Create dense SUNMatrix for use in linear solves */
// Dimension of AB is set to (2*NY, 2*NY)
AB = SUNDenseMatrix(2 * NX, 2 * NX,sunctx);
if (check_retval((void*)AB, "SUNDenseMatrix", 0)) return(1);
/* Create dense SUNLinearSolver object */
LSB = SUNLinSol_Dense(xB, AB,sunctx);
if (check_retval((void*)LSB, "SUNLinSol_Dense", 0)) return(1);
/* Attach the matrix and linear solver */
retval = CVodeSetLinearSolverB(cvode_mem, indexB, LSB, AB);
if (check_retval(&retval, "CVodeSetLinearSolverB", 1)) return(1);
/* Call CVodeQuadInitB to allocate internal memory and initialize backward
quadrature integration. */
retval = CVodeQuadInitB(cvode_mem, indexB, fQB, qB);
if (check_retval(&retval, "CVodeQuadInitB", 1)) return(1);
/* Call CVodeSetQuadErrCon to specify whether or not the quadrature variables
are to be used in the step size control mechanism within CVODES. Call
CVodeQuadSStolerances or CVodeQuadSVtolerances to specify the integration
tolerances for the quadrature variables. */
retval = CVodeSetQuadErrConB(cvode_mem, indexB, SUNTRUE);
if (check_retval(&retval, "CVodeSetQuadErrConB", 1)) return(1);
/* Call CVodeQuadSStolerancesB to specify the scalar relative and absolute tolerances
for the backward problem. */
retval = CVodeQuadSStolerancesB(cvode_mem, indexB, reltolB, abstolQB);
if (check_retval(&retval, "CVodeQuadSStolerancesB", 1)) return(1);
/* Backward Integration */
PrintHead(TB1);
/* Then get results at t = T0*/
//retval = CVodeB(cvode_mem, T0, CV_NORMAL);
//if (check_retval(&retval, "CVodeB", 1)) return(1);
retval = CVodeB(cvode_mem, T0, CV_NORMAL);
if (check_retval(&retval, "CVodeB", 1)) return(1);
CVodeGetNumSteps(CVodeGetAdjCVodeBmem(cvode_mem, indexB), &nstB);
printf("Done ( nst = %ld )\n", nstB);
retval = CVodeGetB(cvode_mem, indexB, &time, xB);
if (check_retval(&retval, "CVodeGetB", 1)) return(1);
/* Call CVodeGetQuadB to get the quadrature solution vector after a
successful return from CVodeB. */
retval = CVodeGetQuadB(cvode_mem, indexB, &time, qB);
if (check_retval(&retval, "CVodeGetQuadB", 1)) return(1);
retval = CVodeGetAdjY(cvode_mem, T0, x);
if (check_retval(&retval, "CVodeGetAdjY", 1)) return(1);
/* Initialize state variables */
S0 = N_VNew_Serial(NP, sunctx);
if (check_retval((void*)S0, "N_VNew_Serial", 0)) return(1);
S0 = S_initial(xB,S0,data);
PrintOutput(time, x, xB, qB,S0);
/* Free memory */
printf("Free memory\n\n");
CVodeFree(&cvode_mem);
N_VDestroy(x);
N_VDestroy(xB);
N_VDestroy(qB);
SUNLinSolFree(LS);
SUNMatDestroy(A);
SUNLinSolFree(LSB);
SUNMatDestroy(AB);
SUNContext_Free(&sunctx); /* Free the SUNDIALS context */
if (ckpnt != NULL) free(ckpnt);
free(data);
auto tend = Time::now();
fsec s_float = tend - tstart;
std::cout<< s_float.count() <<"s\n";
return(0);
}
/*
*--------------------------------------------------------------------
* FUNCTIONS CALLED BY CVODES
*--------------------------------------------------------------------
*/
/*
* Initial conditions for user-supplied ODE.
* Set initial values for original solution, state bounds and state relaxations, denoted as vector x,
*/
template <typename T> T Original_initial(T p[NP], int n)
{
T x0;
/* Size of n depends on the number of functions in user-supplied ODE system*/
switch (n)
{
case 0:
x0 = 0.5 + 0 * p[0];
break;
case 1:
x0 = p[7];
break;
case 2:
x0 = 1 + 0 * p[0];
break;
case 3:
x0 = 5 + 0 * p[0];
break;
case 4:
x0 = 40 + 0 * p[0];
break;
}
return x0;
}
/*
* Set initial conditions for an auxiliary system which solves original ODE solutions,
* along with convex/concave relaxations.
*/
static N_Vector x_initial(N_Vector x, void* user_data)
{
MC x0MC[NX], pMC[NP];
realtype p[NP], x0Aug[NX];
UserData data;
data = (UserData)user_data;
/* Assign values to p and MC pMC*/
for (int j = 0; j < NP; j++) {
p[j] = data->p[j];
pMC[j] = MC(I(pL[j], pU[j]), p[j]);
}
/* Initial conditions for ODE system*/
for (int j = 0; j < NX; j++) {
x0Aug[j] = Original_initial(p, j);
x0MC[j] = Original_initial(pMC, j);
}
/* Construct x vector*/
//x = N_VNew_Serial(NEQ);
for (int j = 0; j < NX; j++) {
Ith(x, j + 1 + 0 * NX) = x0Aug[j];
Ith(x, j + 1 + 1 * NX) = x0MC[j].l();
Ith(x, j + 1 + 2 * NX) = x0MC[j].u();
Ith(x, j + 1 + 3 * NX) = x0MC[j].cv();
Ith(x, j + 1 + 4 * NX) = x0MC[j].cc();
}
return x;
}
/*
* f routine, which is the original right-hand side function returning the interval or McCormick.
*/
template <typename T, typename U> T Original_RHS(T x[NX], U p[NP], int n)
{
T f_rhs;
T mu[2], phi, q;
mu[0] = 1.2 * (1 / (1 + 7.1 * (1 / x[2])));
mu[1] = 0.74 *(1 / (1 + p[6]* (1 / x[3]) + x[3]*(1 / 256)));
phi = x[4] + x[3] - 34 + p[5]* (1 / 19.8) * mu[1] * x[1];
q = 19.8 *(x[4] + x[3] - 50 - 0.5 * phi);
/* Size of n depends on the number of functions in your ODEs*/
switch (n)
{
case 0:
f_rhs = (mu[0] - 0.2) * x[0];
break;
case 1:
f_rhs = (mu[1] - 0.2) * x[1];
break;
case 2:
f_rhs = 0.4 * (5 - x[2]) - p[0] * mu[0] * x[0];
break;
case 3:
f_rhs = 0.4 * (80 - x[3]) + p[1] * mu[0] * x[0] - p[2] * mu[1] * x[1];
break;
case 4:
f_rhs = -0.4 * x[4] - q + p[3] * mu[0] * x[0] + p[4] * mu[1] * x[1];
break;
}
return f_rhs;
}
/*
* RHS of the auxiliary ODE system which solves original ODE solutions,
* along with convex/concave relaxations.
* This ode is solved in a forward mode.
*/
static int f(realtype t, N_Vector x, N_Vector dx, void* user_data)
{
MC pMC[NP], xMC[NX];
I pI[NP], xI[NX];
realtype dxL[NX], dxU[NX], dxcv[NX], dxcc[NX];
realtype xL[NX], xU[NX], xcv[NX], xcc[NX];
realtype p[NP];
realtype xori[NX], xd[NX];
UserData data;
data = (UserData)user_data;
/* Assign values to p, interval pI, McCormick pMC */
for (int j = 0; j < NP; j++) {
p[j] = data->p[j];
pI[j] = I(pL[j], pU[j]);
pMC[j] = MC(I(pL[j], pU[j]), p[j]);
}
/* Generate x_ori, xL, xU, xcv and xcc arrays using values from vector x*/
for (int j = 0; j < NX; j++) {
xori[j] = Ith(x, j + 1 + 0 * NX);
xL[j] = Ith(x, j + 1 + 1 * NX);
xU[j] = Ith(x, j + 1 + 2 * NX);
xcv[j] = Ith(x, j + 1 + 3 * NX);
xcc[j] = Ith(x, j + 1 + 4 * NX);
}
/* Initialize interval xI, McCormick xMC */
for (int j = 0; j < NX; j++) {
xI[j] = I(xL[j], xU[j]);
xMC[j] = MC(I(xL[j], xU[j]), xcv[j], xcc[j]);
}
/* Computation for RHS of the auxiliary ODEs*/
for (int j = 0; j < NX; j++) {
/*-------------------------------------------------------------*/
/*-------------------------------------------------------------*/
/* Construct the original ODE system's RHS */
xd[j] = Original_RHS(xori, p, j);
/*-------------------------------------------------------------*/
/*-------------------------------------------------------------*/
/* Construct the state bounds computation system's RHS */
/* Flatten the ith interval xI (xiL, xiU) to (xiL, xiL)*/
xI[j] = I(xL[j], xL[j]);
/* Apply the flattened xI into the original RHS function, then obtain the lower bound */
dxL[j] = Original_RHS(xI, pI, j).l();
/* Flatten the ith interval xI (xiL, xiU) to (xiU, xiU)*/
xI[j] = I(xU[j], xU[j]);
/* Apply the flattened xI into the original RHS function, then obtain the upper bound */
dxU[j] = Original_RHS(xI, pI, j).u();
/* Unflatten the ith interval*/
xI[j] = I(xL[j], xU[j]);
/*-------------------------------------------------------------*/
/*-------------------------------------------------------------*/
/* Construct the state relaxations computation system's RHS */
/* Flatten the ith xMC (xiL,xiU,xicv,xicc) to (xiL,xiU,xicv,xicv)*/
xMC[j] = MC(I(xL[j], xU[j]), xcv[j], xcv[j]);
/* Apply the flattened xMC into original RHS function,
then obtain the convex relaxation */
dxcv[j] = Original_RHS(xMC, pMC, j).cv();
/* Flatten the ith xMC (xiL,xiU,xicv,xicc) to (xiL,xiU,xicc,xicc)*/
xMC[j] = MC(I(xL[j], xU[j]), xcc[j], xcc[j]);
/* Apply the flattened xMC into the original RHS function,
then obtain the concave relaxation */
dxcc[j] = Original_RHS(xMC, pMC, j).cc();
/* Unflatten the ith xMC*/
xMC[j] = MC(I(xL[j], xU[j]), xcv[j], xcc[j]);
/*-------------------------------------------------------------*/
/*-------------------------------------------------------------*/
/* Construct dx vextor*/
Ith(dx, j + 1 + 0 * NX) = xd[j];
Ith(dx, j + 1 + 1 * NX) = dxL[j];
Ith(dx, j + 1 + 2 * NX) = dxU[j];
Ith(dx, j + 1 + 3 * NX) = dxcv[j];
Ith(dx, j + 1 + 4 * NX) = dxcc[j];
}
return(0);
}
/*
* EwtSet function. Computes the error weights at the current solution.
*/
static int ewt(N_Vector x, N_Vector w, void* user_data)
{
int i;
realtype xx, ww, rtol, atol[NEQ];
rtol = RTOL;
for (int j = 0; j < NEQ; j++) {
atol[j] = ATOL;
}
for (i = 1; i <= NEQ; i++) {
xx = Ith(x, i);
ww = rtol * SUNRabs(xx) + atol[i - 1];
if (ww <= 0.0) return (-1);
Ith(w, i) = 1.0 / ww;
}
return(0);
}
/*
* fB routine. Compute fB(t,x,xB).
* fB is the RHS function for the ODE system which solves lambda.
* fB = -lambda^T * df/dx
*/
static int fB(realtype t, N_Vector x, N_Vector xB, N_Vector xBdot, void* user_dataB)
{
SUNContext sunctx;
SUNContext_Create(NULL, &sunctx);
UserData data;
data = (UserData)user_dataB;
realtype p[NP], xcv[NX], xcc[NX], xL[NX], xU[NX];
MC xMCsub[NX], pMCsub[NP];
realtype l[2 * NX];
double tempsub[2 * NX * 2 * NX];
/* Assign values to p, and MC pMCsub (for subgradient evaluations) */
/* Initialize subgradients for pMCsub with respect to relaxed x*/
/* Since p are not functions of x, dp/dx should be equal to 0
and the dimension of dp/dx should be the same as df/dx*/
for (int j = 0; j < NP; j++) {
p[j] = data->p[j];
pMCsub[j] = MC(I(pL[j], pU[j]), p[j]);
pMCsub[j].sub(NRev);
}
//Debug: CVODE fails to coverage
//Solution: Check the index of the vector defined by CVODES
//Vector or Matrix defined by CVODES must start from 1 instead of 0
/* Initialize vector lambda with size of 2*NX */
for (int j = 0; j < 2 * NX; j++) {
l[j] = Ith(xB, j + 1);
}
/* Collect xL, xU, xcv, xcc values from vector x */
for (int j = 0; j < NX; j++) {
xL[j] = Ith(x, j + 1 + 1 * NX);
xU[j] = Ith(x, j + 1 + 2 * NX);
xcv[j] = Ith(x, j + 1 + 3 * NX);
xcc[j] = Ith(x, j + 1 + 4 * NX);
}
/* Initialize McCormick xMCsub */
for (int j = 0; j < NX; j++)
{
xMCsub[j] = MC(I(xL[j], xU[j]), xcv[j], xcc[j]);
xMCsub[j].sub(NRev);
}
/* Initialize subgradients for xMCsub with 1 or 0 */
double ini_sub[NRev * NRev] = {1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};
/*-------------------------------------------------------------*/
/*-------------------------------------------------------------*/
/* Derivatives (df/dx) computation*/
/* Debug: Flatten the convex and concave relaxations*/
for (int j = 0; j < NX; j++) {
/* Flatten the ith xMCsub (xiL,xiU,xicv,xicc)
to (xiL,xiU,xicv,xicv)*/
xMCsub[j] = MC(I(xL[j], xU[j]), xcv[j], xcv[j]);
/* Apply the flattened xMCsub into fRevAD_dfdx function */
/* Compute the subgradients in reverse mode */
N_Vector adcvcc_flcv = N_VNew_Serial(4 * NX, sunctx);
adcvcc_flcv = fRevAD_dfdx(xMCsub, pMCsub, ini_sub, j, 0);
/* Flattening the ith xMCsub (xiL,xiU,xicv,xicc)
to (xiL,xiU,xicc,xicc)*/
xMCsub[j] = MC(I(xL[j], xU[j]), xcc[j], xcc[j]);
/* Apply the flattened the xMCsub into fRevAD_dfdx function */
/* Compute the subgradients in reverse mode */
N_Vector adcvcc_flcc = N_VNew_Serial(4 * NX,sunctx);
adcvcc_flcc = fRevAD_dfdx(xMCsub, pMCsub, ini_sub, j, 4);
/* Unflattening the ith xMCsub*/
xMCsub[j] = MC(I(xL[j], xU[j]), xcv[j], xcc[j]);
/* Storing values for constructing the rhs functions*/
for (int i = 0; i < 2 * NX; i++)
{
tempsub[2 * j * 2 * NX + i] = Ith(adcvcc_flcv, 1 + i);
tempsub[(2 * j + 1) * 2 * NX + i] = Ith(adcvcc_flcc, 2 * NX + 1 + i);
}
}
double tempxbdot[2 * NX];
for (int i = 0; i < 2 * NX; i++)
{
tempxbdot[i] = 0;
for (int j = 0; j < 2 * NX; j++)
{
tempxbdot[i] = tempxbdot[i] + tempsub[i + j * 2 * NX] * l[j];
}
Ith(xBdot, i + 1) = -tempxbdot[i];
}
SUNContext_Free(&sunctx); /* Free the SUNDIALS context */
return(0);
}
/*
* fQB routine. Compute integrand for quadratures
* fQB is the RHS function for the ODE system which is to compute integration of lambda^T*df/dp.
*/
static int fQB(realtype t, N_Vector x, N_Vector xB, N_Vector qBdot, void* user_dataB)
{
SUNContext sunctx;
SUNContext_Create(NULL, &sunctx);
N_Vector adcvcc_flcv;
N_Vector adcvcc_flcc;
UserData data;
data = (UserData)user_dataB;
realtype theta_B[2 * NX * NP];
realtype l[2 * NX];
MC pMCsub[NP], xMCsub[NX];
realtype p[NP];
realtype xL[NX], xU[NX], xcv[NX], xcc[NX];
/* Assign values to p, interval pI, and MC pMCsub (for subgradients evaluations)*/
for (int j = 0; j < NP; j++) {
p[j] = data->p[j];
pMCsub[j] = MC(I(pL[j], pU[j]), p[j]);
}
/* Initialize subgradeints for pMCsub with respect to p*/
double ini_sub[NRev * NRev] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };
/* Collect values from x */
for (int j = 0; j < NX; j++) {
xL[j] = Ith(x, j + 1 + 1 * NX);
xU[j] = Ith(x, j + 1 + 2 * NX);
xcv[j] = Ith(x, j + 1 + 3 * NX);
xcc[j] = Ith(x, j + 1 + 4 * NX);
}
/* Initialize McCormick xMCsub */
/* Initialize subgradients for xMCsub with respect to p*/
/* When calculating the partial derivatives df/dp, we do not consider dx/dp*/
/* Comments from Dr.Khan: I think it's NOT supposed to include the chain-rule-y dependence of x on p,
since that's included separately in the adjoint ODEs already.*/
for (int j = 0; j < NX; j++) {
xMCsub[j] = MC(I(xL[j], xU[j]), xcv[j], xcc[j]);
xMCsub[j].sub(NRev);
}
/*-------------------------------------------------------------*/
/*-------------------------------------------------------------*/
/* Derivatives (df/dp) computation*/
for (int j = 0; j < NX; j++) {
/* Flattening the ith xMCsub (xiL,xiU,xicv,xicc,xicvsub,xiccsub)
to (xiL,xiU,xicv,xicv,xicvsub,xicvsub)*/
xMCsub[j] = MC(I(xL[j], xU[j]), xcv[j], xcv[j]);
xMCsub[j].sub(NRev);
/* Apply the flattened xMCsub into fRevAD_dfdp function */
/* Compute the subgradients in reverse mode */
adcvcc_flcv = N_VNew_Serial(2 * NP,sunctx);
adcvcc_flcv = fRevAD_dfdp(xMCsub, pMCsub, ini_sub, j);
/* Flattening the ith xMCsub (xiL,xiU,xicv,xicc,xicvsub,xiccsub)
to (xiL,xiU,xicv,xicv,xicvsub,xicvsub)*/
xMCsub[j] = MC(I(xL[j], xU[j]), xcc[j], xcc[j]);
xMCsub[j].sub(NRev);
/* Apply the flattened xMCsub into fRevAD_dfdp function */
/* Compute the subgradients in reverse mode */
adcvcc_flcc = N_VNew_Serial(2 * NP,sunctx);
adcvcc_flcc = fRevAD_dfdp(xMCsub, pMCsub, ini_sub, j);
/* Unflattening the ith xMCsub*/
xMCsub[j] = MC(I(xL[j], xU[j]), xcv[j], xcc[j]);
xMCsub[j].sub(NRev);
/* Store the values to array theta_B*/
for (int i = 0; i < NP; i++)
{
theta_B[2 * j * NP + i] = Ith(adcvcc_flcv, i + 1);
theta_B[(2 * j + 1) * NP + i] = Ith(adcvcc_flcc, NP + i + 1);
}
}
/* Recall values to lambda calculated by fB */
for (int j = 0; j < 2 * NX; j++) {
l[j] = Ith(xB, j + 1);
}
/* Construct the rhs functions */
double tempqbdot[NP];
for (int i = 0; i < NP; i++)
{
tempqbdot[i] = 0;
for (int j = 0; j < 2 * NX; j++)
{
tempqbdot[i] = tempqbdot[i] + theta_B[i + j * NP] * l[j];
}
Ith(qBdot, i + 1) = tempqbdot[i];
}
return(0);
}
/*
* initial condition routine.
*/
static N_Vector S_initial(N_Vector xB, N_Vector S_init, void* user_data)
{
UserData data;
data = (UserData)user_data;
realtype S0[2 * NX * NP];
realtype l[2 * NX];
MC x0MC[NX], pMC[NP];
realtype p[NP];
/* Recall values to lambda calculated by fB */
for (int j = 0; j < 2 * NX; j++) {
l[j] = Ith(xB, j + 1);
}
/* Assign values to p and MC pMC*/
for (int j = 0; j < NP; j++) {
p[j] = data->p[j];
pMC[j] = MC(I(pL[j], pU[j]), p[j]);
}
/* Initialize subgradeints for pMC with respect to p themselves*/
// e.g. if NP = 2, cvsub_p1 = 1.0, 0.0, ccsub_p1 = 1.0, 0.0
double sub[NP * NP] = { 0 };
for (int j = 0; j < NP * NP; j++) {
for (int i = 0; i < NP; i++) {
if (j == i + i * NP) {
sub[j] = 1.0;
}
}
}
/* Set subgradients for pMC*/
for (int j = 0; j < NP; j++) {
pMC[j].sub(NP, &sub[j * NP], &sub[j * NP]);
}
/* Initial conditions for ODE system*/
for (int j = 0; j < NX; j++) {
x0MC[j] = Original_initial(pMC, j);
}
for (int j=0; j<NX; j++)
{
for (int i=0; i<NP;i++)
{
S0[2 * j * NP + i] = x0MC[j].cvsub(i);
S0[(2 * j + 1) * NP + i] = x0MC[j].ccsub(i);
}
}
double tempqbdot[NP];
for (int i = 0; i < NP; i++)
{
tempqbdot[i] = 0;
for (int j = 0; j < 2 * NX; j++)
{
tempqbdot[i] = tempqbdot[i] + S0[i + j * NP] * l[j];
}
Ith(S_init, i + 1) = tempqbdot[i];
}
return S_init;
}
/*
*--------------------------------------------------------------------
* PRIVATE FUNCTIONS
*--------------------------------------------------------------------
*/