summarylogtreecommitdiffstats
path: root/sundials6.patch
blob: 65945bfa59cfa387f4ac1ad12211027dc42bc65c (plain)
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
diff --git a/fmpy/sundials/__init__.py b/fmpy/sundials/__init__.py
index c1bf1c7..cde034f 100644
--- a/fmpy/sundials/__init__.py
+++ b/fmpy/sundials/__init__.py
@@ -1,194 +1,198 @@
-""" Interface to the SUNDIALS libraries """
-
-import numpy as np
-from .cvode import *
-from .cvode_ls import *
-from .nvector_serial import *
-from .sundials_linearsolver import *
-from .sundials_matrix import *
-from .sundials_nvector import *
-from .sundials_types import *
-from .sundials_version import *
-from .sunlinsol_dense import *
-from .sunmatrix_dense import *
-
-
-def _assert_cv_success(status):
-    if status != CV_SUCCESS:
-        raise Exception("Call to CVode failed.")
-
-
-def _assert_version():
-    major = c_int()
-    minor = c_int()
-    patch = c_int()
-    len = 8
-    label = create_string_buffer(len)
-    _assert_cv_success(SUNDIALSGetVersionNumber(byref(major), byref(minor), byref(patch), label, len))
-    if major.value != 5:
-        raise Exception("Wrong SUNDIALS major version number. Expected 5 but was %d." % major.value)
-
-
-_assert_version()
-
-
-class CVodeSolver(object):
-    """ Interface to the CVode solver """
-
-    def __init__(self,
-                 nx, nz, get_x, set_x, get_dx, get_z,
-                 get_nominals,
-                 set_time,
-                 input,
-                 startTime,
-                 maxStep=float('inf'),
-                 relativeTolerance=1e-5,
-                 maxNumSteps=500):
-        """
-        Parameters:
-            nx                  number of continuous states
-            nz                  number of event indicators
-            get_x               callback function to get the continuous states
-            set_x               callback function to set the continuous states
-            get_dx              callback function to get the derivatives
-            get_z               callback function to get the event indicators
-            set_time            callback function to set the time
-            startTime           start time for the integration
-            maxStep             maximum absolute value of step size allowed
-            relativeTolerance   relative tolerance
-            maxNumSteps         maximum number of internal steps to be taken by the solver in its attempt to reach tout
-        """
-
-        self.get_x = get_x
-        self.set_x = set_x
-        self.get_dx = get_dx
-        self.get_z = get_z
-        self.get_nominals = get_nominals
-        self.set_time = set_time
-        self.input = input
-        self.error_info = None
-        self.reltol = relativeTolerance
-
-        self.discrete = nx == 0
-
-        if self.discrete:
-            # insert a dummy state
-            self.nx = 1
-        else:
-            self.nx = nx
-
-        self.nz = nz
-
-        self.x      = N_VNew_Serial(self.nx)
-        self.abstol = N_VNew_Serial(self.nx)
-
-        self.px       = NV_DATA_S(self.x)
-        self.pabstol  = NV_DATA_S(self.abstol)
-        self.npabstol = np.ctypeslib.as_array(self.pabstol, (self.nx,))
-
-        # initialize
-        if self.discrete:
-            x = np.ctypeslib.as_array(self.px, (self.nx,))
-            x[:] = 1.0
-            self.npabstol[:] = 1.0
-        else:
-            self.get_x(self.px, self.nx)
-            self.get_nominals(self.pabstol, self.nx)
-
-        self.npabstol *= self.reltol
-
-        self.cvode_mem = CVodeCreate(CV_BDF)
-
-        # add function pointers as members to save them from GC
-        self.f_ = CVRhsFn(self.f)
-        self.g_ = CVRootFn(self.g)
-        self.ehfun_ = CVErrHandlerFn(self.ehfun)
-
-        _assert_cv_success(CVodeInit(self.cvode_mem, self.f_, startTime, self.x))
-
-        _assert_cv_success(CVodeSVtolerances(self.cvode_mem, relativeTolerance, self.abstol))
-
-        _assert_cv_success(CVodeRootInit(self.cvode_mem, self.nz, self.g_))
-
-        self.A = SUNDenseMatrix(self.nx, self.nx)
-
-        self.LS = SUNLinSol_Dense(self.x, self.A)
-
-        _assert_cv_success(CVodeSetLinearSolver(self.cvode_mem, self.LS, self.A))
-
-        _assert_cv_success(CVodeSetMaxStep(self.cvode_mem, maxStep))
-
-        _assert_cv_success(CVodeSetMaxNumSteps(self.cvode_mem, maxNumSteps))
-
-        _assert_cv_success(CVodeSetNoInactiveRootWarn(self.cvode_mem))
-
-        _assert_cv_success(CVodeSetErrHandlerFn(self.cvode_mem, self.ehfun_, None))
-
-    def ehfun(self, error_code, module, function, msg,  user_data):
-        """ Error handler function """
-        self.error_info = (error_code, module.decode("utf-8"), function.decode("utf-8"), msg.decode("utf-8"))
-
-    def f(self, t, y, ydot, user_data):
-        """ Right-hand-side function """
-
-        self.set_time(t)
-
-        if self.discrete:
-            dx = np.ctypeslib.as_array(NV_DATA_S(ydot), (self.nx,))
-            dx[:] = 0.0
-        else:
-            self.set_x(NV_DATA_S(y), self.nx)
-            self.get_dx(NV_DATA_S(ydot), self.nx)
-        return 0
-
-    def g(self, t, y, gout, user_data):
-        """ Root function """
-
-        self.set_time(t)
-        self.input.apply(t)
-
-        if not self.discrete:
-            self.set_x(NV_DATA_S(y), self.nx)
-
-        self.get_z(gout, self.nz)
-
-        return 0
-
-    def step(self, t, tNext):
-
-        if not self.discrete:
-            # get the states
-            self.get_x(self.px, self.nx)
-
-        tret = realtype(0.0)
-
-        # perform one step
-        flag = CVode(self.cvode_mem, tNext, self.x, byref(tret), CV_NORMAL)
-
-        if not self.discrete:
-            # set the states
-            self.set_x(self.px, self.nx)
-
-        roots_found = np.zeros(shape=(self.nz,), dtype=np.int32)
-
-        if flag == CV_ROOT_RETURN:
-            p_roots_found = np.ctypeslib.as_ctypes(roots_found)
-            _assert_cv_success(CVodeGetRootInfo(self.cvode_mem, p_roots_found))
-        elif flag < 0:
-            raise RuntimeError("CVode error (code %s) in module %s, function %s: %s" % self.error_info)
-
-        return flag > 0, roots_found, tret.value
-
-    def reset(self, time):
-
-        if not self.discrete:
-            self.get_x(self.px, self.nx)
-            self.get_nominals(self.pabstol, self.nx)
-            self.npabstol *= self.reltol
-
-        # reset the solver
-        flag = CVodeReInit(self.cvode_mem, time, self.x)
-
-    def __del__(self):
-        # clean up
-        CVodeFree(byref(c_void_p(self.cvode_mem)))
+""" Interface to the SUNDIALS libraries """
+
+import numpy as np
+from .cvode import *
+from .cvode_ls import *
+from .nvector_serial import *
+from .sundials_linearsolver import *
+from .sundials_matrix import *
+from .sundials_nvector import *
+from .sundials_types import *
+from .sundials_version import *
+from .sunlinsol_dense import *
+from .sunmatrix_dense import *
+
+
+def _assert_cv_success(status):
+    if status != CV_SUCCESS:
+        raise Exception("Call to CVode failed.")
+
+
+def _assert_version():
+    major = c_int()
+    minor = c_int()
+    patch = c_int()
+    len = 8
+    label = create_string_buffer(len)
+    _assert_cv_success(SUNDIALSGetVersionNumber(byref(major), byref(minor), byref(patch), label, len))
+    if major.value != 7:
+        raise Exception("Wrong SUNDIALS major version number. Expected 7 but was %d." % major.value)
+
+
+_assert_version()
+
+
+class CVodeSolver(object):
+    """ Interface to the CVode solver """
+
+    def __init__(self,
+                 nx, nz, get_x, set_x, get_dx, get_z,
+                 get_nominals,
+                 set_time,
+                 input,
+                 startTime,
+                 maxStep=float('inf'),
+                 relativeTolerance=1e-5,
+                 maxNumSteps=500):
+        """
+        Parameters:
+            nx                  number of continuous states
+            nz                  number of event indicators
+            get_x               callback function to get the continuous states
+            set_x               callback function to set the continuous states
+            get_dx              callback function to get the derivatives
+            get_z               callback function to get the event indicators
+            set_time            callback function to set the time
+            startTime           start time for the integration
+            maxStep             maximum absolute value of step size allowed
+            relativeTolerance   relative tolerance
+            maxNumSteps         maximum number of internal steps to be taken by the solver in its attempt to reach tout
+        """
+
+        self.get_x = get_x
+        self.set_x = set_x
+        self.get_dx = get_dx
+        self.get_z = get_z
+        self.get_nominals = get_nominals
+        self.set_time = set_time
+        self.input = input
+        self.error_info = None
+        self.reltol = relativeTolerance
+
+        self.discrete = nx == 0
+
+        if self.discrete:
+            # insert a dummy state
+            self.nx = 1
+        else:
+            self.nx = nx
+
+        self.nz = nz
+
+        self.x      = N_VNew_Serial(self.nx)
+        self.abstol = N_VNew_Serial(self.nx)
+
+        self.px       = NV_DATA_S(self.x)
+        self.pabstol  = NV_DATA_S(self.abstol)
+        self.npabstol = np.ctypeslib.as_array(self.pabstol, (self.nx,))
+
+        # initialize
+        if self.discrete:
+            x = np.ctypeslib.as_array(self.px, (self.nx,))
+            x[:] = 1.0
+            self.npabstol[:] = 1.0
+        else:
+            self.get_x(self.px, self.nx)
+            self.get_nominals(self.pabstol, self.nx)
+
+        self.npabstol *= self.reltol
+
+        self.ctx = SUNContext_()
+        comm = c_int(0)
+        err = SUNContext_Create(comm, pointer(self.ctx))
+        self.cvode_mem = CVodeCreate(CV_BDF, pointer(self.ctx))
+        print("eeeeeeeeeeeeeeeeeeeeeeeeeeeee", err, self.cvode_mem)
+
+        # add function pointers as members to save them from GC
+        self.f_ = CVRhsFn(self.f)
+        self.g_ = CVRootFn(self.g)
+        self.ehfun_ = CVErrHandlerFn(self.ehfun)
+
+        _assert_cv_success(CVodeInit(self.cvode_mem, self.f_, startTime, self.x))
+
+        _assert_cv_success(CVodeSVtolerances(self.cvode_mem, relativeTolerance, self.abstol))
+
+        _assert_cv_success(CVodeRootInit(self.cvode_mem, self.nz, self.g_))
+
+        self.A = SUNDenseMatrix(self.nx, self.nx)
+
+        self.LS = SUNLinSol_Dense(self.x, self.A)
+
+        _assert_cv_success(CVodeSetLinearSolver(self.cvode_mem, self.LS, self.A))
+
+        _assert_cv_success(CVodeSetMaxStep(self.cvode_mem, maxStep))
+
+        _assert_cv_success(CVodeSetMaxNumSteps(self.cvode_mem, maxNumSteps))
+
+        _assert_cv_success(CVodeSetNoInactiveRootWarn(self.cvode_mem))
+
+        _assert_cv_success(SUNContext_PushErrHandler(self.cvode_mem, self.ehfun_, None))
+
+    def ehfun(self, error_code, module, function, msg,  user_data):
+        """ Error handler function """
+        self.error_info = (error_code, module.decode("utf-8"), function.decode("utf-8"), msg.decode("utf-8"))
+
+    def f(self, t, y, ydot, user_data):
+        """ Right-hand-side function """
+
+        self.set_time(t)
+
+        if self.discrete:
+            dx = np.ctypeslib.as_array(NV_DATA_S(ydot), (self.nx,))
+            dx[:] = 0.0
+        else:
+            self.set_x(NV_DATA_S(y), self.nx)
+            self.get_dx(NV_DATA_S(ydot), self.nx)
+        return 0
+
+    def g(self, t, y, gout, user_data):
+        """ Root function """
+
+        self.set_time(t)
+        self.input.apply(t)
+
+        if not self.discrete:
+            self.set_x(NV_DATA_S(y), self.nx)
+
+        self.get_z(gout, self.nz)
+
+        return 0
+
+    def step(self, t, tNext):
+
+        if not self.discrete:
+            # get the states
+            self.get_x(self.px, self.nx)
+
+        tret = realtype(0.0)
+
+        # perform one step
+        flag = CVode(self.cvode_mem, tNext, self.x, byref(tret), CV_NORMAL)
+
+        if not self.discrete:
+            # set the states
+            self.set_x(self.px, self.nx)
+
+        roots_found = np.zeros(shape=(self.nz,), dtype=np.int32)
+
+        if flag == CV_ROOT_RETURN:
+            p_roots_found = np.ctypeslib.as_ctypes(roots_found)
+            _assert_cv_success(CVodeGetRootInfo(self.cvode_mem, p_roots_found))
+        elif flag < 0:
+            raise RuntimeError("CVode error (code %s) in module %s, function %s: %s" % self.error_info)
+
+        return flag > 0, roots_found, tret.value
+
+    def reset(self, time):
+
+        if not self.discrete:
+            self.get_x(self.px, self.nx)
+            self.get_nominals(self.pabstol, self.nx)
+            self.npabstol *= self.reltol
+
+        # reset the solver
+        flag = CVodeReInit(self.cvode_mem, time, self.x)
+
+    def __del__(self):
+        # clean up
+        CVodeFree(byref(c_void_p(self.cvode_mem)))
diff --git a/fmpy/sundials/cvode.py b/fmpy/sundials/cvode.py
index b52e32f..aa19a4d 100644
--- a/fmpy/sundials/cvode.py
+++ b/fmpy/sundials/cvode.py
@@ -1,4 +1,5 @@
 from .libraries import sundials_cvode
