integration.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. /* Implementation of integration.h */
  2. #include "conf.h"
  3. #include "util.h"
  4. #include "integration.h"
  5. #include "jac.h"
  6. #include "result.h"
  7. #include "fmiFunctions_fwd.h"
  8. /* Sundials */
  9. #include <cvode/cvode.h>
  10. #include <cvode/cvode_dense.h>
  11. #include <sundials/sundials_math.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <time.h>
  15. #include <math.h>
  16. #include <assert.h>
  17. /* ----------------- constants ----------------- */
  18. #define RTOL_DEFAULT (1.0e-5) /* scalar relative tolerance */
  19. /* when testing with Modelica wrapper, the external step size may be large due to
  20. variable step size solvers being used externally */
  21. #define MAX_STEPS 100000 /* maximum number if internal steps for a time step */
  22. #define MAX_FAILURES 15 /* maximum number of error test failures permitted in attempting one step */
  23. #define MAX_NON_LIN_ITERS 3 /* maximum number of non-linear iterations */
  24. /* for Sundials */
  25. /* the safety factor used in the nonlinear convergence test */
  26. #define NON_LINEAR_CONV_TEST_COEFF 1e-1
  27. /* ----------------- macros ----------------- */
  28. #define CALL_SET(function, val) \
  29. flag = function(cvode_mem, val); \
  30. if (util_check_flag(&flag, #function, 1, comp)) goto fail \
  31. #define CALL_SET2(function, val1, val2) \
  32. flag = function(cvode_mem, val1, val2); \
  33. if (util_check_flag(&flag, #function, 1, comp)) goto fail \
  34. #define GET_STATISTIC(function, var) \
  35. flag = function(comp->iData->cvode_mem, &var); \
  36. if (util_check_flag(&flag, #function, 1, comp)) { \
  37. var = -1; \
  38. }
  39. #define INT_RESULT_SAMPLE(atEvent) \
  40. if (comp->storeResult == FMITrue) { \
  41. result_sample(comp, atEvent); \
  42. }
  43. /* ----------------- local function declarations ----------------- */
  44. /* clones integration data */
  45. static IntegrationStatus clone_data(Component* target, Component* source);
  46. /* frees integration data */
  47. static void free_data(Component* comp, Component* target);
  48. /* root function used for event indicators */
  49. static int g(realtype t, N_Vector y, realtype *gout, void *user_data);
  50. /* step event check function */
  51. static int check_step_event(void* user_data);
  52. /* error message handler */
  53. static void err_msg_handler(int error_code, const char *module,
  54. const char *function, char *msg,
  55. void *eh_data);
  56. /* ----------------- local variables ----------------- */
  57. static size_t nGroups;
  58. /* ----------------- external variables ----------------- */
  59. extern int QJacobianCG_[];
  60. /* ----------------- external function declarations ----------------- */
  61. extern void initializeData2(double* t);
  62. /* ----------------- function definitions ----------------- */
  63. /* ------------------------------------------------------ */
  64. DYMOLA_STATIC IntegrationStatus integration_setup(FMIComponent c, FMIReal relTol)
  65. {
  66. Component* comp = (Component*) c;
  67. realtype* abstol_data;
  68. void *cvode_mem;
  69. int flag;
  70. size_t i;
  71. IntegrationData* iData;
  72. assert(comp->iData == NULL);
  73. assert(sizeof(realtype) == sizeof(FMIReal));
  74. if (comp->nStates == 0) {
  75. /* Add dummy state fo simplify code and avoid extra conditions for the vast majority of models.
  76. Note that concerned arrays already have 1 allocated element due to guarding offset 1 during instantiation. */
  77. comp->nStates = 1;
  78. comp->states[0] = 0;
  79. comp->statesNominal[0] = 1;
  80. }
  81. if (relTol <= 0) {
  82. relTol = RTOL_DEFAULT;
  83. }
  84. #ifdef FMI_2
  85. comp->iData = (IntegrationData*) comp->functions->allocateMemory(1, sizeof(IntegrationData));
  86. #else
  87. comp->iData = (IntegrationData*) comp->functions.allocateMemory(1, sizeof(IntegrationData));
  88. #endif
  89. if (comp->iData == NULL) goto fail;
  90. iData = comp->iData;
  91. iData->y = iData->abstol = iData->ewt = iData->tmp1 = iData->tmp2 = NULL;
  92. iData->cvode_mem = NULL;
  93. /* create serial vector from states */
  94. assert(comp->nStates > 0);
  95. /* it turns out using N_VNew_Serial(comp->nStates) gives worse accuracy for some reason */
  96. iData->y = N_VMake_Serial((long)comp->nStates, comp->states);
  97. if (util_check_flag((void *)(iData->y), "N_VMake_Serial", 0, comp)) goto fail;
  98. /* Backward Differentiation Formula and the use of a Newton iteration */
  99. cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON);
  100. if (util_check_flag((void *)cvode_mem, "CVodeCreate", 0, comp)) goto fail;
  101. /* initialize the integrator memory and specify the
  102. user's right hand side function in y'=f(t,y), the inital time and
  103. the initial dependent variable vector y */
  104. flag = CVodeInit(cvode_mem, jac_f, comp->time, iData->y);
  105. if (util_check_flag(&flag, "CVodeInit", 1, comp)) goto fail;
  106. /* need to provide the context from FMI */
  107. CALL_SET(CVodeSetUserData, comp);
  108. /* specify the scalar and absolute tolerances */
  109. iData->abstol = N_VNew_Serial((long)comp->nStates);
  110. if (util_check_flag((void *)(iData->abstol), "N_VNew_Serial", 0, comp)) goto fail;
  111. abstol_data = N_VGetArrayPointer(iData->abstol);
  112. for (i = 0; i < comp->nStates; i++) {
  113. abstol_data[i] = relTol * comp->statesNominal[i];
  114. }
  115. CALL_SET2(CVodeSVtolerances, relTol, iData->abstol);
  116. /* specify the safety factor used in the nonlinear convergence test */
  117. CALL_SET(CVodeSetNonlinConvCoef, NON_LINEAR_CONV_TEST_COEFF);
  118. /* specify the root function to handle event indicators */
  119. CALL_SET2(CVodeRootInit, (long)comp->nCross, g);
  120. /* specify step event detection function */
  121. CALL_SET(CVodeStepRootInit, check_step_event);
  122. nGroups = (size_t) QJacobianCG_[0];
  123. jac_setup(nGroups);
  124. /* use the CVDENSE dense linear solver */
  125. CALL_SET(CVDense, (int)comp->nStates);
  126. /* use own Jacobian function to enable use of grouping */
  127. CALL_SET(CVDlsSetDenseJacFn, jac_Jacobian);
  128. /* set maximum number of internal steps for a time step */
  129. CALL_SET(CVodeSetMaxNumSteps, MAX_STEPS);
  130. /* set maximum no. of nonlinear iterations */
  131. CALL_SET(CVodeSetMaxNonlinIters, MAX_NON_LIN_ITERS);
  132. /* set maximum number of error test failures permitted in attempting one step */
  133. CALL_SET(CVodeSetMaxErrTestFails, MAX_FAILURES);
  134. iData->tmp1 = N_VNew_Serial((long)comp->nStates);
  135. iData->tmp2 = N_VNew_Serial((long)comp->nStates);
  136. if (util_check_flag((void *)(iData->tmp1), "N_VNew_Serial", 0, comp) ||
  137. util_check_flag((void *)(iData->tmp2), "N_VNew_Serial", 0, comp)) {
  138. goto fail;
  139. }
  140. N_VConst(0.0,iData->tmp1);
  141. N_VConst(0.0,iData->tmp2);
  142. iData->cvode_mem = cvode_mem;
  143. iData->ewt = N_VNew_Serial((long)comp->nStates);
  144. if (util_check_flag((void *)(iData->ewt), "N_VNew_Serial", 0, comp)) goto fail;
  145. N_VConst(0.0,iData->ewt);
  146. CALL_SET2(CVodeSetErrHandlerFn, err_msg_handler, comp);
  147. #ifdef FMU_VERBOSITY
  148. if (nGroups > 0) {
  149. util_logger(c, comp->instanceName, FMIOK, "",
  150. "grouping will be used when computing J (N = %d)", comp->nStates);
  151. } else {
  152. util_logger(c, comp->instanceName, FMIOK, "",
  153. "grouping will not be used when computing J (N = %d)", comp->nStates);
  154. }
  155. #endif
  156. /* turned out to be faster to set to 0 */
  157. comp->istruct->mSolverHandleEq = 0;
  158. /* initialize input derivatives handling */
  159. iData->inputDerivatives = iData->inputsT0 = NULL;
  160. #ifdef FMI_2
  161. iData->inputDerivatives = (FMIReal*) comp->functions->allocateMemory(comp->nIn + 1, sizeof(FMIReal));
  162. iData->inputsT0 = (FMIReal*) comp->functions->allocateMemory(comp->nIn + 1, sizeof(FMIReal));
  163. #else
  164. iData->inputDerivatives = (FMIReal*) comp->functions.allocateMemory(comp->nIn + 1, sizeof(FMIReal));
  165. iData->inputsT0 = (FMIReal*) comp->functions.allocateMemory(comp->nIn + 1, sizeof(FMIReal));
  166. #endif
  167. /* initialize output derivatives handling */
  168. iData->outputsPrev = NULL;
  169. #ifdef FMI_2
  170. iData->outputsPrev = (FMIReal*) comp->functions->allocateMemory(comp->nOut + 1, sizeof(FMIReal));
  171. #else
  172. iData->outputsPrev = (FMIReal*) comp->functions.allocateMemory(comp->nOut + 1, sizeof(FMIReal));
  173. #endif
  174. if (iData->inputDerivatives == NULL || iData->inputsT0 == NULL || iData->outputsPrev == NULL) {
  175. goto fail;
  176. }
  177. iData->useDerivatives = 0;
  178. /* initialize statistics */
  179. iData->stat.JacCalls = 0;
  180. iData->stat.fCalls = 0;
  181. iData->stat.fTime = 0;
  182. iData->stat.gTime = 0;
  183. iData->stat.totTime = (float) clock();
  184. iData->stat.rejSteps = 0;
  185. iData->stat.rejIntSteps = 0;
  186. iData->stat.rejFCalls = 0;
  187. iData->stat.rejFTime = 0;
  188. iData->stat.rejJacCalls = 0;
  189. #ifdef SAVE_STATE_SUNDIALS
  190. iData->cvode_called = 0;
  191. #endif
  192. return integrationOK;
  193. fail:
  194. integration_teardown(comp);
  195. return integrationError;
  196. }
  197. /* ------------------------------------------------------ */
  198. DYMOLA_STATIC void integration_teardown(FMIComponent c)
  199. {
  200. Component* comp = (Component*) c;
  201. if (comp == NULL || comp->iData == NULL) {
  202. return;
  203. }
  204. #ifdef LOG_STATISTICS
  205. /* log statistics */
  206. if (comp->iData->cvode_mem != NULL) {
  207. int flag;
  208. long nniters, nncfails, ngevals, njevals;
  209. realtype tolsfac;
  210. IntegrationData* iData = comp->iData;
  211. Statistics* stat = &(comp->iData->stat);
  212. stat->totTime = clock() - stat->totTime;
  213. stat->totTime /= CLOCKS_PER_SEC;
  214. stat->fTime /= CLOCKS_PER_SEC;
  215. stat->gTime /= CLOCKS_PER_SEC;
  216. stat->rejFTime /= CLOCKS_PER_SEC;
  217. GET_STATISTIC(CVodeGetNumNonlinSolvIters, nniters);
  218. GET_STATISTIC(CVodeGetNumNonlinSolvConvFails, nncfails);
  219. GET_STATISTIC(CVodeGetNumGEvals, ngevals);
  220. GET_STATISTIC(CVDlsGetNumJacEvals, njevals);
  221. GET_STATISTIC(CVodeGetTolScaleFactor, tolsfac);
  222. util_logger(comp, comp->instanceName, FMIOK, "",
  223. "Sundials CVode Statistics\n"
  224. " Stop time : %.2f s\n"
  225. " Simulation time : %.2f s\n"
  226. " Number of external steps : %d\n"
  227. " Number of internal steps : %d\n"
  228. " Number of non-linear iterations : %ld\n"
  229. " Number of non-linear convergence failures: %ld\n"
  230. " Number of f function evaluations : %d (%.2f s)\n"
  231. " Number of g function evaluations : %ld (%.2f s)\n"
  232. " Number of Jacobian-evaluations (direct) : %ld\n"
  233. " Number of Jac function evaluations : %d\n"
  234. " Suggested tolerance scale factor : %.1f\n"
  235. " Grouping used : %s",
  236. comp->time, stat->totTime, stat->steps, stat->intSteps, nniters, nncfails,
  237. stat->fCalls, stat->fTime,
  238. ngevals, stat->gTime, njevals, stat->JacCalls, tolsfac,
  239. nGroups > 0 ? "yes" : "no");
  240. #ifdef FMI_2
  241. util_logger(comp, comp->instanceName, FMIOK, "",
  242. "Rejected count\n"
  243. " Number of external steps : %d\n"
  244. " Number of internal steps : %d\n"
  245. " Number of f function evaluations : %d (%.2f s)\n"
  246. " Number of Jac function evaluations : %d\n",
  247. stat->rejSteps, stat->rejIntSteps,
  248. stat->rejFCalls, stat->rejFTime, stat->rejJacCalls);
  249. #endif
  250. }
  251. #endif /* LOG_STATISTICS */
  252. free_data(comp, comp);
  253. }
  254. #ifdef SAVE_STATE_SUNDIALS
  255. #include "../src/cvode/cvode_impl.h"
  256. #endif
  257. /* ------------------------------------------------------ */
  258. DYMOLA_STATIC IntegrationStatus integration_step(Component* comp, FMIReal tout)
  259. {
  260. IntegrationData* iData = comp->iData;
  261. void* cvode_mem = iData->cvode_mem;
  262. /* initialize in case tret needs to be reported before set by Sundials */
  263. realtype tret = comp->time;
  264. int done = 0;
  265. assert(comp->nStates > 0);
  266. assert(tout > comp->time);
  267. while (!done) {
  268. int flag;
  269. /* store previous outputs for use in fmiGetRealOutputDerivatives */
  270. if (!util_refresh_cache(comp, iDemandOutput, "fetching current output", NULL)) {
  271. memcpy(iData->outputsPrev, comp->outputs, comp->nOut * sizeof(FMIReal));
  272. iData->timePrev = comp->time;
  273. }
  274. flag = CVode(cvode_mem, tout, iData->y, &tret, CV_NORMAL);
  275. #ifdef SAVE_STATE_SUNDIALS
  276. iData->cvode_called = 1;
  277. #endif
  278. switch (flag) {
  279. case CV_SUCCESS:
  280. done = 1;
  281. break;
  282. case CV_TOO_CLOSE:
  283. /* Sundials simply gives up on finding initial step size if the next step after a restart is too small.
  284. * Must explicitly set initial step size as a workaround. */
  285. {
  286. realtype hcur;
  287. flag = CVodeGetCurrentStep(cvode_mem, &hcur);
  288. if (util_check_flag(&flag, "CVodeGetCurrentStep", 1, comp)) {
  289. goto fail;
  290. }
  291. if (hcur == 0) {
  292. /* next step size not yet computed */
  293. /* somewhat arbitrary value but should never happen on sane usage */
  294. hcur = 2 * UNIT_ROUNDOFF * (1 + SUNMAX(SUNRabs(tout), SUNRabs(comp->time)));
  295. }
  296. util_logger(comp, comp->instanceName, FMIOK, "",
  297. "Internal step too small at t = %f, setting initial step size explicitly to %.16e", comp->time, hcur);
  298. CALL_SET(CVodeSetInitStep, hcur);
  299. }
  300. break;
  301. case CV_ROOT_RETURN:
  302. {
  303. /* state or step event occurred */
  304. FMIStatus status;
  305. #ifdef FMI_2
  306. FMIBoolean terminateSimulation;
  307. #else
  308. FMIEventInfo eventInfo;
  309. #endif
  310. iData->useDerivatives = 0;
  311. fmiSetTime_(comp, tret);
  312. #ifdef LOG_EVENTS
  313. if (comp->istruct->mTriggerStepEvent != 0) {
  314. util_logger(comp, comp->instanceName, FMIOK, "", "%.12f: step event", comp->time);
  315. } else {
  316. util_logger(comp, comp->instanceName, FMIOK, "",
  317. "%.12f: state event", tret);
  318. }
  319. #endif
  320. INT_RESULT_SAMPLE(FMITrue);
  321. status = util_event_update(comp, FMIFalse,
  322. #ifdef FMI_2
  323. &terminateSimulation
  324. #else
  325. &eventInfo
  326. #endif
  327. );
  328. if (status != FMIOK) {
  329. goto fail;
  330. }
  331. INT_RESULT_SAMPLE(FMITrue);
  332. #ifdef FMI_2
  333. if (terminateSimulation == FMITrue) {
  334. #else
  335. if (eventInfo.terminateSimulation == FMITrue) {
  336. #endif
  337. return integrationTerminate;
  338. }
  339. if (integration_reinit(comp) != integrationOK) {
  340. goto fail;
  341. }
  342. }
  343. break;
  344. default:
  345. util_check_flag(&flag, "CVode", 1, comp);
  346. goto fail;
  347. }
  348. }
  349. /* check if we are reasonably close to requested stop time */
  350. if (fabs(tret) - fabs(tout) > SMALL_TIME_DEV(comp->time)) {
  351. util_logger(comp, comp->instanceName, FMIError, "",
  352. "Internal step error: tret = %.16e != tout = %.16e", tret, tout);
  353. goto fail;
  354. }
  355. iData->stat.steps++;
  356. return integrationOK;
  357. fail:
  358. return integrationError;
  359. }
  360. #ifdef FMI_2
  361. DYMOLA_STATIC IntegrationStatus integration_step_return_at_event(Component* comp, FMIReal tout, FMIReal* tRet)
  362. {
  363. IntegrationData* iData = comp->iData;
  364. void* cvode_mem = iData->cvode_mem;
  365. /* initialize in case tret needs to be reported before set by Sundials */
  366. realtype tret = comp->time;
  367. int done = 0;
  368. assert(comp->nStates > 0);
  369. assert(tout > comp->time);
  370. while (!done) {
  371. int flag;
  372. /* store previous outputs for use in fmiGetRealOutputDerivatives */
  373. if (!util_refresh_cache(comp, iDemandOutput, "fetching current output", NULL)) {
  374. memcpy(iData->outputsPrev, comp->outputs, comp->nOut * sizeof(FMIReal));
  375. iData->timePrev = comp->time;
  376. }
  377. flag = CVode(cvode_mem, tout, iData->y, &tret, CV_NORMAL);
  378. #ifdef SAVE_STATE_SUNDIALS
  379. iData->cvode_called = 1;
  380. #endif
  381. switch (flag) {
  382. case CV_SUCCESS:
  383. done = 1;
  384. break;
  385. case CV_TOO_CLOSE:
  386. /* Sundials simply gives up on finding initial step size if the next step after a restart is too small.
  387. * Must explicitly set initial step size as a workaround. */
  388. {
  389. realtype hcur;
  390. flag = CVodeGetCurrentStep(cvode_mem, &hcur);
  391. if (util_check_flag(&flag, "CVodeGetCurrentStep", 1, comp)) {
  392. goto fail;
  393. }
  394. if (hcur == 0) {
  395. /* next step size not yet computed */
  396. /* somewhat arbitrary value but should never happen on sane usage */
  397. hcur = 2 * UNIT_ROUNDOFF * (1 + SUNMAX(SUNRabs(tout), SUNRabs(comp->time)));
  398. }
  399. util_logger(comp, comp->instanceName, FMIOK, "",
  400. "Internal step too small at t = %f, setting initial step size explicitly to %.16e", comp->time, hcur);
  401. CALL_SET(CVodeSetInitStep, hcur);
  402. }
  403. break;
  404. case CV_ROOT_RETURN:
  405. {
  406. /* state or step event occurred */
  407. iData->useDerivatives = 0;
  408. fmiSetTime_(comp, tret);
  409. *tRet = (FMIReal) tret;
  410. #ifdef LOG_EVENTS
  411. if (comp->istruct->mTriggerStepEvent != 0) {
  412. util_logger(comp, comp->instanceName, FMIOK, "", "%.12f: step event", comp->time);
  413. } else {
  414. util_logger(comp, comp->instanceName, FMIOK, "",
  415. "%.12f: state event", tret);
  416. }
  417. #endif
  418. INT_RESULT_SAMPLE(FMITrue);
  419. comp->reinitRequired=1;
  420. return integrationEvent;
  421. }
  422. break;
  423. default:
  424. util_check_flag(&flag, "CVode", 1, comp);
  425. goto fail;
  426. }
  427. }
  428. /* check if we are reasonably close to requested stop time */
  429. if (fabs(tret) - fabs(tout) > SMALL_TIME_DEV(comp->time)) {
  430. util_logger(comp, comp->instanceName, FMIError, "",
  431. "Internal step error: tret = %.16e != tout = %.16e", tret, tout);
  432. goto fail;
  433. }
  434. *tRet = (FMIReal) tret;
  435. iData->stat.steps++;
  436. return integrationOK;
  437. fail:
  438. *tRet = (FMIReal) tret;
  439. return integrationError;
  440. }
  441. #endif
  442. /* ------------------------------------------------------ */
  443. DYMOLA_STATIC IntegrationStatus integration_reinit(Component* comp)
  444. {
  445. int flag;
  446. long nsteps;
  447. assert(comp->nStates > 0);
  448. /* Sundials resets the step counter during reinit */
  449. GET_STATISTIC(CVodeGetNumSteps, nsteps);
  450. comp->iData->stat.intSteps += nsteps;
  451. flag = CVodeReInit(comp->iData->cvode_mem, comp->time, comp->iData->y);
  452. if (util_check_flag(&flag, "CVodeReInit", 1, comp)) return integrationError;
  453. return integrationOK;
  454. }
  455. /* ------------------------------------------------------ */
  456. DYMOLA_STATIC void integration_sync_extrapolation_input(Component* comp, size_t ix)
  457. {
  458. if (comp->iData != NULL && comp->iData->inputsT0 != NULL) {
  459. comp->iData->inputsT0[ix] = comp->inputs[ix];
  460. }
  461. }
  462. /* ------------------------------------------------------ */
  463. DYMOLA_STATIC void integration_extrapolate_inputs(Component* comp, double t)
  464. {
  465. if (comp->iData->useDerivatives) {
  466. IntegrationData* iData = comp->iData;
  467. size_t i;
  468. double dt = (t - iData->derivativeTime);
  469. for (i = 0; i < comp->nIn; i++) {
  470. comp->inputs[i] = iData->inputsT0[i] + iData->inputDerivatives[i] * dt;
  471. }
  472. }
  473. }
  474. #ifdef FMI_2
  475. /* ------------------------------------------------------ */
  476. DYMOLA_STATIC FMIStatus integration_get_state(Component* source, Component* target)
  477. {
  478. if (source->nStates > 0) {
  479. if (source->iData != NULL) {
  480. // possible to reuse iData allocation from target since no sizes of sub parts can have changed
  481. if (clone_data(target, source) != integrationOK) {
  482. goto mem_fail;
  483. }
  484. /* clone also statistics to be able to distinguish between useful and rejected steps */
  485. memcpy(&target->iData->stat, &source->iData->stat, sizeof(Statistics));
  486. } else if (target->iData != NULL) {
  487. // free old iData to avoid memory leak
  488. free_data(source, target);
  489. }
  490. }
  491. return FMIOK;
  492. mem_fail:
  493. util_logger(source, source->instanceName, FMIError, "", "memory allocation failed");
  494. free_data(source, target);
  495. return util_error(source);
  496. }
  497. /* ------------------------------------------------------ */
  498. DYMOLA_STATIC FMIStatus integration_set_state(Component* source, Component* target)
  499. {
  500. if (target->nStates > 0) {
  501. if (source->iData != NULL) {
  502. // possible to reuse iData allocation from comp since no sizes of sub parts can have changed
  503. if (target->iData == NULL) {
  504. target->iData = (IntegrationData*) source->functions->allocateMemory(1, sizeof(IntegrationData));
  505. if (target->iData == NULL) goto mem_fail;
  506. }
  507. if (clone_data(target, source) != integrationOK) {
  508. goto mem_fail;
  509. }
  510. /* count of rejected steps before copying statistics */
  511. source->iData->stat.rejSteps += target->iData->stat.steps - source->iData->stat.steps;
  512. source->iData->stat.rejIntSteps += target->iData->stat.intSteps - source->iData->stat.intSteps;
  513. source->iData->stat.rejFCalls += target->iData->stat.fCalls - source->iData->stat.fCalls;
  514. source->iData->stat.rejJacCalls += target->iData->stat.JacCalls - source->iData->stat.JacCalls;
  515. source->iData->stat.rejFTime += target->iData->stat.fTime - source->iData->stat.fTime;
  516. memcpy(&target->iData->stat, &source->iData->stat, sizeof(Statistics));
  517. #ifdef SAVE_STATE_SUNDIALS
  518. integration_reinit(target);
  519. /* code fetched from CVAckpntGet and modified */
  520. {
  521. CVodeMem cv_mem = (CVodeMem)target->iData->cvode_mem;
  522. CVodeCheckPointData* ck_mem = &target->iData->ck_mem;
  523. N_Vector* cv_zn = cv_mem->cv_zn;
  524. N_Vector* ck_zn = ck_mem->ck_zn;
  525. int q = cv_mem->cv_q;
  526. int qmax = cv_mem->cv_qmax;
  527. int j;
  528. /* Copy parameters from check point data structure */
  529. cv_mem->cv_nst = ck_mem->ck_nst;
  530. cv_mem->cv_tretlast = ck_mem->ck_tretlast;
  531. cv_mem->cv_q = ck_mem->ck_q;
  532. cv_mem->cv_qprime = ck_mem->ck_qprime;
  533. cv_mem->cv_qwait = ck_mem->ck_qwait;
  534. cv_mem->cv_L = ck_mem->ck_L;
  535. cv_mem->cv_gammap = ck_mem->ck_gammap;
  536. cv_mem->cv_h = ck_mem->ck_h;
  537. cv_mem->cv_hprime = ck_mem->ck_hprime;
  538. cv_mem->cv_hscale = ck_mem->ck_hscale;
  539. cv_mem->cv_eta = ck_mem->ck_eta;
  540. cv_mem->cv_etamax = ck_mem->ck_etamax;
  541. cv_mem->cv_saved_tq5 = ck_mem->ck_saved_tq5;
  542. /* Copy the arrays from check point data structure */
  543. for (j=0; j<=q; j++) N_VScale(1.0, ck_zn[j], cv_zn[j]);
  544. if ( q < qmax ) N_VScale(1.0, ck_zn[qmax], cv_zn[qmax]);
  545. for (j=0; j<=L_MAX; j++) cv_mem->cv_tau[j] = ck_mem->ck_tau[j];
  546. for (j=0; j<=NUM_TESTS; j++) cv_mem->cv_tq[j] = ck_mem->ck_tq[j];
  547. for (j=0; j<=q; j++) cv_mem->cv_l[j] = ck_mem->ck_l[j];
  548. }
  549. #endif
  550. } else if (target->iData != NULL) {
  551. // free old iData to avoid memory leak
  552. free_data(source, target);
  553. }
  554. }
  555. /* for explicit saving of Sundials states, we already re-initialized _before_ restoring */
  556. #ifndef SAVE_STATE_SUNDIALS
  557. integration_reinit(target);
  558. #endif
  559. return FMIOK;
  560. mem_fail:
  561. util_logger(target, target->instanceName, FMIError, "", "memory allocation failed");
  562. return util_error(source);
  563. }
  564. /* ------------------------------------------------------ */
  565. DYMOLA_STATIC void integration_free_state(Component* comp, Component* target)
  566. {
  567. if (target->nStates > 0) {
  568. #ifdef SAVE_STATE_SUNDIALS
  569. /* free cloned Sundials internal data */
  570. CVodeCheckPointData* ck_mem = &target->iData->ck_mem;
  571. N_Vector* ck_zn = ck_mem->ck_zn;
  572. int q = ck_mem->ck_q;
  573. int j;
  574. for (j = 0; j < q; j++) {
  575. N_VDestroy(ck_zn[j]);
  576. }
  577. if (q < ck_mem->ck_qmax) {
  578. N_VDestroy(ck_zn[ck_mem->ck_qmax]);
  579. }
  580. #endif
  581. free_data(comp, target);
  582. }
  583. }
  584. #endif /* FMI_2 */
  585. /* ----------------- local function definitions ----------------- */
  586. static IntegrationStatus clone_data(Component* target, Component* source)
  587. {
  588. IntegrationData* iData;
  589. assert(target->nStates > 0);
  590. assert(source->nStates > 0);
  591. assert(source->iData != NULL);
  592. iData = target->iData;
  593. if (iData == NULL) {
  594. #ifdef FMI_2
  595. target->iData = (IntegrationData*) source->functions->allocateMemory(1, sizeof(IntegrationData));
  596. #else
  597. target->iData = (IntegrationData*) source->functions.allocateMemory(1, sizeof(IntegrationData));
  598. #endif
  599. if (target->iData == NULL) {
  600. return integrationError;
  601. }
  602. iData = target->iData;
  603. iData->y = N_VClone(source->iData->y);
  604. iData->abstol = N_VClone(source->iData->abstol);
  605. iData->ewt = N_VClone(source->iData->ewt);
  606. iData->tmp1 = N_VClone(source->iData->tmp1);
  607. iData->tmp2 = N_VClone(source->iData->tmp2);
  608. iData->inputDerivatives = target->iData->inputsT0 = target->iData->outputsPrev = NULL;
  609. target->iData = iData;
  610. }
  611. /* don't use N_V_COPY since it also copies ops member */
  612. N_VScale(1.0, source->iData->abstol, iData->abstol);
  613. N_VScale(1.0, source->iData->ewt, iData->ewt);
  614. N_VScale(1.0, source->iData->tmp1, iData->tmp1);
  615. N_VScale(1.0, source->iData->tmp2, iData->tmp2);
  616. /* handle input derivative data */
  617. iData->useDerivatives = source->iData->useDerivatives;
  618. if (iData->useDerivatives) {
  619. size_t nu = source->nIn;
  620. assert(source->iData->inputDerivatives != NULL);
  621. assert(nu > 0);
  622. if (iData->inputDerivatives == NULL) {
  623. assert(iData->inputsT0 == NULL);
  624. /* add extra array element also here for consistency although we know here that nu > 0 */
  625. #ifdef FMI_2
  626. iData->inputDerivatives = (FMIReal*) source->functions->allocateMemory(nu + 1, sizeof(FMIReal));
  627. iData->inputsT0 = (FMIReal*) source->functions->allocateMemory(nu + 1, sizeof(FMIReal));
  628. #else
  629. iData->inputDerivatives = (FMIReal*) source->functions.allocateMemory(nu + 1, sizeof(FMIReal));
  630. iData->inputsT0 = (FMIReal*) source->functions.allocateMemory(nu + 1, sizeof(FMIReal));
  631. #endif
  632. if (iData->inputDerivatives == NULL || iData->inputsT0 == NULL) {
  633. goto mem_fail;
  634. }
  635. }
  636. memcpy(iData->inputDerivatives, source->iData->inputDerivatives, nu * sizeof(FMIReal));
  637. memcpy(iData->inputsT0, source->iData->inputsT0, nu * sizeof(FMIReal));
  638. iData->derivativeTime = source->iData->derivativeTime;
  639. }
  640. /* handle ouput derivative data */
  641. {
  642. size_t ny = source->nOut;
  643. assert(source->iData->outputsPrev != NULL);
  644. if (iData->outputsPrev == NULL) {
  645. /* add extra array element also here for consistency although we know here that nu > 0 */
  646. #ifdef FMI_2
  647. iData->outputsPrev = (FMIReal*) source->functions->allocateMemory(ny + 1, sizeof(FMIReal));
  648. #else
  649. iData->outputsPrev = (FMIReal*) source->functions.allocateMemory(ny + 1, sizeof(FMIReal));
  650. #endif
  651. if (iData->outputsPrev == NULL) {
  652. goto mem_fail;
  653. }
  654. }
  655. memcpy(iData->outputsPrev, source->iData->outputsPrev, ny * sizeof(FMIReal));
  656. iData->timePrev = source->iData->timePrev;
  657. }
  658. #ifdef SAVE_STATE_SUNDIALS
  659. /* code fetched from CVAckpntNew and modified */
  660. if (iData->cvode_called)
  661. {
  662. CVodeMem cv_mem = (CVodeMem)iData->cvode_mem;
  663. CVodeCheckPointData* ck_mem = &iData->ck_mem;
  664. N_Vector* cv_zn = cv_mem->cv_zn;
  665. N_Vector* ck_zn = ck_mem->ck_zn;
  666. int q = cv_mem->cv_q;
  667. int qmax = cv_mem->cv_qmax;
  668. int j;
  669. if (!target->allocDone) {
  670. /* Test if we need to allocate space for the last zn.
  671. * NOTE: zn(qmax) may be needed for a hot restart, if an order
  672. * increase is deemed necessary at the first step after a check point */
  673. for (j=0; j<=q; j++) {
  674. ck_zn[j] = N_VClone(cv_mem->cv_tempv);
  675. if (ck_zn[j] == NULL) {
  676. int jj;
  677. for (jj=0; jj<j; jj++) N_VDestroy(ck_zn[jj]);
  678. goto mem_fail;
  679. }
  680. }
  681. if (q < qmax) {
  682. ck_zn[qmax] = N_VClone(cv_mem->cv_tempv);
  683. if (ck_zn[qmax] == NULL) {
  684. int jj;
  685. for (jj=0; jj<=q; jj++) N_VDestroy(ck_zn[jj]);
  686. goto mem_fail;
  687. }
  688. }
  689. }
  690. /* Load check point data from cv_mem */
  691. for (j=0; j<=q; j++) N_VScale(1.0, cv_zn[j], ck_zn[j]);
  692. if ( q < qmax ) N_VScale(1.0, cv_zn[qmax], ck_zn[qmax]);
  693. /* TODO: try memcpy */
  694. for (j=0; j<=L_MAX; j++) ck_mem->ck_tau[j] = cv_mem->cv_tau[j];
  695. for (j=0; j<=NUM_TESTS; j++) ck_mem->ck_tq[j] = cv_mem->cv_tq[j];
  696. for (j=0; j<=q; j++) ck_mem->ck_l[j] = cv_mem->cv_l[j];
  697. ck_mem->ck_nst = cv_mem->cv_nst;
  698. ck_mem->ck_tretlast = cv_mem->cv_tretlast;
  699. ck_mem->ck_q = cv_mem->cv_q;
  700. ck_mem->ck_qmax = cv_mem->cv_qmax;
  701. ck_mem->ck_qprime = cv_mem->cv_qprime;
  702. ck_mem->ck_qwait = cv_mem->cv_qwait;
  703. ck_mem->ck_L = cv_mem->cv_L;
  704. ck_mem->ck_gammap = cv_mem->cv_gammap;
  705. ck_mem->ck_h = cv_mem->cv_h;
  706. ck_mem->ck_hprime = cv_mem->cv_hprime;
  707. ck_mem->ck_hscale = cv_mem->cv_hscale;
  708. ck_mem->ck_eta = cv_mem->cv_eta;
  709. ck_mem->ck_etamax = cv_mem->cv_etamax;
  710. ck_mem->ck_saved_tq5 = cv_mem->cv_saved_tq5;
  711. }
  712. /* End of: code fetched from CVAckpntNew and modified */
  713. #endif
  714. return integrationOK;
  715. mem_fail:
  716. util_logger(source, source->instanceName, FMIError, "", "memory allocation failed");
  717. #ifdef FMI_2
  718. source->functions->freeMemory(iData->outputsPrev);
  719. source->functions->freeMemory(iData->inputDerivatives);
  720. source->functions->freeMemory(iData->inputsT0);
  721. source->functions->freeMemory(iData);
  722. #else
  723. source->functions.freeMemory(iData->outputsPrev);
  724. source->functions.freeMemory(iData->inputDerivatives);
  725. source->functions.freeMemory(iData->inputsT0);
  726. source->functions.freeMemory(iData);
  727. #endif
  728. return integrationError;
  729. }
  730. /* ------------------------------------------------------ */
  731. static void free_data(Component* comp, Component* target)
  732. {
  733. IntegrationData* iData;
  734. if (target == NULL || target->iData == NULL) {
  735. return;
  736. }
  737. iData = target->iData;
  738. CVodeFree(&iData->cvode_mem);
  739. if (iData->y != NULL) N_VDestroy_Serial(target->iData->y);
  740. if (iData->abstol != NULL) N_VDestroy_Serial(target->iData->abstol);
  741. if (iData->ewt != NULL) N_VDestroy_Serial(target->iData->ewt);
  742. if (iData->tmp1 != NULL) N_VDestroy_Serial(target->iData->tmp1);
  743. if (iData->tmp2 != NULL) N_VDestroy_Serial(target->iData->tmp2);
  744. #ifdef FMI_2
  745. comp->functions->freeMemory(iData->outputsPrev);
  746. comp->functions->freeMemory(iData->inputDerivatives);
  747. comp->functions->freeMemory(iData->inputsT0);
  748. comp->functions->freeMemory(iData);
  749. #else
  750. comp->functions.freeMemory(iData->outputsPrev);
  751. comp->functions.freeMemory(iData->inputDerivatives);
  752. comp->functions.freeMemory(iData->inputsT0);
  753. comp->functions.freeMemory(iData);
  754. #endif
  755. target->iData = NULL;
  756. }
  757. /* ------------------------------------------------------ */
  758. static int g(realtype t, N_Vector y, realtype *gout, void *user_data)
  759. {
  760. clock_t t0 = clock();
  761. FMIComponent* c = (FMIComponent*) user_data;
  762. Component* comp = (Component*) c;
  763. int retval = 0;
  764. /* temporarily change time, states and inputs to be able to reuse fmiGetEventIndicators */
  765. FMIReal time = comp->time;
  766. FMIReal* states = comp->states;
  767. assert(comp->nStates > 0);
  768. comp->states = N_VGetArrayPointer(y);
  769. integration_extrapolate_inputs(comp, t);
  770. comp->time = t;
  771. comp->icall = 0;
  772. if (fmiGetEventIndicators_(c, gout, comp->nCross) != FMIOK) {
  773. retval= -1;
  774. }
  775. /* restore time, states and inputs */
  776. integration_extrapolate_inputs(comp, time);
  777. comp->states = states;
  778. comp->time = time;
  779. comp->iData->stat.gTime += (clock() - t0);
  780. return retval;
  781. }
  782. /* ------------------------------------------------------ */
  783. static int check_step_event(void* user_data) {
  784. Component* comp = (Component*) user_data;
  785. return (comp->istruct->mTriggerStepEvent != 0);
  786. }
  787. /* ------------------------------------------------------ */
  788. static void err_msg_handler(int error_code, const char *module, const char *function,
  789. char *msg, void *eh_data)
  790. {
  791. Component* comp = (Component*) eh_data;
  792. char * CVodeFlagName = CVodeGetReturnFlagName(error_code);
  793. util_logger(comp, comp->instanceName, FMIWarning, "", "%s: %s failed with %s:\n %s",
  794. module, function, CVodeFlagName, msg);
  795. free(CVodeFlagName);
  796. }