-
Notifications
You must be signed in to change notification settings - Fork 297
/
gbode_main.c
2049 lines (1801 loc) · 85.5 KB
/
gbode_main.c
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
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2022, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE
* GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the OSMC (Open Source Modelica Consortium)
* Public License (OSMC-PL) are obtained from OSMC, either from the above
* address, from the URLs: http://www.openmodelica.org or
* http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica
* distribution. GNU version 3 is obtained from:
* http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from:
* http://www.opensource.org/licenses/BSD-3-Clause.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS
* EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE
* CONDITIONS OF OSMC-PL.
*
*/
/*! \file gbode_main.c
* Implementation of a generic (implicit and explicit) Runge Kutta solver, which works for any
* order and stage based on a provided Butcher tableau. Utilizes the sparsity pattern of the ODE
* together with the KINSOL (KLU) solver
*
* \author bbachmann
*/
#include <time.h>
#include "gbode_main.h"
#include "gbode_util.h"
#include "gbode_conf.h"
#include "gbode_ctrl.h"
#include "gbode_events.h"
#include "gbode_nls.h"
#include "gbode_sparse.h"
#include "gbode_step.h"
#include "gbode_util.h"
#include <float.h>
#include <math.h>
#include <string.h>
#include "external_input.h"
#include "jacobianSymbolical.h"
#include "kinsolSolver.h"
#include "model_help.h"
#include "newtonIteration.h"
#include "nonlinearSystem.h"
#include "simulation/options.h"
#include "simulation/results/simulation_result.h"
#include "util/jacobian_util.h"
#include "util/omc_error.h"
#include "util/omc_file.h"
#include "util/simulation_options.h"
#include "util/varinfo.h"
#include "epsilon.h"
/**
* @brief Calculate function values of function ODE f(t,y).
*
* Assuming the correct values for time value and states are set.
*
* @param data Runtime data struct.
* @param threadData Thread data for error handling.
* @param counter Counter for function calls. Incremented by 1.
*/
void gbode_fODE(DATA *data, threadData_t *threadData, unsigned int* counter)
{
(*counter)++;
externalInputUpdate(data);
data->callback->input_function(data, threadData);
data->callback->functionODE(data, threadData);
return;
}
/**
* @brief Function allocates memory needed for chosen gbodef method.
*
* @param data Runtime data struct.
* @param threadData Thread data for error handling.
* @param solverInfo Information about main solver.
* @return int Return 0 on success, -1 on failure.
*/
int gbodef_allocateData(DATA *data, threadData_t *threadData, SOLVER_INFO *solverInfo, DATA_GBODE *gbData)
{
DATA_GBODEF *gbfData = (DATA_GBODEF *)calloc(1, sizeof(DATA_GBODEF));
gbData->gbfData = gbfData;
ANALYTIC_JACOBIAN *jacobian = NULL;
analyticalJacobianColumn_func_ptr analyticalJacobianColumn = NULL;
int i;
gbfData->nStates = gbData->nStates;
gbfData->GM_method = getGB_method(FLAG_MR);
gbfData->tableau = initButcherTableau(gbfData->GM_method, FLAG_MR_ERR);
if (gbfData->tableau == NULL)
{
// ERROR
messageClose(LOG_STDOUT);
omc_throw_function(threadData);
}
// Get size of non-linear system
analyseButcherTableau(gbfData->tableau, gbData->nStates, &gbfData->nlSystemSize, &gbfData->type);
if (gbfData->GM_method == MS_ADAMS_MOULTON)
{
gbfData->nlSystemSize = gbData->nStates;
gbfData->step_fun = &(full_implicit_MS_MR);
gbfData->type = MS_TYPE_IMPLICIT;
gbfData->isExplicit = FALSE;
}
switch (gbfData->type)
{
case GM_TYPE_EXPLICIT:
gbfData->isExplicit = TRUE;
gbfData->step_fun = &(expl_diag_impl_RK_MR);
break;
case GM_TYPE_DIRK:
gbfData->isExplicit = FALSE;
gbfData->step_fun = &(expl_diag_impl_RK_MR);
break;
case MS_TYPE_IMPLICIT:
gbfData->isExplicit = FALSE;
gbfData->step_fun = &(full_implicit_MS_MR);
break;
case GM_TYPE_IMPLICIT:
throwStreamPrint(NULL, "Fully Implicit RK method is not supported for the fast states integration!");
default:
throwStreamPrint(NULL, "Not handled case for Runge-Kutta method %i", gbfData->type);
}
infoStreamPrint(LOG_SOLVER, 0, "Step control factor is set to %g", gbfData->tableau->fac);
gbfData->ctrl_method = getControllerMethod(FLAG_MR_CTRL);
if (gbfData->ctrl_method == GB_CTRL_CNST) {
warningStreamPrint(LOG_STDOUT, 0, "Constant step size not supported for inner integration. Using IController.");
gbfData->ctrl_method = GB_CTRL_I;
}
gbfData->stepSize_control = getControllFunc(gbfData->ctrl_method);
// allocate memory for the generic RK method
gbfData->y = malloc(gbData->nStates*sizeof(double));
gbfData->yOld = malloc(gbData->nStates*sizeof(double));
gbfData->yt = malloc(gbData->nStates*sizeof(double));
gbfData->y1 = malloc(gbData->nStates*sizeof(double));
gbfData->f = malloc(gbData->nStates*sizeof(double));
gbfData->k = malloc(gbData->nStates*gbfData->tableau->nStages*sizeof(double));
gbfData->x = malloc(gbData->nStates*gbfData->tableau->nStages*sizeof(double));
gbfData->yLeft = malloc(gbData->nStates*sizeof(double));
gbfData->kLeft = malloc(gbData->nStates*sizeof(double));
gbfData->yRight = malloc(gbData->nStates*sizeof(double));
gbfData->kRight = malloc(gbData->nStates*sizeof(double));
gbfData->res_const = malloc(gbData->nStates*sizeof(double));
gbfData->errest = malloc(gbData->nStates*sizeof(double));
gbfData->errtol = malloc(gbData->nStates*sizeof(double));
gbfData->err = malloc(gbData->nStates*sizeof(double));
gbfData->ringBufferSize = 4;
gbfData->errValues = calloc(gbfData->ringBufferSize, sizeof(double));
gbfData->stepSizeValues = malloc(gbfData->ringBufferSize*sizeof(double));
gbfData->tv = malloc(gbfData->ringBufferSize*sizeof(double));
gbfData->yv = malloc(gbData->nStates*gbfData->ringBufferSize*sizeof(double));
gbfData->kv = malloc(gbData->nStates*gbfData->ringBufferSize*sizeof(double));
gbData->nFastStates = 0;
gbData->nSlowStates = gbData->nFastStates;
gbfData->fastStates_old = malloc(gbData->nStates*sizeof(int));
gbfData->nFastStates_old = gbData->nFastStates;
for (int i = 0; i < gbData->nStates; i++)
{
gbfData->fastStates_old[i] = i;
}
printButcherTableau(gbfData->tableau);
/* initialize analytic Jacobian, if available and needed */
if (!gbfData->isExplicit)
{
// Allocate Jacobian, if !gbfData->isExplcit and gbData->isExplicit
// Free is done in gbode_freeData
if (gbData->isExplicit) {
jacobian = &(data->simulationInfo->analyticJacobians[data->callback->INDEX_JAC_A]);
data->callback->initialAnalyticJacobianA(data, threadData, jacobian);
if(jacobian->availability == JACOBIAN_AVAILABLE || jacobian->availability == JACOBIAN_ONLY_SPARSITY) {
infoStreamPrint(LOG_SOLVER, 1, "Initialized Jacobian:");
infoStreamPrint(LOG_SOLVER, 0, "columns: %d rows: %d", jacobian->sizeCols, jacobian->sizeRows);
infoStreamPrint(LOG_SOLVER, 0, "NNZ: %d colors: %d", jacobian->sparsePattern->numberOfNonZeros, jacobian->sparsePattern->maxColors);
messageClose(LOG_SOLVER);
}
// Compare user flag to availabe Jacobian methods
const char* flagValue;
if(omc_flag[FLAG_JACOBIAN]){
flagValue = omc_flagValue[FLAG_JACOBIAN];
} else {
flagValue = NULL;
}
enum JACOBIAN_METHOD jacobianMethod = setJacobianMethod(threadData, jacobian->availability, flagValue);
gbfData->symJacAvailable = jacobian->availability == JACOBIAN_AVAILABLE;
// change GBODE specific jacobian method
if (jacobianMethod == SYMJAC) {
warningStreamPrint(LOG_STDOUT, 0, "Symbolic Jacobians without coloring are currently not supported by GBODE."
" Colored symbolical Jacobian will be used.");
} else if(jacobianMethod == NUMJAC || jacobianMethod == COLOREDNUMJAC || jacobianMethod == INTERNALNUMJAC) {
warningStreamPrint(LOG_STDOUT, 0, "Numerical Jacobians without coloring are currently not supported by GBODE."
" Colored numerical Jacobian will be used.");
gbfData->symJacAvailable = FALSE;
}
} else {
gbfData->symJacAvailable = gbData->symJacAvailable;
}
/* Allocate memory for the nonlinear solver */
gbfData->nlsSolverMethod = getGB_NLS_method(FLAG_MR_NLS);
/* Initialize data for the nonlinear solver */
gbfData->nlsData = initRK_NLS_DATA_MR(data, threadData, gbfData);
if (!gbfData->nlsData)
{
return -1;
}
gbfData->sparsePattern_DIRK = initializeSparsePattern_SR(data, gbfData->nlsData);
}
else
{
gbfData->symJacAvailable = FALSE;
gbfData->nlsSolverMethod = GB_NLS_UNKNOWN;
gbfData->nlsData = NULL;
gbfData->jacobian = NULL;
}
gbfData->interpolation = getInterpolationMethod(FLAG_MR_INT);
if (!gbfData->tableau->withDenseOutput) {
if (gbfData->interpolation == GB_DENSE_OUTPUT) gbfData->interpolation = GB_INTERPOL_HERMITE;
}
switch (gbfData->interpolation)
{
case GB_INTERPOL_LIN:
infoStreamPrint(LOG_SOLVER, 0, "Linear interpolation is used for emitting results");
break;
case GB_INTERPOL_HERMITE:
case GB_INTERPOL_HERMITE_a:
case GB_INTERPOL_HERMITE_b:
case GB_INTERPOL_HERMITE_ERRCTRL:
infoStreamPrint(LOG_SOLVER, 0, "Hermite interpolation is used for the slow states");
break;
case GB_DENSE_OUTPUT:
case GB_DENSE_OUTPUT_ERRCTRL:
infoStreamPrint(LOG_SOLVER, 0, "Dense output is used for emitting results");
break;
default:
throwStreamPrint(NULL, "Unhandled interpolation case.");
}
if (ACTIVE_STREAM(LOG_GBODE_STATES))
{
char filename[4096];
unsigned int bufSize = 4096;
snprintf(filename, bufSize, "%s_ActiveStates.txt", data->modelData->modelFilePrefix);
gbfData->fastStatesDebugFile = omc_fopen(filename, "w");
warningStreamPrint(LOG_STDOUT, 0, "LOG_GBODE_STATES sets -noEquidistantTimeGrid for emitting results!");
solverInfo->integratorSteps = TRUE;
}
else
{
gbfData->fastStatesDebugFile = NULL;
}
i = fmin(fmax(round(gbData->nStates * gbData->percentage), 1), gbData->nStates - 1);
infoStreamPrint(LOG_SOLVER, 0, "Number of states %d (%d slow states, %d fast states)", gbData->nStates, gbData->nStates-i, i);
/* reset statistics because it is accumulated in solver_main.c */
resetSolverStats(&gbfData->stats);
return 0;
}
/**
* @brief Function allocates memory needed for generic RK method.
*
* @param data Runtime data struct.
* @param threadData Thread data for error handling.
* @param solverInfo Information about main solver.
* @return int Return 0 on success, -1 on failure.
*/
int gbode_allocateData(DATA *data, threadData_t *threadData, SOLVER_INFO *solverInfo)
{
DATA_GBODE *gbData = (DATA_GBODE *)calloc(1, sizeof(DATA_GBODE));
// Set backup in simulationInfo
data->simulationInfo->backupSolverData = (void *)gbData;
solverInfo->solverData = (void *)gbData;
gbData->nStates = data->modelData->nStates;
ANALYTIC_JACOBIAN* jacobian = NULL;
analyticalJacobianColumn_func_ptr analyticalJacobianColumn = NULL;
gbData->GM_method = getGB_method(FLAG_SR);
gbData->tableau = initButcherTableau(gbData->GM_method, FLAG_SR_ERR);
if (gbData->tableau == NULL) {
errorStreamPrint(LOG_STDOUT, 0, "allocateDataGm: Failed to initialize gbode tableau for method %s", GB_METHOD_NAME[gbData->GM_method]);
return -1;
}
// Get size of non-linear system
analyseButcherTableau(gbData->tableau, gbData->nStates, &gbData->nlSystemSize, &gbData->type);
switch (gbData->type) {
case GM_TYPE_EXPLICIT:
gbData->isExplicit = TRUE;
gbData->step_fun = &(expl_diag_impl_RK);
break;
case GM_TYPE_DIRK:
gbData->isExplicit = FALSE;
gbData->step_fun = &(expl_diag_impl_RK);
break;
case GM_TYPE_IMPLICIT:
gbData->isExplicit = FALSE;
gbData->step_fun = &(full_implicit_RK);
break;
case MS_TYPE_IMPLICIT:
gbData->isExplicit = FALSE;
gbData->step_fun = &(full_implicit_MS);
break;
default:
throwStreamPrint(NULL, "gbode_allocateData: Unknown type %i", gbData->type);
}
if (gbData->GM_method == MS_ADAMS_MOULTON) {
gbData->nlSystemSize = gbData->nStates;
gbData->step_fun = &(full_implicit_MS);
gbData->type = MS_TYPE_IMPLICIT;
gbData->isExplicit = FALSE;
}
// test of multi-step method
gbData->ctrl_method = getControllerMethod(FLAG_SR_CTRL);
gbData->stepSize_control = getControllFunc(gbData->ctrl_method);
/* define maximum step size gbode is allowed to go */
if (omc_flag[FLAG_MAX_STEP_SIZE])
{
gbData->maxStepSize = atof(omc_flagValue[FLAG_MAX_STEP_SIZE]);
if (gbData->maxStepSize < 0 || gbData->maxStepSize > DBL_MAX/2) {
throwStreamPrint(NULL, "maximum step size %g is not allowed", gbData->maxStepSize);
} else {
infoStreamPrint(LOG_SOLVER, 0, "maximum step size %g", gbData->maxStepSize);
}
}
else
{
gbData->maxStepSize = -1;
infoStreamPrint(LOG_SOLVER, 0, "maximum step size not set");
}
/* Initial step size */
if (omc_flag[FLAG_INITIAL_STEP_SIZE])
{
gbData->initialStepSize = atof(omc_flagValue[FLAG_INITIAL_STEP_SIZE]);
if (gbData->initialStepSize < GB_MINIMAL_STEP_SIZE || gbData->initialStepSize > DBL_MAX/2) {
throwStreamPrint(NULL, "initial step size %g is not allowed, minimal step size is %g", gbData->initialStepSize, GB_MINIMAL_STEP_SIZE);
} else {
infoStreamPrint(LOG_SOLVER, 0, "initial step size %g", gbData->initialStepSize);
}
}
else
{
gbData->initialStepSize = -1; /* use default */
infoStreamPrint(LOG_SOLVER, 0, "initial step size not set");
}
/* if FLAG_NO_RESTART is set, configure gbode */
if (omc_flag[FLAG_NO_RESTART])
{
gbData->noRestart = TRUE;
}
else
{
gbData->noRestart = FALSE;
}
infoStreamPrint(LOG_SOLVER, 0, "gbode performs a restart after an event occurs %s", gbData->noRestart?"NO":"YES");
gbData->isFirstStep = TRUE;
/* Allocate internal memory */
gbData->y = malloc(sizeof(double) * gbData->nStates);
gbData->yOld = malloc(sizeof(double) * gbData->nStates);
gbData->yLeft = malloc(sizeof(double) * gbData->nStates);
gbData->kLeft = malloc(sizeof(double) * gbData->nStates);
gbData->yRight = malloc(sizeof(double) * gbData->nStates);
gbData->kRight = malloc(sizeof(double) * gbData->nStates);
gbData->yt = malloc(sizeof(double) * gbData->nStates);
gbData->y1 = malloc(sizeof(double) * gbData->nStates);
gbData->f = malloc(sizeof(double) * gbData->nStates);
gbData->k = malloc(sizeof(double) * gbData->nStates * gbData->tableau->nStages);
gbData->x = malloc(sizeof(double) * gbData->nStates * gbData->tableau->nStages);
gbData->res_const = malloc(sizeof(double) * gbData->nStates);
gbData->errest = malloc(sizeof(double) * gbData->nStates);
gbData->errtol = malloc(sizeof(double) * gbData->nStates);
gbData->err = malloc(sizeof(double) * gbData->nStates);
// ring buffer for different purposes (extrapolation, etc.)
gbData->ringBufferSize = 4;
gbData->errValues = malloc(sizeof(double) * gbData->ringBufferSize);
gbData->stepSizeValues = malloc(sizeof(double) * gbData->ringBufferSize);
gbData->tv = malloc(sizeof(double) * gbData->ringBufferSize);
gbData->yv = malloc(gbData->nStates*sizeof(double) * gbData->ringBufferSize);
gbData->kv = malloc(gbData->nStates*sizeof(double) * gbData->ringBufferSize);
gbData->tr = malloc(sizeof(double) * 2);
gbData->yr = malloc(gbData->nStates*sizeof(double) * 2);
gbData->kr = malloc(gbData->nStates*sizeof(double) * 2);
printButcherTableau(gbData->tableau);
/* initialize analytic Jacobian, if available and needed */
if (!gbData->isExplicit) {
jacobian = &(data->simulationInfo->analyticJacobians[data->callback->INDEX_JAC_A]);
data->callback->initialAnalyticJacobianA(data, threadData, jacobian);
if(jacobian->availability == JACOBIAN_AVAILABLE || jacobian->availability == JACOBIAN_ONLY_SPARSITY) {
infoStreamPrint(LOG_SOLVER, 1, "Initialized Jacobian:");
infoStreamPrint(LOG_SOLVER, 0, "columns: %d rows: %d", jacobian->sizeCols, jacobian->sizeRows);
infoStreamPrint(LOG_SOLVER, 0, "NNZ: %d colors: %d", jacobian->sparsePattern->numberOfNonZeros, jacobian->sparsePattern->maxColors);
messageClose(LOG_SOLVER);
}
// Compare user flag to availabe Jacobian methods
const char* flagValue;
if(omc_flag[FLAG_JACOBIAN]){
flagValue = omc_flagValue[FLAG_JACOBIAN];
} else {
flagValue = NULL;
}
enum JACOBIAN_METHOD jacobianMethod = setJacobianMethod(threadData, jacobian->availability, flagValue);
gbData->symJacAvailable = jacobian->availability == JACOBIAN_AVAILABLE;
// change GBODE specific jacobian method
if (jacobianMethod == SYMJAC) {
warningStreamPrint(LOG_STDOUT, 0, "Symbolic Jacobians without coloring are currently not supported by GBODE."
" Colored symbolical Jacobian will be used.");
} else if(jacobianMethod == NUMJAC || jacobianMethod == COLOREDNUMJAC || jacobianMethod == INTERNALNUMJAC) {
warningStreamPrint(LOG_STDOUT, 0, "Numerical Jacobians without coloring are currently not supported by GBODE."
" Colored numerical Jacobian will be used.");
gbData->symJacAvailable = FALSE;
}
/* Allocate memory for the nonlinear solver */
gbData->nlsSolverMethod = getGB_NLS_method(FLAG_SR_NLS);
gbData->nlsData = initRK_NLS_DATA(data, threadData, gbData);
if (!gbData->nlsData) {
return -1;
} else {
infoStreamPrint(LOG_SOLVER, 1, "Nominal values of the states:");
for (int i = 0; i < gbData->nStates; i++) {
infoStreamPrint(LOG_SOLVER, 0, "%s = %g", data->modelData->realVarsData[i].info.name, gbData->nlsData->nominal[i]);
}
messageClose(LOG_SOLVER);
}
} else {
gbData->symJacAvailable = FALSE;
gbData->nlsSolverMethod = GB_NLS_UNKNOWN;
gbData->nlsData = NULL;
gbData->jacobian = NULL;
}
gbData->percentage = getGBRatio();
gbData->multi_rate = gbData->percentage > 0 && gbData->percentage < 1;
gbData->fastStatesIdx = malloc(sizeof(int) * gbData->nStates);
gbData->slowStatesIdx = malloc(sizeof(int) * gbData->nStates);
gbData->sortedStatesIdx = malloc(sizeof(int) * gbData->nStates);
gbData->nFastStates = 0;
gbData->nSlowStates = gbData->nStates;
for (int i = 0; i < gbData->nStates; i++) {
gbData->fastStatesIdx[i] = i;
gbData->slowStatesIdx[i] = i;
gbData->sortedStatesIdx[i] = i;
}
if (gbData->multi_rate && omc_flagValue[FLAG_SR_INT]==NULL) {
gbData->interpolation = GB_DENSE_OUTPUT_ERRCTRL;
} else {
gbData->interpolation = getInterpolationMethod(FLAG_SR_INT);
}
if (!gbData->tableau->withDenseOutput) {
if (gbData->interpolation == GB_DENSE_OUTPUT) gbData->interpolation = GB_INTERPOL_HERMITE;
if (gbData->interpolation == GB_DENSE_OUTPUT_ERRCTRL) gbData->interpolation = GB_INTERPOL_HERMITE_ERRCTRL;
}
char buffer[1024];
unsigned int bufSize = 1024;
if (gbData->multi_rate) {
snprintf(buffer, bufSize, "%s", " and slow states interpolation");
} else {
snprintf(buffer, bufSize, "%s"," ");
}
switch (gbData->interpolation)
{
case GB_INTERPOL_LIN:
infoStreamPrint(LOG_SOLVER, 0, "Linear interpolation is used for emitting results%s", buffer);
break;
case GB_INTERPOL_HERMITE_ERRCTRL:
case GB_INTERPOL_HERMITE_a:
case GB_INTERPOL_HERMITE_b:
case GB_INTERPOL_HERMITE:
infoStreamPrint(LOG_SOLVER, 0, "Hermite interpolation is used for emitting results%s", buffer);
break;
case GB_DENSE_OUTPUT:
case GB_DENSE_OUTPUT_ERRCTRL:
infoStreamPrint(LOG_SOLVER, 0, "Dense output is used for emitting results%s", buffer);
break;
default:
throwStreamPrint(NULL, "Unhandled interpolation case.");
}
gbData->err_threshold = 0.1;
gbData->err_int = 0; // needed, if GB_INTERPOL_HERMITE_ERRCTRL or GB_DENSE_OUTPUT_ERRCTRL is used
gbData->eventSearch = 0; // use interpolation for event time search
if (gbData->multi_rate) {
gbodef_allocateData(data, threadData, solverInfo, gbData);
gbData->tableau->isKRightAvailable = FALSE;
} else {
gbData->gbfData = NULL;
}
// Value will be handled in the initial step size determination (-1 and 0 means no failure)
gbData->initialFailures = -1;
return 0;
}
/**
* @brief Free generic RK data.
*
* @param data Pointer to generik Runge-Kutta data struct.
*/
void gbodef_freeData(DATA_GBODEF *gbfData)
{
/* Free non-linear system data */
freeRK_NLS_DATA(gbfData->nlsData);
/* Free Jacobian */
freeAnalyticJacobian(gbfData->jacobian);
free(gbfData->jacobian); gbfData->jacobian = NULL;
/* Free sparsity pattern */
freeSparsePattern(gbfData->sparsePattern_DIRK);
free(gbfData->sparsePattern_DIRK);
/* Free Butcher tableau */
freeButcherTableau(gbfData->tableau);
free(gbfData->y);
free(gbfData->yOld);
free(gbfData->yLeft);
free(gbfData->kLeft);
free(gbfData->yRight);
free(gbfData->kRight);
free(gbfData->yt);
free(gbfData->y1);
free(gbfData->f);
free(gbfData->k);
free(gbfData->x);
free(gbfData->res_const);
free(gbfData->errest);
free(gbfData->errtol);
free(gbfData->err);
free(gbfData->errValues);
free(gbfData->stepSizeValues);
free(gbfData->tv);
free(gbfData->yv);
free(gbfData->kv);
free(gbfData->fastStates_old);
if (gbfData->fastStatesDebugFile != NULL)
fclose(gbfData->fastStatesDebugFile);
free(gbfData);
gbfData = NULL;
return;
}
/**
* @brief Free generic RK data.
*
* @param gbData Pointer to generik Runge-Kutta data struct.
*/
void gbode_freeData(DATA* data, DATA_GBODE *gbData)
{
ANALYTIC_JACOBIAN* jacobian = &(data->simulationInfo->analyticJacobians[data->callback->INDEX_JAC_A]);
freeAnalyticJacobian(jacobian);
/* Free non-linear system data */
freeRK_NLS_DATA(gbData->nlsData);
/* Free Jacobian */
freeAnalyticJacobian(gbData->jacobian);
free(gbData->jacobian); gbData->jacobian = NULL;
/* Free Butcher tableau */
freeButcherTableau(gbData->tableau);
if (gbData->multi_rate)
{
gbodef_freeData(gbData->gbfData);
}
/* Free multi-rate data */
free(gbData->err);
free(gbData->errValues);
free(gbData->stepSizeValues);
free(gbData->tv);
free(gbData->yv);
free(gbData->kv);
free(gbData->tr);
free(gbData->yr);
free(gbData->kr);
free(gbData->fastStatesIdx);
free(gbData->slowStatesIdx);
free(gbData->sortedStatesIdx);
/* Free remaining arrays */
free(gbData->y);
free(gbData->yOld);
free(gbData->yLeft);
free(gbData->kLeft);
free(gbData->yRight);
free(gbData->kRight);
free(gbData->yt);
free(gbData->y1);
free(gbData->f);
free(gbData->k);
free(gbData->x);
free(gbData->res_const);
free(gbData->errest);
free(gbData->errtol);
free(gbData);
gbData = NULL;
return;
}
/**
* @brief Calculate initial step size.
*
* Called at the beginning of simulation or after an event occurred.
*
* @param data Runtime data struct.
* @param threadData Thread data for error handling.
* @param solverInfo Storing Runge-Kutta solver data.
*/
void gbodef_init(DATA* data, threadData_t* threadData, SOLVER_INFO* solverInfo)
{
SIMULATION_DATA *sData = (SIMULATION_DATA*)data->localData[0];
SIMULATION_DATA *sDataOld = (SIMULATION_DATA*)data->localData[1];
DATA_GBODE* gbData = (DATA_GBODE*)solverInfo->solverData;
DATA_GBODEF* gbfData = gbData->gbfData;
int nStates = gbfData->nStates;
int nStages = gbfData->tableau->nStages;
int i;
gbfData->didEventStep = FALSE;
gbfData->time = gbData->time;
gbfData->stepSize = 0.1*gbData->stepSize*IController(&(gbData->err_fast), &(gbData->stepSize), 1);
memcpy(gbfData->yOld, gbData->yOld, sizeof(double) * nStates);
memcpy(gbfData->y, gbData->y, sizeof(double) * nStates);
gbfData->timeRight = gbData->timeLeft;
memcpy(gbfData->yRight, gbData->yLeft, sizeof(double) * nStates);
memcpy(gbfData->kRight, gbData->kLeft, sizeof(double) * nStates);
// set solution ring buffer (extrapolation in case of NLS)
for (i=0; i<gbfData->ringBufferSize; i++) {
gbfData->tv[i] = gbData->tv[i];
memcpy(gbfData->yv + i * nStates, gbData->yv + i * nStates, nStates * sizeof(double));
memcpy(gbfData->kv + i * nStates, gbData->kv + i * nStates, nStates * sizeof(double));
}
}
/**
* @brief Initialize ring buffer and interpolation arrays.
*
* Called at the beginning of simulation or after an event occurred.
*
* @param data Runtime data struct.
* @param threadData Thread data for error handling.
* @param solverInfo Storing Runge-Kutta solver data.
*/
void gbode_init(DATA* data, threadData_t* threadData, SOLVER_INFO* solverInfo)
{
DATA_GBODE* gbData = (DATA_GBODE*)solverInfo->solverData;
SIMULATION_DATA *sData = (SIMULATION_DATA*)data->localData[0];
modelica_real* fODE = &sData->realVars[gbData->nStates];
int nStates = gbData->nStates;
int i;
// initialize ring buffer for error and step size control
for (i=0; i<gbData->ringBufferSize; i++) {
gbData->errValues[i] = 0;
gbData->stepSizeValues[i] = 0;
}
/* reset statistics, because it is accumulated in solver_main.c */
if (!gbData->isExplicit)
gbData->nlsData->numberOfJEval = 0;
resetSolverStats(&gbData->stats);
// initialize vector used for interpolation (equidistant time grid)
// and for the birate inner integration
gbData->timeRight = gbData->time;
memcpy(gbData->yRight, gbData->yOld, nStates*sizeof(double));
memcpy(gbData->kRight, fODE, nStates*sizeof(double));
// set solution ring buffer (extrapolation in case of NLS)
for (i=0; i<gbData->ringBufferSize; i++) {
gbData->tv[i] = gbData->timeRight;
memcpy(gbData->yv + i * nStates, gbData->yRight, nStates * sizeof(double));
memcpy(gbData->kv + i * nStates, gbData->kRight, nStates * sizeof(double));
}
}
/*! \fn gbodef_main
*
* function does one integration step and calculates
* next step size by the implicit midpoint rule
*
* used for solver 'gm'
*/
int gbodef_main(DATA *data, threadData_t *threadData, SOLVER_INFO *solverInfo, double targetTime)
{
SIMULATION_DATA *sData = (SIMULATION_DATA *)data->localData[0];
modelica_real *fODE = sData->realVars + data->modelData->nStates;
DATA_GBODE *gbData = (DATA_GBODE *)solverInfo->solverData;
DATA_GBODEF *gbfData = gbData->gbfData;
double stopTime = data->simulationInfo->stopTime;
double err, eventTime;
double Atol = data->simulationInfo->tolerance;
double Rtol = data->simulationInfo->tolerance;
int i, ii, j, jj, l, ll, r, rr;
int integrator_step_info;
int nStates = gbData->nStates;
int nFastStates = gbData->nFastStates;
int nStages = gbfData->tableau->nStages;
modelica_boolean fastStatesChange = FALSE;
modelica_boolean foundEvent;
// This is the target time of the main integrator
double innerTargetTime = fmin(targetTime, gbData->timeRight);
/* The inner integrator needs to be initialzed, at start time, when an event occured,
* and if outer integrations have been done with all states involved
* (gbfData->timeRight < gbData->timeLeft)
*/
if (gbfData->didEventStep || gbfData->timeRight < gbData->timeLeft) {
gbodef_init(data, threadData, solverInfo);
}
fastStatesChange = checkFastStatesChange(gbData);
if (fastStatesChange && !gbfData->isExplicit) {
struct dataSolver *solverData = gbfData->nlsData->solverData;
// set number of non-linear variables and corresponding nominal values (changes dynamically during simulation)
gbfData->nlsData->size = gbData->nFastStates;
infoStreamPrint(LOG_GBODE, 1, "Fast states and corresponding nominal values:");
for (ii = 0; ii < nFastStates; ii++)
{
i = gbData->fastStatesIdx[ii];
// Get the nominal values of the fast states
gbfData->nlsData->nominal[ii] = fmax(fabs(data->modelData->realVarsData[i].attribute.nominal), 1e-32);
infoStreamPrint(LOG_GBODE, 0, "%s = %g", data->modelData->realVarsData[i].info.name, gbfData->nlsData->nominal[ii]);
}
messageClose(LOG_GBODE);
if (gbfData->nlsData->isPatternAvailable)
{
updateSparsePattern_MR(gbData, gbfData->jacobian->sparsePattern);
gbfData->jacobian->sizeCols = nFastStates;
gbfData->jacobian->sizeRows = nFastStates;
switch (gbfData->nlsSolverMethod)
{
case GB_NLS_NEWTON:
((DATA_NEWTON *)solverData->ordinaryData)->n = gbData->nFastStates;
break;
case GB_NLS_KINSOL:
nlsKinsolFree(solverData->ordinaryData);
/* Set NLS user data */
NLS_USERDATA* nlsUserData = initNlsUserData(data, threadData, -1, gbfData->nlsData, gbfData->jacobian);
nlsUserData->solverData = (void*) gbfData;
solverData->ordinaryData = (void*) nlsKinsolAllocate(gbfData->nlsData->size, nlsUserData, FALSE);
break;
default:
throwStreamPrint(NULL, "NLS method %s not yet implemented.", GB_NLS_METHOD_NAME[gbfData->nlsSolverMethod]);
}
}
}
// print informations on the calling details
infoStreamPrint(LOG_SOLVER, 1, "gbodef solver started (fast states/states): %d/%d", gbData->nFastStates,gbData->nStates);
printIntVector_gb(LOG_SOLVER, "fast States:", gbData->fastStatesIdx, gbData->nFastStates, gbfData->time);
infoStreamPrint(LOG_SOLVER, 0, "interpolation is done between %10g to %10g (SR-stepsize: %10g)",
gbData->timeLeft, gbData->timeRight, gbData->lastStepSize);
if (ACTIVE_STREAM(LOG_GBODE_V)) {
infoStreamPrint(LOG_GBODE_V, 1, "Interpolation values from outer integration:");
printVector_gb(LOG_GBODE_V, "yL", gbData->yLeft, gbData->nStates, gbData->timeLeft);
printVector_gb(LOG_GBODE_V, "kL", gbData->kLeft, gbData->nStates, gbData->timeLeft);
printVector_gb(LOG_GBODE_V, "yR", gbData->yRight, gbData->nStates, gbData->timeRight);
printVector_gb(LOG_GBODE_V, "kR", gbData->kRight, gbData->nStates, gbData->timeRight);
messageClose(LOG_GBODE_V);
}
while (gbfData->time < innerTargetTime) {
// Don't exceed simulation stop time
if (gbfData->time + gbfData->stepSize > stopTime) {
gbfData->stepSize = stopTime - gbfData->time;
}
// Synchronize inner integration with outer integration
// Strategy: either set outer step to the inner integration
// or the other way around (depending on, if more or less
// than 2 inner steps required)
if (gbfData->time + gbfData->stepSize > gbData->timeRight) {
// if (gbfData->time - gbfData->stepSize > gbData->timeLeft) {
// gbData->timeRight = gbfData->timeRight;
// gbData->lastStepSize = gbData->timeRight - gbData->timeLeft;
// messageClose(LOG_SOLVER);
// return 0;
// } else {
gbfData->stepSize = gbData->timeRight - gbfData->time;
// }
}
// store left hand data for later interpolation
gbfData->timeLeft = gbfData->timeRight;
memcpy(gbfData->yLeft, gbfData->yRight, nStates * sizeof(double));
memcpy(gbfData->kLeft, gbfData->kRight, nStates * sizeof(double));
// debug the changes of the states and derivatives during integration
if (ACTIVE_STREAM(LOG_GBODE)) {
infoStreamPrint(LOG_GBODE, 1, "states and derivatives at left hand side (inner integration):");
printVector_gb(LOG_GBODE, "yL", gbfData->yLeft, nStates, gbfData->timeLeft);
printVector_gb(LOG_GBODE, "kL", gbfData->kLeft, nStates, gbfData->timeLeft);
messageClose(LOG_GBODE);
}
do {
if (ACTIVE_STREAM(LOG_SOLVER_V)) {
infoStreamPrint(LOG_SOLVER_V, 1, "States and derivatives of the ring buffer:");
for (int i=0; i<gbfData->ringBufferSize; i++) {
printVector_gbf(LOG_SOLVER_V, "y", gbfData->yv + i * nStates, nStates, gbfData->tv[i], gbData->nFastStates, gbData->fastStatesIdx);
printVector_gbf(LOG_SOLVER_V, "k", gbfData->kv + i * nStates, nStates, gbfData->tv[i], gbData->nFastStates, gbData->fastStatesIdx);
}
messageClose(LOG_SOLVER_V);
}
// do one integration step resulting in two different approximations
// results are stored in gbData->y and gbData->yt
if (gbfData->tableau->richardson) {
integrator_step_info = gbodef_richardson(data, threadData, solverInfo);
} else {
integrator_step_info = gbfData->step_fun(data, threadData, solverInfo);
}
// error handling: try half of the step size!
if (integrator_step_info != 0) {
(gbfData->stats).nConvergenveTestFailures++;
infoStreamPrint(LOG_SOLVER, 0, "gbodef_main: Failed to calculate step at time = %5g.", gbfData->time);
gbfData->stepSize *= 0.5;
infoStreamPrint(LOG_SOLVER, 0, "Try half of the step size = %g", gbfData->stepSize);
if (gbfData->stepSize < GB_MINIMAL_STEP_SIZE) {
errorStreamPrint(LOG_STDOUT, 0, "Simulation aborted! Minimum step size %g reached, but error still to large.", GB_MINIMAL_STEP_SIZE);
messageClose(LOG_SOLVER);
return -1;
}
err = 100;
continue;
}
for (i = 0, err=0; i < nFastStates; i++) {
ii = gbData->fastStatesIdx[i];
// calculate corresponding values for the error estimator and step size control
gbfData->errtol[ii] = Rtol * fmax(fabs(gbfData->y[ii]), fabs(gbfData->yt[ii])) + Atol;
gbfData->errest[ii] = fabs(gbfData->y[ii] - gbfData->yt[ii]);
gbfData->err[ii] = gbfData->tableau->fac * gbfData->errest[ii] / gbfData->errtol[ii];
err = fmax(err, gbfData->err[ii]);
}
gbData->err_fast = err;
// Rotate and update buffer
for (i = (gbfData->ringBufferSize - 1); i > 0 ; i--) {
gbfData->errValues[i] = gbfData->errValues[i - 1];
gbfData->stepSizeValues[i] = gbfData->stepSizeValues[i - 1];
}
gbfData->errValues[0] = err;
gbfData->stepSizeValues[0] = gbfData->stepSize;
// Store performed stepSize for adjusting the time in case of latter interpolation
// Call the step size control
gbfData->lastStepSize = gbfData->stepSize;
gbfData->stepSize *= gbfData->stepSize_control(gbfData->errValues, gbfData->stepSizeValues, gbfData->tableau->error_order);
// debug ring buffer for the states and derviatives of the states
if (ACTIVE_STREAM(LOG_GBODE_V)) {
infoStreamPrint(LOG_GBODE_V, 1, "ring buffer during steps of inner integration");
infoStreamPrint(LOG_GBODE_V, 0, "old value:");
printVector_gb(LOG_GBODE_V, "y", gbfData->yOld, nStates, gbfData->time);
debugRingBuffer(LOG_GBODE_V, gbfData->x, gbfData->k, nStates, gbfData->tableau, gbfData->time, gbfData->lastStepSize);
infoStreamPrint(LOG_GBODE_V, 0, "new value:");
printVector_gb(LOG_GBODE_V, "y", gbfData->y, nStates, gbfData->time + gbfData->lastStepSize);
messageClose(LOG_GBODE_V);
}
// Re-do step, if error is larger than requested
if (err > 1)
{
gbfData->stats.nErrorTestFailures++;
infoStreamPrint(LOG_SOLVER, 0, "Reject step from %10g to %10g, error %10g, new stepsize %10g",
gbfData->time, gbfData->time + gbfData->lastStepSize, err, gbfData->stepSize);
if (ACTIVE_STREAM(LOG_GBODE_STATES)) {
dumpFastStates_gbf(gbData, gbfData->time + gbfData->lastStepSize, 1);
}
}
} while (err > 1);
// Count successful integration steps
gbfData->stats.nStepsTaken += 1;
// interpolate the slow states to the boundaries of current integration interval, this is used for event detection
// interpolate the slow states on the time of the current stage
gb_interpolation(gbfData->interpolation,
gbData->timeLeft, gbData->yLeft, gbData->kLeft,
gbData->timeRight, gbData->yRight, gbData->kRight,
gbfData->time, gbfData->yOld,
gbData->nSlowStates, gbData->slowStatesIdx, nStates, gbData->tableau, gbData->x, gbData->k);
gb_interpolation(gbfData->interpolation,
gbData->timeLeft, gbData->yLeft, gbData->kLeft,
gbData->timeRight, gbData->yRight, gbData->kRight,
gbfData->time + gbfData->lastStepSize, gbfData->y,
gbData->nSlowStates, gbData->slowStatesIdx, nStates, gbData->tableau, gbData->x, gbData->k);
// store right hand values for latter interpolation
gbfData->timeRight = gbfData->time + gbfData->lastStepSize;
memcpy(gbfData->yRight, gbfData->y, nStates * sizeof(double));
// update kRight
if (!gbfData->tableau->isKRightAvailable) {
sData->timeValue = gbfData->timeRight;
memcpy(sData->realVars, gbfData->yRight, data->modelData->nStates * sizeof(double));
gbode_fODE(data, threadData, &(gbData->stats.nCallsODE));
}
memcpy(gbfData->kRight, fODE, nStates * sizeof(double));
eventTime = checkForEvents(data, threadData, solverInfo, gbfData->time, gbfData->yOld, gbfData->time + gbfData->lastStepSize, gbfData->y, TRUE, &foundEvent);
if (foundEvent)
{
solverInfo->currentTime = eventTime;
sData->timeValue = solverInfo->currentTime;
// sData->realVars are the "numerical" values on the right hand side of the event
gbData->time = eventTime;
memcpy(gbData->yOld, sData->realVars, gbData->nStates * sizeof(double));
gbfData->time = eventTime;
memcpy(gbfData->yOld, sData->realVars, gbData->nStates * sizeof(double));
/* write statistics to the solverInfo data structure */