+from .libraries import sundials_core
 from .sundials_types import *
 from .sundials_nvector import *
 
@@ -102,10 +103,12 @@ CVRootFn = CFUNCTYPE(c_int, realtype, N_Vector, POINTER(realtype), c_void_p)
 #
 # typedef int (*CVEwtFn)(N_Vector y, N_Vector ewt, void *user_data);
 #
-# typedef void (*CVErrHandlerFn)(int error_code,
-#                                const char *module, const char *function,
-#                                char *msg, void *user_data);
-CVErrHandlerFn = CFUNCTYPE(None, c_int, c_char_p, c_char_p, c_char_p, c_void_p)
+# typedef void (*SUNErrHandlerFn)(int line, const char* func, const char* file,
+#                                 const char* msg, SUNErrCode err_code,
+#                                 void* err_user_data, SUNContext sunctx);
+
+
+SUNErrHandlerFn = CFUNCTYPE(None, c_int, c_char_p, c_char_p, c_char_p, c_int, c_void_p, c_void_p)
 #
 # /* -------------------
 #  * Exported Functions
@@ -138,11 +141,22 @@ CVodeSVtolerances.restype = c_int
 # SUNDIALS_EXPORT int CVodeWFtolerances(void *cvode_mem, CVEwtFn efun);
 #
 # /* Optional input functions */
