/
fmu2_model_interface.c.inc
2222 lines (1930 loc) · 87.6 KB
/
fmu2_model_interface.c.inc
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-CurrentYear, 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 GPL VERSION 3 LICENSE OR
* THIS 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 Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* 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.
*
* See the full OSMC Public License conditions for more details.
*
*/
#include "fmu2_model_interface.h"
#include "fmu_read_flags.h"
#include "../simulation/solver/stateset.h"
#include "../simulation/solver/model_help.h"
#include "../simulation/solver/cvode_solver.h"
#if !defined(OMC_NUM_NONLINEAR_SYSTEMS) || OMC_NUM_NONLINEAR_SYSTEMS>0
#include "../simulation/solver/nonlinearSystem.h"
#endif
#if !defined(OMC_NUM_LINEAR_SYSTEMS) || OMC_NUM_LINEAR_SYSTEMS>0
#include "../simulation/solver/linearSystem.h"
#endif
#if !defined(OMC_NUM_MIXED_SYSTEMS) || OMC_NUM_MIXED_SYSTEMS>0
#include "../simulation/solver/mixedSystem.h"
#endif
#include "../simulation/solver/delay.h"
#include "../simulation/solver/fmi_events.h"
#include "../simulation/simulation_info_json.h"
#include "../simulation/simulation_input_xml.h"
#include "../simulation/solver/synchronous.h"
#include "../simulation/options.h"
#include "../util/simulation_options.h"
#include "../util/omc_error.h"
/*
DLLExport pthread_key_t fmu2_thread_data_key;
*/
fmi2Boolean isCategoryLogged(ModelInstance *comp, int categoryIndex);
static fmi2String logCategoriesNames[] = {"logEvents", "logSingularLinearSystems", "logNonlinearSystems", "logDynamicStateSelection",
"logStatusWarning", "logStatusDiscard", "logStatusError", "logStatusFatal", "logStatusPending", "logAll", "logFmi2Call"};
// macro to be used to log messages. The macro check if current
// log category is valid and, if true, call the logger provided by simulator.
#define FILTERED_LOG(instance, status, categoryIndex, message, ...) if (isCategoryLogged(instance, categoryIndex)) { \
instance->functions->logger(instance->functions->componentEnvironment, instance->instanceName, status, \
logCategoriesNames[categoryIndex], message, ##__VA_ARGS__); }
// array of value references of states
#if NUMBER_OF_STATES>0
fmi2ValueReference vrStates[NUMBER_OF_STATES] = STATES;
fmi2ValueReference vrStatesDerivatives[NUMBER_OF_STATES] = STATESDERIVATIVES;
#endif
// ---------------------------------------------------------------------------
// Private helpers used below to validate function arguments
// ---------------------------------------------------------------------------
static fmi2Boolean isModelExchange(ModelInstance *comp)
{
return (fmi2ModelExchange == comp->type);
}
static fmi2Boolean isCoSimulation(ModelInstance *comp)
{
return (fmi2CoSimulation == comp->type);
}
const char* stateToString(ModelInstance *comp)
{
if (isModelExchange(comp))
{
switch (comp->state)
{
case model_state_start_end: return "model_state_start_end";
case model_state_instantiated: return "model_state_instantiated";
case model_state_initialization_mode: return "model_state_initialization_mode";
case model_state_cs_step_complete: return "model_state_cs_step_complete (invalid!)";
case model_state_cs_step_in_progress: return "model_state_cs_step_in_progress (invalid!)";
case model_state_cs_step_failed: return "model_state_cs_step_failed (invalid!)";
case model_state_cs_step_canceled: return "model_state_cs_step_canceled (invalid!)";
case model_state_me_event_mode: return "model_state_me_event_mode";
case model_state_me_continuous_time_mode: return "model_state_me_continuous_time_mode";
case model_state_terminated: return "model_state_terminated";
case model_state_error: return "model_state_error";
case model_state_fatal: return "model_state_fatal";
}
}
if (isCoSimulation(comp))
{
switch (comp->state)
{
case model_state_start_end: return "model_state_start_end";
case model_state_instantiated: return "model_state_instantiated";
case model_state_initialization_mode: return "model_state_initialization_mode";
case model_state_cs_step_complete: return "model_state_cs_step_complete";
case model_state_cs_step_in_progress: return "model_state_cs_step_in_progress";
case model_state_cs_step_failed: return "model_state_cs_step_failed";
case model_state_cs_step_canceled: return "model_state_cs_step_canceled";
case model_state_me_event_mode: return "model_state_me_event_mode (invalid!)";
case model_state_me_continuous_time_mode: return "model_state_me_continuous_time_mode (invalid!)";
case model_state_terminated: return "model_state_terminated";
case model_state_error: return "model_state_error";
case model_state_fatal: return "model_state_fatal";
}
}
return "Unknown";
}
static fmi2Boolean invalidNumber(ModelInstance *comp, const char *func, const char *arg, int n, int nExpected)
{
if (n != nExpected)
{
comp->state = model_state_error;
FILTERED_LOG(comp, fmi2Error, LOG_STATUSERROR, "%s: Invalid argument %s = %d. Expected %d.", func, arg, n, nExpected)
return fmi2True;
}
return fmi2False;
}
static fmi2Boolean invalidState(ModelInstance *comp, const char *func, int meStates, int csStates)
{
if (!comp)
return fmi2True;
if (isModelExchange(comp))
{
if (!(comp->state & meStates))
{
FILTERED_LOG(comp, fmi2Error, LOG_STATUSERROR, "%s: Illegal model exchange call sequence. %s is not allowed in %s state.", func, func, stateToString(comp))
comp->state = model_state_error;
return fmi2True;
}
}
if (isCoSimulation(comp))
{
if (!(comp->state & csStates))
{
FILTERED_LOG(comp, fmi2Error, LOG_STATUSERROR, "%s: Illegal co-simulation call sequence. %s is not allowed in %s state.", func, func, stateToString(comp))
comp->state = model_state_error;
return fmi2True;
}
}
return fmi2False;
}
static fmi2Boolean nullPointer(ModelInstance* comp, const char *func, const char *arg, const void *p)
{
if (!p)
{
comp->state = model_state_error;
FILTERED_LOG(comp, fmi2Error, LOG_STATUSERROR, "%s: Invalid argument %s = NULL.", func, arg)
return fmi2True;
}
return fmi2False;
}
static fmi2Boolean vrOutOfRange(ModelInstance *comp, const char *func, fmi2ValueReference vr, int end)
{
if (vr >= end) {
comp->state = model_state_error;
FILTERED_LOG(comp, fmi2Error, LOG_STATUSERROR, "%s: Illegal value reference %u.", func, vr)
return fmi2True;
}
return fmi2False;
}
static fmi2Status unsupportedFunction(ModelInstance *comp, const char *func)
{
FILTERED_LOG(comp, fmi2Error, LOG_STATUSERROR, "%s: Function not implemented.", func)
return fmi2Error;
}
// ---------------------------------------------------------------------------
// Private helpers logger
// ---------------------------------------------------------------------------
// return fmi2True if logging category is on. Else return fmi2False.
fmi2Boolean isCategoryLogged(ModelInstance *comp, int categoryIndex)
{
if (categoryIndex < NUMBER_OF_CATEGORIES && (comp->logCategories[categoryIndex] || comp->logCategories[LOG_ALL])) {
return fmi2True;
}
return fmi2False;
}
static void omc_assert_fmi_common(threadData_t *threadData, fmi2Status status, int categoryIndex, FILE_INFO info, const char *msg, va_list args)
{
const char *str;
ModelInstance* c = (ModelInstance*) threadData->localRoots[LOCAL_ROOT_FMI_DATA];
GC_vasprintf(&str, msg, args);
if (info.lineStart) {
FILTERED_LOG(c, status, categoryIndex, "%s:%d: %s", info.filename, info.lineStart, str)
} else {
FILTERED_LOG(c, status, categoryIndex, "%s", str)
}
}
static void omc_assert_fmi(threadData_t *threadData, FILE_INFO info, const char *msg, ...) __attribute__ ((noreturn));
static void omc_assert_fmi(threadData_t *threadData, FILE_INFO info, const char *msg, ...)
{
va_list args;
va_start(args, msg);
omc_assert_fmi_common(threadData, fmi2Error, LOG_STATUSERROR, info, msg, args);
va_end(args);
MMC_THROW_INTERNAL();
}
static void omc_assert_fmi_warning(FILE_INFO info, const char *msg, ...)
{
va_list args;
va_start(args, msg);
omc_assert_fmi_common((threadData_t*)pthread_getspecific(mmc_thread_data_key), fmi2Warning, LOG_STATUSWARNING, info, msg, args);
va_end(args);
}
// ---------------------------------------------------------------------------
// Private helpers functions
// ---------------------------------------------------------------------------
static inline void resetThreadData(ModelInstance* comp)
{
if (comp->threadDataParent) {
pthread_setspecific(mmc_thread_data_key, comp->threadDataParent);
}
/* Clear the extra memory pools */
omc_alloc_interface.collect_a_little();
}
static inline void setThreadData(ModelInstance* comp)
{
if (comp->threadDataParent) {
pthread_setspecific(mmc_thread_data_key, comp->threadData);
}
}
fmi2Status internalEventUpdate(fmi2Component c, fmi2EventInfo* eventInfo)
{
int i, done=0;
ModelInstance* comp = (ModelInstance *)c;
threadData_t *threadData = comp->threadData;
fmi2Real nextSampleEvent;
fmi2Boolean nextSampleEventDefined;
fmi2Boolean nextTimerDefined;
fmi2Real nextTimerActivationTime;
int syncRet;
if (nullPointer(comp, "internalEventUpdate", "eventInfo", eventInfo)) {
return fmi2Error;
}
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "internalEventUpdate: Start Event Update! Next Sample Event %g", eventInfo->nextEventTime)
setThreadData(comp);
/* try */
MMC_TRY_INTERNAL(simulationJumpBuffer)
#if !defined(OMC_NO_STATESELECTION)
if (stateSelection(comp->fmuData, comp->threadData, 1, 1)) {
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "internalEventUpdate: Need to iterate state values changed!")
/* if new set is calculated reinit the solver */
eventInfo->valuesOfContinuousStatesChanged = fmi2True;
}
#endif
storePreValues(comp->fmuData);
/* activate sample event */
for(i=0; i<comp->fmuData->modelData->nSamples; ++i) {
if (comp->fmuData->simulationInfo->nextSampleTimes[i] <= comp->fmuData->localData[0]->timeValue) {
comp->fmuData->simulationInfo->samples[i] = 1;
infoStreamPrint(LOG_EVENTS, 0, "[%ld] sample(%g, %g)", comp->fmuData->modelData->samplesInfo[i].index, comp->fmuData->modelData->samplesInfo[i].start, comp->fmuData->modelData->samplesInfo[i].interval);
}
}
comp->fmuData->callback->functionDAE(comp->fmuData, comp->threadData);
/* deactivate sample events */
for(i=0; i<comp->fmuData->modelData->nSamples; ++i) {
if (comp->fmuData->simulationInfo->samples[i]) {
comp->fmuData->simulationInfo->samples[i] = 0;
comp->fmuData->simulationInfo->nextSampleTimes[i] += comp->fmuData->modelData->samplesInfo[i].interval;
}
}
for(i=0; i<comp->fmuData->modelData->nSamples; ++i) {
if ((i == 0) || (comp->fmuData->simulationInfo->nextSampleTimes[i] < comp->fmuData->simulationInfo->nextSampleEvent)) {
comp->fmuData->simulationInfo->nextSampleEvent = comp->fmuData->simulationInfo->nextSampleTimes[i];
}
}
/* Handle clock timers */
syncRet = handleTimersFMI(comp->fmuData, comp->threadData, comp->fmuData->localData[0]->timeValue, &nextTimerDefined, &nextTimerActivationTime);
if (checkForDiscreteChanges(comp->fmuData, comp->threadData) || comp->fmuData->simulationInfo->needToIterate || checkRelations(comp->fmuData) || syncRet==2 ) {
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "internalEventUpdate: Need to iterate(discrete changes)!")
eventInfo->newDiscreteStatesNeeded = fmi2True;
eventInfo->valuesOfContinuousStatesChanged = fmi2True;
eventInfo->terminateSimulation = fmi2False;
} else {
eventInfo->newDiscreteStatesNeeded = fmi2False;
eventInfo->terminateSimulation = fmi2False;
}
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "internalEventUpdate: newDiscreteStatesNeeded %s",eventInfo->newDiscreteStatesNeeded?"true":"false");
/* due to an event overwrite old values */
overwriteOldSimulationData(comp->fmuData);
/* TODO: check the event iteration for relation
* in fmi2 import and export. This is an workaround,
* since the iteration seem not starting.
*/
storePreValues(comp->fmuData);
updateRelationsPre(comp->fmuData);
nextSampleEventDefined = getNextSampleTimeFMU(comp->fmuData, &nextSampleEvent);
/* Get next event time */
if (nextSampleEventDefined && !nextTimerDefined) {
eventInfo->nextEventTimeDefined = fmi2True;
eventInfo->nextEventTime = nextSampleEvent;
}
else if (!nextSampleEventDefined && nextTimerDefined) {
eventInfo->nextEventTimeDefined = fmi2True;
eventInfo->nextEventTime = nextTimerActivationTime;
}
else if (nextSampleEventDefined && nextTimerDefined) {
eventInfo->nextEventTimeDefined = fmi2True;
eventInfo->nextEventTime = fmin(nextSampleEvent,nextTimerActivationTime);
}
else {
if (eventInfo->nextEventTime <= comp->fmuData->localData[0]->timeValue) {
eventInfo->nextEventTimeDefined = fmi2False;
}
}
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "internalEventUpdate: Checked for Sample Events! Next Sample Event %g",eventInfo->nextEventTime)
done=1;
/* catch */
MMC_CATCH_INTERNAL(simulationJumpBuffer)
resetThreadData(comp);
if (done) {
return fmi2OK;
}
FILTERED_LOG(comp, fmi2Error, LOG_FMI2_CALL, "internalEventUpdate: terminated by an assertion.")
comp->_need_update = 1;
return fmi2Error;
}
fmi2Status internalEventIteration(fmi2Component c, fmi2EventInfo *eventInfo)
{
fmi2Status status = fmi2OK;
eventInfo->newDiscreteStatesNeeded = fmi2True;
eventInfo->terminateSimulation = fmi2False;
while (eventInfo->newDiscreteStatesNeeded && !eventInfo->terminateSimulation) {
status = internalEventUpdate((ModelInstance *)c, eventInfo);
}
return status;
}
/**
* @brief Helper function for fmi2GetXXX to update the component if needed.
*
* @param comp FMI component
* @param func Name of fmi2GetXXX function calling this function.
* @return fmi2Status Returns fmi2Error if an error was caught, fmi2OK otherwise.
*/
fmi2Status updateIfNeeded(ModelInstance *comp, const char *func)
{
/* Variables */
threadData_t *threadData = comp->threadData;
jmp_buf *old_jmp=threadData->mmc_jumper;
int success = 0;
if (comp->_need_update)
{
setThreadData(comp);
/* TRY */
#if !defined(OMC_EMCC)
MMC_TRY_INTERNAL(simulationJumpBuffer)
threadData->mmc_jumper = threadData->simulationJumpBuffer;
#endif
if (model_state_initialization_mode == comp->state)
{
initialization(comp->fmuData, comp->threadData, "fmi", "", 0.0);
}
else
{
comp->fmuData->callback->functionODE(comp->fmuData, comp->threadData);
overwriteOldSimulationData(comp->fmuData);
comp->fmuData->callback->functionAlgebraics(comp->fmuData, comp->threadData);
comp->fmuData->callback->output_function(comp->fmuData, comp->threadData);
comp->fmuData->callback->function_storeDelayed(comp->fmuData, comp->threadData);
comp->fmuData->callback->function_storeSpatialDistribution(comp->fmuData, threadData);
storePreValues(comp->fmuData);
}
comp->_need_update = 0;
success = 1;
/* CATCH */
#if !defined(OMC_EMCC)
MMC_CATCH_INTERNAL(simulationJumpBuffer)
threadData->mmc_jumper = old_jmp;
#endif
resetThreadData(comp);
if (!success)
{
FILTERED_LOG(comp, fmi2Error, LOG_FMI2_CALL, "%s: terminated by an assertion.", func)
// TODO: Check if fmi2Error or fmi2Discard should be returned
return fmi2Error;
}
}
return fmi2OK;
}
/***************************************************
Common Functions
****************************************************/
const char* fmi2GetTypesPlatform()
{
return fmi2TypesPlatform;
}
const char* fmi2GetVersion()
{
return fmi2Version;
}
fmi2Status fmi2SetDebugLogging(fmi2Component c, fmi2Boolean loggingOn, size_t nCategories, const fmi2String categories[])
{
int i, j;
ModelInstance *comp = (ModelInstance *)c;
if (invalidState(comp, "fmi2SetDebugLogging", model_state_instantiated|model_state_initialization_mode|model_state_me_event_mode|model_state_me_continuous_time_mode|model_state_terminated|model_state_error, model_state_instantiated|model_state_initialization_mode|model_state_cs_step_complete|model_state_cs_step_in_progress|model_state_cs_step_failed|model_state_cs_step_canceled|model_state_terminated|model_state_error))
return fmi2Error;
comp->loggingOn = loggingOn;
for (j = 0; j < NUMBER_OF_CATEGORIES; j++) {
comp->logCategories[j] = fmi2False;
}
for (i = 0; i < nCategories; i++) {
fmi2Boolean categoryFound = fmi2False;
for (j = 0; j < NUMBER_OF_CATEGORIES; j++) {
if (strcmp(logCategoriesNames[j], categories[i]) == 0) {
comp->logCategories[j] = loggingOn;
categoryFound = fmi2True;
break;
}
}
if (!categoryFound) {
comp->functions->logger(comp->componentEnvironment, comp->instanceName, fmi2Warning, logCategoriesNames[LOG_STATUSERROR],
"logging category '%s' is not supported by model", categories[i]);
}
}
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "fmi2SetDebugLogging")
return fmi2OK;
}
fmi2Component fmi2Instantiate(fmi2String instanceName, fmi2Type fmuType, fmi2String fmuGUID, fmi2String fmuResourceLocation, const fmi2CallbackFunctions* functions,
fmi2Boolean visible, fmi2Boolean loggingOn)
{
/*
TODO: We should set the interface, but we can't until it's no longer a global variable.
* The problem is that we might overwrite the main simulation's copy of the interface...
*/
threadData_t *threadDataParent = (threadData_t*) pthread_getspecific(mmc_thread_data_key);
ModelInstance *comp;
if (!functions->logger) {
return NULL;
}
if (!functions->allocateMemory || !functions->freeMemory) {
functions->logger(functions->componentEnvironment, instanceName, fmi2Error, "error", "fmi2Instantiate: Missing callback function.");
return NULL;
}
if (0==threadDataParent) {
/* We can only disable GC if the parent is not OM */
omc_alloc_interface = omc_alloc_interface_pooled;
/* TODO: omc_alloc_interface.malloc_uncollectable = functions->allocateMemory; // Note that the interface is wrong. Should pass threadData to all allocations instead, and have the interface in there. */
}
mmc_init_nogc();
omc_alloc_interface.init();
// ignoring arguments: fmuResourceLocation, visible
if (!instanceName || strlen(instanceName) == 0) {
functions->logger(functions->componentEnvironment, instanceName, fmi2Error, "error", "fmi2Instantiate: Missing instance name.");
return NULL;
}
if (strcmp(fmuGUID, MODEL_GUID) != 0) {
functions->logger(functions->componentEnvironment, instanceName, fmi2Error, "error", "fmi2Instantiate: Wrong GUID %s. Expected %s.", fmuGUID, MODEL_GUID);
return NULL;
}
comp = (ModelInstance *)functions->allocateMemory(1, sizeof(ModelInstance));
if (comp) {
DATA* fmudata = NULL;
MODEL_DATA* modelData = NULL;
SIMULATION_INFO* simInfo = NULL;
threadData_t *threadData = NULL;
int i;
comp->state = model_state_start_end;
comp->instanceName = (fmi2String)functions->allocateMemory(1 + strlen(instanceName), sizeof(char));
comp->GUID = (fmi2String)functions->allocateMemory(1 + strlen(fmuGUID), sizeof(char));
comp->functions = (fmi2CallbackFunctions*)functions->allocateMemory(1, sizeof(fmi2CallbackFunctions));
fmudata = (DATA *)functions->allocateMemory(1, sizeof(DATA));
modelData = (MODEL_DATA *)functions->allocateMemory(1, sizeof(MODEL_DATA));
simInfo = (SIMULATION_INFO *)functions->allocateMemory(1, sizeof(SIMULATION_INFO));
fmudata->modelData = modelData;
fmudata->simulationInfo = simInfo;
threadData = (threadData_t *)functions->allocateMemory(1, sizeof(threadData_t));
memset(threadData, 0, sizeof(threadData_t));
/*
pthread_key_create(&fmu2_thread_data_key,NULL);
pthread_setspecific(fmu2_thread_data_key, threadData);
*/
comp->threadData = threadData;
comp->threadDataParent = threadDataParent;
comp->fmuData = fmudata;
threadData->localRoots[LOCAL_ROOT_FMI_DATA] = comp;
if (!comp->fmuData) {
functions->logger(functions->componentEnvironment, instanceName, fmi2Error, "error", "fmi2Instantiate: Could not initialize the global data structure file.");
return NULL;
}
// set all categories to on or off. fmi2SetDebugLogging should be called to choose specific categories.
for (i = 0; i < NUMBER_OF_CATEGORIES; i++) {
comp->logCategories[i] = loggingOn;
}
}
if (!comp || !comp->instanceName || !comp->GUID || !comp->functions) {
functions->logger(functions->componentEnvironment, instanceName, fmi2Error, "error", "fmi2Instantiate: Out of memory.");
return NULL;
}
pthread_setspecific(mmc_thread_data_key, comp->threadData);
omc_assert = omc_assert_fmi;
omc_assert_warning = omc_assert_fmi_warning;
strcpy((char*)comp->instanceName, (const char*)instanceName);
comp->type = fmuType;
strcpy((char*)comp->GUID, (const char*)fmuGUID);
memcpy((void*)comp->functions, (void*)functions, sizeof(fmi2CallbackFunctions));
comp->componentEnvironment = functions->componentEnvironment;
comp->loggingOn = loggingOn;
comp->state = model_state_instantiated;
/* Add the resourcesDir */
fmuResourceLocation = OpenModelica_parseFmuResourcePath(fmuResourceLocation);
if (fmuResourceLocation) {
comp->fmuData->modelData->resourcesDir = functions->allocateMemory(1 + strlen(fmuResourceLocation), sizeof(char));
strcpy(comp->fmuData->modelData->resourcesDir, fmuResourceLocation);
} else {
FILTERED_LOG(comp, fmi2OK, LOG_STATUSWARNING, "fmi2Instantiate: Ignoring unknown resource URI: %s", fmuResourceLocation)
}
/* initialize modelData */
useStream[LOG_STDOUT] = 1;
useStream[LOG_ASSERT] = 1;
fmu2_model_interface_setupDataStruc(comp->fmuData, comp->threadData);
initializeDataStruc(comp->fmuData, comp->threadData);
/* setup model data with default start data */
setDefaultStartValues(comp);
setAllParamsToStart(comp->fmuData);
setAllVarsToStart(comp->fmuData);
comp->fmuData->callback->read_input_fmu(comp->fmuData->modelData, comp->fmuData->simulationInfo);
#if !defined(OMC_MINIMAL_METADATA)
modelInfoInit(&(comp->fmuData->modelData->modelDataXml));
#endif
#if !defined(OMC_NUM_NONLINEAR_SYSTEMS) || OMC_NUM_NONLINEAR_SYSTEMS>0
/* allocate memory for non-linear system solvers */
initializeNonlinearSystems(comp->fmuData, comp->threadData);
#endif
#if !defined(OMC_NUM_LINEAR_SYSTEMS) || OMC_NUM_LINEAR_SYSTEMS>0
/* allocate memory for non-linear system solvers */
initializeLinearSystems(comp->fmuData, comp->threadData);
#endif
#if !defined(OMC_NUM_MIXED_SYSTEMS) || OMC_NUM_MIXED_SYSTEMS>0
/* allocate memory for mixed system solvers */
initializeMixedSystems(comp->fmuData, comp->threadData);
#endif
#if !defined(OMC_NO_STATESELECTION)
/* allocate memory for state selection */
initializeStateSetJacobians(comp->fmuData, comp->threadData);
#endif
/* allocate memory for Jacobian */
comp->_has_jacobian = 0;
comp->fmiDerJac = NULL;
if (comp->fmuData->callback->initialPartialFMIDER != NULL)
{
comp->fmiDerJac = (ANALYTIC_JACOBIAN*) functions->allocateMemory(1, sizeof(ANALYTIC_JACOBIAN));
if (! comp->fmuData->callback->initialPartialFMIDER(comp->fmuData, comp->threadData, comp->fmiDerJac))
{
comp->_has_jacobian = 1;
}
}
/* allocate memory for Jacobian during initialization DAE */
comp->_has_jacobian_intialization = 0;
comp->fmiDerJacInitialization = NULL;
if (comp->fmuData->callback->initialPartialFMIDERINIT != NULL)
{
comp->fmiDerJacInitialization = (ANALYTIC_JACOBIAN*) functions->allocateMemory(1, sizeof(ANALYTIC_JACOBIAN));
if (! comp->fmuData->callback->initialPartialFMIDERINIT(comp->fmuData, comp->threadData, comp->fmiDerJacInitialization))
{
comp->_has_jacobian_intialization = 1;
}
}
// int cols = comp->fmiDerJac->sizeCols;
// int rows = comp->fmiDerJac->sizeRows;
// printf("\nFMIDER number of rows and colums");
// printf("\nNumber of rows : %i", rows);
// printf("\nNumber of columns: %i", cols);
// printf("\n");
// int cols_ = comp->fmiDerJacInitialization->sizeCols;
// int rows_ = comp->fmiDerJacInitialization->sizeRows;
// printf("\nFMIDER INITIALIZATION number of rows and colums");
// printf("\nNumber of rows : %i", rows_);
// printf("\nNumber of columns: %i", cols_);
// printf("\n");
comp->states = (fmi2Real*)functions->allocateMemory(NUMBER_OF_STATES, sizeof(fmi2Real));
comp->states_der = (fmi2Real*)functions->allocateMemory(NUMBER_OF_STATES, sizeof(fmi2Real));
comp->event_indicators = (fmi2Real*)functions->allocateMemory(NUMBER_OF_EVENT_INDICATORS, sizeof(fmi2Real));
comp->event_indicators_prev = (fmi2Real*)functions->allocateMemory(NUMBER_OF_EVENT_INDICATORS, sizeof(fmi2Real));
if (NUMBER_OF_REAL_INPUTS == 0)
comp->input_real_derivative = NULL; // initialize to 0
else
comp->input_real_derivative = (fmi2Real*)functions->allocateMemory(NUMBER_OF_REAL_INPUTS, sizeof(fmi2Real));
comp->_need_update = 1;
/* Initialize solverInfo */
if (fmi2CoSimulation == comp->type) {
FMI2CS_initializeSolverData(comp);
} else {
comp->solverInfo = NULL;
}
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "fmi2Instantiate: GUID=%s", fmuGUID)
resetThreadData(comp);
return comp;
}
void fmi2FreeInstance(fmi2Component c)
{
ModelInstance *comp = (ModelInstance *)c;
fmi2CallbackFreeMemory freeMemory = comp->functions->freeMemory;
int meStates = model_state_instantiated|model_state_initialization_mode|model_state_me_event_mode|model_state_me_continuous_time_mode|model_state_terminated|model_state_error;
int csStates = model_state_instantiated|model_state_initialization_mode|model_state_cs_step_complete|model_state_cs_step_failed|model_state_cs_step_canceled|model_state_terminated|model_state_error;
if (invalidState(comp, "fmi2FreeInstance", meStates, csStates))
return;
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "fmi2FreeInstance")
/* call external objects destructors */
comp->fmuData->callback->callExternalObjectDestructors(comp->fmuData, comp->threadData);
#if !defined(OMC_NUM_NONLINEAR_SYSTEMS) || OMC_NUM_NONLINEAR_SYSTEMS>0
/* free nonlinear system data */
freeNonlinearSystems(comp->fmuData, comp->threadData);
#endif
#if !defined(OMC_NUM_MIXED_SYSTEMS) || OMC_NUM_MIXED_SYSTEMS>0
/* free mixed system data */
freeMixedSystems(comp->fmuData, comp->threadData);
#endif
#if !defined(OMC_NUM_LINEAR_SYSTEMS) || OMC_NUM_LINEAR_SYSTEMS>0
/* free linear system data */
freeLinearSystems(comp->fmuData, comp->threadData);
#endif
/* free data struct */
deInitializeDataStruc(comp->fmuData); /* TODO: Use comp->functions->freeMemory inside deInitializeDataStruc to be FMI comform */
/* Free jacobian data */
if (comp->_has_jacobian == 1) {
/* TODO: Use comp->functions->freeMemory insted of free,
* but generated code uses malloc / calloc instead of comp->functions->allocateMemory */
free(comp->fmiDerJac->seedVars); comp->fmiDerJac->seedVars = NULL;
free(comp->fmiDerJac->resultVars); comp->fmiDerJac->resultVars = NULL;
free(comp->fmiDerJac->tmpVars); comp->fmiDerJac->tmpVars = NULL;
free(comp->fmiDerJac->sparsePattern->leadindex); comp->fmiDerJac->sparsePattern->leadindex = NULL;
free(comp->fmiDerJac->sparsePattern->index); comp->fmiDerJac->sparsePattern->index = NULL;
free(comp->fmiDerJac->sparsePattern->colorCols); comp->fmiDerJac->sparsePattern->colorCols = NULL;
free(comp->fmiDerJac->sparsePattern); comp->fmiDerJac->sparsePattern = NULL;
freeMemory(comp->fmiDerJac); comp->fmiDerJac=NULL;
}
/* Free jacobian data */
if (comp->_has_jacobian_intialization == 1) {
/* TODO: Use comp->functions->freeMemory insted of free,
* but generated code uses malloc / calloc instead of comp->functions->allocateMemory */
free(comp->fmiDerJacInitialization->seedVars); comp->fmiDerJacInitialization->seedVars = NULL;
free(comp->fmiDerJacInitialization->resultVars); comp->fmiDerJacInitialization->resultVars = NULL;
free(comp->fmiDerJacInitialization->tmpVars); comp->fmiDerJacInitialization->tmpVars = NULL;
free(comp->fmiDerJacInitialization->sparsePattern->leadindex); comp->fmiDerJacInitialization->sparsePattern->leadindex = NULL;
free(comp->fmiDerJacInitialization->sparsePattern->index); comp->fmiDerJacInitialization->sparsePattern->index = NULL;
free(comp->fmiDerJacInitialization->sparsePattern->colorCols); comp->fmiDerJacInitialization->sparsePattern->colorCols = NULL;
free(comp->fmiDerJacInitialization->sparsePattern); comp->fmiDerJacInitialization->sparsePattern = NULL;
freeMemory(comp->fmiDerJacInitialization); comp->fmiDerJacInitialization=NULL;
}
freeMemory(comp->states); comp->states = NULL;
freeMemory(comp->states_der); comp->states_der = NULL;
freeMemory(comp->event_indicators); comp->event_indicators = NULL;
freeMemory(comp->event_indicators_prev); comp->event_indicators_prev = NULL;
freeMemory(comp->input_real_derivative); comp->input_real_derivative = NULL;
freeMemory(comp->fmuData->modelData->resourcesDir);
if (comp->solverInfo) {
FMI2CS_deInitializeSolverData(comp);
}
/* free simuation data */
freeMemory(comp->fmuData->modelData);
freeMemory(comp->fmuData->simulationInfo);
/* free fmuData */
freeMemory(comp->threadData);
freeMemory(comp->fmuData);
/* free instanceName & GUID */
if (comp->instanceName) freeMemory((void*)comp->instanceName);
if (comp->GUID) freeMemory((void*)comp->GUID);
if (comp->functions) freeMemory((void*)comp->functions);
/* free comp */
freeMemory(comp);
free_memory_pool();
}
fmi2Status fmi2SetupExperiment(fmi2Component c, fmi2Boolean toleranceDefined, fmi2Real tolerance, fmi2Real startTime, fmi2Boolean stopTimeDefined, fmi2Real stopTime)
{
ModelInstance *comp = (ModelInstance *)c;
if (invalidState(comp, "fmi2SetupExperiment", model_state_instantiated, model_state_instantiated))
return fmi2Error;
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "fmi2SetupExperiment: toleranceDefined=%d tolerance=%g startTime=%g stopTimeDefined=%d stopTime=%g", toleranceDefined, tolerance,
startTime, stopTimeDefined, stopTime)
comp->toleranceDefined = toleranceDefined;
comp->tolerance = tolerance;
comp->startTime = startTime;
comp->stopTimeDefined = stopTimeDefined;
comp->stopTime = stopTime;
return fmi2OK;
}
fmi2Status fmi2EnterInitializationMode(fmi2Component c)
{
ModelInstance *comp = (ModelInstance *)c;
if (invalidState(comp, "fmi2EnterInitializationMode", model_state_instantiated, model_state_instantiated))
return fmi2Error;
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "fmi2EnterInitializationMode...")
setZCtol(comp->tolerance); /* set zero-crossing tolerance */
setStartValues(comp);
copyStartValuestoInitValues(comp->fmuData);
comp->state = model_state_initialization_mode;
return fmi2OK;
}
fmi2Status fmi2ExitInitializationMode(fmi2Component c)
{
fmi2Status res = fmi2Error;
ModelInstance *comp = (ModelInstance *)c;
threadData_t *threadData = comp->threadData;
jmp_buf *old_jmp = threadData->mmc_jumper;
fmi2Real nextSampleEvent;
fmi2Boolean nextSampleEventDefined;
int done=0;
threadData->currentErrorStage = ERROR_SIMULATION;
if (invalidState(comp, "fmi2ExitInitializationMode", model_state_initialization_mode, model_state_initialization_mode))
return fmi2Error;
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "fmi2ExitInitializationMode...")
setThreadData(comp);
/* try */
MMC_TRY_INTERNAL(simulationJumpBuffer)
threadData->mmc_jumper = threadData->simulationJumpBuffer;
if (comp->_need_update)
{
if (initialization(comp->fmuData, comp->threadData, "fmi", "", 0.0))
{
comp->state = model_state_error;
resetThreadData(comp);
FILTERED_LOG(comp, fmi2Error, LOG_FMI2_CALL, "fmi2EnterInitializationMode: failed")
return fmi2Error;
}
}
/* use defined stopTime, if stopTimeDefined is given to calculate the sample events beforehand.
* TODO: when stopTime is not defined we use an arbitrary constant 100.0, maybe issue a warning
*/
initSample(comp->fmuData, comp->threadData, comp->fmuData->localData[0]->timeValue, comp->stopTimeDefined ? comp->stopTime : 100.0 /* default stopTime */);
/* overwrite old values due to an event */
overwriteOldSimulationData(comp->fmuData);
comp->eventInfo.terminateSimulation = fmi2False;
comp->eventInfo.valuesOfContinuousStatesChanged = fmi2True;
/* get next event time (sample calls) */
nextSampleEventDefined = getNextSampleTimeFMU(comp->fmuData, &nextSampleEvent);
if (nextSampleEventDefined)
{
comp->eventInfo.nextEventTimeDefined = fmi2True;
comp->eventInfo.nextEventTime = nextSampleEvent;
internalEventUpdate(comp, &(comp->eventInfo));
}
else
{
comp->eventInfo.nextEventTimeDefined = fmi2False;
}
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "fmi2EnterInitializationMode: succeed")
res = fmi2OK;
done = 1;
/* catch */
MMC_CATCH_INTERNAL(simulationJumpBuffer)
threadData->mmc_jumper = old_jmp;
if (!done)
{
FILTERED_LOG(comp, fmi2Error, LOG_FMI2_CALL, "fmi2EnterInitializationMode: terminated by an assertion.")
}
comp->state = isCoSimulation(comp) ? model_state_cs_step_complete : model_state_me_event_mode;
resetThreadData(comp);
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "fmi2ExitInitializationMode: succeed")
return res;
}
/*
* fmi2Status fmi2Terminate(fmi2Component c);
* Informs the FMU that the simulation run is terminated. After calling this function, the final
* values of all variables can be inquired with the fmi2GetXXX(..) functions. It is not allowed
* to call this function after one of the functions returned with a status flag of fmi2Error or
* fmi2Fatal.
*
*/
fmi2Status fmi2Terminate(fmi2Component c)
{
ModelInstance *comp = (ModelInstance *)c;
if (invalidState(comp, "fmi2Terminate", model_state_me_event_mode|model_state_me_continuous_time_mode, model_state_cs_step_complete|model_state_cs_step_failed))
return fmi2Error;
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "fmi2Terminate")
setThreadData(comp);
comp->state = model_state_terminated;
resetThreadData(comp);
return fmi2OK;
}
/*!
* Is called by the environment to reset the FMU after a simulation run. Before starting a new run, fmi2EnterInitializationMode has to be called.
*/
fmi2Status fmi2Reset(fmi2Component c)
{
ModelInstance* comp = (ModelInstance *)c;
if (invalidState(comp, "fmi2Reset", model_state_instantiated|model_state_initialization_mode|model_state_me_event_mode|model_state_me_continuous_time_mode|model_state_terminated|model_state_error, model_state_instantiated|model_state_initialization_mode|model_state_cs_step_complete|model_state_cs_step_failed|model_state_cs_step_canceled|model_state_terminated|model_state_error))
return fmi2Error;
FILTERED_LOG(comp, fmi2OK, LOG_FMI2_CALL, "fmi2Reset")
setThreadData(comp);
/* Free modelData */
if (!(comp->state & model_state_terminated)) {
/* call external objects destructors */
comp->fmuData->callback->callExternalObjectDestructors(comp->fmuData, comp->threadData);
#if !defined(OMC_NUM_NONLINEAR_SYSTEMS) || OMC_NUM_NONLINEAR_SYSTEMS>0
/* free nonlinear system data */
freeNonlinearSystems(comp->fmuData, comp->threadData);
#endif
#if !defined(OMC_NUM_MIXED_SYSTEMS) || OMC_NUM_MIXED_SYSTEMS>0
/* free mixed system data */
freeMixedSystems(comp->fmuData, comp->threadData);
#endif
#if !defined(OMC_NUM_LINEAR_SYSTEMS) || OMC_NUM_LINEAR_SYSTEMS>0
/* free linear system data */
freeLinearSystems(comp->fmuData, comp->threadData);
#endif
/* free data struct */
deInitializeDataStruc(comp->fmuData);
}
/* Free CS simulator */
if (comp->solverInfo) {
FMI2CS_deInitializeSolverData(comp);
}
/* Initialize modelData */
useStream[LOG_STDOUT] = 1;
useStream[LOG_ASSERT] = 1;
fmu2_model_interface_setupDataStruc(comp->fmuData, comp->threadData);
initializeDataStruc(comp->fmuData, comp->threadData);
/* reset model data with default start data */
setDefaultStartValues(comp);
setAllParamsToStart(comp->fmuData);
setAllVarsToStart(comp->fmuData);
comp->fmuData->callback->read_input_fmu(comp->fmuData->modelData, comp->fmuData->simulationInfo);
#if !defined(OMC_MINIMAL_METADATA)
modelInfoInit(&(comp->fmuData->modelData->modelDataXml));
#endif
#if !defined(OMC_NUM_NONLINEAR_SYSTEMS) || OMC_NUM_NONLINEAR_SYSTEMS>0
/* allocate memory for non-linear system solvers */
initializeNonlinearSystems(comp->fmuData, comp->threadData);
#endif
#if !defined(OMC_NUM_LINEAR_SYSTEMS) || OMC_NUM_LINEAR_SYSTEMS>0
/* allocate memory for non-linear system solvers */
initializeLinearSystems(comp->fmuData, comp->threadData);
#endif
#if !defined(OMC_NUM_MIXED_SYSTEMS) || OMC_NUM_MIXED_SYSTEMS>0
/* allocate memory for mixed system solvers */
initializeMixedSystems(comp->fmuData, comp->threadData);
#endif
#if !defined(OMC_NO_STATESELECTION)
/* allocate memory for state selection */
initializeStateSetJacobians(comp->fmuData, comp->threadData);
#endif
/* Initialize solverInfo */
if (fmi2CoSimulation == comp->type) {
FMI2CS_initializeSolverData(comp);
} else {
comp->solverInfo = NULL;
}
comp->_need_update = 1;
comp->state = model_state_instantiated;
resetThreadData(comp);
return fmi2OK;
}
fmi2Status fmi2GetReal(fmi2Component c, const fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
{
/* Variables */
int i;
ModelInstance *comp = (ModelInstance*)c;
// Model exchange
// - initialization mode (2) for a variable with causality = "output", or continuous-time states or state derivatives
// - event mode
// - continuous-time mode
// - terminated
// - error (7) always, but retrieved values are usable for debugging only
int meStates = model_state_initialization_mode|model_state_me_event_mode|model_state_me_continuous_time_mode|model_state_terminated|model_state_error;
// Co-simulation
// - initialization mode (2) for a variable with causality = "output" or continuous-time states or state derivatives (if element <Derivatives> is present)
// - stepComplete
// - stepFailed (8) always, but if status is other than fmi2Terminated, retrieved values are useable for debugging only
// - stepCanceled (7) always, but retrieved values are usable for debugging only
// - terminated
// - error (7) always, but retrieved values are usable for debugging only