-# SUNDIALS_EXPORT int CVodeSetErrHandlerFn(void *cvode_mem, CVErrHandlerFn ehfun,
+# SUNDIALS_EXPORT int SUNContext_PushErrHandler(SUNContext sunctx, SUNErrHandlerFn ehfun,
 #                                          void *eh_data);
-CVodeSetErrHandlerFn = getattr(sundials_cvode, 'CVodeSetErrHandlerFn')
-CVodeSetErrHandlerFn.argtypes = [c_void_p, CVErrHandlerFn, c_void_p]
-CVodeSetErrHandlerFn.restype = c_int
+
+
+class SUNContext_(Structure):
+    pass
+SUNContext = POINTER(SUNContext_)
+#
+# typedef struct _N_VectorContent_Serial *N_VectorContent_Serial;
+SUNContext_Create = getattr(sundials_core, 'SUNContext_Create')
+SUNContext_Create.argtypes = [c_int, SUNContext]
+SUNContext_Create.restype = c_int
+
+SUNContext_PushErrHandler = getattr(sundials_core, 'SUNContext_PushErrHandler')
+SUNContext_PushErrHandler.argtypes = [c_void_p, SUNErrHandlerFn, c_void_p]
+SUNContext_PushErrHandler.restype = c_int
 # SUNDIALS_EXPORT int CVodeSetErrFile(void *cvode_mem, FILE *errfp);
 # SUNDIALS_EXPORT int CVodeSetUserData(void *cvode_mem, void *user_data);
 # SUNDIALS_EXPORT int CVodeSetMaxOrd(void *cvode_mem, int maxord);
diff --git a/fmpy/sundials/libraries.py b/fmpy/sundials/libraries.py
index 2f3c077..e10f913 100644
--- a/fmpy/sundials/libraries.py
+++ b/fmpy/sundials/libraries.py
@@ -9,3 +9,4 @@ sundials_nvecserial     = cdll.LoadLibrary(os.path.join(library_dir, platform_tu
 sundials_sunmatrixdense = cdll.LoadLibrary(os.path.join(library_dir, platform_tuple, 'sundials_sunmatrixdense' + sharedLibraryExtension))
 sundials_sunlinsoldense = cdll.LoadLibrary(os.path.join(library_dir, platform_tuple, 'sundials_sunlinsoldense' + sharedLibraryExtension))
 sundials_cvode          = cdll.LoadLibrary(os.path.join(library_dir, platform_tuple, 'sundials_cvode'          + sharedLibraryExtension))
+sundials_core           = cdll.LoadLibrary(os.path.join(library_dir, platform_tuple, 'sundials_core'          + sharedLibraryExtension))
\ No newline at end of file
diff --git a/src/cswrapper/cswrapper.c b/src/cswrapper/cswrapper.c
index d9888a8..4b77b0c 100644
--- a/src/cswrapper/cswrapper.c
+++ b/src/cswrapper/cswrapper.c
@@ -18,7 +18,7 @@
 #include <nvector/nvector_serial.h>    /* access to serial N_Vector            */
 #include <sunmatrix/sunmatrix_dense.h> /* access to dense SUNMatrix            */
 #include <sunlinsol/sunlinsol_dense.h> /* access to dense SUNLinearSolver      */
-#include <sundials/sundials_types.h>   /* defs. of realtype, sunindextype      */
+#include <sundials/sundials_types.h>   /* defs. of sunrealtype, sunindextype      */
 
 #include "fmi2Functions.h"
 
@@ -102,7 +102,7 @@ typedef struct {
 
 } Model;
 
-static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data) {
+static int f(sunrealtype t, N_Vector y, N_Vector ydot, void *user_data) {
     
     Model *m = (Model *)user_data;
         
@@ -117,7 +117,7 @@ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data) {
     
 }
 
-static int g(realtype t, N_Vector y, realtype *gout, void *user_data) {
+static int g(sunrealtype t, N_Vector y, sunrealtype *gout, void *user_data) {
 
     Model *m = (Model *)user_data;
     
@@ -132,12 +132,21 @@ static int g(realtype t, N_Vector y, realtype *gout, void *user_data) {
     return 0;
 }
 
+#if SUNDIALS_VERSION_MAJOR >= 7
+static void ehfun(int line, const char* function, const char* module, const char* msg, SUNErrCode error_code, void* user_data, SUNContext sunctx) {
+
+	Model *m = (Model *)user_data;
+
+	m->logger(m, m->instanceName, fmi2Error, "logError", "CVode error(code %d) in module %s, function %s line %d: %s.", error_code, module, function, line, msg);
+}
+#else
 static void ehfun(int error_code, const char *module, const char *function, char *msg, void *user_data) {
 	
 	Model *m = (Model *)user_data;
 
 	m->logger(m, m->instanceName, fmi2Error, "logError", "CVode error(code %d) in module %s, function %s: %s.", error_code, module, function, msg);
 }
+#endif
 
 
 /***************************************************
@@ -296,22 +305,47 @@ fmi2Component fmi2Instantiate(fmi2String instanceName,
     m->c = m->fmi2Instantiate(instanceName, fmi2ModelExchange, fmuGUID, fmuResourceLocation, functions, visible, loggingOn); 
 	ASSERT_NOT_NULL(m->c)
     
+#if SUNDIALS_VERSION_MAJOR >= 6
+    SUNContext ctx;
+    void *comm = NULL;
+    SUNContext_Create(comm, &ctx);
+#endif
+
     if (m->nx > 0) {
+#if SUNDIALS_VERSION_MAJOR >= 6
+        m->x = N_VNew_Serial(m->nx, ctx);
+        m->abstol = N_VNew_Serial(m->nx, ctx);
+#else
         m->x = N_VNew_Serial(m->nx);
         m->abstol = N_VNew_Serial(m->nx);
+#endif
         for (size_t i = 0; i < m->nx; i++) {
             NV_DATA_S(m->abstol)[i] = RTOL;
         }
+#if SUNDIALS_VERSION_MAJOR >= 6
+        m->A = SUNDenseMatrix(m->nx, m->nx, ctx);
+#else
         m->A = SUNDenseMatrix(m->nx, m->nx);
+#endif
     } else  {
+#if SUNDIALS_VERSION_MAJOR >= 6
+        m->x = N_VNew_Serial(1, ctx);
+        m->abstol = N_VNew_Serial(1, ctx);
+        m->A = SUNDenseMatrix(1, 1, ctx);
+#else
         m->x = N_VNew_Serial(1);
         m->abstol = N_VNew_Serial(1);
-        NV_DATA_S(m->abstol)[0] = RTOL;
         m->A = SUNDenseMatrix(1, 1);
+#endif
+        NV_DATA_S(m->abstol)[0] = RTOL;
     }
-    
+
+#if SUNDIALS_VERSION_MAJOR >= 6
+    m->cvode_mem = CVodeCreate(CV_BDF, ctx);
+#else
     m->cvode_mem = CVodeCreate(CV_BDF);
-    
+#endif
+
 	int flag;
 		
 	flag = CVodeInit(m->cvode_mem, f, 0, m->x);
@@ -324,8 +358,12 @@ fmi2Component fmi2Instantiate(fmi2String instanceName,
         flag = CVodeRootInit(m->cvode_mem, (int)m->nz, g);
 		ASSERT_CV_SUCCESS(flag)
     }
-    
+
+#if SUNDIALS_VERSION_MAJOR >= 6
+    m->LS = SUNLinSol_Dense(m->x, m->A, ctx);
+#else
     m->LS = SUNLinSol_Dense(m->x, m->A);
+#endif
 
     flag = CVodeSetLinearSolver(m->cvode_mem, m->LS, m->A);
 	ASSERT_CV_SUCCESS(flag)
@@ -333,12 +371,19 @@ fmi2Component fmi2Instantiate(fmi2String instanceName,
 	flag = CVodeSetNoInactiveRootWarn(m->cvode_mem);
 	ASSERT_CV_SUCCESS(flag)
 
-	flag = CVodeSetErrHandlerFn(m->cvode_mem, ehfun, NULL);
+#if SUNDIALS_VERSION_MAJOR >= 7
+  flag = SUNContext_PushErrHandler(ctx, ehfun, NULL);
+#else
+  flag = CVodeSetErrHandlerFn(m->cvode_mem, ehfun, NULL);
+#endif
 	ASSERT_CV_SUCCESS(flag)
 
     flag = CVodeSetUserData(m->cvode_mem, m);
 	ASSERT_CV_SUCCESS(flag)
 
+#if SUNDIALS_VERSION_MAJOR >= 6
+    SUNContext_Free(&ctx);
+#endif
     return m;
 }
 
@@ -534,9 +579,9 @@ fmi2Status fmi2DoStep(fmi2Component c,
     
     fmi2Status status;
     
-    realtype tret = currentCommunicationPoint;
-    realtype tNext = currentCommunicationPoint + communicationStepSize;
-	realtype epsilon = (1.0 + fabs(tNext)) * EPSILON;
+    sunrealtype tret = currentCommunicationPoint;
+    sunrealtype tNext = currentCommunicationPoint + communicationStepSize;
+	sunrealtype epsilon = (1.0 + fabs(tNext)) * EPSILON;
         
     if (m->nx > 0) {
         status = m->fmi2GetContinuousStates(m->c, NV_DATA_S(m->x), NV_LENGTH_S(m->x));
@@ -545,7 +590,7 @@ fmi2Status fmi2DoStep(fmi2Component c,
     
     while (tret + epsilon < tNext) {
         
-        realtype tout = tNext;
+        sunrealtype tout = tNext;
         
         if (m->eventInfo.nextEventTimeDefined && m->eventInfo.nextEventTime < tNext) {
             tout = m->eventInfo.nextEventTime;
diff --git a/src/modelica/ModelicaFMI.c b/src/modelica/ModelicaFMI.c
index a74cd73..a1fca6d 100644
--- a/src/modelica/ModelicaFMI.c
+++ b/src/modelica/ModelicaFMI.c
@@ -48,7 +48,7 @@ static void logFunctionCall(FMIInstance* instance, FMIStatus status, const char*
     if (logFile) {
         fprintf(logFile, "[%s] ", instance->name);
         vfprintf(logFile, message, args);
-        fprintf(logFile, suffix);
+        fprintf(logFile, "[%s] ", suffix);
     } else {
         ModelicaFormatMessage("[%s] ", instance->name);
         ModelicaVFormatMessage(message, args);
diff --git a/src/modelica/ModelicaUtilities.c b/src/modelica/ModelicaUtilities.c
index ca5bd71..7365f39 100644
--- a/src/modelica/ModelicaUtilities.c
+++ b/src/modelica/ModelicaUtilities.c
@@ -20,7 +20,7 @@ void ModelicaMessage(const char *string) {
 	if (s_callbacks.ModelicaMessage) {
 		s_callbacks.ModelicaMessage(string);
 	} else {
-		printf(string);
+		printf("%s", string);
 	}
 }
 
@@ -52,7 +52,7 @@ void ModelicaError(const char *string) {
 	if (s_callbacks.ModelicaError) {
 		s_callbacks.ModelicaError(string);
 	} else {
-		printf(string);
+		printf("%s", string);
 	}
 }